Add horoscope-api, synastry, and backend services

- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution,
  POST /v1/natal and POST /v1/synastry
- backend: users with roles, email/password and Google login, saved charts,
  synastries and invites, analyses with credit ledger, public shares, admin
- shared crates: astro-engine, db (migrations), horoscope-client, service-kit
- docker-compose with postgres, legacy Java project for reference

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-15 10:25:35 +00:00
co-authored by Claude Opus 5.5
parent 0b5416df45
commit 3a84110565
148 changed files with 95803 additions and 0 deletions
+117
View File
@@ -0,0 +1,117 @@
package astrochart.client;
import java.util.Date;
import astrochart.client.event.CancelledEvent;
import astrochart.client.event.CancelledEventHandler;
import astrochart.client.presenter.AdminPresenter;
import astrochart.client.presenter.InfoPresenter;
import astrochart.client.presenter.ChartPresenter;
import astrochart.client.presenter.Presenter;
import astrochart.client.util.DateTimeUtil;
import astrochart.client.view.AdminView;
import astrochart.client.view.InfoView;
import astrochart.client.view.ChartView;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.TabPanel;
public class AppController implements Presenter, ValueChangeHandler<String> {
private final HandlerManager eventBus = new HandlerManager(null);
private final DateTimeUtil dateTimeUtil = new DateTimeUtil();
private HasWidgets container;
private final TabPanel tabPanel = new TabPanel();
private final ChartView chartView = new ChartView(eventBus, dateTimeUtil);
private final InfoView infoView = new InfoView();
private final AdminView adminView = new AdminView();
private ChartPresenter mainPresenter;
private Presenter infoPresenter;
private Presenter adminPresenter;
public AppController() {
prepareTabs();
bind();
}
private void prepareTabs() {
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(final SelectionEvent<Integer> event) {
final int selection = event.getSelectedItem().intValue();
if (selection == 0) {
if (!History.getToken().startsWith("chart")) {
History.newItem("chart/");
}
}
if (selection == 1) {
if (!History.getToken().startsWith("info")) {
History.newItem("info/");
}
}
}
});
//tabPanel.setAnimationEnabled(true);
tabPanel.add(chartView.asWidget(), "Chart");
tabPanel.add(infoView.asWidget(), "Info");
}
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(CancelledEvent.TYPE, new CancelledEventHandler() {
@Override
public void onCancelled(final CancelledEvent event) {
doEditTermCancelled();
}
});
}
private void doEditTermCancelled() {
History.newItem("chart/");
}
@Override
public final void go(final HasWidgets container) {
this.container = container;
if ("".equals(History.getToken())) {
History.newItem("chart/");
} else {
History.fireCurrentHistoryState();
}
}
@Override
public final void onValueChange(final ValueChangeEvent<String> event) {
final String token = event.getValue();
if (token.startsWith("chart/")) {
Date providedUtcDate = null;
String dateString = "";
if (token.split("/").length > 1) {
dateString = token.split("/")[1];
try {
providedUtcDate = dateTimeUtil.getUtcDateFromUtcString(dateString);
} catch (final IllegalArgumentException iae) {
assert true; // ignore
}
}
tabPanel.selectTab(0);
mainPresenter = new ChartPresenter(eventBus, dateTimeUtil, tabPanel, chartView, providedUtcDate);
mainPresenter.go(container);
} else if (token.startsWith("info/")) {
tabPanel.selectTab(1);
infoPresenter = new InfoPresenter(eventBus, tabPanel, infoView);
infoPresenter.go(container);
} else if (token.startsWith("admin/")) {
adminPresenter = new AdminPresenter(adminView);
adminPresenter.go(container);
} else {
assert true; // ignore
}
}
}
+19
View File
@@ -0,0 +1,19 @@
package astrochart.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class AstroChart implements EntryPoint {
private final AppController appController = new AppController();
@Override
public final void onModuleLoad() {
final Image titleImage = new Image("/images/AstroChartTitle.png");
RootPanel.get("title").add(titleImage);
appController.go(RootPanel.get("content"));
}
}
+17
View File
@@ -0,0 +1,17 @@
package astrochart.client.event;
import com.google.gwt.event.shared.GwtEvent;
public class CancelledEvent extends GwtEvent<CancelledEventHandler> {
public static final Type<CancelledEventHandler> TYPE = new Type<CancelledEventHandler>();
@Override
public final Type<CancelledEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected final void dispatch(final CancelledEventHandler handler) {
handler.onCancelled(this);
}
}
@@ -0,0 +1,7 @@
package astrochart.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface CancelledEventHandler extends EventHandler {
void onCancelled(final CancelledEvent event);
}
+27
View File
@@ -0,0 +1,27 @@
package astrochart.client.event;
import java.util.Date;
import com.google.gwt.event.shared.GwtEvent;
public class DateUpdatedEvent extends GwtEvent<DateUpdatedEventHandler> {
public static final Type<DateUpdatedEventHandler> TYPE = new Type<DateUpdatedEventHandler>();
private final Date localDate;
public DateUpdatedEvent(final Date localDate) {
this.localDate = localDate;
}
@Override
public final Type<DateUpdatedEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected final void dispatch(final DateUpdatedEventHandler handler) {
handler.onDateUpdated(this);
}
public final Date getLocalDate() {
return localDate;
}
}
@@ -0,0 +1,7 @@
package astrochart.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface DateUpdatedEventHandler extends EventHandler {
void onDateUpdated(final DateUpdatedEvent event);
}
+17
View File
@@ -0,0 +1,17 @@
package astrochart.client.event;
import com.google.gwt.event.shared.GwtEvent;
public class ResetAspectsEvent extends GwtEvent<ResetAspectsEventHandler> {
public static final Type<ResetAspectsEventHandler> TYPE = new Type<ResetAspectsEventHandler>();
@Override
public final Type<ResetAspectsEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected final void dispatch(final ResetAspectsEventHandler handler) {
handler.onResetAspects(this);
}
}
@@ -0,0 +1,7 @@
package astrochart.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface ResetAspectsEventHandler extends EventHandler {
void onResetAspects(final ResetAspectsEvent event);
}
+26
View File
@@ -0,0 +1,26 @@
package astrochart.client.event;
import com.google.gwt.event.shared.GwtEvent;
public class SetStatusEvent extends GwtEvent<SetStatusEventHandler> {
public static final Type<SetStatusEventHandler> TYPE = new Type<SetStatusEventHandler>();
private final String statusMessage;
public SetStatusEvent(final String statusMessage) {
this.statusMessage = statusMessage;
}
@Override
public final Type<SetStatusEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected final void dispatch(final SetStatusEventHandler handler) {
handler.onSetStatus(this);
}
public final String getStatusMessage() {
return statusMessage;
}
}
@@ -0,0 +1,7 @@
package astrochart.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface SetStatusEventHandler extends EventHandler {
void onSetStatus(final SetStatusEvent event);
}
@@ -0,0 +1,23 @@
package astrochart.client.presenter;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;
public class AbstractTabPresenter {
private final TabPanel tabPanel;
private final HandlerManager eventBus;
public AbstractTabPresenter(final HandlerManager eventBus, final TabPanel tabPanel) {
this.tabPanel = tabPanel;
this.eventBus = eventBus;
}
public final Widget getTabPanel() {
return tabPanel;
}
public final HandlerManager getEventBus() {
return eventBus;
}
}
+160
View File
@@ -0,0 +1,160 @@
package astrochart.client.presenter;
import java.util.logging.Logger;
import astrochart.client.service.AdminService;
import astrochart.client.service.AdminServiceAsync;
import astrochart.shared.data.Epoch;
import astrochart.shared.enums.Planet;
import astrochart.shared.enums.Weekday;
import astrochart.shared.enums.time.Month;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
public class AdminPresenter implements Presenter {
private static final Logger LOG = Logger.getLogger(AdminPresenter.class.getName());
private final AdminServiceAsync adminService = GWT.create(AdminService.class);
private final DateTimeFormat format = DateTimeFormat.getFormat("dd MM yyyy HH:mm:ss");
private final Display display;
private Month epochMonth = Month.January;
private int epochYear = 0;
private String[] lines;
private int lineIndex;
private int counter;
private boolean hasError = false;
public interface Display {
Widget asWidget();
Button getSubmitButton();
TextArea getInputTextArea();
Label getStatusLabel();
Label getSecondStatusLabel();
}
public AdminPresenter(final Display view) {
this.display = view;
}
public final void bind() {
display.getSubmitButton().addClickHandler(new ClickHandler() {
@Override
public final void onClick(final ClickEvent event) {
parseAndSubmitEpochs();
}
});
}
@Override
public final void go(final HasWidgets container) {
bind();
container.clear();
container.add(display.asWidget());
display.getStatusLabel().setText("Ready.");
display.getInputTextArea().setFocus(true);
}
private void parseAndSubmitEpochs() {
display.getSubmitButton().setEnabled(false);
counter = 0;
lineIndex = 0;
lines = display.getInputTextArea().getText().split("\n");
hasError = false;
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
parseLine(lineIndex);
}
});
}
private synchronized void parseLine(final int index) {
if (!hasError) {
display.getStatusLabel().setText("Processing line: " + index);
display.getSecondStatusLabel().setText(epochYear + " " + epochMonth);
for (final Month month : Month.values()) {
if (lines[index].startsWith(month.name().toUpperCase())) {
epochMonth = month;
epochYear = Integer.parseInt(lines[index].split(" ")[1]);
}
}
final Month finalEpochMonth = epochMonth;
final int finalEpochYear = epochYear;
parseEpochLine(finalEpochYear, finalEpochMonth, lines[index]);
if (lineIndex >= lines.length) {
display.getSubmitButton().setEnabled(true);
display.getStatusLabel().setText("Done.");
display.getSecondStatusLabel().setText("Number of Epochs submitted: " + counter);
} else { // next
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
parseLine(lineIndex++);
}
});
}
} else {
display.getSubmitButton().setEnabled(true);
return;
}
}
private void parseEpochLine(final int epochYear, final Month epochMonth, final String line) {
for (final Weekday weekday : Weekday.values()) {
if (line.startsWith(weekday.getAbbreviation())) {
final String[] split = line.split(" ");
//DATE SID.TIME SUN MOON MERCURY VENUS MARS JUPITER SATURN URANUS NEPTUNE PLUTO NODE
//0 1 2 3 4 5 6 7 8 9 10 11 12 13
//Fr 01 06:42:57 10CP36 07VI24 18CP00 20AQ04 29AR32 21LI12 25LI38 17AR44 17VI18 02TA24 20PI56
final Epoch epoch = new Epoch();
final String monthString = addZeroIfNeeded(String.valueOf(epochMonth.getNumber()));
epoch.setSidDate(format.parse(
split[1] + " " + monthString + " " + epochYear + " " + split[2]
));
epoch.setDay(weekday.getAbbreviation());
for (final Planet planet : Planet.values()) {
if (!planet.equals(Planet.SouthNode)) {
epoch.setPosition(planet, split[planet.getToken()]);
}
}
submitEpoch(epoch);
}
}
}
private String addZeroIfNeeded(final String monthString) {
if (monthString.length() == 1) {
return "0" + monthString;
} else {
return monthString;
}
}
private void submitEpoch(final Epoch epoch) {
adminService.saveEpoch(epoch, new AsyncCallback<Void>() {
@Override
public void onSuccess(final Void result) {
counter++;
}
@Override
public void onFailure(final Throwable caught) {
hasError = true;
LOG.severe("Fail submitting Epoch: " + caught.getMessage());
LOG.severe("Year: " + epochYear + " Month: " + epochMonth + " Epoch: " + epoch);
display.getStatusLabel().setText("Fail submitting Epoch: " + caught.getMessage());
display.getSecondStatusLabel().setText("Year: " + epochYear + " Month: " + epochMonth + " Epoch: " + epoch);
}
});
}
}
+449
View File
@@ -0,0 +1,449 @@
package astrochart.client.presenter;
import java.util.Date;
import astrochart.client.event.DateUpdatedEvent;
import astrochart.client.event.DateUpdatedEventHandler;
import astrochart.client.event.ResetAspectsEvent;
import astrochart.client.event.ResetAspectsEventHandler;
import astrochart.client.event.SetStatusEvent;
import astrochart.client.event.SetStatusEventHandler;
import astrochart.client.service.EpochService;
import astrochart.client.service.EpochServiceAsync;
import astrochart.client.service.GeocodeService;
import astrochart.client.service.GeocodeServiceAsync;
import astrochart.client.util.AstrologyUtil;
import astrochart.client.util.DateTimeUtil;
import astrochart.client.widgets.Chart;
import astrochart.client.widgets.TimeEntry;
import astrochart.shared.data.Epoch;
import astrochart.shared.data.GeocodeData;
import astrochart.shared.enums.AspectType;
import astrochart.shared.enums.HouseType;
import astrochart.shared.enums.Planet;
import astrochart.shared.exceptions.EpochNotFoundException;
import astrochart.shared.wrappers.AscendentAndOffset;
import astrochart.shared.wrappers.BodyPosition;
import astrochart.shared.wrappers.RiseAndSet;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.geolocation.client.Geolocation;
import com.google.gwt.geolocation.client.Position;
import com.google.gwt.geolocation.client.Position.Coordinates;
import com.google.gwt.geolocation.client.PositionError;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
public class ChartPresenter extends AbstractTabPresenter implements Presenter {
private final EpochServiceAsync epochService = GWT.create(EpochService.class);
private final GeocodeServiceAsync geocodeService = GWT.create(GeocodeService.class);
private final AstrologyUtil astroUtil = new AstrologyUtil();
private final DateTimeUtil dateTimeUtil;
private final Display display;
private Date providedUtcDate;
private Epoch epoch;
private Date localDate;
private Date utcDate;
private boolean disableUpdate = false;
public interface Display {
Widget asWidget();
Button getUpdatePositionsButton();
Button getRegenerateChartButton();
Chart getChart();
Label getUtcLabel();
Label getUtcJdLabel();
Label getUtcSidLabel();
CheckBox getPlanetCheckBox(Planet planet);
Label getPlanetLabel(Planet planet);
Button getSelectAllPlanetsButton();
Button getUnselectAllPlanetsButton();
ListBox getHousesListBox();
CheckBox getAspectCheckBox(AspectType type);
ListBox getAspectListBox(AspectType type);
Label getAspectLabel(AspectType type);
void resetAspects();
Button resetOrbsButton();
void resetOrbs();
Button getSelectAllAspectsButton();
Button getUnselectAllAspectsButton();
TextBox getLocationTextBox();
Button getSubmitCityButton();
TextBox getLatitudeTextBox();
Button getSubmitLatitudeButton();
TextBox getLongitudeTextBox();
Button getSubmitLongitudeButton();
Label getSunriseLabel();
Label getSunsetLabel();
Label getAscendentLabel();
Label getStatusLabel();
Label getSunPositionLabel();
TimeEntry getTimeEntry();
}
public ChartPresenter(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil, final TabPanel tabPanel, final Display view,
final Date providedUtcDate) {
super(eventBus, tabPanel);
this.dateTimeUtil = dateTimeUtil;
this.providedUtcDate = providedUtcDate;
this.display = view;
}
public final void bind() {
bindBus();
this.display.getUpdatePositionsButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
updateEpoch();
}
});
this.display.getRegenerateChartButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
regenerateChart();
}
});
for (final Planet planet : Planet.values()) {
this.display.getPlanetCheckBox(planet).addValueChangeHandler(createDefaultValueChangeHandler());
}
this.display.getSelectAllPlanetsButton().addClickHandler(createPlanetsChangeHandler(true));
this.display.getUnselectAllPlanetsButton().addClickHandler(createPlanetsChangeHandler(false));
this.display.getHousesListBox().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(final ChangeEvent event) {
final String houseSystemName = display.getHousesListBox().getItemText(display.getHousesListBox().getSelectedIndex());
final HouseType type = HouseType.getTypeForName(houseSystemName);
display.getChart().changeHouseSystem(type);
}
});
for (final AspectType type : AspectType.values()) {
this.display.getAspectCheckBox(type).addValueChangeHandler(createDefaultValueChangeHandler());
this.display.getAspectListBox(type).addChangeHandler(new ChangeHandler() {
@Override
public void onChange(final ChangeEvent event) {
regenerateChart();
}
});
}
this.display.resetOrbsButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
disableUpdate = true;
display.resetOrbs();
disableUpdate = false;
regenerateChart();
}
});
this.display.getSelectAllAspectsButton().addClickHandler(createAspectChangeHandler(true));
this.display.getUnselectAllAspectsButton().addClickHandler(createAspectChangeHandler(false));
this.display.getLocationTextBox().addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(final KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
updateGeodataByCityName();
}
}
});
this.display.getSubmitCityButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
updateGeodataByCityName();
}
});
this.display.getSubmitLatitudeButton().addClickHandler(createGeocodeClickHandler());
this.display.getSubmitLongitudeButton().addClickHandler(createGeocodeClickHandler());
this.display.getLatitudeTextBox().addKeyUpHandler(createGeocodeKeyUpHandler());
this.display.getLongitudeTextBox().addKeyUpHandler(createGeocodeKeyUpHandler());
}
public final void bindBus() {
getEventBus().addHandler(DateUpdatedEvent.TYPE, new DateUpdatedEventHandler() {
@Override
public void onDateUpdated(final DateUpdatedEvent event) {
updateEpoch(event.getLocalDate());
}
});
getEventBus().addHandler(ResetAspectsEvent.TYPE, new ResetAspectsEventHandler() {
@Override
public void onResetAspects(final ResetAspectsEvent event) {
display.resetAspects();
}
});
getEventBus().addHandler(SetStatusEvent.TYPE, new SetStatusEventHandler() {
@Override
public void onSetStatus(final SetStatusEvent event) {
display.getStatusLabel().setText(event.getStatusMessage());
}
});
}
@Override
public final void go(final HasWidgets container) {
bind();
container.clear();
container.add(super.getTabPanel());
if (providedUtcDate != null) {
// fill time entry with provided date (calls updateEpoch)
display.getTimeEntry().updateDate(providedUtcDate);
} else {
updateEpoch();
}
// XXX Experimental HTML5 Geolocation
// tryToGetGeolocationFromBrowser();
if (display.getLocationTextBox().getText().equals("unknown")) {
updateGeodataByIp();
}
this.display.getLocationTextBox().setFocus(true);
}
private void updateEpoch() {
updateEpoch(null);
}
private void updateEpoch(final Date inputLocalDate) {
display.getStatusLabel().setText("Updating positions.");
if (inputLocalDate != null) {
localDate = inputLocalDate;
} else {
localDate = display.getTimeEntry().getLocalDate();
}
utcDate = dateTimeUtil.getUtcDate(localDate);
final String timeZone = display.getTimeEntry().getClientTimezone();
display.getUtcLabel().setText(dateTimeUtil.formatDateAsUtc(localDate));
display.getUtcLabel().setTitle("As Time in your local timezone: \n" + dateTimeUtil.formatLocalDate(utcDate) + timeZone);
display.getUtcJdLabel().setText(dateTimeUtil.getFormattedJdTimeDate(utcDate));
display.getUtcJdLabel().setTitle("As JD Time in your local timezone: \n" + dateTimeUtil.getFormattedJdTimeDate(localDate) + timeZone);
final Date sidDate = dateTimeUtil.getLocalSidTimeDate(localDate); // also known as LST
final Date utcSidDate = dateTimeUtil.getLocalSidTimeDate(utcDate); // also known as GMST
display.getUtcSidLabel().setTitle("As Sidereal Time in your local timezone: \n" + dateTimeUtil.formatLocalDate(sidDate) + timeZone);
display.getUtcSidLabel().setText(dateTimeUtil.formatLocalDate(utcSidDate));
epochService.readEpoch(utcSidDate, new AsyncCallback<Epoch>() {
@Override
public void onSuccess(final Epoch result) {
epoch = result;
for (final Planet planet : Planet.values()) {
final Label label = display.getPlanetLabel(planet);
label.setText(result.getPositionDegreeString(planet));
label.setTitle(result.getPositionString(planet));
}
display.getStatusLabel().setText("Positions updated.");
processCustomGeocode(false);
}
@Override
public void onFailure(final Throwable caught) {
if (caught instanceof EpochNotFoundException) {
display.getStatusLabel().setText("Epoch not found. Please try another date.");
} else {
display.getStatusLabel().setText("Fail reading epoch: " + caught.getMessage());
}
}
});
}
/**
* Experimental HTML5 feature
*/
@SuppressWarnings("unused")
private void tryToGetGeolocationFromBrowser() {
final Geolocation geolocation = Geolocation.getIfSupported(); // experimental
geolocation.getCurrentPosition(new Callback<Position, PositionError>() {
@Override
public void onSuccess(final Position result) {
final Coordinates coords = result.getCoordinates();
display.getLatitudeTextBox().setText(String.valueOf(coords.getLatitude()));
display.getLatitudeTextBox().setTitle(astroUtil.convertDegrees(coords.getLatitude()));
display.getLongitudeTextBox().setText(String.valueOf(coords.getLongitude()));
display.getLongitudeTextBox().setTitle(astroUtil.convertDegrees(coords.getLongitude()));
processCustomGeocode(true);
}
@Override
public void onFailure(final PositionError reason) {
display.getStatusLabel().setText("Fail: Not able to get geolocation data from browser.");
}
});
}
private void updateGeodataByIp() {
display.getStatusLabel().setText("Updating geodata by IP.");
geocodeService.getGeocodeDataForIp(new AsyncCallback<GeocodeData>() {
@Override
public void onSuccess(final GeocodeData result) {
processGeocodeData(result);
}
@Override
public void onFailure(final Throwable caught) {
display.getStatusLabel().setText(
"Fail: Getting geocode data from IP. Please enter a city name or provide the latitude and longitude manually.");
}
});
}
private void updateGeodataByCityName() {
display.getStatusLabel().setText("Updating geodata by location name.");
final String cityName = display.getLocationTextBox().getText().trim();
geocodeService.getGeocodeData(cityName, new AsyncCallback<GeocodeData>() {
@Override
public void onSuccess(final GeocodeData result) {
processGeocodeData(result);
}
@Override
public void onFailure(final Throwable caught) {
display.getStatusLabel().setText("Fail: Getting geocode data.");
}
});
}
private void processCustomGeocode(final boolean resetCityName) {
display.getStatusLabel().setText("Processing custom geocode data.");
final GeocodeData geocode = new GeocodeData();
if (resetCityName) {
geocode.setCityName("user input");
this.display.getLocationTextBox().setText("user input");
} else {
geocode.setCityName(display.getLocationTextBox().getText());
}
this.display.getStatusLabel().setText("");
try {
geocode.setLatitude(Double.valueOf(display.getLatitudeTextBox().getText()));
try {
geocode.setLongitude(Double.valueOf(display.getLongitudeTextBox().getText()));
processGeocodeData(geocode);
} catch (final NumberFormatException nfe) {
final String message = "Fail: Longitude is not numeric.";
this.display.getStatusLabel().setText(message);
this.display.getLongitudeTextBox().setFocus(true);
}
} catch (final NumberFormatException nfe) {
final String message = "Fail: Latitide is not numeric.";
this.display.getStatusLabel().setText(message);
this.display.getLatitudeTextBox().setFocus(true);
}
}
private void processGeocodeData(final GeocodeData geocode) {
if (geocode == null || (geocode.getCityName().equals("") && geocode.getLatitude() == 0.0D && geocode.getLongitude() == 0.0D)) {
assert true; // ignore
} else {
display.getLocationTextBox().setText(geocode.getCityName());
final NumberFormat nf = NumberFormat.getFormat("0.0000000");
display.getLatitudeTextBox().setTitle(astroUtil.convertDegrees(geocode.getLatitude()));
display.getLatitudeTextBox().setText(nf.format(geocode.getLatitude()));
display.getLongitudeTextBox().setTitle(astroUtil.convertDegrees(geocode.getLongitude()));
display.getLongitudeTextBox().setText(nf.format(geocode.getLongitude()));
final RiseAndSet ras = astroUtil.calculateSunRiseAndSet(localDate, geocode.getLatitude(), geocode.getLongitude());
display.getSunriseLabel().setText(dateTimeUtil.formatLocalDate(ras.getRise()));
display.getSunsetLabel().setText(dateTimeUtil.formatLocalDate(ras.getSet()));
final BodyPosition position = astroUtil.calculateSunPosition(utcDate, geocode.getLatitude(), geocode.getLongitude());
display.getSunPositionLabel().setText(position.toString());
final AscendentAndOffset ascendent = astroUtil.determineAscendent(utcDate, geocode.getLongitude(), geocode.getLatitude());
display.getAscendentLabel().setText(ascendent.toString());
display.getStatusLabel().setText("Generating chart...");
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
final String houseSystemName = display.getHousesListBox().getItemText(display.getHousesListBox().getSelectedIndex());
final HouseType type = HouseType.getTypeForName(houseSystemName);
display.getChart().generateChart(ascendent, epoch, type);
}
});
}
}
public final void regenerateChart() {
if (disableUpdate) {
return;
}
display.getStatusLabel().setText("Generating chart...");
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
processCustomGeocode(false);
}
});
}
private ClickHandler createAspectChangeHandler(final boolean value) {
return new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
disableUpdate = true;
for (final AspectType aspectType : AspectType.values()) {
display.getAspectCheckBox(aspectType).setValue(value);
}
disableUpdate = false;
regenerateChart();
}
};
}
private ClickHandler createPlanetsChangeHandler(final boolean value) {
return new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
disableUpdate = true;
for (final Planet planet : Planet.values()) {
display.getPlanetCheckBox(planet).setValue(value);
}
disableUpdate = false;
regenerateChart();
}
};
}
private ValueChangeHandler<Boolean> createDefaultValueChangeHandler() {
return new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(final ValueChangeEvent<Boolean> event) {
regenerateChart();
}
};
}
private ClickHandler createGeocodeClickHandler() {
return new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
processCustomGeocode(true);
}
};
}
private KeyUpHandler createGeocodeKeyUpHandler() {
return new KeyUpHandler() {
@Override
public void onKeyUp(final KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
processCustomGeocode(true);
}
}
};
}
}
+72
View File
@@ -0,0 +1,72 @@
package astrochart.client.presenter;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;
public class InfoPresenter extends AbstractTabPresenter implements Presenter {
private final Display display;
private int row = 0;
public interface Display {
FlexTable getInfoList();
Widget asWidget();
}
public InfoPresenter(final HandlerManager eventBus,
final TabPanel tabPanel, final Display view) {
super(eventBus, tabPanel);
this.display = view;
}
public final void bind() {
}
@Override
public final void go(final HasWidgets container) {
bind();
prepareTable();
container.clear();
container.add(super.getTabPanel());
}
private void prepareTable() {
display.getInfoList().removeAllRows();
display.getInfoList().getColumnFormatter().setWidth(0, "100px");
addRowText("Welcome to Astrology Chart Generator.");
addRowText("This application is work in progress and may therefore still display incorrect results.");
addRowWidget(new HTML("&nbsp;"));
addRowText("The ephemeris used in this application can be found at:");
addRowWidget(new Anchor("http://www.findyourfate.com/astrology/ephemeris/ephemeris.html", "http://www.findyourfate.com/astrology/ephemeris/ephemeris.html"));
addRowWidget(new HTML("&nbsp;"));
addRowText("Astrology Chart Generator uses the following IP-location lookup service:");
addRowWidget(new Anchor("http://freegeoip.net", "http://freegeoip.net"));
addRowWidget(new HTML("&nbsp;"));
addRowText("The location lookup by city-name is powered by:");
addRowWidget(new Anchor("http://code.google.com/apis/maps/index.html", "http://code.google.com/apis/maps/index.html"));
addRowWidget(new HTML("&nbsp;"));
addRowText("Sunrise and sunset calculations are done according to the formulas provided at:");
addRowWidget(new Anchor("http://users.electromagnetic.net/bu/astro/sunrise-set.php", "http://users.electromagnetic.net/bu/astro/sunrise-set.php"));
addRowText("This application will therefore calculate the same results for sunrise and sunset as calculated here:");
addRowWidget(new Anchor("http://users.electromagnetic.net/bu/astro/iyf-calc.php", "http://users.electromagnetic.net/bu/astro/iyf-calc.php"));
addRowText("(Beware: There are many other online calculators that result in different results.)");
addRowWidget(new HTML("&nbsp;"));
addRowText("The source code and the unit tests of this application can be found at:");
addRowWidget(new Anchor("https://github.com/Tok/AstroChart", "https://github.com/Tok/AstroChart"));
}
private void addRowText(final String text) {
display.getInfoList().setText(row, 0, text);
row++;
}
private void addRowWidget(final Widget widget) {
display.getInfoList().setWidget(row, 0, widget);
row++;
}
}
+7
View File
@@ -0,0 +1,7 @@
package astrochart.client.presenter;
import com.google.gwt.user.client.ui.HasWidgets;
public abstract interface Presenter {
void go(final HasWidgets container);
}
+10
View File
@@ -0,0 +1,10 @@
package astrochart.client.service;
import astrochart.shared.data.Epoch;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("admin")
public interface AdminService extends RemoteService {
void saveEpoch(final Epoch epoch);
}
@@ -0,0 +1,8 @@
package astrochart.client.service;
import astrochart.shared.data.Epoch;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface AdminServiceAsync {
void saveEpoch(final Epoch epoch, final AsyncCallback<Void> callback);;
}
+12
View File
@@ -0,0 +1,12 @@
package astrochart.client.service;
import java.util.Date;
import astrochart.shared.data.Epoch;
import astrochart.shared.exceptions.EpochNotFoundException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("epoch")
public interface EpochService extends RemoteService {
Epoch readEpoch(final Date date) throws EpochNotFoundException;
}
@@ -0,0 +1,9 @@
package astrochart.client.service;
import java.util.Date;
import astrochart.shared.data.Epoch;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface EpochServiceAsync {
void readEpoch(final Date date, final AsyncCallback<Epoch> callback);
}
+11
View File
@@ -0,0 +1,11 @@
package astrochart.client.service;
import astrochart.shared.data.GeocodeData;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("geocode")
public interface GeocodeService extends RemoteService {
GeocodeData getGeocodeData(final String cityName);
GeocodeData getGeocodeDataForIp();
}
@@ -0,0 +1,9 @@
package astrochart.client.service;
import astrochart.shared.data.GeocodeData;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GeocodeServiceAsync {
void getGeocodeData(final String cityName, final AsyncCallback<GeocodeData> callback);
void getGeocodeDataForIp(final AsyncCallback<GeocodeData> callback);;
}
+546
View File
@@ -0,0 +1,546 @@
package astrochart.client.util;
import java.util.Date;
import com.google.gwt.i18n.client.NumberFormat;
import astrochart.shared.EquinocticalShaddowLengths;
import astrochart.shared.enums.ZodiacSign;
import astrochart.shared.wrappers.AscendentAndOffset;
import astrochart.shared.wrappers.BodyPosition;
import astrochart.shared.wrappers.RiseAndSet;
public class AstrologyUtil {
public static final double EARTH_INCLINATION_J2000 = 23.4392911D; // in degrees
public static final double EARTH_INCLINATION_J1950 = 23.4457889D; // in degrees
public static final double EARTH_AXIS_TILT = 23.45D; // TODO change to EARTH_AXIS_TILT_PRECISE
public static final double EARTH_AXIS_TILT_PRECISE = 23.439D; // TODO use EARTH_INCLINATION_J2000
public static final double EARTH_AXIS_TILT_DAILY_CHANGE = 0.0000004D;
public static final double PERIHELION_TO_VENERAL_EQUINOX_DEGREES = 102.9372D;
public static final double LONG_ABERRATION = 0.9856474D;
public static final double ANGLE_TO_SUN_FROM_PERIHELION = 357.528D; // TODO change to ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
public static final double ANGLE_TO_SUN_FROM_PERIHELION_PRECISE = 357.5291D;
public static final double SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION = 0.9856003D; // TODO change to SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE
public static final double SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE = 0.98560028D;
public static final double SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET = -0.83D;
public static final double EARTHS_SOLAR_TRANSIT_DATE = 0.0009D;
public static final double EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION = 0.0053D;
public static final double EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION = 0.0069D;
public static final double EARTH_ECCENTRICITY = 0.0167D;
public static final double SAEMUNDSON_REFRACTION_CONSTANT_1 = 1.02D;
public static final double SAEMUNDSON_REFRACTION_CONSTANT_2 = 10.3D;
public static final double SAEMUNDSON_REFRACTION_CONSTANT_3 = 5.11D;
public static final double EQUATION_OF_CENTER_CONSTANT_1 = 1.9148D;
public static final double EQUATION_OF_CENTER_CONSTANT_2 = 0.0200D;
public static final double EQUATION_OF_CENTER_CONSTANT_3 = 0.0003D;
private final EquinocticalShaddowLengths esl = new EquinocticalShaddowLengths();
private final DateTimeUtil dateTimeUtil = new DateTimeUtil();
private double meanSolarAnomaly = 0D;
private double equationOfCenter = 0D;
private double solarEclipticalLongitude = 0D;
private double solarNoonTransit = 0D;
public final double getMeanSolarNoonAnomaly() {
return meanSolarAnomaly;
}
public final double getEquationOfCenter() {
return equationOfCenter;
}
public final double getSolarEclipticalLongitude() {
return solarEclipticalLongitude;
}
public final double getSolarNoonTransit() {
return solarNoonTransit;
}
/**
* Asserts the ascendent for the provided local SiderealTime at latitude
* @param localSiderealTimeDeg Local siderealTime in degrees
* @param latitude of the location
* @return
*/
@Deprecated
public final ZodiacSign getTropicalAscendent(final double localSiderealTimeDeg, final double localLatitude) {
double ascendentDegrees = Math.atan(
(Math.cos(localSiderealTimeDeg) * -1)
/ (
(Math.sin(localSiderealTimeDeg) * Math.cos(EARTH_INCLINATION_J2000))
+ (Math.tan(localLatitude) * Math.sin(EARTH_INCLINATION_J2000))
));
if (ascendentDegrees < 0D || Math.cos(localSiderealTimeDeg) < 0D) {
ascendentDegrees = ascendentDegrees + (Constants.DEGREES_IN_CIRCLE / 2);
}
return ZodiacSign.getSignAtDegree(ascendentDegrees);
}
public final long calculateRashimanaSeconds(final ZodiacSign sign, final double latitude) {
final int roundedLat = Double.valueOf(latitude).intValue();
final int charakhandas = esl.calculateCharakhandas(sign, roundedLat);
final long asus = getAsus(sign, charakhandas);
return dateTimeUtil.convertAsusToSiderealSeconds(asus);
}
private long getAsus(final ZodiacSign sign, final int charakhandas) {
if (sign.hasLongAscension()) {
return sign.getRashimanaGroup().getEquatorialAsus() + charakhandas;
} else {
return sign.getRashimanaGroup().getEquatorialAsus() - charakhandas;
}
}
public final double calculateEclipticLongitude(final double julianDayNumber) {
return Constants.MEAN_LONGITUDE_OF_THE_SUN + (LONG_ABERRATION * julianDayNumber);
}
public final double calculateMeanAnomaly(final double julianDayNumber) {
return ANGLE_TO_SUN_FROM_PERIHELION + (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION * julianDayNumber);
}
public final double calculateJulianCycle(final double julianDay, final double longitudeWest) {
final double cycle = julianDay - DateTimeUtil.J_CONSTANT - (longitudeWest / Constants.DEGREES_IN_CIRCLE);
return cycle + Constants.HALF_JULIAN_DAY;
}
public final double calculateAccurateJulianCycle(final double julianDay, final double longitude) {
return Math.round((julianDay - Constants.JULIAN_DAY_AT_01_01_2000 - EARTHS_SOLAR_TRANSIT_DATE) - (longitude / Constants.DEGREES_IN_CIRCLE));
}
/**
* calculates the solar meanpoint as ecliptic coordinate
* with a numeric eccentricity of ~0.0167
* @param eclipticLongitude
* @param meanAnormaly
* @return
*/
public final double calculateEclipticalLength(final double eclipticLongitude, final double meanAnormaly) {
final double el = Math.toRadians(eclipticLongitude % Constants.DEGREES_IN_CIRCLE);
final double ma = Math.toRadians(meanAnormaly % Constants.DEGREES_IN_CIRCLE);
final double result = el
+ ((2 * EARTH_ECCENTRICITY * Math.sin(ma))
+ ((5.0D / 4.0D) * Math.pow(EARTH_ECCENTRICITY, 2) * Math.sin(2 * EARTH_ECCENTRICITY))
);
return Math.toDegrees(result);
}
public final double calculateEclipticInclination(final double julianDayNumber) {
return EARTH_AXIS_TILT_PRECISE - (EARTH_AXIS_TILT_DAILY_CHANGE * julianDayNumber);
}
/**
* http://de.wikipedia.org/wiki/Sonnenstand#.C3.84quatorialkoordinaten_der_Sonne
* @param eclipticInclination
* @param eclipticalLength
* @return
*/
public final double calculateRightAscension(final double eclipticInclination, final double eclipticalLength) {
final double eclipticInclinationRadians = Math.toRadians(eclipticInclination);
final double eclipticalLengthRadians = Math.toRadians(eclipticalLength);
final double argument = (Math.cos(eclipticInclinationRadians) * Math.sin(eclipticalLengthRadians)) / Math.cos(eclipticalLengthRadians);
final double atan = Math.atan(argument);
final double result = Math.toDegrees(atan);
return clampResult(result);
}
private double clampResult(final double result) {
if (result < 0.0D) {
return result + (Constants.DEGREES_IN_CIRCLE / 2);
} else {
return result;
}
}
public final double calculateDeclination(final double eclipticInclination, final double eclipticalLength) {
final double result = Math.asin(Math.sin(Math.toRadians(eclipticInclination)) * Math.sin(Math.toRadians(eclipticalLength)));
return Math.toDegrees(result);
}
public final double calculateVeneralEquinoxDegrees(final double starTimeDegrees, final double longitude) {
return (starTimeDegrees + longitude) % Constants.DEGREES_IN_CIRCLE;
}
public final double calculateHourAngle(final double localJulianDeg, final double rightAscension) {
return localJulianDeg - rightAscension;
}
public final double calculateAzimuth(final double hourAngle, final double latitude, final double declination) {
final double divisor =
(Math.cos(Math.toRadians(hourAngle)) * Math.sin(Math.toRadians(latitude)))
- (Math.tan(Math.toRadians(declination)) * Math.cos(Math.toRadians(latitude)));
final double azimuthAtan = Math.atan(Math.sin(Math.toRadians(hourAngle)) / divisor);
final double azimuth = Math.toDegrees(azimuthAtan);
return clampAzimuth(azimuth, divisor);
}
private double clampAzimuth(final double azimuth, final double divisor) {
if (divisor < 0D) {
return azimuth + (Constants.DEGREES_IN_CIRCLE / 2);
} else {
return azimuth;
}
}
public final double calculateAzimuthNorth(final double hourAngle, final double latitude, final double declination) {
return calculateAzimuth(hourAngle, latitude, declination) + (Constants.DEGREES_IN_CIRCLE / 2);
}
public final double calculateHeightAngle(final double hourAngle, final double latitude, final double declination) {
final double heightAngle =
Math.asin((Math.cos(Math.toRadians(declination))
* Math.cos(Math.toRadians(hourAngle))
* Math.cos(Math.toRadians(latitude)))
+ (Math.sin(Math.toRadians(declination))
* Math.sin(Math.toRadians(latitude))));
return Math.toDegrees(heightAngle);
}
/**
* Calculates the mean refraction for an object at the provided angle at 1010 mbar and 10� C.
* http://de.wikipedia.org/wiki/Sonnenstand#Korrektur_der_H.C3.B6he_wegen_Refraktion
* @param heightAngle
* @return
*/
private double calculateRefraction(final double heightAngle) {
final double term = heightAngle + (SAEMUNDSON_REFRACTION_CONSTANT_2 / (heightAngle + SAEMUNDSON_REFRACTION_CONSTANT_3));
final double termRadians = Math.toRadians(term);
return SAEMUNDSON_REFRACTION_CONSTANT_1 / Math.tan(termRadians);
}
public final double calculateRefractionDegrees(final double heightAngle) {
return heightAngle + (calculateRefraction(heightAngle) / Constants.MINUTES_PER_DEGREE);
}
/**
* http://de.wikipedia.org/wiki/Sonnenstand
*/
public final BodyPosition calculateSunPosition(final Date date, final double latitude, final double longitude) {
final double julianDay = dateTimeUtil.getJdTimeDate(date);
final double n = dateTimeUtil.calculateJulianDayNumberFromJd(julianDay);
final double l = calculateEclipticLongitude(n);
final double g = calculateMeanAnomaly(n);
final double lambda = calculateEclipticalLength(l, g); //solar ecliptic coordinate
final double epsilon = calculateEclipticInclination(n); //ecliptic inclination
final double rightAscension = calculateRightAscension(epsilon, lambda);
final double declination = calculateDeclination(epsilon, lambda); //equatorical declination
final double jdo = dateTimeUtil.getJulianDayNumberTimeDropped(date);
final double t = dateTimeUtil.getJulianCenturiesSinceJ2000(jdo); //julian centuries since J2000.0
final double decimalHours = dateTimeUtil.getDecimalHours(date);
final double starTimeHours = dateTimeUtil.calculateStarTimeHours(t, decimalHours);
final double starTimeDegrees = dateTimeUtil.convertHoursToDegree(starTimeHours);
final double localJulianDeg = calculateVeneralEquinoxDegrees(starTimeDegrees, longitude); //veneral equinox degrees
final double hourAngle = calculateHourAngle(localJulianDeg, rightAscension);
final double azimuth = calculateAzimuth(hourAngle, latitude, declination);
final double heightAngle = calculateHeightAngle(hourAngle, latitude, declination);
final double refHeight = calculateRefractionDegrees(heightAngle);
return new BodyPosition(azimuth, refHeight);
}
public final double calculateApproxSolarNoon(final double julianCycle, final double longitude) {
return Constants.JULIAN_DAY_AT_01_01_2000 + EARTHS_SOLAR_TRANSIT_DATE + (longitude / Constants.DEGREES_IN_CIRCLE) + julianCycle;
}
public final double calculateAccurateMeanAnomaly(final double solarNoonApprox) {
return (ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
+ (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE
* (solarNoonApprox - Constants.JULIAN_DAY_AT_01_01_2000)))
% Constants.DEGREES_IN_CIRCLE;
}
/**
* http://en.wikipedia.org/wiki/Sunrise_equation#Equation_of_Center
* @param meanSolarAnomaly
* @return
*/
public final double calculateEquationOfCenter(final double meanSolarAnomaly) {
return (EQUATION_OF_CENTER_CONSTANT_1 * Math.sin(Math.toRadians(meanSolarAnomaly)))
+ (EQUATION_OF_CENTER_CONSTANT_2 * Math.sin(2D * Math.toRadians(meanSolarAnomaly)))
+ (EQUATION_OF_CENTER_CONSTANT_3 * Math.sin(3D * Math.toRadians(meanSolarAnomaly)));
}
public final double calculateSolarEclipticLongitude(final double meanSolarAnomaly, final double equationOfCenter) {
return (meanSolarAnomaly + PERIHELION_TO_VENERAL_EQUINOX_DEGREES + equationOfCenter + (Constants.DEGREES_IN_CIRCLE / 2)) % Constants.DEGREES_IN_CIRCLE;
}
public final double calculateSolarNoonTransit(final double solarNoonApprox, final double meanSolarAnomaly, final double solarEclipticalLongitude) {
return solarNoonApprox
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(Math.toRadians(meanSolarAnomaly)))
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(Math.toRadians(2D * solarEclipticalLongitude)));
}
public final double calculateSolarDeclination(final double solarEclipticalLongitude) {
final double result = Math.asin(
Math.sin(Math.toRadians(solarEclipticalLongitude))
* Math.sin(Math.toRadians(EARTH_AXIS_TILT))
);
return Math.toDegrees(result);
}
public final double calculateAccurateMeanAnomalyRecursive(final double solarNoonApprox, final double oldMeanSolarAnomaly, final double solarNoonTransit) {
final double meanSolarAnomaly = calculateAccurateMeanAnomaly(solarNoonTransit);
if (oldMeanSolarAnomaly != meanSolarAnomaly) {
final double equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
final double solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
final double newSolarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
return calculateAccurateMeanAnomalyRecursive(solarNoonApprox, meanSolarAnomaly, newSolarNoonTransit);
} else {
this.meanSolarAnomaly = meanSolarAnomaly;
this.equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
this.solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
this.solarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
return meanSolarAnomaly;
}
}
public final double calculateExactHourAngle(final double latitude, final double solarDeclination) {
final double result =
Math.acos(
(Math.sin(Math.toRadians(SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET))
- (Math.sin(Math.toRadians(latitude))
* Math.sin(Math.toRadians(solarDeclination))))
/ (Math.cos(Math.toRadians(latitude))
* Math.cos(Math.toRadians(solarDeclination)))
);
return Math.toDegrees(result);
}
public final double calculateSolarNoonSecondApprox(final double hourAngle, final double longitude, final double julianCycle) {
return Constants.JULIAN_DAY_AT_01_01_2000 + EARTHS_SOLAR_TRANSIT_DATE + ((hourAngle + longitude) / Constants.DEGREES_IN_CIRCLE) + julianCycle;
}
public final double calculateSunset(final double solarNoonSecondApprox, final double meanSolarAnomaly, final double solarEclipticalLongitude) {
return solarNoonSecondApprox
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(Math.toRadians(meanSolarAnomaly)))
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(Math.toRadians(2D * solarEclipticalLongitude)));
}
public final double calculateSunrise(final double sunset, final double solarNoonTransit) {
return solarNoonTransit - (sunset - solarNoonTransit);
}
/**
* http://users.electromagnetic.net/bu/astro/sunrise-set.php
* http://www.jgiesen.de/astro/astroJS/sunriseJS/index.htm
* @param julianDay
* @param latitude
* @param longitude
* @return
*/
public final RiseAndSet calculateSunRiseAndSet(final Date date, final double latitude, final double longitude) {
final double julianDate = dateTimeUtil.calculateJulianDate(date);
final double julianCycle = calculateAccurateJulianCycle(julianDate, longitude);
final double solarNoonApprox = calculateApproxSolarNoon(julianCycle, longitude);
final double meanSolarAnomaly = calculateAccurateMeanAnomaly(solarNoonApprox);
this.equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
this.solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
this.solarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
final double accurateMeanSolarAnomaly = calculateAccurateMeanAnomalyRecursive(solarNoonApprox, meanSolarAnomaly, solarNoonTransit);
final double solarDeclination = calculateSolarDeclination(solarEclipticalLongitude);
final double hourAngle = calculateExactHourAngle(latitude, solarDeclination);
final double solarNoonSecondApprox = calculateSolarNoonSecondApprox(hourAngle, longitude, julianCycle);
final double sunset = calculateSunset(solarNoonSecondApprox, accurateMeanSolarAnomaly, getSolarEclipticalLongitude());
final double sunrise = calculateSunrise(sunset, getSolarNoonTransit());
final Date sunriseDate = dateTimeUtil.convertJdToDate(sunrise);
final Date sunsetDate = dateTimeUtil.convertJdToDate(sunset);
final RiseAndSet result = new RiseAndSet(sunriseDate, sunsetDate);
return result;
}
/**
* http://en.wikipedia.org/wiki/Sunrise_equation
* @param julianDay
* @param latitude
* @param longitude
* @return
*/
@Deprecated
public final double calculateSunrise(final double julianDay, final double latitude, final double longitude) {
//FIXME
final double currentJulianCycle = calculateJulianCycle(julianDay, longitude);
final double approximateSolarNoon = DateTimeUtil.J_CONSTANT + (longitude / Constants.DEGREES_IN_CIRCLE) + currentJulianCycle;
final double solarMeanAnomaly = (ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
+ (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE * (approximateSolarNoon - Constants.JULIAN_DAY_AT_01_01_2000)))
% Constants.DEGREES_IN_CIRCLE;
final double equationOfCenter =
(EQUATION_OF_CENTER_CONSTANT_1 * Math.sin(solarMeanAnomaly))
+ (EQUATION_OF_CENTER_CONSTANT_2 * Math.sin(2.0D * solarMeanAnomaly))
+ (EQUATION_OF_CENTER_CONSTANT_3 * Math.sin(3.0D * solarMeanAnomaly));
final double eclipticLongitude = (solarMeanAnomaly + PERIHELION_TO_VENERAL_EQUINOX_DEGREES + equationOfCenter + (Constants.DEGREES_IN_CIRCLE / 2))
% Constants.DEGREES_IN_CIRCLE;
final double solarTransit =
approximateSolarNoon
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(solarMeanAnomaly))
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(2.0D * eclipticLongitude)); //hour angle for solar noon
final double sunDeclination = Math.asin(Math.sin(eclipticLongitude) * Math.sin(EARTH_AXIS_TILT));
final double hourAngle =
Math.acos(
(Math.sin(SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET) - (Math.sin(latitude) * Math.sin(sunDeclination)))
/ (Math.cos(latitude) * Math.cos(sunDeclination))
);
final double sunSet = DateTimeUtil.J_CONSTANT + ((hourAngle + longitude) / Constants.DEGREES_IN_CIRCLE) + currentJulianCycle
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(solarMeanAnomaly))
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(2D * eclipticLongitude));
final double sunRise = solarTransit - (sunSet - solarTransit);
return sunRise;
}
/**
* http://de.wikipedia.org/wiki/Aszendent_%28Astrologie%29#Berechnung_des_Aszendenten
* @param localSiderealDegrees
* @param latitude
* @return
*/
public final double calculateEclipticLongitudeJ2000Tangens(final double localSiderealDegrees, final double latitude) {
final double tanLambda =
(Math.cos(Math.toRadians(localSiderealDegrees)) * -1)
/ ((Math.sin(Math.toRadians(localSiderealDegrees))
* Math.cos(Math.toRadians(EARTH_INCLINATION_J2000)))
+ (Math.tan(Math.toRadians(latitude))
* Math.sin(Math.toRadians(EARTH_INCLINATION_J2000))));
return tanLambda;
}
public final boolean returnDescendent(final double localSiderealDegrees) {
return ((Constants.DEGREES_IN_CIRCLE / 4) < localSiderealDegrees && localSiderealDegrees < ((Constants.DEGREES_IN_CIRCLE / 4) * 3));
}
public final double getFirstHorizontEclipticSection(final double eclipticLongitudeTan) {
final double eclipticLongitude = Math.atan(eclipticLongitudeTan);
final double eclipticLongitudeDeg = Math.toDegrees(eclipticLongitude);
final double firstS1 = (eclipticLongitudeDeg + (Constants.DEGREES_IN_CIRCLE / 2)) % Constants.DEGREES_IN_CIRCLE;
return clampS1(firstS1);
}
private double clampS1(final double firstS1) {
if (firstS1 >= (Constants.DEGREES_IN_CIRCLE / 2)) {
return firstS1 - (Constants.DEGREES_IN_CIRCLE / 2);
} else {
return firstS1;
}
}
public final double getSecondHorizontEclipticSection(final double eclipticLongitudeTan) {
return getFirstHorizontEclipticSection(eclipticLongitudeTan) + (Constants.DEGREES_IN_CIRCLE / 2);
}
public final ZodiacSign returnSign(final double s1, final double s2, final boolean returnDescendent) {
if (returnDescendent) {
return ZodiacSign.getSignAtDegree(s2);
} else {
return ZodiacSign.getSignAtDegree(s1);
}
}
public final double returnPosition(final double s1, final double s2, final boolean returnDescendent) {
if (returnDescendent) {
return s2 - returnSign(s1, s2, returnDescendent).getEclipticLongitude();
} else {
return s1 - returnSign(s1, s2, returnDescendent).getEclipticLongitude();
}
}
public final AscendentAndOffset determineAscendent(final Date utcDate, final double longitude, final double latitude) {
final double jd = dateTimeUtil.getJdTimeDate(utcDate);
final double siderealDegrees = dateTimeUtil.getSiderealDegrees(jd);
final double localSiderealDegrees = dateTimeUtil.getLocalSiderealDegrees(siderealDegrees, longitude);
final double eclipticLongitudeTan = calculateEclipticLongitudeJ2000Tangens(localSiderealDegrees, latitude);
final double s1 = getFirstHorizontEclipticSection(eclipticLongitudeTan);
final double s2 = getSecondHorizontEclipticSection(eclipticLongitudeTan);
final boolean returnDescendent = returnDescendent(localSiderealDegrees);
final ZodiacSign sign = returnSign(s1, s2, returnDescendent);
final double position = returnPosition(s1, s2, returnDescendent);
// final double midheaven = calculateMidheaven(localSiderealDegrees);
// final double midheaven = calculateMc(localSiderealDegrees);
final double midheaven = 0.0D; //FIXME
final AscendentAndOffset asc = new AscendentAndOffset(sign, position, midheaven);
return asc;
}
/**
* http://www.sismoloc.info/mc_east_and_ac_north.html
* ARMC = ascensio recta medii coeli = right ascension of the local meridian
* @return
*/
@Deprecated
public final double calculateMidheaven(final double armcDegree) {
return Math.toDegrees(
Math.atan(
Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
* (1D / Math.tan(Math.toRadians(armcDegree))) //=cot
) * -1D
) + ((Constants.DEGREES_IN_CIRCLE / 4) * 3);
}
/**
* http://groups.google.com/group/alt.astrology.moderated/browse_thread/thread/5cf05d6fe8eabb52/17e0c6282d8c7dce?lnk=raot
* @return
*/
@Deprecated
public final double calculateMc(final double ramc) {
return Math.toDegrees(Math.atan(
Math.tan(Math.toRadians(ramc))
/ Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
)) + ((Constants.DEGREES_IN_CIRCLE / 4) * 3);
}
@Deprecated
public final double calculateObliqueAscension(final double ascendentLongitude, final double longitude) {
final double rightAscension =
Math.toDegrees(Math.atan(
Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
* Math.tan(Math.toRadians(ascendentLongitude))
));
final double d =
Math.toDegrees(Math.asin(
Math.sin(Math.toRadians(EARTH_INCLINATION_J2000))
* Math.sin(Math.toRadians(ascendentLongitude))
));
System.out.println("rightAscension: " + rightAscension);
final double obliqueAscension =
rightAscension
- Math.toDegrees(Math.asin(
Math.tan(Math.toRadians(d))
* Math.tan(Math.toRadians(longitude))
));
return obliqueAscension;
}
/**
* Converts the provided degrees from decimal to a String with degrees, minutes and seconds.
* @param inDegrees decimal
* @return converted String
*/
public final String convertDegrees(final double inDegrees) {
final int degrees;
if (inDegrees >= 0) {
degrees = Double.valueOf(Math.floor(inDegrees)).intValue();
} else {
degrees = Double.valueOf(Math.ceil(inDegrees)).intValue();
}
final double decimalPlaces = Math.abs(inDegrees - degrees);
final double exactMinutes = decimalPlaces * Constants.MINUTES_PER_DEGREE;
final int minutes = Double.valueOf(Math.floor(exactMinutes)).intValue();
final double second = Double.valueOf((exactMinutes - Math.floor(exactMinutes)) * Constants.SECONDS_PER_MINUTE);
final String secondString = NumberFormat.getFormat("0.0").format(second);
return "" + degrees + Constants.DEGREE_SIGN + minutes + Constants.MINUTE_SIGN + secondString + Constants.SECOND_SIGN;
}
}
+22
View File
@@ -0,0 +1,22 @@
package astrochart.client.util;
public final class Constants {
public static final double JULIAN_DAY_AT_01_01_2000 = 2451545D;
public static final double HALF_JULIAN_DAY = 0.5D;
public static final double MEAN_LONGITUDE_OF_THE_SUN = 280.460D; // XXX sometimes given as 280.461
public static final double MEAN_LONGITUDE_OF_THE_SUN_PRECISE = 280.46061837D;
public static final double DEGREES_IN_CIRCLE = 360.0D;
public static final double DEGREES_PER_HOUR = 15D;
public static final double MINUTES_PER_DEGREE = 60.0D;
public static final double HOURS_PER_DAY = 24D;
public static final double MINUTES_PER_HOUR = 60D;
public static final double SECONDS_PER_MINUTE = 60D;
public static final double SECONDS_PER_HOUR = 3600D;
public static final long MILLISECONDS_PER_MINUTE = 60000L;
public static final long MILLISECONDS_PER_DAY = 86400000L;
public static final char DEGREE_SIGN = '\u00B0';
public static final char MINUTE_SIGN = '\u2032';
public static final char SECOND_SIGN = '\u2033';
private Constants() { }
}
+392
View File
@@ -0,0 +1,392 @@
package astrochart.client.util;
import java.util.Date;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.i18n.client.TimeZone;
public class DateTimeUtil {
public static final double J_CONSTANT = 2451545.0009D;
private static final long MS_2000 = 946684800000L; //2000-01-01 00:00:00 +0000 in milliseconds
private static final double JD_2000 = Constants.JULIAN_DAY_AT_01_01_2000 - Constants.HALF_JULIAN_DAY; //2000-01-01 00:00:00 as JD
private static final long MS_PER_DAY = 86400000L;
private static final double DAYS_PER_YEAR = 365D;
private static final long MONTHS_PER_YEAR = 12L;
private static final double DAYS_PER_JULIAN_CENTURY = 36525D;
private static final double MINUTES_PER_DAY = 1440D;
private static final double SECONDS_PER_HOUR = 3600D;
private static final double SECONDS_PER_DAY = 86400D;
private static final double SIDEREAL_CONSTANT_1 = 13185000.77D;
private static final double SIDEREAL_CONSTANT_2 = 2577.765D;
private static final double SIDEREAL_CONSTANT_3 = 38710000D;
private static final double SIDEREAL_GMST_CONSTANT_0 = 24110.54841D;
private static final double SIDEREAL_GMST_CONSTANT_1 = 8640184.812866D;
private static final double SIDEREAL_GMST_CONSTANT_2 = 0.093104D;
private static final double SIDEREAL_GMST_CONSTANT_3 = 0.0000062D;
private static final double SIDEREAL_HOUR_CONSTANT_1 = 18.697374558D;
private static final double SIDEREAL_HOUR_CONSTANT_2 = 24.06570982441908D;
private static final double GMST_HOUR_CONSTANT_1 = 6.697374558D;
private static final double GMST_HOUR_CONSTANT_2 = 0.06570982441908D;
private static final double GMST_HOUR_CONSTANT_3 = 1.00273790935D;
private static final double GMST_HOUR_CONSTANT_4 = 0.000026D;
private static final double STARTIME_CONSTANT_1 = 6.697376D; //change to GMST_HOUR_CONSTANT_1?
private static final double STARTIME_CONSTANT_2 = 2400.05134D;
private static final double STARTIME_CONSTANT_3 = 1.002738D;
private static final long LEAP_YEAR_CONSTANT_4 = 4L;
private static final long LEAP_YEAR_CONSTANT_100 = 100L;
private static final long LEAP_YEAR_CONSTANT_400 = 400L;
private static final long JULIAN_DAY_0_BC = 4800L;
private static final long MONTH_FACTOR = 153L;
private static final long JDN_OFFSET = 32045L;
private final DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss");
private final NumberFormat nf = NumberFormat.getFormat("00"); //number format for hours, minutes or seconds
private final NumberFormat jdNf = NumberFormat.getFormat("0.0000"); //number format for JD
private enum DateTimeRange {
Year(0, 4),
Month(5, 7),
Days(8, 10),
Hours(11, 13),
Minutes(14, 16),
Seconds(17, 19);
private int from;
private int to;
DateTimeRange(final int from, final int to) {
this.from = from;
this.to = to;
}
public final int getFrom() {
return from;
}
public final int getTo() {
return to;
}
}
public final String formatDateAsUtc(final Date localDate) {
return dateTimeFormat.format(localDate, TimeZone.createTimeZone(0));
}
public final String formatLocalDate(final Date localDate) {
return dateTimeFormat.format(localDate);
}
public final String formatLocalDate(final Date localDate, final String timeZone) {
final int timeZoneMinutes = getTimeZoneMinutes(timeZone);
return dateTimeFormat.format(localDate, TimeZone.createTimeZone(timeZoneMinutes));
}
private int getTimeZoneMinutes(final String timeZone) {
if (timeZone.contains("+")) {
return Double.valueOf(Double.valueOf(timeZone.split("\\+")[1]) * Constants.MINUTES_PER_HOUR).intValue();
} else if (timeZone.contains("-")) {
return Double.valueOf(Double.valueOf(timeZone.split("\\-")[1]) * Constants.MINUTES_PER_HOUR).intValue();
} else {
return 0;
}
}
public final Date getUtcDate(final Date localDate) {
return dateTimeFormat.parse(formatDateAsUtc(localDate));
}
public final Date getUtcDateFromUtcString(final String utcDateString) {
return dateTimeFormat.parse(utcDateString);
}
public final Date getLocalDateFromUtc(final Date providedUtcDate) {
return dateTimeFormat.parse(dateTimeFormat.format(providedUtcDate));
}
/**
* http://en.wikipedia.org/wiki/Julian_day#Julian_Date
* @param date
* @return Julian Date
*/
public final double getJdTimeDate(final Date date) {
final long differenceMs = date.getTime() - new Date(MS_2000).getTime(); //milliseconds since 2000-01-01 00:00:00
final double daysSince2000 = differenceMs / Double.valueOf(MS_PER_DAY);
final double jd = JD_2000 + daysSince2000; //Julian Date
return jd;
}
public final Date convertJdToDate(final double jd) {
final double daysSince2000 = jd - JD_2000;
final double differenceMs = daysSince2000 * Double.valueOf(MS_PER_DAY);
final long dateMs = Double.valueOf(differenceMs).longValue() + new Date(MS_2000).getTime();
final Date result = new Date(dateMs);
return result;
}
public final String getFormattedJdTimeDate(final Date date) {
return jdNf.format(getJdTimeDate(date));
}
// /**
// * Also known as GMST
// * @param localDate
// * @return
// */
// public final Date getGmtSidTimeDate(final Date localDate) {
// return getLocalSidTimeDate(getUtcDate(localDate));
// }
/**
* Also known as LST
* http://en.wikipedia.org/wiki/Sidereal_time
* @param date
* @return
*/
public final Date getLocalSidTimeDate(final Date date) {
final double jd = getJdTimeDate(date);
final double a = clampA(getSiderealDegrees(jd) / Constants.DEGREES_PER_HOUR);
final double gmstHours = a % Constants.HOURS_PER_DAY;
final double gmstMinutes = ((a % Constants.HOURS_PER_DAY) * Constants.MINUTES_PER_HOUR) % Constants.MINUTES_PER_HOUR;
final double gmstSeconds = ((a % Constants.HOURS_PER_DAY) * Constants.MINUTES_PER_HOUR * Constants.SECONDS_PER_MINUTE)
% Constants.SECONDS_PER_MINUTE;
final String dateString = dateTimeFormat.format(date);
final int dateYear = Integer.valueOf(dateString.substring(0, 4));
final int dateMonth = Integer.valueOf(dateString.substring(5, 7));
final int dateDay = Integer.valueOf(dateString.substring(8, 10));
final String gmstHoursString = nf.format(Math.floor(gmstHours));
final String gmstMinutesString = nf.format(Math.floor(gmstMinutes));
final String gmstSecondsString = nf.format(Math.floor(gmstSeconds));
final String gmstDateString =
nf.format(dateYear) + "." + nf.format(dateMonth) + "." + nf.format(dateDay) + " "
+ gmstHoursString + ":" + gmstMinutesString + ":" + gmstSecondsString;
return dateTimeFormat.parse(gmstDateString);
}
private double clampA(final double a) {
if (a < 0D) {
return Constants.DEGREES_IN_CIRCLE - (Math.abs(a) % Constants.DEGREES_IN_CIRCLE);
} else {
return a;
}
}
/**
* http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html
* @param jd
* @return GmstSiderealSeconds
*/
@Deprecated
public final double getGmstSeconds(final double jd) {
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
final double gmstSiderealSeconds =
SIDEREAL_GMST_CONSTANT_0
+ (SIDEREAL_GMST_CONSTANT_1 * julianCenturiesSinceJ2000)
+ (SIDEREAL_GMST_CONSTANT_2 * Math.pow(julianCenturiesSinceJ2000, 2))
- (SIDEREAL_GMST_CONSTANT_3 * Math.pow(julianCenturiesSinceJ2000, 3));
return gmstSiderealSeconds;
}
/**
* http://answers.yahoo.com/question/index?qid=20070830185150AAoNT4i
* @param jd
* @return gmstSiderealHours
*/
@Deprecated
public final double getGmstHours(final double jd) {
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
final double h = 0D;
final double gmstSiderealHours =
GMST_HOUR_CONSTANT_1
+ (GMST_HOUR_CONSTANT_2 * julianCenturiesSinceJ2000)
+ (GMST_HOUR_CONSTANT_3 * h)
- (GMST_HOUR_CONSTANT_4 * Math.pow(julianCenturiesSinceJ2000, 2));
return gmstSiderealHours;
}
/**
* http://de.wikipedia.org/wiki/Sternzeit#Berechnung_der_Sternzeit
* @param jd
* @return sidereal time in degrees.
*/
public final double getSiderealDegrees(final double jd) {
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
final double siderealDegrees =
Constants.MEAN_LONGITUDE_OF_THE_SUN_PRECISE
+ (SIDEREAL_CONSTANT_1 * julianCenturiesSinceJ2000)
+ ((Math.pow(julianCenturiesSinceJ2000, 2)) / SIDEREAL_CONSTANT_2)
- ((Math.pow(julianCenturiesSinceJ2000, 3)) / SIDEREAL_CONSTANT_3);
return siderealDegrees;
}
/**
* http://en.wikipedia.org/wiki/Sidereal_time#Definition
* loss of precision of 0.1 second per century
* @param decimalDays
* @return sidereal time in hours
*/
public final double getSiderealHours(final double jd) {
final double daysSinceJ2000 = jd - Constants.JULIAN_DAY_AT_01_01_2000;
final double siderealHours = SIDEREAL_HOUR_CONSTANT_1 + (SIDEREAL_HOUR_CONSTANT_2 * daysSinceJ2000);
return siderealHours;
}
/**
* Converts asus into seconds compare:
* http://www.aryabhatt.com/vediclessons/vediclesson5.htm
* @param asus
* @return
*/
public final long convertAsusToSiderealSeconds(final long asus) {
return asus * 4L;
}
/**
* http://en.wikipedia.org/wiki/Julian_day#Converting_Gregorian_calendar_date_to_Julian_Day_Number
* @param date
* @return
*/
public final double getJulianDayNumber(final Date date) {
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
final int dateYear = Integer.valueOf(dateString.substring(0, 4));
final int dateMonth = Integer.valueOf(dateString.substring(5, 7));
final int dateDay = Integer.valueOf(dateString.substring(8, 10));
final long a = ((MONTHS_PER_YEAR + 2L) - dateMonth) / MONTHS_PER_YEAR;
final long y = dateYear + JULIAN_DAY_0_BC - a;
final long m = dateMonth + (MONTHS_PER_YEAR * a) - 3;
final double jdn = dateDay
+ (((MONTH_FACTOR * m) + 2L) / 5L)
+ (DAYS_PER_YEAR * y)
+ (y / LEAP_YEAR_CONSTANT_4)
- (y / LEAP_YEAR_CONSTANT_100)
+ (y / LEAP_YEAR_CONSTANT_400)
- JDN_OFFSET;
return jdn;
}
public final double getJulianDayNumberWithTime(final Date date) {
final double jdn = getJulianDayNumber(date);
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
final double hours = Double.valueOf(dateString.substring(11, 13));
final double minutes = Double.valueOf(dateString.substring(14, 16));
final double seconds = Double.valueOf(dateString.substring(17, 19));
final double result = jdn
+ ((hours - MONTHS_PER_YEAR) / Constants.HOURS_PER_DAY)
+ minutes / MINUTES_PER_DAY
+ seconds / SECONDS_PER_DAY;
return result;
}
public final double getJulianDayNumberTimeDropped(final Date date) {
final double jdn = getJulianDayNumber(date);
final double hours = 0D;
final double minutes = 0D;
final double seconds = 0D;
final double result = jdn
+ ((hours - MONTHS_PER_YEAR) / Constants.HOURS_PER_DAY)
+ minutes / MINUTES_PER_DAY
+ seconds / SECONDS_PER_DAY;
return result;
}
/**
* calculates julian centuries since J2000.0 for the provided julian day number
* @param julianDayNumber
* @return
*/
public final double getJulianCenturiesSinceJ2000(final double jd) {
return ((jd - Constants.JULIAN_DAY_AT_01_01_2000) / DAYS_PER_JULIAN_CENTURY); //julian centuries since J2000
}
public final double calculateJulianDayNumberFromJd(final double julianDay) {
return julianDay - Constants.JULIAN_DAY_AT_01_01_2000; // days since equinox J2000.0
}
/**
* days since Jan 1, 2000 + 2451545
* @param date
* @return
*/
public final double calculateJulianDate(final Date date) {
final long differenceMs = date.getTime() - new Date(MS_2000).getTime(); //milliseconds since 2000-01-01 00:00:00
final double daysSince2000 = differenceMs / Double.valueOf(MS_PER_DAY);
return Math.floor(daysSince2000 + Constants.JULIAN_DAY_AT_01_01_2000);
}
public final double calculateStarTimeHours(final double julianCenturies, final double decimalHours) {
return STARTIME_CONSTANT_1
+ (STARTIME_CONSTANT_2 * julianCenturies)
+ (STARTIME_CONSTANT_3 * decimalHours);
}
public final double convertHoursToDegree(final double starTimeHours) {
return starTimeHours * Constants.DEGREES_PER_HOUR;
}
public final double getDecimalHours(final Date date) {
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
final double hours = Double.valueOf(dateString.substring(11, 13));
final double minutes = Double.valueOf(dateString.substring(14, 16));
final double seconds = Double.valueOf(dateString.substring(17, 19));
final double decimalHours = hours + (minutes / Constants.SECONDS_PER_MINUTE) + (seconds / SECONDS_PER_HOUR);
return decimalHours;
}
public final int getYear(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Year.getFrom(), DateTimeRange.Year.getTo()));
}
public final int getMonth(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Month.getFrom(), DateTimeRange.Month.getTo()));
}
public final int getDay(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Days.getFrom(), DateTimeRange.Days.getTo()));
}
public final int getHours(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Hours.getFrom(), DateTimeRange.Hours.getTo()));
}
public final int getMinutes(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Minutes.getFrom(), DateTimeRange.Minutes.getTo()));
}
public final int getSeconds(final Date date) {
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Seconds.getFrom(), DateTimeRange.Seconds.getTo()));
}
public final double getLocalSiderealDegrees(final double siderealDegrees, final double longitude) {
return clampResult((siderealDegrees % Constants.DEGREES_IN_CIRCLE) + longitude);
}
private double clampResult(final double result) {
if (result < 0D) {
return result + Constants.DEGREES_IN_CIRCLE;
} else {
return result;
}
}
/**
* http://en.wikipedia.org/wiki/Leap_year#Algorithm
* @param year
* @return
*/
public static final boolean isLeapYear(final int year) {
if (year % LEAP_YEAR_CONSTANT_4 == 0) {
if (year % LEAP_YEAR_CONSTANT_100 == 0) {
return (year % LEAP_YEAR_CONSTANT_400 == 0);
} else {
return true;
}
} else {
return false;
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package astrochart.client.view;
import astrochart.client.presenter.AdminPresenter;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
public class AdminView extends Composite implements AdminPresenter.Display {
private final FlexTable contentTable;
private final Button submitButton = new Button("Submit");
private final TextArea inputTextArea = new TextArea();
private final Label statusLabel = new Label();
private final Label secondStatusLabel = new Label();
public AdminView() {
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
contentTableDecorator.setWidth("1010px");
initWidget(contentTableDecorator);
contentTable = new FlexTable();
contentTable.setWidget(0, 0, submitButton);
inputTextArea.setWidth("997px");
inputTextArea.setHeight("500px");
contentTable.setWidget(1, 0, inputTextArea);
contentTable.setWidget(2, 0, statusLabel);
contentTable.setWidget(3, 0, secondStatusLabel);
contentTableDecorator.add(contentTable);
}
@Override
public final Widget asWidget() {
return this;
}
@Override
public final Button getSubmitButton() {
return submitButton;
}
@Override
public final TextArea getInputTextArea() {
return inputTextArea;
}
@Override
public final Label getStatusLabel() {
return statusLabel;
}
@Override
public final Label getSecondStatusLabel() {
return secondStatusLabel;
}
}
+409
View File
@@ -0,0 +1,409 @@
package astrochart.client.view;
import java.util.HashMap;
import java.util.Map;
import astrochart.client.presenter.ChartPresenter;
import astrochart.client.util.DateTimeUtil;
import astrochart.client.widgets.Chart;
import astrochart.client.widgets.TimeEntry;
import astrochart.shared.enums.AspectType;
import astrochart.shared.enums.HouseType;
import astrochart.shared.enums.Planet;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class ChartView extends Composite implements ChartPresenter.Display {
private final FlexTable contentTable = new FlexTable();
private final Button updatePositionsButton = new Button("Update Positions");
private final Button regenerateChartButton = new Button("Regenerate Chart");
private final TextBox locationTextBox = new TextBox();
private final Button submitCityButton = new Button("Get");
private final Label latitudeLabel = new Label("Latitude: ");
private final TextBox latitudeTextBox = new TextBox();
private final Button submitLatitudeButton = new Button("Set");
private final Label longitudeLabel = new Label("Longitude: ");
private final TextBox longitudeTextBox = new TextBox();
private final Button submitLongitudeButton = new Button("Set");
private final Label utcLabel = new Label();
private final Label utcJdLabel = new Label();
private final Label utcSidLabel = new Label();
private final ListBox housesListBox = new ListBox();
private final Label sunriseLabel = new Label();
private final Label sunsetLabel = new Label();
private final Label sunPositionLabel = new Label();
private final Label ascendentLabel = new Label();
private final Label statusLabel = new Label();
private final Map<Planet, CheckBox> planetCheckBoxes = new HashMap<Planet, CheckBox>();
private final Map<Planet, Label> planetLabels = new HashMap<Planet, Label>();
private final Button selectAllPlanetsButton = new Button("Select All");
private final Button unselectAllPlanetsButton = new Button("Unselect All");
private final Map<AspectType, CheckBox> aspectCheckBoxes = new HashMap<AspectType, CheckBox>();
private final Map<AspectType, Label> aspectLabels = new HashMap<AspectType, Label>();
private final Map<AspectType, ListBox> aspectListboxes = new HashMap<AspectType, ListBox>();
private final Button selectAllAspectsButton = new Button("Select All");
private final Button unselectAllAspectsButton = new Button("Unselect All");
private final Button resetOrbsButton = new Button("Reset Orbs");
private final TimeEntry timeEntry;
private final Chart chart;
private int row;
public ChartView(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil) {
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
contentTableDecorator.setWidth("1010px");
initWidget(contentTableDecorator);
row = 0;
final HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.setSpacing(5);
buttonPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
final HorizontalPanel locPanel = new HorizontalPanel();
locPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
locationTextBox.setText("unknown");
locationTextBox.setWidth("240px");
locPanel.add(new Label("Location: "));
locPanel.add(locationTextBox);
locPanel.add(submitCityButton);
buttonPanel.add(locPanel);
final HorizontalPanel latPanel = new HorizontalPanel();
latPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
latitudeTextBox.setText("0.0000000");
latitudeTextBox.setWidth("80px");
latPanel.add(latitudeLabel);
latPanel.add(latitudeTextBox);
latPanel.add(submitLatitudeButton);
buttonPanel.add(latPanel);
final HorizontalPanel longPanel = new HorizontalPanel();
longPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
longitudeTextBox.setText("0.0000000");
longitudeTextBox.setWidth("80px");
longPanel.add(longitudeLabel);
longPanel.add(longitudeTextBox);
longPanel.add(submitLongitudeButton);
buttonPanel.add(longPanel);
buttonPanel.add(updatePositionsButton);
buttonPanel.add(regenerateChartButton);
contentTable.setWidget(row, 0, buttonPanel);
contentTable.getFlexCellFormatter().setColSpan(row, 0, 3);
row++;
timeEntry = new TimeEntry(eventBus, dateTimeUtil);
final VerticalPanel chartPanel = new VerticalPanel();
chartPanel.add(timeEntry);
chart = new Chart(eventBus, planetCheckBoxes, aspectListboxes, aspectCheckBoxes, aspectLabels);
chartPanel.add(chart);
contentTable.setWidget(row, 0, chartPanel);
contentTable.setText(row, 1, "UTC Time: ");
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_MIDDLE);
contentTable.setWidget(row, 2, utcLabel);
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_MIDDLE);
row++;
addRow("UTC JD Time: ", utcJdLabel);
addRow("UTC Sidereal Time: ", utcSidLabel);
contentTable.setWidget(row, 0, new HTML("&nbsp;"));
row++;
for (final Planet planet : Planet.values()) {
final HorizontalPanel pan = new HorizontalPanel();
final CheckBox planetCheckBox = new CheckBox();
if (planet.isBody() && !planet.isOuter()) {
planetCheckBox.setValue(true);
}
planetCheckBoxes.put(planet, planetCheckBox);
final Label planetLabel = new Label();
planetLabels.put(planet, planetLabel);
pan.add(planetCheckBox);
pan.add(new Label(planet.getUnicode() + " " + planet.name() + ": "));
addWidgetRow(pan, planetLabel);
}
final HorizontalPanel planetButtonPan = new HorizontalPanel();
planetButtonPan.add(selectAllPlanetsButton);
planetButtonPan.add(unselectAllPlanetsButton);
contentTable.setWidget(row, 0, planetButtonPan);
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
row++;
contentTable.setWidget(row, 0, new HTML("&nbsp;"));
row++;
for (final HouseType houseType : HouseType.values()) {
housesListBox.addItem(houseType.getName());
}
contentTable.setText(row, 0, "Houses System: ");
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_MIDDLE);
contentTable.setWidget(row, 1, housesListBox);
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_MIDDLE);
row++;
contentTable.setWidget(row, 0, new HTML("&nbsp;"));
row++;
final FlexTable aspectFlex = new FlexTable();
aspectFlex.setText(0, 0, "Aspect");
aspectFlex.setText(0, 1, "Counter");
aspectFlex.setText(0, 2, "Orb");
int aspectRow = 1;
for (final AspectType aspectType : AspectType.values()) {
final HorizontalPanel pan = new HorizontalPanel();
final CheckBox aspectCheckBox = new CheckBox();
aspectCheckBox.setValue(true);
aspectCheckBoxes.put(aspectType, aspectCheckBox);
pan.add(aspectCheckBox);
pan.add(new Label(aspectType.getUnicode() + " " + aspectType.name() + "s: "));
aspectFlex.setWidget(aspectRow, 0, pan);
final Label aspectLabel = new Label();
aspectLabel.setText("0");
aspectLabels.put(aspectType, aspectLabel);
aspectFlex.setWidget(aspectRow, 1, aspectLabel);
final ListBox listBox = new ListBox();
listBox.setWidth("70px");
for (final double orb : aspectType.getOrbs()) {
listBox.addItem(String.valueOf(orb));
}
aspectListboxes.put(aspectType, listBox);
aspectFlex.setWidget(aspectRow, 2, listBox);
aspectRow++;
}
resetOrbs();
contentTable.setWidget(row, 0, aspectFlex);
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
row++;
final HorizontalPanel aspectButtonPan = new HorizontalPanel();
aspectButtonPan.add(selectAllAspectsButton);
aspectButtonPan.add(unselectAllAspectsButton);
aspectButtonPan.add(resetOrbsButton);
contentTable.setWidget(row, 0, aspectButtonPan);
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
row++;
contentTable.setWidget(row, 0, new HTML("&nbsp;"));
row++;
addRow("Sunrise Time: ", sunriseLabel);
addRow("Sunset Time: ", sunsetLabel);
addRow("Sun Position: ", sunPositionLabel);
addRow("Tropical Ascendent: ", ascendentLabel);
contentTable.setWidget(row, 0, statusLabel);
contentTable.getFlexCellFormatter().setColSpan(row, 0, 3);
contentTable.getFlexCellFormatter().setRowSpan(1, 0, row - 1); // chart
contentTableDecorator.add(contentTable);
}
private void addRow(final String label, final Widget widget) {
contentTable.setText(row, 0, label);
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
contentTable.setWidget(row, 1, widget);
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
row++;
}
private void addWidgetRow(final Widget first, final Widget second) {
contentTable.setWidget(row, 0, first);
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
contentTable.setWidget(row, 1, second);
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
row++;
}
@SuppressWarnings("unused")
private void addRow(final String label, final Widget firstWidget, final Widget secondWidget) {
contentTable.setText(row, 0, label);
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
contentTable.setWidget(row, 1, firstWidget);
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
contentTable.setWidget(row, 2, secondWidget);
contentTable.getCellFormatter().setVerticalAlignment(row, 2, HasVerticalAlignment.ALIGN_TOP);
row++;
}
@Override
public final Widget asWidget() {
return this;
}
@Override
public final Button getUpdatePositionsButton() {
return updatePositionsButton;
}
@Override
public final Button getRegenerateChartButton() {
return regenerateChartButton;
}
@Override
public final Label getUtcLabel() {
return utcLabel;
}
@Override
public final Label getUtcJdLabel() {
return utcJdLabel;
}
@Override
public final Label getUtcSidLabel() {
return utcSidLabel;
}
@Override
public final Chart getChart() {
return chart;
}
@Override
public final CheckBox getPlanetCheckBox(final Planet planet) {
return planetCheckBoxes.get(planet);
}
@Override
public final Label getPlanetLabel(final Planet planet) {
return planetLabels.get(planet);
}
@Override
public final Button getSelectAllPlanetsButton() {
return selectAllPlanetsButton;
}
@Override
public final Button getUnselectAllPlanetsButton() {
return unselectAllPlanetsButton;
}
@Override
public final ListBox getHousesListBox() {
return housesListBox;
}
@Override
public final CheckBox getAspectCheckBox(final AspectType type) {
return aspectCheckBoxes.get(type);
}
@Override
public final ListBox getAspectListBox(final AspectType type) {
return aspectListboxes.get(type);
}
@Override
public final Label getAspectLabel(final AspectType type) {
return aspectLabels.get(type);
}
@Override
public final void resetAspects() {
for (final AspectType aspectType : AspectType.values()) {
getAspectLabel(aspectType).setText("0");
}
}
@Override
public final Button resetOrbsButton() {
return resetOrbsButton;
}
@Override
public final Button getUnselectAllAspectsButton() {
return unselectAllAspectsButton;
}
@Override
public final Button getSelectAllAspectsButton() {
return selectAllAspectsButton;
}
@Override
public final void resetOrbs() {
for (final AspectType aspectType : AspectType.values()) {
int index = 0;
for (final double orb : aspectType.getOrbs()) {
if (orb == aspectType.getDefaultOrb()) {
getAspectListBox(aspectType).setItemSelected(index, true);
}
index++;
}
}
}
@Override
public final TextBox getLocationTextBox() {
return locationTextBox;
}
@Override
public final Button getSubmitCityButton() {
return submitCityButton;
}
@Override
public final TextBox getLatitudeTextBox() {
return latitudeTextBox;
}
@Override
public final Button getSubmitLatitudeButton() {
return submitLatitudeButton;
}
@Override
public final TextBox getLongitudeTextBox() {
return longitudeTextBox;
}
@Override
public final Button getSubmitLongitudeButton() {
return submitLongitudeButton;
}
@Override
public final Label getSunriseLabel() {
return sunriseLabel;
}
@Override
public final Label getSunsetLabel() {
return sunsetLabel;
}
@Override
public final Label getSunPositionLabel() {
return sunPositionLabel;
}
@Override
public final Label getAscendentLabel() {
return ascendentLabel;
}
@Override
public final Label getStatusLabel() {
return statusLabel;
}
@Override
public final TimeEntry getTimeEntry() {
return timeEntry;
}
}
+33
View File
@@ -0,0 +1,33 @@
package astrochart.client.view;
import astrochart.client.presenter.InfoPresenter;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;
public class InfoView extends Composite implements InfoPresenter.Display {
private final FlexTable contentTable;
private final FlexTable infoList = new FlexTable();
public InfoView() {
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
contentTableDecorator.setWidth("1010px");
initWidget(contentTableDecorator);
contentTable = new FlexTable();
infoList.setWidth("987px");
contentTable.setWidget(0, 0, infoList);
contentTableDecorator.add(contentTable);
}
@Override
public final Widget asWidget() {
return this;
}
@Override
public final FlexTable getInfoList() {
return infoList;
}
}
+393
View File
@@ -0,0 +1,393 @@
package astrochart.client.widgets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import astrochart.client.event.ResetAspectsEvent;
import astrochart.client.event.SetStatusEvent;
import astrochart.shared.data.Epoch;
import astrochart.shared.enums.AspectType;
import astrochart.shared.enums.ChartColor;
import astrochart.shared.enums.ChartProportions;
import astrochart.shared.enums.HouseType;
import astrochart.shared.enums.Planet;
import astrochart.shared.enums.ZodiacSign;
import astrochart.shared.wrappers.AscendentAndOffset;
import astrochart.shared.wrappers.TextPosition;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class Chart extends Composite {
private static final int CANVAS_WIDTH = 600;
private static final int CANVAS_HEIGHT = 600;
private static final int TEXT_SIZE_LARGER = 12;
private static final int TEXT_SIZE_LARGE = 8;
private static final double LINE_WIDTH_LIGHT = 0.8;
private static final double LINE_WIDTH_LIGHTER = 0.75D;
private static final double LINE_WIDTH_ALMOSTSUPERLIGHT = 0.40;
private static final double LINE_WIDTH_SUPERLIGHT = 0.20;
private static final double LINE_WIDTH_HYPERLIGHT = 0.10;
private static final int Y_OFFSET = 18;
private static final int X_OFFSET = 23;
private static final double FULL_CIRCLE = 360D;
private static final double RIGHT_ANGLE = 90D;
private static final double DEGREES_PER_SIGN = 30D;
private static final double DEGREES_PER_HALF_SIGN = DEGREES_PER_SIGN / 2;
private final HandlerManager eventBus;
private final Map<Planet, CheckBox> planetCheckBoxes;
private final Map<AspectType, ListBox> aspectListboxes;
private final Map<AspectType, CheckBox> aspectCheckBoxes;
private final Map<AspectType, Label> aspectLabels;
private final VerticalPanel chartPanel = new VerticalPanel();
private final Canvas canvas = Canvas.createIfSupported();
private AscendentAndOffset ascendent;
private Epoch epoch;
@SuppressWarnings("unused")
private HouseType houseType;
private final Map<String, TextPosition> aspects = new HashMap<String, TextPosition>();
public Chart(final HandlerManager eventBus, final Map<Planet, CheckBox> planetCheckBoxes, final Map<AspectType, ListBox> aspectListboxes,
final Map<AspectType, CheckBox> aspectCheckBoxes, final Map<AspectType, Label> aspectLabels) {
this.eventBus = eventBus;
this.planetCheckBoxes = planetCheckBoxes;
this.aspectListboxes = aspectListboxes;
this.aspectCheckBoxes = aspectCheckBoxes;
this.aspectLabels = aspectLabels;
if (canvas != null) {
canvas.setCoordinateSpaceWidth(CANVAS_WIDTH);
canvas.setCoordinateSpaceHeight(CANVAS_HEIGHT);
chartPanel.add(canvas);
} else {
chartPanel.add(new Label("Fail: Your browser doesn't support HTML5 Canvas."));
}
initWidget(chartPanel);
setStyleName("chart");
}
@SuppressWarnings("unused")
private void generateEmptyChart() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
generateChart(new AscendentAndOffset(ZodiacSign.Aries, 0.0D, ((FULL_CIRCLE * 3) / 4)), null, HouseType.Equal);
}
});
}
public final void generateChart(final AscendentAndOffset ascendent, final Epoch epoch, final HouseType houseType) {
this.ascendent = ascendent;
this.epoch = epoch;
this.houseType = houseType;
final Context2d ctx = canvas.getContext2d();
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
ctx.setFont("10pt Arial");
ctx.fillRect(0, 0, canvas.getOffsetWidth(), canvas.getOffsetHeight()); //clear ctx
final double offset = ascendent.getOffset() + ascendent.getAscendent().getEclipticLongitude();
ctx.setLineWidth(1D);
markFiveDegrees(ctx, offset);
markDegrees(ctx, offset);
drawAscendentLine(
getXCenter(),
getYCenter(),
ChartProportions.getRadius(getHcs(), ChartProportions.Inner),
ascendent);
ctx.setLineWidth(2D);
drawArc(getXCenter(),
getYCenter(),
ChartProportions.getRadius(getHcs(), ChartProportions.Inner),
0D,
FULL_CIRCLE,
false);
//put zodiac
ctx.setFont("36pt Arial");
for (final ZodiacSign sign : ZodiacSign.values()) {
final double angle = keepInRange(sign.getEclipticLongitude() + RIGHT_ANGLE - offset);
//draw colored section
ctx.beginPath();
ctx.setFillStyle(CssColor.make(sign.getColor().getHex()));
final double start = Math.toRadians((sign.getEclipticLongitude() * -1) + (FULL_CIRCLE / 2) - DEGREES_PER_SIGN + offset);
final double end = Math.toRadians((sign.getEclipticLongitude() * -1) + (FULL_CIRCLE / 2) + offset);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterEclyptic), start, end, false);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerEclyptic), end, start, true);
ctx.fill();
ctx.stroke();
ctx.closePath();
//draw Signs
final double xSign = getHcs()
- (Math.sin(Math.toRadians(angle + DEGREES_PER_HALF_SIGN))
* ChartProportions.getRadius(getHcs(), ChartProportions.EclypticCenter)) - X_OFFSET;
final double ySign = getHcs()
- (Math.cos(Math.toRadians(angle + DEGREES_PER_HALF_SIGN))
* ChartProportions.getRadius(getHcs(), ChartProportions.EclypticCenter)) + Y_OFFSET;
ctx.beginPath();
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
ctx.fillText(String.valueOf(sign.getUnicode()), xSign, ySign);
ctx.strokeText(String.valueOf(sign.getUnicode()), xSign, ySign);
ctx.closePath();
}
//draw houses
int house = 1;
if (houseType.equals(HouseType.Equal) || houseType.equals(HouseType.WholeSigns)) {
for (final ZodiacSign sign : ZodiacSign.values()) {
double angle = keepInRange(sign.getEclipticLongitude() + RIGHT_ANGLE);
if (houseType.equals(HouseType.WholeSigns)) {
angle = angle - (offset % DEGREES_PER_SIGN);
}
ctx.setLineWidth(LINE_WIDTH_HYPERLIGHT);
drawExcentricLine(ctx, angle, ChartProportions.Inner, ChartProportions.InnerMark);
drawExcentricLine(ctx, angle, ChartProportions.OuterEclyptic, ChartProportions.Outer);
ctx.setLineWidth(LINE_WIDTH_LIGHT);
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, String.valueOf(house), angle + DEGREES_PER_HALF_SIGN, ChartProportions.HouseNumber);
house++;
}
}
if (epoch != null) {
//place planet information
ctx.setLineWidth(LINE_WIDTH_LIGHTER);
for (final Planet planet : Planet.values()) {
if (planetCheckBoxes.get(planet).getValue()) {
final ZodiacSign sign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(planet));
final double degrees = epoch.getPreciseDegrees(planet) + sign.getEclipticLongitude();
final double angle = keepInRange(degrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
drawExcentricLine(ctx, angle, ChartProportions.PlanetMark, ChartProportions.InnerMark); //draw outer planet mark
writeExcentricInfo(ctx, TEXT_SIZE_LARGER, String.valueOf(planet.getUnicode()), angle, ChartProportions.PlanetSign);
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, epoch.getDegrees(planet) + String.valueOf('\u00B0'), angle, ChartProportions.Degree);
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, epoch.getMinutes(planet) + String.valueOf('\u2032'), angle, ChartProportions.Minute);
drawExcentricLine(ctx, angle, ChartProportions.Inner, ChartProportions.InnerLine); //draw inner planet mark
}
}
/*
//mark midheaven
System.out.println("MC: " + ascendent.getMidheaven());
final double angle = keepInRange(ascendent.getMidheaven());
drawExcentricLine(ctx, angle, ChartProportions.PlanetMark, ChartProportions.InnerMark); //draw outer mark
writeExcentricInfo(ctx, 12, "MC", angle, ChartProportions.PlanetSign);
drawExcentricLine(ctx, angle, ChartProportions.Degree, ChartProportions.Inner); //draw inner mark
*/
//draw aspects
eventBus.fireEvent(new ResetAspectsEvent());
aspects.clear();
for (final Planet firstPlanet : Planet.values()) {
if (planetCheckBoxes.get(firstPlanet).getValue()) {
for (final Planet secondPlanet : Planet.values()) {
if (planetCheckBoxes.get(secondPlanet).getValue()) {
drawAspectLine(ctx, firstPlanet, secondPlanet, offset);
}
}
}
}
//write aspect labels
ctx.setFont("12pt Arial");
final Iterator<Entry<String, TextPosition>> it = aspects.entrySet().iterator();
while (it.hasNext()) {
final Entry<String, TextPosition> entry = it.next();
if (entry.getValue() != null) {
final TextPosition tp = entry.getValue();
ctx.setLineWidth(LINE_WIDTH_ALMOSTSUPERLIGHT);
ctx.fillRect(tp.getX() - 1D, tp.getY() - DEGREES_PER_HALF_SIGN - 3, DEGREES_PER_HALF_SIGN - 1, DEGREES_PER_HALF_SIGN);
ctx.strokeRect(tp.getX() - 1D, tp.getY() - DEGREES_PER_HALF_SIGN - 3, DEGREES_PER_HALF_SIGN - 1, DEGREES_PER_HALF_SIGN);
ctx.setLineWidth(1D);
ctx.strokeText(tp.getText(), tp.getX(), tp.getY());
it.remove(); // avoids a ConcurrentModificationException
}
}
}
eventBus.fireEvent(new SetStatusEvent("Ready."));
}
private void drawAspectLine(final Context2d ctx, final Planet firstPlanet, final Planet secondPlanet, final double offset) {
if (firstPlanet.equals(secondPlanet)
|| aspects.containsKey(secondPlanet.name() + ":" + firstPlanet.name())) {
return; //aspect already placed
}
final ZodiacSign firstSign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(firstPlanet));
final double firstDegrees = epoch.getPreciseDegrees(firstPlanet) + firstSign.getEclipticLongitude();
final double firstAngle = keepInRange(firstDegrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
final ZodiacSign secondSign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(secondPlanet));
final double secondDegrees = epoch.getPreciseDegrees(secondPlanet) + secondSign.getEclipticLongitude();
final double secondAngle = keepInRange(secondDegrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
final double xFirst = getHcs()
- (Math.sin(Math.toRadians(firstAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
final double yFirst = getHcs()
- (Math.cos(Math.toRadians(firstAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
final double xSecond = getHcs()
- (Math.sin(Math.toRadians(secondAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
final double ySecond = getHcs()
- (Math.cos(Math.toRadians(secondAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
double difference = firstAngle - secondAngle;
if (difference < 0D) {
difference = difference * -1D;
}
AspectType isType = null;
for (final AspectType type : AspectType.values()) {
if (difference <= type.getAngle() + getAspectOrb(type)
&& difference >= type.getAngle() - getAspectOrb(type)) {
isType = type;
break;
}
}
TextPosition tp = null;
if (isType != null) {
addAspect(isType);
if (aspectCheckBoxes.get(isType).getValue()) {
ctx.setLineWidth(2.0D); //Labeled aspects with type
drawLine(xFirst, yFirst, xSecond, ySecond);
final double x = ((xFirst + xSecond) / 2D) - 6D;
final double y = ((yFirst + ySecond) / 2D) + 6D;
tp = new TextPosition(String.valueOf(isType.getUnicode()), x, y);
} else {
ctx.setLineWidth(1.0D); //Unlabeled Aspects with type
drawLine(xFirst, yFirst, xSecond, ySecond);
}
} else {
ctx.setLineWidth(LINE_WIDTH_SUPERLIGHT); //Apsects without type
drawLine(xFirst, yFirst, xSecond, ySecond);
}
aspects.put(firstPlanet.name() + ":" + secondPlanet.name(), tp);
}
private void drawExcentricLine(final Context2d ctx, final double angle, final ChartProportions from, final ChartProportions to) {
final double xFrom = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), from));
final double yFrom = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), from));
final double xTo = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), to));
final double yTo = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), to));
drawLine(xFrom, yFrom, xTo, yTo);
}
private void writeExcentricInfo(final Context2d ctx, final int textSize, final String text, final double angle, final ChartProportions prop) {
ctx.setFont(textSize + "pt Arial");
final double xMinute = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), prop)) - (textSize / 2);
final double yMinute = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), prop)) + (textSize / 2);
ctx.strokeText(text, xMinute, yMinute);
}
private void markFiveDegrees(final Context2d ctx, final double offset) {
for (int angle = 0; angle < FULL_CIRCLE; angle = angle + 5) {
ctx.beginPath();
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
final double start = Math.toRadians(angle + offset);
final double end = Math.toRadians(angle + offset + 5D);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerEclyptic), start, end, false);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterMark), end, start, true);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
private void markDegrees(final Context2d ctx, final double offset) {
for (int angle = 0; angle < FULL_CIRCLE; angle++) {
ctx.beginPath();
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
final double start = Math.toRadians(angle + offset);
final double end = Math.toRadians(angle + offset + 1D);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterMark), start, end, false);
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark), end, start, true);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
/**
* returns the half size of the chart
* @return
*/
private int getHcs() {
if (getXCenter() >= getYCenter()) {
return getXCenter();
} else {
return getYCenter();
}
}
private int getXCenter() {
return canvas.getOffsetWidth() / 2;
}
private int getYCenter() {
return canvas.getOffsetHeight() / 2;
}
private double keepInRange(final double angle) {
double result = angle;
while (result < 0D) {
result = result + FULL_CIRCLE;
}
result = result % FULL_CIRCLE;
return result;
}
private void drawArc(final int x, final int y, final int r,
final double startAngle, final double endAngle, final boolean antiClock) {
canvas.getContext2d().beginPath();
final double start = Math.toRadians(startAngle - RIGHT_ANGLE);
final double end = Math.toRadians(endAngle - RIGHT_ANGLE);
canvas.getContext2d().arc(x, y, r, start, end, antiClock);
canvas.getContext2d().fill();
canvas.getContext2d().stroke();
canvas.getContext2d().closePath();
}
private void drawAscendentLine(final int xCenter, final int yCenter, final int innerRadius,
final AscendentAndOffset asc) {
drawLine(xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.Inner), yCenter,
xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark), yCenter);
final String text = "ASC " + asc.getAscendent().getUnicode() + " " + asc.getFormattedOffset();
canvas.getContext2d().strokeText(text, xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark) + 5D, yCenter - 5D);
}
private void drawLine(final double startX, final double startY, final double endX, final double endY) {
canvas.getContext2d().beginPath();
canvas.getContext2d().moveTo(startX, startY);
canvas.getContext2d().lineTo(endX, endY);
canvas.getContext2d().closePath();
canvas.getContext2d().stroke();
}
private double getAspectOrb(final AspectType type) {
final ListBox box = aspectListboxes.get(type);
final int selection = box.getSelectedIndex();
return Double.valueOf(box.getItemText(selection));
}
private void addAspect(final AspectType aspectType) {
final Label label = aspectLabels.get(aspectType);
int counter = Integer.parseInt(label.getText());
counter++;
label.setText(String.valueOf(counter));
}
public final void changeHouseSystem(final HouseType houseType) {
this.houseType = houseType;
generateChart(ascendent, epoch, houseType);
}
}
+259
View File
@@ -0,0 +1,259 @@
package astrochart.client.widgets;
import java.util.Date;
import astrochart.client.event.DateUpdatedEvent;
import astrochart.client.util.Constants;
import astrochart.client.util.DateTimeUtil;
import astrochart.shared.enums.time.Month;
import astrochart.shared.enums.time.TimeZone;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
public class TimeEntry extends Composite {
private static final int HIGHER_BOUNDARY = 2100;
private static final int LOWER_BOUNDARY = 1900;
private final HandlerManager eventBus;
private final DateTimeUtil dateTimeUtil;
private final FlexTable flex = new FlexTable();
private final TextBox yearTextBox = new TextBox();
private final ListBox monthListBox = new ListBox();
private final TextBox dayTextBox = new TextBox();
private final TextBox hoursTextBox = new TextBox();
private final TextBox minutesTextBox = new TextBox();
private final TextBox secondsTextBox = new TextBox();
private final ListBox timeZoneListBox = new ListBox();
private final Button updateButton = new Button("Enter");
private final Label statusLabel = new Label(String.valueOf('\u00A0')); // NBSP
private final DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss");
private int clientOffset;
private Date localDate; // local date of the client, not the ListBox
private enum Column {
Year(0),
Month(1),
Day(2),
Hours(3),
Minutes(4),
Seconds(5),
Timezone(6),
Action(7);
private int number;
Column(final int number) {
this.number = number;
}
public int getNumber() {
return number;
}
};
public TimeEntry(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil) {
this.eventBus = eventBus;
this.dateTimeUtil = dateTimeUtil;
localDate = new Date();
for (final Column column : Column.values()) {
flex.setText(0, column.getNumber(), column.name());
}
yearTextBox.setWidth("50px");
flex.setWidget(1, Column.Year.getNumber(), yearTextBox);
for (final Month month : Month.values()) {
monthListBox.addItem(month.name());
}
flex.setWidget(1, Column.Month.getNumber(), monthListBox);
dayTextBox.setWidth("50px");
flex.setWidget(1, Column.Day.getNumber(), dayTextBox);
hoursTextBox.setWidth("50px");
flex.setWidget(1, Column.Hours.getNumber(), hoursTextBox);
minutesTextBox.setWidth("50px");
flex.setWidget(1, Column.Minutes.getNumber(), minutesTextBox);
secondsTextBox.setWidth("50px");
flex.setWidget(1, Column.Seconds.getNumber(), secondsTextBox);
for (final TimeZone zone : TimeZone.values()) {
timeZoneListBox.addItem(zone.getName());
}
flex.setWidget(1, Column.Timezone.getNumber(), timeZoneListBox);
updateButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
updateDate();
}
});
flex.setWidget(1, Column.Action.getNumber(), updateButton);
flex.setWidget(2, 0, statusLabel);
flex.getFlexCellFormatter().setColSpan(2, 0, Column.values().length + 1);
updateValues();
updateDate();
initWidget(flex);
setStyleName("time-entry");
}
private void updateValues() {
yearTextBox.setText(String.valueOf(dateTimeUtil.getYear(localDate)));
int monthListIndex = 0;
for (final Month month : Month.values()) {
if (dateTimeUtil.getMonth(localDate) == month.getNumber()) {
monthListBox.setSelectedIndex(monthListIndex);
}
monthListIndex++;
}
dayTextBox.setText(String.valueOf(dateTimeUtil.getDay(localDate)));
hoursTextBox.setText(String.valueOf(dateTimeUtil.getHours(localDate)));
minutesTextBox.setText(String.valueOf(dateTimeUtil.getMinutes(localDate)));
secondsTextBox.setText(String.valueOf(dateTimeUtil.getSeconds(localDate)));
final double timeZoneOffset = DOM.getElementById("timeZone").getPropertyDouble("value");
int zoneListIndex = 0;
for (final TimeZone zone : TimeZone.values()) {
if (Double.valueOf(timeZoneOffset * Constants.SECONDS_PER_MINUTE).intValue() == zone.getUtcOffsetMinutes()) {
clientOffset = Double.valueOf(timeZoneOffset * Constants.SECONDS_PER_MINUTE).intValue();
timeZoneListBox.setSelectedIndex(zoneListIndex);
}
zoneListIndex++;
}
}
private void updateDate() {
// "yyyy.MM.dd HH:mm:ss"
statusLabel.setText(String.valueOf('\u00A0'));
try {
final StringBuilder dateString = new StringBuilder();
validateYear();
dateString.append(yearTextBox.getText());
dateString.append(".");
final Month month = Month.valueOf(monthListBox.getValue(monthListBox.getSelectedIndex()));
dateString.append(formatToTwoDigits(String.valueOf(month.getNumber())));
dateString.append(".");
validateDay();
dateString.append(formatToTwoDigits(dayTextBox.getText()));
dateString.append(" ");
validateHours();
dateString.append(formatToTwoDigits(hoursTextBox.getText()));
dateString.append(":");
validateMinutes();
dateString.append(formatToTwoDigits(minutesTextBox.getText()));
dateString.append(":");
validateSeconds();
dateString.append(formatToTwoDigits(secondsTextBox.getText()));
final Date tempDate = dateTimeFormat.parse(dateString.toString());
final TimeZone timeZone = TimeZone.getTimeZoneForName(timeZoneListBox.getValue(timeZoneListBox.getSelectedIndex()));
// final com.google.gwt.i18n.client.TimeZone tzUtc =
// com.google.gwt.i18n.client.TimeZone.createTimeZone(0);
// final com.google.gwt.i18n.client.TimeZone tz =
// com.google.gwt.i18n.client.TimeZone.createTimeZone(timeZone.getUtcOffsetMinutes());
final Date boxDate = new Date(tempDate.getTime() - (timeZone.getUtcOffsetMinutes() * Constants.MILLISECONDS_PER_MINUTE));
localDate = new Date(boxDate.getTime() + (clientOffset * Constants.MILLISECONDS_PER_MINUTE));
final StringBuilder status = new StringBuilder();
status.append(dateTimeFormat.format(tempDate));
status.append(" ");
status.append(timeZone.getName());
if (timeZone.getUtcOffsetMinutes() != clientOffset) {
status.append(" --> ");
status.append(dateTimeFormat.format(localDate));
status.append(" UTC+");
status.append(clientOffset / Constants.SECONDS_PER_MINUTE);
}
if (timeZone.getUtcOffsetMinutes() != 0) {
status.append(" --> ");
status.append(dateTimeFormat.format(boxDate));
status.append(" UTC ");
}
statusLabel.setText(status.toString());
eventBus.fireEvent(new DateUpdatedEvent(localDate));
} catch (final IllegalArgumentException iae) {
statusLabel.setText(iae.getMessage());
}
}
private void validateSeconds() {
final int minutes = Integer.valueOf(secondsTextBox.getText());
if (minutes < 0 || minutes > Constants.MINUTES_PER_HOUR - 1) {
secondsTextBox.setFocus(true);
throw new IllegalArgumentException("Seconds are out of range.");
}
}
private void validateMinutes() {
final int minutes = Integer.valueOf(minutesTextBox.getText());
if (minutes < 0 || minutes > Constants.MINUTES_PER_HOUR - 1) {
minutesTextBox.setFocus(true);
throw new IllegalArgumentException("Minutes are out of range.");
}
}
private void validateHours() {
final int hours = Integer.valueOf(hoursTextBox.getText());
if (hours < 0 || hours > Constants.HOURS_PER_DAY - 1) {
hoursTextBox.setFocus(true);
throw new IllegalArgumentException("Hour is out of range.");
}
}
private void validateYear() {
final int year = Integer.valueOf(yearTextBox.getText());
if (year < LOWER_BOUNDARY || year > HIGHER_BOUNDARY) {
yearTextBox.setFocus(true);
throw new IllegalArgumentException("Year is out of range.");
}
}
private void validateDay() {
final int day = Integer.valueOf(dayTextBox.getText());
final Month month = Month.valueOf(monthListBox.getValue(monthListBox.getSelectedIndex()));
if (day < 1 || day > month.getDays()) {
final int year = Integer.valueOf(yearTextBox.getText());
if (day == month.getDays() + 1 && DateTimeUtil.isLeapYear(year) && month.equals(Month.February)) {
dayTextBox.setFocus(true);
throw new IllegalArgumentException("Day is out of range. (" + year + " is a leap year).");
} else {
dayTextBox.setFocus(true);
throw new IllegalArgumentException("Day is out of range.");
}
}
}
private String formatToTwoDigits(final String in) {
if (in.length() == 1) {
return "0" + in;
} else {
return in;
}
}
public final Date getLocalDate() {
return localDate;
}
public final String getClientTimezone() {
return " UTC+" + (clientOffset / Constants.MINUTES_PER_HOUR);
}
public final void updateDate(final Date newUtcDate) {
localDate = newUtcDate;
updateValues();
int zoneListIndex = 0;
for (final TimeZone zone : TimeZone.values()) {
if (zone.getUtcOffsetMinutes() == 0) {
timeZoneListBox.setSelectedIndex(zoneListIndex);
break;
}
zoneListIndex++;
}
updateDate();
}
}