answer stringlengths 17 10.2M |
|---|
package com.dianping.cat;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.dianping.cat.report.alert.RuleConfigTest;
import com.dianping.cat.report.graph.ValueTranslaterTest;
import com.dianping.cat.report.page.cross.CrossReportMergerTest;
import com.dianping.cat.report.page.dependency.DependencyReportMergerTest;
import com.dianping.cat.report.page.event.EventGraphDataTest;
import com.dianping.cat.report.page.event.EventReportFilterTest;
import com.dianping.cat.report.page.metric.MetricReportMergerTest;
import com.dianping.cat.report.page.metric.MetricReportParseTest;
import com.dianping.cat.report.page.problem.ProblemGraphDataTest;
import com.dianping.cat.report.page.problem.ProblemReportMergerTest;
import com.dianping.cat.report.page.state.StateReportMergerTest;
import com.dianping.cat.report.page.system.SystemReportConvertorTest;
import com.dianping.cat.report.page.transaction.PayloadTest;
import com.dianping.cat.report.page.transaction.TransactionGraphDataTest;
import com.dianping.cat.report.page.transaction.TransactionReportFilterTest;
import com.dianping.cat.report.page.web.WebReportConvertorTest;
import com.dianping.cat.report.task.TaskConsumerTest;
import com.dianping.cat.report.task.TaskHelperTest;
import com.dianping.cat.report.alert.AlertReportBuilderTest;
import com.dianping.cat.report.alert.ExtractDataTest;
import com.dianping.cat.report.alert.JudgeTimeTest;
import com.dianping.cat.report.alert.MetricIdAndRuleMappingTest;
import com.dianping.cat.report.alert.TopReportVisitorTest;
import com.dianping.cat.report.alert.UserDefineRuleTest;
import com.dianping.cat.report.task.event.EventDailyGraphMergerTest;
import com.dianping.cat.report.task.event.EventGraphCreatorTest;
import com.dianping.cat.report.task.event.HistoryEventMergerTest;
import com.dianping.cat.report.task.heavy.HeavyReportBuilderTest;
import com.dianping.cat.report.task.metric.AlertConfigTest;
import com.dianping.cat.report.task.problem.ProblemCreateGraphDataTest;
import com.dianping.cat.report.task.problem.ProblemDailyGraphMergerTest;
import com.dianping.cat.report.task.problem.ProblemDailyGraphTest;
import com.dianping.cat.report.task.problem.ProblemGraphCreatorTest;
import com.dianping.cat.report.task.service.ServiceReportMergerTest;
import com.dianping.cat.report.task.storage.HistoryStorageReportMergerTest;
import com.dianping.cat.report.task.system.SystemReportStatisticsTest;
import com.dianping.cat.report.task.transaction.DailyTransactionReportGraphTest;
import com.dianping.cat.report.task.transaction.HistoryTransactionMergerTest;
import com.dianping.cat.report.task.transaction.TransactionDailyGraphMergerTest;
import com.dianping.cat.report.task.transaction.TransactionGraphCreatorTest;
import com.dianping.cat.system.notify.RenderTest;
@RunWith(Suite.class)
@SuiteClasses({
/* .report.graph */
ValueTranslaterTest.class,
/* .report.page.model */
EventReportFilterTest.class,
TransactionReportFilterTest.class,
ProblemReportMergerTest.class,
/* . report.page.transcation */
PayloadTest.class,
/* . report.page.cross */
CrossReportMergerTest.class,
/* graph test */
EventGraphDataTest.class,
ProblemGraphDataTest.class,
TransactionGraphDataTest.class,
/* .report.task */
TaskConsumerTest.class,
TaskHelperTest.class,
HistoryEventMergerTest.class,
HistoryTransactionMergerTest.class,
ProblemCreateGraphDataTest.class,
ProblemGraphCreatorTest.class,
TransactionGraphCreatorTest.class,
EventGraphCreatorTest.class,
EventDailyGraphMergerTest.class,
TransactionDailyGraphMergerTest.class,
ProblemDailyGraphMergerTest.class,
/* alarm .render */
RenderTest.class,
StateReportMergerTest.class,
/* Daily Graph Test */
DailyTransactionReportGraphTest.class,
ProblemDailyGraphTest.class,
/* Metric */
MetricReportParseTest.class,
MetricReportMergerTest.class,
/* Dependency */
DependencyReportMergerTest.class,
MetricReportParseTest.class,
/* service */
ServiceReportMergerTest.class,
HistoryStorageReportMergerTest.class,
AlertConfigTest.class,
HeavyReportBuilderTest.class,
AlertReportBuilderTest.class,
TopReportVisitorTest.class,
RuleConfigTest.class,
AlertConfigTest.class,
SystemReportConvertorTest.class,
WebReportConvertorTest.class,
SystemReportStatisticsTest.class,
MetricIdAndRuleMappingTest.class,
ExtractDataTest.class,
JudgeTimeTest.class })
public class AllTests {
@BeforeClass
public static void setUp() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
Locale.setDefault(Locale.CHINESE);
}
} |
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import org.jdesktop.swingx.action.LinkAction;
/**
* A Renderer/Editor for "Links". <p>
*
* The renderer is configured with a LinkAction<T>.
* It's mostly up to the developer to guarantee that the all
* values which are passed into the getXXRendererComponent(...) are
* compatible with T: she can provide a runtime class to check against.
* If it isn't the renderer will configure the
* action with a null target. <p>
*
* It's recommended to not use the given Action anywhere else in code,
* as it is updated on each getXXRendererComponent() call which might
* lead to undesirable side-effects. <p>
*
* Internally uses JXHyperlink for both CellRenderer and CellEditor
* It's recommended to not reuse the same instance for both functions. <p>
*
* PENDING: make renderer respect selected cell state.
*
* PENDING: TreeCellRenderer has several issues
* - no icons
* - usual background highlighter issues
*
* @author Jeanette Winzenburg
*
* @deprecated as renderer (the editor part is not yet handled),
* use the SwingX DefaultXXRenderer configured with a
* {@link HyperlinkProvider} instead
*/
public class LinkRenderer extends AbstractCellEditor implements
TableCellRenderer, TableCellEditor, ListCellRenderer,
TreeCellRenderer, RolloverRenderer {
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
private JXHyperlink linkButton;
private LinkAction<Object> linkAction;
protected Class<?> targetClass;
/**
* Instantiate a LinkRenderer with null LinkAction and null
* targetClass.
*
*/
public LinkRenderer() {
this(null, null);
}
/**
* Instantiate a LinkRenderer with the LinkAction to use with
* target values.
*
* @param linkAction the action that acts on values.
*/
public LinkRenderer(LinkAction linkAction) {
this(linkAction, null);
}
/**
* Instantiate a LinkRenderer with a LinkAction to use with
* target values and the type of values the action can cope with. <p>
*
* It's up to developers to take care of matching types.
*
* @param linkAction the action that acts on values.
* @param targetClass the type of values the action can handle.
*/
public LinkRenderer(LinkAction linkAction, Class targetClass) {
linkButton = createHyperlink();
linkButton.addActionListener(createEditorActionListener());
setLinkAction(linkAction, targetClass);
}
/**
* Sets the class the action is supposed to handle. <p>
*
* PENDING: make sense to set independently of LinkAction?
*
* @param targetClass the type of values the action can handle.
*/
public void setTargetClass(Class targetClass) {
this.targetClass = targetClass;
}
/**
* Sets the LinkAction for handling the values. <p>
*
* The action is assumed to be able to cope with any type, that is
* this method is equivalent to setLinkAction(linkAction, null).
*
* @param linkAction
*/
public void setLinkAction(LinkAction linkAction) {
setLinkAction(linkAction, null);
}
/**
* Sets the LinkAction for handling the values and the
* class the action can handle. <p>
*
* PENDING: in the general case this is not independent of the
* targetClass. Need api to set them combined?
*
* @param linkAction
*/
public void setLinkAction(LinkAction linkAction, Class targetClass) {
if (linkAction == null) {
linkAction = createDefaultLinkAction();
}
setTargetClass(targetClass);
this.linkAction = linkAction;
linkButton.setAction(linkAction);
}
/**
* decides if the given target is acceptable for setTarget.
* <p>
*
* target == null is acceptable for all types.
* targetClass == null is the same as Object.class
*
* @param target the target to set.
* @return true if setTarget can cope with the object,
* false otherwise.
*
*/
public boolean isTargetable(Object target) {
// we accept everything
if (targetClass == null) return true;
if (target == null) return true;
return targetClass.isAssignableFrom(target.getClass());
}
/**
* creates and returns the hyperlink component used for rendering
* the value and activating the action on the target value.
*
* @return the hyperlink renderer component.
*/
protected JXHyperlink createHyperlink() {
return new JXHyperlink() {
@Override
public void updateUI() {
super.updateUI();
setBorderPainted(true);
setOpaque(true);
}
};
}
/**
* default action - does nothing... except showing the target.
*
* @return a default LinkAction for showing the target.
*/
protected LinkAction createDefaultLinkAction() {
return new LinkAction<Object>(null) {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
}
public boolean isEnabled() {
return true;
}
public void doClick() {
linkButton.doClick();
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if ((value != null) && !isTargetable(value)) {
value = null;
}
linkAction.setTarget(value);
if (list != null) {
Point p = (Point) list
.getClientProperty(RolloverProducer.ROLLOVER_KEY);
if (/*cellHasFocus ||*/ (p != null && (p.y >= 0) && (p.y == index))) {
linkButton.getModel().setRollover(true);
} else {
linkButton.getModel().setRollover(false);
}
updateSelectionColors(list, isSelected);
updateFocusBorder(cellHasFocus);
};
return linkButton;
}
private void updateSelectionColors(JList table, boolean isSelected) {
if (isSelected) {
// linkButton.setForeground(table.getSelectionForeground());
linkButton.setBackground(table.getSelectionBackground());
} else {
// linkButton.setForeground(table.getForeground());
linkButton.setBackground(table.getBackground());
}
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if ((value != null) && !isTargetable(value)) {
value = null;
}
linkAction.setTarget(value);
if (table != null) {
Point p = (Point) table
.getClientProperty(RolloverProducer.ROLLOVER_KEY);
if (/*hasFocus || */(p != null && (p.x >= 0) && (p.x == column) && (p.y == row))) {
linkButton.getModel().setRollover(true);
} else {
linkButton.getModel().setRollover(false);
}
updateSelectionColors(table, isSelected);
updateFocusBorder(hasFocus);
}
return linkButton;
}
private void updateSelectionColors(JTable table, boolean isSelected) {
if (isSelected) {
// linkButton.setForeground(table.getSelectionForeground());
linkButton.setBackground(table.getSelectionBackground());
}
else {
// linkButton.setForeground(table.getForeground());
linkButton.setBackground(table.getBackground());
}
}
private void updateFocusBorder(boolean hasFocus) {
if (hasFocus) {
linkButton.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
} else {
linkButton.setBorder(noFocusBorder);
}
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
linkAction.setTarget(value);
linkButton.getModel().setRollover(true);
updateSelectionColors(table, isSelected);
return linkButton;
}
public Object getCellEditorValue() {
return linkAction.getTarget();
}
@Override
protected void fireEditingStopped() {
fireEditingCanceled();
}
private ActionListener createEditorActionListener() {
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelCellEditing();
}
};
return l;
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
if ((value != null) && !isTargetable(value)) {
value = null;
}
linkAction.setTarget(value);
if (tree != null) {
Point p = (Point) tree
.getClientProperty(RolloverProducer.ROLLOVER_KEY);
if (/*cellHasFocus ||*/ (p != null && (p.y >= 0) && (p.y == row))) {
linkButton.getModel().setRollover(true);
} else {
linkButton.getModel().setRollover(false);
}
updateSelectionColors(tree, isSelected);
updateFocusBorder(hasFocus);
}
return linkButton;
}
private void updateSelectionColors(JTree tree, boolean isSelected) {
if (isSelected) {
// linkButton.setForeground(table.getSelectionForeground());
linkButton.setBackground(UIManager.getColor("Tree.selectionBackground"));
}
else {
// linkButton.setForeground(table.getForeground());
linkButton.setBackground(tree.getBackground());
}
}
} |
package com.opengamma.core.historicaltimeseries.impl;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.time.calendar.LocalDate;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.FudgeMsgEnvelope;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.fudgemsg.FudgeMapWrapper;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.rest.AbstractDataResource;
/**
* RESTful resource for time-series.
* <p>
* The time-series resource receives and processes RESTful calls to the time-series source.
*/
@Path("htsSource")
public class DataHistoricalTimeSeriesSourceResource extends AbstractDataResource {
/**
* The time-series source.
*/
private final HistoricalTimeSeriesSource _htsSource;
/**
* Creates the resource, exposing the underlying source over REST.
*
* @param htsSource the underlying time-series source, not null
*/
public DataHistoricalTimeSeriesSourceResource(final HistoricalTimeSeriesSource htsSource) {
ArgumentChecker.notNull(htsSource, "htsSource");
_htsSource = htsSource;
}
/**
* Gets the time-series source.
*
* @return the time-series source, not null
*/
public HistoricalTimeSeriesSource getHistoricalTimeSeriesSource() {
return _htsSource;
}
@GET
public Response getHateaos(@Context UriInfo uriInfo) {
return hateoasResponse(uriInfo);
}
@GET
@Path("hts/{htsId}")
public Response get(
@PathParam("htsId") String idStr,
@QueryParam("version") String version,
@QueryParam("start") String startStr,
@QueryParam("includeStart") boolean includeStart,
@QueryParam("end") String endStr,
@QueryParam("includeEnd") boolean includeEnd,
@QueryParam("maxPoints") Integer maxPoints) {
final UniqueId uniqueId = ObjectId.parse(idStr).atVersion(version);
final LocalDate start = (startStr != null ? LocalDate.parse(startStr) : null);
final LocalDate end = (endStr != null ? LocalDate.parse(endStr) : null);
final HistoricalTimeSeries result;
if (start == null && end == null && maxPoints == null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(uniqueId);
} else if (maxPoints != null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(uniqueId, start, includeStart, end, includeEnd, maxPoints);
} else {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(uniqueId, start, includeStart, end, includeEnd);
}
return responseOkFudge(result);
}
@GET
@Path("htsMeta/externalIdBundle/{htsId}")
public Response getExternalIdBundle(
@PathParam("htsId") String idStr,
@QueryParam("version") String version) {
final UniqueId uniqueId = ObjectId.parse(idStr).atVersion(version);
final ExternalIdBundle idBundle = getHistoricalTimeSeriesSource().getExternalIdBundle(uniqueId);
return responseOkFudge(idBundle);
}
@GET
@Path("htsSearches/single")
public Response searchSingle(
@QueryParam("id") List<String> idStrs,
@QueryParam("idValidityDate") String idValidityDateStr,
@QueryParam("dataSource") String dataSource,
@QueryParam("dataProvider") String dataProvider,
@QueryParam("dataField") String dataField,
@QueryParam("start") String startStr,
@QueryParam("includeStart") boolean includeStart,
@QueryParam("end") String endStr,
@QueryParam("includeEnd") boolean includeEnd,
@QueryParam("maxPoints") Integer maxPoints) {
final ExternalIdBundle bundle = ExternalIdBundle.parse(idStrs);
final LocalDate start = (startStr != null ? LocalDate.parse(startStr) : null);
final LocalDate end = (endStr != null ? LocalDate.parse(endStr) : null);
final HistoricalTimeSeries result;
if (idValidityDateStr != null) {
final LocalDate idValidityDate = (idValidityDateStr == null || "ALL".equals(idValidityDateStr) ? null : LocalDate.parse(idValidityDateStr));
if (start == null && end == null && maxPoints == null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, idValidityDate, dataSource, dataProvider, dataField);
} else if (maxPoints != null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, idValidityDate, dataSource, dataProvider, dataField, start, includeStart, end, includeEnd, maxPoints);
} else {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, idValidityDate, dataSource, dataProvider, dataField, start, includeStart, end, includeEnd);
}
} else {
if (start == null && end == null && maxPoints == null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, dataSource, dataProvider, dataField);
} else if (maxPoints != null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, dataSource, dataProvider, dataField, start, includeStart, end, includeEnd, maxPoints);
} else {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
bundle, dataSource, dataProvider, dataField, start, includeStart, end, includeEnd);
}
}
return responseOkFudge(result);
}
@GET
@Path("htsSearches/resolve")
public Response searchResolve(
@QueryParam("id") List<String> idStrs,
@QueryParam("idValidityDate") String idValidityDateStr,
@QueryParam("dataField") String dataField,
@QueryParam("resolutionKey") String resolutionKey,
@QueryParam("start") String startStr,
@QueryParam("includeStart") boolean includeStart,
@QueryParam("end") String endStr,
@QueryParam("includeEnd") boolean includeEnd,
@QueryParam("maxPoints") Integer maxPoints) {
final ExternalIdBundle bundle = ExternalIdBundle.parse(idStrs);
final LocalDate start = (startStr != null ? LocalDate.parse(startStr) : null);
final LocalDate end = (endStr != null ? LocalDate.parse(endStr) : null);
final HistoricalTimeSeries result;
if (idValidityDateStr != null) {
final LocalDate idValidityDate = (idValidityDateStr == null || "ALL".equals(idValidityDateStr) ? null : LocalDate.parse(idValidityDateStr));
if (start == null && end == null && maxPoints == null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, idValidityDate, resolutionKey);
} else if (maxPoints != null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, idValidityDate, resolutionKey, start, includeStart, end, includeEnd, maxPoints);
} else {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, idValidityDate, resolutionKey, start, includeStart, end, includeEnd);
}
} else {
if (start == null && end == null && maxPoints == null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, resolutionKey);
} else if (maxPoints != null) {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, resolutionKey, start, includeStart, end, includeEnd, maxPoints);
} else {
result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
dataField, bundle, resolutionKey, start, includeStart, end, includeEnd);
}
}
return responseOkFudge(result);
}
@SuppressWarnings("unchecked")
@POST
@Path("htsSearches/bulk")
public Response searchBulk(FudgeMsgEnvelope request) {
// non-ideal variant using POST
FudgeMsg msg = request.getMessage();
FudgeDeserializer deserializationContext = new FudgeDeserializer(OpenGammaFudgeContext.getInstance());
Set<ExternalIdBundle> identifierSet = deserializationContext.fudgeMsgToObject(Set.class, msg.getMessage("id"));
String dataSource = msg.getString("dataSource");
String dataProvider = msg.getString("dataProvider");
String dataField = msg.getString("dataField");
LocalDate start = deserializationContext.fieldValueToObject(LocalDate.class, msg.getByName("start"));
boolean inclusiveStart = msg.getBoolean("includeStart");
LocalDate end = deserializationContext.fieldValueToObject(LocalDate.class, msg.getByName("end"));
boolean includeEnd = msg.getBoolean("includeEnd");
Map<ExternalIdBundle, HistoricalTimeSeries> result = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(
identifierSet, dataSource, dataProvider, dataField, start, inclusiveStart, end, includeEnd);
return responseOkFudge(FudgeMapWrapper.of(result));
}
/**
* For debugging purposes only.
*
* @return some debug information about the state of this resource object
*/
@GET
@Path("debugInfo")
public FudgeMsgEnvelope getDebugInfo() {
final MutableFudgeMsg message = OpenGammaFudgeContext.getInstance().newMessage();
message.add("fudgeContext", OpenGammaFudgeContext.getInstance().toString());
message.add("historicalTimeSeriesSource", getHistoricalTimeSeriesSource().toString());
return new FudgeMsgEnvelope(message);
}
public static URI uriGet(URI baseUri, UniqueId uniqueId) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("hts/{htsId}");
if (uniqueId.getVersion() != null) {
bld.queryParam("version", uniqueId.getVersion());
}
return bld.build(uniqueId.getObjectId());
}
public static URI uriExternalIdBundleGet(URI baseUri, UniqueId uniqueId) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsMeta/externalIdBundle/{htsId}");
if (uniqueId.getVersion() != null) {
bld.queryParam("version", uniqueId.getVersion());
}
return bld.build(uniqueId.getObjectId());
}
public static URI uriGet(URI baseUri, UniqueId uniqueId, LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, Integer maxPoints) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("hts/{htsId}");
if (uniqueId.getVersion() != null) {
bld.queryParam("version", uniqueId.getVersion());
}
if (start != null) {
bld.queryParam("start", start);
bld.queryParam("includeStart", includeStart);
}
if (end != null) {
bld.queryParam("end", end);
bld.queryParam("includeEnd", includeEnd);
}
if (maxPoints != null) {
bld.queryParam("maxPoints", maxPoints);
}
return bld.build(uniqueId.getObjectId());
}
/**
* Workaround for {@link UriBuilder#queryParam} that will not escape strings that contain valid escaped sequences. For example, "%3FFoo" will be left as-is since "%3F" is a valid escape whereas
* "%3GFoo" will be escaped to "%253GFoo". If the string contains a "%" then we will escape it in advance and the builder will leave it alone. Otherwise we'll let the builder deal with the string.
*
* @param bundle the identifiers to convert
* @return the array of, possibly encoded, identifier strings
*/
private static Object[] identifiers(final ExternalIdBundle bundle) {
final List<String> identifiers = bundle.toStringList();
final String[] array = new String[identifiers.size()];
identifiers.toArray(array);
try {
for (int i = 0; i < array.length; i++) {
if (array[i].indexOf('%') >= 0) {
array[i] = URLEncoder.encode(array[i], "UTF-8").replace('+', ' ');
}
}
} catch (UnsupportedEncodingException e) {
throw new OpenGammaRuntimeException("Caught", e);
}
return array;
}
public static URI uriSearchSingle(
URI baseUri, ExternalIdBundle identifierBundle, String dataSource, String dataProvider, String dataField,
LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, Integer maxPoints) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsSearches/single");
bld.queryParam("id", identifiers(identifierBundle));
if (dataSource != null) {
bld.queryParam("dataSource", dataSource);
}
if (dataProvider != null) {
bld.queryParam("dataProvider", dataProvider);
}
if (dataField != null) {
bld.queryParam("dataField", dataField);
}
if (start != null) {
bld.queryParam("start", start);
bld.queryParam("includeStart", includeStart);
}
if (end != null) {
bld.queryParam("end", end);
bld.queryParam("includeEnd", includeEnd);
}
if (maxPoints != null) {
bld.queryParam("maxPoints", maxPoints);
}
return bld.build();
}
public static URI uriSearchSingle(
URI baseUri, ExternalIdBundle identifierBundle, LocalDate identifierValidityDate, String dataSource, String dataProvider, String dataField,
LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, Integer maxPoints) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsSearches/single");
bld.queryParam("id", identifiers(identifierBundle));
bld.queryParam("idValidityDate", (identifierValidityDate != null ? identifierValidityDate : "ALL"));
if (dataSource != null) {
bld.queryParam("dataSource", dataSource);
}
if (dataProvider != null) {
bld.queryParam("dataProvider", dataProvider);
}
if (dataField != null) {
bld.queryParam("dataField", dataField);
}
if (start != null) {
bld.queryParam("start", start);
bld.queryParam("includeStart", includeStart);
}
if (end != null) {
bld.queryParam("end", end);
bld.queryParam("includeEnd", includeEnd);
}
if (maxPoints != null) {
bld.queryParam("maxPoints", maxPoints);
}
return bld.build();
}
public static URI uriSearchResolve(
URI baseUri, ExternalIdBundle identifierBundle, String dataField, String resolutionKey,
LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, Integer maxPoints) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsSearches/resolve");
bld.queryParam("id", identifiers(identifierBundle));
if (dataField != null) {
bld.queryParam("dataField", dataField);
}
if (resolutionKey != null) {
bld.queryParam("resolutionKey", resolutionKey);
}
if (start != null) {
bld.queryParam("start", start);
bld.queryParam("includeStart", includeStart);
}
if (end != null) {
bld.queryParam("end", end);
bld.queryParam("includeEnd", includeEnd);
}
if (maxPoints != null) {
bld.queryParam("maxPoints", maxPoints);
}
return bld.build();
}
public static URI uriSearchResolve(
URI baseUri, ExternalIdBundle identifierBundle, LocalDate identifierValidityDate, String dataField, String resolutionKey,
LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, Integer maxPoints) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsSearches/resolve");
bld.queryParam("id", identifiers(identifierBundle));
bld.queryParam("idValidityDate", (identifierValidityDate != null ? identifierValidityDate : "ALL"));
if (dataField != null) {
bld.queryParam("dataField", dataField);
}
if (resolutionKey != null) {
bld.queryParam("resolutionKey", resolutionKey);
}
if (start != null) {
bld.queryParam("start", start);
bld.queryParam("includeStart", includeStart);
}
if (end != null) {
bld.queryParam("end", end);
bld.queryParam("includeEnd", includeEnd);
}
if (maxPoints != null) {
bld.queryParam("maxPoints", maxPoints);
}
return bld.build();
}
public static URI uriSearchBulk(URI baseUri) {
UriBuilder bld = UriBuilder.fromUri(baseUri).path("htsSearches/bulk");
return bld.build();
}
public static FudgeMsg uriSearchBulkData(
Set<ExternalIdBundle> identifierSet, String dataSource, String dataProvider, String dataField,
LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd) {
FudgeSerializer serializationContext = new FudgeSerializer(OpenGammaFudgeContext.getInstance());
MutableFudgeMsg msg = serializationContext.newMessage();
serializationContext.addToMessage(msg, "id", null, identifierSet);
serializationContext.addToMessage(msg, "dataSource", null, dataSource);
serializationContext.addToMessage(msg, "dataProvider", null, dataProvider);
serializationContext.addToMessage(msg, "dataField", null, dataField);
serializationContext.addToMessage(msg, "start", null, start);
serializationContext.addToMessage(msg, "includeStart", null, includeStart);
serializationContext.addToMessage(msg, "end", null, end);
serializationContext.addToMessage(msg, "includeEnd", null, includeEnd);
return msg;
}
} |
package org.gitlab4j.api;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MultivaluedHashMap;
import org.gitlab4j.api.models.AccessLevel;
import org.gitlab4j.api.utils.ISO8601;
/**
* This class extends the standard JAX-RS Form class to make it fluent.
*/
public class GitLabApiForm extends Form {
public GitLabApiForm() {
super();
}
public GitLabApiForm(MultivaluedHashMap<String, String> map) {
super(map);
}
/**
* Create a GitLabApiForm instance with the "page", and "per_page" parameters preset.
*
* @param page the value for the "page" parameter
* @param perPage the value for the "per_page" parameter
*/
public GitLabApiForm(int page, int perPage) {
super();
withParam(AbstractApi.PAGE_PARAM, page);
withParam(AbstractApi.PER_PAGE_PARAM, (Integer)perPage);
}
/**
* Fluent method for adding query and form parameters to a get() or post() call.
*
* @param name the name of the field/attribute to add
* @param value the value of the field/attribute to add
* @return this GitLabAPiForm instance
*/
public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException {
return (withParam(name, value, false));
}
/**
* Fluent method for adding Date query and form parameters to a get() or post() call.
*
* @param name the name of the field/attribute to add
* @param date the value of the field/attribute to add
* @return this GitLabAPiForm instance
*/
public GitLabApiForm withParam(String name, Date date) throws IllegalArgumentException {
return (withParam(name, date, false));
}
public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException {
return (withParam(name, (date == null ? null : ISO8601.toString(date)), required));
}
/**
* Fluent method for adding AccessLevel query and form parameters to a get() or post() call.
*
* @param name the name of the field/attribute to add
* @param date the value of the field/attribute to add
* @return this GitLabAPiForm instance
*/
public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException {
return (withParam(name, level, false));
}
public GitLabApiForm withParam(String name, AccessLevel level, boolean required) throws IllegalArgumentException {
return (withParam(name, (level == null ? null : level.toValue()), required));
}
/**
* Fluent method for adding a List type query and form parameters to a get() or post() call.
*
* @param <T> the type contained by the List
* @param name the name of the field/attribute to add
* @param values a List containing the values of the field/attribute to add
* @return this GitLabAPiForm instance
*/
public <T> GitLabApiForm withParam(String name, List<T> values) {
return (withParam(name, values, false));
}
public <T> GitLabApiForm withParam(String name, List<T> values, boolean required) throws IllegalArgumentException {
if (values == null || values.isEmpty()) {
if (required) {
throw new IllegalArgumentException(name + " cannot be empty or null");
}
return (this);
}
for (T value : values) {
if (value != null) {
this.param(name + "[]", value.toString());
}
}
return (this);
}
public GitLabApiForm withParam(String name, Object value, boolean required) throws IllegalArgumentException {
if (value == null) {
if (required) {
throw new IllegalArgumentException(name + " cannot be empty or null");
}
return (this);
}
String stringValue = value.toString();
if (required && stringValue.trim().length() == 0) {
throw new IllegalArgumentException(name + " cannot be empty or null");
}
this.param(name, stringValue);
return (this);
}
} |
package org.gitlab4j.api;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.models.Issue;
import org.gitlab4j.api.models.MergeRequest;
import org.gitlab4j.api.models.Milestone;
public class MilestonesApi extends AbstractApi {
public MilestonesApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of group milestones.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @return the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getGroupMilestones(Object groupIdOrPath) throws GitLabApiException {
return (getGroupMilestones(groupIdOrPath, getDefaultPerPage()).all());
}
/**
* Get a list of group milestones.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param page the page number to get
* @param perPage how many milestones per page
* @return the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getGroupMilestones(Object groupIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a Page of group milestones.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param itemsPerPage The number of Milestone instances that will be fetched per page
* @return the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public Pager<Milestone> getGroupMilestones(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException {
return (new Pager<Milestone>(this, Milestone.class, itemsPerPage, null,
"groups", getGroupIdOrPath(groupIdOrPath), "milestones"));
}
/**
* Get a Stream of group milestones.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @return a Stream of the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public Stream<Milestone> getGroupMilestonesStream(Object groupIdOrPath) throws GitLabApiException {
return (getGroupMilestones(groupIdOrPath, getDefaultPerPage()).stream());
}
/**
* Get a list of group milestones that have the specified state.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param state the milestone state
* @return the milestones associated with the specified group and state
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getGroupMilestones(Object groupIdOrPath, MilestoneState state) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("state", state).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a list of group milestones that have match the search string.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param search the search string
* @return the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getGroupMilestones(Object groupIdOrPath, String search) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a list of group milestones that have the specified state and match the search string.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param state the milestone state
* @param search the search string
* @return the milestones associated with the specified group
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getGroupMilestones(Object groupIdOrPath, MilestoneState state, String search) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("state", state)
.withParam("search", search)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get the specified group milestone.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the ID of the milestone tp get
* @return a Milestone instance for the specified IDs
* @throws GitLabApiException if any exception occurs
*/
public Milestone getGroupMilestone(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Get the list of issues associated with the specified group milestone.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id/issues</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to get the issues for
* @return a List of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getGroupIssues(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
return (getGroupIssues(groupIdOrPath, milestoneId, getDefaultPerPage()).all());
}
/**
* Get the Pager of issues associated with the specified group milestone.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id/issues</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to get the issues for
* @param itemsPerPage The number of Milestone instances that will be fetched per page
* @return a Pager of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public Pager<Issue> getGroupIssues(Object groupIdOrPath, Integer milestoneId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Issue>(this, Issue.class, itemsPerPage, null,
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId, "issues"));
}
/**
* Get a Stream of issues associated with the specified group milestone.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id/issues</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to get the issues for
* @return a Stream of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public Stream<Issue> getGroupIssuesStream(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
return (getGroupIssues(groupIdOrPath, milestoneId, getDefaultPerPage()).stream());
}
/**
* Get the list of merge requests associated with the specified group milestone.
*
* <pre><code>GitLab Endpoint: GET /groups/:id/milestones/:milestone_id/merge_requests</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to get the merge requests for
* @return a list of merge requests associated with the specified milestone
* @throws GitLabApiException if any exception occurs
*/
public List<MergeRequest> getGroupMergeRequest(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {}));
}
/**
* Create a group milestone.
*
* <pre><code>GitLab Endpoint: POST /groups/:id/milestones</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param title the title for the milestone
* @param description the description for the milestone
* @param dueDate the due date for the milestone
* @param startDate the start date for the milestone
* @return the created Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone createGroupMilestone(Object groupIdOrPath, String title, String description, Date dueDate, Date startDate) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("description", description)
.withParam("due_date", dueDate)
.withParam("start_date", startDate);
Response response = post(Response.Status.CREATED, formData, "groups", getGroupIdOrPath(groupIdOrPath), "milestones");
return (response.readEntity(Milestone.class));
}
/**
* Close a group milestone.
*
* <pre><code>GitLab Endpoint: PUT /groups/:id/milestones/:milestone_id</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to close
* @return the closed Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone closeGroupMilestone(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", MilestoneState.CLOSE);
Response response = put(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Activate a group milestone.
*
* <pre><code>GitLab Endpoint: PUT /groups/:id/milestones/:milestone_id</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to activate
* @return the activated Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone activateGroupMilestone(Object groupIdOrPath, Integer milestoneId) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", MilestoneState.ACTIVATE);
Response response = put(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Update the specified group milestone.
*
* <pre><code>GitLab Endpoint: PUT /groups/:id/milestones/:milestone_id</code></pre>
*
* @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
* @param milestoneId the milestone ID to update
* @param title the updated title for the milestone
* @param description the updated description for the milestone
* @param dueDate the updated due date for the milestone
* @param startDate the updated start date for the milestone
* @param milestoneState the updated milestone state
* @return the updated Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone updateGroupMilestone(Object groupIdOrPath, Integer milestoneId, String title, String description,
Date dueDate, Date startDate, MilestoneState milestoneState) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("description", description)
.withParam("due_date", dueDate)
.withParam("start_date", startDate)
.withParam("state_event", milestoneState);
Response response = put(Response.Status.OK, formData.asMap(),
"groups", getGroupIdOrPath(groupIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Get a list of project milestones.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getMilestones(Object projectIdOrPath) throws GitLabApiException {
return (getMilestones(projectIdOrPath, getDefaultPerPage()).all());
}
/**
* Get a list of project milestones.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page number to get
* @param perPage how many milestones per page
* @return the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getMilestones(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a Pager of project milestones.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage The number of Milestone instances that will be fetched per page
* @return the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<Milestone> getMilestones(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (new Pager<Milestone>(this, Milestone.class, itemsPerPage, null,
"projects", getProjectIdOrPath(projectIdOrPath), "milestones"));
}
/**
* Get a Stream of project milestones.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a Stream of the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public Stream<Milestone> getMilestonesStream(Object projectIdOrPath) throws GitLabApiException {
return (getMilestones(projectIdOrPath, getDefaultPerPage()).stream());
}
/**
* Get a list of project milestones that have the specified state.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param state the milestone state
* @return the milestones associated with the specified project and state
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getMilestones(Object projectIdOrPath, MilestoneState state) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("state", state).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a list of project milestones that have match the search string.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param search the search string
* @return the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getMilestones(Object projectIdOrPath, String search) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get a list of project milestones that have the specified state and match the search string.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param state the milestone state
* @param search the search string
* @return the milestones associated with the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Milestone> getMilestones(Object projectIdOrPath, MilestoneState state, String search) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("state", state)
.withParam("search", search)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones");
return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
/**
* Get the specified milestone.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones/:milestone_id</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the ID of the milestone tp get
* @return a Milestone instance for the specified IDs
* @throws GitLabApiException if any exception occurs
*/
public Milestone getMilestone(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Get the list of issues associated with the specified milestone.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones/:milestone_id/issues</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to get the issues for
* @return a List of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getIssues(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
return (getIssues(projectIdOrPath, milestoneId, getDefaultPerPage()).all());
}
/**
* Get a Pager of issues associated with the specified milestone.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones/:milestone_id/issues</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to get the issues for
* @param itemsPerPage the number of Milestone instances that will be fetched per page
* @return a Pager of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public Pager<Issue> getIssues(Object projectIdOrPath, Integer milestoneId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Issue>(this, Issue.class, itemsPerPage, null,
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId, "issues"));
}
/**
* Get a Stream of issues associated with the specified milestone.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones/:milestone_id/issues</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to get the issues for
* @return a Stream of Issue for the milestone
* @throws GitLabApiException if any exception occurs
*/
public Stream<Issue> getIssuesStream(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
return (getIssues(projectIdOrPath, milestoneId, getDefaultPerPage()).stream());
}
/**
* Get the list of merge requests associated with the specified milestone.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/milestones/:milestone_id/merge_requests</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to get the merge requests for
* @return a list of merge requests associated with the specified milestone
* @throws GitLabApiException if any exception occurs
*/
public List<MergeRequest> getMergeRequest(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {}));
}
/**
* Create a milestone.
*
* <pre><code>GitLab Endpoint: POST /projects/:id/milestones</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param title the title for the milestone
* @param description the description for the milestone
* @param dueDate the due date for the milestone
* @param startDate the start date for the milestone
* @return the created Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone createMilestone(Object projectIdOrPath, String title, String description, Date dueDate, Date startDate) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("description", description)
.withParam("due_date", dueDate)
.withParam("start_date", startDate);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "milestones");
return (response.readEntity(Milestone.class));
}
/**
* Close a milestone.
*
* <pre><code>GitLab Endpoint: PUT /projects/:id/milestones/:milestone_id</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to close
* @return the closed Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone closeMilestone(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", MilestoneState.CLOSE);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Activate a milestone.
*
* <pre><code>GitLab Endpoint: PUT /projects/:id/milestones/:milestone_id</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to activate
* @return the activated Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone activateMilestone(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", MilestoneState.ACTIVATE);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
/**
* Update the specified milestone.
*
* <pre><code>GitLab Endpoint: PUT /projects/:id/milestones/:milestone_id</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param milestoneId the milestone ID to update
* @param title the updated title for the milestone
* @param description the updated description for the milestone
* @param dueDate the updated due date for the milestone
* @param startDate the updated start date for the milestone
* @param milestoneState the updated milestone state
* @return the updated Milestone instance
* @throws GitLabApiException if any exception occurs
*/
public Milestone updateMilestone(Object projectIdOrPath, Integer milestoneId, String title, String description,
Date dueDate, Date startDate, MilestoneState milestoneState) throws GitLabApiException {
if (milestoneId == null) {
throw new RuntimeException("milestoneId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("description", description)
.withParam("due_date", dueDate)
.withParam("start_date", startDate)
.withParam("state_event", milestoneState);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId);
return (response.readEntity(Milestone.class));
}
} |
package org.jaxen.dom4j;
import java.io.File;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
class Performance {
public static void main(String[] args) {
try {
Document doc = new SAXReader().read(new File("D:/dev/jaxen/xml/much_ado.xml"));
Dom4jXPath xpath = new Dom4jXPath("PLAY/ACT/SCENE/SPEECH/SPEAKER");
long start = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 1000; i++) {
Element speaker = (Element) xpath.selectSingleNode(doc);
count += (speaker == null ? 0 : 1);
}
long end = System.currentTimeMillis();
System.out.println((end - start));
System.out.println(count);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
package com.github.scribejava.apis.examples;
import com.github.scribejava.apis.MicrosoftAzureActiveDirectory20Api;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class MicrosoftAzureActiveDirectory20Example {
private static final String NETWORK_NAME = "Microsoft Azure Active Directory";
private static final String PROTECTED_RESOURCE_URL = "https://graph.microsoft.com/v1.0/me";
private MicrosoftAzureActiveDirectory20Example() {
}
public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
// Replace these with your client id and secret
final String clientId = "client id here";
final String clientSecret = "client secret here";
final OAuth20Service service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.scope("openid User.Read")
.callback("http:
.build(MicrosoftAzureActiveDirectory20Api.instance());
final Scanner in = new Scanner(System.in, "UTF-8");
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
final String authorizationUrl = service.getAuthorizationUrl();
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize ScribeJava here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
final String code = in.nextLine();
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth2AccessToken accessToken = service.getAccessToken(code);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)");
}
} |
package railo.runtime.coder;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import railo.runtime.exp.ExpressionException;
import railo.runtime.op.Caster;
/**
* Util class to handle Base 64 Encoded Strings
*/
public final class Base64Coder {
/**
* decodes a Base64 String to a Plain String
* @param encoded
* @return
* @throws ExpressionException
*/
public static String decodeToString(String encoded,String charset) throws CoderException, UnsupportedEncodingException {
byte[] dec = decode(Caster.toString(encoded,null),charset);
return new String(dec,charset);
}
/**
* decodes a Base64 String to a Plain String
* @param encoded
* @return decoded binary data
* @throws CoderException
*/
public static byte[] decode(String encoded, String charset) throws CoderException {
try {
return Base64.decodeBase64(encoded.getBytes(charset));
}
catch(Throwable t) {
return _decode(encoded);
}
}
/**
* encodes a String to Base64 String
* @param plain String to encode
* @return encoded String
* @throws CoderException
* @throws UnsupportedEncodingException
*/
public static String encodeFromString(String plain,String charset) throws CoderException, UnsupportedEncodingException {
return encode(plain.getBytes(charset),charset);
}
/**
* encodes a byte array to Base64 String
* @param barr byte array to encode
* @return encoded String
* @throws CoderException
*/
public static String encode(byte[] barr, String charset) throws CoderException {
try {
return new String(Base64.encodeBase64(barr),charset);
}
catch(Throwable t) {
return _encode(barr);
}
}
private static byte[] _decode(String encoded) throws CoderException {
try {
char[] chars;
chars = encoded.toCharArray();
byte[] bytes=new byte[chars.length];
for(int i=0;i<chars.length;i++) {
bytes[i]=(byte)chars[i];
}
return Base64.decodeBase64(bytes);
}
catch(Throwable t) {
throw new CoderException("can't decode input ["+encoded+"]");
}
}
private static String _encode(byte[] barr) {
byte[] bytes=Base64.encodeBase64(barr);
StringBuffer sb=new StringBuffer();
for(int i=0;i<bytes.length;i++) {
sb.append((char)bytes[i]);
}
return sb.toString();
}
} |
package org.jfree.chart.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import org.jfree.chart.LegendItem;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtils;
import org.jfree.chart.util.PaintUtils;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.ResourceBundleWrapper;
import org.jfree.chart.util.SerialUtils;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.ValueDataset;
/**
* A plot that displays a single value in the form of a needle on a dial.
* Defined ranges (for example, 'normal', 'warning' and 'critical') can be
* highlighted on the dial.
*/
public class MeterPlot extends Plot implements Serializable, Cloneable {
/** For serialization. */
private static final long serialVersionUID = 2987472457734470962L;
/** The default background paint. */
static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.BLACK;
/** The default needle paint. */
static final Paint DEFAULT_NEEDLE_PAINT = Color.GREEN;
/** The default value font. */
static final Font DEFAULT_VALUE_FONT = new Font("SansSerif", Font.BOLD, 12);
/** The default value paint. */
static final Paint DEFAULT_VALUE_PAINT = Color.YELLOW;
/** The default meter angle. */
public static final int DEFAULT_METER_ANGLE = 270;
/** The default border size. */
public static final float DEFAULT_BORDER_SIZE = 3f;
/** The default circle size. */
public static final float DEFAULT_CIRCLE_SIZE = 10f;
/** The default label font. */
public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif",
Font.BOLD, 10);
/** The dataset (contains a single value). */
private ValueDataset dataset;
/** The dial shape (background shape). */
private DialShape shape;
/** The dial extent (measured in degrees). */
private int meterAngle;
/** The overall range of data values on the dial. */
private Range range;
/** The tick size. */
private double tickSize;
/** The paint used to draw the ticks. */
private transient Paint tickPaint;
/** The units displayed on the dial. */
private String units;
/** The font for the value displayed in the center of the dial. */
private Font valueFont;
/** The paint for the value displayed in the center of the dial. */
private transient Paint valuePaint;
/** A flag that controls whether or not the border is drawn. */
private boolean drawBorder;
/** The outline paint. */
private transient Paint dialOutlinePaint;
/** The paint for the dial background. */
private transient Paint dialBackgroundPaint;
/** The paint for the needle. */
private transient Paint needlePaint;
/** A flag that controls whether or not the tick labels are visible. */
private boolean tickLabelsVisible;
/** The tick label font. */
private Font tickLabelFont;
/** The tick label paint. */
private transient Paint tickLabelPaint;
/** The tick label format. */
private NumberFormat tickLabelFormat;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundleWrapper.getBundle(
"org.jfree.chart.plot.LocalizationBundle");
/**
* A (possibly empty) list of the {@link MeterInterval}s to be highlighted
* on the dial.
*/
private List<MeterInterval> intervals;
/**
* Creates a new plot with a default range of <code>0</code> to
* <code>100</code> and no value to display.
*/
public MeterPlot() {
this(null);
}
/**
* Creates a new plot that displays the value from the supplied dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public MeterPlot(ValueDataset dataset) {
super();
this.shape = DialShape.CIRCLE;
this.meterAngle = DEFAULT_METER_ANGLE;
this.range = new Range(0.0, 100.0);
this.tickSize = 10.0;
this.tickPaint = Color.WHITE;
this.units = "Units";
this.needlePaint = MeterPlot.DEFAULT_NEEDLE_PAINT;
this.tickLabelsVisible = true;
this.tickLabelFont = MeterPlot.DEFAULT_LABEL_FONT;
this.tickLabelPaint = Color.BLACK;
this.tickLabelFormat = NumberFormat.getInstance();
this.valueFont = MeterPlot.DEFAULT_VALUE_FONT;
this.valuePaint = MeterPlot.DEFAULT_VALUE_PAINT;
this.dialBackgroundPaint = MeterPlot.DEFAULT_DIAL_BACKGROUND_PAINT;
this.intervals = new java.util.ArrayList<MeterInterval>();
setDataset(dataset);
}
/**
* Returns the dial shape. The default is {@link DialShape#CIRCLE}).
*
* @return The dial shape (never <code>null</code>).
*
* @see #setDialShape(DialShape)
*/
public DialShape getDialShape() {
return this.shape;
}
/**
* Sets the dial shape and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getDialShape()
*/
public void setDialShape(DialShape shape) {
ParamChecks.nullNotPermitted(shape, "shape");
this.shape = shape;
fireChangeEvent();
}
/**
* Returns the meter angle in degrees. This defines, in part, the shape
* of the dial. The default is 270 degrees.
*
* @return The meter angle (in degrees).
*
* @see #setMeterAngle(int)
*/
public int getMeterAngle() {
return this.meterAngle;
}
/**
* Sets the angle (in degrees) for the whole range of the dial and sends
* a {@link PlotChangeEvent} to all registered listeners.
*
* @param angle the angle (in degrees, in the range 1-360).
*
* @see #getMeterAngle()
*/
public void setMeterAngle(int angle) {
if (angle < 1 || angle > 360) {
throw new IllegalArgumentException("Invalid 'angle' (" + angle
+ ")");
}
this.meterAngle = angle;
fireChangeEvent();
}
/**
* Returns the overall range for the dial.
*
* @return The overall range (never <code>null</code>).
*
* @see #setRange(Range)
*/
public Range getRange() {
return this.range;
}
/**
* Sets the range for the dial and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param range the range (<code>null</code> not permitted and zero-length
* ranges not permitted).
*
* @see #getRange()
*/
public void setRange(Range range) {
ParamChecks.nullNotPermitted(range, "range");
if (!(range.getLength() > 0.0)) {
throw new IllegalArgumentException(
"Range length must be positive.");
}
this.range = range;
fireChangeEvent();
}
/**
* Returns the tick size (the interval between ticks on the dial).
*
* @return The tick size.
*
* @see #setTickSize(double)
*/
public double getTickSize() {
return this.tickSize;
}
/**
* Sets the tick size and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param size the tick size (must be > 0).
*
* @see #getTickSize()
*/
public void setTickSize(double size) {
if (size <= 0) {
throw new IllegalArgumentException("Requires 'size' > 0.");
}
this.tickSize = size;
fireChangeEvent();
}
/**
* Returns the paint used to draw the ticks around the dial.
*
* @return The paint used to draw the ticks around the dial (never
* <code>null</code>).
*
* @see #setTickPaint(Paint)
*/
public Paint getTickPaint() {
return this.tickPaint;
}
/**
* Sets the paint used to draw the tick labels around the dial and sends
* a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickPaint()
*/
public void setTickPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.tickPaint = paint;
fireChangeEvent();
}
/**
* Returns a string describing the units for the dial.
*
* @return The units (possibly <code>null</code>).
*
* @see #setUnits(String)
*/
public String getUnits() {
return this.units;
}
/**
* Sets the units for the dial and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param units the units (<code>null</code> permitted).
*
* @see #getUnits()
*/
public void setUnits(String units) {
this.units = units;
fireChangeEvent();
}
/**
* Returns the paint for the needle.
*
* @return The paint (never <code>null</code>).
*
* @see #setNeedlePaint(Paint)
*/
public Paint getNeedlePaint() {
return this.needlePaint;
}
/**
* Sets the paint used to display the needle and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getNeedlePaint()
*/
public void setNeedlePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.needlePaint = paint;
fireChangeEvent();
}
/**
* Returns the flag that determines whether or not tick labels are visible.
*
* @return The flag.
*
* @see #setTickLabelsVisible(boolean)
*/
public boolean getTickLabelsVisible() {
return this.tickLabelsVisible;
}
/**
* Sets the flag that controls whether or not the tick labels are visible
* and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #getTickLabelsVisible()
*/
public void setTickLabelsVisible(boolean visible) {
if (this.tickLabelsVisible != visible) {
this.tickLabelsVisible = visible;
fireChangeEvent();
}
}
/**
* Returns the tick label font.
*
* @return The font (never <code>null</code>).
*
* @see #setTickLabelFont(Font)
*/
public Font getTickLabelFont() {
return this.tickLabelFont;
}
/**
* Sets the tick label font and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getTickLabelFont()
*/
public void setTickLabelFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.tickLabelFont = font;
fireChangeEvent();
}
/**
* Returns the tick label paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the tick label paint and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.tickLabelPaint = paint;
fireChangeEvent();
}
/**
* Returns the tick label format.
*
* @return The tick label format (never <code>null</code>).
*
* @see #setTickLabelFormat(NumberFormat)
*/
public NumberFormat getTickLabelFormat() {
return this.tickLabelFormat;
}
/**
* Sets the format for the tick labels and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param format the format (<code>null</code> not permitted).
*
* @see #getTickLabelFormat()
*/
public void setTickLabelFormat(NumberFormat format) {
ParamChecks.nullNotPermitted(format, "format");
this.tickLabelFormat = format;
fireChangeEvent();
}
/**
* Returns the font for the value label.
*
* @return The font (never <code>null</code>).
*
* @see #setValueFont(Font)
*/
public Font getValueFont() {
return this.valueFont;
}
/**
* Sets the font used to display the value label and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getValueFont()
*/
public void setValueFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.valueFont = font;
fireChangeEvent();
}
/**
* Returns the paint for the value label.
*
* @return The paint (never <code>null</code>).
*
* @see #setValuePaint(Paint)
*/
public Paint getValuePaint() {
return this.valuePaint;
}
/**
* Sets the paint used to display the value label and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getValuePaint()
*/
public void setValuePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.valuePaint = paint;
fireChangeEvent();
}
/**
* Returns the paint for the dial background.
*
* @return The paint (possibly <code>null</code>).
*
* @see #setDialBackgroundPaint(Paint)
*/
public Paint getDialBackgroundPaint() {
return this.dialBackgroundPaint;
}
/**
* Sets the paint used to fill the dial background. Set this to
* <code>null</code> for no background.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getDialBackgroundPaint()
*/
public void setDialBackgroundPaint(Paint paint) {
this.dialBackgroundPaint = paint;
fireChangeEvent();
}
/**
* Returns a flag that controls whether or not a rectangular border is
* drawn around the plot area.
*
* @return A flag.
*
* @see #setDrawBorder(boolean)
*/
public boolean getDrawBorder() {
return this.drawBorder;
}
/**
* Sets the flag that controls whether or not a rectangular border is drawn
* around the plot area and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param draw the flag.
*
* @see #getDrawBorder()
*/
public void setDrawBorder(boolean draw) {
// TODO: fix output when this flag is set to true
this.drawBorder = draw;
fireChangeEvent();
}
/**
* Returns the dial outline paint.
*
* @return The paint.
*
* @see #setDialOutlinePaint(Paint)
*/
public Paint getDialOutlinePaint() {
return this.dialOutlinePaint;
}
/**
* Sets the dial outline paint and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param paint the paint.
*
* @see #getDialOutlinePaint()
*/
public void setDialOutlinePaint(Paint paint) {
this.dialOutlinePaint = paint;
fireChangeEvent();
}
/**
* Returns the dataset for the plot.
*
* @return The dataset (possibly <code>null</code>).
*
* @see #setDataset(ValueDataset)
*/
public ValueDataset getDataset() {
return this.dataset;
}
/**
* Sets the dataset for the plot, replacing the existing dataset if there
* is one, and triggers a {@link PlotChangeEvent}.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset()
*/
public void setDataset(ValueDataset dataset) {
// if there is an existing dataset, remove the plot from the list of
// change listeners...
ValueDataset existing = this.dataset;
if (existing != null) {
existing.removeChangeListener(this);
}
// set the new dataset, and register the chart as a change listener...
this.dataset = dataset;
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self...
DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);
datasetChanged(event);
}
/**
* Returns an unmodifiable list of the intervals for the plot.
*
* @return A list.
*
* @see #addInterval(MeterInterval)
*/
public List<MeterInterval> getIntervals() {
return Collections.unmodifiableList(this.intervals);
}
/**
* Adds an interval and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param interval the interval (<code>null</code> not permitted).
*
* @see #getIntervals()
* @see #clearIntervals()
*/
public void addInterval(MeterInterval interval) {
ParamChecks.nullNotPermitted(interval, "interval");
this.intervals.add(interval);
fireChangeEvent();
}
/**
* Clears the intervals for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @see #addInterval(MeterInterval)
*/
public void clearIntervals() {
this.intervals.clear();
fireChangeEvent();
}
/**
* Returns an item for each interval.
*
* @return A collection of legend items.
*/
@Override
public List<LegendItem> getLegendItems() {
List<LegendItem> result = new ArrayList<LegendItem>();
for (MeterInterval mi : this.intervals) {
Paint color = mi.getBackgroundPaint();
if (color == null) {
color = mi.getOutlinePaint();
}
LegendItem item = new LegendItem(mi.getLabel(), mi.getLabel(),
null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0),
color);
item.setDataset(getDataset());
result.add(item);
}
return result;
}
/**
* Draws the plot on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device.
* @param area the area within which the plot should be drawn.
* @param anchor the anchor point (<code>null</code> permitted).
* @param parentState the state from the parent plot, if there is one.
* @param info collects info about the drawing.
*/
@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,
PlotState parentState, PlotRenderingInfo info) {
if (info != null) {
info.setPlotArea(area);
}
// adjust for insets...
RectangleInsets insets = getInsets();
insets.trim(area);
area.setRect(area.getX() + 4, area.getY() + 4, area.getWidth() - 8,
area.getHeight() - 8);
// FIXME : the 'drawBorder' flag is unnecessary, because the background
// will be drawn by painters...if they are null, nothing is drawn
if (this.drawBorder) {
drawBackground(g2, area);
}
// adjust the plot area by the interior spacing value
double gapHorizontal = (2 * DEFAULT_BORDER_SIZE);
double gapVertical = (2 * DEFAULT_BORDER_SIZE);
double meterX = area.getX() + gapHorizontal / 2;
double meterY = area.getY() + gapVertical / 2;
double meterW = area.getWidth() - gapHorizontal;
double meterH = area.getHeight() - gapVertical
+ ((this.meterAngle <= 180) && (this.shape != DialShape.CIRCLE)
? area.getHeight() / 1.25 : 0);
double min = Math.min(meterW, meterH) / 2;
meterX = (meterX + meterX + meterW) / 2 - min;
meterY = (meterY + meterY + meterH) / 2 - min;
meterW = 2 * min;
meterH = 2 * min;
Rectangle2D meterArea = new Rectangle2D.Double(meterX, meterY, meterW,
meterH);
Rectangle2D.Double originalArea = new Rectangle2D.Double(
meterArea.getX() - 4, meterArea.getY() - 4,
meterArea.getWidth() + 8, meterArea.getHeight() + 8);
double meterMiddleX = meterArea.getCenterX();
double meterMiddleY = meterArea.getCenterY();
// plot the data (unless the dataset is null)...
ValueDataset data = getDataset();
if (data != null) {
double dataMin = this.range.getLowerBound();
double dataMax = this.range.getUpperBound();
Shape savedClip = g2.getClip();
g2.clip(originalArea);
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
if (this.dialBackgroundPaint != null) {
fillArc(g2, originalArea, dataMin, dataMax,
this.dialBackgroundPaint, true);
}
drawTicks(g2, meterArea, dataMin, dataMax);
drawArcForInterval(g2, meterArea, new MeterInterval("", this.range,
this.dialOutlinePaint, new BasicStroke(1.0f), null));
for (MeterInterval interval : this.intervals) {
drawArcForInterval(g2, meterArea, interval);
}
Number n = data.getValue();
if (n != null) {
double value = n.doubleValue();
drawValueLabel(g2, meterArea);
if (this.range.contains(value)) {
g2.setPaint(this.needlePaint);
g2.setStroke(new BasicStroke(2.0f));
double radius = (meterArea.getWidth() / 2)
+ DEFAULT_BORDER_SIZE + 15;
double valueAngle = valueToAngle(value);
double valueP1 = meterMiddleX
+ (radius * Math.cos(Math.PI * (valueAngle / 180)));
double valueP2 = meterMiddleY
- (radius * Math.sin(Math.PI * (valueAngle / 180)));
Polygon arrow = new Polygon();
if ((valueAngle > 135 && valueAngle < 225)
|| (valueAngle < 45 && valueAngle > -45)) {
double valueP3 = (meterMiddleY
- DEFAULT_CIRCLE_SIZE / 4);
double valueP4 = (meterMiddleY
+ DEFAULT_CIRCLE_SIZE / 4);
arrow.addPoint((int) meterMiddleX, (int) valueP3);
arrow.addPoint((int) meterMiddleX, (int) valueP4);
}
else {
arrow.addPoint((int) (meterMiddleX
- DEFAULT_CIRCLE_SIZE / 4), (int) meterMiddleY);
arrow.addPoint((int) (meterMiddleX
+ DEFAULT_CIRCLE_SIZE / 4), (int) meterMiddleY);
}
arrow.addPoint((int) valueP1, (int) valueP2);
g2.fill(arrow);
Ellipse2D circle = new Ellipse2D.Double(meterMiddleX
- DEFAULT_CIRCLE_SIZE / 2, meterMiddleY
- DEFAULT_CIRCLE_SIZE / 2, DEFAULT_CIRCLE_SIZE,
DEFAULT_CIRCLE_SIZE);
g2.fill(circle);
}
}
g2.setClip(savedClip);
g2.setComposite(originalComposite);
}
if (this.drawBorder) {
drawOutline(g2, area);
}
}
/**
* Draws the arc to represent an interval.
*
* @param g2 the graphics device.
* @param meterArea the drawing area.
* @param interval the interval.
*/
protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea,
MeterInterval interval) {
double minValue = interval.getRange().getLowerBound();
double maxValue = interval.getRange().getUpperBound();
Paint outlinePaint = interval.getOutlinePaint();
Stroke outlineStroke = interval.getOutlineStroke();
Paint backgroundPaint = interval.getBackgroundPaint();
if (backgroundPaint != null) {
fillArc(g2, meterArea, minValue, maxValue, backgroundPaint, false);
}
if (outlinePaint != null) {
if (outlineStroke != null) {
drawArc(g2, meterArea, minValue, maxValue, outlinePaint,
outlineStroke);
}
drawTick(g2, meterArea, minValue, true);
drawTick(g2, meterArea, maxValue, true);
}
}
/**
* Draws an arc.
*
* @param g2 the graphics device.
* @param area the plot area.
* @param minValue the minimum value.
* @param maxValue the maximum value.
* @param paint the paint.
* @param stroke the stroke.
*/
protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue,
double maxValue, Paint paint, Stroke stroke) {
double startAngle = valueToAngle(maxValue);
double endAngle = valueToAngle(minValue);
double extent = endAngle - startAngle;
double x = area.getX();
double y = area.getY();
double w = area.getWidth();
double h = area.getHeight();
g2.setPaint(paint);
g2.setStroke(stroke);
if (paint != null && stroke != null) {
Arc2D.Double arc = new Arc2D.Double(x, y, w, h, startAngle,
extent, Arc2D.OPEN);
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(arc);
}
}
/**
* Fills an arc on the dial between the given values.
*
* @param g2 the graphics device.
* @param area the plot area.
* @param minValue the minimum data value.
* @param maxValue the maximum data value.
* @param paint the background paint (<code>null</code> not permitted).
* @param dial a flag that indicates whether the arc represents the whole
* dial.
*/
protected void fillArc(Graphics2D g2, Rectangle2D area, double minValue,
double maxValue, Paint paint, boolean dial) {
ParamChecks.nullNotPermitted(paint, "paint");
double startAngle = valueToAngle(maxValue);
double endAngle = valueToAngle(minValue);
double extent = endAngle - startAngle;
double x = area.getX();
double y = area.getY();
double w = area.getWidth();
double h = area.getHeight();
int joinType;
if (this.shape == DialShape.PIE) {
joinType = Arc2D.PIE;
} else if (this.shape == DialShape.CHORD) {
if (dial && this.meterAngle > 180) {
joinType = Arc2D.CHORD;
} else {
joinType = Arc2D.PIE;
}
} else if (this.shape == DialShape.CIRCLE) {
joinType = Arc2D.PIE;
if (dial) {
extent = 360;
}
} else {
throw new IllegalStateException("DialShape not recognised.");
}
g2.setPaint(paint);
Arc2D.Double arc = new Arc2D.Double(x, y, w, h, startAngle, extent,
joinType);
g2.fill(arc);
}
/**
* Translates a data value to an angle on the dial.
*
* @param value the value.
*
* @return The angle on the dial.
*/
public double valueToAngle(double value) {
value = value - this.range.getLowerBound();
double baseAngle = 180 + ((this.meterAngle - 180) / 2);
return baseAngle - ((value / this.range.getLength()) * this.meterAngle);
}
/**
* Draws the ticks that subdivide the overall range.
*
* @param g2 the graphics device.
* @param meterArea the meter area.
* @param minValue the minimum value.
* @param maxValue the maximum value.
*/
protected void drawTicks(Graphics2D g2, Rectangle2D meterArea,
double minValue, double maxValue) {
for (double v = minValue; v <= maxValue; v += this.tickSize) {
drawTick(g2, meterArea, v);
}
}
/**
* Draws a tick.
*
* @param g2 the graphics device.
* @param meterArea the meter area.
* @param value the value.
*/
protected void drawTick(Graphics2D g2, Rectangle2D meterArea,
double value) {
drawTick(g2, meterArea, value, false);
}
/**
* Draws a tick on the dial.
*
* @param g2 the graphics device.
* @param meterArea the meter area.
* @param value the tick value.
* @param label a flag that controls whether or not a value label is drawn.
*/
protected void drawTick(Graphics2D g2, Rectangle2D meterArea,
double value, boolean label) {
double valueAngle = valueToAngle(value);
double meterMiddleX = meterArea.getCenterX();
double meterMiddleY = meterArea.getCenterY();
g2.setPaint(this.tickPaint);
g2.setStroke(new BasicStroke(2.0f));
double valueP2X;
double valueP2Y;
double radius = (meterArea.getWidth() / 2) + DEFAULT_BORDER_SIZE;
double radius1 = radius - 15;
double valueP1X = meterMiddleX
+ (radius * Math.cos(Math.PI * (valueAngle / 180)));
double valueP1Y = meterMiddleY
- (radius * Math.sin(Math.PI * (valueAngle / 180)));
valueP2X = meterMiddleX
+ (radius1 * Math.cos(Math.PI * (valueAngle / 180)));
valueP2Y = meterMiddleY
- (radius1 * Math.sin(Math.PI * (valueAngle / 180)));
Line2D.Double line = new Line2D.Double(valueP1X, valueP1Y, valueP2X,
valueP2Y);
g2.draw(line);
if (this.tickLabelsVisible && label) {
String tickLabel = this.tickLabelFormat.format(value);
g2.setFont(this.tickLabelFont);
g2.setPaint(this.tickLabelPaint);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D tickLabelBounds
= TextUtilities.getTextBounds(tickLabel, g2, fm);
double x = valueP2X;
double y = valueP2Y;
if (valueAngle == 90 || valueAngle == 270) {
x = x - tickLabelBounds.getWidth() / 2;
}
else if (valueAngle < 90 || valueAngle > 270) {
x = x - tickLabelBounds.getWidth();
}
if ((valueAngle > 135 && valueAngle < 225)
|| valueAngle > 315 || valueAngle < 45) {
y = y - tickLabelBounds.getHeight() / 2;
}
else {
y = y + tickLabelBounds.getHeight() / 2;
}
g2.drawString(tickLabel, (float) x, (float) y);
}
}
/**
* Draws the value label just below the center of the dial.
*
* @param g2 the graphics device.
* @param area the plot area.
*/
protected void drawValueLabel(Graphics2D g2, Rectangle2D area) {
g2.setFont(this.valueFont);
g2.setPaint(this.valuePaint);
String valueStr = "No value";
if (this.dataset != null) {
Number n = this.dataset.getValue();
if (n != null) {
valueStr = this.tickLabelFormat.format(n.doubleValue()) + " "
+ this.units;
}
}
float x = (float) area.getCenterX();
float y = (float) area.getCenterY() + DEFAULT_CIRCLE_SIZE;
TextUtilities.drawAlignedString(valueStr, g2, x, y,
TextAnchor.TOP_CENTER);
}
/**
* Returns a short string describing the type of plot.
*
* @return A string describing the type of plot.
*/
@Override
public String getPlotType() {
return localizationResources.getString("Meter_Plot");
}
/**
* A zoom method that does nothing. Plots are required to support the
* zoom operation. In the case of a meter plot, it doesn't make sense to
* zoom in or out, so the method is empty.
*
* @param percent The zoom percentage.
*/
@Override
public void zoom(double percent) {
// intentionally blank
}
/**
* Tests the plot for equality with an arbitrary object. Note that the
* dataset is ignored for the purposes of testing equality.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MeterPlot)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
MeterPlot that = (MeterPlot) obj;
if (!ObjectUtils.equal(this.units, that.units)) {
return false;
}
if (!ObjectUtils.equal(this.range, that.range)) {
return false;
}
if (!ObjectUtils.equal(this.intervals, that.intervals)) {
return false;
}
if (!PaintUtils.equal(this.dialOutlinePaint,
that.dialOutlinePaint)) {
return false;
}
if (this.shape != that.shape) {
return false;
}
if (!PaintUtils.equal(this.dialBackgroundPaint,
that.dialBackgroundPaint)) {
return false;
}
if (!PaintUtils.equal(this.needlePaint, that.needlePaint)) {
return false;
}
if (!ObjectUtils.equal(this.valueFont, that.valueFont)) {
return false;
}
if (!PaintUtils.equal(this.valuePaint, that.valuePaint)) {
return false;
}
if (!PaintUtils.equal(this.tickPaint, that.tickPaint)) {
return false;
}
if (this.tickSize != that.tickSize) {
return false;
}
if (this.tickLabelsVisible != that.tickLabelsVisible) {
return false;
}
if (!ObjectUtils.equal(this.tickLabelFont, that.tickLabelFont)) {
return false;
}
if (!PaintUtils.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!ObjectUtils.equal(this.tickLabelFormat,
that.tickLabelFormat)) {
return false;
}
if (this.drawBorder != that.drawBorder) {
return false;
}
if (this.meterAngle != that.meterAngle) {
return false;
}
return true;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtils.writePaint(this.dialBackgroundPaint, stream);
SerialUtils.writePaint(this.dialOutlinePaint, stream);
SerialUtils.writePaint(this.needlePaint, stream);
SerialUtils.writePaint(this.valuePaint, stream);
SerialUtils.writePaint(this.tickPaint, stream);
SerialUtils.writePaint(this.tickLabelPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.dialBackgroundPaint = SerialUtils.readPaint(stream);
this.dialOutlinePaint = SerialUtils.readPaint(stream);
this.needlePaint = SerialUtils.readPaint(stream);
this.valuePaint = SerialUtils.readPaint(stream);
this.tickPaint = SerialUtils.readPaint(stream);
this.tickLabelPaint = SerialUtils.readPaint(stream);
if (this.dataset != null) {
this.dataset.addChangeListener(this);
}
}
/**
* Returns an independent copy (clone) of the plot. The dataset is NOT
* cloned - both the original and the clone will have a reference to the
* same dataset.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the plot cannot
* be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
MeterPlot clone = (MeterPlot) super.clone();
clone.tickLabelFormat = (NumberFormat) this.tickLabelFormat.clone();
// the following relies on the fact that the intervals are immutable
clone.intervals = new java.util.ArrayList<MeterInterval>(this.intervals);
if (clone.dataset != null) {
clone.dataset.addChangeListener(clone);
}
return clone;
}
} |
package org.collectionspace.services.client.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.PersonJAXBSchema;
import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.ContactClient;
import org.collectionspace.services.client.ObjectExitClient;
import org.collectionspace.services.client.PayloadOutputPart;
import org.collectionspace.services.client.PersonAuthorityClient;
import org.collectionspace.services.client.PersonAuthorityClientUtils;
import org.collectionspace.services.client.PoxPayloadIn;
import org.collectionspace.services.client.PoxPayloadOut;
import org.collectionspace.services.common.authorityref.AuthorityRefList;
import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.collectionspace.services.objectexit.ObjectexitCommon;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObjectExitAuthRefsTest extends BaseServiceTest {
private final String CLASS_NAME = ObjectExitAuthRefsTest.class.getName();
private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
final String PERSON_AUTHORITY_NAME = "ObjectexitPersonAuth";
private String knownResourceId = null;
private List<String> objectexitIdsCreated = new ArrayList<String>();
private List<String> personIdsCreated = new ArrayList<String>();
private String personAuthCSID = null;
private String depositorRefName = null;
private String exitDate = null;
private String exitNumber = null;
private final static String CURRENT_DATE_UTC =
GregorianCalendarDateTimeUtils.currentDateUTC();
@Override
public String getServicePathComponent() {
return ObjectExitClient.SERVICE_PATH_COMPONENT;
}
@Override
protected String getServiceName() {
return ObjectExitClient.SERVICE_NAME;
}
@Override
protected CollectionSpaceClient getClientInstance() {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
@Override
protected AbstractCommonList getAbstractCommonList(ClientResponse<AbstractCommonList> response) {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
private PoxPayloadOut createObjectExitInstance(String depositorRefName, String exitNumber, String exitDate) {
this.exitDate = exitDate;
this.exitNumber = exitNumber;
this.depositorRefName = depositorRefName;
ObjectexitCommon objectexit = new ObjectexitCommon();
objectexit.setDepositor(depositorRefName);
objectexit.setExitNumber(exitNumber);
objectexit.setExitDate(exitDate);
PoxPayloadOut multipart = new PoxPayloadOut(ObjectExitClient.SERVICE_PAYLOAD_NAME);
PayloadOutputPart commonPart = multipart.addPart(objectexit, MediaType.APPLICATION_XML_TYPE);
commonPart.setLabel(new ObjectExitClient().getCommonPartName());
logger.debug("to be created, objectexit common: " + objectAsXmlString(objectexit, ObjectexitCommon.class));
return multipart;
}
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
public void createWithAuthRefs(String testName) throws Exception {
logger.debug(testBanner(testName, CLASS_NAME));
testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
String identifier = createIdentifier(); // Submit the request to the service and store the response.
createPersonRefs();// Create all the person refs and entities
// Create a new Loans In resource. One or more fields in this resource will be PersonAuthority
// references, and will refer to Person resources by their refNames.
ObjectExitClient objectexitClient = new ObjectExitClient();
PoxPayloadOut multipart = createObjectExitInstance(depositorRefName,
"exitNumber-" + identifier, CURRENT_DATE_UTC);
ClientResponse<Response> res = objectexitClient.create(multipart);
assertStatusCode(res, testName);
if (knownResourceId == null) {// Store the ID returned from the first resource created for additional tests below.
knownResourceId = extractId(res);
}
objectexitIdsCreated.add(extractId(res));// Store the IDs from every resource created; delete on cleanup
}
protected void createPersonRefs() {
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
// Create a temporary PersonAuthority resource, and its corresponding refName by which it can be identified.
PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
ClientResponse<Response> res = personAuthClient.create(multipart);
assertStatusCode(res, "createPersonRefs (not a surefire test)");
personAuthCSID = extractId(res);
String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
// Create temporary Person resources, and their corresponding refNames by which they can be identified.
String csid = "";
csid = createPerson("Owen the Cur", "Owner", "owenCurOwner", authRefName);
personIdsCreated.add(csid);
depositorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
csid = createPerson("Davenport", "Depositor", "davenportDepositor", authRefName);
personIdsCreated.add(csid);
depositorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
}
protected String createPerson(String firstName, String surName, String shortId, String authRefName) {
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
Map<String, String> personInfo = new HashMap<String, String>();
personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, authRefName, personInfo, personAuthClient.getItemCommonPartName());
ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
assertStatusCode(res, "createPerson (not a surefire test)");
return extractId(res);
}
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"createWithAuthRefs"})
public void readAndCheckAuthRefs(String testName) throws Exception {
logger.debug(testBanner(testName, CLASS_NAME));
testSetup(STATUS_OK, ServiceRequestType.READ);
ObjectExitClient objectexitClient = new ObjectExitClient();
ClientResponse<String> res = objectexitClient.read(knownResourceId);
assertStatusCode(res, testName);
PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
ObjectexitCommon objectexit = (ObjectexitCommon) extractPart(input, objectexitClient.getCommonPartName(), ObjectexitCommon.class);
Assert.assertNotNull(objectexit);
logger.debug(objectAsXmlString(objectexit, ObjectexitCommon.class));
// Check a couple of fields
Assert.assertEquals(objectexit.getDepositor(), depositorRefName);
Assert.assertEquals(objectexit.getExitNumber(), exitNumber);
// Get the auth refs and check them
ClientResponse<AuthorityRefList> res2 = objectexitClient.getAuthorityRefs(knownResourceId);
assertStatusCode(res2, testName);
AuthorityRefList list = res2.getEntity();
List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
int numAuthRefsFound = items.size();
logger.debug("Authority references, found " + numAuthRefsFound);
//Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
// "Did not find all expected authority references! " +
// "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
if (logger.isDebugEnabled()) {
int i = 0;
for (AuthorityRefList.AuthorityRefItem item : items) {
logger.debug(testName + ": list-item[" + i + "] Field:" + item.getSourceField() + "= " + item.getAuthDisplayName() + item.getItemDisplayName());
logger.debug(testName + ": list-item[" + i + "] refName=" + item.getRefName());
logger.debug(testName + ": list-item[" + i + "] URI=" + item.getUri());
i++;
}
}
}
@AfterClass(alwaysRun = true)
public void cleanUp() {
String noTest = System.getProperty("noTestCleanup");
if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
logger.debug("Skipping Cleanup phase ...");
return;
}
logger.debug("Cleaning up temporary resources created for testing ...");
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
// Delete Person resource(s) (before PersonAuthority resources).
for (String resourceId : personIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
personAuthClient.deleteItem(personAuthCSID, resourceId);
}
// Delete PersonAuthority resource(s).
// Note: Any non-success response is ignored and not reported.
if (personAuthCSID != null) {
personAuthClient.delete(personAuthCSID);
// Delete Loans In resource(s).
ObjectExitClient objectexitClient = new ObjectExitClient();
for (String resourceId : objectexitIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
objectexitClient.delete(resourceId);
}
}
}
} |
package org.jtrfp.trcl;
import java.util.Arrays;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.TR;
public class CharLineDisplay
{
private char [] content;
private final CharDisplay [] displays;
double [] position = new double []{0,0,.0001};
private GLFont font;
private final double glSize;
private double totGlLen=0;
private boolean centered=false;
public CharLineDisplay(TR tr,RenderableSpacePartitioningGrid grid, double glSize, int lengthInChars, GLFont font)
{content = new char[lengthInChars];
displays = new CharDisplay[lengthInChars];
this.font=font;
for(int i=0; i<lengthInChars; i++)
{content[i]='X';
displays[i]=new CharDisplay(tr,grid,glSize,font);
displays[i].setChar('X');
grid.add(displays[i]);
}//end for(lengthInChars)
this.glSize=glSize;
updatePositions();
}//end LineDisplay(...)
public void setContent(String content)
{for(int i=0; i<this.content.length; i++)
{char newContent;
if(i<content.length())
{newContent=content.charAt(i);}
else{newContent=0;}
this.content[i]=newContent;
displays[i].setChar(newContent);
}//end for(length)
updatePositions();
}//end setContent(...)
private void updatePositions()
{final double[] charPosition=Arrays.copyOf(position,3);
totGlLen=0;
//Determine total length;
for(int i=0; i<displays.length; i++){
char _content = content[i];
if(_content!=0){
final double progress=((double)glSize)*font.glWidthOf(_content)*1.1;//1.1 fudge factor for space between letters
totGlLen+=progress;}
}//end for(displays)
if(centered)charPosition[0]-=totGlLen/2.;
for(int i=0; i<displays.length; i++){
final double [] dispPos = displays[i].getPosition();
dispPos[0]=charPosition[0];
dispPos[1]=charPosition[1];
dispPos[2]=charPosition[2];
displays[i].notifyPositionChange();
char _content = content[i];
final double progress=((double)glSize)*font.glWidthOf(_content)*1.1;//1.1 fudge factor for space between letters
charPosition[0]+=progress;
}//end for(displays)
}//end updatePositions
public void setPosition(double [] location)
{this.position=location;
updatePositions();
}//end setPosition(...)
public void setPosition(double x, double y, double z) {
position[0]=x;
position[1]=y;
position[2]=z;
updatePositions();
}
/**
* @return the displays
*/
public CharDisplay[] getDisplays() {
return displays;
}
public GLFont getFont() {
return font;
}
/**
* @return the centered
*/
public boolean isCentered() {
return centered;
}
/**
* @param centered the centered to set
*/
public void setCentered(boolean centered) {
this.centered = centered;
}
public void setVisible(boolean b) {
for(CharDisplay disp:displays){
disp.setVisible(b);
}//end for(displays)
}//end setVisible(...)
}//end LineDisplay |
package io.vrap.rmf.raml.test;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import io.vrap.rmf.raml.model.RamlModelBuilder;
import io.vrap.rmf.raml.model.RamlModelResult;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class RamlTckTest implements ResourceFixtures {
private class TckParseException extends Exception {
public TckParseException(String message, Throwable cause) {
super(message, cause);
}
}
private static final String TCK_VERSION = "1.1";
private static final String RAML_VERSION = "1.0";
private static final String RAML_TCK_VERSION = Optional.ofNullable(System.getenv("RAML_TCK_VERSION")).orElse(TCK_VERSION);
private final static URL tckURL = RamlTckTest.class.getResource("/raml-tck-" + RAML_TCK_VERSION + "/tests/raml-" + RAML_VERSION);
@Test
@UseDataProvider("allTckRamlFiles")
public void tckFilesParse(final File f) throws TckParseException {
tckParse(f);
}
@Test
@UseDataProvider("allTckInvalidRamlFiles")
public void tckInvalidRaml(final File f) throws TckParseException {
tckParse(f, false);
}
@Test
@UseDataProvider("allTckValidRamlFiles")
public void tckValidRaml(final File f) throws TckParseException {
tckParse(f, true);
}
@Test
@UseDataProvider("allTckApiRamlFiles")
public void tckTest(final File f) throws TckParseException {
tckParse(f);
}
@DataProvider
public static List<File> allTestRamlFiles() throws IOException {
return Files.walk(Paths.get(tckURL.getPath()))
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".raml")).map(Path::toFile).collect(Collectors.toList());
}
@DataProvider
public static List<File> allTckRamlFiles() throws IOException {
return Files.walk(Paths.get(tckURL.getPath()))
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".raml")).map(Path::toFile).collect(Collectors.toList());
}
@DataProvider
public static List<File> allTckInvalidRamlFiles() throws IOException {
return Files.walk(Paths.get(tckURL.getPath()))
.filter(Files::isRegularFile)
.filter(path -> path.toString().toLowerCase().endsWith("invalid.raml")).map(Path::toFile).collect(Collectors.toList());
}
@DataProvider
public static List<File> allTckValidRamlFiles() throws IOException {
return Files.walk(Paths.get(tckURL.getPath()))
.filter(Files::isRegularFile)
.filter(path -> !path.toString().toLowerCase().endsWith("invalid.raml") && path.toString().toLowerCase().endsWith("valid.raml")).map(Path::toFile).collect(Collectors.toList());
}
@DataProvider
public static List<File> allTckApiRamlFiles() throws IOException {
return Files.walk(Paths.get(tckURL.getPath()))
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith("api.raml")).map(Path::toFile).collect(Collectors.toList());
}
public void tckParse(final File f, final Boolean valid) throws TckParseException {
final URI fileURI = URI.createURI(f.toURI().toString());
try {
final RamlModelResult<EObject> result = new RamlModelBuilder().build(fileURI);
if (valid) {
assertThat(result.getValidationResults())
.describedAs(fileURI.toFileString().replace(tckURL.getPath(), "") + "(" + f.getName() + ":0)")
.isEmpty();
} else {
assertThat(result.getValidationResults())
.describedAs(fileURI.toFileString().replace(tckURL.getPath(), "") + "(" + f.getName() + ":0)")
.isNotEmpty();
}
} catch (Throwable e) {
throw new TckParseException(f.toString() + "(" + f.getName() + ":0)", e);
}
}
public void tckParse(final File f) throws TckParseException {
final URI fileURI = URI.createURI(f.toURI().toString());
try {
final RamlModelResult<EObject> result = new RamlModelBuilder().build(fileURI);
assertThat(result.getRootObject() != null);
} catch (Throwable e) {
throw new TckParseException(f.toString() + "(" + f.getName() + ":0)", e);
}
}
} |
package org.openmhealth.shim.runkeeper.mapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.*;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import static java.util.UUID.randomUUID;
import static org.openmhealth.schema.domain.omh.DurationUnit.SECOND;
import static org.openmhealth.schema.domain.omh.LengthUnit.METER;
import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndDuration;
import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*;
public class RunKeeperPhysicalActivityDataPointMapper extends RunKeeperDataPointMapper<PhysicalActivity> {
@Override
protected String getListNodeName() {
return "items";
}
@Override
protected Optional<DataPoint<PhysicalActivity>> asDataPoint(JsonNode itemNode) {
PhysicalActivity measure = getMeasure(itemNode);
DataPointHeader header = getDataPointHeader(itemNode, measure);
return Optional.of(new DataPoint<>(header, measure));
}
private PhysicalActivity getMeasure(JsonNode itemNode) {
String activityName = asRequiredString(itemNode, "type");
PhysicalActivity.Builder builder = new PhysicalActivity.Builder(activityName);
Optional<LocalDateTime> localStartDateTime =
asOptionalLocalDateTime(itemNode, "start_time", DATE_TIME_FORMATTER);
// RunKeeper doesn't support fractional time zones
Optional<Integer> utcOffset = asOptionalInteger(itemNode, "utc_offset");
Optional<Double> durationInS = asOptionalDouble(itemNode, "duration");
if (localStartDateTime.isPresent() && utcOffset.isPresent() && durationInS.isPresent()) {
OffsetDateTime startDateTime = localStartDateTime.get().atOffset(ZoneOffset.ofHours(utcOffset.get()));
DurationUnitValue duration = new DurationUnitValue(SECOND, durationInS.get());
builder.setEffectiveTimeFrame(ofStartDateTimeAndDuration(startDateTime, duration));
}
asOptionalDouble(itemNode, "total_distance")
.ifPresent(distanceInM -> builder.setDistance(new LengthUnitValue(METER, distanceInM)));
asOptionalString(itemNode, "notes").ifPresent(builder::setUserNotes);
return builder.build();
}
private DataPointHeader getDataPointHeader(JsonNode itemNode, PhysicalActivity measure) {
DataPointAcquisitionProvenance.Builder provenanceBuilder =
new DataPointAcquisitionProvenance.Builder(RESOURCE_API_SOURCE_NAME);
getModality(itemNode).ifPresent(provenanceBuilder::setModality);
DataPointAcquisitionProvenance provenance = provenanceBuilder.build();
asOptionalString(itemNode, "uri")
.ifPresent(externalId -> provenance.setAdditionalProperty("external_id", externalId));
DataPointHeader.Builder headerBuilder =
new DataPointHeader.Builder(randomUUID().toString(), measure.getSchemaId())
.setAcquisitionProvenance(provenance);
asOptionalInteger(itemNode, "userId").ifPresent(userId -> headerBuilder.setUserId(userId.toString()));
return headerBuilder.build();
}
public Optional<DataPointModality> getModality(JsonNode itemNode) {
String source = asOptionalString(itemNode, "source").orElse(null);
String entryMode = asOptionalString(itemNode, "entry_mode").orElse(null);
Boolean hasPath = asOptionalBoolean(itemNode, "has_path").orElse(null);
if (entryMode != null && entryMode.equals("Web")) {
return Optional.of(DataPointModality.SELF_REPORTED);
}
if (source != null && source.equals("RunKeeper")
&& entryMode != null && entryMode.equals("API")
&& hasPath != null && hasPath) {
return Optional.of(DataPointModality.SENSED);
}
return Optional.empty();
}
} |
package org.jtrfp.trcl.core;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Callable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import org.jtrfp.trcl.dbg.FramebufferStateWindow;
import org.jtrfp.trcl.gui.ConfigWindow;
import org.jtrfp.trcl.mem.GPUMemDump;
public class RootWindow extends JFrame {
private static final long serialVersionUID = -2412572500302248185L;
static {GLProfile.initSingleton();}
private final TR tr;
private final GLProfile glProfile = GLProfile.get(GLProfile.GL2GL3);
private final GLCapabilities capabilities = new GLCapabilities(glProfile);
private final GLCanvas canvas = new GLCanvas(capabilities);
private final FramebufferStateWindow fbsw;
private final ConfigWindow configWindow;
public RootWindow(TR tr) {
this.tr = tr;
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
configureMenuBar();
// frame.setBackground(Color.black);
getContentPane().add(canvas);
setVisible(true);
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
} catch (Exception e) {
e.printStackTrace();
}//end try/catch Exception
setTitle("Terminal Recall");
fbsw = new FramebufferStateWindow(tr);
configWindow = new ConfigWindow(tr.getTrConfig());
}//end constructor
private void configureMenuBar() {
setJMenuBar(new JMenuBar());
JMenu file = new JMenu("File"), window = new JMenu("Window"), gameMenu = new JMenu("Game");
// And menus to menubar
JMenuItem file_exit = new JMenuItem("Exit");
JMenuItem file_config = new JMenuItem("Configure");
JMenuItem game_new = new JMenuItem("New Game");
JMenuItem debugStatesMenuItem = new JMenuItem("Debug States");
JMenuItem frameBufferStatesMenuItem = new JMenuItem("Framebuffer States");
JMenuItem gpuMemDump = new JMenuItem("Dump GPU Memory");
// Menu item behaviors
game_new.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
tr.getThreadManager().submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
tr.getGameShell().newGame();
return null;
}});
}});
file_config.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
configWindow.setVisible(true);
}});
file_exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(1);
}
});
debugStatesMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
tr.getReporter().setVisible(true);
};
});
frameBufferStatesMenuItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
fbsw.setVisible(true);
}});
gpuMemDump.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
tr.getThreadManager().submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
new GPUMemDump(tr);
return null;
}});
};
});
final String showDebugStatesOnStartup = System
.getProperty("org.jtrfp.trcl.showDebugStates");
if (showDebugStatesOnStartup != null) {
if (showDebugStatesOnStartup.toUpperCase().contains("TRUE")) {
tr.getReporter().setVisible(true);
}
}
file.add(file_exit);
file.add(file_config);
file.add(gpuMemDump);
window.add(debugStatesMenuItem);
window.add(frameBufferStatesMenuItem);
gameMenu.add(game_new);
getJMenuBar().add(file);
getJMenuBar().add(gameMenu);
getJMenuBar().add(window);
}//end configureMenuBar()
public GLCanvas getCanvas() {
return canvas;
}
}// end RootWindow |
package no.steria.skuldsku.testrunner.dbrunner.dbchange;
import no.steria.skuldsku.recorder.logging.RecorderLog;
import no.steria.skuldsku.utils.*;
import javax.sql.DataSource;
import java.io.File;
import java.util.List;
import java.util.Map.Entry;
public class DatabaseChangeRollback {
private static final String ROW = "ROW.";
private static final String OLDROW = "OLDROW.";
private final TransactionManager transactionManager;
public DatabaseChangeRollback(DataSource dataSource) {
this(new SimpleTransactionManager(dataSource));
}
DatabaseChangeRollback(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void rollback(File f) {
final List<DatabaseChange> databaseChanges = DatabaseChange.readDatabaseChanges(f);
rollback(databaseChanges);
}
public static String generateRollbackScript(final List<DatabaseChange> databaseChanges) {
final StringBuilder sb = new StringBuilder();
for (int i=databaseChanges.size()-1; i>=0; i
final String rollbackSql = DatabaseChangeRollback.generateRollbackSql(databaseChanges.get(i));
sb.append(rollbackSql + ";\n");
}
return sb.toString();
}
public void rollback(final List<DatabaseChange> databaseChanges) {
transactionManager.doInTransaction(jdbc -> {
// TODO: Test at disable + reenable virker
final List<String> triggerNames = getEnabledTriggerNames(jdbc);
disableTriggers(jdbc, triggerNames);
try {
for (int i=databaseChanges.size()-1; i>=0; i
final String rollbackSql = DatabaseChangeRollback.generateRollbackSql(databaseChanges.get(i));
jdbc.execute(rollbackSql);
}
} finally {
enableTriggers(jdbc, triggerNames);
}
return null;
});
}
List<String> getEnabledTriggerNames(Jdbc jdbc) {
return jdbc.queryForList("SELECT TRIGGER_NAME FROM USER_TRIGGERS WHERE STATUS = 'ENABLED'", String.class);
}
void enableTrigger(Jdbc jdbc, String triggerName) {
jdbc.execute("ALTER TRIGGER " + triggerName + " ENABLE");
}
void enableTriggers(Jdbc jdbc, final List<String> triggerNames) {
for (String triggerName : triggerNames) {
try {
enableTrigger(jdbc, triggerName);
} catch (JdbcException e) {
RecorderLog.debug("Reenabling of trigger \"" + triggerName + "\" failed.");
}
}
}
void disableTrigger(Jdbc jdbc, String triggerName) {
jdbc.execute("ALTER TRIGGER " + triggerName + " DISABLE");
}
void disableTriggers(Jdbc jdbc, final List<String> triggerNames) {
RecorderLog.debug("Disabling triggers. Run these SQLs in case later reenabling fails:");
for (String triggerName : triggerNames) {
RecorderLog.debug(" ALTER TRIGGER " + triggerName + " ENABLE;");
disableTrigger(jdbc, triggerName);
}
RecorderLog.debug("");
}
public static String generateRollbackSql(DatabaseChange databaseChange) {
final String action = databaseChange.getAction();
if (action.equals("DELETE")) {
return generateDeleteRollback(databaseChange);
} else if (action.equals("INSERT")) {
return generateInsertRollback(databaseChange);
} else if (action.equals("UPDATE")) {
return generateUpdateRollback(databaseChange);
} else {
throw new IllegalStateException("Unknown action: " + action);
}
}
private static String generateUpdateRollback(DatabaseChange databaseChange) {
final String setValues = generateSetValuesUsingOldValues(databaseChange);
final String whereConditions = generateWhereConditionsUsingNewValues(databaseChange);
return "UPDATE " + databaseChange.getTableName() + " SET " + setValues + " WHERE " + whereConditions;
}
private static String generateSetValuesUsingOldValues(DatabaseChange databaseChange) {
final StringBuilder values = new StringBuilder();
boolean append = false;
for (Entry<String, String> entry :databaseChange. getFields(OLDROW)) {
if (append) {
values.append(", ");
}
final String name = stripQualifier(entry.getKey());
String value = entry.getValue();
if (value == null) {
value = "null";
} else {
value = "'" + value + "'";
}
values.append(name).append("=").append(value).append("");
append = true;
}
return values.toString();
}
private static String generateInsertRollback(DatabaseChange databaseChange) {
final String whereConditions = generateWhereConditionsUsingNewValues(databaseChange);
return "DELETE FROM " + databaseChange.getTableName() + " WHERE " + whereConditions;
}
private static String generateWhereConditionsUsingNewValues(DatabaseChange databaseChange) {
final StringBuilder where = new StringBuilder();
boolean append = false;
for (Entry<String, String> entry : databaseChange.getFields(ROW)) {
if (append) {
where.append(" AND ");
}
final String name = stripQualifier(entry.getKey());
final String value = entry.getValue();
if (value != null) {
where.append("TO_CHAR(").append(name).append(")='").append(value).append("'");
} else {
where.append(name).append(" IS NULL");
}
append = true;
}
return where.toString();
}
private static String generateDeleteRollback(DatabaseChange databaseChange) {
final StringBuilder names = new StringBuilder();
final StringBuilder values = new StringBuilder();
boolean append = false;
for (Entry<String, String> entry : databaseChange.getFields(ROW)) {
if (append) {
names.append(", ");
values.append(", ");
}
names.append(stripQualifier(entry.getKey()));
final String value = entry.getValue();
if (value != null) {
values.append("'").append(value).append("'");
} else {
values.append("null");
}
append = true;
}
return "INSERT INTO " + databaseChange.getTableName() + " (" + names.toString() + ") VALUES (" + values.toString() + ")";
}
private static String stripQualifier(String s) {
return s.replaceFirst("^ROW\\.", "").replaceFirst("^OLDROW\\.", "");
}
} |
package org.jtrfp.trcl.gpu;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
public class RawGLBuffer {
private int bufferID;
protected ByteBuffer localBuffer;
private boolean mapped = false;
private int memoryUsageHint = MemoryUsageHint.DymamicDraw.getGLEnumInt();
private final int sizeInBytes;
protected RawGLBuffer(int sizeInBytes, GPU gpu) {
if (sizeInBytes == 0)
throw new RuntimeException("Cannot allocate a buffer of size zero.");
this.sizeInBytes=sizeInBytes;
final GL3 gl = gpu.getGl();
final IntBuffer iBuf = IntBuffer.allocate(1);
gl.glGenBuffers(1, iBuf);
bufferID = iBuf.get();
gl.glBindBuffer(getBindingTarget(), bufferID);
gl.glBufferData(getBindingTarget(), sizeInBytes, null,
getReadWriteParameter());
gl.glBindBuffer(getBindingTarget(), 0);
}// end constructor
void setUsageHint(int hint) {
memoryUsageHint = hint;
}
protected int getReadWriteParameter() {
return memoryUsageHint;
}
protected int getBindingTarget() {
return GL2.GL_ARRAY_BUFFER;
}
public void rewind() {
localBuffer.rewind();
}
public void map(GL3 gl) {
if (mapped)
return;
gl.glBindBuffer(getBindingTarget(), bufferID);
localBuffer = gl.glMapBufferRange(getBindingTarget(), 0, sizeInBytes, GL3.GL_MAP_WRITE_BIT|GL3.GL_MAP_UNSYNCHRONIZED_BIT|GL3.GL_MAP_FLUSH_EXPLICIT_BIT);
if (localBuffer == null) {
throw new NullPointerException("Failed to map buffer.");
}
gl.glBindBuffer(getBindingTarget(), 0);
mapped = true;
}
public void unmap(GL3 gl) {
if (!mapped)
return;
gl.glBindBuffer(getBindingTarget(), bufferID);
gl.glUnmapBuffer(getBindingTarget());
gl.glBindBuffer(getBindingTarget(), 0);
mapped = false;
}
public void free(GL3 gl) {
unmap(gl);
gl.glDeleteBuffers(1, IntBuffer.wrap(new int[] { bufferID }));
localBuffer = null;
}
public void bind(GL2 gl) {
gl.glBindBuffer(getBindingTarget(), getBufferID());
}
public void bindAsElementArrayBuffer(final GL2 gl) {
// gl.glEnableClientState(GL2.GL_ELEMENT_ARRAY_BUFFER);
gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, getBufferID());
}
public void unbind(GL2 gl) {
gl.glBindBuffer(getBindingTarget(), 0);
}
public void position(int pos) {
localBuffer.position(pos);
}
public int position() {
return localBuffer.position();
}
/**
* @return the bufferID
*/
public int getBufferID() {
return bufferID;
}
/**
* @param bufferID
* the bufferID to set
*/
public void setBufferID(int bufferID) {
this.bufferID = bufferID;
}
public ByteBuffer getUnderlyingBuffer() {
return localBuffer;
}
public ByteBuffer getDuplicateReferenceOfUnderlyingBuffer() {
final ByteBuffer result = localBuffer.duplicate();
result.order(localBuffer.order()).clear();
return result;
}
public boolean isMapped(){
return mapped;
}
}// end GLBuffer |
/*
* Tic Tac Toe - The Online Game
* Author : Shaheed Ahmed Dewan Sagar
* AUST CSE : 12-01-04-085
* Dated: 23.07.2013
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tictacktoe;
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Shaheed Ahmed Dewan Sagar
* sdewan64@gmail.com
* AUST-12-01-04-085
*/
public class PlayOnlineClient extends javax.swing.JFrame {
Socket socket;
String host;
DataInputStream in;
DataOutputStream out;
waitThread wt = new waitThread();
char sign = 'X';
char signop = 'O';
int count,port;
int[][] array = new int[3][3];
boolean clickable = false;
public PlayOnlineClient(int port,String host) throws IOException {
initComponents();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int sx = (screen.width / 2) - 100;
int sy = (screen.height / 2) - 150;
this.setBounds(sx, sy, 250, 350);
this.getContentPane().setBackground(Color.DARK_GRAY);
try{
socket = new Socket(host , port);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Sorry the HOST PC refuced to play with you");
}
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
this.port = port;
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
array[i][j] = 0;
}
}
count = 1;
ipbox.setText("Connected to : "+host+":"+port);
wt.start();
}
int Iswin()
{
if (array[0][0]==1 && array[0][1]==1 && array[0][2]==1)
return 1;
else if (array[1][0]==1 && array[1][1]==1 && array[1][2]==1)
return 1;
else if (array[2][0]==1 && array[2][1]==1 && array[2][2]==1)
return 1;
else if (array[0][0]==1 && array[1][0]==1 && array[2][0]==1)
return 1;
else if (array[0][1]==1 && array[1][1]==1 && array[2][1]==1)
return 1;
else if (array[0][2]==1 && array[1][2]==1 && array[2][2]==1)
return 1;
else if (array[0][0]==1 && array[1][1]==1 && array[2][2]==1)
return 1;
else if (array[0][2]==1 && array[1][1]==1 && array[2][0]==1)
return 1;
else if (array[0][0]==2 && array[0][1]==2 && array[0][2]==2)
return 2;
else if (array[1][0]==2 && array[1][1]==2 && array[1][2]==2)
return 2;
else if (array[2][0]==2 && array[2][1]==2 && array[2][2]==2)
return 2;
else if (array[0][0]==2 && array[1][0]==2 && array[2][0]==2)
return 2;
else if (array[0][1]==2 && array[1][1]==2 && array[2][1]==2)
return 2;
else if (array[0][2]==2 && array[1][2]==2 && array[2][2]==2)
return 2;
else if (array[0][0]==2 && array[1][1]==2 && array[2][2]==2)
return 2;
else if (array[0][2]==2 && array[1][1]==2 && array[2][0]==2)
return 2;
else
return -1;
}
void Won(int who) throws IOException{
if(who==1){
out.writeInt(22);
clickable = false;
int choice = JOptionPane.showConfirmDialog(null, "You Lost!Better Luck next Time.\nDo you Want to Play again?");
if(choice==0){
socket.close();
port++;
PlayOnlineClient pc = new PlayOnlineClient(port,host);
pc.setVisible(true);
this.setVisible(false);
}else if(choice == 1||choice == 2){
System.exit(0);
}
}else if(who==2){
out.writeInt(22);
clickable = false;
int choice = JOptionPane.showConfirmDialog(null, "You WON!Congratulations.\nDo you want to play again?");
if(choice==0){
socket.close();
port++;
PlayOnlineClient pc = new PlayOnlineClient(port,host);
pc.setVisible(true);
this.setVisible(false);
}else if(choice == 1||choice == 2){
System.exit(0);
}
}else if(who==3){
out.writeInt(22);
clickable = false;
int choice = JOptionPane.showConfirmDialog(null, "Game DRAWN.\nDo you Want to Play again?");
if(choice==0){
socket.close();
port++;
PlayOnlineClient pc = new PlayOnlineClient(port,host);
pc.setVisible(true);
this.setVisible(false);
}else if(choice == 1||choice == 2){
System.exit(0);
}
}
}
JLabel link(int l,int m)
{
if(l==0)
{
if(m==0)
return box1;
if(m==1)
return box2;
if(m==2)
return box3;
}
if(l==1)
{
if(m==0)
return box4;
if(m==1)
return box5;
if(m==2)
return box6;
}
if(l==2)
{
if(m==0)
return box7;
if(m==1)
return box8;
if(m==2)
return box9;
}
return null;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
box1 = new javax.swing.JLabel();
box2 = new javax.swing.JLabel();
box3 = new javax.swing.JLabel();
box6 = new javax.swing.JLabel();
box5 = new javax.swing.JLabel();
box4 = new javax.swing.JLabel();
box9 = new javax.swing.JLabel();
box8 = new javax.swing.JLabel();
box7 = new javax.swing.JLabel();
label1 = new java.awt.Label();
label2 = new java.awt.Label();
label3 = new java.awt.Label();
label4 = new java.awt.Label();
statusbox = new javax.swing.JLabel();
ipbox = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
exit = new javax.swing.JMenuItem();
howtto = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
about = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Tic Tac Toe");
setBackground(java.awt.Color.darkGray);
setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
box1.setBackground(java.awt.Color.darkGray);
box1.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box1.setForeground(java.awt.Color.white);
box1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box1.setOpaque(true);
box1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box1MouseClicked(evt);
}
});
getContentPane().add(box1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 68, 69));
box2.setBackground(java.awt.Color.darkGray);
box2.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box2.setForeground(java.awt.Color.white);
box2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box2.setOpaque(true);
box2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box2MouseClicked(evt);
}
});
getContentPane().add(box2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 68, 69));
box3.setBackground(java.awt.Color.darkGray);
box3.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box3.setForeground(java.awt.Color.white);
box3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box3.setOpaque(true);
box3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box3MouseClicked(evt);
}
});
getContentPane().add(box3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 10, 68, 69));
box6.setBackground(java.awt.Color.darkGray);
box6.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box6.setForeground(java.awt.Color.white);
box6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box6.setOpaque(true);
box6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box6MouseClicked(evt);
}
});
getContentPane().add(box6, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 90, 68, 69));
box5.setBackground(java.awt.Color.darkGray);
box5.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box5.setForeground(java.awt.Color.white);
box5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box5.setOpaque(true);
box5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box5MouseClicked(evt);
}
});
getContentPane().add(box5, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 90, 68, 69));
box4.setBackground(java.awt.Color.darkGray);
box4.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box4.setForeground(java.awt.Color.white);
box4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box4.setOpaque(true);
box4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box4MouseClicked(evt);
}
});
getContentPane().add(box4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 68, 69));
box9.setBackground(java.awt.Color.darkGray);
box9.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box9.setForeground(java.awt.Color.white);
box9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box9.setOpaque(true);
box9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box9MouseClicked(evt);
}
});
getContentPane().add(box9, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 68, 69));
box8.setBackground(java.awt.Color.darkGray);
box8.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box8.setForeground(java.awt.Color.white);
box8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box8.setOpaque(true);
box8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box8MouseClicked(evt);
}
});
getContentPane().add(box8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 170, 68, 69));
box7.setBackground(java.awt.Color.darkGray);
box7.setFont(new java.awt.Font("Comic Sans MS", 1, 60)); // NOI18N
box7.setForeground(java.awt.Color.white);
box7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
box7.setOpaque(true);
box7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
box7MouseClicked(evt);
}
});
getContentPane().add(box7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 68, 69));
label1.setBackground(java.awt.Color.white);
getContentPane().add(label1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 161, 228, 6));
label2.setBackground(java.awt.Color.white);
getContentPane().add(label2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 81, 228, 6));
label3.setBackground(java.awt.Color.white);
getContentPane().add(label3, new org.netbeans.lib.awtextra.AbsoluteConstraints(161, 10, 6, 230));
label4.setBackground(java.awt.Color.white);
getContentPane().add(label4, new org.netbeans.lib.awtextra.AbsoluteConstraints(81, 10, 6, 230));
statusbox.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
statusbox.setText("Opponents Turn");
statusbox.setOpaque(true);
getContentPane().add(statusbox, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 250, 250, 18));
ipbox.setFont(new java.awt.Font("Trajan Pro", 0, 11)); // NOI18N
ipbox.setForeground(new java.awt.Color(255, 255, 255));
ipbox.setText("IP");
getContentPane().add(ipbox, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 280, -1, -1));
jMenuBar1.setBackground(java.awt.Color.darkGray);
jMenuBar1.setBorder(null);
jMenuBar1.setForeground(java.awt.Color.white);
jMenuBar1.setFocusable(false);
jMenuBar1.setOpaque(false);
jMenu1.setForeground(new java.awt.Color(51, 51, 51));
jMenu1.setText("Game");
exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
jMenu1.add(exit);
jMenuBar1.add(jMenu1);
howtto.setForeground(new java.awt.Color(51, 51, 51));
howtto.setText("Help");
jMenuItem3.setText("How to Play");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
howtto.add(jMenuItem3);
about.setText("About");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutActionPerformed(evt);
}
});
howtto.add(about);
jMenuBar1.add(howtto);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>//GEN-END:initComponents
private void box1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box1MouseClicked
if(array[0][0]==0&&clickable==true){
int i,j;
array[0][0] = 2;
JLabel ct=link(0,0);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(0);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(0);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(0);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box1MouseClicked
private void box2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box2MouseClicked
if(array[0][1]==0&&clickable==true){
int i,j;
array[0][1] = 2;
JLabel ct=link(0,1);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(1);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(1);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(1);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box2MouseClicked
private void box3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box3MouseClicked
if(array[0][2]==0&&clickable==true){
int i,j;
array[0][2] = 2;
JLabel ct=link(0,2);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(2);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(2);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(0);
out.writeInt(10);
out.writeInt(2);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box3MouseClicked
private void box4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box4MouseClicked
if(array[1][0]==0&&clickable==true){
int i,j;
array[1][0] = 2;
JLabel ct=link(1,0);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(0);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(0);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(0);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box4MouseClicked
private void box5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box5MouseClicked
if(array[1][1]==0&&clickable==true){
int i,j;
array[1][1] = 2;
JLabel ct=link(1,1);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(1);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(1);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(1);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box5MouseClicked
private void box6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box6MouseClicked
if(array[1][2]==0&&clickable==true){
int i,j;
array[1][2] = 2;
JLabel ct=link(1,2);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(2);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(2);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(1);
out.writeInt(10);
out.writeInt(2);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box6MouseClicked
private void box7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box7MouseClicked
if(array[2][0]==0&&clickable==true){
int i,j;
array[2][0] = 2;
JLabel ct=link(2,0);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(0);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(0);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(0);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box7MouseClicked
private void box8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box8MouseClicked
if(array[2][1]==0&&clickable==true){
int i,j;
array[2][1] = 2;
JLabel ct=link(2,1);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(1);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(1);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(1);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box8MouseClicked
private void box9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_box9MouseClicked
if(array[2][2]==0&&clickable==true){
int i,j;
array[2][2] = 2;
JLabel ct=link(2,2);
ct.setText(String.valueOf(sign));
int win = Iswin();
if(win==1){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(2);
Won(1);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else if(win==2){
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(2);
Won(2);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
out.writeInt(5);
out.writeInt(10);
out.writeInt(2);
out.writeInt(10);
out.writeInt(2);
new waitThread().start();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//GEN-LAST:event_box9MouseClicked
private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(PlayOnlineHost.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}//GEN-LAST:event_exitActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
JOptionPane.showMessageDialog(null, "*Play by clicking with the mouse.\n*During online play the game must be hosted first.\n*On re-game the hosted game should accept re-match first.\n*Enjoy the game.");
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutActionPerformed
JOptionPane.showMessageDialog(null, "Author : Shaheed Ahmed Dewan Sagar\nAUST CSE\n12-01-04-085");
}//GEN-LAST:event_aboutActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
String h = JOptionPane.showInputDialog("Enter HOST IP");
int p = Integer.parseInt(JOptionPane.showInputDialog("Enter PORT number : "));
try {
new PlayOnlineClient(p,h).setVisible(true);
} catch (IOException ex) {
Logger.getLogger(PlayOnlineClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem about;
private javax.swing.JLabel box1;
private javax.swing.JLabel box2;
private javax.swing.JLabel box3;
private javax.swing.JLabel box4;
private javax.swing.JLabel box5;
private javax.swing.JLabel box6;
private javax.swing.JLabel box7;
private javax.swing.JLabel box8;
private javax.swing.JLabel box9;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JMenuItem exit;
private javax.swing.JMenu howtto;
private javax.swing.JLabel ipbox;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem3;
private java.awt.Label label1;
private java.awt.Label label2;
private java.awt.Label label3;
private java.awt.Label label4;
private javax.swing.JLabel statusbox;
// End of variables declaration//GEN-END:variables
class waitThread extends Thread{
boolean respond = false;
public void run(){
//System.out.println("Thread running");
try {
clickable=false;
statusbox.setText("Wait for Opponents TURN");
if(in.readInt()==5){
// System.out.println("REading data from host:");
int a,b,c;
c = in.readInt();
a = in.readInt();
c = in.readInt();
b = in.readInt();
//System.out.println("DATA : "+a+" "+b);
array[a][b] = 1;
JLabel ct=link(a,b);
ct.setText(String.valueOf(signop));
int win = Iswin();
if(win==1){
Won(1);
}else if(win==2){
Won(2);
}else{
if(count==5){
Won(3);
}
count++;
statusbox.setText("Your TURN");
int x,y;
/*
for(x=0;x<3;x++){
for(y=0;y<3;y++){
System.out.print(array[x][y]+" ");
}
System.out.println();
}*/
clickable=true;
wt.stop();
}
}else if(in.readInt()==22){
int win = Iswin();
if(win==1){
Won(1);
}else if(win==2){
Won(2);
}else{
if(count==5){
Won(3);
}
}
}
} catch (IOException ex) {
Logger.getLogger(PlayOnlineClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} |
package com.andexert.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ListView;
import android.widget.RelativeLayout;
/**
* Author : Chutaux Robin
* Date : 10/8/2014
*/
public class RippleView extends RelativeLayout {
private int WIDTH;
private int HEIGHT;
private int frameRate = 10;
private int rippleDuration = 400;
private int rippleAlpha = 90;
private Handler canvasHandler;
private float radiusMax = 0;
private boolean animationRunning = false;
private int timer = 0;
private int timerEmpty = 0;
private int durationEmpty = -1;
private float x = -1;
private float y = -1;
private int zoomDuration;
private float zoomScale;
private ScaleAnimation scaleAnimation;
private Boolean hasToZoom;
private Boolean isCentered;
private Integer rippleType;
private Paint paint;
private Bitmap originBitmap;
private int rippleColor;
private int ripplePadding;
private GestureDetector gestureDetector;
private final Runnable runnable = new Runnable() {
@Override
public void run() {
invalidate();
}
};
private OnRippleCompleteListener onCompletionListener;
public RippleView(Context context) {
super(context);
}
public RippleView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RippleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (isInEditMode())
return;
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleView);
rippleColor = typedArray.getColor(R.styleable.RippleView_rv_color, getResources().getColor(R.color.rippelColor));
rippleType = typedArray.getInt(R.styleable.RippleView_rv_type, 0);
hasToZoom = typedArray.getBoolean(R.styleable.RippleView_rv_zoom, false);
isCentered = typedArray.getBoolean(R.styleable.RippleView_rv_centered, false);
rippleDuration = typedArray.getInteger(R.styleable.RippleView_rv_rippleDuration, rippleDuration);
frameRate = typedArray.getInteger(R.styleable.RippleView_rv_framerate, frameRate);
rippleAlpha = typedArray.getInteger(R.styleable.RippleView_rv_alpha, rippleAlpha);
ripplePadding = typedArray.getDimensionPixelSize(R.styleable.RippleView_rv_ripplePadding, 0);
canvasHandler = new Handler();
zoomScale = typedArray.getFloat(R.styleable.RippleView_rv_zoomScale, 1.03f);
zoomDuration = typedArray.getInt(R.styleable.RippleView_rv_zoomDuration, 200);
typedArray.recycle();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(rippleColor);
paint.setAlpha(rippleAlpha);
this.setWillNotDraw(false);
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public void onLongPress(MotionEvent event) {
super.onLongPress(event);
animateRipple(event);
sendClickEvent(true);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
this.setDrawingCacheEnabled(true);
this.setClickable(true);
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
if (animationRunning) {
if (rippleDuration <= timer * frameRate) {
animationRunning = false;
timer = 0;
durationEmpty = -1;
timerEmpty = 0;
canvas.restore();
invalidate();
if (onCompletionListener != null) onCompletionListener.onComplete(this);
return;
} else
canvasHandler.postDelayed(runnable, frameRate);
if (timer == 0)
canvas.save();
canvas.drawCircle(x, y, (radiusMax * (((float) timer * frameRate) / rippleDuration)), paint);
paint.setColor(Color.parseColor("#ffff4444"));
if (rippleType == 1 && originBitmap != null && (((float) timer * frameRate) / rippleDuration) > 0.4f) {
if (durationEmpty == -1)
durationEmpty = rippleDuration - timer * frameRate;
timerEmpty++;
final Bitmap tmpBitmap = getCircleBitmap((int) ((radiusMax) * (((float) timerEmpty * frameRate) / (durationEmpty))));
canvas.drawBitmap(tmpBitmap, 0, 0, paint);
tmpBitmap.recycle();
}
paint.setColor(rippleColor);
if (rippleType == 1) {
if ((((float) timer * frameRate) / rippleDuration) > 0.6f)
paint.setAlpha((int) (rippleAlpha - ((rippleAlpha) * (((float) timerEmpty * frameRate) / (durationEmpty)))));
else
paint.setAlpha(rippleAlpha);
}
else
paint.setAlpha((int) (rippleAlpha - ((rippleAlpha) * (((float) timer * frameRate) / rippleDuration))));
timer++;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
WIDTH = w;
HEIGHT = h;
scaleAnimation = new ScaleAnimation(1.0f, zoomScale, 1.0f, zoomScale, w / 2, h / 2);
scaleAnimation.setDuration(zoomDuration);
scaleAnimation.setRepeatMode(Animation.REVERSE);
scaleAnimation.setRepeatCount(1);
}
public void animateRipple(MotionEvent event) {
createAnimation(event.getX(), event.getY());
}
public void animateRipple(final float x, final float y) {
createAnimation(x, y);
}
private void createAnimation(final float x, final float y) {
if (!animationRunning) {
if (hasToZoom)
this.startAnimation(scaleAnimation);
radiusMax = Math.max(WIDTH, HEIGHT);
if (rippleType != 2)
radiusMax /= 2;
radiusMax -= ripplePadding;
if (isCentered || rippleType == 1) {
this.x = getMeasuredWidth() / 2;
this.y = getMeasuredHeight() / 2;
} else {
this.x = x;
this.y = y;
}
animationRunning = true;
if (rippleType == 1 && originBitmap == null)
originBitmap = getDrawingCache(true);
invalidate();
}
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
animateRipple(event);
sendClickEvent(false);
}
return super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
this.onTouchEvent(event);
return super.onInterceptTouchEvent(event);
}
private void sendClickEvent(final Boolean isLongClick) {
if (getParent() instanceof ListView) {
final int position = ((ListView) getParent()).getPositionForView(this);
final long id = ((ListView) getParent()).getItemIdAtPosition(position);
if (isLongClick) {
if (((ListView) getParent()).getOnItemLongClickListener() != null)
((ListView) getParent()).getOnItemLongClickListener().onItemLongClick(((ListView) getParent()), this, position, id);
} else {
if (((ListView) getParent()).getOnItemClickListener() != null)
((ListView) getParent()).getOnItemClickListener().onItemClick(((ListView) getParent()), this, position, id);
}
}
}
private Bitmap getCircleBitmap(final int radius) {
final Bitmap output = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect((int)(x - radius), (int)(y - radius), (int)(x + radius), (int)(y + radius));
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(x, y, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(originBitmap, rect, rect, paint);
return output;
}
public void setRippleColor(int rippleColor) {
this.rippleColor = rippleColor;
}
public int getRippleColor() {
return rippleColor;
}
public RippleType getRippleType()
{
return RippleType.values()[rippleType];
}
public void setRippleType(final RippleType rippleType)
{
this.rippleType = rippleType.ordinal();
}
public Boolean isCentered()
{
return isCentered;
}
public void setCentered(final Boolean isCentered)
{
this.isCentered = isCentered;
}
public int getRipplePadding()
{
return ripplePadding;
}
public void setRipplePadding(int ripplePadding)
{
this.ripplePadding = ripplePadding;
}
public Boolean isZooming()
{
return hasToZoom;
}
public void setZooming(Boolean hasToZoom)
{
this.hasToZoom = hasToZoom;
}
public float getZoomScale()
{
return zoomScale;
}
public void setZoomScale(float zoomScale)
{
this.zoomScale = zoomScale;
}
public int getZoomDuration()
{
return zoomDuration;
}
public void setZoomDuration(int zoomDuration)
{
this.zoomDuration = zoomDuration;
}
public int getRippleDuration()
{
return rippleDuration;
}
public void setRippleDuration(int rippleDuration)
{
this.rippleDuration = rippleDuration;
}
public int getFrameRate()
{
return frameRate;
}
public void setFrameRate(int frameRate)
{
this.frameRate = frameRate;
}
public int getRippleAlpha()
{
return rippleAlpha;
}
public void setRippleAlpha(int rippleAlpha)
{
this.rippleAlpha = rippleAlpha;
}
public void setOnRippleCompleteListener(OnRippleCompleteListener listener) {
this.onCompletionListener = listener;
}
public interface OnRippleCompleteListener {
void onComplete(RippleView rippleView);
}
public enum RippleType {
SIMPLE(0),
DOUBLE(1),
RECTANGLE(2);
int type;
RippleType(int type)
{
this.type = type;
}
}
} |
package org.lantern;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.channel.Channel;
import org.jivesoftware.smack.packet.Presence;
import org.lantern.event.Events;
import org.lantern.event.IncomingPeerEvent;
import org.lantern.event.KscopeAdEvent;
import org.lantern.event.PeerCertEvent;
import org.lantern.event.UpdatePresenceEvent;
import org.lantern.kscope.LanternKscopeAdvertisement;
import org.lantern.state.Mode;
import org.lantern.state.Model;
import org.lantern.state.ModelUtils;
import org.lantern.state.Peer;
import org.lantern.state.Peer.Type;
import org.lantern.state.Peers;
import org.lantern.util.LanternTrafficCounter;
import org.lantern.util.Threads;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* Factory for creating peers that include data to be shown to the frontend.
*/
@Singleton
public class DefaultPeerFactory implements PeerFactory {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ModelUtils modelUtils;
private final Peers peers;
/**
* We create an executor here because we need to thread our geo-ip lookups.
*/
private final ExecutorService exec =
Threads.newCachedThreadPool("Peer-Factory-Thread-");
private final Roster roster;
@Inject
public DefaultPeerFactory(final ModelUtils modelUtils, final Model model,
final Roster roster) {
this.modelUtils = modelUtils;
this.roster = roster;
this.peers = model.getPeerCollector();
Events.register(this);
}
/**
* There are two ways we initially learn about new peers. The first is a
* Lantern peer directly on our roster, which will produce this event. The
* second is a kaleidoscope advertisement. Those Kaleidoscope
* advertisements can be from peers on our roster, but they can also be
* from peers we're not directly connected to. This method captures the
* first case where peers on our roster are running Lantern.
*
* @param event The update presence event.
*/
@Subscribe
public void onUpdatePresenceEvent(final UpdatePresenceEvent event) {
log.debug("Processing presence event");
final Presence presence = event.getPresence();
final String from = presence.getFrom();
if (StringUtils.isBlank(from)) {
log.warn("Presence with blank from?");
} else {
addPeer(LanternUtils.newURI(from), Type.pc);
}
}
@Subscribe
public void onKscopeAd(final KscopeAdEvent event) {
final LanternKscopeAdvertisement ad = event.getAd();
// It is possible and even likely we already know about this peer
// through some other means, in which case we have to update the data
// about that peer as necessary.
log.debug("Adding peer through kscop add...");
final String jid = ad.getJid();
final URI uri = LanternUtils.newURI(jid);
final Peer existing = this.peers.getPeer(uri);
final LanternRosterEntry entry = this.roster.getRosterEntry(jid);
if (existing == null) {
// The following can be null.
final Peer peer = new Peer(uri, "",
ad.hasMappedEndpoint(), 0, 0, Type.pc, ad.getAddress(),
ad.getPort(), Mode.give, false, null, entry);
this.peers.addPeer(uri, peer);
updateGeoData(peer, ad.getAddress());
} else {
existing.setIp(ad.getAddress());
existing.setPort(ad.getPort());
existing.setMode(Mode.give);
existing.setMapped(ad.hasMappedEndpoint());
if (existing.getRosterEntry() == null) {
// Ours could be null too, but can't hurt to set.
existing.setRosterEntry(entry);
}
existing.setVersion(ad.getLanternVersion());
updateGeoData(existing, ad.getAddress());
}
}
private void updateGeoData(final Peer peer, final InetAddress address) {
updateGeoData(peer, address.getHostAddress());
}
private void updateGeoData(final Peer peer, final String address) {
if (StringUtils.isNotBlank(peer.getCountry())) {
log.debug("Peer already had geo data: {}", peer);
return;
}
final Runnable runner = new Runnable() {
@Override
public void run() {
final GeoData geo = modelUtils.getGeoData(address);
peer.setCountry(geo.getCountrycode());
peer.setLat(geo.getLatitude());
peer.setLon(geo.getLongitude());
}
};
this.exec.submit(runner);
}
private void updatePeer(final URI fullJid, final InetSocketAddress isa,
final Type type, final LanternTrafficCounter trafficCounter) {
final Peer peer = peers.getPeer(fullJid);
if (peer == null) {
log.warn("No peer for {}", fullJid);
return;
}
updatePeer(peer, isa, type, trafficCounter);
}
private void updatePeer(final Peer peer, final InetSocketAddress isa,
final Type type, final LanternTrafficCounter trafficCounter) {
// We can get multiple notifications for the same peer, in which case
// they'll already have a counter.
if (peer.getTrafficCounter() == null) {
log.debug("Setting traffic counter...");
peer.setTrafficCounter(trafficCounter);
} else {
log.debug("Peer already has traffic counter...");
}
final String address = isa.getAddress().getHostAddress();
if (StringUtils.isBlank(peer.getIp())) {
peer.setIp(address);
}
if (peer.getPort() == 0) {
peer.setPort(isa.getPort());
}
if (peer.getRosterEntry() == null) {
log.debug("Setting roster entry");
final URI uri = LanternUtils.newURI(peer.getPeerid());
peer.setRosterEntry(rosterEntry(uri));
}
peer.setType(type.toString());
updateGeoData(peer, isa.getAddress());
// Note we don't sync peers with the frontend here because the timer
// will do it for us
}
@Override
public void onOutgoingConnection(final URI fullJid,
final InetSocketAddress isa, final Type type,
final LanternTrafficCounter trafficCounter) {
updatePeer(fullJid, isa, type, trafficCounter);
}
@Override
public void addPeer(final URI fullJid, final Type type) {
// This is a peer we know very little about at this point, as we
// haven't made any network connections with them.
final LanternRosterEntry entry = rosterEntry(fullJid);
final Peer existing = peers.getPeer(fullJid);
if (existing != null) {
log.debug("Peer already exists...");
} else {
log.debug("Adding peer {}", fullJid);
final Peer peer = new Peer(fullJid, "", false, 0L, 0L, type,
"", 0, Mode.none, false, null, entry);
peers.addPeer(fullJid, peer);
}
}
private LanternRosterEntry rosterEntry(final URI fullJid) {
return this.roster.getRosterEntry(fullJid.toASCIIString());
}
private final Map<String, Peer> certsToPeers =
new ConcurrentHashMap<String, Peer>();
@Subscribe
public void onCert(final PeerCertEvent event) {
final Peer peer = this.peers.getPeer(event.getJid());
if (peer == null) {
log.error("Got a cert for peer we don't know about? " +
"{} not found in {}", event.getJid(), this.peers.getPeers().keySet());
} else {
certsToPeers.put(event.getBase64Cert(), peer);
}
}
@Subscribe
public void onIncomingPeerEvent(final IncomingPeerEvent event) {
// First we have to figure out which peer this is an incoming socket
// for base on the certificate.
final X509Certificate cert = event.getCert();
final Channel channel = event.getChannel();
final LanternTrafficCounter counter = event.getTrafficCounter();
try {
final String base64Cert =
Base64.encodeBase64String(cert.getEncoded());
final Peer peer = certsToPeers.get(base64Cert);
if (peer == null) {
log.error("No matching peer for cert: {} in {}", base64Cert,
certsToPeers);
return;
}
log.debug("Found peer by certificate!!!");
peer.setMode(Mode.get);
updatePeer(peer, (InetSocketAddress)channel.getRemoteAddress(),
Type.pc, counter);
} catch (final CertificateEncodingException e) {
log.error("Could not encode certificate?", e);
}
}
} |
package org.lightmare.ejb;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.handlers.BeanHandlerFactory;
import org.lightmare.ejb.handlers.BeanLocalHandlerFactory;
import org.lightmare.ejb.handlers.RestHandler;
import org.lightmare.ejb.handlers.RestHandlerFactory;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.RpcUtils;
import org.lightmare.utils.StringUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Connector class for get EJB beans or call remote procedure in this bean (RPC)
* by interface class
*
* @author Levan
* @since 0.0.15-SNAPSHOT
*/
public class EjbConnector {
/**
* Gets {@link MetaData} from {@link MetaContainer} if it is not locked or
* waits while {@link MetaData#isInProgress()} is true
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
private MetaData getMeta(String beanName) throws IOException {
MetaData metaData = MetaContainer.getSyncMetaData(beanName);
return metaData;
}
/**
* Gets connection for {@link javax.ejb.Stateless} bean {@link Class} from
* cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactory(ConnectionData connection)
throws IOException {
if (connection.getEmf() == null) {
String unitName = connection.getUnitName();
if (StringUtils.valid(unitName)) {
ConnectionSemaphore semaphore = ConnectionContainer
.getConnection(unitName);
connection.setConnection(semaphore);
}
}
}
/**
* Gets connections for {@link Stateless} bean {@link Class} from cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactories(MetaData metaData)
throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
setEntityManagerFactory(connection);
}
}
}
/**
* Instantiates bean by class
*
* @param metaData
* @return <code>T</code> Bean instance
* @throws IOException
*/
private <T> T getBeanInstance(MetaData metaData) throws IOException {
T beanInstance;
Class<? extends T> beanClass = ObjectUtils
.cast(metaData.getBeanClass());
beanInstance = MetaUtils.instantiate(beanClass);
return beanInstance;
}
/**
* Creates {@link InvocationHandler} implementation for server mode
*
* @param metaData
* @return {@link InvocationHandler}
* @throws IOException
*/
private <T> BeanHandler getBeanHandler(MetaData metaData)
throws IOException {
BeanHandler handler;
T beanInstance = getBeanInstance(metaData);
// Caches EnriryManagerFactory instances in MetaData if they are not
// cached yet
setEntityManagerFactories(metaData);
// Initializes BeanHandler instance and caches it in MetaData if it was
// not cached yet
handler = BeanHandlerFactory.get(metaData, beanInstance);
return handler;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaces
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T>[] interfaces,
InvocationHandler handler, ClassLoader loader) {
T beanInstance;
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
} else {
LibraryLoader.loadCurrentLibraries(loader);
}
Object instance = Proxy.newProxyInstance(loader, interfaces, handler);
beanInstance = ObjectUtils.cast(instance);
return beanInstance;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaceClass
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T> interfaceClass,
InvocationHandler handler, ClassLoader loader) {
T beanInstance;
Class<T>[] interfaceArray = ObjectUtils
.cast(new Class<?>[] { interfaceClass });
beanInstance = instatiateBean(interfaceArray, handler, loader);
return beanInstance;
}
/**
* Initializes and caches all interfaces for bean class from passed
* {@link MetaData} instance if it is not already cached
*
* @param metaData
* @return {@link Class}[]
*/
private Class<?>[] setInterfaces(MetaData metaData) {
Class<?>[] interfaceClasses = metaData.getInterfaceClasses();
if (CollectionUtils.invalid(interfaceClasses)) {
List<Class<?>> interfacesList = new ArrayList<Class<?>>();
Class<?>[] interfaces = metaData.getLocalInterfaces();
if (CollectionUtils.valid(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
interfaces = metaData.getRemoteInterfaces();
if (CollectionUtils.valid(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
int size = interfacesList.size();
interfaceClasses = interfacesList.toArray(new Class[size]);
metaData.setInterfaceClasses(interfaceClasses);
}
return interfaceClasses;
}
/**
* Creates appropriate bean {@link Proxy} instance by passed
* {@link MetaData} parameter
*
* @param metaData
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(MetaData metaData) throws IOException {
T beanInstance;
InvocationHandler handler = getBeanHandler(metaData);
Class<?>[] interfaces = setInterfaces(metaData);
Class<T>[] typedInterfaces = ObjectUtils.cast(interfaces);
ClassLoader loader = metaData.getLoader();
beanInstance = instatiateBean(typedInterfaces, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface {@link Class} instance
*
* @param interfaceClass
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, Class<T> interfaceClass,
Object... rpcArgs) throws IOException {
T beanInstance;
InvocationHandler handler;
ClassLoader loader;
if (Configuration.isServer()) {
MetaData metaData = getMeta(beanName);
setInterfaces(metaData);
handler = getBeanHandler(metaData);
loader = metaData.getLoader();
} else {
if (rpcArgs.length == RpcUtils.RPC_ARGS_LENGTH) {
handler = BeanLocalHandlerFactory.get(rpcArgs);
loader = null;
} else {
throw new IOException(RpcUtils.RPC_ARGS_ERROR);
}
}
beanInstance = instatiateBean(interfaceClass, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface name
*
* @param beanName
* @param interfaceName
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, String interfaceName,
Object... rpcArgs) throws IOException {
T beanInstance;
MetaData metaData = getMeta(beanName);
ClassLoader loader = metaData.getLoader();
Class<?> classForName = MetaUtils.classForName(interfaceName,
Boolean.FALSE, loader);
Class<T> interfaceClass = ObjectUtils.cast(classForName);
beanInstance = connectToBean(beanName, interfaceClass, rpcArgs);
return beanInstance;
}
/**
* Creates {@link RestHandler} instance for invoking bean methods by REST
* services
*
* @param metaData
* @return {@link RestHandler}
* @throws IOException
*/
public <T> RestHandler<T> createRestHandler(MetaData metaData)
throws IOException {
RestHandler<T> restHandler;
BeanHandler handler = getBeanHandler(metaData);
Class<T> beanClass = ObjectUtils.cast(metaData.getBeanClass());
T beanInstance = MetaUtils.instantiate(beanClass);
restHandler = RestHandlerFactory.get(handler, beanInstance);
return restHandler;
}
} |
package com.pannny.view;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
@SuppressWarnings("unused")
public class StretchCardView extends CardView {
/**
* Title view.
*/
private TextView titleView;
/**
* parent is LinearLayout and weight > 0.
*/
private boolean parentHasWeight = false;
/**
* Title text "title" by default.
*/
private static final String DEFAULT_TITLE_TEXT = "title";
/**
* stretch state.
*/
private boolean stretch = true;
/**
* title view height.
*/
private int titleHeight;
/**
* animation cost time.
*/
private static final int ANIMATION_DURATION = 300;
/**
* for before api21, open state title background drawable.
*/
private GradientDrawable normalDrawable;
/**
* for before api21, close state title background drawable.
*/
private GradientDrawable tinyDrawable;
/**
* title background color.
*/
private int titleBackgroundColor;
/**
* stretch callback.
*/
private StretchListener stretchListener;
/**
* when attach to window, the StretchCardView's height.
*/
private int normalHeight;
/**
* children margin to top
*/
private int childTopMargin = 0;
/**
* when parent layout is LinearLayout,set min weight for animation.
*/
private float minWeight = 1;
/**
* when parent layout is LinearLayout,set normal weight for animation.
*/
private float normalWeight = 1;
/**
* title can be touched or not..
*/
private boolean titleTouchAble = true;
/**
* title view
*/
private static final int SELF_CHILDREN_COUNT = 1;
private StretchCard stretchCard;
public StretchCardView(Context context) {
super(context);
initialize(context, null);
}
public StretchCardView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs);
}
public StretchCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs);
}
private void initialize(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT >= 21) {
stretchCard = new StretchCardApi21Impl();
} else {
stretchCard = new StretchCardImpl();
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StretchCardView);
TypedArray card = context.obtainStyledAttributes(attrs, android.support.v7.cardview.R.styleable.CardView);
initTitleView(context, a, card);
a.recycle();
card.recycle();
addView(titleView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
private void initTitleView(Context context, TypedArray typedArray, TypedArray cardTypeArray) {
titleView = new TextView(context);
//set title text
String titleText = typedArray.getString(R.styleable.StretchCardView_stretchCardTitleText);
if (titleText == null) {
titleText = DEFAULT_TITLE_TEXT;
}
titleView.setText(titleText);
//set title text color. default by white.
if (typedArray.hasValue(R.styleable.StretchCardView_stretchCardTitleTextColor)) {
ColorStateList titleTextColor = typedArray.getColorStateList(R.styleable.StretchCardView_stretchCardTitleTextColor);
titleView.setTextColor(titleTextColor);
} else {
titleView.setTextColor(Color.WHITE);
}
//set title background. color primary by default.
if (typedArray.hasValue(R.styleable.StretchCardView_stretchCardTitleBackgroundColor)) {
ColorStateList titleTextColor = typedArray.getColorStateList(R.styleable.StretchCardView_stretchCardTitleBackgroundColor);
titleBackgroundColor = titleTextColor == null ? ContextCompat.getColor(context, R.color.colorPrimary) : titleTextColor.getDefaultColor();
} else {
titleBackgroundColor = ContextCompat.getColor(context, R.color.colorPrimary);
}
titleView.setBackgroundColor(titleBackgroundColor);
//set title text size. 6sp by default.
int titleTextSize = typedArray.getDimensionPixelSize(R.styleable.StretchCardView_stretchCardTitleTextSize, getResources().getDimensionPixelSize(R.dimen.stretch_card_view_title_text_size));
titleView.setTextSize(titleTextSize);
titleView.setPadding((int) getResources().getDimension(R.dimen.custom_title_text_padding_left), (int) getResources().getDimension(R.dimen.custom_title_text_padding), 0, (int) getResources().getDimension(R.dimen.custom_title_text_padding));
//set corner radius
int titleH = (titleTextSize + titleView.getPaddingTop() + titleView.getPaddingBottom());
int cornerRadius = cardTypeArray.getDimensionPixelSize(android.support.v7.cardview.R.styleable.CardView_cardCornerRadius, getResources().getDimensionPixelSize(R.dimen.stretch_card_view_corner_radius));
initRadius(titleH, cornerRadius);
//set title view elevation.
stretchCard.initTitle(this, titleView, normalDrawable);
titleView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickTitle();
}
});
}
/**
* set CardView's corner radius.
*
* @param radius corner radius
*/
@Override
public void setRadius(float radius) {
setGradientDrawables(radius);
super.setRadius(radius);
}
private void initRadius(int titleHeight, int cornerRadius) {
if (cornerRadius > titleHeight && titleHeight != 0) {
cornerRadius = (titleHeight) / 2;
}
setGradientDrawables(cornerRadius);
setRadius(cornerRadius);
}
private void setGradientDrawables(float radius) {
if (normalDrawable == null) {
normalDrawable = new GradientDrawable();
}
normalDrawable.setCornerRadii(new float[]{radius, radius, radius, radius, 0, 0, 0, 0});
normalDrawable.setColor(titleBackgroundColor);
if (tinyDrawable == null) {
tinyDrawable = new GradientDrawable();
}
tinyDrawable.setCornerRadius(radius);
tinyDrawable.setColor(titleBackgroundColor);
}
private void titleCallback() {
if (stretchListener == null) {
return;
}
//title can not click will go here
if (!titleTouchAble) {
stretchListener.onStretchBlocked(stretch);
return;
}
// start stretch
stretchListener.onStretchChangedListener(stretch);
}
public void setTitleBackgroundColor(int color) {
titleBackgroundColor = color;
normalDrawable.setColor(color);
tinyDrawable.setColor(color);
}
private void trigger() {
if (!titleTouchAble)
return;
stretch = !stretch;
final ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (stretch) {//stretch out
ValueAnimator valueAnimator;
if (parentHasWeight) {
valueAnimator = ValueAnimator.ofFloat(minWeight, normalWeight).setDuration(ANIMATION_DURATION);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
((LinearLayout.LayoutParams) layoutParams).weight = (float) animation.getAnimatedValue();
setLayoutParams(layoutParams);
}
});
} else {
valueAnimator = ValueAnimator.ofInt(titleHeight, normalHeight).setDuration(ANIMATION_DURATION);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.height = (int) animation.getAnimatedValue();
requestLayout();
}
});
}
//before 5.0 ,set title corner.
stretchCard.onAnimationStart(valueAnimator, titleView, normalDrawable);
valueAnimator.start();
} else {//close
ValueAnimator valueAnimator;
if (parentHasWeight) {
valueAnimator = ValueAnimator.ofFloat(normalWeight, minWeight).setDuration(ANIMATION_DURATION);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
((LinearLayout.LayoutParams) layoutParams).weight = (float) animation.getAnimatedValue();
setLayoutParams(layoutParams);
}
});
} else {
valueAnimator = ValueAnimator.ofInt(normalHeight, titleHeight + getPaddingBottom() + getPaddingTop()).setDuration(ANIMATION_DURATION);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.height = (int) animation.getAnimatedValue();
requestLayout();
}
});
}
//before 5.0 ,set title corner.
stretchCard.onAnimationEnd(valueAnimator, titleView, tinyDrawable);
valueAnimator.start();
}
}
synchronized final public void clickTitle() {
trigger();
titleCallback();
}
private void setChildTopMargin() {
childTopMargin = titleView.getHeight();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
titleHeight = getTitleHeight();
setChildTopMargin();
int count = getChildCount();
//except title view.
for (int i = 1; i < count; i++) {
final View child = getChildAt(i);
final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams();
lp.topMargin = childTopMargin;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initNormalHeight() {
if (normalHeight > titleHeight) {
return;
}
normalHeight = this.getMeasuredHeight();
setParentHasWeight();
}
public void setNormalHeight(int height) {
if (height > titleHeight) {
normalHeight = height;
} else {
throw new IllegalArgumentException("Normal height must grater than title height.");
}
}
private int getTitleHeight() {
return titleView.getHeight();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int height = titleView != null && titleView.getVisibility() != View.GONE ? titleView.getHeight() : 0;
super.onLayout(changed, left, top + height, right, bottom);
initNormalHeight();
}
/**
* set title text.
*
* @param titleText title
*/
public void setTitleText(String titleText) {
if (titleView != null)
titleView.setText(titleText);
}
/**
* get title text.
*
* @return title string
*/
public String getTitleText() {
return titleView == null ? "" : titleView.getText().toString();
}
/**
* @return title can be touched.
*/
public boolean getTitleTouchAble() {
return titleTouchAble;
}
/**
* set title touchable
*
* @param able touchable
*/
public void setTitleTouchAble(boolean able) {
titleTouchAble = able;
}
@Override
protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params) {
return super.addViewInLayout(child, index + SELF_CHILDREN_COUNT, params);
}
@Override
protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) {
return super.addViewInLayout(child, index + SELF_CHILDREN_COUNT, params, preventRequestLayout);
}
@Override
public int indexOfChild(View child) {
return super.indexOfChild(child) - SELF_CHILDREN_COUNT;
}
@Override
public int getChildCount() {
return super.getChildCount() - SELF_CHILDREN_COUNT;
}
@Override
public View getChildAt(int index) {
return super.getChildAt(index + SELF_CHILDREN_COUNT);
}
@Override
public void removeViews(int start, int count) {
super.removeViews(start + SELF_CHILDREN_COUNT, count);
}
@Override
public void removeViewsInLayout(int start, int count) {
super.removeViewsInLayout(start + SELF_CHILDREN_COUNT, count);
}
@Override
protected void detachViewsFromParent(int start, int count) {
super.detachViewsFromParent(start + SELF_CHILDREN_COUNT, count);
}
/**
* if parent is instance of LinearLayout ,set parentHasWeight, normalWeight and minWeight.
*/
private void setParentHasWeight() {
if (getParent() instanceof LinearLayout && ((LinearLayout.LayoutParams) (getLayoutParams())).weight > 0) {
parentHasWeight = true;
normalWeight = ((LinearLayout.LayoutParams) (getLayoutParams())).weight;
float otherWeight = 0;
int count = ((LinearLayout) getParent()).getChildCount();
for (int i = 0; i < count; i++) {
View v = ((LinearLayout) getParent()).getChildAt(i);
if (v.equals(this)) {
continue;
}
otherWeight += ((LinearLayout.LayoutParams) (v.getLayoutParams())).weight;
}
float weightOfSelf = ((LinearLayout.LayoutParams) (getLayoutParams())).weight * (getTitleHeight() + getPaddingBottom() + getPaddingTop()) / (normalHeight);
minWeight = weightOfSelf * (otherWeight / ((normalWeight - weightOfSelf) + otherWeight));
}
}
/**
* get event listener.
*
* @return instance
*/
public StretchListener getStretchListener() {
return stretchListener;
}
/**
* set event listener.
*
* @param stretchListener instance
*/
public void setStretchListener(StretchListener stretchListener) {
this.stretchListener = stretchListener;
}
public interface StretchListener {
/**
* stretch state changed will call this.
*
* @param stretch true:hide to show ; false: show to hide
*/
void onStretchChangedListener(boolean stretch);
/**
* when cant stretch and user click title,will call this.
*
* @param stretch current state, true:show; false:hide
*/
void onStretchBlocked(boolean stretch);
}
} |
package org.lightmare.ejb;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.handlers.BeanHandlerFactory;
import org.lightmare.ejb.handlers.BeanLocalHandler;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.remote.rpc.RPCall;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.RpcUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Connector class for get ejb beans or call remote procedure in ejb bean (RPC)
* by interface class
*
* @author Levan
*
*/
public class EjbConnector {
/**
* Gets {@link MetaData} from {@link MetaContainer} if it is not locked or
* waits while {@link MetaData#isInProgress()} is true
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
private MetaData getMeta(String beanName) throws IOException {
MetaData metaData = MetaContainer.getSyncMetaData(beanName);
return metaData;
}
/**
* Gets connection for {@link javax.ejb.Stateless} bean {@link Class} from
* cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactory(ConnectionData connection)
throws IOException {
if (connection.getEmf() == null) {
String unitName = connection.getUnitName();
if (ObjectUtils.available(unitName)) {
ConnectionSemaphore semaphore = ConnectionContainer
.getConnection(unitName);
connection.setConnection(semaphore);
}
}
}
/**
* Gets connections for {@link Stateless} bean {@link Class} from cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactories(MetaData metaData)
throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (ObjectUtils.available(connections)) {
for (ConnectionData connection : connections) {
setEntityManagerFactory(connection);
}
}
}
/**
* Instantiates bean by class
*
* @param metaData
* @return Bean instance
* @throws IOException
*/
private <T> T getBeanInstance(MetaData metaData) throws IOException {
@SuppressWarnings("unchecked")
Class<? extends T> beanClass = (Class<? extends T>) metaData
.getBeanClass();
T beanInstance = MetaUtils.instantiate(beanClass);
return beanInstance;
}
/**
* Creates {@link InvocationHandler} implementation for server mode
*
* @param metaData
* @return {@link InvocationHandler}
* @throws IOException
*/
private <T> InvocationHandler getHandler(MetaData metaData)
throws IOException {
T beanInstance = getBeanInstance(metaData);
// Caches EnriryManagerFactory instances in MetaData if they are not
// cached yet
setEntityManagerFactories(metaData);
// Initializes BeanHandler instance and caches it in MetaData if it was
// not cached yet
BeanHandler handler = BeanHandlerFactory.get(metaData, beanInstance);
return handler;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaces
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T>[] interfaces,
InvocationHandler handler, ClassLoader loader) {
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
} else {
LibraryLoader.loadCurrentLibraries(loader);
}
@SuppressWarnings("unchecked")
T beanInstance = (T) Proxy
.newProxyInstance(loader, interfaces, handler);
return beanInstance;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaceClass
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T> interfaceClass,
InvocationHandler handler, ClassLoader loader) {
@SuppressWarnings("unchecked")
Class<T>[] interfaceArray = (Class<T>[]) new Class<?>[] { interfaceClass };
T beanInstance = instatiateBean(interfaceArray, handler, loader);
return beanInstance;
}
/**
* Initializes and caches all interfaces for bean class from passed
* {@link MetaData} instance if it is not already cached
*
* @param metaData
* @return {@link Class}[]
*/
private Class<?>[] setInterfaces(MetaData metaData) {
Class<?>[] interfaceClasses = metaData.getInterfaceClasses();
if (ObjectUtils.notAvailable(interfaceClasses)) {
List<Class<?>> interfacesList = new ArrayList<Class<?>>();
Class<?>[] interfaces = metaData.getLocalInterfaces();
if (ObjectUtils.available(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
interfaces = metaData.getRemoteInterfaces();
if (ObjectUtils.available(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
int size = interfacesList.size();
interfaceClasses = interfacesList.toArray(new Class[size]);
metaData.setInterfaceClasses(interfaceClasses);
}
return interfaceClasses;
}
/**
* Creates appropriate bean {@link Proxy} instance by passed
* {@link MetaData} parameter
*
* @param metaData
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
@SuppressWarnings("unchecked")
public <T> T connectToBean(MetaData metaData) throws IOException {
InvocationHandler handler = getHandler(metaData);
Class<?>[] interfaces = setInterfaces(metaData);
ClassLoader loader = metaData.getLoader();
T beanInstance = (T) instatiateBean((Class<T>[]) interfaces, handler,
loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface {@link Class} instance
*
* @param interfaceClass
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, Class<T> interfaceClass,
Object... rpcArgs) throws IOException {
InvocationHandler handler;
ClassLoader loader;
if (Configuration.isServer()) {
MetaData metaData = getMeta(beanName);
setInterfaces(metaData);
handler = getHandler(metaData);
loader = metaData.getLoader();
} else {
if (rpcArgs.length == RpcUtils.RPC_ARGS_LENGTH) {
String host = (String) rpcArgs[0];
int port = (Integer) rpcArgs[1];
RPCall call = new RPCall(host, port);
handler = new BeanLocalHandler(call);
loader = null;
} else {
throw new IOException(RpcUtils.RPC_ARGS_ERROR);
}
}
T beanInstance = (T) instatiateBean(interfaceClass, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface name
*
* @param beanName
* @param interfaceName
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, String interfaceName,
Object... rpcArgs) throws IOException {
MetaData metaData = getMeta(beanName);
ClassLoader loader = metaData.getLoader();
@SuppressWarnings("unchecked")
Class<T> interfaceClass = (Class<T>) MetaUtils.classForName(
interfaceName, Boolean.FALSE, loader);
T beanInstance = (T) connectToBean(beanName, interfaceClass);
return beanInstance;
}
} |
package com.tylersuehr.library;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import com.tylersuehr.library.data.Chip;
public class ChipView extends FrameLayout {
private CircleImageView mAvatarImageView;
private ImageButton mButtonDelete;
private TextView mTitleView;
private ColorStateList mLabelColor;
private String mLabel;
private boolean mHasAvatarIcon = false;
private Drawable mAvatarIconDrawable;
private Uri mAvatarIconUri;
private boolean mDeletable = false;
private Drawable mDeleteIcon;
private ColorStateList mDeleteIconColor;
private ColorStateList mBackgroundColor;
private LetterTileProvider mLetterTileProvider;
private Chip mChip;
public ChipView(@NonNull Context context) {
this(context, null);
}
public ChipView(@NonNull Context c, @Nullable AttributeSet attrs) {
super(c, attrs);
// Inflate the layout
inflate(c, R.layout.chip_view, this);
this.mAvatarImageView = findViewById(R.id.icon);
this.mTitleView = findViewById(R.id.label);
this.mButtonDelete = findViewById(R.id.delete_button);
this.mLetterTileProvider = new LetterTileProvider(c);
}
/**
* Sets properties from a chip.
* @param chip {@link Chip}
*/
public void inflateWithChip(Chip chip) {
this.mChip = chip;
this.mLabel = mChip.getTitle();
this.mAvatarIconUri = mChip.getAvatarUri();
this.mAvatarIconDrawable = mChip.getAvatarDrawable();
inflateWithAttributes();
}
/**
* Sets properties from the set XML attributes.
*/
private void inflateWithAttributes() {
setLabel(mLabel);
if (mLabelColor != null) {
setLabelColor(mLabelColor);
}
setHasAvatarIcon(mHasAvatarIcon);
setDeletable(mDeletable);
if (mBackgroundColor != null) {
setChipBackgroundColor(mBackgroundColor);
}
}
public String getLabel() {
return mLabel;
}
public void setLabel(String label) {
this.mLabel = label;
this.mTitleView.setText(label);
}
public void setLabelColor(ColorStateList color) {
this.mLabelColor = color;
this.mTitleView.setTextColor(color);
}
public void setLabelColor(@ColorInt int color) {
this.mLabelColor = ColorStateList.valueOf(color);
this.mTitleView.setTextColor(color);
}
/**
* Show or hide the avatar icon.
* @param hasAvatarIcon True if avatar icon should be shown
*/
public void setHasAvatarIcon(boolean hasAvatarIcon) {
this.mHasAvatarIcon = hasAvatarIcon;
if (hasAvatarIcon) { // Show the avatar icon
this.mAvatarImageView.setVisibility(VISIBLE);
// Adjust label's padding
if (mButtonDelete.getVisibility() == VISIBLE) {
this.mTitleView.setPadding(Utils.dp(8), 0, 0, 0);
} else {
this.mTitleView.setPadding(Utils.dp(8), 0, Utils.dp(12), 0);
}
// Set the avatar icon
if (mAvatarIconUri != null) { // Use the URI
this.mAvatarImageView.setImageURI(mAvatarIconUri);
} else if (mAvatarIconDrawable != null) { // Use the Drawable
this.mAvatarImageView.setImageDrawable(mAvatarIconDrawable);
} else { // Use the tile provider
this.mAvatarImageView.setImageBitmap(mLetterTileProvider.getLetterTile(getLabel()));
}
} else { // Hide the avatar icon
this.mAvatarImageView.setVisibility(GONE);
// Adjust label's padding
if(mButtonDelete.getVisibility() == VISIBLE) {
this.mTitleView.setPadding(Utils.dp(12), 0, 0, 0);
} else {
this.mTitleView.setPadding(Utils.dp(12), 0, Utils.dp(12), 0);
}
}
}
public void setAvatarIcon(Drawable avatarIcon) {
this.mAvatarIconDrawable = avatarIcon;
this.mHasAvatarIcon = true;
inflateWithAttributes();
}
public void setAvatarIcon(Uri avatarUri) {
this.mAvatarIconUri = avatarUri;
this.mHasAvatarIcon = true;
inflateWithAttributes();
}
/**
* Show or hide the delete button.
* @param deletable True if delete button should be shown
*/
public void setDeletable(boolean deletable) {
this.mDeletable = deletable;
if (deletable) { // Show the delete button
this.mButtonDelete.setVisibility(VISIBLE);
// Adjust label's padding
if (mAvatarImageView.getVisibility() == VISIBLE) {
this.mTitleView.setPadding(Utils.dp(8), 0, 0, 0);
} else {
this.mTitleView.setPadding(Utils.dp(12), 0, 0, 0);
}
// Set the delete icon
if (mDeleteIcon != null) {
this.mButtonDelete.setImageDrawable(mDeleteIcon);
}
if (mDeleteIconColor != null) {
this.mButtonDelete.getDrawable().mutate().setColorFilter(mDeleteIconColor.getDefaultColor(), PorterDuff.Mode.SRC_ATOP);
}
} else { // Hide the delete button
this.mButtonDelete.setVisibility(GONE);
// Adjust label's padding
if (mAvatarImageView.getVisibility() == VISIBLE) {
this.mTitleView.setPadding(Utils.dp(8), 0, Utils.dp(12), 0);
} else {
this.mTitleView.setPadding(Utils.dp(12), 0, Utils.dp(12), 0);
}
}
}
public void setDeleteIconColor(ColorStateList color) {
this.mDeleteIconColor = color;
this.mDeletable = true;
inflateWithAttributes();
}
public void setDeleteIconColor(@ColorInt int color) {
this.mDeleteIconColor = ColorStateList.valueOf(color);
this.mDeletable = true;
inflateWithAttributes();
}
public void setDeleteIcon(Drawable deleteIcon) {
this.mDeleteIcon = deleteIcon;
this.mDeletable = true;
inflateWithAttributes();
}
public void setChipBackgroundColor(ColorStateList color) {
this.mBackgroundColor = color;
setChipBackgroundColor(color.getDefaultColor());
}
public void setChipBackgroundColor(@ColorInt int color) {
this.mBackgroundColor = ColorStateList.valueOf(color);
getChildAt(0).getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
/**
* Set the chip object.
* @param chip the chip
*/
public void setChip(Chip chip) {
this.mChip = chip;
}
/**
* Sets an OnClickListener on the ChipView itself.
* @param onClickListener {@link OnClickListener}
*/
public void setOnChipClicked(OnClickListener onClickListener) {
getChildAt(0).setOnClickListener(onClickListener);
}
/**
* Sets an OnClickListener on the delete button.
* @param onClickListener {@link OnClickListener}
*/
public void setOnDeleteClicked(OnClickListener onClickListener) {
this.mButtonDelete.setOnClickListener(onClickListener);
}
/**
* Builder class
*/
static class Builder {
private Context context;
private String label;
private ColorStateList labelColor;
private Uri avatarIconUri;
private Drawable avatarIconDrawable;
private boolean hasAvatarIcon = false;
private boolean deletable = false;
private Drawable deleteIcon;
private ColorStateList deleteIconColor;
private ColorStateList backgroundColor;
private Chip chip;
Builder(Context context) {
this.context = context;
}
Builder label(String label) {
this.label = label;
return this;
}
Builder labelColor(ColorStateList labelColor) {
this.labelColor = labelColor;
return this;
}
Builder hasAvatarIcon(boolean hasAvatarIcon) {
this.hasAvatarIcon = hasAvatarIcon;
return this;
}
Builder avatarIcon(Uri avatarUri) {
this.avatarIconUri = avatarUri;
return this;
}
Builder avatarIcon(Drawable avatarIcon) {
this.avatarIconDrawable = avatarIcon;
return this;
}
Builder deletable(boolean deletable) {
this.deletable = deletable;
return this;
}
Builder deleteIcon(Drawable deleteIcon) {
this.deleteIcon = deleteIcon;
return this;
}
Builder deleteIconColor(ColorStateList deleteIconColor) {
this.deleteIconColor = deleteIconColor;
return this;
}
Builder backgroundColor(ColorStateList backgroundColor) {
this.backgroundColor = backgroundColor;
return this;
}
Builder chip(Chip chip) {
this.chip = chip;
this.label = chip.getTitle();
this.avatarIconDrawable = chip.getAvatarDrawable();
this.avatarIconUri = chip.getAvatarUri();
return this;
}
ChipView build() {
return newInstance(this);
}
}
private static ChipView newInstance(Builder builder) {
ChipView chipView = new ChipView(builder.context);
chipView.mLabel = builder.label;
chipView.mLabelColor = builder.labelColor;
chipView.mHasAvatarIcon = builder.hasAvatarIcon;
chipView.mAvatarIconUri = builder.avatarIconUri;
chipView.mAvatarIconDrawable = builder.avatarIconDrawable;
chipView.mDeletable = builder.deletable;
chipView.mDeleteIcon = builder.deleteIcon;
chipView.mDeleteIconColor = builder.deleteIconColor;
chipView.mBackgroundColor = builder.backgroundColor;
chipView.mChip = builder.chip;
chipView.inflateWithAttributes();
return chipView;
}
} |
package org.restheart.db;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
import org.restheart.utils.HttpStatus;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Deque;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Data Access Object for the mongodb Collection resource. NOTE: this class
* is package-private and only meant to be used as a delagate within the DbsDAO
* class.
*
* @author Andrea Di Cesare <andrea@softinstigate.com>
*/
class CollectionDAO {
private final MongoClient client;
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionDAO.class);
private static final BasicDBObject fieldsToReturn;
CollectionDAO(MongoClient client) {
this.client = client;
}
static {
fieldsToReturn = new BasicDBObject();
fieldsToReturn.put("_id", 1);
fieldsToReturn.put("_created_on", 1);
}
/**
* Checks if the collection exists.
*
* WARNING: slow method. perf tests show this can take up to 35% overall
* requests processing time when getting data from a collection
*
* @deprecated
* @param dbName the database name of the collection
* @param collName the collection name
* @return true if the specified collection exits in the db dbName
*/
boolean doesCollectionExist(String dbName, String collName) {
if (dbName == null || dbName.isEmpty() || dbName.contains(" ")) {
return false;
}
BasicDBObject query = new BasicDBObject("name", dbName + "." + collName);
return client.getDB(dbName).getCollection("system.namespaces").findOne(query) != null;
}
/**
* Returns the mongodb DBCollection object for the collection in db dbName.
*
* @param dbName the database name of the collection the database name of
* the collection
* @param collName the collection name
* @return the mongodb DBCollection object for the collection in db dbName
*/
DBCollection getCollection(String dbName, String collName) {
return client.getDB(dbName).getCollection(collName);
}
/**
* Checks if the given collection is empty. Note that RESTHeart creates a
* reserved properties document in every collection (with _id
* '_properties'). This method returns true even if the collection contains
* such document.
*
* @param coll the mongodb DBCollection object
* @return true if the commection is empty
*/
public boolean isCollectionEmpty(DBCollection coll) {
return coll.count() == 0;
}
/**
* Returns the number of documents in the given collection (taking into
* account the filters in case).
*
* @param coll the mongodb DBCollection object.
* @param filters the filters to apply. it is a Deque collection of mongodb
* query conditions.
* @return the number of documents in the given collection (taking into
* account the filters in case)
*/
public long getCollectionSize(DBCollection coll, Deque<String> filters) {
final BasicDBObject query = new BasicDBObject();
if (filters != null) {
try {
filters.stream().forEach(f -> {
query.putAll((BSONObject) JSON.parse(f)); // this can throw JSONParseException for invalid filter parameters
});
} catch (JSONParseException jpe) {
LOGGER.warn("****** error parsing filter expression {}", filters, jpe);
}
}
return coll.count(query);
}
/**
* Returs the DBCursor of the collection applying sorting and filtering.
*
* @param coll the mongodb DBCollection object
* @param sortBy the Deque collection of fields to use for sorting (prepend
* field name with - for descending sorting)
* @param filters the filters to apply. it is a Deque collection of mongodb
* query conditions.
* @return
* @throws JSONParseException
*/
DBCursor getCollectionDBCursor(DBCollection coll, Deque<String> sortBy, Deque<String> filters) throws JSONParseException {
// apply sort_by
DBObject sort = new BasicDBObject();
if (sortBy == null || sortBy.isEmpty()) {
sort.put("_id", -1);
} else {
sortBy.stream().forEach((s) -> {
String _s = s.trim(); // the + sign is decoded into a space, in case remove it
if (_s.startsWith("-")) {
sort.put(_s.substring(1), -1);
} else if (_s.startsWith("+")) {
sort.put(_s.substring(1), 1);
} else {
sort.put(_s, 1);
}
});
}
// apply filter
final BasicDBObject query = new BasicDBObject();
if (filters != null) {
filters.stream().forEach((String f) -> {
BSONObject filterQuery = (BSONObject) JSON.parse(f);
query.putAll(filterQuery); // this can throw JSONParseException for invalid filter parameters
});
}
return coll.find(query).sort(sort);
}
ArrayList<DBObject> getCollectionData(
DBCollection coll,
int page,
int pagesize,
Deque<String> sortBy,
Deque<String> filters,
DBCursorPool.EAGER_CURSOR_ALLOCATION_POLICY eager) throws JSONParseException {
ArrayList<DBObject> ret = new ArrayList<>();
int toskip = pagesize * (page - 1);
DBCursor cursor;
SkippedDBCursor _cursor = null;
if (eager != DBCursorPool.EAGER_CURSOR_ALLOCATION_POLICY.NONE) {
_cursor = DBCursorPool.getInstance().get(new DBCursorPoolEntryKey(coll, sortBy, filters, toskip, 0), eager);
}
int alreadySkipped;
// in case there is not cursor in the pool to reuse
if (_cursor == null) {
cursor = getCollectionDBCursor(coll, sortBy, filters);
alreadySkipped = 0;
} else {
cursor = _cursor.getCursor();
alreadySkipped = _cursor.getAlreadySkipped();
}
if (toskip - alreadySkipped > 0) {
cursor.skip(toskip - alreadySkipped);
}
while (pagesize > 0 && cursor.hasNext()) {
ret.add(cursor.next());
pagesize
}
// add the _lastupdated_on and _created_on
ret.forEach(row -> {
Object etag = row.get("_etag");
if (row.get("_lastupdated_on") == null && etag != null && etag instanceof ObjectId) {
row.put("_lastupdated_on", Instant.ofEpochSecond(((ObjectId) etag).getTimestamp()).toString());
}
Object id = row.get("_id");
// generate the _created_on timestamp from the _id if this is an instance of ObjectId
if (row.get("_created_on") == null && id != null && id instanceof ObjectId) {
row.put("_created_on", Instant.ofEpochSecond(((ObjectId) id).getTimestamp()).toString());
}
}
);
return ret;
}
/**
* Returns the collection properties document.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @return the collection properties document
*/
public DBObject getCollectionProps(String dbName, String collName, boolean fixMissingProperties) {
DBCollection propsColl = getCollection(dbName, "_properties");
DBObject properties = propsColl.findOne(new BasicDBObject("_id", "_properties.".concat(collName)));
if (properties != null) {
properties.put("_id", collName);
Object etag = properties.get("_etag");
if (etag != null && etag instanceof ObjectId) {
properties.put("_lastupdated_on", Instant.ofEpochSecond(((ObjectId) etag).getTimestamp()).toString());
}
} else if (fixMissingProperties) {
new PropsFixer().addCollectionProps(dbName, collName);
return getCollectionProps(dbName, collName, false);
}
return properties;
}
/**
* Upsert the collection properties.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @param content the new collection properties
* @param etag the entity tag. must match to allow actual write (otherwise
* http error code is returned)
* @param updating true if updating existing document
* @param patching true if use patch semantic (update only specified fields)
* @return the HttpStatus code to set in the http response
*/
int upsertCollection(String dbName, String collName, DBObject content, ObjectId etag, boolean updating, boolean patching) {
DB db = client.getDB(dbName);
DBCollection propsColl = db.getCollection("_properties");
if (patching && !updating) {
return HttpStatus.SC_NOT_FOUND;
}
if (updating) {
if (etag == null) {
return HttpStatus.SC_CONFLICT;
}
BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties.".concat(collName));
idAndEtagQuery.append("_etag", etag);
if (propsColl.count(idAndEtagQuery) < 1) {
return HttpStatus.SC_PRECONDITION_FAILED;
}
}
ObjectId timestamp = new ObjectId();
Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());
if (content == null) {
content = new BasicDBObject();
}
content.removeField("_id"); // make sure we don't change this field
if (updating) {
content.removeField("_crated_on"); // don't allow to update this field
content.put("_etag", timestamp);
} else {
content.put("_id", "_properties.".concat(collName));
content.put("_created_on", now.toString());
content.put("_etag", timestamp);
}
if (patching) {
propsColl.update(new BasicDBObject("_id", "_properties.".concat(collName)), new BasicDBObject("$set", content), true, false);
return HttpStatus.SC_OK;
} else {
// we use findAndModify to get the @created_on field value from the existing properties document
// we need to put this field back using a second update
// it is not possible in a single update even using $setOnInsert update operator
// in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic)
DBObject old = propsColl.findAndModify(new BasicDBObject("_id", "_properties.".concat(collName)), fieldsToReturn, null, false, content, false, true);
if (old != null) {
Object oldTimestamp = old.get("_created_on");
if (oldTimestamp == null) {
oldTimestamp = now.toString();
LOGGER.warn("properties of collection {} had no @created_on field. set it to now", dbName + "." + collName);
}
// need to readd the @created_on field
BasicDBObject createdContent = new BasicDBObject("_created_on", "" + oldTimestamp);
createdContent.markAsPartialObject();
propsColl.update(new BasicDBObject("_id", "_properties.".concat(collName)), new BasicDBObject("$set", createdContent), true, false);
return HttpStatus.SC_OK;
} else {
// need to readd the @created_on field
BasicDBObject createdContent = new BasicDBObject("_created_on", now.toString());
createdContent.markAsPartialObject();
propsColl.update(new BasicDBObject("_id", "_properties.".concat(collName)), new BasicDBObject("$set", createdContent), true, false);
initDefaultIndexes(db.getCollection(collName));
return HttpStatus.SC_CREATED;
}
}
}
/**
* Deletes a collection.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @param etag the entity tag. must match to allow actual write (otherwise
* http error code is returned)
* @return the HttpStatus code to set in the http response
*/
int deleteCollection(String dbName, String collName, ObjectId etag) {
DBCollection coll = getCollection(dbName, collName);
DBCollection propsColl = getCollection(dbName, "_properties");
BasicDBObject checkEtag = new BasicDBObject("_id", "_properties.".concat(collName));
checkEtag.append("_etag", etag);
DBObject exists = propsColl.findOne(checkEtag, fieldsToReturn);
if (exists == null) {
return HttpStatus.SC_PRECONDITION_FAILED;
} else {
propsColl.remove(new BasicDBObject("_id", "_properties.".concat(collName)));
coll.drop();
return HttpStatus.SC_NO_CONTENT;
}
}
private void initDefaultIndexes(DBCollection coll) {
coll.createIndex(new BasicDBObject("_id", 1).append("_etag", 1), new BasicDBObject("name", "_id_etag_idx"));
coll.createIndex(new BasicDBObject("_etag", 1), new BasicDBObject("name", "_etag_idx"));
}
} |
package org.scijava.object;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.scijava.util.ClassUtils;
/**
* Data structure for managing lists of registered objects.
* <p>
* The object index keeps lists of objects segregated by type. The type
* hierarchy beneath which each object is classified can be customized through
* subclassing (e.g., see {@link org.scijava.plugin.PluginIndex}), but by
* default, each registered object is added to all type lists with which its
* class is compatible. For example, an object of type {@link String} would be
* added to the following type lists: {@link String},
* {@link java.io.Serializable}, {@link Comparable}, {@link CharSequence} and
* {@link Object}. A subsequent request for all objects of type
* {@link Comparable} (via a call to {@link #get(Class)}) would return a list
* that includes the object.
* </p>
* <p>
* Note that similar to {@link List}, it is possible for the same object to be
* added to the index more than once, in which case it will appear on relevant
* type lists multiple times.
* </p>
* <p>
* Note that similar to {@link List}, it is possible for the same object to be
* added to the index more than once, in which case it will appear on compatible
* type lists multiple times.
* </p>
*
* @author Curtis Rueden
*/
public class ObjectIndex<E> implements Collection<E> {
/**
* "Them as counts counts moren them as dont count." <br>
* —Russell Hoban, <em>Riddley Walker</em>
*/
protected final Map<Class<?>, List<E>> hoard =
new ConcurrentHashMap<Class<?>, List<E>>();
private final Class<E> baseClass;
public ObjectIndex(final Class<E> baseClass) {
this.baseClass = baseClass;
}
// -- ObjectIndex methods --
/** Gets the base class of the items being managed. */
public Class<E> getBaseClass() {
return baseClass;
}
/**
* Gets a list of <em>all</em> registered objects.
*
* @return Read-only list of all registered objects, or an empty list if none
* (this method never returns null).
*/
public List<E> getAll() {
// NB: We return the special "All" list here, since in some cases,
// *no* other list contains *all* elements of the index.
// We cannot use Object.class, since interface type hierarchies do not
// extend Object. In particular, PluginIndex classifies objects beneath the
// SciJavaPlugin type hierarchy, which does not extend Object.
// And we cannot use getBaseClass() because the actual base class of the
// objects stored in the index may differ from the type hierarchy beneath
// which they are classified. In particular, PluginIndex classifies its
// PluginInfo objects beneath the SciJavaPlugin type hierarchy, and not that
// of PluginInfo.
return get(All.class);
}
/**
* Gets a list of registered objects compatible with the given type.
*
* @return New list of registered objects of the given type, or an empty
* list if no such objects exist (this method never returns null).
*/
public List<E> get(final Class<?> type) {
List<E> list = retrieveList(type);
// NB: Return a copy of the data, to facilitate thread safety.
list = new ArrayList<E>(list);
return list;
}
// -- Collection methods --
@Override
public int size() {
return getAll().size();
}
@Override
public boolean isEmpty() {
return getAll().isEmpty();
}
@Override
public boolean contains(final Object o) {
if (!getBaseClass().isAssignableFrom(o.getClass())) return false;
@SuppressWarnings("unchecked")
final E typedObj = (E) o;
final Class<?> type = getType(typedObj);
return get(type).contains(o);
}
@Override
public Iterator<E> iterator() {
return getAll().iterator();
}
@Override
public Object[] toArray() {
return getAll().toArray();
}
@Override
public <T> T[] toArray(final T[] a) {
return getAll().toArray(a);
}
@Override
public boolean add(final E o) {
return add(o, false);
}
@Override
public boolean remove(final Object o) {
return remove(o, false);
}
@Override
public boolean containsAll(final Collection<?> c) {
return getAll().containsAll(c);
}
@Override
public boolean addAll(final Collection<? extends E> c) {
boolean changed = false;
for (final E o : c) {
final boolean result = add(o, true);
if (result) changed = true;
}
return changed;
}
@Override
public boolean removeAll(final Collection<?> c) {
boolean changed = false;
for (final Object o : c) {
final boolean result = remove(o, true);
if (result) changed = true;
}
return changed;
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
hoard.clear();
}
// -- Object methods --
@Override
public String toString() {
final List<Class<?>> classes = new ArrayList<Class<?>>(hoard.keySet());
Collections.sort(classes, new Comparator<Class<?>>() {
@Override
public int compare(final Class<?> c1, final Class<?> c2) {
return ClassUtils.compare(c1, c2);
}
});
final String nl = System.getProperty("line.separator");
final StringBuilder sb = new StringBuilder();
for (final Class<?> c : classes) {
sb.append(c.getName() + ": {");
final List<E> list = hoard.get(c);
boolean first = true;
for (final E element : list) {
if (first) first = false;
else sb.append(", ");
sb.append(element);
}
sb.append("}" + nl);
}
return sb.toString();
}
// -- Internal methods --
/** Adds the object to all compatible type lists. */
protected boolean add(final E o, final boolean batch) {
return add(o, getType(o), batch);
}
/** Return the type by which to index the object. */
protected Class<?> getType(final E o) {
return o.getClass();
}
/** Removes the object from all compatible type lists. */
protected boolean remove(final Object o, final boolean batch) {
if (!getBaseClass().isAssignableFrom(o.getClass())) return false;
@SuppressWarnings("unchecked")
final E e = (E) o;
return remove(o, getType(e), batch);
}
private Map<Class<?>, List<E>[]> type2Lists =
new HashMap<Class<?>, List<E>[]>();
protected synchronized List<E>[] retrieveListsForType(final Class<?> type) {
final List<E>[] lists = type2Lists.get(type);
if (lists != null) return lists;
final ArrayList<List<E>> listOfLists = new ArrayList<List<E>>();
for (final Class<?> c : getTypes(type)) {
listOfLists.add(retrieveList(c));
}
// convert list of lists to array of lists
@SuppressWarnings("rawtypes")
final List[] arrayOfRawLists =
listOfLists.toArray(new List[listOfLists.size()]);
@SuppressWarnings({ "unchecked" })
final List<E>[] arrayOfLists = arrayOfRawLists;
type2Lists.put(type, arrayOfLists);
return arrayOfLists;
}
/** Adds an object to type lists beneath the given type hierarchy. */
@SuppressWarnings("unchecked")
protected boolean add(final E o, final Class<?> type, final boolean batch) {
boolean result = false;
for (final List<?> list : retrieveListsForType(type)) {
if (addToList(o, (List<E>)list, batch)) result = true;
}
return result;
}
/** Removes an object from type lists beneath the given type hierarchy. */
protected boolean remove(final Object o, final Class<?> type,
final boolean batch)
{
boolean result = false;
for (final List<E> list : retrieveListsForType(type)) {
if (removeFromList(o, list, batch)) result = true;
}
return result;
}
protected boolean addToList(final E obj, final List<E> list,
@SuppressWarnings("unused") final boolean batch)
{
return list.add(obj);
}
protected boolean removeFromList(final Object obj, final List<E> list,
@SuppressWarnings("unused") final boolean batch)
{
return list.remove(obj);
}
// -- Helper methods --
private static Map<Class<?>, Class<?>[]> typeMap =
new HashMap<Class<?>, Class<?>[]>();
/** Gets a new set containing the type and all its supertypes. */
protected static synchronized Class<?>[] getTypes(final Class<?> type) {
Class<?>[] types = typeMap.get(type);
if (types != null) return types;
final Set<Class<?>>set = new LinkedHashSet<Class<?>>();
set.add(All.class); // NB: Always include the "All" class.
getTypes(type, set);
types = set.toArray(new Class[set.size()]);
typeMap.put(type, types);
return types;
}
/** Recursively adds the type and all its supertypes to the given set. */
private static synchronized void getTypes(final Class<?> type,
final Set<Class<?>> types)
{
if (type == null) return;
types.add(type);
// recursively add to supertypes
getTypes(type.getSuperclass(), types);
for (final Class<?> iface : type.getInterfaces()) {
getTypes(iface, types);
}
}
/** Retrieves the type list for the given type, creating it if necessary. */
protected List<E> retrieveList(final Class<?> type) {
List<E> list = hoard.get(type);
if (list == null) {
list = new ArrayList<E>();
hoard.put(type, list);
}
return list;
}
// -- Helper classes --
private static class All {
// NB: A special class beneath which *all* elements of the index are listed.
}
} |
package org.vietabroader.view;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vietabroader.GoogleAPIUtils;
import org.vietabroader.controller.AuthenticationController;
import org.vietabroader.controller.SheetRefreshController;
import org.vietabroader.controller.SpreadsheetConnectController;
import org.vietabroader.model.GlobalState;
import org.vietabroader.model.VASpreadsheet;
import org.vietabroader.view.verifier.RowVerifier;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.ProgressBarUI;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.util.List;
import java.util.Observer;
import java.util.Observable;
/*
Main view of the app. This view observes the changes in GlobalState singleton.
Prefix rules:
btn: JButton
lbl: JLabel
txt: JTextField
spn: JSpinner
cbb: JComboBox
pan: JPanel
prg: JProgressBar
*/
public class MainView extends JFrame implements Observer {
/**
* Panel with title
*/
private static class TitledPanel extends JPanel {
private TitledPanel(String title) {
this.setLayout(new GridBagLayout());
this.setBorder(new CompoundBorder(
new TitledBorder(title),
new EmptyBorder(8, 2, 8, 2)) // Inner padding of each panel
);
}
@Override
public void setEnabled(boolean b) {
super.setEnabled(b);
Component[] children = this.getComponents();
for (Component child: children) {
child.setEnabled(b);
}
}
}
/**
* This label cuts off text that is too long. Full text can be seen in tooltip.
*/
private static class MessageLabel extends JLabel {
private final int CUT_OFF = 60;
MessageLabel(String text) {
super(text);
}
@Override
public void setText(String text) {
String cutOff = text;
if (cutOff.length() > CUT_OFF) {
cutOff = cutOff.substring(0, CUT_OFF) + "...";
}
super.setText(cutOff);
setToolTipText(text);
}
}
private static final Logger logger = LoggerFactory.getLogger(GoogleAPIUtils.class);
private final String QR_GENERATOR_URL = "https://vietabroader-qr.appspot.com/";
private final String BUTTON_TEXT_SIGN_IN = "Sign In";
private final String BUTTON_TEXT_SIGN_OUT = "Sign Out";
private final String LABEL_TEXT_SIGN_IN = "Please sign in with your Google account";
private final String BUTTON_TEXT_CONNECT = "Connect";
private final String BUTTON_TEXT_REFRESH = "Refresh";
private final Dimension BUTTON_DIM_AUTHENTICATE = new Dimension(100, 30);
private final Dimension LABEL_DIM_EMAIL = new Dimension(300, 15);
private final Dimension BUTTON_DIM_REFRESH = new Dimension(100, 50);
private final JButton btnAuthenticate = new JButton(BUTTON_TEXT_SIGN_IN);
private final JLabel lblAuthMessage = new JLabel(LABEL_TEXT_SIGN_IN);
private final JButton btnConnect = new JButton(BUTTON_TEXT_CONNECT);
private final JTextField txtSpreadsheetID = new JTextField(15);
private final MessageLabel lblSpreadsheetMessage = new MessageLabel(" ");
private final MessageLabel lblSheetMessage = new MessageLabel(" ");
private final JComboBox<String> cbbSheet = new JComboBox<>();
private final JProgressBar prgIndicator = new JProgressBar();
private final JButton btnRefresh = new JButton(BUTTON_TEXT_REFRESH);
private final JTextField txtRowFrom = new JTextField("1",5);
private final JTextField txtRowTo = new JTextField("1",5);
private final OneColumn[] columnArray = new OneColumn[4];
private final JPanel panSignIn = createSignInPanel();
private final JPanel panSpreadsheet = createSpreadsheetPanel();
private final JPanel panWorkspace = createWorkspacePanel();
private final JPanel panGenerate = createGeneratePanel();
private final JPanel panWebcam = createWebcamPanel();
private final JPanel panFooter = createFooterPanel();
public MainView() {
initUI();
resetOnSignedOut();
initControllers();
}
private void resetOnSignedOut() {
setMessageColor(lblSpreadsheetMessage, MessageType.INACTIVE);
lblSpreadsheetMessage.setText(" ");
setMessageColor(lblSheetMessage, MessageType.INACTIVE);
lblSheetMessage.setText(" ");
btnAuthenticate.setText(BUTTON_TEXT_SIGN_IN);
lblAuthMessage.setText(LABEL_TEXT_SIGN_IN);
cbbSheet.removeAllItems();
}
private void initUI() {
JPanel panelMain = new JPanel();
panelMain.setLayout(new GridBagLayout());
getContentPane().add(panelMain);
GridBagConstraints c = new GridBagConstraints();
// Sign in panel
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(4, 4, 4, 4); // Outer margin of each panel
panelMain.add(panSignIn, c);
// Spreadsheet connect panel
c.gridy = 2;
panelMain.add(panSpreadsheet, c);
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
lblSpreadsheetMessage.setBorder(BorderFactory.createLoweredSoftBevelBorder());
lblSpreadsheetMessage.setOpaque(true);
panelMain.add(lblSpreadsheetMessage, c);
// Sheet workspace panel
c.gridy = 4;
panelMain.add(panWorkspace, c);
c.gridy = 5;
c.fill = GridBagConstraints.HORIZONTAL;
lblSheetMessage.setBorder(BorderFactory.createLoweredSoftBevelBorder());
lblSheetMessage.setOpaque(true);
panelMain.add(lblSheetMessage, c);
// QR generating and reading panel
c.gridy = 6;
c.gridwidth = 1;
c.weightx = 1 / 2.0;
c.gridx = 0;
c.fill = GridBagConstraints.BOTH;
panelMain.add(panGenerate, c);
c.gridx = 1;
panelMain.add(panWebcam, c);
c.gridy = 7;
c.gridx = 0;
c.gridwidth = 2;
c.insets = new Insets(0, 0, 0, 0);
panelMain.add(panFooter, c);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e){
GoogleAPIUtils.signOut();
}
});
this.setTitle("VAQR");
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
}
private JPanel createSignInPanel() {
TitledPanel panel = new TitledPanel("Account");
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
btnAuthenticate.setPreferredSize(BUTTON_DIM_AUTHENTICATE);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(0, 10, 0, 0);;
panel.add(btnAuthenticate, c);
lblAuthMessage.setPreferredSize(LABEL_DIM_EMAIL);
c.gridx = 1;
c.gridy = 0;
panel.add(lblAuthMessage, c);
return panel;
}
private JPanel createSpreadsheetPanel() {
TitledPanel panel = new TitledPanel("Spreadsheet");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Spreadsheet ID: "), c);
c.gridx = 1;
c.insets = new Insets(0, 10, 0, 0);
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(txtSpreadsheetID, c);
c.anchor = GridBagConstraints.CENTER;
c.gridx = 2;
panel.add(btnConnect, c);
return panel;
}
private JPanel createWorkspacePanel() {
TitledPanel panel = new TitledPanel("Workspace");
// Sheet selection
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_END;
panel.add(new JLabel("Sheet: "), c);
c.gridx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 10, 10, 10);
panel.add(cbbSheet, c);
// Row range specification
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1/6.0;
panel.add(new JLabel("Row: "), c);
c.gridx = 1;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 2/6.0;
txtRowFrom.setInputVerifier(new RowVerifier());
txtRowFrom.setToolTipText("Enter a positive integer");
panel.add(txtRowFrom, c);
c.gridx = 2;
c.weightx = 1/6.0;
panel.add(new JLabel("to"), c);
c.gridx = 3;
c.weightx = 2/6.0;
txtRowTo.setInputVerifier(new RowVerifier());
txtRowTo.setToolTipText("Enter a positive integer");
panel.add(txtRowTo, c);
// Key columns and refresh button
c = new GridBagConstraints();
c.gridy = 2;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 0, 0);
JPanel panCol = createColumnPanel();
panel.add(panCol, c);
return panel;
}
private JPanel createColumnPanel() {
JPanel panelMain = new JPanel() {
@Override
public void setEnabled(boolean b) {
super.setEnabled(b);
Component[] children = this.getComponents();
for (Component child: children) {
child.setEnabled(b);
}
}
};
panelMain.setLayout(new GridBagLayout());
TitledPanel panel = new TitledPanel("Columns");
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1 / 4.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 5, 0, 5);
c.gridx = 0;
OneColumn colKey = new OneColumn(VASpreadsheet.KEY_COL_NAME);
panel.add(colKey, c);
columnArray[0] = colKey;
c.gridx = 1;
OneColumn colSecret = new OneColumn(VASpreadsheet.SECRET_COL_NAME);
// TODO: enable or remove secret column in next version
colSecret.setVisible(false);
panel.add(colSecret, c);
columnArray[1] = colSecret;
c.gridx = 2;
OneColumn colQR = new OneColumn(VASpreadsheet.QR_COL_NAME);
// TODO: enable or remove QR column in next version
colQR.setVisible(false);
panel.add(colQR, c);
columnArray[2] = colQR;
c.gridx = 3;
OneColumn colOutput = new OneColumn(VASpreadsheet.OUTPUT_COL_NAME);
panel.add(colOutput, c);
columnArray[3] = colOutput;
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1 / 2.0;
panelMain.add(panel, c);
c.gridx = 1;
btnRefresh.setPreferredSize(BUTTON_DIM_REFRESH);
panelMain.add(btnRefresh, c);
return panelMain;
}
private JPanel createGeneratePanel() {
TitledPanel panel = new TitledPanel("Generate QR Code");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
JButton btnGenerator = new JButton("Go to QR Generator");
btnGenerator.setPreferredSize(new Dimension(160, 60));
panel.add(btnGenerator, c);
btnGenerator.addActionListener(e -> {
try {
Desktop.getDesktop().browse(new URI(QR_GENERATOR_URL));
} catch (Exception ex) {
logger.error("Cannot open QR Generator", ex);
}
});
return panel;
}
private JPanel createWebcamPanel() {
TitledPanel panel = new TitledPanel("Scan QR Code");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
JButton btnWebcam = new JButton("Start Webcam");
btnWebcam.setPreferredSize(new Dimension(150, 60));
panel.add(btnWebcam, c);
btnWebcam.addActionListener(e -> {
WebcamView camView = new WebcamView();
camView.setVisible(true);
GlobalState currentState = GlobalState.getInstance();
currentState.setStatus(GlobalState.Status.QR_READING);
});
return panel;
}
private JPanel createFooterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1/2.0;
c.insets = new Insets(5, 10, 5, 10);
c.gridx = 0;
c.anchor = GridBagConstraints.LINE_START;
JLabel lblCopyright = new JLabel("\u00a9 VietAbroader 2017");
lblCopyright.setForeground(Color.GRAY);
panel.add(lblCopyright, c);
c.gridx = 1;
c.anchor = GridBagConstraints.LINE_END;
prgIndicator.setIndeterminate(false);
panel.add(prgIndicator, c);
return panel;
}
/**
* Initialize controllers
*/
private void initControllers() {
AuthenticationController authController = new AuthenticationController();
authController.setButtonAuthenticate(btnAuthenticate)
.setProgressIndicator(prgIndicator)
.setLabelAuthenticate(lblAuthMessage)
.control();
SpreadsheetConnectController spreadSheetConnectController = new SpreadsheetConnectController();
spreadSheetConnectController.setButtonConnect(btnConnect)
.setTextSpreadsheetID(txtSpreadsheetID)
.setLabelSpreadsheetMessage(lblSpreadsheetMessage)
.setProgressIndicator(prgIndicator)
.control();
SheetRefreshController sheetRefreshController = new SheetRefreshController();
sheetRefreshController.setButtonRefresh(btnRefresh)
.setComSheets(cbbSheet)
.setRowFields(txtRowFrom, txtRowTo)
.setSheetMessage(lblSheetMessage)
.setProgressIndicator(prgIndicator);
for (OneColumn column: columnArray) {
sheetRefreshController.setColumnArray(column.getLabelText(), column.getTextField());
}
sheetRefreshController.control();
}
/**
* Handle global state change
*/
@Override
public void update(Observable o, Object arg) {
logger.debug("Global state changed");
GlobalState currentState = (GlobalState) o;
GlobalState.Status currentStatus = currentState.getStatus();
switch (currentStatus) {
case SIGNED_OUT:
resetOnSignedOut();
setEnabledChildren(false);
panSignIn.setEnabled(true);
break;
case SIGNED_IN:
btnAuthenticate.setText(BUTTON_TEXT_SIGN_OUT);
lblAuthMessage.setText(currentState.getUserEmail());
setEnabledChildren(false);
panSignIn.setEnabled(true);
panSpreadsheet.setEnabled(true);
break;
case CONNECTED:
VASpreadsheet currentSpreadsheet = currentState.getSpreadsheet();
String spreadsheetTitle = currentSpreadsheet.getSpreadsheetTitle();
setMessageColor(lblSpreadsheetMessage, MessageType.SUCCESS);
lblSpreadsheetMessage.setText("Connected to: " + spreadsheetTitle);
List<String> sheets = currentSpreadsheet.getSheetTitles();
cbbSheet.removeAllItems();
sheets.forEach(cbbSheet::addItem);
setMessageColor(lblSheetMessage, MessageType.INACTIVE);
lblSheetMessage.setText(" ");
setEnabledChildren(true);
panWebcam.setEnabled(false);
break;
case REFRESHED:
setEnabledChildren(true);
break;
case QR_READING:
setEnabledChildren(false);
break;
}
}
private void setEnabledChildren(boolean b) {
panSignIn.setEnabled(b);
panSpreadsheet.setEnabled(b);
panWorkspace.setEnabled(b);
panWebcam.setEnabled(b);
}
public enum MessageType {
INACTIVE,
SUCCESS,
WARNING,
ERROR
}
/**
* Set the background and foreground color of a component depending on
* selected {@link MessageType}:
* @param comp a Swing component
* @param type type of message
*/
public static void setMessageColor(JComponent comp, MessageType type) {
Color background = Color.LIGHT_GRAY;
Color foreground = Color.BLACK;
switch (type) {
case INACTIVE:
background = Color.LIGHT_GRAY;
foreground = Color.BLACK;
break;
case SUCCESS:
background = Color.GREEN;
foreground = Color.BLACK;
break;
case WARNING:
background = Color.YELLOW;
foreground = Color.BLACK;
break;
case ERROR:
background = Color.RED;
foreground = Color.WHITE;
break;
}
comp.setBackground(background);
comp.setForeground(foreground);
if (comp instanceof JTextComponent) {
((JTextComponent) comp).setDisabledTextColor(foreground);
}
}
} |
package redis.clients.jedis;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.Protocol.Command;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder;
/**
* "Redis"
*
* @author huagang.li 2014123 1:18:04
*/
public class Connection implements Closeable {
private String host;
private int port = Protocol.DEFAULT_PORT;
private Socket socket;
private RedisOutputStream outputStream;
private RedisInputStream inputStream;
private int timeout = Protocol.DEFAULT_TIMEOUT;
private boolean broken = false;
private int pipelinedCommands = 0;
/**
* Redis
*
* @param host
*/
public Connection(final String host) {
this.host = host;
}
public Socket getSocket() {
return socket;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(final int timeout) {
this.timeout = timeout;
}
public void setTimeoutInfinite() {
try {
if (!isConnected()) {
connect();
}
socket.setKeepAlive(true);
socket.setSoTimeout(0);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
public void rollbackTimeout() {
try {
socket.setSoTimeout(timeout);
socket.setKeepAlive(false);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
/**
* Redis
*
* @param cmd
* Redis
* @param args
*
* @return
*/
protected Connection sendCommand(final Command cmd, final String... args) {
final byte[][] bargs = new byte[args.length][];
for (int i = 0; i < args.length; i++) {
bargs[i] = SafeEncoder.encode(args[i]);
}
return sendCommand(cmd, bargs);
}
/**
* Redis
*
* <pre>
*
* 1.
* 2.
* 3. 1
* </pre>
*
* @param cmd
* Redis
* @param args
*
* @return
*/
protected Connection sendCommand(final Command cmd, final byte[]... args) {
try {
connect();
Protocol.sendCommand(outputStream, cmd, args);
pipelinedCommands++;
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}
protected Connection sendCommand(final Command cmd) {
try {
connect();
Protocol.sendCommand(outputStream, cmd, new byte[0][]);
pipelinedCommands++;
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}
public Connection(final String host, final int port) {
super();
this.host = host;
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
public Connection() {
}
public void connect() {
if (!isConnected()) {
try {
socket = new Socket();
// ->@wjw_add
socket.setReuseAddress(true);
socket.setKeepAlive(true); // Will monitor the TCP connection is
// valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
// ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method,
// the underlying socket is closed
// immediately
// <-@wjw_add
socket.connect(new InetSocketAddress(host, port), timeout);
socket.setSoTimeout(timeout);
outputStream = new RedisOutputStream(socket.getOutputStream());
inputStream = new RedisInputStream(socket.getInputStream());
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
}
@Override
public void close() {
disconnect();
}
public void disconnect() {
if (isConnected()) {
try {
inputStream.close();
outputStream.close();
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
}
public boolean isConnected() {
return socket != null && socket.isBound() && !socket.isClosed()
&& socket.isConnected() && !socket.isInputShutdown()
&& !socket.isOutputShutdown();
}
protected String getStatusCodeReply() {
flush();
pipelinedCommands
final byte[] resp = (byte[]) readProtocolWithCheckingBroken();
if (null == resp) {
return null;
} else {
return SafeEncoder.encode(resp);
}
}
public String getBulkReply() {
final byte[] result = getBinaryBulkReply();
if (null != result) {
return SafeEncoder.encode(result);
} else {
return null;
}
}
public byte[] getBinaryBulkReply() {
flush();
pipelinedCommands
return (byte[]) readProtocolWithCheckingBroken();
}
public Long getIntegerReply() {
flush();
pipelinedCommands
return (Long) readProtocolWithCheckingBroken();
}
public List<String> getMultiBulkReply() {
return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply());
}
@SuppressWarnings("unchecked")
public List<byte[]> getBinaryMultiBulkReply() {
flush();
pipelinedCommands
return (List<byte[]>) readProtocolWithCheckingBroken();
}
public void resetPipelinedCount() {
pipelinedCommands = 0;
}
@SuppressWarnings("unchecked")
public List<Object> getRawObjectMultiBulkReply() {
return (List<Object>) readProtocolWithCheckingBroken();
}
public List<Object> getObjectMultiBulkReply() {
flush();
pipelinedCommands
return getRawObjectMultiBulkReply();
}
@SuppressWarnings("unchecked")
public List<Long> getIntegerMultiBulkReply() {
flush();
pipelinedCommands
return (List<Long>) readProtocolWithCheckingBroken();
}
public List<Object> getAll() {
return getAll(0);
}
public List<Object> getAll(int except) {
List<Object> all = new ArrayList<Object>();
flush();
while (pipelinedCommands > except) {
try {
all.add(readProtocolWithCheckingBroken());
} catch (JedisDataException e) {
all.add(e);
}
pipelinedCommands
}
return all;
}
public Object getOne() {
flush();
pipelinedCommands
return readProtocolWithCheckingBroken();
}
public boolean isBroken() {
return broken;
}
protected void flush() {
try {
outputStream.flush();
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
protected Object readProtocolWithCheckingBroken() {
try {
return Protocol.read(inputStream);
} catch (JedisConnectionException exc) {
broken = true;
throw exc;
}
}
} |
package ru.extas.web.commons;
import com.ejt.vaadin.sizereporter.ComponentResizeEvent;
import com.ejt.vaadin.sizereporter.ComponentResizeListener;
import com.ejt.vaadin.sizereporter.SizeReporter;
import com.vaadin.server.Sizeable;
import com.vaadin.ui.JavaScript;
import com.vaadin.ui.UI;
import com.vaadin.ui.Window;
import java.text.MessageFormat;
import java.util.UUID;
public class FormUtils {
public static void showModalWin(final ExtaEditForm<?> editWin) {
final Window window = new Window(editWin.getCaption(), editWin);
window.setClosable(true);
window.setModal(true);
if (editWin.getWinHeight() != Sizeable.SIZE_UNDEFINED)
window.setHeight(editWin.getWinHeight(), editWin.getWinHeightUnit());
if (editWin.getWinWidth() != Sizeable.SIZE_UNDEFINED)
window.setWidth(editWin.getWinWidth(), editWin.getWinWidthUnit());
window.addCloseListener(event -> editWin.closeForm());
editWin.addCloseFormListener(event -> window.close());
new WinSizeAdjuster(editWin, window);
final UUID id = UUID.randomUUID();
window.setId(id.toString());
JavaScript.getCurrent().addFunction("extaGetHeight",
arguments -> {
final int wndHeight = arguments.getJSONObject(0).getInt("height");
final int brwHeight = UI.getCurrent().getPage().getBrowserWindowHeight();
if (wndHeight >= brwHeight)
window.setHeight(100, Sizeable.Unit.PERCENTAGE);
else
window.setHeight(wndHeight, Sizeable.Unit.PIXELS);
editWin.adjustSize();
});
UI.getCurrent().addWindow(window);
}
private static class WinSizeAdjuster {
private int formHeight;
private final int brwHeight;
private int wndHeight;
private boolean adjusted;
public WinSizeAdjuster(ExtaEditForm<?> editWin, Window window) {
brwHeight = UI.getCurrent().getPage().getBrowserWindowHeight();
final SizeReporter winSizeReporter = new SizeReporter(window);
winSizeReporter.addResizeListener(e -> {
wndHeight = e.getHeight();
adjustWindow(editWin, window);
});
final SizeReporter formSizeReporter = new SizeReporter(editWin);
formSizeReporter.addResizeListenerOnce(e -> formHeight = e.getHeight());
}
protected void adjustWindow(ExtaEditForm<?> editWin, Window window) {
if (!adjusted) {
if(formHeight != 0 && wndHeight > formHeight || wndHeight >= brwHeight) {
if (wndHeight >= brwHeight)
window.setHeight(100, Sizeable.Unit.PERCENTAGE);
else
window.setHeight(wndHeight, Sizeable.Unit.PIXELS);
editWin.adjustSize();
adjusted = true;
}
}
}
}
} |
package ru.r2cloud.satellite;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.r2cloud.Lifecycle;
import ru.r2cloud.RtlSdrLock;
import ru.r2cloud.cloud.R2CloudService;
import ru.r2cloud.model.IQData;
import ru.r2cloud.model.ObservationFull;
import ru.r2cloud.model.ObservationRequest;
import ru.r2cloud.model.ObservationResult;
import ru.r2cloud.model.Satellite;
import ru.r2cloud.satellite.decoder.Decoder;
import ru.r2cloud.satellite.reader.IQReader;
import ru.r2cloud.satellite.reader.RtlFmReader;
import ru.r2cloud.satellite.reader.RtlSdrReader;
import ru.r2cloud.util.Clock;
import ru.r2cloud.util.ConfigListener;
import ru.r2cloud.util.Configuration;
import ru.r2cloud.util.NamingThreadFactory;
import ru.r2cloud.util.ProcessFactory;
import ru.r2cloud.util.SafeRunnable;
import ru.r2cloud.util.ThreadPoolFactory;
import ru.r2cloud.util.Util;
public class Scheduler implements Lifecycle, ConfigListener {
private static final Logger LOG = LoggerFactory.getLogger(Scheduler.class);
private final ObservationFactory factory;
private final SatelliteDao satellites;
private final Configuration config;
private final RtlSdrLock lock;
private final ThreadPoolFactory threadpoolFactory;
private final Clock clock;
private final R2CloudService r2cloudService;
private final ProcessFactory processFactory;
private final ObservationResultDao dao;
private final Map<String, Decoder> decoders;
private final Map<String, ScheduledObservation> scheduledObservations = new ConcurrentHashMap<String, ScheduledObservation>();
private ScheduledExecutorService scheduler = null;
private ScheduledExecutorService reaper = null;
private ScheduledExecutorService decoder = null;
public Scheduler(Configuration config, SatelliteDao satellites, RtlSdrLock lock, ObservationFactory factory, ThreadPoolFactory threadpoolFactory, Clock clock, R2CloudService r2cloudService, ProcessFactory processFactory, ObservationResultDao dao, Map<String, Decoder> decoders) {
this.config = config;
this.config.subscribe(this, "satellites.enabled");
this.config.subscribe(this, "locaiton.lat");
this.config.subscribe(this, "locaiton.lon");
this.satellites = satellites;
this.lock = lock;
this.factory = factory;
this.threadpoolFactory = threadpoolFactory;
this.clock = clock;
this.r2cloudService = r2cloudService;
this.processFactory = processFactory;
this.dao = dao;
this.decoders = decoders;
}
@Override
public void onConfigUpdated() {
List<Satellite> supportedSatellites = satellites.findAll();
for (Satellite cur : supportedSatellites) {
if (!cur.isEnabled()) {
continue;
}
boolean schedule = false;
switch (cur.getType()) {
case WEATHER:
if (config.getBoolean("satellites.enabled")) {
schedule = true;
}
break;
case AMATEUR:
if (config.getProperty("locaiton.lat") != null && config.getProperty("locaiton.lon") != null) {
schedule = true;
}
break;
default:
throw new IllegalArgumentException("type is not supported: " + cur.getType());
}
if (schedule) {
schedule(cur);
} else {
ScheduledObservation previousObservation = scheduledObservations.get(cur.getId());
if (previousObservation != null) {
previousObservation.cancel();
}
}
}
}
// protection from calling start 2 times and more
@Override
public synchronized void start() {
if (scheduler != null) {
return;
}
scheduler = threadpoolFactory.newScheduledThreadPool(1, new NamingThreadFactory("scheduler"));
reaper = threadpoolFactory.newScheduledThreadPool(1, new NamingThreadFactory("reaper"));
decoder = threadpoolFactory.newScheduledThreadPool(1, new NamingThreadFactory("decoder"));
onConfigUpdated();
LOG.info("started");
}
public void schedule(Satellite cur) {
long current = clock.millis();
ObservationRequest observation = factory.create(new Date(current), cur);
if (observation == null) {
return;
}
LOG.info("scheduled next pass for {}: {}", cur.getName(), observation.getStart().getTime());
IQReader reader = createReader(observation);
Future<?> future = scheduler.schedule(new SafeRunnable() {
@Override
public void doRun() {
if (!lock.tryLock(Scheduler.this)) {
LOG.info("unable to acquire lock for {}", cur.getName());
return;
}
try {
reader.start();
} finally {
lock.unlock(Scheduler.this);
}
}
}, observation.getStartTimeMillis() - current, TimeUnit.MILLISECONDS);
Future<?> reaperFuture = reaper.schedule(new SafeRunnable() {
@Override
public void doRun() {
IQData data;
future.cancel(true);
try {
data = reader.stop();
} finally {
scheduledObservations.remove(cur.getId());
}
schedule(cur);
if (data == null || data.getWavFile() == null || !data.getWavFile().exists()) {
return;
}
// actual start/end might be different
observation.setStartTimeMillis(data.getActualStart());
observation.setEndTimeMillis(data.getActualEnd());
File wavFile = dao.insert(observation, data.getWavFile());
if (wavFile == null) {
return;
}
decoder.execute(new SafeRunnable() {
@Override
public void doRun() {
Decoder decoder = decoders.get(observation.getDecoder());
if (decoder == null) {
LOG.error("unknown decoder: {}", decoder);
return;
}
LOG.info("decoding: {}", cur.getName());
ObservationResult result = decoder.decode(wavFile, observation);
LOG.info("decoded: {}", cur.getName());
if (result.getDataPath() != null) {
result.setDataPath(dao.saveData(observation.getSatelliteId(), observation.getId(), result.getDataPath()));
}
if (result.getaPath() != null) {
result.setaPath(dao.saveImage(observation.getSatelliteId(), observation.getId(), result.getaPath()));
}
ObservationFull full = dao.find(observation.getSatelliteId(), observation.getId());
full.setResult(result);
dao.update(full);
r2cloudService.uploadObservation(full);
}
});
}
}, observation.getEndTimeMillis() - current, TimeUnit.MILLISECONDS);
ScheduledObservation previous = scheduledObservations.put(cur.getId(), new ScheduledObservation(observation, future, reaperFuture));
if (previous != null) {
LOG.info("cancelling previous: {}", previous.getReq().getStart().getTime());
previous.cancel();
}
}
private IQReader createReader(ObservationRequest req) {
String decoder = req.getDecoder();
if (decoder.equals("apt")) {
return new RtlFmReader(config, processFactory, req);
} else if (decoder.equals("lrpt") || decoder.equals("aausat4") || decoder.equals("kunspf")) {
return new RtlSdrReader(config, processFactory, req);
} else {
throw new IllegalArgumentException("unsupported decoder: " + decoder);
}
}
public Long getNextObservation(String id) {
ScheduledObservation result = scheduledObservations.get(id);
if (result == null) {
return null;
}
return result.getReq().getStartTimeMillis();
}
// protection from calling stop 2 times and more
@Override
public synchronized void stop() {
Util.shutdown(scheduler, config.getThreadPoolShutdownMillis());
Util.shutdown(reaper, config.getThreadPoolShutdownMillis());
scheduler = null;
LOG.info("stopped");
}
public void cancel(Satellite satelliteToEdit) {
ScheduledObservation previous = scheduledObservations.remove(satelliteToEdit.getId());
if (previous == null) {
return;
}
LOG.info("cancelling {}: {}", satelliteToEdit.getName(), previous.getReq().getStart().getTime());
previous.cancel();
}
} |
package se.kth.hopsworks.util;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import se.kth.hopsworks.certificates.CertsFacade;
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Settings {
private final static Logger LOGGER = Logger.getLogger(Settings.class.
getName());
@PersistenceContext(unitName = "kthfsPU")
private EntityManager em;
@EJB
private CertsFacade certsFacade;
@PostConstruct
public void init() {
try {
//Generate glassfish certificate and persist to db
if(!isGlassfishCertGenerated()){
LOGGER.log(Level.INFO, "Attempting to generate super user certificate");
LocalhostServices.createServiceCertificates(getIntermediateCaDir(), getHdfsSuperUser());
certsFacade.putServiceCerts(getHdfsSuperUser());
//Updated variables table
Variables variable = findById(VARIABLE_GLASSFISH_CERT_CENERATED);
variable.setValue("true");
em.persist(variable);
em.flush();
LOGGER.log(Level.INFO, "Super user certificate was generated successfully");
} else {
LOGGER.log(Level.INFO, "Super user certificate is already generated");
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error while generating superuser cert", ex);
}
}
public static String AGENT_EMAIL = "kagent@hops.io";
public static final String SITE_EMAIL = "admin@kth.se";
/**
* Global Variables taken from the DB
*/
private static final String VARIABLE_KIBANA_IP = "kibana_ip";
private static final String VARIABLE_LIVY_IP = "livy_ip";
private static final String VARIABLE_JHS_IP = "jhs_ip";
private static final String VARIABLE_OOZIE_IP = "oozie_ip";
private static final String VARIABLE_SPARK_HISTORY_SERVER_IP = "spark_history_server_ip";
private static final String VARIABLE_ELASTIC_IP = "elastic_ip";
private static final String VARIABLE_SPARK_USER = "spark_user";
private static final String VARIABLE_YARN_SUPERUSER = "yarn_user";
private static final String VARIABLE_HDFS_SUPERUSER = "hdfs_user";
private static final String VARIABLE_ZEPPELIN_DIR = "zeppelin_dir";
private static final String VARIABLE_ZEPPELIN_PROJECTS_DIR = "zeppelin_projects_dir";
private static final String VARIABLE_ZEPPELIN_SYNC_INTERVAL = "zeppelin_sync_interval";
private static final String VARIABLE_ZEPPELIN_USER = "zeppelin_user";
private static final String VARIABLE_SPARK_DIR = "spark_dir";
private static final String VARIABLE_FLINK_DIR = "flink_dir";
private static final String VARIABLE_FLINK_USER = "flink_user";
private static final String VARIABLE_NDB_DIR = "ndb_dir";
private static final String VARIABLE_MYSQL_DIR = "mysql_dir";
private static final String VARIABLE_HADOOP_DIR = "hadoop_dir";
private static final String VARIABLE_HOPSWORKS_DIR = "hopsworks_dir";
private static final String VARIABLE_YARN_DEFAULT_QUOTA = "yarn_default_quota";
private static final String VARIABLE_HDFS_DEFAULT_QUOTA = "hdfs_default_quota";
private static final String VARIABLE_MAX_NUM_PROJ_PER_USER = "max_num_proj_per_user";
private static final String VARIABLE_ADAM_USER = "adam_user";
private static final String VARIABLE_ADAM_DIR = "adam_dir";
private static final String VARIABLE_TWOFACTOR_AUTH = "twofactor_auth";
private static final String VARIABLE_KAFKA_DIR = "kafka_dir";
private static final String VARIABLE_KAFKA_USER = "kafka_user";
private static final String VARIABLE_ZK_DIR = "zk_dir";
private static final String VARIABLE_ZK_USER = "zk_user";
private static final String VARIABLE_ZK_IP = "zk_ip";
private static final String VARIABLE_KAFKA_IP = "kafka_ip";
private static final String VARIABLE_DRELEPHANT_IP = "drelephant_ip";
private static final String VARIABLE_DRELEPHANT_DB = "drelephant_db";
private static final String VARIABLE_DRELEPHANT_PORT = "drelephant_port";
private static final String VARIABLE_YARN_WEB_UI_IP = "yarn_ui_ip";
private static final String VARIABLE_YARN_WEB_UI_PORT = "yarn_ui_port";
private static final String VARIABLE_FILE_PREVIEW_IMAGE_SIZE = "file_preview_image_size";
private static final String VARIABLE_FILE_PREVIEW_TXT_SIZE = "file_preview_txt_size";
private static final String VARIABLE_GVOD_REST_ENDPOINT = "gvod_rest_endpoint";
private static final String VARIABLE_PUBLIC_SEARCH_ENDPOINT = "public_search_endpoint";
private static final String VARIABLE_REST_PORT = "rest_port";
public static final String ERASURE_CODING_CONFIG = "erasure-coding-site.xml";
private static final String VARIABLE_KAFKA_NUM_PARTITIONS = "kafka_num_partitions";
private static final String VARIABLE_KAFKA_NUM_REPLICAS = "kafka_num_replicas";
private static final String VARIABLE_HOPSWORKS_SSL_MASTER_PASSWORD = "hopsworks_master_password";
private static final String VARIABLE_GLASSFISH_CERT_CENERATED = "glassfish_cert";
private String setVar(String varName, String defaultValue) {
Variables userName = findById(varName);
if (userName != null && userName.getValue() != null && (userName.getValue().isEmpty() == false)) {
String user = userName.getValue();
if (user != null && user.isEmpty() == false) {
return user;
}
}
return defaultValue;
}
private String setStrVar(String varName, String defaultValue) {
Variables var = findById(varName);
if (var != null && var.getValue() != null) {
String val = var.getValue();
if (val != null && val.isEmpty() == false) {
return val;
}
}
return defaultValue;
}
private String setDirVar(String varName, String defaultValue) {
Variables dirName = findById(varName);
if (dirName != null && dirName.getValue() != null && (new File(dirName.getValue()).isDirectory())) {
String val = dirName.getValue();
if (val != null && val.isEmpty() == false) {
return val;
}
}
return defaultValue;
}
private String setIpVar(String varName, String defaultValue) {
Variables ip = findById(varName);
if (ip != null && ip.getValue() != null && Ip.validIp(ip.getValue())) {
String val = ip.getValue();
if (val != null && val.isEmpty() == false) {
return val;
}
}
return defaultValue;
}
private String setDbVar(String varName, String defaultValue) {
Variables ip = findById(varName);
if (ip != null && ip.getValue() != null) {
// TODO - check this is a valid DB name
String val = ip.getValue();
if (val != null && val.isEmpty() == false) {
return val;
}
}
return defaultValue;
}
private int setIntVar(String varName, int defaultValue) {
Variables ip = findById(varName);
if (ip != null && ip.getValue() != null) {
String val = ip.getValue();
if (val != null && val.isEmpty() == false) {
return Integer.parseInt(val);
}
}
return defaultValue;
}
private long setLongVar(String varName, long defaultValue) {
Variables ip = findById(varName);
if (ip != null && ip.getValue() != null) {
String val = ip.getValue();
if (val != null && val.isEmpty() == false) {
return Long.parseLong(val);
}
}
return defaultValue;
}
private boolean cached = false;
private void populateCache() {
if (!cached) {
TWOFACTOR_AUTH = setVar(VARIABLE_TWOFACTOR_AUTH, TWOFACTOR_AUTH);
HDFS_SUPERUSER = setVar(VARIABLE_HDFS_SUPERUSER, HDFS_SUPERUSER);
YARN_SUPERUSER = setVar(VARIABLE_YARN_SUPERUSER, YARN_SUPERUSER);
SPARK_USER = setVar(VARIABLE_SPARK_USER, SPARK_USER);
SPARK_DIR = setDirVar(VARIABLE_SPARK_DIR, SPARK_DIR);
FLINK_USER = setVar(VARIABLE_FLINK_USER, FLINK_USER);
FLINK_DIR = setDirVar(VARIABLE_FLINK_DIR, FLINK_DIR);
ZEPPELIN_USER = setVar(VARIABLE_ZEPPELIN_USER, ZEPPELIN_USER);
ZEPPELIN_DIR = setDirVar(VARIABLE_ZEPPELIN_DIR, ZEPPELIN_DIR);
ZEPPELIN_PROJECTS_DIR = setDirVar(VARIABLE_ZEPPELIN_PROJECTS_DIR, ZEPPELIN_PROJECTS_DIR);
ZEPPELIN_SYNC_INTERVAL = setLongVar(VARIABLE_ZEPPELIN_SYNC_INTERVAL, ZEPPELIN_SYNC_INTERVAL);
ADAM_USER = setVar(VARIABLE_ADAM_USER, ADAM_USER);
ADAM_DIR = setDirVar(VARIABLE_ADAM_DIR, ADAM_DIR);
MYSQL_DIR = setDirVar(VARIABLE_MYSQL_DIR, MYSQL_DIR);
HADOOP_DIR = setDirVar(VARIABLE_HADOOP_DIR, HADOOP_DIR);
HOPSWORKS_INSTALL_DIR = setDirVar(VARIABLE_HOPSWORKS_DIR, HOPSWORKS_INSTALL_DIR);
NDB_DIR = setDirVar(VARIABLE_NDB_DIR, NDB_DIR);
ELASTIC_IP = setIpVar(VARIABLE_ELASTIC_IP, ELASTIC_IP);
JHS_IP = setIpVar(VARIABLE_JHS_IP, JHS_IP);
LIVY_IP = setIpVar(VARIABLE_LIVY_IP, LIVY_IP);
OOZIE_IP = setIpVar(VARIABLE_OOZIE_IP, OOZIE_IP);
SPARK_HISTORY_SERVER_IP = setIpVar(VARIABLE_SPARK_HISTORY_SERVER_IP, SPARK_HISTORY_SERVER_IP);
ZK_IP = setIpVar(VARIABLE_ZK_IP, ZK_IP);
ZK_USER = setVar(VARIABLE_ZK_USER, ZK_USER);
ZK_DIR = setDirVar(VARIABLE_ZK_DIR, ZK_DIR);
DRELEPHANT_IP = setIpVar(VARIABLE_DRELEPHANT_IP, DRELEPHANT_IP);
DRELEPHANT_PORT = setIntVar(VARIABLE_DRELEPHANT_PORT, DRELEPHANT_PORT);
DRELEPHANT_DB = setDbVar(VARIABLE_DRELEPHANT_DB, DRELEPHANT_DB);
KIBANA_IP = setIpVar(VARIABLE_KIBANA_IP, KIBANA_IP);
KAFKA_IP = setIpVar(VARIABLE_KAFKA_IP, KAFKA_IP);
KAFKA_USER = setVar(VARIABLE_KAFKA_USER, KAFKA_USER);
KAFKA_DIR = setDirVar(VARIABLE_KAFKA_DIR, KAFKA_DIR);
KAFKA_DEFAULT_NUM_PARTITIONS = setDirVar(VARIABLE_KAFKA_NUM_PARTITIONS, KAFKA_DEFAULT_NUM_PARTITIONS);
KAFKA_DEFAULT_NUM_REPLICAS = setDirVar(VARIABLE_KAFKA_NUM_REPLICAS, KAFKA_DEFAULT_NUM_REPLICAS);
YARN_DEFAULT_QUOTA = setDirVar(VARIABLE_YARN_DEFAULT_QUOTA, YARN_DEFAULT_QUOTA);
YARN_WEB_UI_IP = setIpVar(VARIABLE_YARN_WEB_UI_IP, YARN_WEB_UI_IP);
YARN_WEB_UI_PORT = setIntVar(VARIABLE_YARN_WEB_UI_PORT, YARN_WEB_UI_PORT);
HDFS_DEFAULT_QUOTA_MBs = setDirVar(VARIABLE_HDFS_DEFAULT_QUOTA, HDFS_DEFAULT_QUOTA_MBs);
MAX_NUM_PROJ_PER_USER = setDirVar(VARIABLE_MAX_NUM_PROJ_PER_USER, MAX_NUM_PROJ_PER_USER);
HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD = setVar(VARIABLE_HOPSWORKS_SSL_MASTER_PASSWORD, HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD);
GLASSFISH_CERT_GENERATED = setVar(VARIABLE_GLASSFISH_CERT_CENERATED, GLASSFISH_CERT_GENERATED);
FILE_PREVIEW_IMAGE_SIZE = setIntVar(VARIABLE_FILE_PREVIEW_IMAGE_SIZE, 10000000);
FILE_PREVIEW_TXT_SIZE = setIntVar(VARIABLE_FILE_PREVIEW_TXT_SIZE, 100);
GVOD_REST_ENDPOINT = setStrVar(VARIABLE_GVOD_REST_ENDPOINT, GVOD_REST_ENDPOINT);
PUBLIC_SEARCH_ENDPOINT = setStrVar(VARIABLE_PUBLIC_SEARCH_ENDPOINT, PUBLIC_SEARCH_ENDPOINT);
REST_PORT = setIntVar(VARIABLE_REST_PORT, REST_PORT);
cached = true;
}
}
private void checkCache() {
if (!cached) {
populateCache();
}
}
private static String GLASSFISH_DIR = "/srv/glassfish";
public static synchronized String getGlassfishDir() {
return GLASSFISH_DIR;
}
private String TWOFACTOR_AUTH = "false";
public synchronized String getTwoFactorAuth() {
checkCache();
return TWOFACTOR_AUTH;
}
/**
* Default Directory locations
*/
private String SPARK_DIR = "/srv/spark";
public static final String SPARK_EXAMPLES_DIR = "/examples/jars";
public static final String HOPS_VERSION = "2.4.0";
public static final String SPARK_HISTORY_SERVER_ENV = "spark.yarn.historyServer.address";
public static final String SPARK_NUMBER_EXECUTORS_ENV = "spark.executor.instances";
public static final String SPARK_DYNAMIC_ALLOC_ENV = "spark.dynamicAllocation.enabled";
public static final String SPARK_DYNAMIC_ALLOC_MIN_EXECS_ENV = "spark.dynamicAllocation.minExecutors";
public static final String SPARK_DYNAMIC_ALLOC_MAX_EXECS_ENV = "spark.dynamicAllocation.maxExecutors";
public static final String SPARK_DYNAMIC_ALLOC_INIT_EXECS_ENV = "spark.dynamicAllocation.initialExecutors";
public static final String SPARK_SHUFFLE_SERVICE = "spark.shuffle.service.enabled";
public static final String SPARK_DRIVER_MEMORY_ENV = "spark.driver.memory";
public static final String SPARK_DRIVER_CORES_ENV = "spark.driver.cores";
public static final String SPARK_EXECUTOR_MEMORY_ENV = "spark.executor.memory";
public static final String SPARK_EXECUTOR_CORES_ENV = "spark.executor.cores";
public static final String SPARK_EXECUTOR_EXTRACLASSPATH = "spark.executor.extraClassPath";
public static final String SPARK_CACHE_FILENAMES = "spark.yarn.cache.filenames";
public static final String SPARK_CACHE_SIZES = "spark.yarn.cache.sizes";
public static final String SPARK_CACHE_TIMESTAMPS = "spark.yarn.cache.timestamps";
public static final String SPARK_CACHE_VISIBILITIES = "spark.yarn.cache.visibilities";
public static final String SPARK_CACHE_TYPES = "spark.yarn.cache.types";
public synchronized String getSparkDir() {
checkCache();
return SPARK_DIR;
}
private String SPARK_CONF_DIR = SPARK_DIR + "/conf";
public synchronized String getSparkConfDir(){
checkCache();
return SPARK_CONF_DIR;
}
private String SPARK_CONF_FILE = SPARK_CONF_DIR + "/spark-defaults.conf";
public synchronized String getSparkConfFile() {
//checkCache();
return SPARK_CONF_FILE;
}
private String ADAM_USER = "glassfish";
public synchronized String getAdamUser() {
checkCache();
return ADAM_USER;
}
private String FLINK_DIR = "/srv/flink";
public synchronized String getFlinkDir() {
checkCache();
return FLINK_DIR;
}
private final String FLINK_CONF_DIR = "conf";
public String getFlinkConfDir() {
String flinkDir = getFlinkDir();
return flinkDir + File.separator + FLINK_CONF_DIR;
}
private final String FLINK_CONF_FILE = "flink-conf.yaml";
public String getFlinkConfFile() {
return getFlinkConfDir() + File.separator + FLINK_CONF_FILE;
}
private String MYSQL_DIR = "/usr/local/mysql";
public synchronized String getMySqlDir() {
checkCache();
return MYSQL_DIR;
}
private String NDB_DIR = "/var/lib/mysql-cluster";
public synchronized String getNdbDir() {
checkCache();
return NDB_DIR;
}
private String ADAM_DIR = "/srv/adam";
public synchronized String getAdamDir() {
checkCache();
return ADAM_DIR;
}
private String HADOOP_DIR = "/srv/hadoop";
public synchronized String getHadoopDir() {
checkCache();
return HADOOP_DIR;
}
private static String HOPSWORKS_INSTALL_DIR = "/srv/glassfish";
public synchronized String getHopsworksInstallDir() {
checkCache();
return HOPSWORKS_INSTALL_DIR;
}
private static String HOPSWORKS_DOMAIN_DIR = HOPSWORKS_INSTALL_DIR + "/domain1";
public synchronized String getHopsworksDomainDir() {
checkCache();
return HOPSWORKS_DOMAIN_DIR;
}
public synchronized String getIntermediateCaDir() {
checkCache();
return getHopsworksDomainDir() + Settings.CA_DIR;
}
//User under which yarn is run
private String YARN_SUPERUSER = "glassfish";
public synchronized String getYarnSuperUser() {
checkCache();
return YARN_SUPERUSER;
}
private String HDFS_SUPERUSER = "glassfish";
public synchronized String getHdfsSuperUser() {
checkCache();
return HDFS_SUPERUSER;
}
private String SPARK_USER = "glassfish";
public synchronized String getSparkUser() {
checkCache();
return SPARK_USER;
}
private String FLINK_USER = "glassfish";
public synchronized String getFlinkUser() {
checkCache();
return FLINK_USER;
}
private String ZEPPELIN_USER = "glassfish";
public synchronized String getZeppelinUser() {
checkCache();
return ZEPPELIN_USER;
}
private String HIWAY_DIR = "/home/glassfish";
public synchronized String getHiwayDir() {
checkCache();
return HIWAY_DIR;
}
private String YARN_DEFAULT_QUOTA = "60000";
public synchronized String getYarnDefaultQuota() {
checkCache();
return YARN_DEFAULT_QUOTA;
}
private String YARN_WEB_UI_IP = "127.0.0.1";
private int YARN_WEB_UI_PORT = 8088;
public synchronized String getYarnWebUIAddress() {
checkCache();
return YARN_WEB_UI_IP + ":" + YARN_WEB_UI_PORT;
}
private String HDFS_DEFAULT_QUOTA_MBs = "200000";
public synchronized long getHdfsDefaultQuotaInMBs() {
checkCache();
return Long.parseLong(HDFS_DEFAULT_QUOTA_MBs);
}
private String MAX_NUM_PROJ_PER_USER = "5";
public synchronized Integer getMaxNumProjPerUser() {
checkCache();
int num = 5;
try {
num = Integer.parseInt(MAX_NUM_PROJ_PER_USER);
} catch (NumberFormatException ex) {
// should print to log here
}
return num;
}
//Hadoop locations
public synchronized String getHadoopConfDir() {
return hadoopConfDir(getHadoopDir());
}
private static String hadoopConfDir(String hadoopDir) {
return hadoopDir + "/" + HADOOP_CONF_RELATIVE_DIR;
}
public static String getHadoopConfDir(String hadoopDir) {
return hadoopConfDir(hadoopDir);
}
public synchronized String getYarnConfDir() {
return getHadoopConfDir();
}
public static String getYarnConfDir(String hadoopDir) {
return hadoopConfDir(hadoopDir);
}
//Default configuration file names
public static final String DEFAULT_YARN_CONFFILE_NAME = "yarn-site.xml";
public static final String DEFAULT_HADOOP_CONFFILE_NAME = "core-site.xml";
public static final String DEFAULT_HDFS_CONFFILE_NAME = "hdfs-site.xml";
public static final String DEFAULT_SPARK_CONFFILE_NAME = "spark-defaults.conf";
//Environment variable keys
//TODO: Check if ENV_KEY_YARN_CONF_DIR should be replaced with ENV_KEY_YARN_CONF
public static final String ENV_KEY_YARN_CONF_DIR = "hdfs";
public static final String ENV_KEY_HADOOP_CONF_DIR = "HADOOP_CONF_DIR";
public static final String ENV_KEY_YARN_CONF = "YARN_CONF_DIR";
public static final String ENV_KEY_SPARK_CONF_DIR = "SPARK_CONF_DIR";
//YARN constants
public static final int YARN_DEFAULT_APP_MASTER_MEMORY = 1024;
public static final String YARN_DEFAULT_OUTPUT_PATH = "Logs/Yarn/";
public static final String HADOOP_COMMON_HOME_KEY = "HADOOP_COMMON_HOME";
public static final String HADOOP_HOME_KEY = "HADOOP_HOME";
// private static String HADOOP_COMMON_HOME_VALUE = HADOOP_DIR;
public static final String HADOOP_HDFS_HOME_KEY = "HADOOP_HDFS_HOME";
// private static final String HADOOP_HDFS_HOME_VALUE = HADOOP_DIR;
public static final String HADOOP_YARN_HOME_KEY = "HADOOP_YARN_HOME";
// private static final String HADOOP_YARN_HOME_VALUE = HADOOP_DIR;
public static final String HADOOP_CONF_DIR_KEY = "HADOOP_CONF_DIR";
// public static final String HADOOP_CONF_DIR_VALUE = HADOOP_CONF_DIR;
public static final String HADOOP_CONF_RELATIVE_DIR = "etc/hadoop";
public static final String SPARK_CONF_RELATIVE_DIR = "conf";
public static final String YARN_CONF_RELATIVE_DIR = HADOOP_CONF_RELATIVE_DIR;
//Spark constants
public static final String SPARK_STAGING_DIR = ".sparkStaging";
//public static final String SPARK_LOCRSC_SPARK_JAR = "__spark__.jar";
public static final String SPARK_JARS = "spark.yarn.jars";
public static final String SPARK_ARCHIVE = "spark.yarn.archive";
// Subdirectory where Spark libraries will be placed.
public static final String LOCALIZED_LIB_DIR = "__spark_libs__";
public static final String LOCALIZED_CONF_DIR = "__spark_conf__";
public static final String SPARK_LOCRSC_APP_JAR = "__app__.jar";
// Distribution-defined classpath to add to processes
public static final String ENV_DIST_CLASSPATH = "SPARK_DIST_CLASSPATH";
public static final String SPARK_AM_MAIN = "org.apache.spark.deploy.yarn.ApplicationMaster";
public static final String SPARK_DEFAULT_OUTPUT_PATH = "Logs/Spark/";
public static final String SPARK_CONFIG_FILE = "conf/spark-defaults.conf";
public static final int SPARK_MIN_EXECS = 1;
public static final int SPARK_MAX_EXECS = 300;
public static final int SPARK_INIT_EXECS = 1;
//Flink constants
public static final String FLINK_DEFAULT_OUTPUT_PATH = "Logs/Flink/";
public static final String FLINK_DEFAULT_CONF_FILE = "flink-conf.yaml";
public static final String FLINK_DEFAULT_LOG4J_FILE = "log4j.properties";
public static final String FLINK_DEFAULT_LOGBACK_FILE = "logback.xml";
public static final String FLINK_LOCRSC_FLINK_JAR = "flink.jar";
public static final String FLINK_LOCRSC_APP_JAR = "app.jar";
public static final String FLINK_AM_MAIN = "org.apache.flink.yarn.ApplicationMaster";
public static final int FLINK_APP_MASTER_MEMORY = 768;
public static final String FLINK_KAFKA_CERTS_DIR = "/srv/glassfish/domain1/config";
//Zeppelin constants
public static final String JAVA_HOME = "/usr/lib/jvm/default-java";
public synchronized String getLocalFlinkJarPath() {
return getFlinkDir()+ "/flink.jar";
}
public synchronized String getHdfsFlinkJarPath() {
return hdfsFlinkJarPath(getFlinkUser());
}
private static String hdfsFlinkJarPath(String flinkUser) {
return "hdfs:///user/" + flinkUser + "/flink.jar";
}
public static String getHdfsFlinkJarPath(String flinkUser) {
return hdfsFlinkJarPath(flinkUser);
}
public synchronized String getFlinkDefaultClasspath() {
return flinkDefaultClasspath(getFlinkDir());
}
private static String flinkDefaultClasspath(String flinkDir) {
//ADAM constants
public static final String ADAM_MAINCLASS = "org.bdgenomics.adam.cli.ADAMMain";
// public static final String ADAM_DEFAULT_JAR_HDFS_PATH = "hdfs:///user/adam/repo/adam-cli.jar";
//Or: "adam-cli/target/appassembler/repo/org/bdgenomics/adam/adam-cli/0.15.1-SNAPSHOT/adam-cli-0.15.1-SNAPSHOT.jar"
public static final String ADAM_DEFAULT_OUTPUT_PATH = "Logs/Adam/";
public static final String ADAM_DEFAULT_HDFS_REPO = "/user/adam/repo/";
public String getAdamJarHdfsPath() {
return "hdfs:///user/" + getAdamUser() + "/adam-cli.jar";
}
//Directory names in HDFS
public static final String DIR_ROOT = "Projects";
public static final String DIR_SAMPLES = "Samples";
public static final String DIR_RESULTS = "Results";
public static final String DIR_CONSENTS = "consents";
public static final String DIR_BAM = "bam";
public static final String DIR_SAM = "sam";
public static final String DIR_FASTQ = "fastq";
public static final String DIR_FASTA = "fasta";
public static final String DIR_VCF = "vcf";
public static final String DIR_TEMPLATES = "Templates";
public static final String PROJECT_STAGING_DIR = "Resources";
// Elasticsearch
private String ELASTIC_IP = "127.0.0.1";
public synchronized String getElasticIp() {
checkCache();
return ELASTIC_IP;
}
public static final int ELASTIC_PORT = 9300;
// Spark
private String SPARK_HISTORY_SERVER_IP = "127.0.0.1";
public synchronized String getSparkHistoryServerIp() {
checkCache();
return SPARK_HISTORY_SERVER_IP + ":18080";
}
// Oozie
private String OOZIE_IP = "127.0.0.1";
public synchronized String getOozieIp() {
checkCache();
return OOZIE_IP;
}
// MapReduce Job History Server
private String JHS_IP = "127.0.0.1";
public synchronized String getJhsIp() {
checkCache();
return JHS_IP;
}
// Livy Server
private String LIVY_IP = "127.0.0.1";
private String LIVY_YARN_MODE = "yarn";
public synchronized String getLivyIp() {
checkCache();
return LIVY_IP;
}
public synchronized String getLivyUrl() {
return "http://" + getLivyIp() + ":8998";
}
public synchronized String getLivyYarnMode() {
checkCache();
return LIVY_YARN_MODE;
}
public static final int ZK_PORT = 2181;
// Kibana
private String KIBANA_IP = "10.0.2.15";
public static final int KIBANA_PORT = 5601;
public synchronized String getKibanaUri() {
checkCache();
return "http://" + KIBANA_IP+":"+KIBANA_PORT;
}
// Zookeeper
private String ZK_IP = "10.0.2.15";
public synchronized String getZkConnectStr() {
checkCache();
return ZK_IP+":"+ZK_PORT;
}
private String ZK_USER = "zk";
public synchronized String getZkUser() {
checkCache();
return ZK_USER;
}
// Zeppelin
private String ZEPPELIN_DIR = "/srv/zeppelin";
public synchronized String getZeppelinDir() {
checkCache();
return ZEPPELIN_DIR;
}
private String ZEPPELIN_PROJECTS_DIR = "/srv/zeppelin/Projects";
public synchronized String getZeppelinProjectsDir() {
checkCache();
return ZEPPELIN_PROJECTS_DIR;
}
private long ZEPPELIN_SYNC_INTERVAL = 24 * 60 * 60* 1000;
public synchronized long getZeppelinSyncInterval(){
checkCache();
return ZEPPELIN_SYNC_INTERVAL;
}
// Kafka
private String KAFKA_IP = "10.0.2.15";
public static final int KAFKA_PORT = 9091;
public synchronized String getKafkaConnectStr() {
checkCache();
return KAFKA_IP+":"+KAFKA_PORT;
}
private String KAFKA_USER = "kafka";
public synchronized String getKafkaUser() {
checkCache();
return KAFKA_USER;
}
private String KAFKA_DIR = "/srv/kafka";
public synchronized String getKafkaDir() {
checkCache();
return KAFKA_DIR;
}
private String GVOD_REST_ENDPOINT = "http://10.0.2.15:42000";
public synchronized String getGVodRestEndpoint() {
checkCache();
return GVOD_REST_ENDPOINT;
}
private String PUBLIC_SEARCH_ENDPOINT = "http://10.0.2.15:8080/hopsworks/api/elastic/publicdatasets/";
public synchronized String getPublicSearchEndpoint() {
checkCache();
return PUBLIC_SEARCH_ENDPOINT;
}
private int REST_PORT = 8080;
public synchronized int getRestPort() {
checkCache();
return REST_PORT;
}
/**
* Generates the Endpoint for kafka.
* @return
*/
public String getRestEndpoint(){
String gvod_endpoint = getGVodRestEndpoint();
String ip = getGVodRestEndpoint().substring(0,gvod_endpoint.lastIndexOf(":"));
int port = getRestPort();
return ip+":"+port;
}
private String HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD = "adminpw";
public synchronized String getHopsworksMasterPasswordSsl() {
checkCache();
return HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD;
}
private String GLASSFISH_CERT_GENERATED = "false";
public synchronized boolean isGlassfishCertGenerated() {
checkCache();
return Boolean.parseBoolean(GLASSFISH_CERT_GENERATED);
}
private String KAFKA_DEFAULT_NUM_PARTITIONS = "2";
private String KAFKA_DEFAULT_NUM_REPLICAS = "1";
public synchronized String getKafkaDefaultNumPartitions() {
checkCache();
return KAFKA_DEFAULT_NUM_PARTITIONS;
}
public synchronized String getKafkaDefaultNumReplicas() {
checkCache();
return KAFKA_DEFAULT_NUM_REPLICAS;
}
private String ZK_DIR = "/srv/zookeeper";
public synchronized String getZkDir() {
checkCache();
return ZK_DIR;
}
// Dr Elephant
private String DRELEPHANT_IP = "127.0.0.1";
private String DRELEPHANT_DB = "hopsworks";
public static int DRELEPHANT_PORT = 11000;
public synchronized String getDrElephantUrl() {
checkCache();
return "http://" + DRELEPHANT_IP+":"+DRELEPHANT_PORT;
}
public synchronized String getDrElephantDb() {
checkCache();
return DRELEPHANT_DB;
}
// Hopsworks
public static final Charset ENCODING = StandardCharsets.UTF_8;
public static final String HOPS_USERS_HOMEDIR = "/home/";
public static final String HOPS_USERNAME_SEPARATOR = "__";
// public static final String HOPS_USERS_HOMEDIR = "/srv/users/";
private static String CA_DIR = "/config/ca/intermediate";
public static final String SSL_CREATE_CERT_SCRIPTNAME = "createusercerts.sh";
public static final String SSL_DELETE_CERT_SCRIPTNAME = "deleteusercerts.sh";
public static final String SSL_DELETE_PROJECT_CERTS_SCRIPTNAME = "deleteprojectcerts.sh";
public static final int USERNAME_LEN = 8;
public static final int MAX_USERNAME_SUFFIX = 99;
public static final int MAX_RETRIES = 500;
public static final String META_NAME_FIELD = "name";
public static final String META_DESCRIPTION_FIELD = "description";
public static final String META_INDEX = "projects";
public static final String META_PROJECT_TYPE = "proj";
public static final String META_DATASET_TYPE = "ds";
public static final String META_INODE_TYPE = "inode";
public static final String META_PROJECT_ID_FIELD = "project_id";
public static final String META_ID = "_id";
public static final String META_DATA_NESTED_FIELD = "xattr";
public static final String META_DATA_FIELDS = META_DATA_NESTED_FIELD + ".*";
//Filename conventions
public static final String FILENAME_DISALLOWED_CHARS = " /\\?*:|'\"<>%()&;
public static final String PRINT_FILENAME_DISALLOWED_CHARS
= "__, space, /, \\, ?, *, :, |, ', \", <, >, %, (, ), &, ;,
public static final String SHARED_FILE_SEPARATOR = "::";
public static final String DOUBLE_UNDERSCORE = "__";
public static final String KAFKA_K_CERTIFICATE = "kafka_k_certificate";
public static final String KAFKA_T_CERTIFICATE = "kafka_t_certificate";
public static final String TMP_CERT_STORE_LOCAL = "/srv/glassfish/kafkacerts";
public static final String TMP_CERT_STORE_REMOTE = "/user/glassfish/kafkacerts";
//Used to retrieve schema by KafkaUtil
public static final String KAFKA_SESSIONID_ENV_VAR = "hopsworks.sessionid";
public static final String KAFKA_PROJECTID_ENV_VAR = "hopsworks.projectid";
public static final String KAFKA_BROKERADDR_ENV_VAR = "hopsworks.kafka.brokeraddress";
public static final String KAFKA_JOB_ENV_VAR = "hopsworks.kafka.job";
public static final String KAFKA_JOB_TOPICS_ENV_VAR = "hopsworks.kafka.job.topics";
public static final String KEYSTORE_PASSWORD_ENV_VAR = "hopsworks.keystore.password";
public static final String TRUSTSTORE_PASSWORD_ENV_VAR = "hopsworks.truststore.password";
public static final String KAFKA_CONSUMER_GROUPS = "hopsworks.kafka.consumergroups";
public static final String KAFKA_REST_ENDPOINT_ENV_VAR = "hopsworks.kafka.restendpoint";
public static int FILE_PREVIEW_IMAGE_SIZE = 10000000;
public static int FILE_PREVIEW_TXT_SIZE = 100;
public static int FILE_PREVIEW_TXT_SIZE_BYTES = 1024*128;
public static int FILE_PREVIEW_TXT_SIZE_BYTES_README = 1024*512;
public static String README_TEMPLATE = "*This is an auto-generated README.md"
+ " file for your Dataset!*\n"
+ "To replace it, go into your DataSet and edit the README.md file.\n"
+ "\n" + "*%s* DataSet\n" + "===\n" + "\n"
+ "
//Dataset request subject
public static String MESSAGE_DS_REQ_SUBJECT = "Dataset access request.";
// QUOTA
public static final float DEFAULT_YARN_MULTIPLICATOR = 1.0f;
/**
* Returns the maximum image size in bytes that can be previewed in the
* browser.
* @return
*/
public synchronized int getFilePreviewImageSize() {
checkCache();
return FILE_PREVIEW_IMAGE_SIZE;
}
/**
* Returns the maximum number of lines of the file that can be previewed in the
* browser.
* @return
*/
public synchronized int getFilePreviewTxtSize() {
checkCache();
return FILE_PREVIEW_TXT_SIZE;
}
//Project creation: default datasets
public static enum DefaultDataset {
LOGS("Logs", "Contains the logs for jobs that have been run through the Hopsworks platform."),
RESOURCES("Resources", "Contains resources used by jobs, for example, jar files."),
NOTEBOOKS("notebook", "Contains zeppelin notebooks.");
private final String name;
private final String description;
private DefaultDataset(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
public Settings() {
}
/**
* Get the variable value with the given name.
* <p/>
* @param id
* @return The user with given email, or null if no such user exists.
*/
public Variables findById(String id) {
try {
return em.createNamedQuery("Variables.findById", Variables.class
).setParameter("id", id).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
// public void setIdValue(String id, String value) {
// Variables v = new Variables(id, value);
// try {
// em.persist(v)
// } catch (EntityExistsException ex) {
public void detach(Variables variable) {
em.detach(variable);
}
public static String getProjectPath(String projectname) {
return File.separator + DIR_ROOT + File.separator + projectname;
}
} |
//@@author A0139930B
package seedu.taskitty.model.task;
import seedu.taskitty.commons.util.CollectionUtil;
import seedu.taskitty.model.tag.UniqueTagList;
import java.util.Objects;
/**
* Represents a Task in the taskManager.
* Guarantees: details are present and not null, field values are validated.
*/
public class Task implements ReadOnlyTask {
public static final int TASK_COMPONENT_INDEX_NAME = 0;
public static final int TASK_COMPONENT_COUNT = 1;
public static final int DEADLINE_COMPONENT_INDEX_NAME = 0;
public static final int DEADLINE_COMPONENT_INDEX_END_DATE = 1;
public static final int DEADLINE_COMPONENT_INDEX_END_TIME = 2;
public static final int DEADLINE_COMPONENT_COUNT = 3;
public static final int EVENT_COMPONENT_INDEX_NAME = 0;
public static final int EVENT_COMPONENT_INDEX_START_DATE = 1;
public static final int EVENT_COMPONENT_INDEX_START_TIME = 2;
public static final int EVENT_COMPONENT_INDEX_END_DATE = 3;
public static final int EVENT_COMPONENT_INDEX_END_TIME = 4;
public static final int EVENT_COMPONENT_COUNT = 5;
private Name name;
private TaskDate startDate;
private TaskTime startTime;
private TaskDate endDate;
private TaskTime endTime;
private int numArgs;
private boolean isDone;
private UniqueTagList tags;
/**
* Constructor for a "todo" Task.
* "todo" is a Task only has name
* Every field must be present and not null.
*/
public Task(Name name, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, tags);
this.name = name;
this.tags = new UniqueTagList(tags);
this.numArgs = TASK_COMPONENT_COUNT;
}
/**
* Constructor for a "deadline" Task.
* "deadline" is a Task only has name, endDate and endTime
* Every field must be present and not null.
*/
public Task(Name name, TaskDate endDate, TaskTime endTime, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, endDate, endTime, tags);
this.name = name;
this.endDate = endDate;
this.endTime = endTime;
this.tags = new UniqueTagList(tags);
this.numArgs = DEADLINE_COMPONENT_COUNT;
}
/**
* Constructor for a "event" Task.
* "event" is a Task with all fields.
* This constructor allows nulls and can be used when unsure which values are null
*/
public Task(Name name, TaskDate startDate, TaskTime startTime,
TaskDate endDate, TaskTime endTime, UniqueTagList tags) {
this.name = name;
this.startDate = startDate;
this.startTime = startTime;
this.endDate = endDate;
this.endTime = endTime;
this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list
if (this.startDate != null && this.startTime != null) {
numArgs = EVENT_COMPONENT_COUNT;
} else if (this.endDate != null && this.endTime != null) {
numArgs = DEADLINE_COMPONENT_COUNT;
} else {
numArgs = TASK_COMPONENT_COUNT;
}
}
/**
* Copy constructor.
*/
public Task(ReadOnlyTask source) {
this(source.getName(), source.getStartDate(), source.getStartTime(),
source.getEndDate(), source.getEndTime(), source.getTags());
this.isDone = source.getIsDone();
}
@Override
public Name getName() {
return name;
}
@Override
public TaskDate getStartDate() {
return startDate;
}
@Override
public TaskDate getEndDate() {
return endDate;
}
@Override
public TaskTime getStartTime() {
return startTime;
}
@Override
public TaskTime getEndTime() {
return endTime;
}
@Override
public int getNumArgs() {
return numArgs;
}
//@@author
@Override
public UniqueTagList getTags() {
return new UniqueTagList(tags);
}
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
/**
* Marks task as done.
*/
public void markAsDone() {
if (!isDone) {
this.isDone = true;
}
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(name, tags);
}
@Override
public String toString() {
return getAsText();
}
@Override
public boolean getIsDone() {
return isDone;
}
@Override
public boolean isTodo() {
return numArgs == 1;
}
@Override
public boolean isDeadline() {
return numArgs == 3;
}
@Override
public boolean isEvent() {
return numArgs == 5;
}
} |
package uk.me.karlsen.ode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class ReaderWriter {
RandomAccessFile raf = null;
public ReaderWriter(String path){
this(path, true);
}
public ReaderWriter(String path, boolean readOnly){
File f = new File(path);
try {
if(readOnly) {
raf = new RandomAccessFile(f, "r");
} else {
raf = new RandomAccessFile(f, "rw");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
}
public ReaderWriter(String origPath, String newPath){
File f = new File(origPath);
File newFile = this.createNewFile(f, newPath);
try {
raf = new RandomAccessFile(newFile, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
}
private File createNewFile(File originalFile, String newPath) {
FileInputStream fis = null;
try {
fis = new FileInputStream(originalFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
File newFile = new File(newPath);
try {
newFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
FileChannel fisChannel = fis.getChannel();
FileChannel fosChannel = fos.getChannel();
try {
fosChannel.transferFrom(fisChannel, 0, fisChannel.size());
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
try {
fisChannel.close();
fosChannel.close();
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
return newFile;
}
public void seek(long position){
try {
raf.seek(position);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public int read(){
int read = -1;
try {
read = raf.read();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
return read;
}
public byte readByte(){
byte read = -1;
try {
read = raf.readByte();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
return read;
}
public byte[] readBytes(int numBytes){
byte[] bytes = new byte[numBytes];
try {
raf.read(bytes);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
return bytes;
}
public void writeBytes(byte[] bytes, long pos){
System.out.println("Writing bytes to " + pos);
try {
raf.seek(pos);
raf.write(bytes);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public void writeByte(byte b, long pos){
System.out.println("Writing byte to " + pos);
try {
raf.seek(pos);
raf.write(b);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
} |
package com.lightcrafts.jai.utils;
import com.lightcrafts.jai.JAIContext;
import com.lightcrafts.utils.LCArrays;
import com.lightcrafts.utils.MemoryLimits;
import com.lightcrafts.utils.cache.*;
import com.sun.media.jai.util.CacheDiagnostics;
import com.sun.media.jai.util.ImageUtil;
import lombok.Getter;
import lombok.Setter;
import javax.media.jai.EnumeratedParameter;
import javax.media.jai.TileCache;
import javax.media.jai.util.ImagingListener;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.prefs.Preferences;
/**
* This is Sun Microsystems' reference implementation of the
* <code>javax.media.jai.TileCache</code> interface. It provides a
* central location for images to cache computed tiles, and is used as
* the default tile cache mechanism when no other tile cache objects
* are specified.
*
* <p> In this implementation, the cache size is limited by the memory
* capacity, which may be set at construction time or using the
* <code>setMemoryCapacity(long)</code> method. The tile capacity
* is not used. Different images may have very different tile sizes.
* Therefore, the memory usage for a specific tile capacity may vary
* greatly depends on the type of images involved. In fact, the tile
* capacity is rather meaningless.
*
* @see javax.media.jai.TileCache
*
*/
public final class LCTileCache extends Observable
implements TileCache,
CacheDiagnostics {
/** The default memory capacity of the cache (16 MB). */
private static final long DEFAULT_MEMORY_CAPACITY = 16L * 1024L * 1024L;
/** The default hashtable capacity (heuristic) */
private static final int DEFAULT_HASHTABLE_CAPACITY = 1009; // prime number
/** The hashtable load factor */
private static final float LOAD_FACTOR = 0.5F;
/** Listener for the flush() method, to detect low memory situations. */
@Setter
private static LCTileCacheListener Listener;
/**
* The tile cache.
* A Hashtable is used to cache the tiles. The "key" is a
* <code>Object</code> determined based on tile owner's UID if any or
* hashCode if the UID doesn't exist, and tile index. The
* "value" is a LCCachedTile.
*/
@Getter
private Hashtable<Object, LCCachedTile> cachedObject;
/**
* Sorted (Tree) Set used with tile metrics.
* Adds another level of metrics used to determine
* which tiles are removed during memoryControl().
*/
private SortedSet<LCCachedTile> cacheSortedSet;
private LinkedList<LCCachedTile> tileList;
/** The memory capacity of the cache. */
@Getter
private long memoryCapacity;
/** The amount of memory currently being used by the cache. */
@Getter
private long cacheMemoryUsed = 0;
/** The amount of memory to keep after memory control */
private float memoryThreshold = 0.75F;
/** A indicator for tile access time. */
private long timeStamp = 0;
/** Custom tileComparator used to determine tile cost or
* priority ordering in the tile cache.
*/
@Getter
private Comparator tileComparator = null;
/** Tile count used for diagnostics */
@Getter
private long cacheTileCount = 0;
/** Cache hit count */
@Getter
private long cacheHitCount = 0;
/** Cache miss count */
@Getter
private long cacheMissCount = 0;
/** Diagnostics enable/disable */
private boolean diagnostics;
private Cache m_objectCache;
// diagnostic actions
// !!! If actions are changed in any way (removal, modification, addition)
// then the getCachedTileActions() method below should be changed to match.
private static final int ADD = 0;
private static final int REMOVE = 1;
private static final int REMOVE_FROM_FLUSH = 2;
private static final int REMOVE_FROM_MEMCON = 3;
private static final int UPDATE_FROM_ADD = 4;
private static final int UPDATE_FROM_GETTILE = 5;
private static final int ABOUT_TO_REMOVE = 6;
private static final int REMOVE_FROM_GCEVENT = 7;
/**
* Returns an array of <code>EnumeratedParameter</code>s corresponding
* to the numeric values returned by the <code>getAction()</code>
* method of the <code>CachedTile</code> implementation used by
* <code>SunTileCache</code>. The "name" of each
* <code>EnumeratedParameter</code> provides a brief string
* describing the numeric action value.
*/
public static EnumeratedParameter[] getCachedTileActions() {
return new EnumeratedParameter[] {
new EnumeratedParameter("add", ADD),
new EnumeratedParameter("remove", REMOVE),
new EnumeratedParameter("remove_by_flush", REMOVE_FROM_FLUSH),
new EnumeratedParameter("remove_by_memorycontrol",
REMOVE_FROM_MEMCON),
new EnumeratedParameter("remove_by_gcevent",
REMOVE_FROM_GCEVENT),
new EnumeratedParameter("timestamp_update_by_add", UPDATE_FROM_ADD),
new EnumeratedParameter("timestamp_update_by_gettile",
UPDATE_FROM_GETTILE),
new EnumeratedParameter("preremove", ABOUT_TO_REMOVE)
};
}
/**
* No args constructor. Use the DEFAULT_MEMORY_CAPACITY of 16 Megs.
*/
public LCTileCache(boolean useDisk) {
this(DEFAULT_MEMORY_CAPACITY, useDisk);
}
public LCTileCache(long memoryCapacity, boolean useDisk) {
if (memoryCapacity < 0) {
throw new IllegalArgumentException("memory capacity must be >= 0");
}
this.memoryCapacity = memoryCapacity;
// try to get a prime number (more efficient?)
// lower values of LOAD_FACTOR increase speed, decrease space efficiency
cachedObject = new Hashtable<>(DEFAULT_HASHTABLE_CAPACITY, LOAD_FACTOR);
tileList = new LinkedList<>();
if (useDisk) {
m_objectCache = createDiskCache();
m_tileReaper = new TileReaper( this );
m_tileReaper.start();
}
}
/**
* Adds a tile to the cache.
*
* <p> If the specified tile is already in the cache, it will not be
* cached again. If by adding this tile, the cache exceeds the memory
* capacity, older tiles in the cache are removed to keep the cache
* memory usage under the specified limit.
*
* @param owner The image the tile blongs to.
* @param tileX The tile's X index within the image.
* @param tileY The tile's Y index within the image.
* @param tile The tile to be cached.
*/
@Override
public void add(RenderedImage owner,
int tileX,
int tileY,
Raster tile) {
add(owner, tileX, tileY, tile, null);
}
/**
* Adds a tile to the cache with an associated tile compute cost.
*
* <p> If the specified tile is already in the cache, it will not be
* cached again. If by adding this tile, the cache exceeds the memory
* capacity, older tiles in the cache are removed to keep the cache
* memory usage under the specified limit.
*
* @param owner The image the tile blongs to.
* @param tileX The tile's X index within the image.
* @param tileY The tile's Y index within the image.
* @param tile The tile to be cached.
* @param tileCacheMetric Metric for prioritizing tiles
*/
@Override
public synchronized void add(RenderedImage owner,
int tileX,
int tileY,
Raster tile,
Object tileCacheMetric) {
if ( memoryCapacity == 0 ) {
return;
}
// This tile is not in the cache; create a new LCCachedTile.
// else just update.
Object key = LCCachedTile.hashKey(owner, tileX, tileY);
LCCachedTile ct = cachedObject.get(key);
if ( ct != null ) {
updateTileList(ct, UPDATE_FROM_ADD);
} else {
// create a new tile
ct = new LCCachedTile(owner, tileX, tileY, tile, tileCacheMetric);
updateTileList(ct, ADD);
// add to tile cache
if ( cachedObject.put(ct.key, ct) == null ) {
cacheMemoryUsed += ct.tileSize;
cacheTileCount++;
//cacheMissCount++; Not necessary?
if ( cacheSortedSet != null ) {
cacheSortedSet.add(ct);
}
}
// Bring memory usage down to memoryThreshold % of memory capacity.
if (cacheMemoryUsed > memoryCapacity) {
memoryControl();
}
}
if (m_tileReaper != null) {
// TODO: do we need this?
synchronized ( this ) {
Reference<RenderedImage> weakKey = null;
Set<Reference<RenderedImage>> keySet = m_imageMap.keySet();
for (Reference<RenderedImage> ref : keySet) {
if (ref.get() == owner) {
weakKey = ref;
break;
}
}
// weakKey = (WeakReference) m_weakRefMap.get(owner);
if (weakKey == null) {
weakKey = new WeakReference<>( owner, m_tileReaper.getRefQ() );
// m_weakRefMap.put(owner, weakKey);
}
Set<Object> hashKeys = m_imageMap.computeIfAbsent(weakKey, k -> new HashSet<>());
hashKeys.add(key);
}
}
}
private boolean removeFromTileList(Object key, int action) {
LCCachedTile ct = cachedObject.remove(key);
if (ct != null) {
cacheMemoryUsed -= ct.tileSize;
cacheTileCount
if ( cacheSortedSet != null ) {
cacheSortedSet.remove(ct);
}
tileList.remove(ct);
// Notify observers that a tile has been removed.
if ( diagnostics ) {
ct.action = action;
setChanged();
notifyObservers(ct);
}
return true;
}
return false;
}
private void updateTileList(LCCachedTile ct, int action) {
ct.tileTimeStamp = timeStamp++;
if (tileList.isEmpty()) {
tileList.add(ct);
}
else if (!tileList.getFirst().equals(ct)) {
// Bring this tile to the beginning of the list.
tileList.remove(ct);
tileList.addFirst(ct);
}
cacheHitCount++;
if ( diagnostics ) {
ct.action = action;
setChanged();
notifyObservers(ct);
}
}
/**
* Removes a tile from the cache.
*
* <p> If the specified tile is not in the cache, this method
* does nothing.
*/
@Override
public synchronized void remove(RenderedImage owner,
int tileX,
int tileY) {
if ( memoryCapacity == 0 ) {
return;
}
Object key = LCCachedTile.hashKey(owner, tileX, tileY);
LCCachedTile ct = cachedObject.get(key);
if ( ct != null ) {
// Notify observers that a tile is about to be removed.
// It is possible that the tile will be removed from the
// cache before the observers get notified. This should
// be ok, since a hard reference to the tile will be
// kept for the observers, so the garbage collector won't
// remove the tile until the observers release it.
ct.action = ABOUT_TO_REMOVE;
setChanged();
notifyObservers(ct);
removeFromTileList(key, REMOVE);
} else {
// if the tile is not in the memory cache than it might be on disk...
if (m_objectCache != null && m_objectCache.contains(key)) {
m_objectCache.remove(key);
tilesOnDisk
}
}
}
/**
* Retrieves a tile from the cache.
*
* <p> If the specified tile is not in the cache, this method
* returns <code>null</code>. If the specified tile is in the
* cache, its last-access time is updated.
*
* @param owner The image the tile blongs to.
* @param tileX The tile's X index within the image.
* @param tileY The tile's Y index within the image.
*/
@Override
public synchronized Raster getTile(RenderedImage owner,
int tileX,
int tileY) {
if ( memoryCapacity == 0 )
return null;
Object key = LCCachedTile.hashKey(owner, tileX, tileY);
LCCachedTile ct = cachedObject.get(key);
if (m_objectCache != null && ct == null) {
Raster raster = readTileFromDisk(owner, tileX, tileY, key);
if (raster != null) {
add(owner, tileX, tileY, raster, null);
ct = cachedObject.get(key);
assert ct != null;
}
}
Raster tile = null;
if ( ct == null ) {
cacheMissCount++;
} else { // found tile in cachedObject
tile = ct.getTile();
updateTileList(ct, UPDATE_FROM_GETTILE);
}
return tile;
}
/**
* Retrieves a contiguous array of all tiles in the cache which are
* owned by the specified image. May be <code>null</code> if there
* were no tiles in the cache. The array contains no null entries.
*
* @param owner The <code>RenderedImage</code> to which the tiles belong.
* @return An array of all tiles owned by the specified image or
* <code>null</code> if there are none currently in the cache.
*/
@Override
public synchronized Raster[] getTiles(RenderedImage owner) {
Raster[] tiles = null;
if ( memoryCapacity == 0 ) {
return null;
}
int size = Math.min(owner.getNumXTiles() * owner.getNumYTiles(),
(int) cacheTileCount);
if ( size > 0 ) {
int minTx = owner.getMinTileX();
int minTy = owner.getMinTileY();
int maxTx = minTx + owner.getNumXTiles();
int maxTy = minTy + owner.getNumYTiles();
// arbitrarily set a temporary vector size
Vector<Raster> temp = new Vector<>(10, 20);
for (int y = minTy; y < maxTy; y++) {
for (int x = minTx; x < maxTx; x++) {
Raster raster = getTile(owner, x, y);
if ( raster != null ) {
temp.add(raster);
}
}
}
int tmpsize = temp.size();
if ( tmpsize > 0 ) {
tiles = temp.toArray(new Raster[tmpsize]);
}
}
return tiles;
}
/**
* Removes all the tiles that belong to a <code>RenderedImage</code>
* from the cache.
*
* @param owner The image whose tiles are to be removed from the cache.
*/
@Override
public void removeTiles(RenderedImage owner) {
if ( memoryCapacity > 0 ) {
int minTx = owner.getMinTileX();
int minTy = owner.getMinTileY();
int maxTx = minTx + owner.getNumXTiles();
int maxTy = minTy + owner.getNumYTiles();
for (int y=minTy; y<maxTy; y++) {
for (int x=minTx; x<maxTx; x++) {
remove(owner, x, y);
}
}
}
}
/**
* Adds an array of tiles to the tile cache.
*
* @param owner The <code>RenderedImage</code> that the tile belongs to.
* @param tileIndices An array of <code>Point</code>s containing the
* <code>tileX</code> and <code>tileY</code> indices for each tile.
* @param tiles The array of tile <code>Raster</code>s containing tile data.
* @param tileCacheMetric Object which provides an ordering metric
* associated with the <code>RenderedImage</code> owner.
* @since 1.1
*/
@Override
public synchronized void addTiles(RenderedImage owner,
Point[] tileIndices,
Raster[] tiles,
Object tileCacheMetric) {
if ( memoryCapacity == 0 ) {
return;
}
for ( int i = 0; i < tileIndices.length; i++ ) {
int tileX = tileIndices[i].x;
int tileY = tileIndices[i].y;
Raster tile = tiles[i];
add(owner, tileX, tileY, tile, tileCacheMetric);
}
}
/**
* Returns an array of tile <code>Raster</code>s from the cache.
* Any or all of the elements of the returned array may be <code>null</code>
* if the corresponding tile is not in the cache.
*
* @param owner The <code>RenderedImage</code> that the tile belongs to.
* @param tileIndices An array of <code>Point</code>s containing the
* <code>tileX</code> and <code>tileY</code> indices for each tile.
* @since 1.1
*/
@Override
public synchronized Raster[] getTiles(RenderedImage owner, Point[] tileIndices) {
if ( memoryCapacity == 0 ) {
return null;
}
Raster[] tiles = new Raster[tileIndices.length];
for ( int i = 0; i < tiles.length; i++ ) {
int tileX = tileIndices[i].x;
int tileY = tileIndices[i].y;
tiles[i] = getTile(owner, tileX, tileY);
}
return tiles;
}
/** Removes -ALL- tiles from the cache. */
@Override
public synchronized void flush() {
// Call the LCTileCacheListener, if one is defined. This helps detect
// low memory conditions.
if (Listener != null) {
Listener.tileCacheFlushed();
}
// NOTE: we don't do flushing for disk caches, it wipes the persistent cache, rather spill half of the cache out
if (m_objectCache != null) {
System.err.println("flushing the cache");
float mt = memoryThreshold;
memoryThreshold = 0.1f;
memoryControl();
memoryThreshold = mt;
return;
}
// It is necessary to clear all the elements
// from the old cache in order to remove dangling
// references, due to the linked list. In other
// words, it is possible to reache the object
// through 2 paths so the object does not
// become weakly reachable until the reference
// to it in the hash map is null. It is not enough
// to just set the object to null.
cachedObject.forEach((key, ct) -> removeFromTileList(key, REMOVE_FROM_FLUSH));
// reset counters before diagnostics
cacheHitCount = 0;
cacheMissCount = 0;
if ( memoryCapacity > 0 ) {
cachedObject = new Hashtable<>(DEFAULT_HASHTABLE_CAPACITY, LOAD_FACTOR);
}
if ( cacheSortedSet != null ) {
cacheSortedSet.clear();
cacheSortedSet = Collections.synchronizedSortedSet( new TreeSet<LCCachedTile>(tileComparator) );
}
tileList.clear();
// force reset after diagnostics
cacheTileCount = 0;
timeStamp = 0;
cacheMemoryUsed = 0;
// no System.gc() here, it's too slow and may occur anyway.
}
/**
* Returns the cache's tile capacity.
*
* <p> This implementation of <code>TileCache</code> does not use
* the tile capacity. This method always returns 0.
*/
@Override
public int getTileCapacity() { return 0; }
/**
* Sets the cache's tile capacity to the desired number of tiles.
*
* <p> This implementation of <code>TileCache</code> does not use
* the tile capacity. The cache size is limited by the memory
* capacity only. This method does nothing and has no effect on
* the cache.
*
* @param tileCapacity The desired tile capacity for this cache
* in number of tiles.
*/
@Override
public void setTileCapacity(int tileCapacity) { }
@Override
public void setMemoryCapacity(long memoryCapacity) {
if (memoryCapacity < 0) {
throw new IllegalArgumentException("memory capacity must be >= 0");
} else if ( memoryCapacity == 0 ) {
flush();
}
this.memoryCapacity = memoryCapacity;
if ( cacheMemoryUsed > memoryCapacity ) {
memoryControl();
}
}
/** Enable Tile Monitoring and Diagnostics */
@Override
public void enableDiagnostics() {
diagnostics = true;
}
/** Turn off diagnostic notification */
@Override
public void disableDiagnostics() {
diagnostics = false;
}
/**
* Reset hit and miss counters.
*
* @since 1.1
*/
@Override
public void resetCounts() {
cacheHitCount = 0;
cacheMissCount = 0;
}
/**
* Set the memory threshold value.
*
* @since 1.1
*/
@Override
public void setMemoryThreshold(float mt) {
if ( mt < 0.0F || mt > 1.0F ) {
throw new IllegalArgumentException("memory threshold must be between 0 and 1");
} else {
memoryThreshold = mt;
memoryControl();
}
}
/**
* Returns the current <code>memoryThreshold</code>.
*
* @since 1.1
*/
@Override
public float getMemoryThreshold() {
return memoryThreshold;
}
/** Returns a string representation of the class object. */
@Override
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode()) +
": memoryCapacity = " + Long.toHexString(memoryCapacity) +
" cacheMemoryUsed = " + Long.toHexString(cacheMemoryUsed) +
" #tilesInCache = " + cachedObject.size();
}
/**
* Removes tiles from the cache based on their last-access time
* (old to new) until the memory usage is memoryThreshold % of that of the
* memory capacity.
*/
@Override
public synchronized void memoryControl() {
if ( cacheSortedSet == null ) {
standard_memory_control();
} else {
custom_memory_control();
}
}
// time stamp based memory control (LRU)
private void standard_memory_control() {
long limit = (long)(memoryCapacity * memoryThreshold);
while( cacheMemoryUsed > limit && ! tileList.isEmpty() ) {
final Object lastKey = tileList.getLast().key;
LCCachedTile ct = cachedObject.get(lastKey);
if ( ct != null ) {
if (m_objectCache != null) {
RenderedImage owner = ct.getOwner();
if (owner != null && owner.getProperty(JAIContext.PERSISTENT_CACHE_TAG) == Boolean.TRUE) {
writeTileToDisk(ct, lastKey);
}
}
removeFromTileList(lastKey, REMOVE_FROM_MEMCON);
}
}
}
private static class TileCacheCacheObjectBroker implements CacheObjectBroker {
@Override
public int getEncodedSizeOf( Object obj ) {
if ( obj instanceof byte[] ) {
final byte[] ba = (byte[])obj;
return ba.length;
} else if ( obj instanceof short[] ) {
final short[] sa = (short[])obj;
return sa.length * 2;
} else if ( obj instanceof int[] ) {
final int[] ia = (int[])obj;
return ia.length * 4;
} else
throw new IllegalArgumentException(
"can't get size of " + obj.getClass()
);
}
// TODO: cache the ByteBuffer with a soft reference
@Override
public Object decodeFromByteBuffer( ByteBuffer buf, Object obj ) {
if ( obj instanceof byte[] )
if ( buf.hasArray() )
LCArrays.copy( buf.array(), 0, (byte[])obj, 0, buf.capacity() );
else
buf.get( (byte[])obj );
else if ( obj instanceof short[] )
if ( buf.hasArray() )
LCArrays.copy( buf.array(), 0, (short[])obj, 0, buf.capacity() );
else
buf.asShortBuffer().get( (short[])obj );
else if ( obj instanceof int[] )
if ( buf.hasArray() )
LCArrays.copy( buf.array(), 0, (int[])obj, 0, buf.capacity() );
else
buf.asIntBuffer().get( (int[])obj );
else
throw new IllegalArgumentException(
"can't decode " + obj.getClass()
);
return obj;
}
@Override
public void encodeToByteBuffer( ByteBuffer buf, Object obj ) {
if ( obj instanceof byte[] )
if ( buf.hasArray() )
LCArrays.copy( (byte[])obj, 0, buf.array(), 0, buf.capacity() );
else
buf.put( (byte[])obj );
else if ( obj instanceof short[] )
if ( buf.hasArray() )
LCArrays.copy( (short[])obj, 0, buf.array(), 0, buf.capacity() );
else
buf.asShortBuffer().put( (short[])obj );
else if ( obj instanceof int[] )
if ( buf.hasArray() )
LCArrays.copy( (int[])obj, 0, buf.array(), 0, buf.capacity() );
else
buf.asIntBuffer().put( (int[])obj );
else
throw new IllegalArgumentException(
"can't encode " + obj.getClass()
);
}
}
static class CacheFileFilter implements FilenameFilter {
File goodFile;
CacheFileFilter(File goodFile) {
this.goodFile = goodFile;
}
@Override
public boolean accept(File dir, String name) {
return !name.equals(goodFile.getName()) && name.startsWith("LCCacheFile") && name.endsWith(".cce");
}
}
private final static Preferences Prefs =
Preferences.userNodeForPackage(LCTileCache.class);
private final static String CacheDirKey = "ScratchDirectory";
private File tmpFile = null;
private Cache createDiskCache() {
try {
// Try creating the temp file in the user-specified location
String path = Prefs.get(CacheDirKey, null);
tmpFile = null;
if (path != null) {
File tmpDir = new File(path);
if (tmpDir.isDirectory() && tmpDir.canWrite()) {
tmpFile = File.createTempFile("LCCacheFile", ".cce", tmpDir);
}
}
// Fall back to the regular java temp directory
if (tmpFile == null) {
tmpFile = File.createTempFile("LCCacheFile", ".cce");
}
tmpFile.deleteOnExit();
// Try to delete old cache files, checking if the file is locked by some other instance of ourself
File[] oldCacheFiles = tmpFile.getParentFile().listFiles(new CacheFileFilter(tmpFile));
if ( oldCacheFiles != null )
for (File oldCacheFile : oldCacheFiles) {
oldCacheFile.delete();
}
int defaultMemorySize = MemoryLimits.getDefault();
Preferences prefs = Preferences.userRoot().node("/com/lightcrafts/app");
long maxMemory = (long) prefs.getInt("MaxMemory", defaultMemorySize) * 1024 * 1024;
long maxHeap = Runtime.getRuntime().maxMemory();
long extraCacheSize = Math.max( maxMemory - maxHeap, 0 );
System.out.println("Allocating " + (extraCacheSize / (1024 * 1024)) + "MB for the image cache.");
return new Cache(
new TileCacheCacheObjectBroker(),
extraCacheSize < 128 * 1024 * 1024 ?
new WriteThroughCacheObjectMap() :
new LRUCacheObjectMap(
new NativeByteBufferAllocator( CHUNK_SIZE ), extraCacheSize
),
new DirectFileCacheStore( tmpFile ),
new CoalescingFreeBlockManager()
);
}
catch ( IOException e ) {
e.printStackTrace();
return null;
}
}
// private static final long CACHE_SIZE = (long) (1024 * 1024 * 1024);
private static final int CHUNK_SIZE = 16 * 1024 * 1024;
public synchronized void dispose() throws IOException {
m_objectCache.dispose();
// Close and delete the old cache file
if (m_tileReaper != null)
m_tileReaper.kill();
if (tmpFile != null)
tmpFile.delete();
}
/**
* Finalize an <code>LCTileCache</code>.
*/
@Override
protected void finalize() throws Throwable {
dispose();
super.finalize();
}
private long tilesWritten = 0;
private long tilesRead = 0;
private long tilesOnDisk = 0;
public long tilesWritten() {
return tilesWritten;
}
public long tilesRead() {
return tilesRead;
}
public long tilesOnDisk() {
return tilesOnDisk;
}
private Raster readTileFromDisk(RenderedImage owner, int tileX, int tileY, Object key) {
if (m_objectCache.contains(key)) {
SampleModel sm = owner.getSampleModel();
DataBuffer db = sm.createDataBuffer();
try {
switch (db.getDataType()) {
case DataBuffer.TYPE_BYTE:
m_objectCache.getOnce(key, ((DataBufferByte) db).getData());
break;
case DataBuffer.TYPE_USHORT:
m_objectCache.getOnce(key, ((DataBufferUShort) db).getData());
break;
case DataBuffer.TYPE_INT:
m_objectCache.getOnce(key, ((DataBufferInt) db).getData());
break;
default:
throw new IllegalArgumentException("unsupported image type " + db.getClass());
}
synchronized (this) {
tilesOnDisk
}
} catch (IOException e) {
e.printStackTrace();
}
WritableRaster raster;
if (true)
raster = Raster.createWritableRaster(sm, db, new Point(tileX * owner.getTileWidth(),
tileY * owner.getTileHeight()));
else {
int bands = sm.getNumBands();
int[] bandOffsets = ((PixelInterleavedSampleModel) sm).getBandOffsets();
raster = Raster.createInterleavedRaster(db, owner.getTileWidth(), owner.getTileHeight(),
bands * owner.getTileWidth(), bands, bandOffsets,
new Point(tileX * owner.getTileWidth(),
tileY * owner.getTileHeight()));
}
synchronized (this) {
tilesRead++;
}
return raster;
} else
return null;
}
private void writeTileToDisk(LCCachedTile ct, Object key) {
Raster raster = ct.getTile();
DataBuffer db = raster.getDataBuffer();
try {
switch (db.getDataType()) {
case DataBuffer.TYPE_BYTE:
m_objectCache.put(key, ((DataBufferByte) db).getData());
break;
case DataBuffer.TYPE_USHORT:
m_objectCache.put(key, ((DataBufferUShort) db).getData());
break;
case DataBuffer.TYPE_INT:
m_objectCache.put(key, ((DataBufferInt) db).getData());
break;
default:
throw new IllegalArgumentException("unsupported image type " + db.getClass());
}
synchronized (this) {
tilesOnDisk++;
}
} catch (IOException e) {
e.printStackTrace();
}
synchronized (this) {
tilesWritten++;
}
}
// tileComparator based memory control (TreeSet)
private void custom_memory_control() {
long limit = (long)(memoryCapacity * memoryThreshold);
Iterator<LCCachedTile> iter = cacheSortedSet.iterator();
while( iter.hasNext() && (cacheMemoryUsed > limit) ) {
final LCCachedTile ct = iter.next();
cacheMemoryUsed -= ct.tileSize;
synchronized (this) {
cacheTileCount
}
// remove from sorted set
try {
iter.remove();
} catch(ConcurrentModificationException e) {
ImagingListener listener =
ImageUtil.getImagingListener((RenderingHints)null);
listener.errorOccurred("something wrong with the TileCache",
e, this, false);
// e.printStackTrace();
}
tileList.remove(ct);
cachedObject.remove(ct.key);
if ( diagnostics ) {
ct.action = REMOVE_FROM_MEMCON;
setChanged();
notifyObservers(ct);
}
}
// If the custom memory control didn't release sufficient
// number of tiles to satisfy the memory limit, fallback
// to the standard memory controller.
if ( cacheMemoryUsed > limit ) {
standard_memory_control();
}
}
/**
* The <code>Comparator</code> is used to produce an
* ordered list of tiles based on a user defined
* compute cost or priority metric. This determines
* which tiles are subject to "ordered" removal
* during a memory control operation.
*
* @since 1.1
*/
@Override
public synchronized void setTileComparator(Comparator c) {
if (tileComparator != null)
throw new IllegalArgumentException("TileComparator not supported by LCTileCache");
tileComparator = c;
if ( tileComparator == null ) {
// turn off tileComparator
if ( cacheSortedSet != null ) {
cacheSortedSet.clear();
cacheSortedSet = null;
}
} else {
// copy tiles from hashtable to sorted tree set
cacheSortedSet = Collections.synchronizedSortedSet( new TreeSet<LCCachedTile>(tileComparator) );
cachedObject.forEach((key, ct) -> cacheSortedSet.add(ct));
}
}
// test
public void dump() {
System.out.println("first = " + tileList.getFirst());
System.out.println("last = " + tileList.getLast());
int k = 0;
for (LCCachedTile ct : cacheSortedSet) {
System.out.println(k++);
System.out.println(ct);
}
}
void sendExceptionToListener(String message, Exception e) {
ImagingListener listener =
ImageUtil.getImagingListener((RenderingHints)null);
listener.errorOccurred(message, e, this, false);
}
/**
* A <code>TileReaper</code> is-a {@link Thread} that runs continuously and
* asynchronously in the background waiting for {@link RenderedImage}s that
* the Java garbage collector has determined are weakly reachable. Once
* that's the case, remove all of a {@link RenderedImage}'s associated
* tiles from the disk cache.
*/
private static final class TileReaper extends Thread {
////////// public /////////////////////////////////////////////////////
/**
* Run the thread: wait for a weakly reachable {@link RenderedImage} to
* become available and remove all of its tiles from the disk cache
* (if any).
*/
@Override
public void run() {
while ( !m_killed ) {
try {
final Reference weakKey = m_refQ.remove(); // Image to be garbage collected
final LCTileCache tileCache =
m_tileCacheRef.get();
if ( tileCache == null )
break;
synchronized ( tileCache ) {
// System.out.println( "Removing tiles from caches" );
Set hashKeys = tileCache.m_imageMap.remove(weakKey);
assert hashKeys != null;
for (Object o : hashKeys) {
if (tileCache.removeFromTileList(o, REMOVE_FROM_GCEVENT)) {
// System.out.println("removed entry from memory cache");
}
if (tileCache.m_objectCache.remove(o)) {
synchronized (tileCache) {
tileCache.tilesOnDisk
}
// System.out.println("removed entry from disk cache");
}
}
}
}
catch ( InterruptedException e ) {
// do nothing
}
}
}
////////// package ////////////////////////////////////////////////////
/**
* Construct a <code>TileReaper</code> and make it a daemon.
*/
TileReaper( LCTileCache tileCache ) {
super("TileReaper");
setDaemon( true );
m_refQ = new ReferenceQueue<>();
m_tileCacheRef = new WeakReference<>( tileCache );
}
/**
* Gets the {@link ReferenceQueue} being used.
*
* @return Returns said {@link ReferenceQueue}.
*/
ReferenceQueue<RenderedImage> getRefQ() {
return m_refQ;
}
/**
* Kill this thread.
*/
void kill() {
m_killed = true;
interrupt();
}
////////// private ////////////////////////////////////////////////////
/**
* A flag to indicate whether this thread has been killed.
*/
private boolean m_killed;
/**
* The {@link ReferenceQueue} wherein the Java garbage collector
* deposits objects that have become weakly reachable.
*/
private final ReferenceQueue<RenderedImage> m_refQ;
/**
* A {@link WeakReference} to the owning {@link LCTileCache}.
* TODO: explain why this is needed instead of using an inner class.
*/
private final WeakReference<LCTileCache> m_tileCacheRef;
}
/**
* This is a set of {@link WeakReference}s to {@link RenderedImage}s.
*/
private final Map<Reference<RenderedImage>, Set<Object>> m_imageMap = new HashMap<>();
/**
* The {@link TileReaper} associated with this <code>LCTileCache</code>.
*/
private TileReaper m_tileReaper;
}
/* vim:set et sw=4 ts=4: */ |
package dr.evomodel.treedatalikelihood.continuous.cdi;
import dr.math.matrixAlgebra.missingData.MissingOps;
import org.ejml.data.Complex64F;
import org.ejml.data.DenseMatrix64F;
import org.ejml.factory.DecompositionFactory;
import org.ejml.interfaces.decomposition.EigenDecomposition;
import org.ejml.ops.EigenOps;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Paul Bastide
*/
public class SafeMultivariateActualizedWithDriftIntegratorTest {
// @Test
// public void getBranchMatrices() throws Exception {
interface Instance {
int getDimTrait();
double[] getPrecision();
double[] getSelectionStrength();
double[] getStationaryVariance();
double[] getEigenValuesStrengthOfSelection();
double[] getEigenVectorsStrengthOfSelection();
abstract class Basic implements Instance {
private EigenDecomposition decomposeStrenghtOfSelection(double[] Aparam){
int n = getDimTrait();
DenseMatrix64F A = MissingOps.wrap(Aparam, 0, n, n);
// Decomposition
EigenDecomposition eigA = DecompositionFactory.eig(n, true, true);
if( !eigA.decompose(A) ) throw new RuntimeException("Eigen decomposition failed.");
return eigA;
}
final EigenDecomposition eigenDecompositionStrengthOfSelection = decomposeStrenghtOfSelection(getSelectionStrength());
public double[] getEigenValuesStrengthOfSelection() {
int dim = getDimTrait();
double[] eigA = new double[dim];
for (int p = 0; p < dim; ++p) {
Complex64F ev = eigenDecompositionStrengthOfSelection.getEigenvalue(p);
if (!ev.isReal()) throw new RuntimeException("Selection strength A should only have real eigenvalues.");
eigA[p] = ev.real;
}
return eigA;
}
public double[] getEigenVectorsStrengthOfSelection() {
return EigenOps.createMatrixV(eigenDecompositionStrengthOfSelection).data;
}
}
}
/**
* Results obtained using the following R code:
*
* variance <- matrix(data = c(1, 0, 0, 1), 2, 2)
* alpha <- matrix(data = c(1, 0, 0, 1), 2, 2)
* gamma <- PylogeneticEM::compute_stationary_variance(variance, alpha)
*
*/
Instance test0 = new Instance.Basic() {
public int getDimTrait(){ return 2;}
public double[] getPrecision() {
return new double[]{
1.0, 0.0,
0.0, 1.0
};
}
public double[] getSelectionStrength() {
return new double[]{
1.0, 0.0,
0.0, 1.0
};
}
public double[] getStationaryVariance() {
return new double[]{
0.5, 0.0,
0.0, 0.5
};
}
};
Instance test1 = new Instance.Basic() {
public int getDimTrait(){ return 2;}
public double[] getPrecision() {
return new double[]{
1.4, 0.4,
0.4, 1.0
};
}
public double[] getSelectionStrength() {
return new double[]{
2.3, 0.2,
0.2, 1.2
};
}
public double[] getStationaryVariance() {
return new double[]{
0.1867037, -0.1309637,
-0.1309637, 0.4922574
};
}
};
Instance test2 = new Instance.Basic() {
public int getDimTrait(){ return 5;}
public double[] getPrecision() {
return new double[]{
1.4, 0.4, 0.0, 0.1, 0.9,
0.4, 1.0, 0.3, 0.0, 0.0,
0.0, 0.3, 2.1, 0.2, 0.2,
0.1, 0.0, 0.2, 1.2, 0.5,
0.9, 0.0, 0.2, 0.5, 2.0
};
}
public double[] getSelectionStrength() {
return new double[]{
1.4, 0.0, 0.0, 0.0, 1.0,
0.0, 2.0, 0.5, 0.0, 0.0,
0.0, 0.5, 3.1, 0.0, 0.0,
0.0, 0.0, 0.0, 2.2, 0.4,
1.0, 0.0, 0.0, 0.4, 1.0
};
}
public double[] getStationaryVariance() {
return new double[]{
2.55009871, -0.21879549, 0.064601442, 0.578712147, -2.94641261,
-0.21879549, 0.33965614, -0.082974248, -0.024285677, 0.17602648,
0.06460144, -0.08297425, 0.097219008, -0.004240138, -0.05931872,
0.57871215, -0.02428568, -0.004240138, 0.357880727, -0.77676809,
-2.94641261, 0.17602648, -0.059318715, -0.776768090, 3.68424701
};
}
};
Instance[] all = {test0, test1, test2};
@Test
public void setDiffusionStationaryVariance() throws Exception {
for (Instance test : all) {
PrecisionType precisionType = PrecisionType.FULL;
int numTraits = 1;
int dimTrait = test.getDimTrait();
int partialBufferCount = 1;
int matrixBufferCount = 1;
SafeMultivariateActualizedWithDriftIntegrator cdi = new SafeMultivariateActualizedWithDriftIntegrator(
precisionType,
numTraits,
dimTrait,
partialBufferCount,
matrixBufferCount
);
double precision[] = test.getPrecision();
cdi.setDiffusionPrecision(0, precision, 2.0);
double[] alphaEig = test.getEigenValuesStrengthOfSelection();
double[] alphaRot = test.getEigenVectorsStrengthOfSelection();
cdi.setDiffusionStationaryVariance(0, alphaEig, alphaRot);
double[] stationaryVariance = cdi.getStationaryVariance(0);
double expectedStationaryVariance[] = test.getStationaryVariance();
assertEquals(stationaryVariance.length, expectedStationaryVariance.length, 1e-6);
for (int i = 0; i < expectedStationaryVariance.length; ++i) {
assertEquals(stationaryVariance[i], expectedStationaryVariance[i], 1e-6);
}
}
}
// @Test
// public void updateOrnsteinUhlenbeckDiffusionMatrices() throws Exception {
// for (Instance test : all) {
// PrecisionType precisionType = PrecisionType.FULL;
// int numTraits = 1;
// int dimTrait = test.getDimTrait();
// int partialBufferCount = 1;
// int matrixBufferCount = 1;
// SafeMultivariateActualizedWithDriftIntegrator cdi = new SafeMultivariateActualizedWithDriftIntegrator(
// precisionType,
// numTraits,
// dimTrait,
// partialBufferCount,
// matrixBufferCount
// double precision[] = test.getPrecision();
// cdi.setDiffusionPrecision(0, precision, 2.0);
// double alpha[] = test.getSelectionStrength();
// cdi.setDiffusionStationaryVariance(0, alpha);
// final double[] edgeLengths = test.getEdgeLengths();
// final double[] optimalRates = test.getOptimalRates();
// cdi.updateOrnsteinUhlenbeckDiffusionMatrices(0, 0,
// edgeLengths,
// optimalRates,
// alpha,
// @Test
// public void updatePreOrderPartial() throws Exception {
// @Test
// public void updatePartial() throws Exception {
} |
package com.sandwell.JavaSimulation3D;
import com.sun.j3d.utils.picking.PickCanvas;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.media.j3d.Link;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.CapabilityNotSetException;
import javax.media.j3d.Locale;
import javax.media.j3d.Node;
import javax.media.j3d.SceneGraphPath;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.Point;
import java.util.ArrayList;
/**
* Class to implement the picking of objects from the simulation world.
*/
public class PickingListener implements MouseListener {
private PickCanvas pickCanvas;
private final JPopupMenu menu;
public PickingListener(Canvas3D target, Locale locale) {
pickCanvas = new PickCanvas( target, locale );
// pickCanvas.setMode( PickTool.BOUNDS ); // Pick the object based on its bounding box (Huge for objects which are at an angle)
// pickCanvas.setMode(PickTool.GEOMETRY); // This one works better, but still picks over too large an area
pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO); // Pick the object based on its geometry
pickCanvas.setTolerance( 4.0f ); // Mouse click can miss object by as much as 4 pixels
menu = new JPopupMenu();
}
public void destroy() {
pickCanvas = null;
}
/** event handler when the mouse is clicked **/
public void mouseClicked( MouseEvent e ) {
// verify this is an Info Request -- Right Click
if( e.getButton() == MouseEvent.BUTTON3 ) {
processMenuClick( e );
}
}
private void processMenuClick( MouseEvent e ) {
ArrayList<DisplayEntity> entList = getEntityList(e);
menu.removeAll();
// if there is only one entity, display it
if( entList.size() == 1 ) {
entList.get(0).addMenuItems(menu, e.getX(), e.getY());
}
else {
// there are multiple entities, select from a menu
// for each menu, add a menu item that pops up an info box
for( int i = 0; i < entList.size(); i++ ) {
final DisplayEntity thisEnt = entList.get( i );
final Point pt = new Point(e.getX(), e.getY());
final Component canvas = e.getComponent();
JMenuItem thisItem = new JMenuItem(thisEnt.getName());
thisItem.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
menu.removeAll();
thisEnt.addMenuItems(menu, pt.x, pt.y);
menu.show(canvas, pt.x, pt.y);
}
} );
menu.add( thisItem );
}
}
// display the popup menu
menu.show(e.getComponent(), e.getX(), e.getY());
}
public void mouseEntered( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseReleased( MouseEvent e ) {}
/**
* returns the selected DisplayEntities(including TextLabels) for this mouse position.
* If there are no objects, returns null.
* If there are objects, it returns a Vector of those objects
* @param e
* @return
*/
private ArrayList<DisplayEntity> getEntityList(MouseEvent e) {
// 1) All objects but TextLabels are pickable by their geometry
ArrayList<DisplayEntity> results = this.getEntityList_ForPickTool(e, PickTool.GEOMETRY_INTERSECT_INFO);
// 2) TextLabel is only pickable by its bounding box (this picks a lot more objects, but we only need the TextLabels)
ArrayList<DisplayEntity> textLabels = this.getEntityList_ForPickTool(e, PickTool.BOUNDS);
// Only add TextLabels from textLabels list to the results
for (DisplayEntity each : textLabels) {
if (each instanceof TextLabel)
results.add(each);
}
return results;
}
private PickResult[] pickResults(MouseEvent e, int pickMode) {
pickCanvas.setShapeLocation(e);
pickCanvas.setMode(pickMode);
// obtain all of the objects that are located under this ray
try {
return pickCanvas.pickAllSorted();
}
catch (CapabilityNotSetException excep) {
System.out.println("Missing capabilty: " + excep);
return null;
}
catch (NullPointerException excep) {
//FIXME: we sometimes cause a pick to occur on a branchgroup that has been
// detached and we get a null return, return null to the picker and
// hope the next call goes more smoothly
return null;
}
}
private DisplayEntity lookupEntity(SceneGraphPath path) {
if (path.nodeCount() < 2)
return null;
/*
* BranchGroups are returned in order from the top of the
* SceneGraph tree to the bottom. Links are found after all
* Region and DisplayEntity BranchGroups as they will be
* lower in the tree.
*/
Node node = path.getNode(1);
// The item before the first Link(if there is any) is DisplayEntity BranchGroup
for(int i=2; i < path.nodeCount(); i++) {
if(path.getNode(i) instanceof Link)
break;
node = path.getNode(i);
}
if (node.getUserData() instanceof DisplayEntity)
return (DisplayEntity)node.getUserData();
else
return null;
}
/**
* returns the selected DisplayEntities for this mouse position based o picktool property
* If there are no objects, returns null.
* If there are objects, it returns a Vector of those objects
* for all objects but TextLabel use PickTool.GEOMETRY_INTERSECT_INFO
* for TextLabel use PickTool.BOUNDS
* @param e
* @param pickTool
* @return
*/
private ArrayList<DisplayEntity> getEntityList_ForPickTool( MouseEvent e, int pickTool ) {
PickResult[] results = this.pickResults(e, pickTool);
// if there are no objects we are done
if (results == null)
return new ArrayList<DisplayEntity>();
// a list of DisplayEntities
ArrayList<DisplayEntity> entList = new ArrayList<DisplayEntity>();
// go through all of the picked objects and obtain the DisplayEntities that they are related to
for( int i = 0; i < results.length; i++ ) {
DisplayEntity ent = this.lookupEntity(results[i].getSceneGraphPath());
if (ent != null && !entList.contains(ent) && ent.isMovable())
entList.add(ent);
}
// return the list of entities
return entList;
}
/**
* returns the selected DisplayEntities for this mouse position only if their showToolTips are true
* If there are no objects, returns null.
* If there are objects, it returns a Vector of those objects
* @param e
* @return
*/
protected ArrayList<DisplayEntity> getEntityListWithToolTip( MouseEvent e ) {
ArrayList<DisplayEntity> entList = new ArrayList<DisplayEntity>();
for (DisplayEntity each : this.getEntityList(e)) {
if (each.showToolTip()) {
entList.add(each);
}
}
// return the list of entities
if (entList.size() == 0)
return null;
else
return entList;
}
/**
* return the closest DisplayEntity to the mouse pointer
*
* @param e
* @return
*/
protected DisplayEntity getClosestEntity(MouseEvent e) {
// 1) All objects but TextLabels are pickable by their geometry
DisplayEntity result = this.getClosestEntity_ForPickTool( e, PickTool.GEOMETRY_INTERSECT_INFO );
if ( result != null ) {
return result;
}
// 2) TextLabel is only pickable by its bounding box (this picks a lot more objects, but we only need the TextLabels)
result = this.getClosestEntity_ForPickTool( e, PickTool.BOUNDS );
return result;
}
/**
* return the closest DisplayEntity (except Regions) to the mouse pointer based on the picktool property
* for all objects but TextLabel use PickTool.GEOMETRY_INTERSECT_INFO
* for TextLabel use PickTool.BOUNDS
* @param e
* @param pickTool
* @return
*/
private DisplayEntity getClosestEntity_ForPickTool(MouseEvent e, int pickTool) {
PickResult[] results = this.pickResults(e, pickTool);
// if there are no objects we are done
if( results == null ) {
return null;
}
for( int i = 0; i < results.length; i++ ) {
DisplayEntity candidate = this.lookupEntity(results[i].getSceneGraphPath());
if (candidate == null)
continue;
// If we are picking based on bounds candidate should be TextLabel
if( pickTool == PickTool.BOUNDS && !( candidate instanceof TextLabel ) ) {
continue;
}
// Ignore Region
if( ! ( candidate instanceof Region ) ) {
if (candidate.isMovable())
return candidate;
}
}
return null;
}
public JPopupMenu getMenu() {
return menu;
}
} |
package org.openspaces.grid.esm;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jini.rio.boot.BootUtil;
import org.jini.rio.core.ClassBundle;
import org.jini.rio.core.jsb.ServiceBeanContext;
import org.jini.rio.jsb.ServiceBeanActivation;
import org.jini.rio.jsb.ServiceBeanActivation.LifeCycleManager;
import org.jini.rio.jsb.ServiceBeanAdapter;
import org.openspaces.admin.Admin;
import org.openspaces.admin.bean.BeanConfigException;
import org.openspaces.admin.bean.BeanConfigurationException;
import org.openspaces.admin.internal.InternalAdminFactory;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.events.ProcessingUnitAddedEventListener;
import org.openspaces.admin.pu.events.ProcessingUnitRemovedEventListener;
import org.openspaces.grid.gsm.ScaleBeanServer;
import org.openspaces.grid.gsm.containers.ContainersSlaEnforcement;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcement;
import org.openspaces.grid.gsm.rebalancing.RebalancingSlaEnforcement;
import com.gigaspaces.grid.gsa.AgentHelper;
import com.gigaspaces.grid.zone.ZoneHelper;
import com.gigaspaces.internal.dump.InternalDumpException;
import com.gigaspaces.internal.dump.InternalDumpHelper;
import com.gigaspaces.internal.dump.InternalDumpResult;
import com.gigaspaces.internal.jvm.JVMDetails;
import com.gigaspaces.internal.jvm.JVMHelper;
import com.gigaspaces.internal.jvm.JVMStatistics;
import com.gigaspaces.internal.log.InternalLogHelper;
import com.gigaspaces.internal.os.OSDetails;
import com.gigaspaces.internal.os.OSHelper;
import com.gigaspaces.internal.os.OSStatistics;
import com.gigaspaces.log.LogEntries;
import com.gigaspaces.log.LogEntryMatcher;
import com.gigaspaces.log.LogProcessType;
import com.gigaspaces.lrmi.nio.info.NIODetails;
import com.gigaspaces.lrmi.nio.info.NIOInfoHelper;
import com.gigaspaces.lrmi.nio.info.NIOStatistics;
import com.gigaspaces.management.entry.JMXConnection;
import com.gigaspaces.security.SecurityException;
import com.gigaspaces.security.directory.UserDetails;
import com.gigaspaces.security.service.SecurityContext;
import com.gigaspaces.start.SystemBoot;
import com.sun.jini.start.LifeCycle;
public class ESMImpl<x> extends ServiceBeanAdapter implements ESM, ProcessingUnitRemovedEventListener, ProcessingUnitAddedEventListener
/*, RemoteSecuredService*//*, ServiceDiscoveryListener*/ {
private static final String CONFIG_COMPONENT = "org.openspaces.grid.esm";
private static final Logger logger = Logger.getLogger(CONFIG_COMPONENT);
private final Admin admin;
private final MachinesSlaEnforcement machinesSlaEnforcement;
private final ContainersSlaEnforcement containersSlaEnforcement;
private final RebalancingSlaEnforcement rebalancingSlaEnforcement;
private final Map<ProcessingUnit,ScaleBeanServer> scaleBeanServerPerProcessingUnit;
private final Map<String,Map<String,String>> elasticPropertiesPerProcessingUnit;
private LifeCycle lifeCycle;
private String[] configArgs;
/**
* Create an ESM
*/
public ESMImpl() throws Exception {
super();
scaleBeanServerPerProcessingUnit = new HashMap<ProcessingUnit,ScaleBeanServer>();
elasticPropertiesPerProcessingUnit = new ConcurrentHashMap<String, Map<String,String>>();
admin = new InternalAdminFactory().singleThreadedEventListeners().createAdmin();
admin.getProcessingUnits().getProcessingUnitAdded().add(this);
admin.getProcessingUnits().getProcessingUnitRemoved().add(this);
machinesSlaEnforcement = new MachinesSlaEnforcement(admin);
containersSlaEnforcement = new ContainersSlaEnforcement(admin);
rebalancingSlaEnforcement = new RebalancingSlaEnforcement();
}
/**
* Create an ESM launched from the ServiceStarter framework
*/
public ESMImpl(String[] configArgs, LifeCycle lifeCycle)
throws Exception {
this();
this.lifeCycle = lifeCycle;
this.configArgs = configArgs;
bootstrap(configArgs);
}
protected void bootstrap(String[] configArgs) throws Exception {
try {
/* Configure a FaultDetectionHandler for the ESM */
String fdh = "org.openspaces.grid.esm.ESMFaultDetectionHandler";
Object[] fdhConfigArgs = new Object[]{new String[]{
"-",
"org.openspaces.grid.esm.ESMFaultDetectionHandler.invocationDelay=" + System.getProperty("org.openspaces.grid.esm.ESMFaultDetectionHandler.invocationDelay", "1000"),
"org.openspaces.grid.esm.ESMFaultDetectionHandler.retryCount=" + System.getProperty("org.openspaces.grid.esm.ESMFaultDetectionHandler.retryCount", "1"),
"org.openspaces.grid.esm.ESMFaultDetectionHandler.retryTimeout=" + System.getProperty("org.openspaces.grid.esm.ESMFaultDetectionHandler.retryTimeout", "500")
}
};
ClassBundle faultDetectionHandler =
new org.jini.rio.core.ClassBundle(fdh,
null, // load from classpath
new String[]{"setConfiguration"},
new Object[]{ fdhConfigArgs });
context = ServiceBeanActivation.getServiceBeanContext(
CONFIG_COMPONENT,
"ESM",
"Service Grid Infrastructure",
"com.gigaspaces.grid:type=ESM",
faultDetectionHandler,
configArgs,
getClass().getClassLoader());
} catch(Exception e) {
logger.log(Level.SEVERE, "Getting ServiceElement", e);
throw e;
}
try {
start(context);
LifeCycleManager lMgr = (LifeCycleManager)context
.getServiceBeanManager().getDiscardManager();
lMgr.register(getServiceProxy(), context);
} catch(Exception e) {
logger.log(Level.SEVERE, "Register to LifeCycleManager", e);
throw e;
}
}
@Override
public synchronized void initialize(ServiceBeanContext context) throws Exception {
logger.info("Starting ESM ...");
super.initialize(context);
/* Get the JMX Service URL */
String jmxServiceURL = SystemBoot.getJMXServiceURL();
if (jmxServiceURL != null) {
String hostName = BootUtil.getHostAddress();
int port = SystemBoot.getRegistryPort();
String name = context.getServiceElement().getName() +
"_" +
hostName +
"_" +
port;
addAttribute(new JMXConnection(jmxServiceURL, name));
}
}
@Override
public void advertise() throws IOException {
super.advertise();
logger.info("ESM started successfully with groups " + Arrays.toString(admin.getGroups()) + " and locators " + Arrays.toString(admin.getLocators()) + "");
}
@Override
public synchronized void destroy(boolean force) {
logger.info("Stopping ESM ...");
admin.getProcessingUnits().getProcessingUnitRemoved().remove(this);
admin.getProcessingUnits().getProcessingUnitAdded().remove(this);
synchronized (scaleBeanServerPerProcessingUnit) {
for (ScaleBeanServer beanServer : scaleBeanServerPerProcessingUnit.values()) {
beanServer.destroy();
}
this.scaleBeanServerPerProcessingUnit.clear();
}
if (lifeCycle != null) {
lifeCycle.unregister(this);
}
super.destroy(force);
logger.info("ESM stopped successfully");
}
@Override
protected Object createProxy() {
Object proxy = ESMProxy.getInstance((ESM)getExportedProxy(), getUuid());
return(proxy);
}
public int getAgentId() throws RemoteException {
return AgentHelper.getAgentId();
}
public String getGSAServiceID() throws RemoteException {
return AgentHelper.getGSAServiceID();
}
public NIODetails getNIODetails() throws RemoteException {
return NIOInfoHelper.getDetails();
}
public NIOStatistics getNIOStatistics() throws RemoteException {
return NIOInfoHelper.getNIOStatistics();
}
public long getCurrentTimestamp() throws RemoteException {
return System.currentTimeMillis();
}
public OSDetails getOSDetails() throws RemoteException {
return OSHelper.getDetails();
}
public OSStatistics getOSStatistics() throws RemoteException {
return OSHelper.getStatistics();
}
public JVMDetails getJVMDetails() throws RemoteException {
return JVMHelper.getDetails();
}
public JVMStatistics getJVMStatistics() throws RemoteException {
return JVMHelper.getStatistics();
}
public void runGc() throws RemoteException {
System.gc();
}
public String[] getZones() throws RemoteException {
return ZoneHelper.getSystemZones();
}
public LogEntries logEntriesDirect(LogEntryMatcher matcher)
throws RemoteException, IOException {
return InternalLogHelper.logEntriesDirect(LogProcessType.ESM, matcher);
}
public byte[] dumpBytes(String file, long from, int length)
throws RemoteException, IOException {
return InternalDumpHelper.dumpBytes(file, from, length);
}
public InternalDumpResult generateDump(String cause,
Map<String, Object> context) throws RemoteException,
InternalDumpException {
if (context == null) {
context = new HashMap<String, Object>();
}
context.put("esm", this);
return InternalDumpHelper.generateDump(cause, context);
}
public InternalDumpResult generateDump(String cause,
Map<String, Object> context, String... contributors)
throws RemoteException, InternalDumpException {
if (context == null) {
context = new HashMap<String, Object>();
}
context.put("esm", this);
return InternalDumpHelper.generateDump(cause, context, contributors);
}
public String[] getManagedProcessingUnits() {
return scaleBeanServerPerProcessingUnit.keySet().toArray(new String[]{});
}
public boolean isServiceSecured() throws RemoteException {
return false;
}
public SecurityContext login(UserDetails userDetails) throws SecurityException, RemoteException {
return null;
}
public Map<String, String> getProcessingUnitElasticProperties(String processingUnitName) throws RemoteException {
// uses a concurrent hashmap. Consistency not guaranteed with #setPRocessingUnitElasticConfig
return elasticPropertiesPerProcessingUnit.get(processingUnitName);
}
public void setProcessingUnitElasticProperties(final String puName, final Map<String, String> properties) throws RemoteException {
((InternalAdmin)admin).scheduleNonBlockingStateChange(
new Runnable() {
public void run() {
ESMImpl.this.processingUnitElasticPropertiesChanged(puName,properties);
}
}
);
}
public void processingUnitRemoved(ProcessingUnit processingUnit) {
try {
ScaleBeanServer beanServer = scaleBeanServerPerProcessingUnit.remove(processingUnit.getName());
if (beanServer != null) {
beanServer.destroy();
}
}
catch(Exception e) {
logger.log(Level.SEVERE, "Failed to destroy ScaleBeanServer for pu " + processingUnit.getName(),e);
}
}
public void processingUnitAdded(ProcessingUnit pu) {
Map<String,String> puConfig = this.elasticPropertiesPerProcessingUnit.get(pu.getName());
if (puConfig != null) {
refreshProcessingUnitElasticConfig(pu, puConfig);
}
else {
logger.info("Processing Unit " + pu.getName() + " was detected, but elastic properties for that pu was not set yet.");
}
}
private void refreshProcessingUnitElasticConfig(ProcessingUnit pu, Map<String,String> elasticProperties) {
try {
if (pu.getRequiredZones().length != 1) {
throw new BeanConfigurationException("Processing Unit must have exactly one container zone defined.");
}
ScaleBeanServer beanServer = scaleBeanServerPerProcessingUnit.get(pu);
if (beanServer == null) {
beanServer = new ScaleBeanServer(pu,rebalancingSlaEnforcement,containersSlaEnforcement,machinesSlaEnforcement,elasticProperties);
scaleBeanServerPerProcessingUnit.put(pu, beanServer);
logger.info("Elastic properties for pu " + pu.getName() + " are being enforced.");
}
else {
beanServer.setElasticProperties(elasticProperties);
logger.info("Elastic properties for pu " + pu.getName() + " are being refreshed.");
}
}
catch (BeanConfigException e) {
logger.log(Level.SEVERE,"Error configuring elasitc scale bean.",e);
}
}
private void processingUnitElasticPropertiesChanged(String puName, Map<String,String> elasticProperties) {
elasticPropertiesPerProcessingUnit.put(puName,elasticProperties);
ProcessingUnit pu = admin.getProcessingUnits().getProcessingUnit(puName);
if (pu != null) {
refreshProcessingUnitElasticConfig(pu,elasticProperties);
}
else {
logger.info("Elastic properties for pu " + puName + " has been set, but the processing unit itself was not detected yet.");
}
}
} |
package markehme.factionsplus;
import markehme.factionsplus.config.Config;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
public class FactionsPlusTemplates {
public static String Go(String templateOption, String args[]) {
String workingstring = "Invalid Template File for " + templateOption;
if(templateOption == "announcement_message") {
workingstring = Config.templates.getString("announcement_message");
}
if(templateOption == "warp_created") {
workingstring = Config.templates.getString("warp_created");
}
if(templateOption == "notify_warp_created") {
workingstring = Config.templates.getString("notify_warp_created");
}
if(templateOption == "jailed_message") {
workingstring = Config.templates.getString("jailed_message");
}
workingstring = colorFormat(workingstring);
if(args.length == 2) {
workingstring = workingstring.replace("$1", args[1]);
workingstring = workingstring.replace("!1", args[1]);
return(workingstring);
}
if(args.length == 3) {
workingstring = workingstring.replace("!1", args[1]);
workingstring = workingstring.replace("!2", args[2]);
return(workingstring);
}
if(args.length == 4) {
workingstring = workingstring.replaceAll("!1", args[1]);
workingstring = workingstring.replaceAll("!2", args[2]);
workingstring = workingstring.replaceAll("!3", args[3]);
return(workingstring);
}
if(args.length == 5) {
workingstring = workingstring.replace("!1", args[1]);
workingstring = workingstring.replace("!2", args[2]);
workingstring = workingstring.replace("!3", args[3]);
workingstring = workingstring.replace("!4", args[4]);
return(workingstring);
}
return workingstring;
}
public static String colorFormat(String a) {
String b = a.replaceAll("<green>", ChatColor.GREEN + "");
b = b.replaceAll("<red>", ChatColor.RED + "");
b = b.replaceAll("<white>", ChatColor.WHITE + "");
b = b.replaceAll("<purple>", ChatColor.DARK_PURPLE + "");
b = b.replaceAll("<aqua>", ChatColor.AQUA + "");
b = b.replaceAll("<black>", ChatColor.BLACK + "");
b = b.replaceAll("<blue>", ChatColor.BLUE + "");
b = b.replaceAll("<yellow>", ChatColor.YELLOW + "");
b = b.replaceAll("<gray>", ChatColor.GRAY + "");
b = b.replaceAll("<grey>", ChatColor.GRAY + "");
return b;
}
@SuppressWarnings("boxing")
public static void createTemplatesFile() {
try {
if(Config.templatesFile.exists()) {
Config.templatesFile.delete();
}
Config.templatesFile.createNewFile();
Config.templates = YamlConfiguration.loadConfiguration(Config.templatesFile);
// For announcements
Config.templates.set("announcement_message", "<red>!1 <white>announced: !2");
// For warps
Config.templates.set("warp_created", "<green>Warp <white>!1 <green>set for your Faction!");
Config.templates.set("notify_warp_created", "!1 created a warp in your faction called !2");
// For jail
Config.templates.set("jailed_message", "<red>You have been Jailed! If you are unhappy with this faction, you can leave the Faction.");
// Default value don't change
Config.templates.set("doNotChangeMe", 3);
Config.templates.save(Config.templatesFile);
} catch (Exception e) {
e.printStackTrace();
FactionsPlusPlugin.info("ERROR: Couldn't create templates file.");
return;
}
}
} |
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.WeightedRandomItem;
public class DungeonHooks
{
private static int dungeonLootAttempts = 8;
private static ArrayList<DungeonMob> dungeonMobs = new ArrayList<DungeonMob>();
private static ArrayList<DungeonLoot> dungeonLoot = new ArrayList<DungeonLoot>();
/**
* Set the number of item stacks that will be attempted to be added to each Dungeon chest.
* Note: Due to random number generation, you will not always get this amount per chest.
* @param number The maximum number of item stacks to add to a chest.
*/
public static void setDungeonLootTries(int number)
{
dungeonLootAttempts = number;
}
/**
* @return The max number of item stacks found in each dungeon chest.
*/
public static int getDungeonLootTries()
{
return dungeonLootAttempts;
}
/**
* Adds a mob to the possible list of creatures the spawner will create.
* If the mob is already in the spawn list, the rarity will be added to the existing one,
* causing the mob to be more common.
*
* @param name The name of the monster, use the same name used when registering the entity.
* @param rarity The rarity of selecting this mob over others. Must be greater then 0.
* Vanilla Minecraft has the following mobs:
* Spider 100
* Skeleton 100
* Zombie 200
* Meaning, Zombies are twice as common as spiders or skeletons.
* @return The new rarity of the monster,
*/
public static float addDungeonMob(String name, int rarity)
{
if (rarity <= 0)
{
throw new IllegalArgumentException("Rarity must be greater then zero");
}
for (DungeonMob mob : dungeonMobs)
{
if (name.equals(mob.type))
{
return mob.itemWeight += rarity;
}
}
dungeonMobs.add(new DungeonMob(rarity, name));
return rarity;
}
/**
* Will completely remove a Mob from the dungeon spawn list.
*
* @param name The name of the mob to remove
* @return The rarity of the removed mob, prior to being removed.
*/
public static int removeDungeonMob(String name)
{
for (DungeonMob mob : dungeonMobs)
{
if (name.equals(mob.type))
{
dungeonMobs.remove(mob);
return mob.itemWeight;
}
}
return 0;
}
/**
* Gets a random mob name from the list.
* @param rand World generation random number generator
* @return The mob name
*/
public static String getRandomDungeonMob(Random rand)
{
DungeonMob mob = (DungeonMob)WeightedRandom.getRandomItem(rand, dungeonMobs);
if (mob == null)
{
return "";
}
return mob.type;
}
/**
* Adds a item stack to the dungeon loot list with a stack size
* of 1.
*
* @param item The ItemStack to be added to the loot list
* @param rarity The relative chance that this item will spawn, Vanilla has
* most of its items set to 1. Like the saddle, bread, silk, wheat, etc..
* Rarer items are set to lower values, EXA: Golden Apple 0.01
*/
public static void addDungeonLoot(ItemStack item, int rarity)
{
addDungeonLoot(item, rarity, 1, 1);
}
/**
* Adds a item stack, with a range of sizes, to the dungeon loot list.
* If a stack matching the same item, and size range, is already in the list
* the rarities will be added together making the item more common.
*
* @param item The ItemStack to be added to the loot list
* @param rarity The relative chance that this item will spawn, Vanilla has
* most of its items set to 1. Like the saddle, bread, silk, wheat, etc..
* Rarer items are set to lower values, EXA: Golden Apple 0.01
* @param minCount When this item does generate, the minimum number that is in the stack
* @param maxCount When this item does generate, the maximum number that can bein the stack
* @return The new rarity of the loot.
*/
public static float addDungeonLoot(ItemStack item, int rarity, int minCount, int maxCount)
{
for (DungeonLoot loot : dungeonLoot)
{
if (loot.equals(item, minCount, maxCount))
{
return loot.itemWeight += rarity;
}
}
dungeonLoot.add(new DungeonLoot(rarity, item, minCount, maxCount));
return rarity;
}
/**
* Removes a item stack from the dungeon loot list, this will remove all items
* as long as the item stack matches, it will not care about matching the stack
* size ranges perfectly.
*
* @param item The item stack to remove
*/
public static void removeDungeonLoot(ItemStack item)
{
removeDungeonLoot(item, -1, 0);
}
/**
* Removes a item stack from the dungeon loot list. If 'minCount' parameter
* is greater then 0, it will only remove loot items that have the same exact
* stack size range as passed in by parameters.
*
* @param item The item stack to remove
* @param minCount The minimum count for the match check, if less then 0,
* the size check is skipped
* @param maxCount The max count used in match check when 'minCount' is >= 0
*/
public static void removeDungeonLoot(ItemStack item, int minCount, int maxCount)
{
ArrayList<DungeonLoot> lootTmp = (ArrayList<DungeonLoot>)dungeonLoot.clone();
if (minCount < 0)
{
for (DungeonLoot loot : lootTmp)
{
if (loot.equals(item))
{
dungeonLoot.remove(loot);
}
}
}
else
{
for (DungeonLoot loot : lootTmp)
{
if (loot.equals(item, minCount, maxCount))
{
dungeonLoot.remove(loot);
}
}
}
}
/**
* Gets a random item stack to place in a dungeon chest during world generation
* @param rand World generation random number generator
* @return The item stack
*/
public static ItemStack getRandomDungeonLoot(Random rand)
{
DungeonLoot ret = (DungeonLoot)WeightedRandom.getRandomItem(rand, dungeonLoot);
if (ret != null)
{
return ret.generateStack(rand);
}
return null;
}
public static class DungeonLoot extends WeightedRandomItem
{
private ItemStack itemStack;
private int minCount = 1;
private int maxCount = 1;
/**
* @param item A item stack
* @param min Minimum stack size when randomly generating
* @param max Maximum stack size when randomly generating
*/
public DungeonLoot(int weight, ItemStack item, int min, int max)
{
super(weight);
this.itemStack = item;
minCount = min;
maxCount = max;
}
/**
* Grabs a ItemStack ready to be added to the dungeon chest,
* the stack size will be between minCount and maxCount
* @param rand World gen random number generator
* @return The ItemStack to be added to the chest
*/
public ItemStack generateStack(Random rand)
{
ItemStack ret = this.itemStack.copy();
ret.stackSize = minCount + (rand.nextInt(maxCount - minCount + 1));
return ret;
}
public boolean equals(ItemStack item, int min, int max)
{
return (min == minCount && max == maxCount && item.isItemEqual(this.itemStack) && ItemStack.areItemStackTagsEqual(item, this.itemStack));
}
public boolean equals(ItemStack item)
{
return item.isItemEqual(this.itemStack) && ItemStack.areItemStackTagsEqual(item, this.itemStack);
}
}
public static class DungeonMob extends WeightedRandomItem
{
public String type;
public DungeonMob(int weight, String type)
{
super(weight);
this.type = type;
}
@Override
public boolean equals(Object target)
{
if (target instanceof DungeonMob)
{
return this.type.equals(((DungeonMob)target).type);
}
return false;
}
}
public void addDungeonLoot(DungeonLoot loot)
{
dungeonLoot.add(loot);
}
public boolean removeDungeonLoot(DungeonLoot loot)
{
return dungeonLoot.remove(loot);
}
static
{
addDungeonMob("Skeleton", 100);
addDungeonMob("Zombie", 200);
addDungeonMob("Spider", 100);
addDungeonLoot(new ItemStack(Item.saddle), 100 );
addDungeonLoot(new ItemStack(Item.ingotIron), 100, 1, 4);
addDungeonLoot(new ItemStack(Item.bread), 100 );
addDungeonLoot(new ItemStack(Item.wheat), 100, 1, 4);
addDungeonLoot(new ItemStack(Item.gunpowder), 100, 1, 4);
addDungeonLoot(new ItemStack(Item.silk), 100, 1, 4);
addDungeonLoot(new ItemStack(Item.bucketEmpty), 100 );
addDungeonLoot(new ItemStack(Item.appleGold), 001 );
addDungeonLoot(new ItemStack(Item.redstone), 050, 1, 4);
addDungeonLoot(new ItemStack(Item.record13), 005 );
addDungeonLoot(new ItemStack(Item.recordCat), 005 );
addDungeonLoot(new ItemStack(Item.dyePowder, 1, 3), 100 );
}
} |
package net.silentchaos512.gems.block;
import java.util.List;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.lib.EnumGem;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.lib.util.RecipeHelper;
public class BlockGem extends BlockGemSubtypes {
public final boolean supercharged;
public BlockGem(boolean dark, boolean supercharged) {
super(dark, Names.GEM_BLOCK + (supercharged ? "Super" : "") + (dark ? "Dark" : ""));
this.supercharged = supercharged;
setHardness(supercharged ? 7.0f : 3.0f);
setResistance(supercharged ? 6000000.0F : 30.0f);
setStepSound(SoundType.METAL);
setHarvestLevel("pickaxe", supercharged ? 3 : 1);
}
@Override
public void addRecipes() {
for (int i = 0; i < 16; ++i) {
EnumGem gem = getGem(i);
if (supercharged) {
GameRegistry.addRecipe(new ShapedOreRecipe(gem.getBlockSuper(), " g ", "gog", " g ", 'g',
gem.getItemSuperOreName(), 'o', Blocks.obsidian));
} else {
RecipeHelper.addCompressionRecipe(gem.getItem(), gem.getBlock(), 9);
}
}
}
@Override
public void addOreDict() {
for (int i = 0; i < 16; ++i) {
EnumGem gem = getGem(i);
if (supercharged) {
OreDictionary.registerOre(gem.getBlockSuperOreName(), gem.getBlockSuper());
} else {
OreDictionary.registerOre(gem.getBlockOreName(), gem.getBlock());
}
}
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List<String> list,
boolean advanced) {
list.addAll(SilentGems.instance.localizationHelper
.getBlockDescriptionLines(blockName.replaceFirst("Dark", "")));
}
@Override
public EnumRarity getRarity(int meta) {
return supercharged ? EnumRarity.RARE : EnumRarity.COMMON;
}
@Override
public boolean canEntityDestroy(IBlockState state, IBlockAccess world, BlockPos pos,
Entity entity) {
// Does not prevent Withers from breaking. Only the Ender Dragon seems to call this...
if (supercharged) {
return entity instanceof EntityPlayer;
}
return super.canEntityDestroy(state, world, pos, entity);
}
} |
package stroom.statistics.internal;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import io.vavr.Tuple3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.query.api.v2.DocRef;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Passes the internal statistic events to zero-many {@link InternalStatisticsService} instances
* as defined by the docRefTypeToServiceMap
*/
class MultiServiceInternalStatisticsReceiver implements InternalStatisticsReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiServiceInternalStatisticsReceiver.class);
private final Map<String, InternalStatisticsService> docRefTypeToServiceMap;
private final InternalStatisticDocRefCache internalStatisticDocRefCache;
MultiServiceInternalStatisticsReceiver(final InternalStatisticDocRefCache internalStatisticDocRefCache,
final Map<String, InternalStatisticsService> docRefTypeToServiceMap) {
this.docRefTypeToServiceMap = Preconditions.checkNotNull(docRefTypeToServiceMap);
this.internalStatisticDocRefCache = Preconditions.checkNotNull(internalStatisticDocRefCache);
}
@Override
public void putEvent(final InternalStatisticEvent event) {
putEvents(Collections.singletonList(event));
}
@Override
public void putEvents(final List<InternalStatisticEvent> statisticEvents) {
try {
// Group the events by service and docref
Map<InternalStatisticsService, Map<DocRef, List<InternalStatisticEvent>>> serviceToEventsMapMap =
statisticEvents.stream()
.flatMap(event ->
internalStatisticDocRefCache.getDocRefs(event.getKey()).stream()
.map(docRef ->
new Tuple3<>(docRefTypeToServiceMap.get(docRef.getType()),
docRef,
event))
.filter(tuple3 -> tuple3._1() != null))
.collect(Collectors.groupingBy(
Tuple3::_1, //service
Collectors.groupingBy(
Tuple3::_2, //docRef
Collectors.mapping(
Tuple3::_3, //event
Collectors.toList()))));
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Putting {} events to {} services",
statisticEvents.size(),
serviceToEventsMapMap.size());
}
serviceToEventsMapMap.entrySet().forEach(entry -> {
//TODO as it stands if we get a failure to send with one service, we won't send to any other services
//it may be better to record the exception without letting it propagate and then throw an exception at
//the end if any failed
putEvents(entry.getKey(), entry.getValue());
});
} catch (Exception e) {
Throwable rootCause = Throwables.getRootCause(e);
LOGGER.warn("Error sending internal stats to all services [{}]", rootCause.getMessage());
}
}
private void putEvents(final InternalStatisticsService service, Map<DocRef, List<InternalStatisticEvent>> eventsMap) {
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Putting events for docRef(s) [{}] to {}",
eventsMap.keySet().stream()
.map(DocRef::getName)
.collect(Collectors.joining(",")),
service.getClass().getName());
}
service.putEvents(eventsMap);
} catch (Exception e) {
throw new RuntimeException("Error sending internal statistics to service of type " + service.getDocRefType(), e);
}
}
} |
package org.wildfly.extension.undertow.deployment;
import io.undertow.websockets.jsr.JsrWebSocketLogger;
import io.undertow.websockets.jsr.ServerWebSocketContainer;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.naming.ImmediateManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.reflect.DeploymentClassIndex;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.extension.undertow.logging.UndertowLogger;
import javax.websocket.ClientEndpoint;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Deployment processor for native JSR-356 websockets
* <p/>
*
* @author Stuart Douglas
*/
public class UndertowJSRWebSocketDeploymentProcessor implements DeploymentUnitProcessor {
private static final DotName SERVER_ENDPOINT = DotName.createSimple(ServerEndpoint.class.getName());
private static final DotName CLIENT_ENDPOINT = DotName.createSimple(ClientEndpoint.class.getName());
private static final DotName SERVER_APPLICATION_CONFIG = DotName.createSimple(ServerApplicationConfig.class.getName());
private static final DotName ENDPOINT = DotName.createSimple(Endpoint.class.getName());
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentClassIndex classIndex = deploymentUnit.getAttachment(Attachments.CLASS_INDEX);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (module == null) {
return;
}
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(module.getClassLoader());
WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (metaData == null) {
return;
}
final Set<Class<?>> annotatedEndpoints = new HashSet<>();
final Set<Class<? extends Endpoint>> endpoints = new HashSet<>();
final Set<Class<? extends ServerApplicationConfig>> config = new HashSet<>();
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
final List<AnnotationInstance> serverEndpoints = index.getAnnotations(SERVER_ENDPOINT);
if (serverEndpoints != null) {
for (AnnotationInstance endpoint : serverEndpoints) {
if (endpoint.target() instanceof ClassInfo) {
ClassInfo clazz = (ClassInfo) endpoint.target();
try {
Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass();
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
annotatedEndpoints.add(moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e);
}
}
}
}
final List<AnnotationInstance> clientEndpoints = index.getAnnotations(CLIENT_ENDPOINT);
if (clientEndpoints != null) {
for (AnnotationInstance endpoint : clientEndpoints) {
if (endpoint.target() instanceof ClassInfo) {
ClassInfo clazz = (ClassInfo) endpoint.target();
try {
Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass();
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
annotatedEndpoints.add(moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e);
}
}
}
}
final Set<ClassInfo> subclasses = index.getAllKnownImplementors(SERVER_APPLICATION_CONFIG);
if (subclasses != null) {
for (final ClassInfo clazz : subclasses) {
try {
Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass();
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
config.add((Class) moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e);
}
}
}
final Set<ClassInfo> epClasses = index.getAllKnownSubclasses(ENDPOINT);
if (epClasses != null) {
for (final ClassInfo clazz : epClasses) {
try {
Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass();
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
endpoints.add((Class) moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e);
}
}
}
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
doDeployment(webSocketDeploymentInfo, annotatedEndpoints, config, endpoints);
installWebsockets(phaseContext, webSocketDeploymentInfo);
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
}
}
private void installWebsockets(final DeploymentPhaseContext phaseContext, final WebSocketDeploymentInfo webSocketDeploymentInfo) {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
deploymentUnit.putAttachment(UndertowAttachments.WEB_SOCKET_DEPLOYMENT_INFO, webSocketDeploymentInfo);
//bind the container to JNDI to make it available for resource injection
//this is not request by the spec, but is a convenient extension
if(moduleDescription != null) {
final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName());
bindJndiServices(deploymentUnit, phaseContext.getServiceTarget(), moduleContextServiceName, webSocketDeploymentInfo);
}
}
private void bindJndiServices(final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final ServiceName contextServiceName, final WebSocketDeploymentInfo webSocketInfo) {
final ServiceName bindingServiceName = contextServiceName.append("ServerContainer");
final BinderService binderService = new BinderService("ServerContainer");
serviceTarget.addService(bindingServiceName, binderService)
.addDependency(contextServiceName, ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.install();
webSocketInfo.addListener(new WebSocketDeploymentInfo.ContainerReadyListener() {
@Override
public void ready(ServerWebSocketContainer container) {
binderService.getManagedObjectInjector().inject(new ImmediateManagedReferenceFactory(container));
}
});
deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES, bindingServiceName);
}
private void doDeployment(final WebSocketDeploymentInfo container, final Set<Class<?>> annotatedEndpoints, final Set<Class<? extends ServerApplicationConfig>> serverApplicationConfigClasses, final Set<Class<? extends Endpoint>> endpoints) throws DeploymentUnitProcessingException {
Set<Class<? extends Endpoint>> allScannedEndpointImplementations = new HashSet<>(endpoints);
Set<Class<?>> allScannedAnnotatedEndpoints = new HashSet<>(annotatedEndpoints);
Set<Class<?>> newAnnotatatedEndpoints = new HashSet<>();
Set<ServerEndpointConfig> serverEndpointConfigurations = new HashSet<>();
final Set<ServerApplicationConfig> configInstances = new HashSet<>();
for (Class<? extends ServerApplicationConfig> clazz : serverApplicationConfigClasses) {
try {
configInstances.add(clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
JsrWebSocketLogger.ROOT_LOGGER.couldNotInitializeConfiguration(clazz, e);
}
}
if (!configInstances.isEmpty()) {
for (ServerApplicationConfig config : configInstances) {
Set<Class<?>> returnedEndpoints = config.getAnnotatedEndpointClasses(allScannedAnnotatedEndpoints);
if (returnedEndpoints != null) {
newAnnotatatedEndpoints.addAll(returnedEndpoints);
}
Set<ServerEndpointConfig> endpointConfigs = config.getEndpointConfigs(allScannedEndpointImplementations);
if (endpointConfigs != null) {
serverEndpointConfigurations.addAll(endpointConfigs);
}
}
} else {
newAnnotatatedEndpoints.addAll(allScannedAnnotatedEndpoints);
}
//annotated endpoints first
for (Class<?> endpoint : newAnnotatatedEndpoints) {
container.addEndpoint(endpoint);
}
for (final ServerEndpointConfig endpoint : serverEndpointConfigurations) {
container.addEndpoint(endpoint);
}
}
@Override
public void undeploy(final DeploymentUnit context) {
}
} |
package tachyon.conf;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import tachyon.Constants;
import tachyon.util.FormatUtils;
import tachyon.util.network.NetworkAddressUtils;
/**
* <p>
* Configuration of Tachyon. It sets various Tachyon parameters as key-value pairs. This class
* contains all the runtime configuration properties. The default properties is stored in file
* <code>tachyon-default.properties</code> and users can override these default properties by
* modifying file <code>tachyon-site.properties</code>.
* </p>
* <p>
* User can create an instance of this class by <code>new TachyonConf()</code>, which will load
* values from any Java system properties set as well.
* </p>
* The class only supports creation using <code>new TachyonConf(properties)</code> to override
* default values.
*/
public class TachyonConf {
/** File to set default properties */
public static final String DEFAULT_PROPERTIES = "tachyon-default.properties";
/** File to set customized properties */
public static final String SITE_PROPERTIES = "tachyon-site.properties";
/** Regex string to find ${key} for variable substitution */
public static final String REGEX_STRING = "(\\$\\{([^{}]*)\\})";
/** Regex to find ${key} for variable substitution */
public static final Pattern CONF_REGEX = Pattern.compile(REGEX_STRING);
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final Properties mProperties = new Properties();
public static void assertValidPort(final int port, TachyonConf tachyonConf) {
Preconditions.checkArgument(port < 65536, "Port must be less than 65536");
if (!tachyonConf.getBoolean(Constants.IN_TEST_MODE)) {
Preconditions.checkArgument(port > 0, "Port is only allowed to be zero in test mode.");
}
}
public static void assertValidPort(final InetSocketAddress address, TachyonConf tachyonConf) {
assertValidPort(address.getPort(), tachyonConf);
}
/**
* Copy constructor to merge the properties of the incoming <code>TachyonConf</code>.
*
* @param tachyonConf The source {@link tachyon.conf.TachyonConf} to be merged.
*/
public TachyonConf(TachyonConf tachyonConf) {
merge(tachyonConf);
}
/**
* Overrides default properties.
*
* @param props override {@link Properties}
*/
public TachyonConf(Map<String, String> props) {
if (props != null) {
mProperties.putAll(props);
}
}
/**
* Overrides default properties.
*
* @param props override {@link Properties}
*/
public TachyonConf(Properties props) {
if (props != null) {
mProperties.putAll(props);
}
}
/**
* Default constructor.
*
* Most clients will call this constructor to allow default loading of properties to happen.
*/
public TachyonConf() {
this(true);
}
/**
* Test constructor for TachyonConfTest class.
*
* Here is the order of the sources to load the properties:
* -) System properties if desired
* -) Site specific properties via tachyon-site.properties file
* -) Default properties via tachyon-default.properties file
*/
TachyonConf(boolean includeSystemProperties) {
// Load default
Properties defaultProps = new Properties();
// Override runtime default
defaultProps.setProperty(Constants.MASTER_HOSTNAME, NetworkAddressUtils.getLocalHostName(250));
defaultProps.setProperty(Constants.WORKER_MIN_WORKER_THREADS,
String.valueOf(Runtime.getRuntime().availableProcessors()));
defaultProps.setProperty(Constants.MASTER_MIN_WORKER_THREADS,
String.valueOf(Runtime.getRuntime().availableProcessors()));
InputStream defaultInputStream =
TachyonConf.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES);
if (defaultInputStream == null) {
throw new RuntimeException("The default Tachyon properties file does not exist.");
}
try {
defaultProps.load(defaultInputStream);
} catch (IOException e) {
throw new RuntimeException("Unable to load default Tachyon properties file.", e);
}
// Load site specific properties file
Properties siteProps = new Properties();
InputStream siteInputStream =
TachyonConf.class.getClassLoader().getResourceAsStream(SITE_PROPERTIES);
if (siteInputStream != null) {
try {
siteProps.load(siteInputStream);
} catch (IOException e) {
LOG.warn("Unable to load site Tachyon configuration file.", e);
}
}
// Load system properties
Properties systemProps = new Properties();
if (includeSystemProperties) {
systemProps.putAll(System.getProperties());
}
// Now lets combine
mProperties.putAll(defaultProps);
mProperties.putAll(siteProps);
mProperties.putAll(systemProps);
// Update tachyon.master_address
String masterHostname = mProperties.getProperty(Constants.MASTER_HOSTNAME);
String masterPort = mProperties.getProperty(Constants.MASTER_PORT);
boolean useZk = Boolean.parseBoolean(mProperties.getProperty(Constants.USE_ZOOKEEPER));
String masterAddress =
(useZk ? Constants.HEADER_FT : Constants.HEADER) + masterHostname + ":" + masterPort;
mProperties.setProperty(Constants.MASTER_ADDRESS, masterAddress);
}
@Override
public int hashCode() {
int hash = 0;
for (Object s : mProperties.keySet()) {
hash ^= s.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof TachyonConf) {
Properties props = ((TachyonConf) obj).getInternalProperties();
return mProperties.equals(props);
}
return false;
}
/**
* @return the deep copy of the internal <code>Properties</code> of this TachyonConf instance.
*/
public Properties getInternalProperties() {
return SerializationUtils.clone(mProperties);
}
/**
* Merge the current configuration properties with another one. A property from the new
* configuration wins if it also appears in the current configuration.
*
* @param alternateConf The source <code>TachyonConf</code> to be merged.
*/
public void merge(TachyonConf alternateConf) {
if (alternateConf != null) {
// merge the system properties
mProperties.putAll(alternateConf.getInternalProperties());
}
}
// Public accessor methods
public void set(String key, String value) {
mProperties.put(key, value);
}
public String get(String key, final String defaultValue) {
String raw = mProperties.getProperty(key, defaultValue);
String updated = lookup(raw);
LOG.debug("Get Tachyon property {} as {} with default {}", key, updated, defaultValue);
return updated;
}
public String get(String key) {
return get(key, null);
}
public boolean containsKey(String key) {
return mProperties.containsKey(key);
}
public int getInt(String key, final int defaultValue) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Integer.parseInt(lookup(rawValue));
} catch (NumberFormatException e) {
LOG.warn("Configuration cannot evaluate key " + key + " as integer.");
}
}
return defaultValue;
}
public int getInt(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Integer.parseInt(lookup(rawValue));
} catch (NumberFormatException e) {
throw new RuntimeException("Configuration cannot evaluate key " + key + " as integer.");
}
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public long getLong(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Long.parseLong(lookup(rawValue));
} catch (NumberFormatException e) {
LOG.warn("Configuration cannot evaluate key " + key + " as long.");
}
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public double getDouble(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Double.parseDouble(lookup(rawValue));
} catch (NumberFormatException e) {
throw new RuntimeException("Configuration cannot evaluate key " + key + " as double.");
}
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public float getFloat(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Float.parseFloat(lookup(rawValue));
} catch (NumberFormatException e) {
LOG.warn("Configuration cannot evaluate key " + key + " as float.");
}
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public boolean getBoolean(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
return Boolean.parseBoolean(lookup(rawValue));
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public List<String> getList(String key, String delimiter) {
Preconditions.checkArgument(delimiter != null, "Illegal separator for Tachyon properties as "
+ "list");
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
return Lists.newLinkedList(Splitter.on(',').trimResults().omitEmptyStrings().split(rawValue));
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public <T extends Enum<T>> T getEnum(String key, T defaultValue) {
if (mProperties.containsKey(key)) {
final String val = get(key, defaultValue.toString());
return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val);
}
return defaultValue;
}
public long getBytes(String key) {
if (mProperties.containsKey(key)) {
String rawValue = get(key);
try {
return FormatUtils.parseSpaceSize(rawValue);
} catch (Exception ex) {
throw new RuntimeException("Configuration cannot evaluate key " + key + " as bytes.");
}
}
throw new RuntimeException("Invalid configuration key " + key + ".");
}
public <T> Class<T> getClass(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return (Class<T>) Class.forName(rawValue);
} catch (Exception e) {
String msg = "requested class could not be loaded";
LOG.error("{} : {} , {}", msg, rawValue, e);
}
}
// if key is not found among the default properties
throw new RuntimeException("Invalid configuration key " + key + ".");
}
/**
* Return the properties as a Map.
*
* @return a Map from each property name to its property values
*/
public Map<String, String> toMap() {
Map<String, String> copy = new HashMap<String, String>();
for (Enumeration<?> names = mProperties.propertyNames(); names.hasMoreElements();) {
Object key = names.nextElement();
copy.put(key.toString(), mProperties.get(key).toString());
}
return copy;
}
@Override
public String toString() {
return mProperties.toString();
}
/**
* Lookup key names to handle ${key} stuff. Set as package private for testing.
*
* @param base string to look for.
* @return the key name with the ${key} substituted
*/
String lookup(String base) {
return lookup(base, new HashMap<String, String>());
}
/**
* Actual recursive lookup replacement.
*
* @param base the String to look for.
* @param found {@link Map} of String that already seen in this path.
* @return resolved String value.
*/
protected String lookup(final String base, Map<String, String> found) {
// check argument
if (base == null) {
return null;
}
String resolved = base;
// Lets find pattern match to ${key}. TODO: Consider using Apache Commons StrSubstitutor
Matcher matcher = CONF_REGEX.matcher(base);
while (matcher.find()) {
String match = matcher.group(2).trim();
String value;
if (!found.containsKey(match)) {
value = lookup(mProperties.getProperty(match), found);
found.put(match, value);
} else {
value = found.get(match);
}
if (value != null) {
LOG.debug("Replacing {} with {}", matcher.group(1), value);
resolved = resolved.replaceFirst(REGEX_STRING, value);
}
}
return resolved;
}
} |
package gov.hhs.fha.nhinc.saml.extraction;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Jon Hoppesch
*/
public class SamlTokenCreator {
private static Log log = LogFactory.getLog(SamlTokenCreator.class);
/**
* This method will populate a Map with information from the assertion that is used within
* the SAML Token. This Map can be used to set up the requestContext prior to sending
* a message on the Nhin.
*
* @param assertion The assertion object that contains information required by the SAML Token.
* @param url The URL to the destination service.
* @param action The specified Action for this message.
* @return A Map containing all of the information needed for creation of the SAML Token.
*/
public Map CreateRequestContext(AssertionType assertion, String url, String action) {
log.debug("Entering SamlTokenCreator.CreateRequestContext...");
Map<String, String> requestContext = new HashMap<String, String>();
if (assertion != null) {
if (assertion.getUserInfo() != null) {
if (NullChecker.isNotNullish(assertion.getUserInfo().getUserName())) {
requestContext.put(NhincConstants.USER_NAME_PROP, assertion.getUserInfo().getUserName());
}
if (assertion.getUserInfo().getOrg() != null) {
if (NullChecker.isNotNullish(assertion.getUserInfo().getOrg().getName())) {
requestContext.put(NhincConstants.USER_ORG_PROP, assertion.getUserInfo().getOrg().getName());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getOrg().getHomeCommunityId())) {
requestContext.put(NhincConstants.USER_ORG_ID_PROP, assertion.getUserInfo().getOrg().getHomeCommunityId());
}
} else {
log.error("Error: samlSendOperation input assertion user org is null");
}
if (assertion.getUserInfo().getRoleCoded() != null) {
if (NullChecker.isNotNullish(assertion.getUserInfo().getRoleCoded().getCode())) {
requestContext.put(NhincConstants.USER_CODE_PROP, assertion.getUserInfo().getRoleCoded().getCode());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getRoleCoded().getCodeSystem())) {
requestContext.put(NhincConstants.USER_SYST_PROP, assertion.getUserInfo().getRoleCoded().getCodeSystem());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getRoleCoded().getCodeSystemName())) {
requestContext.put(NhincConstants.USER_SYST_NAME_PROP, assertion.getUserInfo().getRoleCoded().getCodeSystemName());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getRoleCoded().getDisplayName())) {
requestContext.put(NhincConstants.USER_DISPLAY_PROP, assertion.getUserInfo().getRoleCoded().getDisplayName());
}
} else {
log.error("Error: samlSendOperation input assertion user info role is null");
}
if (assertion.getUserInfo().getPersonName() != null) {
if (NullChecker.isNotNullish(assertion.getUserInfo().getPersonName().getGivenName())) {
requestContext.put(NhincConstants.USER_FIRST_PROP, assertion.getUserInfo().getPersonName().getGivenName());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getPersonName().getSecondNameOrInitials())) {
requestContext.put(NhincConstants.USER_MIDDLE_PROP, assertion.getUserInfo().getPersonName().getSecondNameOrInitials());
}
if (NullChecker.isNotNullish(assertion.getUserInfo().getPersonName().getFamilyName())) {
requestContext.put(NhincConstants.USER_LAST_PROP, assertion.getUserInfo().getPersonName().getFamilyName());
}
} else {
log.error("Error: samlSendOperation input assertion user person name is null");
}
} else {
log.error("Error: samlSendOperation input assertion user info is null");
}
if (assertion.getPurposeOfDisclosureCoded() != null) {
if (assertion.getPurposeOfDisclosureCoded() != null) {
if (NullChecker.isNotNullish(assertion.getPurposeOfDisclosureCoded().getCode())) {
requestContext.put(NhincConstants.PURPOSE_CODE_PROP, assertion.getPurposeOfDisclosureCoded().getCode());
}
if (NullChecker.isNotNullish(assertion.getPurposeOfDisclosureCoded().getCodeSystem())) {
requestContext.put(NhincConstants.PURPOSE_SYST_PROP, assertion.getPurposeOfDisclosureCoded().getCodeSystem());
}
if (NullChecker.isNotNullish(assertion.getPurposeOfDisclosureCoded().getCodeSystemName())) {
requestContext.put(NhincConstants.PURPOSE_SYST_NAME_PROP, assertion.getPurposeOfDisclosureCoded().getCodeSystemName());
}
if (NullChecker.isNotNullish(assertion.getPurposeOfDisclosureCoded().getDisplayName())) {
requestContext.put(NhincConstants.PURPOSE_DISPLAY_PROP, assertion.getPurposeOfDisclosureCoded().getDisplayName());
}
} else {
log.error("Error: samlSendOperation input assertion purpose coded is null");
}
} else {
log.error("Error: samlSendOperation input assertion purpose is null");
}
if (assertion.getHomeCommunity() != null) {
if (NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) {
requestContext.put(NhincConstants.HOME_COM_PROP, assertion.getHomeCommunity().getHomeCommunityId());
}
} else {
log.error("Error: samlSendOperation input assertion Home Community is null");
}
if (assertion.getUniquePatientId() != null && assertion.getUniquePatientId().size() > 0) {
// take first non-null item in the List as the identifier
for (String patId : assertion.getUniquePatientId()) {
if (NullChecker.isNotNullish(patId)) {
requestContext.put(NhincConstants.PATIENT_ID_PROP, patId);
break;
}
}
}
if (assertion.getSamlAuthnStatement() != null) {
if (NullChecker.isNotNullish(assertion.getSamlAuthnStatement().getAuthInstant())) {
requestContext.put(NhincConstants.AUTHN_INSTANT_PROP, assertion.getSamlAuthnStatement().getAuthInstant());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthnStatement().getSessionIndex())) {
requestContext.put(NhincConstants.AUTHN_SESSION_INDEX_PROP, assertion.getSamlAuthnStatement().getSessionIndex());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthnStatement().getAuthContextClassRef())) {
requestContext.put(NhincConstants.AUTHN_CONTEXT_CLASS_PROP, assertion.getSamlAuthnStatement().getAuthContextClassRef());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthnStatement().getSubjectLocalityAddress())) {
requestContext.put(NhincConstants.SUBJECT_LOCALITY_ADDR_PROP, assertion.getSamlAuthnStatement().getSubjectLocalityAddress());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthnStatement().getSubjectLocalityDNSName())) {
requestContext.put(NhincConstants.SUBJECT_LOCALITY_DNS_PROP, assertion.getSamlAuthnStatement().getSubjectLocalityDNSName());
}
} else {
log.error("Error: samlSendOperation input assertion AuthnStatement is null");
}
if (assertion.getSamlAuthzDecisionStatement() != null) {
requestContext.put(NhincConstants.AUTHZ_STATEMENT_EXISTS_PROP, "true");
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getAction())) {
requestContext.put(NhincConstants.ACTION_PROP, assertion.getSamlAuthzDecisionStatement().getAction());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getResource())) {
requestContext.put(NhincConstants.RESOURCE_PROP, assertion.getSamlAuthzDecisionStatement().getResource());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getDecision())) {
requestContext.put(NhincConstants.AUTHZ_DECISION_PROP, assertion.getSamlAuthzDecisionStatement().getDecision());
}
if (assertion.getSamlAuthzDecisionStatement().getEvidence() != null && assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion() != null) {
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getId())) {
requestContext.put(NhincConstants.EVIDENCE_ID_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getId());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssueInstant())) {
requestContext.put(NhincConstants.EVIDENCE_INSTANT_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssueInstant());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getVersion())) {
requestContext.put(NhincConstants.EVIDENCE_VERSION_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getVersion());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssuer())) {
requestContext.put(NhincConstants.EVIDENCE_ISSUER_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssuer());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssuerFormat())) {
requestContext.put(NhincConstants.EVIDENCE_ISSUER_FORMAT_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getIssuerFormat());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getAccessConsentPolicy())) {
requestContext.put(NhincConstants.EVIDENCE_ACCESS_CONSENT_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getAccessConsentPolicy());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getInstanceAccessConsentPolicy())) {
requestContext.put(NhincConstants.EVIDENCE_INST_ACCESS_CONSENT_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getInstanceAccessConsentPolicy());
}
if (assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getConditions() != null) {
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getConditions().getNotBefore())) {
requestContext.put(NhincConstants.EVIDENCE_CONDITION_NOT_BEFORE_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getConditions().getNotBefore());
}
if (NullChecker.isNotNullish(assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getConditions().getNotOnOrAfter())) {
requestContext.put(NhincConstants.EVIDENCE_CONDITION_NOT_AFTER_PROP, assertion.getSamlAuthzDecisionStatement().getEvidence().getAssertion().getConditions().getNotOnOrAfter());
}
} else {
log.error("Error: samlSendOperation input assertion AuthzDecisionStatement Evidence Conditions is null");
}
} else {
log.error("Error: samlSendOperation input assertion AuthzDecisionStatement Evidence is null");
}
} else {
requestContext.put(NhincConstants.AUTHZ_STATEMENT_EXISTS_PROP, "false");
log.info("AuthzDecisionStatement is null. It will not be part of the SAML Assertion");
}
if (assertion.getSamlIssuer() != null) {
if (NullChecker.isNotNullish(assertion.getSamlIssuer().getIssuer())) {
requestContext.put(NhincConstants.ASSERTION_ISSUER_PROP, assertion.getSamlIssuer().getIssuer());
}
if (NullChecker.isNotNullish(assertion.getSamlIssuer().getIssuerFormat())) {
requestContext.put(NhincConstants.ASSERTION_ISSUER_FORMAT_PROP, assertion.getSamlIssuer().getIssuerFormat());
}
} else {
log.debug("samlSendOperation input assertion Saml Issuer is null");
}
} else {
log.error("Error: samlSendOperation input assertion is null");
}
// This will be overwrite any value that is available in
// assertion.getSamlAuthzDecisionStatement().getResource()
if (NullChecker.isNotNullish(url)) {
requestContext.put(NhincConstants.RESOURCE_PROP, url);
}
// This will be overwrite any value that is available in
// assertion.getSamlAuthzDecisionStatement().getAction()
if (NullChecker.isNotNullish(action)) {
requestContext.put(NhincConstants.ACTION_PROP, action);
}
log.info("Request Context:");
Set allKeys = requestContext.keySet();
for (Object key : allKeys) {
log.info(key + " = " + requestContext.get(key));
}
log.debug("Exiting SamlTokenCreator.CreateRequestContext...");
return requestContext;
}
} |
package net.sf.taverna.t2.workbench.ui.servicepanel.menu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import net.sf.taverna.t2.servicedescriptions.ConfigurableServiceProvider;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
import net.sf.taverna.t2.servicedescriptions.ServiceDescriptionProvider;
import net.sf.taverna.t2.servicedescriptions.ServiceDescriptionRegistry;
import net.sf.taverna.t2.servicedescriptions.impl.ServiceDescriptionRegistryImpl;
import net.sf.taverna.t2.workbench.ui.servicepanel.ServicePanel;
import net.sf.taverna.t2.workbench.ui.servicepanel.actions.AddServiceProviderAction;
/**
* A menu that provides a set up menu actions for adding new service providers to
* the Service Panel.
* <p>
* The Actions are discovered from the {@link ServiceDescriptionProvider}s found through the
* SPI.
*
* @author Stuart Owen
* @author Stian Soiland-Reyes
* @author Alan R Williams
*
* @see ServiceDescription
* @see ServicePanel
* @see ServiceDescriptionRegistry#addServiceDescriptionProvider(net.sf.taverna.t2.servicedescriptions.ServiceDescriptionProvider)
*
*/
@SuppressWarnings("serial")
public class AddServiceProviderMenu extends JButton {
private final static String ADD_SERVICE_PROVIDER_MENU_NAME = "Import new services";
public AddServiceProviderMenu() {
super();
final Component c = createCustomComponent();
this.setAction(new AbstractAction(ADD_SERVICE_PROVIDER_MENU_NAME){
public void actionPerformed(ActionEvent e) {
((JPopupMenu) c).show(AddServiceProviderMenu.this, 0, AddServiceProviderMenu.this.getHeight());
}});
}
private ServiceDescriptionRegistry serviceDescriptionRegistry = ServiceDescriptionRegistryImpl
.getInstance();
@SuppressWarnings("unchecked")
private Component createCustomComponent() {
JPopupMenu addServiceMenu = new JPopupMenu(ADD_SERVICE_PROVIDER_MENU_NAME);
addServiceMenu.setToolTipText("Add a new service provider");
boolean isEmpty = true;
for (ConfigurableServiceProvider provider : getServiceDescriptionRegistry()
.getUnconfiguredServiceProviders()) {
AddServiceProviderAction addAction = new AddServiceProviderAction(
provider, this);
addAction.setServiceDescriptionRegistry(getServiceDescriptionRegistry());
addServiceMenu.add(addAction);
isEmpty = false;
}
if (isEmpty) {
addServiceMenu.setEnabled(false);
}
return addServiceMenu;
}
public void setServiceDescriptionRegistry(
ServiceDescriptionRegistry serviceDescriptionRegistry) {
this.serviceDescriptionRegistry = serviceDescriptionRegistry;
}
public ServiceDescriptionRegistry getServiceDescriptionRegistry() {
return serviceDescriptionRegistry;
}
} |
package com.github.stephanenicolas.afterburner;
import static org.junit.Assert.*;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.github.stephanenicolas.afterburner.exception.AfterBurnerImpossibleException;
import com.github.stephanenicolas.afterburner.inserts.InsertableConstructor;
public class InsertableConstructorBuilderTest {
private InsertableConstructorBuilder builder;
private AfterBurner afterBurnerMock;
@Before
public void setUp() {
afterBurnerMock = EasyMock.createNiceMock(AfterBurner.class);
builder = new InsertableConstructorBuilder(afterBurnerMock);
}
@Test
public void testDoIt_calls_afterburner() throws CannotCompileException, AfterBurnerImpossibleException, NotFoundException {
//GIVEN
afterBurnerMock = EasyMock.createMock(AfterBurner.class);
afterBurnerMock.insertConstructor((InsertableConstructor) EasyMock.anyObject());
EasyMock.replay(afterBurnerMock);
builder = new InsertableConstructorBuilder(afterBurnerMock);
CtClass classToInsertInto = CtClass.intType;
String body = "";
//WHEN
builder
.insertIntoClass(classToInsertInto)
.withBody(body);
builder.doIt();
//THEN
EasyMock.verify(afterBurnerMock);
}
@Test
public void testCheckAllFields_should_succeed_with_all_fields_defined() throws AfterBurnerImpossibleException {
//GIVEN
CtClass classToInsertInto = CtClass.intType;
String body = "";
builder
.insertIntoClass(classToInsertInto)
.withBody(body);
//WHEN
InsertableConstructor constructor = builder.createInsertableConstructor();
//THEN
assertNotNull(constructor);
assertEquals(classToInsertInto, constructor.getClassToInsertInto());
assertEquals(body, constructor.getConstructorBody(null));
assertTrue(constructor.acceptParameters(null));
}
@Test
public void testCheckAllFields_should_succeed_with_all_fields_defined_using_class() throws Exception {
//GIVEN
String body = "";
Class<?> classToInsertInto = String.class;
builder
.insertIntoClass(classToInsertInto )
.withBody(body);
//WHEN
InsertableConstructor constructor = builder.createInsertableConstructor();
//THEN
assertNotNull(constructor);
assertEquals(ClassPool.getDefault().get(String.class.getName()), constructor.getClassToInsertInto());
assertEquals(body, constructor.getConstructorBody(null));
assertTrue(constructor.acceptParameters(null));
}
@Test(expected = AfterBurnerImpossibleException.class)
public void testCheckAllFields_should_throw_exceptions_if_no_targetClass_defined() throws AfterBurnerImpossibleException {
//GIVEN
builder.withBody("");
//WHEN
builder.checkFields();
//THEN
fail("Should have thrown exception");
}
@Test(expected = AfterBurnerImpossibleException.class)
public void testCheckAllFields_should_throw_exceptions_if_no_body_defined() throws AfterBurnerImpossibleException {
//GIVEN
CtClass classToInsertInto = CtClass.intType;
builder.insertIntoClass(classToInsertInto);
//WHEN
builder.checkFields();
//THEN
fail("Should have thrown exception");
}
} |
package foodrev.org.foodrev.presentation.ui.activities.rapidprototype;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import foodrev.org.foodrev.R;
import foodrev.org.foodrev.domain.infos.AbstractInfo;
import foodrev.org.foodrev.domain.infos.models.AbstractModel;
import foodrev.org.foodrev.domain.infos.models.Care;
import foodrev.org.foodrev.domain.infos.models.CommunityCenter;
import foodrev.org.foodrev.domain.infos.models.DonationCenter;
import foodrev.org.foodrev.domain.infos.models.Driver;
import foodrev.org.foodrev.presentation.ui.activities.rapidprototype.ItemFragment.OnListFragmentInteractionListener;
//import java.util.List;
//import foodrev.org.rapidprototype.ItemFragment.OnListFragmentInteractionListener;
//import foodrev.org.rapidprototype.dummy.DummyContent.DummyItem;
//import foodrev.org.rapidprototype.dummy.DummyContentDriver.DummyItemDriver;
/**
* {@link RecyclerView.Adapter} that can display a {@link AbstractModel} and makes a call to the
* specified {@link OnListFragmentInteractionListener}.
* TODO: Replace the implementation with code for your data type.
*/
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final AbstractInfo mValues;
private final OnListFragmentInteractionListener mListener;
// public MyItemRecyclerViewAdapter(List<? extends BaseModel> items,
// OnListFragmentInteractionListener listener) {
// mValues = items;
// mListener = listener;
public MyItemRecyclerViewAdapter(AbstractInfo items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
final ViewHolder holder = (ViewHolder) viewHolder;
holder.mItem = mValues.get(position);
// holder.mItemImage.setImageResource(R.mipmap.ic_launcher);
// holder.mIdView.setText(mValues.get(position).id);
AbstractModel data = mValues.get(position);
if (data instanceof Driver) {
holder.mContentView.setText(((Driver) data).getName());
} else if (data instanceof DonationCenter) {
holder.mContentView.setText(((DonationCenter) data).getPhoneNumber());
} else if (data instanceof CommunityCenter) {
holder.mContentView.setText(((CommunityCenter) data).getName());
} else if (data instanceof Care) {
holder.mContentView.setText(((Care) data).getCareTitle());
}
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
// @Override
// public int getItemViewType(int position) {
// // Just as an example, return 0 or 2 depending on position
// // Note that unlike in ListView adapters, types don't have to be contiguous
// return position % 2 * 2;
@Override
public int getItemCount() {
return mValues != null ? mValues.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
// public final TextView mIdView;
public final ImageView mItemImage;
public final TextView mContentView;
public AbstractModel mItem;
public ViewHolder(View view) {
super(view);
mView = view;
// mIdView = (TextView) view.findViewById(R.id.id);
mItemImage = (ImageView) view.findViewById(R.id.item_image);
mContentView = (TextView) view.findViewById(R.id.dummy_content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
} |
package org.openntf.maven;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.codehaus.plexus.util.StringUtils;
@Mojo(name = "ddehd", requiresDependencyResolution=ResolutionScope.COMPILE)
@Execute(goal="compile", phase=LifecyclePhase.COMPILE)
public class HeadlessDesignerBuilder extends AbstractMojo {
@Parameter(property = "ddehd.designerexec", defaultValue = "designer.exe")
private String m_DesignerExec;
@Parameter(property = "ddehd.notesdata")
private String m_NotesData;
@Parameter(property = "ddehd.targetdbname")
private String m_TargetDBName;
@Parameter(property = "ddehd.odpdirectory")
private String m_ODPDirectory;
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Starting DDE HeadlessDesigner Plugin");
getLog().info("Designer Exec =" + m_DesignerExec);
getLog().info("Notes Data =" + m_NotesData);
getLog().info("TargetDB Name =" + m_TargetDBName);
getLog().info("ODP =" + m_ODPDirectory);
if (StringUtils.isEmpty(m_NotesData) || StringUtils.isEmpty(m_TargetDBName) || StringUtils.isEmpty(m_ODPDirectory)) {
getLog().info("DDE HeadlessDesigner Plugin miss some configuration (ddehd.targetdbname, ddehd.notesdata)");
throw new MojoExecutionException("DDE HeadlessDesigner Plugin miss some configuration (ddehd.targetdbname, ddehd.notesdata, ddehd.odpdirectory)");
}
StringBuilder sbNotesData = new StringBuilder("=");
sbNotesData.append(m_NotesData);
sbNotesData.append("\\notes.ini");
StringBuilder sbDesignerArgs = new StringBuilder("-Dcom.ibm.designer.cmd=\"");
sbDesignerArgs.append("true,true,");
sbDesignerArgs.append(m_TargetDBName);
sbDesignerArgs.append(",");
sbDesignerArgs.append("importandbuild,");
sbDesignerArgs.append(m_ODPDirectory + "\\.project,");
sbDesignerArgs.append(m_TargetDBName);
sbDesignerArgs.append("\"");
getLog().info("Designer call = "+ sbDesignerArgs.toString());
//ProcessBuilder pb = new ProcessBuilder(m_DesignerExec, "-console", "-RPARAMS", "-vmargs", sbDesignerArgs.toString());
try {
Process process = Runtime.getRuntime().exec(m_DesignerExec + " -console -RPARAMS -vmargs "+sbDesignerArgs.toString());
//Process process = pb.start();
int result = process.waitFor();
getLog().info("DDE HeadlessDesigner ended with: " + result);
} catch (Exception ex) {
throw new MojoExecutionException("DDE HeadlessDesignerPlugin reports an error: ", ex);
}
}
} |
package gov.nih.nci.cagrid.data.utilities;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.EnumerationMethodConstants;
import gov.nih.nci.cagrid.data.MetadataConstants;
import gov.nih.nci.cagrid.data.TransferMethodConstants;
import gov.nih.nci.cagrid.data.utilities.validation.WSDLUtils;
import gov.nih.nci.cagrid.metadata.ResourcePropertyHelper;
import java.io.StringReader;
import java.util.Iterator;
import javax.wsdl.Definition;
import javax.wsdl.Message;
import javax.wsdl.Operation;
import javax.wsdl.Port;
import javax.wsdl.PortType;
import javax.wsdl.Service;
import javax.wsdl.WSDLException;
import javax.xml.namespace.QName;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.dataservice.cql.support.Cql2SupportType;
import org.cagrid.dataservice.cql.support.QueryLanguageSupport;
import org.globus.wsrf.utils.XmlUtils;
import org.w3c.dom.Element;
/**
* DataServiceFeatureDiscoveryUtil
* Discover what features a data service supports
* FIXME: needs to drill through port types and operations to find
* the query operations, not just rely on the port type being there
*
* @author David
*
*/
public class DataServiceFeatureDiscoveryUtil {
private static Log LOG = LogFactory.getLog(DataServiceFeatureDiscoveryUtil.class);
private DataServiceFeatureDiscoveryUtil() {
}
public static boolean serviceSupportsCql2(EndpointReferenceType epr) throws Exception {
Element resourceProperty = null;
resourceProperty = ResourcePropertyHelper.getResourceProperty(
epr, MetadataConstants.QUERY_LANGUAGE_SUPPORT_QNAME);
if (resourceProperty != null) {
// deserialize the resource property
QueryLanguageSupport support = Utils.deserializeObject(
new StringReader(XmlUtils.toString(resourceProperty)), QueryLanguageSupport.class);
return !(support.getCQL2Support() != null &&
support.getCQL2Support().equals(Cql2SupportType.ImplementationNotProvided));
}
return false;
}
public static Operation getOperation(EndpointReferenceType epr, QName inputMessage, QName outputMessage, String operationName) throws WSDLException {
String wsdlLocation = WSDLUtils.getWSDLLocation(epr);
LOG.debug("Loading WSDL from " + wsdlLocation);
Definition wsdlDef = WSDLUtils.parseServiceWSDL(wsdlLocation);
Operation foundOperation = null;
Iterator<?> serviceIter = wsdlDef.getServices().values().iterator();
while (serviceIter.hasNext() && foundOperation == null) {
Service service = (Service) serviceIter.next();
Iterator<?> portIter = service.getPorts().values().iterator();
while (portIter.hasNext() && foundOperation == null) {
Port port = (Port) portIter.next();
PortType portType = port.getBinding().getPortType();
Iterator<?> opIter = portType.getOperations().iterator();
while (opIter.hasNext() && foundOperation == null) {
Operation op = (Operation) opIter.next();
if (op.getName().equals(operationName)) {
LOG.debug("Found operation " + operationName + ", checking input / output messages");
Message input = op.getInput().getMessage();
Message output = op.getOutput().getMessage();
if (input.getQName().equals(inputMessage) &&
output.getQName().equals(outputMessage)) {
foundOperation = op;
LOG.debug("Input / output messages match");
break;
}
}
}
}
}
return foundOperation;
}
public static boolean serviceHasCql2TransferOperation(EndpointReferenceType epr) throws WSDLException {
Operation transferOp = getOperation(epr,
TransferMethodConstants.CQL2_TRANSFER_QUERY_METHOD_INPUT_MESSAGE,
TransferMethodConstants.CQL2_TRANSFER_QUERY_METHOD_OUTPUT_MESSAGE,
TransferMethodConstants.CQL2_TRANSFER_QUERY_METHOD_NAME);
return transferOp != null;
}
public static boolean serviceHasCql1TransferOperation(EndpointReferenceType epr) throws WSDLException {
Operation transferOp = getOperation(epr,
TransferMethodConstants.TRANSFER_QUERY_METHOD_INPUT_MESSAGE,
TransferMethodConstants.TRANSFER_QUERY_METHOD_OUTPUT_MESSAGE,
TransferMethodConstants.TRANSFER_QUERY_METHOD_NAME);
return transferOp != null;
}
public static boolean serviceHasCql2EnumerationOperation(EndpointReferenceType epr) throws WSDLException {
Operation enumerationOp = getOperation(epr,
EnumerationMethodConstants.CQL2_ENUMERATION_QUERY_INPUT_MESSAGE,
EnumerationMethodConstants.CQL2_ENUMERATION_QUERY_OUTPUT_MESSAGE,
EnumerationMethodConstants.CQL2_ENUMERATION_QUERY_METHOD_NAME);
return enumerationOp != null;
}
public static boolean serviceHasCql1EnumerationOperation(EndpointReferenceType epr) throws WSDLException {
Operation enumerationOp = getOperation(epr,
EnumerationMethodConstants.ENUMERATION_QUERY_INPUT_MESSAGE,
EnumerationMethodConstants.ENUMERATION_QUERY_OUTPUT_MESSAGE,
EnumerationMethodConstants.ENUMERATION_QUERY_METHOD_NAME);
return enumerationOp != null;
}
public static void main(String[] args) {
try {
EndpointReferenceType epr = new EndpointReferenceType(new Address(
"http://localhost:8080/wsrf/services/cagrid/DataEnum"));
System.out.println("Has enum? " + serviceHasCql2EnumerationOperation(epr));
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
package edu.wustl.catissuecore.bizlogic.test;
import java.text.ParseException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import edu.wustl.catissuecore.domain.Capacity;
import edu.wustl.catissuecore.domain.CellSpecimen;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.FluidSpecimen;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.StorageType;
import edu.wustl.catissuecore.domain.TissueSpecimen;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.logger.Logger;
public class StorageContainerRestrictionsTestCases extends CaTissueBaseTestCase {
StorageType box =null;
StorageType rack =null;
StorageType freezer =null;
StorageContainer freezerContainer = null;
StorageContainer rackContainer = null;
StorageContainer boxContainer = null;
public void testAddTissueSpecInStorageContainerCanHoldTissueSpecimen()
{
try{
StorageType tissueST = BaseTestCaseUtility.initTissueStorageType();
tissueST = (StorageType) appService.createObject(tissueST);
StorageContainer storageContainer= BaseTestCaseUtility.initStorageContainerHoldsTissueSpec();
storageContainer.setStorageType(tissueST);
System.out.println(storageContainer);
storageContainer = (StorageContainer) appService.createObject(storageContainer);
TestCaseUtility.setObjectMap(storageContainer, StorageContainer.class);
SpecimenCollectionGroup scg = BaseTestCaseUtility.initSCG();
scg = (SpecimenCollectionGroup) appService.createObject(scg);
TestCaseUtility.setObjectMap(scg, SpecimenCollectionGroup.class);
TissueSpecimen ts =(TissueSpecimen) BaseTestCaseUtility.initTissueSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(1));
ts.setPositionDimensionTwo(new Integer(1));
ts.setSpecimenCollectionGroup(scg);
System.out.println("Befor creating Tissue Specimen");
ts = (TissueSpecimen) appService.createObject(ts);
System.out.println("Tissue Specimen successfully created with Lable"+ ts.getLabel());
Logger.out.info("Tissue Specimen successfully created with Lable"+ ts.getLabel());
assertTrue("Successfully added tissue specimen in container", true);
}
catch(Exception e){
e.printStackTrace();
assertFalse("could not add object", true);
}
}
public void testAddMolSpecInStorageContainerCanHoldTissueSpecimenNegativeTestcase()
{
try{
StorageContainer storageContainer= (StorageContainer) TestCaseUtility.getObjectMap(StorageContainer.class);
SpecimenCollectionGroup scg = (SpecimenCollectionGroup) TestCaseUtility.getObjectMap(SpecimenCollectionGroup.class);
MolecularSpecimen ts =(MolecularSpecimen) BaseTestCaseUtility.initMolecularSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(1));
ts.setPositionDimensionTwo(new Integer(2));
ts.setSpecimenCollectionGroup(scg);
System.out.println("Befor creating Mol Specimen");
ts = (MolecularSpecimen) appService.createObject(ts);
assertFalse("Successfully added mol specimen in container which can only store tissue specimens", true);
}
catch(Exception e){
e.printStackTrace();
assertTrue("Failed to add Mol specimen in container which can only store tissue specimens", true);
}
}
/* public void testAddCellSpecInStorageContainer()
{
try{
StorageContainer storageContainer= (StorageContainer) TestCaseUtility.getObjectMap(StorageContainer.class);
SpecimenCollectionGroup scg = (SpecimenCollectionGroup) TestCaseUtility.getObjectMap(SpecimenCollectionGroup.class);
CellSpecimen ts =(CellSpecimen) BaseTestCaseUtility.initCellSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(2));
ts.setPositionDimensionTwo(new Integer(1));
ts.setSpecimenCollectionGroup(scg);
System.out.println("Befor creating Mol Specimen");
ts = (CellSpecimen) appService.createObject(ts);
assertFalse("could not add object", true);
}
catch(Exception e){
e.printStackTrace();
assertTrue("Failed to add Mol specimen in SC", true);
}
}
public void testAddFluidSpecInStorageContainer()
{
try{
StorageContainer storageContainer= (StorageContainer) TestCaseUtility.getObjectMap(StorageContainer.class);
SpecimenCollectionGroup scg = (SpecimenCollectionGroup) TestCaseUtility.getObjectMap(SpecimenCollectionGroup.class);
FluidSpecimen ts =(FluidSpecimen) BaseTestCaseUtility.initFluidSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(2));
ts.setPositionDimensionTwo(new Integer(1));
ts.setSpecimenCollectionGroup(scg);
System.out.println("Befor creating Mol Specimen");
ts = (FluidSpecimen) appService.createObject(ts);
assertFalse("could not add object", true);
}
catch(Exception e){
e.printStackTrace();
assertTrue("Failed to add Mol specimen in SC", true);
}
} */
public void testStorageContainerRestrictionToHoldSpecimensOfParticularCPPositiveTest()
{
try {
CollectionProtocol cp = BaseTestCaseUtility.initCollectionProtocol();
cp = (CollectionProtocol) appService.createObject(cp);
StorageType ST = BaseTestCaseUtility.initStorageType();
ST = (StorageType) appService.createObject(ST);
StorageContainer storageContainer= BaseTestCaseUtility.initStorageContainer();
Collection cpCollection = new HashSet();
cpCollection.add(cp);
storageContainer.setCollectionProtocolCollection(cpCollection);
storageContainer.setStorageType(ST);
System.out.println("Storage Container"+storageContainer.getName()+" successfully created");
storageContainer = (StorageContainer) appService.createObject(storageContainer);
TestCaseUtility.setObjectMap(storageContainer, StorageContainer.class);
SpecimenCollectionGroup scg= (SpecimenCollectionGroup)cpRestriction(cp);
TissueSpecimen ts =(TissueSpecimen) BaseTestCaseUtility.initTissueSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(1));
ts.setPositionDimensionTwo(new Integer(2));
ts.setSpecimenCollectionGroup(scg);
ts.setLabel("TisSpec"+UniqueKeyGeneratorUtil.getUniqueKey());
System.out.println("Befor creating Tissue Specimen");
ts = (TissueSpecimen) appService.createObject(ts);
System.out.println("TissueSpec:"+ts.getLabel());
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to register participant", true);
}
}
public void testStorageContainerRestrictionToHoldSpecimensOfParticularCPNegativeTest()
{
StorageContainer storageContainer =(StorageContainer) TestCaseUtility.getObjectMap(StorageContainer.class);
CollectionProtocol cp = BaseTestCaseUtility.initCollectionProtocol();
try{
cp = (CollectionProtocol) appService.createObject(cp);
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to create collection protocol", true);
}
System.out.println("CP:"+cp.getTitle());
SpecimenCollectionGroup scg= (SpecimenCollectionGroup)cpRestriction(cp);
TissueSpecimen ts =(TissueSpecimen) BaseTestCaseUtility.initTissueSpecimen();
ts.setStorageContainer(storageContainer);
ts.setPositionDimensionOne(new Integer(1));
ts.setPositionDimensionTwo(new Integer(2));
ts.setSpecimenCollectionGroup(scg);
ts.setLabel("WithDiffCPTisSpec"+UniqueKeyGeneratorUtil.getUniqueKey());
System.out.println("Befor creating Tissue Specimen");
try{
ts = (TissueSpecimen) appService.createObject(ts);
}
catch(Exception e){
assertTrue("Failed to add Specimen in container which has restriction to hold diff. CP", true);
}
System.out.println("TissueSpec:"+ts.getLabel());
}
public SpecimenCollectionGroup cpRestriction(CollectionProtocol cp)
{
Participant participant = BaseTestCaseUtility.initParticipant();
try{
participant = (Participant) appService.createObject(participant);
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to create collection protocol", true);
}
System.out.println("Participant:"+participant.getFirstName());
CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
collectionProtocolRegistration.setCollectionProtocol(cp);
collectionProtocolRegistration.setParticipant(participant);
collectionProtocolRegistration.setProtocolParticipantIdentifier("");
collectionProtocolRegistration.setActivityStatus("Active");
try
{
collectionProtocolRegistration.setRegistrationDate(Utility.parseDate("08/15/1975",
Utility.datePattern("08/15/1975")));
collectionProtocolRegistration.setConsentSignatureDate(Utility.parseDate("11/23/2006",Utility.datePattern("11/23/2006")));
}
catch (ParseException e)
{
e.printStackTrace();
assertFalse("Failed to add collection protocol registration", true);
}
collectionProtocolRegistration.setSignedConsentDocumentURL("F:/doc/consentDoc.doc");
User user = (User)TestCaseUtility.getObjectMap(User.class);
collectionProtocolRegistration.setConsentWitness(user);
Collection consentTierResponseCollection = new HashSet();
Collection consentTierCollection = cp.getConsentTierCollection();
ConsentTierResponse r1 = new ConsentTierResponse();
r1.setResponse("Yes");
consentTierResponseCollection.add(r1);
ConsentTierResponse r2 = new ConsentTierResponse();
r2.setResponse("No");
consentTierResponseCollection.add(r2);
ConsentTierResponse r3 = new ConsentTierResponse();
r3.setResponse("Not Applicable");
consentTierResponseCollection.add(r3);
Iterator ConsentierItr = consentTierCollection.iterator();
Iterator ConsentierResponseItr = consentTierResponseCollection.iterator();
while(ConsentierItr.hasNext()&& ConsentierResponseItr.hasNext())
{
ConsentTier consentTier = (ConsentTier)ConsentierItr.next();
ConsentTierResponse consentResponse = (ConsentTierResponse) ConsentierResponseItr.next();
consentResponse.setConsentTier(consentTier);
}
collectionProtocolRegistration.setConsentTierResponseCollection(consentTierResponseCollection);
collectionProtocolRegistration.setConsentTierResponseCollection(consentTierResponseCollection);
System.out.println("Creating CPR");
try{
collectionProtocolRegistration = (CollectionProtocolRegistration) appService.createObject(collectionProtocolRegistration);
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to register participant", true);
}
SpecimenCollectionGroup scg = new SpecimenCollectionGroup();
scg =(SpecimenCollectionGroup) BaseTestCaseUtility.createSCG(collectionProtocolRegistration);
Site site = (Site) TestCaseUtility.getObjectMap(Site.class);
scg.setSpecimenCollectionSite(site);
scg.setName("New SCG"+UniqueKeyGeneratorUtil.getUniqueKey());
scg = (SpecimenCollectionGroup) BaseTestCaseUtility.setEventParameters(scg);
System.out.println("Creating SCG");
try{
scg = (SpecimenCollectionGroup) appService.createObject(scg);
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to register participant", true);
}
return scg;
}
public void createStorageTypes()
{
box = new StorageType();
Capacity capacity = new Capacity();
box.setName("Box" + UniqueKeyGeneratorUtil.getUniqueKey());
box.setDefaultTempratureInCentigrade(new Double(-30));
box.setOneDimensionLabel("label 1");
box.setTwoDimensionLabel("label 2");
capacity.setOneDimensionCapacity(new Integer(5));
capacity.setTwoDimensionCapacity(new Integer(3));
box.setCapacity(capacity);
box.setActivityStatus("Active");
Collection holdsSpecimenClassCollection = new HashSet();
holdsSpecimenClassCollection.add("Tissue");
holdsSpecimenClassCollection.add("Fluid");
holdsSpecimenClassCollection.add("Molecular");
holdsSpecimenClassCollection.add("Cell");
box.setHoldsSpecimenClassCollection(holdsSpecimenClassCollection);
try{
box = (StorageType) appService.createObject(box);
}
catch(Exception e){
assertFalse("",true);
}
rack = new StorageType();
Capacity rackCapacity = new Capacity();
rack.setName("Rack" + UniqueKeyGeneratorUtil.getUniqueKey());
rack.setDefaultTempratureInCentigrade(new Double(-30));
rack.setOneDimensionLabel("label 1");
rack.setTwoDimensionLabel("label 2");
rackCapacity.setOneDimensionCapacity(new Integer(5));
rackCapacity.setTwoDimensionCapacity(new Integer(4));
rack.setCapacity(rackCapacity);
rack.setActivityStatus("Active");
Collection holdsBox = new HashSet();
holdsBox.add(box);
rack.setHoldsStorageTypeCollection(holdsBox);
try{
rack = (StorageType) appService.createObject(rack);
}
catch(Exception e){
assertFalse("",true);
}
freezer = new StorageType();
Capacity freezerCapacity = new Capacity();
freezer.setName("Freezer" + UniqueKeyGeneratorUtil.getUniqueKey());
freezer.setDefaultTempratureInCentigrade(new Double(-30));
freezer.setOneDimensionLabel("label 1");
freezer.setTwoDimensionLabel("label 2");
freezerCapacity.setOneDimensionCapacity(new Integer(5));
freezerCapacity.setTwoDimensionCapacity(new Integer(4));
freezer.setCapacity(freezerCapacity);
freezer.setActivityStatus("Active");
Collection holdsRack = new HashSet();
holdsRack.add(rack);
freezer.setHoldsStorageTypeCollection(holdsRack);
try{
freezer = (StorageType) appService.createObject(freezer);
}
catch(Exception e){
assertFalse("",true);
}
}
public void createStorageContainers()
{
freezerContainer = new StorageContainer();
freezerContainer.setStorageType(freezer);
Site site = (Site) TestCaseUtility.getObjectMap(Site.class);
freezerContainer.setSite(site);
freezerContainer.setNoOfContainers(3);
freezerContainer.setActivityStatus("Active");
Capacity capacity1 = new Capacity();
capacity1.setOneDimensionCapacity(new Integer(3));
capacity1.setTwoDimensionCapacity(new Integer(3));
freezerContainer.setCapacity(capacity1);
freezerContainer.setFull(Boolean.valueOf(false));
Collection holdsRackCollection = new HashSet();
holdsRackCollection.add(rack);
freezerContainer.setHoldsStorageTypeCollection(holdsRackCollection);
try{
freezerContainer = (StorageContainer) appService.createObject(freezerContainer);
}
catch(Exception e){
assertFalse("",true);
}
rackContainer = new StorageContainer();
rackContainer.setStorageType(rack);
rackContainer.setParent(freezerContainer);
rackContainer.setPositionDimensionOne(new Integer(1));
rackContainer.setPositionDimensionOne(new Integer(1));
rackContainer.setNoOfContainers(3);
rackContainer.setActivityStatus("Active");
rackContainer.setCapacity(capacity1);
rackContainer.setFull(Boolean.valueOf(false));
Collection holdsBoxCollection = new HashSet();
holdsBoxCollection.add(box);
rackContainer.setHoldsStorageTypeCollection(holdsBoxCollection);
try{
rackContainer = (StorageContainer) appService.createObject(rackContainer);
}
catch(Exception e){
assertFalse("",true);
}
boxContainer = new StorageContainer();
boxContainer.setStorageType(box);
boxContainer.setParent(rackContainer);
boxContainer.setPositionDimensionOne(new Integer(1));
boxContainer.setPositionDimensionOne(new Integer(2));
boxContainer.setActivityStatus("Active");
boxContainer.setCapacity(capacity1);
boxContainer.setFull(Boolean.valueOf(false));
try{
boxContainer = (StorageContainer) appService.createObject(boxContainer);
assertTrue("created box SC",true);
}
catch(Exception e){
assertFalse("Should not allow",true);
}
}
public void testAddBoxInRackContainerPositiveTestcase()
{
createStorageTypes();
createStorageContainers();
StorageContainer sc = new StorageContainer();
sc.setStorageType(box);
sc.setParent(rackContainer);
sc.setPositionDimensionOne(new Integer(1));
sc.setPositionDimensionOne(new Integer(1));
sc.setNoOfContainers(1);
sc.setActivityStatus("Active");
Capacity capacity1 = new Capacity();
capacity1.setOneDimensionCapacity(new Integer(3));
capacity1.setTwoDimensionCapacity(new Integer(3));
sc.setCapacity(capacity1);
sc.setFull(Boolean.valueOf(false));
try{
sc = (StorageContainer) appService.createObject(sc);
assertTrue("Successfully added box container in rack container",true);
}catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Failed to add the box container in rack container ",true);
}
}
public void testAddBoxInFreezerContainerNegativeTestCase()
{
StorageContainer sc = new StorageContainer();
sc.setStorageType(box);
sc.setParent(freezerContainer);
sc.setPositionDimensionOne(new Integer(1));
sc.setPositionDimensionOne(new Integer(2));
sc.setNoOfContainers(1);
sc.setActivityStatus("Active");
Capacity capacity1 = new Capacity();
capacity1.setOneDimensionCapacity(new Integer(3));
capacity1.setTwoDimensionCapacity(new Integer(3));
sc.setCapacity(capacity1);
sc.setFull(Boolean.valueOf(false));
try{
sc = (StorageContainer) appService.createObject(sc);
assertFalse("Successfully added box container in freezer container",true);
}
catch(Exception e){
Logger.out.error(e.getMessage(),e);
e.printStackTrace();
assertTrue("Shoudnot allow to create container ",true);
}
}
} |
package traviscimafer;
import javax.swing.*;
/**
*
* Autora:Mafer Delgado
*/
public class TravisCIMafer {
public static void main(String[] args)
{
System.out.println("Práctica TravisCI");
System.out.println("Integración Continua con TravisCI y GitHUB");
System.out.println("Universidad Laica Eloy Alfaro de Manabí");
System.out.println("Calculadora Básica");
System.out.println("Ingeniería de Software");
System.out.println("Ing. Diego Toala");
int op=0;
double n1,n2,multiplicacion,suma,division,resta;
do{
op=Integer.parseInt(JOptionPane.showInputDialog("nCalculadoran"+
"************n"+
"[1] SUMARn"+
"[2] RESTARn"+
"[3] MULTIPLICARn"+
"[4] DIVIDIRn"+
"[5] SALIRn"+
"Ingresa una opción:"));
switch(op)
{
case 1:
n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1"));
n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2"));
suma=n1+n2;
JOptionPane.showMessageDialog(null,"La suma es:"+suma);
break;
case 2:
n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1"));
n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2"));
resta=n1-n2;
JOptionPane.showMessageDialog(null,"La resta es:"+resta);
break;
case 3:
n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1"));
n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2"));
multiplicacion=n1*n2;
JOptionPane.showMessageDialog(null,"La multiplicación es:"+multiplicacion);
break;
case 4:
n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1"));
n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2"));
division=n1/n2;
JOptionPane.showMessageDialog(null,"La división es:"+division);
break;
}
}while(op!=5);
}
} |
package ucsbCurriculum.Utility;
import java.util.ArrayList;
import ucsbCurriculum.Utility.Time;
import ucsbCurriculum.Utility.Time;
public class Util {
// return true if those two Time have conflicts
public static boolean have_conflict(Time t1, Time t2){
return t1.start_time > t2.start_time ? (t1.start_time > t2.end_time) : (t2.start_time > t1.start_time);
}
public Time converts_to_minute(String daym, String timm){
int[] t = new int[2];
int time = 0;
char a_char;
char b_char;
char c_char;
char d_char;
int addedmin;
int minutes;
int firstmin;
int more;
String hi;
//String hello = " 9:30am - 12:33am ";
String[] tab = timm.split("-");
int timesforday=0;
//converts day to int
String daytomin = daym;
if(daytomin.contains("M"))
timesforday=0;
if(daytomin.contains("T"))
timesforday=(24*60);
if(daytomin.contains("W"))
timesforday=(48*60);
if(daytomin.contains("R"))
timesforday=(72*60);
if(daytomin.contains("F"))
timesforday=(96*60);
//converts time to int
for(int i=0; i<tab.length; i++){
if(tab[i].contains("pm")){
if(tab[i].length()==8){
hi = tab[i];
a_char = hi.charAt(1);
b_char = hi.charAt(3);
c_char = hi.charAt(4);
addedmin = Character.getNumericValue(a_char);
minutes = Character.getNumericValue(b_char);
more = Character.getNumericValue(c_char);
time = (12*60) + (addedmin * 60) + (minutes*10) + (more);
t[i]=time;
}
else if(tab[i].length() == 9){
hi = tab[i];
a_char = hi.charAt(1);
d_char = hi.charAt(2);
b_char = hi.charAt(4);
c_char = hi.charAt(5);
addedmin = Character.getNumericValue(a_char);
firstmin = Character.getNumericValue(d_char);
minutes = Character.getNumericValue(b_char);
more = Character.getNumericValue(c_char);
if((addedmin==1)&&(firstmin==2)){
time = ((12 * 60) + (minutes*10) + (more));
t[i]=time;
}
else{
time = ((12*60) + ((10 + firstmin) * 60) + (minutes*10) + (more));
t[i]=time;
}
}
}
else if(tab[i].contains("am")){
if(tab[i].length()==8){
hi = tab[i];
a_char = hi.charAt(1);
b_char = hi.charAt(3);
c_char = hi.charAt(4);
addedmin = Character.getNumericValue(a_char);
minutes = Character.getNumericValue(b_char);
more = Character.getNumericValue(c_char);
time =(addedmin * 60) + (minutes*10) + (more);
t[i]=time;
}
else if(tab[i].length() == 9){
hi = tab[i];
a_char = hi.charAt(1);
d_char = hi.charAt(2);
b_char = hi.charAt(4);
c_char = hi.charAt(5);
addedmin = Character.getNumericValue(a_char);
firstmin = Character.getNumericValue(d_char);
minutes = Character.getNumericValue(b_char);
more = Character.getNumericValue(c_char);
if((addedmin==1)&&(firstmin==2)){
time = 0 +(minutes*10)+more;
t[i]=time;
}
else{
time = (((10 + firstmin) * 60) + (minutes*10) + (more));
t[i]=time;
}
}
}
//return t;
}
Time ti= new Time();
ti.starttime=timesforday+t[0];
ti.endtime=timesforday+t[1];
return ti;
}
public static String convert_to_string(int starttime, int endtime){
String[] names = {"M","T","W","R","F"};
//starttime
int startday = (starttime / (24*60));
String strday1 = names[startday];
String strtime;
//starttime
int fhour;
int fdays = (starttime/(24*60));
if(fdays==0){
fhour = (starttime/(60))-12;
}
else
fhour = (starttime-(fdays*24*60))/60-12;
int ftenminute = (starttime-(fdays*24*60)-(fhour*60+(12*60)))/10;
int foneminute = (starttime-(fdays*24*60)-(fhour*60+(12*60)))%10;
//endtime
int shour;
int sdays = (endtime/(24*60));
if(sdays==0){
shour = (endtime/(60))-12;
}
else
shour = (endtime-(sdays*24*60))/60-12;
int stenminute = (endtime-(sdays*24*60)-(shour*60+(12*60)))/10;
int soneminute = (endtime-(sdays*24*60)-(shour*60+(12*60)))%10;
strtime = strday1 + " " + Integer.toString(fhour)+":"+Integer.toString(ftenminute)+ Integer.toString(foneminute) + " - " + Integer.toString(shour)+":"+Integer.toString(stenminute)+ Integer.toString(soneminute)+ " ";
return strtime;
}
} |
package net.domesdaybook.automata.trie;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.domesdaybook.automata.base.BaseAutomata;
import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.base.BaseStateFactory;
import net.domesdaybook.automata.factory.StateFactory;
import net.domesdaybook.automata.base.ByteMatcherTransitionFactory;
import net.domesdaybook.automata.factory.TransitionFactory;
import net.domesdaybook.bytes.ByteUtilities;
/**
*
* @author Matt Palmer
*/
public abstract class AbstractTrie<T> extends BaseAutomata<T> implements Trie<T> {
private final StateFactory<T> stateFactory;
private final TransitionFactory transitionFactory;
private final List<T> sequences;
private int minimumLength = -1;
private int maximumLength = 0;
public AbstractTrie() {
this(null, null);
}
public AbstractTrie(final StateFactory<T> stateFactory) {
this(stateFactory, null);
}
public AbstractTrie(final TransitionFactory transitionFactory) {
this(null, transitionFactory);
}
public AbstractTrie(final StateFactory<T> stateFactory,
final TransitionFactory transitionFactory) {
this.stateFactory = stateFactory != null?
stateFactory : new BaseStateFactory<T>();
this.transitionFactory = transitionFactory != null?
transitionFactory : new ByteMatcherTransitionFactory();
this.sequences = new ArrayList<T>();
setInitialState(this.stateFactory.create(State.NON_FINAL));
}
public int getMinimumLength() {
return minimumLength == -1 ? 0 : minimumLength;
}
public int getMaximumLength() {
return maximumLength;
}
public Collection<T> getSequences() {
return new ArrayList<T>(sequences);
}
public void add(final T sequence) {
List<State<T>> currentStates = new ArrayList<State<T>>();
currentStates.add(initialState);
final int length = getSequenceLength(sequence);
for (int position = 0; position < length; position++) {
final byte[] matchingBytes = getBytesForPosition(sequence, position);
final boolean isFinal = position == length - 1;
currentStates = nextStates(currentStates, matchingBytes, isFinal);
}
for (final State<T> finalState : currentStates) {
finalState.addAssociation(sequence);
}
setMinMaxLength(length);
sequences.add(sequence);
}
public void addAll(final Collection<? extends T> sequences) {
for (final T sequence : sequences) {
add(sequence);
}
}
public void addReversed(final T sequence) {
List<State<T>> currentStates = new ArrayList<State<T>>();
currentStates.add(initialState);
final int length = getSequenceLength(sequence);
for (int position = length - 1; position >= 0; position
final byte[] matchingBytes = getBytesForPosition(sequence, position);
final boolean isFinal = position == 0;
currentStates = nextStates(currentStates, matchingBytes, isFinal);
}
for (final State<T> finalState : currentStates) {
finalState.addAssociation(sequence);
}
setMinMaxLength(length);
sequences.add(sequence);
}
public void addAllReversed(final Collection<? extends T> sequences) {
for (final T sequence : sequences) {
addReversed(sequence);
}
}
protected abstract int getSequenceLength(T sequence);
protected abstract byte[] getBytesForPosition(T sequence, int position);
private void setMinMaxLength(final int length) {
if (length > maximumLength) {
maximumLength = length;
}
if (length < minimumLength || minimumLength == -1) {
minimumLength = length;
}
}
/**
*
* @param currentStates
* @param bytes
* @param isFinal
* @return
*/
private List<State<T>> nextStates(final List<State<T>> currentStates,
final byte[] bytes,
final boolean isFinal) {
final List<State<T>> nextStates = new ArrayList<State<T>>();
final Set<Byte> allBytesToTransitionOn = ByteUtilities.toSet(bytes);
for (final State currentState : currentStates) {
// make a defensive copy of the transitions of the current state:
final List<Transition> transitions = new ArrayList<Transition>(currentState.getTransitions());
final Set<Byte> bytesToTransitionOn = new HashSet<Byte>(allBytesToTransitionOn);
for (final Transition transition : transitions) {
final Set<Byte> originalTransitionBytes = ByteUtilities.toSet(transition.getBytes());
final int originalTransitionBytesSize = originalTransitionBytes.size();
final Set<Byte> bytesInCommon = ByteUtilities.subtract(originalTransitionBytes, bytesToTransitionOn);
// If the existing transition is the same or a subset of the new transition bytes:
final int numberOfBytesInCommon = bytesInCommon.size();
if (numberOfBytesInCommon == originalTransitionBytesSize) {
final State toState = transition.getToState();
// Ensure that the state is final if necessary:
if (isFinal) {
toState.setIsFinal(true);
}
// Add this state to the states we have to process next.
nextStates.add((State<T>) toState);
} else if (numberOfBytesInCommon > 0) {
// Only some bytes are in common.
// We will have to split the existing transition to
// two states, and recreate the transitions to them:
final State originalToState = transition.getToState();
if (isFinal) {
originalToState.setIsFinal(true);
}
final State newToState = originalToState.deepCopy();
// Add a transition to the bytes which are not in common:
final Transition bytesNotInCommonTransition = transitionFactory.createSetTransition(originalTransitionBytes, false, originalToState);
currentState.addTransition(bytesNotInCommonTransition);
// Add a transition to the bytes in common:
final Transition bytesInCommonTransition = transitionFactory.createSetTransition(bytesInCommon, false, newToState);
currentState.addTransition(bytesInCommonTransition);
// Add the bytes in common state to the next states to process:
nextStates.add((State<T>) newToState);
// Remove the original transition from the current state:
currentState.removeTransition(transition);
}
// If we have no further bytes to process, just break out.
final int numberOfBytesLeft = bytesToTransitionOn.size();
if (numberOfBytesLeft == 0) {
break;
}
}
// If there are any bytes left over, create a transition to a new state:
final int numberOfBytesLeft = bytesToTransitionOn.size();
if (numberOfBytesLeft > 0) {
final State<T> newState = stateFactory.create(isFinal);
final Transition newTransition = transitionFactory.createSetTransition(bytesToTransitionOn, false, newState);
currentState.addTransition(newTransition);
nextStates.add(newState);
}
}
return nextStates;
}
} |
package act.db.morphia;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Id;
import org.osgl.util.E;
import org.osgl.util.S;
/**
* The default morphia model base implementation using {@link ObjectId} as the id type
* @param <MODEL_TYPE>
*/
public abstract class MorphiaModel<MODEL_TYPE extends MorphiaModel> extends MorphiaModelBase<ObjectId, MODEL_TYPE> {
@Id
private ObjectId id;
public MorphiaModel() {
}
public MorphiaModel(ObjectId id) {
this.id = id;
}
public String getIdAsStr() {
return null != id ? id.toString() : null;
}
public void setId(String id) {
E.illegalArgumentIf(!ObjectId.isValid(id), "Invalid Object Id: %s", id);
this.id = new ObjectId(id);
}
public ObjectId _id() {
return id;
}
@Override
public MODEL_TYPE _id(ObjectId id) {
E.illegalStateIf(null != this.id);
this.id = id;
return _me();
}
@Override
public String toString() {
return S.builder().append(getClass().getName()).append("[").append(id).append("]").toString();
}
} |
package nl.sense_os.commonsense.client;
public class LastDeployed {
private static final String deployed = "Thu Oct 13 17:42";
private LastDeployed() {
// do not instantiate
}
public static String getPrettyString() {
return deployed;
}
} |
package org.jboss.as.clustering.controller.validation;
import org.jboss.as.clustering.logging.ClusteringLogger;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* A builder for creating a range validator for {@link ModelType#DOUBLE} parameters.
* @author Paul Ferraro
*/
public class DoubleRangeValidatorBuilder extends AbstractParameterValidatorBuilder {
private Bound upperBound;
private Bound lowerBound;
/**
* Sets an inclusive lower bound of this validator.
* @param lowerBound the lower bound
*/
public DoubleRangeValidatorBuilder lowerBound(double value) {
this.lowerBound = new Bound(value, false);
return this;
}
/**
* Sets an exclusive lower bound of this validator.
* @param lowerBound the lower bound
*/
public DoubleRangeValidatorBuilder lowerBoundExclusive(double value) {
this.lowerBound = new Bound(value, true);
return this;
}
/**
* Sets the inclusive upper bound of this validator.
* @param upperBound the upper bound
*/
public DoubleRangeValidatorBuilder upperBound(double value) {
this.upperBound = new Bound(value, false);
return this;
}
/**
* Sets the exclusive upper bound of this validator.
* @param upperBound the upper bound
*/
public DoubleRangeValidatorBuilder upperBoundExclusive(double value) {
this.upperBound = new Bound(value, true);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ParameterValidator build() {
return new DoubleRangeValidator(this.lowerBound, this.upperBound, this.allowsUndefined, this.allowsExpressions);
}
private static class Bound {
private final double value;
private final boolean exclusive;
Bound(double value, boolean exclusive) {
this.value = value;
this.exclusive = exclusive;
}
double getValue() {
return this.value;
}
boolean isExclusive() {
return this.exclusive;
}
}
private static class DoubleRangeValidator extends ModelTypeValidator {
private final Bound lowerBound;
private final Bound upperBound;
/**
* Creates an upper- and lower-bounded validator.
* @param lowerBound the lower bound
* @param lowerBound the upper bound
* @param nullable indicates whether {@link ModelType#UNDEFINED} is allowed
* @param allowExpressions whether {@link ModelType#EXPRESSION} is allowed
*/
DoubleRangeValidator(Bound lowerBound, Bound upperBound, boolean nullable, boolean allowExpressions) {
super(ModelType.DOUBLE, nullable, allowExpressions, false);
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
/**
* {@inheritDoc}
*/
@Override
public void validateParameter(String parameterName, ModelNode parameterValue) throws OperationFailedException {
super.validateParameter(parameterName, parameterValue);
if (parameterValue.isDefined() && parameterValue.getType() != ModelType.EXPRESSION) {
double value = parameterValue.asDouble();
if (this.lowerBound != null) {
double bound = this.lowerBound.getValue();
boolean exclusive = this.lowerBound.isExclusive();
if ((value < bound) || (exclusive && (value == bound))) {
throw ClusteringLogger.ROOT_LOGGER.parameterValueOutOfBounds(parameterName, value, exclusive ? ">" : ">=", bound);
}
}
if (this.upperBound != null) {
double bound = this.upperBound.getValue();
boolean exclusive = this.upperBound.isExclusive();
if ((value > bound) || (exclusive && (value == bound))) {
throw ClusteringLogger.ROOT_LOGGER.parameterValueOutOfBounds(parameterName, value, exclusive ? "<" : "<=", bound);
}
}
}
}
}
} |
package ch.javasoft.decimal;
import java.math.BigDecimal;
import java.math.RoundingMode;
import ch.javasoft.decimal.arithmetic.DecimalArithmetics;
/**
* Mutable or immutable fixed-precision signed decimal numbers similar to
* {@link BigDecimal}. A {@code Decimal} consists of an <i>unscaled long
* value</i> and a {@link #getScale() scale}. The scale defines the number of
* digits to the right of the decimal point. The value of the number represented
* by the {@code Decimal} is <tt>(unscaledValue × 10<sup>-n</sup>)</tt>
* with {@code n} {@link Scale#getFractionDigits() fraction digits}.
* <p>
* Scale is a generic parameter of the <tt>Decimal</tt> to ensure that only
* decimal numbers of the same scale can directly be combined in arithmetic
* operations (without conversion); the {@link Scale} class provides scale
* subclasses to support this principle.
* <p>
* The {@link #getArithmetics() arithmetics} object defines {@link RoundingMode}
* applied to methods which involve rounding as well as the {@link OverflowMode}
* used when an operation results in an overflow. The arithmetics of
* {@code this} decimal always determines the arithmetics of the result
* irrespective of rounding mode arguments and potentially different arithmetics
* of other operands. Note that this may lead to a violation of the commutative
* property inherent to certain mathematical operations if operands are used
* with another arithmetic than that of {@code this} decimal value.
*
* @param <S>
* the scale subclass type associated with this decimal
*/
public interface Decimal<S extends Scale> extends Comparable<Decimal<S>> {
/**
* Decimal arithmetics used for arithmetic operations and conversions using
* the same scale and defining the default
* {@link DecimalArithmetics#getRoundingMode() rounding mode} applied to
* operations where rounding is necessary.
*
* @return the decimal arithmetics with the same scale as this decimal and
* the default {@link DecimalArithmetics#getRoundingMode() rounding
* mode} applied to operations with rounding
*/
DecimalArithmetics getArithmetics();
/**
* Returns the scale associated with this decimal. The scale defines the
* number of {@link Scale#getFractionDigits() fraction digits} and the
* {@link Scale#getScaleFactor() scale factor} applied to the {@code long}
* value underlying this <tt>Decimal</tt>.
*
* @return the scale object
*/
S getScale();
/**
* Returns the value of this <tt>Decimal</tt> as a <code>byte</code>. This
* may involve rounding or truncation.
*
* @return the numeric value represented by this object after conversion to
* type <code>byte</code>.
* @see Number#byteValue()
*/
byte byteValue();
/**
* Returns the value of this <tt>Decimal</tt> as a <code>short</code>. This
* may involve rounding or truncation.
*
* @return the numeric value represented by this object after conversion to
* type <code>short</code>.
* @see Number#shortValue()
*/
short shortValue();
/**
* Returns the value of this <tt>Decimal</tt> as an <code>int</code>. This
* may involve rounding or truncation.
*
* @return the numeric value represented by this object after conversion to
* type <code>int</code>.
* @see Number#intValue()
*/
int intValue();
/**
* Returns the value of this <tt>Decimal</tt> as a <code>long</code>. This
* may involve rounding.
*
* @return the numeric value represented by this object after conversion to
* type <code>long</code>.
* @see Number#longValue()
*/
long longValue();
/**
* Returns the value of this <tt>Decimal</tt> as a <code>float</code>. This
* may involve rounding.
*
* @return the numeric value represented by this object after conversion to
* type <code>float</code>.
* @see Number#floatValue()
*/
float floatValue();
/**
* Returns the value of this <tt>Decimal</tt> as a <code>double</code>. This
* may involve rounding.
*
* @return the numeric value represented by this object after conversion to
* type <code>double</code>.
* @see Number#doubleValue()
*/
double doubleValue();
/**
* Returns the unscaled value underlying this <tt>Decimal</tt>. Since the
* value of this {@code Decimal} is
* <tt>(unscaledValue × 10<sup>-n</sup>)</tt>, the returned value
* equals <tt>(this × 10<sup>n</sup>)</tt> with {@code n} standing for
* the number of {@link Scale#getFractionDigits() fraction digits}.
*
* @return the unscaled numeric value represented by this object when to
* type <code>long</code>
* @see #getScale()
* @see Scale#getFractionDigits()
* @see Scale#getScaleFactor()
*/
long unscaledValue();
/**
* Returns a {@code Decimal} whose value is {@code (this + augend)}.
* Depending on the implementation, a new decimal instance may be created
* and returned for the result, or this decimal may be modified and
* returned.
*
* @param augend
* value to be added to this {@code Decimal}.
* @return {@code this + augend}
*/
Decimal<S> add(Decimal<S> augend);
/**
* Returns a {@code Decimal} whose value is {@code (this - subtrahend)}.
* Depending on the implementation, a new decimal instance may be created
* and returned for the result, or this decimal may be modified and
* returned.
*
* @param subtrahend
* value to be subtracted from this {@code Decimal}.
* @return {@code this - subtrahend}
*/
Decimal<S> subtract(Decimal<S> subtrahend);
/**
* Returns a {@code Decimal} whose value is
* <tt>(this × multiplicand)</tt>. Depending on the implementation, a
* new decimal instance may be created and returned for the result, or this
* decimal may be modified and returned.
*
* @param multiplicand
* value to be multiplied with this {@code Decimal}.
* @return {@code this * multiple}
*/
Decimal<S> multiply(Decimal<S> multiplicand);
/**
* Returns a {@code Decimal} whose value is
* <tt>(this × multiplicand)</tt> applying the specified rounding
* mode. Depending on the implementation, a new decimal instance may be
* created and returned for the result, or this decimal may be modified and
* returned.
*
* @param multiplicand
* value to be multiplied with this {@code Decimal}.
* @param roundingMode
* the rounding mode to apply for this operation
* @return {@code this * multiple}
*/
Decimal<S> multiply(Decimal<S> multiplicand, RoundingMode roundingMode);
/**
* Returns a {@code Decimal} whose value is {@code (this / divisor)}.
* Depending on the implementation, a new decimal instance may be created
* and returned for the result, or this decimal may be modified and
* returned.
*
* @param divisor
* value by which this {@code Decimal} is to be divided.
* @return {@code this / divisor}
*/
Decimal<S> divide(Decimal<S> divisor);
/**
* Returns a {@code Decimal} whose value is {@code (this / divisor)}
* applying the specified rounding mode. Depending on the implementation, a
* new decimal instance may be created and returned for the result, or this
* decimal may be modified and returned.
*
* @param divisor
* value by which this {@code Decimal} is to be divided.
* @param roundingMode
* the rounding mode to apply for this operation
* @return {@code this / divisor}
*/
Decimal<S> divide(Decimal<S> divisor, RoundingMode roundingMode);
/**
* Returns a {@code Decimal} whose value is {@code (-this)}. Depending on
* the implementation, a new decimal instance may be created and returned
* for the result, or this decimal may be modified and returned.
*
* @return {@code -this}
*/
Decimal<S> negate();
/**
* Returns a {@code Decimal} whose value is the absolute value of this
* {@code Decimal}. Depending on the implementation, a new decimal instance
* may be created and returned for the result, or this decimal may be
* modified and returned.
*
* @return {@code abs(this)}
*/
Decimal<S> abs();
/**
* Returns a {@code Decimal} whose value is {@code (1/this)}. Depending on
* the implementation, a new decimal instance may be created and returned
* for the result, or this decimal may be modified and returned.
*
* @return {@code 1/this}
*/
Decimal<S> invert();
/**
* Returns a {@code Decimal} whose value is {@code (1/this)} applying the
* specified rounding mode. Depending on the implementation, a new decimal
* instance may be created and returned for the result, or this decimal may
* be modified and returned.
*
* @param roundingMode
* the rounding mode to apply for this operation
* @return {@code 1/this}
*/
Decimal<S> invert(RoundingMode roundingMode);
/**
* Returns the size of an ulp, a unit in the last place, of this
* {@code Decimal}. An ulp of a nonzero {@code Decimal} value is the
* positive distance between this value and the {@code Decimal} value next
* larger in magnitude with the same number of digits. An ulp of a zero
* value is numerically equal to 1 with the scale of {@code this}. The
* result is stored with the same scale as {@code this} so the result for
* zero and nonzero values is equal to {@code [1,
* getArithmethics().scale()]}.
* <p>
* Calling this method does NOT modify {@code this} instance; for constant
* decimals, an ULP constant is returned; for mutable decimals, a new
* mutable ULP instance is returned.
*
* @return the size of an ulp of {@code this}
*/
Decimal<S> ulp();
/**
* Returns the signum function of this {@code Decimal}.
*
* @return -1, 0, or 1 as the value of this {@code Decimal} is negative,
* zero, or positive.
*/
int signum();
/**
* Returns a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the left. If {@code n} is
* negative, the call is equivalent to {@code movePointRight(-n)}. The
* {@code Decimal} returned by this call has value <tt>(this ×
* 10<sup>-n</sup>)</tt>.
*
* @param n
* number of places to move the decimal point to the left.
* @return a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the left.
* @throws ArithmeticException
* if scale overflows.
*/
Decimal<S> movePointLeft(int n);
/**
* Returns a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the left. If {@code n} is
* negative, the call is equivalent to {@code movePointRight(-n)}. The
* {@code Decimal} returned by this call has value <tt>(this ×
* 10<sup>-n</sup>)</tt>. The specified rounding mode is applied if rounding
* is necessary.
*
* @param n
* number of places to move the decimal point to the left.
* @param roundingMode
* the rounding mode to apply for this operation
* @return a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the left.
* @throws ArithmeticException
* if scale overflows.
*/
Decimal<S> movePointLeft(int n, RoundingMode roundingMode);
/**
* Returns a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the right. If {@code n} is
* negative, the call is equivalent to {@code movePointLeft(-n)}. The
* {@code Decimal} returned by this call has value <tt>(this
* × 10<sup>n</sup>)</tt>.
*
* @param n
* number of places to move the decimal point to the right.
* @return a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the right.
* @throws ArithmeticException
* if scale overflows.
*/
Decimal<S> movePointRight(int n);
/**
* Returns a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the right. If {@code n} is
* negative, the call is equivalent to {@code movePointLeft(-n)}. The
* {@code Decimal} returned by this call has value <tt>(this
* × 10<sup>n</sup>)</tt>. The specified rounding mode is applied if
* rounding is necessary.
*
* @param n
* number of places to move the decimal point to the right.
* @param roundingMode
* the rounding mode to apply for this operation
* @return a {@code Decimal} which is equivalent to this one with the
* decimal point moved {@code n} places to the right.
* @throws ArithmeticException
* if scale overflows.
*/
Decimal<S> movePointRight(int n, RoundingMode roundingMode);
/**
* Returns a {@code Decimal} whose value is <tt>(this<sup>n</sup>)</tt>.
*
* @param n
* power to raise this {@code Decimal} to.
* @return <tt>this<sup>n</sup></tt>
* @throws ArithmeticException
* if {@code n} is negative and {@code this==0}
*/
Decimal<S> pow(int n);
/**
* Returns a {@code Decimal} whose value is <tt>(this<sup>n</sup>)</tt>
* applying the specified rounding mode.
*
* @param n
* power to raise this {@code Decimal} to.
* @param roundingMode
* the rounding mode to apply for this operation
* @return <tt>this<sup>n</sup></tt>
* @throws ArithmeticException
* if {@code n} is negative and {@code this==0}
*/
Decimal<S> pow(int n, RoundingMode roundingMode);
/**
* Returns a hash code for this {@code Decimal}. The result is the exclusive
* OR of the two halves of the primitive unscaled {@code long} value making
* up this {@code Decimal} object. That is, the hashcode is the value of the
* expression:
*
* <blockquote>
* {@code (int)(this.unscaledValue()^(this.unscaledValue()>>>32))}
* </blockquote>
*
* @return a hash code value for this object
*/
@Override
int hashCode();
/**
* Compares this object to the specified object. The result is {@code true}
* if and only if the argument is not {@code null} and is a {@code Decimal}
* object that contains the same value as this object and if the two
* decimals have the same {@link #getScale() scale}.
*
* @param obj
* the object to compare with.
* @return {@code true} if the argument is {@code Decimal} object that
* contains the same value and arithmetics as this object;
* {@code false} otherwise.
*/
@Override
boolean equals(Object obj);
/**
* Compares two {@code Decimal} objects numerically.
*
* @param anotherDecimal
* the {@code Decimal} to be compared.
* @return the value {@code 0} if this {@code Decimal} is equal to the
* argument {@code Decimal}; a value less than {@code 0} if this
* {@code Decimal} is numerically less than the argument
* {@code Decimal}; and a value greater than {@code 0} if this
* {@code Decimal} is numerically greater than the argument
* {@code Decimal} (signed comparison).
*/
@Override
int compareTo(Decimal<S> anotherDecimal);
/**
* Returns a string representation of this {@code Decimal} object as fixed
* precision decimal always showing all decimal places (also trailing zeros)
* and a leading sign character if negative.
*
* @return a {@code String} decimal representation of this {@code Decimal}
* object with all the fraction digits (including trailing zeros)
*/
@Override
String toString();
} |
package io.cattle.platform.docker.transform;
import static io.cattle.platform.core.constants.InstanceConstants.*;
import static io.cattle.platform.docker.constants.DockerInstanceConstants.*;
import io.cattle.platform.core.addon.BlkioDeviceOption;
import io.cattle.platform.core.addon.LogConfig;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.constants.VolumeConstants;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.util.SystemLabels;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;
import io.github.ibuildthecloud.gdapi.validation.ValidationErrorCodes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Device;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.LxcConf;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Ports.Binding;
import com.github.dockerjava.api.model.RestartPolicy;
import com.github.dockerjava.api.model.VolumeBind;
public class DockerTransformerImpl implements DockerTransformer {
private static final String HOST_CONFIG = "HostConfig";
private static final String CONFIG = "Config";
private static final String IMAGE_PREFIX = "docker:";
private static final String IMAGE_KIND_PATTERN = "^(sim|docker):.*";
private static final String READ_WRITE = "rw";
private static final String READ_ONLY = "ro";
private static final String ACCESS_MODE = "RW";
private static final String DRIVER = "Driver";
private static final String DEST = "Destination";
private static final String SRC = "Source";
private static final String NAME = "Name";
private static final String READ_IOPS= "BlkioDeviceReadIOps";
private static final String WRITE_IOPS= "BlkioDeviceWriteIOps";
private static final String READ_BPS= "BlkioDeviceReadBps";
private static final String WRITE_BPS= "BlkioDeviceWriteBps";
private static final String WEIGHT = "BlkioWeightDevice";
@Inject
JsonMapper jsonMapper;
@Override
@SuppressWarnings("unchecked")
public List<DockerInspectTransformVolume> transformVolumes(Map<String, Object> fromInspect, List<Object> mounts) {
List<DockerInspectTransformVolume> volumes = transformMounts(mounts);
if (volumes != null) {
return volumes;
}
volumes = new ArrayList<DockerInspectTransformVolume>();
InspectContainerResponse inspect = transformInspect(fromInspect);
HostConfig hostConfig = inspect.getHostConfig();
VolumeBind[] volumeBinds = null;
try {
volumeBinds = inspect.getVolumes();
} catch (NullPointerException e) {
// A bug in docker-java can cause this.
volumeBinds = new VolumeBind[0];
}
Set<String> binds = bindSet(hostConfig.getBinds());
Map<String, String> rw = rwMap((Map<String, Boolean>) fromInspect.get("VolumesRW"));
for (VolumeBind vb : volumeBinds) {
String am = rw.containsKey(vb.getContainerPath()) ? rw.get(vb.getContainerPath()) : READ_WRITE;
boolean isBindMound = binds.contains(vb.getContainerPath());
String uri = String.format(VolumeConstants.URI_FORMAT, VolumeConstants.FILE_PREFIX, vb.getHostPath());
volumes.add(new DockerInspectTransformVolume(vb.getContainerPath(), uri, am, isBindMound, null, vb.getContainerPath(), null));
}
return volumes;
}
@SuppressWarnings("unchecked")
protected List<DockerInspectTransformVolume> transformMounts(List<Object> mounts) {
if (mounts == null) {
return null;
}
List<DockerInspectTransformVolume> volumes = new ArrayList<DockerInspectTransformVolume>();
for (Object mount : mounts) {
Map<String, Object> mountObj = (Map<String, Object>)mount;
String am = ((boolean)mountObj.get(ACCESS_MODE)) ? "rw" : "ro";
String dr = (String)mountObj.get(DRIVER);
String containerPath = (String)mountObj.get(DEST);
String hostPath = (String)mountObj.get(SRC);
String name = (String)mountObj.get(NAME);
String externalId = null;
if (StringUtils.isEmpty(name)) {
name = hostPath;
} else {
externalId = name;
}
if ("rancher-cni".equals(name)) {
continue;
}
boolean isBindMount = (dr == null);
// TODO When we implement proper volume deletion in py-agent, we can change this so that if the driver is explicitly, local, we don't
// use 'file://'
String uriPrefix = StringUtils.isEmpty(dr) || StringUtils.equals(dr, VolumeConstants.LOCAL_DRIVER) ? VolumeConstants.FILE_PREFIX : dr;
String uri = String.format(VolumeConstants.URI_FORMAT, uriPrefix, hostPath);
volumes.add(new DockerInspectTransformVolume(containerPath, uri, am, isBindMount, dr, name, externalId));
}
return volumes;
}
Map<String, String> rwMap(Map<String, Boolean> volumeRws) {
// TODO When this bug is fixed, switch to using java-docker's volumesRW
Map<String, String> rwMap = new HashMap<String, String>();
if (volumeRws == null) {
return rwMap;
}
for (Map.Entry<String, Boolean> volume : volumeRws.entrySet()) {
Boolean readWrite = volume.getValue();
String perms = readWrite ? READ_WRITE : READ_ONLY;
rwMap.put(volume.getKey(), perms);
}
return rwMap;
}
Set<String> bindSet(String[] binds) {
Set<String> hostBindMounts = new HashSet<String>();
if (binds == null)
return hostBindMounts;
for (String bindMount : binds) {
String[] parts = bindMount.split(":");
hostBindMounts.add(parts[1]);
}
return hostBindMounts;
}
@Override
public void transform(Map<String, Object> fromInspect, Instance instance) {
InspectContainerResponse inspect = transformInspect(fromInspect);
ContainerConfig containerConfig = inspect.getConfig();
HostConfig hostConfig = inspect.getHostConfig();
instance.setExternalId(inspect.getId());
instance.setKind(KIND_CONTAINER);
setName(instance, inspect, fromInspect);
if (containerConfig != null) {
instance.setHostname((String) fixEmptyValue(containerConfig.getHostName()));
setField(instance, FIELD_MEMORY, containerConfig.getMemoryLimit());
setField(instance, FIELD_CPU_SET, containerConfig.getCpuset());
setField(instance, FIELD_CPU_SHARES, containerConfig.getCpuShares());
setField(instance, FIELD_MEMORY_SWAP, containerConfig.getMemorySwap());
setField(instance, FIELD_DOMAIN_NAME, containerConfig.getDomainName());
setField(instance, FIELD_USER, containerConfig.getUser());
setField(instance, FIELD_TTY, containerConfig.isTty());
setField(instance, FIELD_STDIN_OPEN, containerConfig.isStdinOpen());
setImage(instance, containerConfig.getImage());
setField(instance, FIELD_WORKING_DIR, containerConfig.getWorkingDir());
setEnvironment(instance, containerConfig.getEnv());
setCommand(instance, containerConfig.getCmd());
setListField(instance, FIELD_ENTRY_POINT, containerConfig.getEntrypoint());
setField(instance, FIELD_VOLUME_DRIVER, fromInspect, "Config", "VolumeDriver");
setField(instance, FIELD_STOP_SIGNAL, fromInspect, CONFIG, "StopSignal");
setHealthConfig(fromInspect, instance);
}
if (containerConfig != null && hostConfig != null) {
setVolumes(instance, containerConfig.getVolumes(), hostConfig.getBinds());
setPorts(instance, safeGetExposedPorts(containerConfig), hostConfig.getPortBindings());
}
if (hostConfig != null) {
setField(instance, FIELD_PRIVILEGED, hostConfig.isPrivileged());
setField(instance, FIELD_PUBLISH_ALL_PORTS, hostConfig.isPublishAllPorts());
setLxcConf(instance, hostConfig.getLxcConf());
setListField(instance, FIELD_DNS, hostConfig.getDns());
setListField(instance, FIELD_DNS_SEARCH, hostConfig.getDnsSearch());
setCapField(instance, FIELD_CAP_ADD, hostConfig.getCapAdd());
setCapField(instance, FIELD_CAP_DROP, hostConfig.getCapDrop());
setRestartPolicy(instance, hostConfig.getRestartPolicy());
setDevices(instance, hostConfig.getDevices());
setMemoryReservation(fromInspect, instance);
setField(instance, FIELD_BLKIO_WEIGHT, fromInspect, HOST_CONFIG, "BlkioWeight");
setField(instance, FIELD_CGROUP_PARENT, fromInspect, HOST_CONFIG, "CgroupParent");
setField(instance, FIELD_CPU_PERIOD, fromInspect, HOST_CONFIG, "CpuPeriod");
setField(instance, FIELD_CPU_QUOTA, fromInspect, HOST_CONFIG, "CpuQuota");
setField(instance, FIELD_CPUSET_MEMS, fromInspect, HOST_CONFIG, "CpusetMems");
setField(instance, FIELD_DNS_OPT, fromInspect, HOST_CONFIG, "DnsOptions");
setField(instance, FIELD_GROUP_ADD, fromInspect, HOST_CONFIG, "GroupAdd");
setField(instance, FIELD_KERNEL_MEMORY, fromInspect, HOST_CONFIG, "KernelMemory");
setField(instance, FIELD_MEMORY_SWAPPINESS, fromInspect, HOST_CONFIG, "MemorySwappiness");
setField(instance, FIELD_OOMKILL_DISABLE, fromInspect, HOST_CONFIG, "OomKillDisable");
setField(instance, FIELD_SHM_SIZE, fromInspect, HOST_CONFIG, "ShmSize");
setField(instance, FIELD_TMPFS, fromInspect, HOST_CONFIG, "Tmpfs");
setField(instance, FIELD_UTS, fromInspect, HOST_CONFIG, "UTSMode");
setField(instance, FIELD_IPC_MODE, fromInspect, HOST_CONFIG, "IpcMode");
setField(instance, FIELD_SYSCTLS, fromInspect, HOST_CONFIG, "Sysctls");
setField(instance, FIELD_OOM_SCORE_ADJ, fromInspect, HOST_CONFIG, "OomScoreAdj");
setField(instance, FIELD_ULIMITS, fromInspect, HOST_CONFIG, "Ulimits");
}
setBlkioDeviceOptionss(instance, fromInspect);
setNetworkMode(instance, containerConfig, hostConfig);
setField(instance, FIELD_SECURITY_OPT, fromInspect, HOST_CONFIG, "SecurityOpt");
setField(instance, FIELD_PID_MODE, fromInspect, HOST_CONFIG, "PidMode");
setField(instance, FIELD_READ_ONLY, fromInspect, HOST_CONFIG, "ReadonlyRootfs");
setField(instance, FIELD_EXTRA_HOSTS, fromInspect, HOST_CONFIG, "ExtraHosts");
setFieldIfNotEmpty(instance, FIELD_CPU_SHARES, fromInspect, HOST_CONFIG, "CpuShares");
setFieldIfNotEmpty(instance, FIELD_CPU_SET, fromInspect, HOST_CONFIG, "CpusetCpus");
setFieldIfNotEmpty(instance, FIELD_MEMORY, fromInspect, HOST_CONFIG, "Memory");
setFieldIfNotEmpty(instance, FIELD_MEMORY_SWAP, fromInspect, HOST_CONFIG, "MemorySwap");
setLogConfig(instance, fromInspect);
setLabels(instance, fromInspect);
// Currently not implemented: VolumesFrom, Links,
// Consider: AttachStdin, AttachStdout, AttachStderr, StdinOnce,
}
void setMemoryReservation(Map<String, Object> fromInspect, Instance instance) {
Object memRes = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "MemoryReservation");
if (memRes != null && memRes instanceof Number) {
instance.setMemoryReservation(((Number)memRes).longValue());
}
}
void setHealthConfig(Map<String, Object> fromInspect, Instance instance) {
Object healthCmd = CollectionUtils.getNestedValue(fromInspect, CONFIG, "Healthcheck", "Test");
Object healthInterval = CollectionUtils.getNestedValue(fromInspect, CONFIG, "Healthcheck", "Interval");
Object healthTimeout = CollectionUtils.getNestedValue(fromInspect, CONFIG, "Healthcheck", "Timeout");
Object healthRetries = CollectionUtils.getNestedValue(fromInspect, CONFIG, "Healthcheck", "Retries");
if (healthCmd != null) {
setField(instance, "healthCmd", healthCmd);
}
if (healthInterval != null) {
setField(instance, "healthInterval", healthInterval);
}
if (healthTimeout != null) {
setField(instance, "healthTimeout", healthTimeout);
}
if (healthTimeout != null) {
setField(instance, "healthRetries", healthRetries);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void setBlkioDeviceOptionss(Instance instance, Map<String, Object> fromInspect) {
/*
* We're coverting from docker's structure of:
* {BlkioDeviceReadIOps: [{Path: <device>, Rate: 1000} ... ], BlkioDeviceWriteIOps: [{Path: <device>, Rate: 1000} ... ] ... }
* to cattle's structure of:
* {blkioDeviceOptions: {<device>: {readIops: 1000m writeIops: 1000 ... } ... }
*/
List<String> fields = Arrays.asList(READ_IOPS, WRITE_IOPS, READ_BPS, WRITE_BPS, WEIGHT);
Map<String, BlkioDeviceOption> target = new HashMap<>();
for (String field : fields) {
List<Map> deviceOptions = null;
try {
deviceOptions = (List<Map>)CollectionUtils.toList(CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, field));
} catch (Exception e) {
continue;
}
if (deviceOptions == null || deviceOptions.isEmpty()) {
continue;
}
for (Map deviceOption : deviceOptions) {
String path = null;
Integer value = null;
try {
path = (String)deviceOption.get("Path");
value = (Integer)(field == WEIGHT ? deviceOption.get("Weight") : deviceOption.get("Rate"));
} catch (Exception e) {
// just skip it
}
if (path != null && value != null) {
BlkioDeviceOption targetDevOpt = target.get(path);
if (targetDevOpt == null) {
targetDevOpt = new BlkioDeviceOption();
target.put(path, targetDevOpt);
}
switch (field) {
case READ_IOPS:
targetDevOpt.setReadIops(value);
break;
case WRITE_IOPS:
targetDevOpt.setWriteIops(value);
break;
case READ_BPS:
targetDevOpt.setReadBps(value);
break;
case WRITE_BPS:
targetDevOpt.setWriteBps(value);
break;
case WEIGHT:
targetDevOpt.setWeight(value);
break;
}
}
}
}
if (!target.isEmpty()) {
setField(instance, FIELD_BLKIO_DEVICE_OPTIONS, target);
}
}
void setNetworkMode(Instance instance, ContainerConfig containerConfig, HostConfig hostConfig) {
if(DataAccessor.fields(instance).withKey(FIELD_NETWORK_MODE).get() != null)
return;
String netMode = null;
if (containerConfig != null && containerConfig.isNetworkDisabled()) {
netMode = NetworkConstants.NETWORK_MODE_NONE;
} else if (hostConfig != null) {
String inspectNetMode = hostConfig.getNetworkMode();
if (NetworkConstants.NETWORK_MODE_BRIDGE.equals(inspectNetMode) ||
NetworkConstants.NETWORK_MODE_HOST.equals(inspectNetMode) ||
NetworkConstants.NETWORK_MODE_NONE.equals(inspectNetMode)) {
netMode = inspectNetMode;
} else if (NetworkConstants.NETWORK_MODE_DEFAULT.equals(inspectNetMode) || StringUtils.isBlank(inspectNetMode)) {
netMode = NetworkConstants.NETWORK_MODE_BRIDGE;
} else if (StringUtils.startsWith(inspectNetMode, NetworkConstants.NETWORK_MODE_CONTAINER)) {
throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_OPTION,
"Transformer API does not support container network mode.", null);
} else {
throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_OPTION,
"Unrecognized network mode: " + inspectNetMode, null);
}
}
setField(instance, FIELD_NETWORK_MODE, netMode);
}
void setField(Instance instance, String field, Map<String, Object> fromInspect, String... keys) {
Object l = CollectionUtils.getNestedValue(fromInspect, keys);
setField(instance, field, l);
}
void setFieldIfNotEmpty(Instance instance, String field, Map<String, Object> fromInspect, String... keys) {
Object l = CollectionUtils.getNestedValue(fromInspect, keys);
if (!isEmptyValue(l)) {
setField(instance, field, l);
}
}
@SuppressWarnings("unchecked")
void setLogConfig(Instance instance, Map<String, Object> fromInspect) {
Object type = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "LogConfig", "Type");
Object config = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "LogConfig", "Config");
if (type == null && config == null) {
return;
}
LogConfig logConfig = new LogConfig();
if (type != null) {
logConfig.setDriver(type.toString());
}
if (config instanceof Map) {
logConfig.setConfig((Map<String, String>)config);
}
setField(instance, FIELD_LOG_CONFIG, logConfig);
}
@Override
@SuppressWarnings({ "rawtypes" })
public void setLabels(Instance instance, Map<String, Object> fromInspect) {
// Labels not yet implemented in docker-java. Need to use the raw map
Object l = CollectionUtils.getNestedValue(fromInspect, "Config", "Labels");
Map<String, Object> cleanedLabels = new HashMap<String, Object>();
if (l instanceof Map) {
Map labels = (Map)l;
for (Object key : labels.keySet()) {
if (key == null)
continue;
Object value = labels.get(key);
if (value == null)
value = "";
cleanedLabels.put(key.toString(), value.toString());
}
}
Map<String, Object> labels = DataAccessor.fieldMap(instance, FIELD_LABELS);
labels.putAll(cleanedLabels);
setField(instance, FIELD_LABELS, labels);
}
void setImage(Instance instance, String image) {
if (StringUtils.isNotBlank(image) && !image.matches(IMAGE_KIND_PATTERN)) {
image = IMAGE_PREFIX + image;
}
setField(instance, FIELD_IMAGE_UUID, image);
}
void setName(Instance instance, InspectContainerResponse inspect, Map<String, Object> fromInspect) {
String name = inspect.getName();
Object displayNameLabel = CollectionUtils.getNestedValue(fromInspect, "Config", "Labels", SystemLabels.LABEL_DISPLAY_NAME);
if (displayNameLabel == null) {
displayNameLabel = DataAccessor.fieldMap(instance, FIELD_LABELS).get(SystemLabels.LABEL_DISPLAY_NAME);
}
if (displayNameLabel != null) {
String displayName = displayNameLabel.toString();
if (StringUtils.isNotBlank(displayName)) {
name = displayName;
}
}
if (name != null) {
name = name.replaceFirst("/", "");
instance.setName(name);
}
}
private ExposedPort[] safeGetExposedPorts(ContainerConfig containerConfig) {
try {
return containerConfig.getExposedPorts();
} catch (NullPointerException e) {
// Bug in docker-java doesn't account for this property being null
return null;
}
}
void setDevices(Instance instance, Device[] devices) {
if (devices == null) {
devices = new Device[0];
}
List<String> instanceDevices = new ArrayList<String>();
for (Device d : devices) {
StringBuilder fullDevice = new StringBuilder(d.getPathOnHost()).append(":").append(d.getPathInContainer()).append(":");
if (StringUtils.isEmpty(d.getcGroupPermissions())) {
fullDevice.append("rwm");
} else {
fullDevice.append(d.getcGroupPermissions());
}
instanceDevices.add(fullDevice.toString());
}
setField(instance, FIELD_DEVICES, instanceDevices);
}
void setRestartPolicy(Instance instance, RestartPolicy restartPolicy) {
if (restartPolicy == null || StringUtils.isEmpty(restartPolicy.getName())) {
return;
}
io.cattle.platform.core.addon.RestartPolicy rp = new io.cattle.platform.core.addon.RestartPolicy();
rp.setMaximumRetryCount(restartPolicy.getMaximumRetryCount());
rp.setName(restartPolicy.getName());
setField(instance, FIELD_RESTART_POLICY, rp);
}
void setCapField(Instance instance, String field, Capability[] caps) {
if (caps == null) {
caps = new Capability[0];
}
List<String> list = new ArrayList<String>();
for (Capability cap : caps) {
list.add(cap.toString());
}
setField(instance, field, list);
}
void setLxcConf(Instance instance, LxcConf[] lxcConf) {
if (lxcConf == null || lxcConf.length == 0) {
lxcConf = new LxcConf[0];
}
Map<String, String> instanceLxcConf = new HashMap<String, String>();
for (LxcConf lxc : lxcConf) {
instanceLxcConf.put(lxc.getKey(), lxc.getValue());
}
setField(instance, FIELD_LXC_CONF, instanceLxcConf);
}
void setPorts(Instance instance, ExposedPort[] exposedPorts, Ports portBindings) {
if (exposedPorts == null) {
exposedPorts = new ExposedPort[0];
}
List<String> ports = new ArrayList<String>();
for (ExposedPort ep : exposedPorts) {
String port = ep.toString();
Binding[] bindings = portBindings == null || portBindings.getBindings() == null ? null : portBindings.getBindings().get(ep);
if (bindings != null && bindings.length > 0) {
for (Binding b : bindings) {
// HostPort should really be a string, not an int. Somehow empty string becomes 0
if (b.getHostPort() != null && b.getHostPort() != 0) {
String fullPort = b.getHostPort() + ":" + port;
ports.add(fullPort);
} else {
ports.add(port);
}
}
}
}
setField(instance, FIELD_PORTS, ports);
}
void setVolumes(Instance instance, Map<String, ?> volumes, String[] binds) {
List<String> dataVolumes = new ArrayList<String>();
if (volumes != null) {
dataVolumes.addAll(volumes.keySet());
}
if (binds != null) {
dataVolumes.addAll(Arrays.asList(binds));
}
setField(instance, InstanceConstants.FIELD_DATA_VOLUMES, dataVolumes);
}
void setListField(Instance instance, String field, String[] value) {
if (value == null) {
value = new String[0];
}
List<String> list = new ArrayList<String>(Arrays.asList(value));
setField(instance, field, list);
}
void setCommand(Instance instance, String[] cmd) {
if (cmd == null) {
cmd = new String[0];
}
List<String> args = new ArrayList<String>();
args.addAll(Arrays.asList(cmd));
setField(instance, FIELD_COMMAND, args);
}
void setEnvironment(Instance instance, String[] env) {
if (env == null) {
env = new String[0];
}
Map<String, String> envMap = new HashMap<String, String>();
for (String e : env) {
String[] kvp = e.split("=", 2);
if (kvp.length == 2) {
envMap.put(kvp[0], kvp[1]);
} else if (kvp.length == 1) {
// TODO Change the Rancher API to support valueless environment variables.
// -e FOO and -e FOO="" are not the same thing.
envMap.put(kvp[0], "");
}
}
setField(instance, FIELD_ENVIRONMENT, envMap);
}
private void setField(Instance instance, String field, Object fieldValue) {
fieldValue = fixEmptyValue(fieldValue);
DataAccessor.fields(instance).withKey(field).set(fieldValue);
}
@SuppressWarnings({ "rawtypes", "unused" })
private Object fixEmptyValue(Object fieldValue) {
if (fieldValue instanceof String && StringUtils.isEmpty((String)fieldValue)) {
return null;
} else if (fieldValue instanceof Number && ((Number)fieldValue).longValue() == 0L) {
return null;
} else if (fieldValue instanceof List && fieldValue == null) {
return new ArrayList();
} else if (fieldValue instanceof Map && fieldValue == null) {
return new HashMap();
}
return fieldValue;
}
private boolean isEmptyValue(Object fieldValue) {
return fieldValue == null ||
(fieldValue instanceof String && StringUtils.isEmpty((String) fieldValue)) ||
(fieldValue instanceof Number && ((Number) fieldValue).longValue() == 0L) ||
(fieldValue instanceof List && fieldValue == null) ||
(fieldValue instanceof Map && fieldValue == null);
}
InspectContainerResponse transformInspect(Map<String, Object> inspect) {
return jsonMapper.convertValue(inspect, InspectContainerResponse.class);
}
} |
package codechicken.lib.gui;
import codechicken.lib.math.MathHelper;
import codechicken.lib.texture.TextureUtils;
import codechicken.lib.vec.Rectangle4i;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.event.RenderTooltipEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.config.GuiUtils;
import org.lwjgl.input.Mouse;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GuiDraw {
public static class GuiHook extends Gui {
public void setZLevel(float f) {
zLevel = f;
}
public float getZLevel() {
return zLevel;
}
public void incZLevel(float f) {
zLevel += f;
}
@Override
public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) {
super.drawGradientRect(par1, par2, par3, par4, par5, par6);
}
}
public static final GuiHook gui = new GuiHook();
public static FontRenderer fontRenderer = Minecraft.getMinecraft().fontRendererObj;
public static TextureManager renderEngine = Minecraft.getMinecraft().renderEngine;
public static void drawRect(int x, int y, int w, int h, int colour) {
drawGradientRect(x, y, w, h, colour, colour);
}
public static void drawGradientRectDirect(int left, int top, int right, int bottom, int colour1, int colour2) {
gui.drawGradientRect(left, top, right, bottom, colour1, colour2);
}
public static void drawGradientRect(int x, int y, int w, int h, int colour1, int colour2) {
gui.drawGradientRect(x, y, x + w, y + h, colour1, colour2);
}
public static void drawTexturedModalRect(int x, int y, int tx, int ty, int w, int h) {
gui.drawTexturedModalRect(x, y, tx, ty, w, h);
}
public static void drawString(String text, int x, int y, int colour, boolean shadow) {
if (shadow) {
fontRenderer.drawStringWithShadow(text, x, y, colour);
} else {
fontRenderer.drawString(text, x, y, colour);
}
}
public static void drawString(String text, int x, int y, int colour) {
drawString(text, x, y, colour, true);
}
public static void drawStringC(String text, int x, int y, int w, int h, int colour, boolean shadow) {
drawString(text, x + (w - getStringWidth(text)) / 2, y + (h - 8) / 2, colour, shadow);
}
public static void drawStringC(String text, int x, int y, int w, int h, int colour) {
drawStringC(text, x, y, w, h, colour, true);
}
public static void drawStringC(String text, int x, int y, int colour, boolean shadow) {
drawString(text, x - getStringWidth(text) / 2, y, colour, shadow);
}
public static void drawStringC(String text, int x, int y, int colour) {
drawStringC(text, x, y, colour, true);
}
public static void drawStringR(String text, int x, int y, int colour, boolean shadow) {
drawString(text, x - getStringWidth(text), y, colour, shadow);
}
public static void drawStringR(String text, int x, int y, int colour) {
drawStringR(text, x, y, colour, true);
}
public static int getStringWidth(String s) {
if (s == null || s.equals("")) {
return 0;
}
return fontRenderer.getStringWidth(TextFormatting.getTextWithoutFormattingCodes(s));
}
//TODO, getDisplaySize.
public static Dimension displaySize() {
Minecraft mc = Minecraft.getMinecraft();
ScaledResolution res = new ScaledResolution(mc);
return new Dimension(res.getScaledWidth(), res.getScaledHeight());
}
//TODO, getDisplayRes
public static Dimension displayRes() {
Minecraft mc = Minecraft.getMinecraft();
return new Dimension(mc.displayWidth, mc.displayHeight);
}
public static Point getMousePosition(int eventX, int eventY) {
Dimension size = displaySize();
Dimension res = displayRes();
return new Point(eventX * size.width / res.width, size.height - eventY * size.height / res.height - 1);
}
public static Point getMousePosition() {
return getMousePosition(Mouse.getX(), Mouse.getY());
}
public static void changeTexture(String s) {
TextureUtils.changeTexture(s);
}
public static void changeTexture(ResourceLocation r) {
TextureUtils.changeTexture(r);
}
public static void drawTip(int x, int y, String text) {
drawMultilineTip(x, y, Arrays.asList(text));
}
/**
* Append a string in the tooltip list with TOOLTIP_LINESPACE to have a small gap between it and the next line
*/
public static final String TOOLTIP_LINESPACE = "\u00A7h";
/**
* Have a string in the tooltip list with TOOLTIP_HANDLER + getTipLineId(handler) for a custom handler
*/
@Deprecated
public static final String TOOLTIP_HANDLER = "\u00A7x";
@Deprecated
private static List<ITooltipLineHandler> tipLineHandlers = new ArrayList<ITooltipLineHandler>();
@Deprecated//This is dead as there are forge events.
public interface ITooltipLineHandler {
Dimension getSize();
void draw(int x, int y);
}
@Deprecated
public static int getTipLineId(ITooltipLineHandler handler) {
return -1;
}
public static ITooltipLineHandler getTipLine(String line) {
return null;
}
@Deprecated
public static void drawMultilineTip(int x, int y, List<String> list) {
drawMultilineTip(null, x, y, list);
}
public static void drawMultilineTip(@Nullable ItemStack stack, int x, int y, List<String> lines) {
//TODO TOOLTIP_LINESPACE support, pr forge to clip the box in the top bound of the screen + TOOLTIP_LINESPACE
/*if (lines.isEmpty()) {
return;
}
GlStateManager.disableRescaleNormal();
RenderHelper.disableStandardItemLighting();
GlStateManager.disableDepth();
int w = 0;
int h = -2;
for (int i = 0; i < lines.size(); i++) {
String s = lines.get(i);
ITooltipLineHandler line = getTipLine(s);
Dimension d = line != null ? line.getSize() : new Dimension(getStringWidth(s), lines.get(i).endsWith(TOOLTIP_LINESPACE) && i + 1 < lines.size() ? 12 : 10);
w = Math.max(w, d.width);
h += d.height;
}
if (x < 8) {
x = 8;
} else if (x > displaySize().width - w - 8) {
x -= 24 + w;//flip side of cursor
if (x < 8) {
x = 8;
}
}
y = (int) MathHelper.clip(y, 8, displaySize().height - 8 - h);
gui.incZLevel(300);
drawTooltipBox(x - 4, y - 4, w + 7, h + 7);
for (String s : lines) {
ITooltipLineHandler line = getTipLine(s);
if (line != null) {
line.draw(x, y);
y += line.getSize().height;
} else {
fontRenderer.drawStringWithShadow(s, x, y, -1);
y += s.endsWith(TOOLTIP_LINESPACE) ? 12 : 10;
}
}
tipLineHandlers.clear();
gui.incZLevel(-300);
GlStateManager.enableDepth();
RenderHelper.enableStandardItemLighting();
GlStateManager.enableRescaleNormal();*/
ScaledResolution res = new ScaledResolution(Minecraft.getMinecraft());
int screenWidth = res.getScaledWidth();
int screenHeight = res.getScaledHeight();
if (lines.isEmpty()) {
return;
}
RenderTooltipEvent.Pre event = new RenderTooltipEvent.Pre(stack, lines, x, y, screenWidth, screenHeight, -1, fontRenderer);
if (MinecraftForge.EVENT_BUS.post(event)) {
return;
}
x = event.getX();
y = event.getY();
screenWidth = event.getScreenWidth();
screenHeight = event.getScreenHeight();
int maxTextWidth = event.getMaxWidth();
FontRenderer font = event.getFontRenderer();
GlStateManager.disableRescaleNormal();
RenderHelper.disableStandardItemLighting();
GlStateManager.disableLighting();
GlStateManager.disableDepth();
if (x < 8) {
x = 8;
}
y = MathHelper.clip(y, 8, displaySize().height - 8);
int tooltipTextWidth = 0;
for (String textLine : lines)
{
int textLineWidth = font.getStringWidth(textLine);
if (textLineWidth > tooltipTextWidth)
{
tooltipTextWidth = textLineWidth;
}
}
boolean needsWrap = false;
int titleLinesCount = 1;
int tooltipX = x + 12;
if (tooltipX + tooltipTextWidth + 4 > screenWidth)
{
tooltipX = x - 16 - tooltipTextWidth;
if (tooltipX < 4) // if the tooltip doesn't fit on the screen
{
if (x > screenWidth / 2)
{
tooltipTextWidth = x - 12 - 8;
}
else
{
tooltipTextWidth = screenWidth - 16 - x;
}
needsWrap = true;
}
}
if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth)
{
tooltipTextWidth = maxTextWidth;
needsWrap = true;
}
if (needsWrap)
{
int wrappedTooltipWidth = 0;
List<String> wrappedTextLines = new ArrayList<String>();
for (int i = 0; i < lines.size(); i++)
{
String textLine = lines.get(i);
List<String> wrappedLine = font.listFormattedStringToWidth(textLine, tooltipTextWidth);
if (i == 0)
{
titleLinesCount = wrappedLine.size();
}
for (String line : wrappedLine)
{
int lineWidth = font.getStringWidth(line);
if (lineWidth > wrappedTooltipWidth)
{
wrappedTooltipWidth = lineWidth;
}
wrappedTextLines.add(line);
}
}
tooltipTextWidth = wrappedTooltipWidth;
lines = wrappedTextLines;
if (x > screenWidth / 2)
{
tooltipX = x - 16 - tooltipTextWidth;
}
else
{
tooltipX = x;
}
}
int tooltipY = y;
int tooltipHeight = 8;
if (lines.size() > 1)
{
tooltipHeight += (lines.size() - 1) * 10;
if (lines.size() > titleLinesCount) {
tooltipHeight += 2; // gap between title lines and next lines
}
}
if (tooltipY + tooltipHeight + 6 > screenHeight) {
tooltipY = screenHeight - tooltipHeight - 6;
}
int backgroundColor = 0xF0100010;
drawGradientRectDirect(tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3, tooltipY - 3, backgroundColor, backgroundColor);
drawGradientRectDirect(tooltipX - 3, tooltipY + tooltipHeight + 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, backgroundColor, backgroundColor);
drawGradientRectDirect(tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
drawGradientRectDirect(tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
drawGradientRectDirect(tooltipX + tooltipTextWidth + 3, tooltipY - 3, tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
int borderColorStart = 0x505000FF;
int borderColorEnd = (borderColorStart & 0xFEFEFE) >> 1 | borderColorStart & 0xFF000000;
drawGradientRectDirect(tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
drawGradientRectDirect(tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
drawGradientRectDirect(tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY - 3 + 1, borderColorStart, borderColorStart);
drawGradientRectDirect(tooltipX - 3, tooltipY + tooltipHeight + 2, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd);
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostBackground(stack, lines, tooltipX, tooltipY, font, tooltipTextWidth, tooltipHeight));
int tooltipTop = tooltipY;
for (int lineNumber = 0; lineNumber < lines.size(); ++lineNumber)
{
String line = lines.get(lineNumber);
font.drawStringWithShadow(line, (float)tooltipX, (float)tooltipY, -1);
if (lineNumber + 1 == titleLinesCount)
{
tooltipY += 2;
}
tooltipY += 10;
}
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostText(stack, lines, tooltipX, tooltipTop, font, tooltipTextWidth, tooltipHeight));
GlStateManager.enableLighting();
GlStateManager.enableDepth();
RenderHelper.enableStandardItemLighting();
GlStateManager.enableRescaleNormal();
}
@Deprecated//TODO 1.11, update this to do what is done in the other method(vague, i know what it means tho :P)
public static void drawTooltipBox(int x, int y, int w, int h) {
int bg = 0xf0100010;
drawGradientRect(x + 1, y, w - 1, 1, bg, bg);
drawGradientRect(x + 1, y + h, w - 1, 1, bg, bg);
drawGradientRect(x + 1, y + 1, w - 1, h - 1, bg, bg);//center
drawGradientRect(x, y + 1, 1, h - 1, bg, bg);
drawGradientRect(x + w, y + 1, 1, h - 1, bg, bg);
int grad1 = 0x505000ff;
int grad2 = 0x5028007F;
drawGradientRect(x + 1, y + 2, 1, h - 3, grad1, grad2);
drawGradientRect(x + w - 1, y + 2, 1, h - 3, grad1, grad2);
drawGradientRect(x + 1, y + 1, w - 1, 1, grad1, grad1);
drawGradientRect(x + 1, y + h - 1, w - 1, 1, grad2, grad2);
}
} |
package com.africacraft.main;
import com.africacraft.entity.ModEntities;
import com.africacraft.item.ModItems;
import com.africacraft.mob.SoundEvents2;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = ACMain.MODID, name = ACMain.MODNAME, version = ACMain.MODVERSION)
public class ACMain {
public static final String MODID = "africacraft";
public static final String MODNAME = "AfricaCraft, an African Safari Experience";
public static final String MODVERSION = "1.0.0";
public static final CreativeTabs AfricaCraft_Items = new CreativeTabs("AfricaCraft") {
@Override public Item getTabIconItem() {
return ModItems.redstarpickaxe;
}
};
@SidedProxy(clientSide="com.africacraft.main.ClientProxy", serverSide="com.africacraft.main.ServerProxy")
public static CommonProxy proxy;
@Mod.Instance
public static ACMain instance;
public static org.apache.logging.log4j.Logger logger;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent e) {
logger = e.getModLog();
proxy.preInit(e);
}
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
proxy.init(e);
proxy.registerRenders();
proxy.registerRenders();
ModEntities.registerEntity();
SoundEvents2.registerSounds();
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent e) {
proxy.postInit(e);
}
public static ACMain getInstance(){
return instance;
}
} |
package com.cidic.design.model;
// Generated 2017-5-9 16:09:09 by Hibernate Tools 4.3.1.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* News generated by hbm2java
*/
@Entity
@Table(name = "news", catalog = "design_competition")
public class News implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String title;
private String newsAbstract;
private String thumb;
private Date publishTime;
private String content;
public News() {
}
public News(String title, Date publishTime, String content) {
this.title = title;
this.publishTime = publishTime;
this.content = content;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "title", nullable = false, length = 50)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "news_abstract", nullable = false)
public String getNewsAbstract() {
return this.newsAbstract;
}
public void setNewsAbstract(String newsAbstract) {
this.newsAbstract = newsAbstract;
}
@Column(name = "thumb", nullable = false, length = 40)
public String getThumb() {
return this.thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "publish_time", nullable = false, length = 19)
public Date getPublishTime() {
return this.publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
@Column(name = "content", nullable = false, length = 65535)
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
} |
package com.dta.services.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.codehaus.jackson.annotate.JsonIgnore;
@Entity
@Cacheable(false)
public class User {
/*Attributes*/
@Id
@GeneratedValue
private long id;
@NotNull
private String login;
@NotNull
private String password;
private int balance;
@NotNull
private String email;
@Enumerated(EnumType.STRING)
private Role role;
@Temporal(TemporalType.TIMESTAMP)
private Date creation;
@Temporal(TemporalType.TIMESTAMP)
private Date birth;
@NotNull
private String department;
@NotNull
private String country;
@OneToMany(mappedBy="author",cascade=CascadeType.PERSIST)
private List<Advert> adverts;
private boolean enabled;
/*Constructors*/
public User() {
}
public User(String login, String password, int balance, String email, Role role) {
this.login = login;
this.password = password;
this.balance = balance;
this.email = email;
this.role = role;
}
/*Getters*/
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public int getBalance() {
return balance;
}
public String getEmail() {
return email;
}
public Role getRole() {
return role;
}
/*Setters*/
public void setId(long id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setBalance(int balance) {
this.balance = balance;
}
public void setEmail(String email) {
this.email = email;
}
public void setRole(Role role) {
this.role = role;
}
public Date getCreation() {
return creation;
}
public void setCreation(Date creation) {
this.creation = creation;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@JsonIgnore
public List<Advert> getAdverts() {
return adverts;
}
public void setAdverts(List<Advert> adverts) {
this.adverts = adverts;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
} |
package org.hisp.dhis.dxf2.events.event;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.category.CategoryService;
import org.hisp.dhis.common.CodeGenerator;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.GridHeader;
import org.hisp.dhis.common.IdScheme;
import org.hisp.dhis.common.IdSchemes;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.OrganisationUnitSelectionMode;
import org.hisp.dhis.common.Pager;
import org.hisp.dhis.common.QueryFilter;
import org.hisp.dhis.common.QueryItem;
import org.hisp.dhis.common.QueryOperator;
import org.hisp.dhis.commons.collection.CachingMap;
import org.hisp.dhis.commons.util.DebugUtils;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.dbms.DbmsManager;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.events.RelationshipParams;
import org.hisp.dhis.dxf2.events.TrackerAccessManager;
import org.hisp.dhis.dxf2.events.enrollment.EnrollmentStatus;
import org.hisp.dhis.dxf2.events.relationship.RelationshipService;
import org.hisp.dhis.dxf2.events.report.EventRow;
import org.hisp.dhis.dxf2.events.report.EventRows;
import org.hisp.dhis.dxf2.importsummary.ImportConflict;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummaries;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.fileresource.FileResourceService;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.organisationunit.FeatureType;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramInstanceService;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageDataElement;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.program.ProgramStageInstanceService;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.program.ProgramStatus;
import org.hisp.dhis.program.ProgramType;
import org.hisp.dhis.program.ValidationStrategy;
import org.hisp.dhis.program.notification.ProgramNotificationEventType;
import org.hisp.dhis.program.notification.ProgramNotificationPublisher;
import org.hisp.dhis.programrule.engine.DataValueUpdatedEvent;
import org.hisp.dhis.programrule.engine.ProgramStageInstanceCompletedEvent;
import org.hisp.dhis.programrule.engine.ProgramStageInstanceScheduledEvent;
import org.hisp.dhis.query.Order;
import org.hisp.dhis.query.Query;
import org.hisp.dhis.query.QueryService;
import org.hisp.dhis.query.Restrictions;
import org.hisp.dhis.scheduling.JobConfiguration;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.security.Authorities;
import org.hisp.dhis.security.acl.AclService;
import org.hisp.dhis.system.grid.ListGrid;
import org.hisp.dhis.system.notification.NotificationLevel;
import org.hisp.dhis.system.notification.Notifier;
import org.hisp.dhis.system.util.DateUtils;
import org.hisp.dhis.system.util.GeoUtils;
import org.hisp.dhis.system.util.ValidationUtils;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.trackedentity.TrackerOwnershipAccessManager;
import org.hisp.dhis.trackedentitycomment.TrackedEntityComment;
import org.hisp.dhis.trackedentitycomment.TrackedEntityCommentService;
import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue;
import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValueService;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserCredentials;
import org.hisp.dhis.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hisp.dhis.dxf2.events.event.EventSearchParams.*;
import static org.hisp.dhis.system.notification.NotificationLevel.ERROR;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@Transactional
public abstract class AbstractEventService
implements EventService
{
private static final Log log = LogFactory.getLog( AbstractEventService.class );
public static final List<String> STATIC_EVENT_COLUMNS = Arrays.asList( EVENT_ID, EVENT_ENROLLMENT_ID, EVENT_CREATED_ID,
EVENT_LAST_UPDATED_ID, EVENT_STORED_BY_ID, EVENT_COMPLETED_BY_ID, EVENT_COMPLETED_DATE_ID,
EVENT_EXECUTION_DATE_ID, EVENT_DUE_DATE_ID, EVENT_ORG_UNIT_ID, EVENT_ORG_UNIT_NAME, EVENT_STATUS_ID,
EVENT_PROGRAM_STAGE_ID, EVENT_PROGRAM_ID,
EVENT_ATTRIBUTE_OPTION_COMBO_ID, EVENT_DELETED, EVENT_GEOMETRY );
// Dependencies
@Autowired
protected ProgramService programService;
@Autowired
protected ProgramStageService programStageService;
@Autowired
protected ProgramInstanceService programInstanceService;
@Autowired
protected ProgramStageInstanceService programStageInstanceService;
@Autowired
protected OrganisationUnitService organisationUnitService;
@Autowired
protected DataElementService dataElementService;
@Autowired
protected CurrentUserService currentUserService;
@Autowired
protected TrackedEntityDataValueService dataValueService;
@Autowired
protected TrackedEntityInstanceService entityInstanceService;
@Autowired
protected TrackedEntityCommentService commentService;
@Autowired
protected EventStore eventStore;
@Autowired
protected I18nManager i18nManager;
@Autowired
protected Notifier notifier;
@Autowired
protected SessionFactory sessionFactory;
@Autowired
protected DbmsManager dbmsManager;
@Autowired
protected IdentifiableObjectManager manager;
@Autowired
protected CategoryService categoryService;
@Autowired
protected FileResourceService fileResourceService;
@Autowired
protected SchemaService schemaService;
@Autowired
protected QueryService queryService;
@Autowired
protected TrackerAccessManager trackerAccessManager;
@Autowired
protected TrackerOwnershipAccessManager trackerOwnershipAccessManager;
@Autowired
protected AclService aclService;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
protected ProgramNotificationPublisher programNotificationPublisher;
@Autowired
protected RelationshipService relationshipService;
@Autowired
protected UserService userService;
protected static final int FLUSH_FREQUENCY = 100;
// Caches
private CachingMap<String, OrganisationUnit> organisationUnitCache = new CachingMap<>();
private CachingMap<String, Program> programCache = new CachingMap<>();
private CachingMap<String, ProgramStage> programStageCache = new CachingMap<>();
private CachingMap<String, DataElement> dataElementCache = new CachingMap<>();
private CachingMap<String, CategoryOption> categoryOptionCache = new CachingMap<>();
private CachingMap<String, CategoryOptionCombo> categoryOptionComboCache = new CachingMap<>();
private CachingMap<String, CategoryOptionCombo> attributeOptionComboCache = new CachingMap<>();
private CachingMap<String, List<ProgramInstance>> activeProgramInstanceCache = new CachingMap<>();
private CachingMap<Class<? extends IdentifiableObject>, IdentifiableObject> defaultObjectsCache = new CachingMap<>();
// CREATE
@Override
public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions, boolean clearSession )
{
ImportSummaries importSummaries = new ImportSummaries();
importOptions = updateImportOptions( importOptions );
List<List<Event>> partitions = Lists.partition( events, FLUSH_FREQUENCY );
for ( List<Event> _events : partitions )
{
reloadUser( importOptions );
prepareCaches( importOptions.getUser(), _events );
for ( Event event : _events )
{
importSummaries.addImportSummary( addEvent( event, importOptions ) );
}
if ( clearSession && events.size() >= FLUSH_FREQUENCY )
{
clearSession();
}
}
return importSummaries;
}
@Override
public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions, JobConfiguration jobId )
{
notifier.clear( jobId ).notify( jobId, "Importing events" );
importOptions = updateImportOptions( importOptions );
try
{
ImportSummaries importSummaries = addEvents( events, importOptions, true );
if ( jobId != null )
{
notifier.notify( jobId, NotificationLevel.INFO, "Import done", true ).addJobSummary( jobId, importSummaries, ImportSummaries.class );
}
return importSummaries;
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.notify( jobId, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummaries().addImportSummary( new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() ) );
}
}
@Override
public ImportSummary addEvent( Event event, ImportOptions importOptions )
{
importOptions = updateImportOptions( importOptions );
if ( programStageInstanceService.programStageInstanceExistsIncludingDeleted( event.getEvent() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Event ID " + event.getEvent() + " was already used. The ID is unique and cannot be used more than once" )
.setReference( event.getEvent() ).incrementIgnored();
}
Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() );
ProgramStage programStage = getProgramStage( importOptions.getIdSchemes().getProgramStageIdScheme(), event.getProgramStage() );
ProgramInstance programInstance;
ProgramStageInstance programStageInstance = null;
if ( program == null )
{
return new ImportSummary( ImportStatus.ERROR, "Event.program does not point to a valid program: " + event.getProgram() )
.setReference( event.getEvent() ).incrementIgnored();
}
if ( programStage == null && program.isRegistration() )
{
return new ImportSummary( ImportStatus.ERROR, "Event.programStage does not point to a valid programStage, and program is multi-stage: " + event.getProgramStage() )
.setReference( event.getEvent() ).incrementIgnored();
}
else if ( programStage == null )
{
programStage = program.getProgramStageByStage( 1 );
}
Assert.notNull( programStage, "Program stage cannot be null" );
if ( program.isRegistration() )
{
if ( event.getTrackedEntityInstance() == null )
{
return new ImportSummary( ImportStatus.ERROR, "No Event.trackedEntityInstance was provided for registration based program" )
.setReference( event.getEvent() ).incrementIgnored();
}
org.hisp.dhis.trackedentity.TrackedEntityInstance entityInstance = entityInstanceService
.getTrackedEntityInstance( event.getTrackedEntityInstance() );
if ( entityInstance == null )
{
return new ImportSummary( ImportStatus.ERROR, "Event.trackedEntityInstance does not point to a valid tracked entity instance: "
+ event.getTrackedEntityInstance() ).setReference( event.getEvent() ).incrementIgnored();
}
List<ProgramInstance> programInstances = new ArrayList<>(
programInstanceService.getProgramInstances( entityInstance, program, ProgramStatus.ACTIVE ) );
if ( programInstances.isEmpty() )
{
return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid()
+ " is not enrolled in program: " + program.getUid() ).setReference( event.getEvent() )
.incrementIgnored();
}
else if ( programInstances.size() > 1 )
{
return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid()
+ " has multiple active enrollments in program: " + program.getUid() ).setReference( event.getEvent() ).incrementIgnored();
}
programInstance = programInstances.get( 0 );
if ( !programStage.getRepeatable() )
{
programStageInstance = programStageInstanceService.getProgramStageInstance( programInstance,
programStage );
if ( programStageInstance != null && !programStageInstance.getUid().equals( event.getEvent() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Program stage is not repeatable and an event already exists" )
.setReference( event.getEvent() ).incrementIgnored();
}
}
else
{
if ( !StringUtils.isEmpty( event.getEvent() ) )
{
programStageInstance = manager.getObject( ProgramStageInstance.class,
importOptions.getIdSchemes().getProgramStageInstanceIdScheme(), event.getEvent() );
if ( programStageInstance == null )
{
if ( !CodeGenerator.isValidUid( event.getEvent() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() )
.setReference( event.getEvent() ).incrementIgnored();
}
}
}
}
}
else
{
String cacheKey = program.getUid() + "-" + ProgramStatus.ACTIVE;
List<ProgramInstance> programInstances = getActiveProgramInstances( cacheKey, program );
if ( programInstances.isEmpty() )
{
// Create PI if it doesn't exist (should only be one)
String storedBy = event.getStoredBy() != null && event.getStoredBy().length() < 31 ? event.getStoredBy()
: importOptions.getUser().getUsername();
ProgramInstance pi = new ProgramInstance();
pi.setEnrollmentDate( new Date() );
pi.setIncidentDate( new Date() );
pi.setProgram( program );
pi.setStatus( ProgramStatus.ACTIVE );
pi.setStoredBy( storedBy );
programInstanceService.addProgramInstance( pi );
programInstances.add( pi );
}
else if ( programInstances.size() > 1 )
{
return new ImportSummary( ImportStatus.ERROR, "Multiple active program instances exists for program: " + program.getUid() )
.setReference( event.getEvent() ).incrementIgnored();
}
programInstance = programInstances.get( 0 );
if ( !StringUtils.isEmpty( event.getEvent() ) )
{
programStageInstance = manager.getObject( ProgramStageInstance.class,
importOptions.getIdSchemes().getProgramStageInstanceIdScheme(), event.getEvent() );
if ( programStageInstance == null )
{
if ( importOptions.getIdSchemes().getProgramStageInstanceIdScheme().equals( IdScheme.UID )
&& !CodeGenerator.isValidUid( event.getEvent() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() )
.setReference( event.getEvent() ).incrementIgnored();
}
}
}
}
OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() );
program = programInstance.getProgram();
if ( programStageInstance != null )
{
programStage = programStageInstance.getProgramStage();
}
if ( organisationUnit == null )
{
return new ImportSummary( ImportStatus.ERROR, "Event.orgUnit does not point to a valid organisation unit: " + event.getOrgUnit() )
.setReference( event.getEvent() ).incrementIgnored();
}
if ( !programInstance.getProgram().hasOrganisationUnit( organisationUnit ) )
{
return new ImportSummary( ImportStatus.ERROR, "Program is not assigned to this organisation unit: " + event.getOrgUnit() )
.setReference( event.getEvent() ).incrementIgnored();
}
if ( importOptions.getUser() == null || !importOptions.getUser().isAuthorized( Authorities.F_EDIT_EXPIRED.getAuthority() ) )
{
validateExpiryDays( event, program, null );
}
if ( event.getGeometry() != null )
{
if ( programStage.getFeatureType().equals( FeatureType.NONE ) || !programStage.getFeatureType().value().equals( event.getGeometry().getGeometryType() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Geometry (" + event.getGeometry().getGeometryType() + ") does not conform to the feature type (" + programStage.getFeatureType().value() + ") specified for the program stage: " + programStage.getUid() );
}
}
else if ( event.getCoordinate() != null && event.getCoordinate().hasLatitudeLongitude() )
{
Coordinate coordinate = event.getCoordinate();
try
{
event.setGeometry( GeoUtils.getGeoJsonPoint( coordinate.getLongitude(), coordinate.getLatitude() ) );
}
catch ( IOException e )
{
return new ImportSummary( ImportStatus.ERROR, "Invalid longitude or latitude for property 'coordinates'." );
}
}
List<String> errors = trackerAccessManager.canWrite( importOptions.getUser(),
new ProgramStageInstance( programInstance, programStage ).setOrganisationUnit( organisationUnit ).setStatus( event.getStatus() ) );
if ( !errors.isEmpty() )
{
ImportSummary importSummary = new ImportSummary( ImportStatus.ERROR, errors.toString() );
importSummary.incrementIgnored();
return importSummary;
}
return saveEvent( program, programInstance, programStage, programStageInstance, organisationUnit, event, importOptions );
}
// READ
@Override
public Events getEvents( EventSearchParams params )
{
validate( params );
List<OrganisationUnit> organisationUnits = getOrganisationUnits( params );
if ( !params.isPaging() && !params.isSkipPaging() )
{
params.setDefaultPaging();
}
Events events = new Events();
if ( params.isPaging() )
{
int count = 0;
if ( params.isTotalPages() )
{
count = eventStore.getEventCount( params, organisationUnits );
}
Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() );
events.setPager( pager );
}
List<Event> eventList = eventStore.getEvents( params, organisationUnits );
User user = currentUserService.getCurrentUser();
for ( Event event : eventList )
{
if ( trackerOwnershipAccessManager.hasAccess( user, event.getTrackedEntityInstance(), event.getProgram() ) )
{
events.getEvents().add( event );
}
}
return events;
}
@Override
public Grid getEventsGrid( EventSearchParams params )
{
User user = currentUserService.getCurrentUser();
if ( params.getProgramStage() == null || params.getProgramStage().getProgram() == null )
{
throw new IllegalQueryException( "Program stage can not be null" );
}
if ( params.getProgramStage().getProgramStageDataElements() == null )
{
throw new IllegalQueryException( "Program stage should have at least one data element" );
}
List<OrganisationUnit> organisationUnits = getOrganisationUnits( params );
// If includeAllDataElements is set to true, return all data elements.
// If no data element is specified, use those configured for display
// in report
if ( params.isIncludeAllDataElements() )
{
for ( ProgramStageDataElement pde : params.getProgramStage().getProgramStageDataElements() )
{
QueryItem qi = new QueryItem( pde.getDataElement(), pde.getDataElement().getLegendSet(),
pde.getDataElement().getValueType(), pde.getDataElement().getAggregationType(),
pde.getDataElement().hasOptionSet() ? pde.getDataElement().getOptionSet() : null );
params.getDataElements().add( qi );
}
}
else
{
if ( params.getDataElements().isEmpty() )
{
for ( ProgramStageDataElement pde : params.getProgramStage().getProgramStageDataElements() )
{
if ( pde.getDisplayInReports() )
{
QueryItem qi = new QueryItem( pde.getDataElement(), pde.getDataElement().getLegendSet(),
pde.getDataElement().getValueType(), pde.getDataElement().getAggregationType(),
pde.getDataElement().hasOptionSet() ? pde.getDataElement().getOptionSet() : null );
params.getDataElements().add( qi );
}
}
}
}
// Grid headers
Grid grid = new ListGrid();
for ( String col : STATIC_EVENT_COLUMNS )
{
grid.addHeader( new GridHeader( col, col ) );
}
for ( QueryItem item : params.getDataElements() )
{
grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName() ) );
}
List<Map<String, String>> events = eventStore.getEventsGrid( params, organisationUnits );
// Grid rows
for ( Map<String, String> event : events )
{
grid.addRow();
if ( params.getProgramStage().getProgram().isRegistration() && user != null || !user.isSuper() )
{
ProgramInstance enrollment = programInstanceService.getProgramInstance( event.get( EVENT_ENROLLMENT_ID ) );
if ( enrollment != null && enrollment.getEntityInstance() != null )
{
if ( !trackerOwnershipAccessManager.hasAccess( user, enrollment.getEntityInstance(), params.getProgramStage().getProgram() ) )
{
continue;
}
}
}
for ( String col : STATIC_EVENT_COLUMNS )
{
grid.addValue( event.get( col ) );
}
for ( QueryItem item : params.getDataElements() )
{
grid.addValue( event.get( item.getItemId() ) );
}
}
Map<String, Object> metaData = new HashMap<>();
if ( params.isPaging() )
{
int count = 0;
if ( params.isTotalPages() )
{
count = eventStore.getEventCount( params, organisationUnits );
}
Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() );
metaData.put( PAGER_META_KEY, pager );
}
grid.setMetaData( metaData );
return grid;
}
@Override
public int getAnonymousEventValuesCountLastUpdatedAfter( Date lastSuccessTime )
{
EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime );
return eventStore.getEventCount( params, null );
}
@Override
public int getAnonymousEventReadyForSynchronizationCount()
{
EventSearchParams params = new EventSearchParams();
params.setProgramType( ProgramType.WITHOUT_REGISTRATION );
params.setIncludeDeleted( true );
params.setSynchronizationQuery( true );
return eventStore.getEventCount( params, null );
}
//TODO: In next step, remove executeEventPush() from DefaultSynchronizationManager and therefore, remove also method below as it won't be used anymore
//TODO: Do changes from the comment above
@Override
public Events getAnonymousEventValuesLastUpdatedAfter( Date lastSuccessTime )
{
EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime );
Events anonymousEvents = new Events();
List<Event> events = eventStore.getEvents( params, null );
anonymousEvents.setEvents( events );
return anonymousEvents;
}
@Override
public Events getAnonymousEventsForSync( int pageSize )
{
//A page is not specified here. The reason is, that after a page is synchronized, the items that were in that page
// get lastSynchronized column updated. Therefore, they are not present in the results in the next query anymore.
// If I used paging, I would come to SQLGrammarException because I would try to fetch entries (with specific offset)
// that don't exist anymore.
EventSearchParams params = new EventSearchParams();
params.setProgramType( ProgramType.WITHOUT_REGISTRATION );
params.setIncludeDeleted( true );
params.setSynchronizationQuery( true );
params.setPageSize( pageSize );
Events anonymousEvents = new Events();
List<Event> events = eventStore.getEvents( params, null );
anonymousEvents.setEvents( events );
return anonymousEvents;
}
private EventSearchParams buildAnonymousEventsSearchParams( Date lastSuccessTime )
{
EventSearchParams params = new EventSearchParams();
params.setProgramType( ProgramType.WITHOUT_REGISTRATION );
params.setLastUpdatedStartDate( lastSuccessTime );
params.setIncludeDeleted( true );
return params;
}
@Override
public EventRows getEventRows( EventSearchParams params )
{
List<OrganisationUnit> organisationUnits = getOrganisationUnits( params );
User user = currentUserService.getCurrentUser();
EventRows eventRows = new EventRows();
List<EventRow> eventRowList = eventStore.getEventRows( params, organisationUnits );
for ( EventRow eventRow : eventRowList )
{
if ( trackerOwnershipAccessManager.hasAccess( user, eventRow.getTrackedEntityInstance(), eventRow.getProgram() ) )
{
eventRows.getEventRows().add( eventRow );
}
}
return eventRows;
}
@Override
public Event getEvent( ProgramStageInstance programStageInstance )
{
return getEvent( programStageInstance, false );
}
@Override
public Event getEvent( ProgramStageInstance programStageInstance, boolean isSynchronizationQuery )
{
if ( programStageInstance == null )
{
return null;
}
Event event = new Event();
event.setEvent( programStageInstance.getUid() );
if ( programStageInstance.getProgramInstance().getEntityInstance() != null )
{
event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() );
}
event.setFollowup( programStageInstance.getProgramInstance().getFollowup() );
event.setEnrollmentStatus( EnrollmentStatus.fromProgramStatus( programStageInstance.getProgramInstance().getStatus() ) );
event.setStatus( programStageInstance.getStatus() );
event.setEventDate( DateUtils.getIso8601NoTz( programStageInstance.getExecutionDate() ) );
event.setDueDate( DateUtils.getIso8601NoTz( programStageInstance.getDueDate() ) );
event.setStoredBy( programStageInstance.getStoredBy() );
event.setCompletedBy( programStageInstance.getCompletedBy() );
event.setCompletedDate( DateUtils.getIso8601NoTz( programStageInstance.getCompletedDate() ) );
event.setCreated( DateUtils.getIso8601NoTz( programStageInstance.getCreated() ) );
event.setCreatedAtClient( DateUtils.getIso8601NoTz( programStageInstance.getCreatedAtClient() ) );
event.setLastUpdated( DateUtils.getIso8601NoTz( programStageInstance.getLastUpdated() ) );
event.setLastUpdatedAtClient( DateUtils.getIso8601NoTz( programStageInstance.getLastUpdatedAtClient() ) );
event.setGeometry( programStageInstance.getGeometry() );
event.setDeleted( programStageInstance.isDeleted() );
// Lat and lnt deprecated in 2.30, remove by 2.33
if ( event.getGeometry() != null && event.getGeometry().getGeometryType().equals( "Point" ) )
{
com.vividsolutions.jts.geom.Coordinate geometryCoordinate = event.getGeometry().getCoordinate();
event.setCoordinate( new Coordinate( geometryCoordinate.x, geometryCoordinate.y ) );
}
User user = currentUserService.getCurrentUser();
OrganisationUnit ou = programStageInstance.getOrganisationUnit();
List<String> errors = trackerAccessManager.canRead( user, programStageInstance );
if ( !errors.isEmpty() )
{
throw new IllegalQueryException( errors.toString() );
}
if ( ou != null )
{
event.setOrgUnit( ou.getUid() );
event.setOrgUnitName( ou.getName() );
}
Program program = programStageInstance.getProgramInstance().getProgram();
event.setProgram( program.getUid() );
event.setEnrollment( programStageInstance.getProgramInstance().getUid() );
event.setProgramStage( programStageInstance.getProgramStage().getUid() );
event.setAttributeOptionCombo( programStageInstance.getAttributeOptionCombo().getUid() );
event.setAttributeCategoryOptions( String.join( ";", programStageInstance.getAttributeOptionCombo()
.getCategoryOptions().stream().map( CategoryOption::getUid ).collect( Collectors.toList() ) ) );
if ( programStageInstance.getProgramInstance().getEntityInstance() != null )
{
event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() );
}
Collection<TrackedEntityDataValue> dataValues;
if ( !isSynchronizationQuery )
{
dataValues = dataValueService.getTrackedEntityDataValues( programStageInstance );
}
else
{
dataValues = dataValueService.getTrackedEntityDataValuesForSynchronization( programStageInstance );
}
for ( TrackedEntityDataValue dataValue : dataValues )
{
errors = trackerAccessManager.canRead( user, dataValue );
if ( !errors.isEmpty() )
{
continue;
}
DataValue value = new DataValue();
value.setCreated( DateUtils.getIso8601NoTz( dataValue.getCreated() ) );
value.setLastUpdated( DateUtils.getIso8601NoTz( dataValue.getLastUpdated() ) );
value.setDataElement( dataValue.getDataElement().getUid() );
value.setValue( dataValue.getValue() );
value.setProvidedElsewhere( dataValue.getProvidedElsewhere() );
value.setStoredBy( dataValue.getStoredBy() );
event.getDataValues().add( value );
}
List<TrackedEntityComment> comments = programStageInstance.getComments();
for ( TrackedEntityComment comment : comments )
{
Note note = new Note();
note.setNote( comment.getUid() );
note.setValue( comment.getCommentText() );
note.setStoredBy( comment.getCreator() );
note.setStoredDate( DateUtils.getIso8601NoTz( comment.getCreated() ) );
event.getNotes().add( note );
}
event.setRelationships( programStageInstance.getRelationshipItems().stream()
.map( ( r ) -> relationshipService.getRelationship( r.getRelationship(), RelationshipParams.FALSE, user ) )
.collect( Collectors.toSet() )
);
return event;
}
@Override
public EventSearchParams getFromUrl( String program, String programStage, ProgramStatus programStatus,
Boolean followUp, String orgUnit, OrganisationUnitSelectionMode orgUnitSelectionMode,
String trackedEntityInstance, Date startDate, Date endDate, Date dueDateStart, Date dueDateEnd,
Date lastUpdatedStartDate, Date lastUpdatedEndDate, EventStatus status,
CategoryOptionCombo attributeOptionCombo, IdSchemes idSchemes, Integer page, Integer pageSize,
boolean totalPages, boolean skipPaging, List<Order> orders, List<String> gridOrders, boolean includeAttributes,
Set<String> events, Set<String> filters, Set<String> dataElements, boolean includeAllDataElements, boolean includeDeleted )
{
User user = currentUserService.getCurrentUser();
UserCredentials userCredentials = user.getUserCredentials();
EventSearchParams params = new EventSearchParams();
Program pr = programService.getProgram( program );
if ( !StringUtils.isEmpty( program ) && pr == null )
{
throw new IllegalQueryException( "Program is specified but does not exist: " + program );
}
ProgramStage ps = programStageService.getProgramStage( programStage );
if ( !StringUtils.isEmpty( programStage ) && ps == null )
{
throw new IllegalQueryException( "Program stage is specified but does not exist: " + programStage );
}
OrganisationUnit ou = organisationUnitService.getOrganisationUnit( orgUnit );
if ( !StringUtils.isEmpty( orgUnit ) && ou == null )
{
throw new IllegalQueryException( "Org unit is specified but does not exist: " + orgUnit );
}
if ( ou != null && !organisationUnitService.isInUserHierarchy( ou ) )
{
if ( !userCredentials.isSuper()
&& !userCredentials.isAuthorized( "F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS" ) )
{
throw new IllegalQueryException( "User has no access to organisation unit: " + ou.getUid() );
}
}
if ( pr != null && !userCredentials.isSuper() && !aclService.canDataRead( user, pr ) )
{
throw new IllegalQueryException( "User has no access to program: " + pr.getUid() );
}
if ( ps != null && !userCredentials.isSuper() && !aclService.canDataRead( user, ps ) )
{
throw new IllegalQueryException( "User has no access to program stage: " + ps.getUid() );
}
TrackedEntityInstance tei = entityInstanceService.getTrackedEntityInstance( trackedEntityInstance );
if ( !StringUtils.isEmpty( trackedEntityInstance ) && tei == null )
{
throw new IllegalQueryException( "Tracked entity instance is specified but does not exist: " + trackedEntityInstance );
}
if ( attributeOptionCombo != null && !userCredentials.isSuper() && !aclService.canDataRead( user, attributeOptionCombo ) )
{
throw new IllegalQueryException( "User has no access to attribute category option combo: " + attributeOptionCombo.getUid() );
}
if ( events != null && filters != null )
{
throw new IllegalQueryException( "Event UIDs and filters can not be specified at the same time" );
}
if ( events == null )
{
events = new HashSet<>();
}
if ( filters != null )
{
if ( !StringUtils.isEmpty( programStage ) && ps == null )
{
throw new IllegalQueryException( "ProgramStage needs to be specified for event filtering to work" );
}
for ( String filter : filters )
{
QueryItem item = getQueryItem( filter );
params.getFilters().add( item );
}
}
if ( dataElements != null )
{
for ( String de : dataElements )
{
QueryItem dataElement = getQueryItem( de );
params.getDataElements().add( dataElement );
}
}
params.setProgram( pr );
params.setProgramStage( ps );
params.setOrgUnit( ou );
params.setTrackedEntityInstance( tei );
params.setProgramStatus( programStatus );
params.setFollowUp( followUp );
params.setOrgUnitSelectionMode( orgUnitSelectionMode );
params.setStartDate( startDate );
params.setEndDate( endDate );
params.setDueDateStart( dueDateStart );
params.setDueDateEnd( dueDateEnd );
params.setLastUpdatedStartDate( lastUpdatedStartDate );
params.setLastUpdatedEndDate( lastUpdatedEndDate );
params.setEventStatus( status );
params.setCategoryOptionCombo( attributeOptionCombo );
params.setIdSchemes( idSchemes );
params.setPage( page );
params.setPageSize( pageSize );
params.setTotalPages( totalPages );
params.setSkipPaging( skipPaging );
params.setIncludeAttributes( includeAttributes );
params.setIncludeAllDataElements( includeAllDataElements );
params.setOrders( orders );
params.setGridOrders( gridOrders );
params.setEvents( events );
params.setIncludeDeleted( includeDeleted );
return params;
}
// UPDATE
@Override
public ImportSummaries updateEvents( List<Event> events, ImportOptions importOptions, boolean singleValue, boolean clearSession )
{
ImportSummaries importSummaries = new ImportSummaries();
importOptions = updateImportOptions( importOptions );
List<List<Event>> partitions = Lists.partition( events, FLUSH_FREQUENCY );
for ( List<Event> _events : partitions )
{
reloadUser( importOptions );
prepareCaches( importOptions.getUser(), _events );
for ( Event event : _events )
{
importSummaries.addImportSummary( updateEvent( event, singleValue, importOptions ) );
}
if ( clearSession && events.size() >= FLUSH_FREQUENCY )
{
clearSession();
}
}
return importSummaries;
}
@Override
public ImportSummary updateEvent( Event event, boolean singleValue )
{
return updateEvent( event, singleValue, null );
}
@Override
public ImportSummary updateEvent( Event event, boolean singleValue, ImportOptions importOptions )
{
importOptions = updateImportOptions( importOptions );
if ( event == null || StringUtils.isEmpty( event.getEvent() ) )
{
return new ImportSummary( ImportStatus.ERROR, "No event or event ID was supplied" ).incrementIgnored();
}
ImportSummary importSummary = new ImportSummary( event.getEvent() );
ProgramStageInstance programStageInstance = programStageInstanceService
.getProgramStageInstance( event.getEvent() );
List<String> errors = trackerAccessManager.canWrite( importOptions.getUser(), programStageInstance );
if ( programStageInstance == null )
{
importSummary.setStatus( ImportStatus.ERROR );
importSummary.setDescription( "ID " + event.getEvent() + " doesn't point to valid event" );
importSummary.getConflicts().add( new ImportConflict( "Invalid Event ID", event.getEvent() ) );
return importSummary.incrementIgnored();
}
if ( !errors.isEmpty() )
{
return new ImportSummary( ImportStatus.ERROR, errors.toString() ).incrementIgnored();
}
OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() );
if ( organisationUnit == null )
{
organisationUnit = programStageInstance.getOrganisationUnit();
}
Date executionDate = new Date();
if ( event.getEventDate() != null )
{
executionDate = DateUtils.parseDate( event.getEventDate() );
programStageInstance.setExecutionDate( executionDate );
}
Date dueDate = new Date();
if ( event.getDueDate() != null )
{
dueDate = DateUtils.parseDate( event.getDueDate() );
}
String storedBy = getStoredBy( event, null, importOptions.getUser() != null ? importOptions.getUser().getUsername() : "[Unknown]" );
programStageInstance.setStoredBy( storedBy );
String completedBy = getCompletedBy( event, null, importOptions.getUser() != null ? importOptions.getUser().getUsername() : "[Unknown]" );
if ( event.getStatus() != programStageInstance.getStatus()
&& programStageInstance.getStatus() == EventStatus.COMPLETED )
{
UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials();
if ( !userCredentials.isSuper() && !userCredentials.isAuthorized( "F_UNCOMPLETE_EVENT" ) )
{
importSummary.setStatus( ImportStatus.ERROR );
importSummary.setDescription( "User is not authorized to uncomplete events" );
return importSummary;
}
}
if ( event.getStatus() == EventStatus.ACTIVE )
{
programStageInstance.setStatus( EventStatus.ACTIVE );
programStageInstance.setCompletedBy( null );
programStageInstance.setCompletedDate( null );
}
else if ( programStageInstance.getStatus() != event.getStatus() && event.getStatus() == EventStatus.COMPLETED )
{
programStageInstance.setCompletedBy( completedBy );
Date completedDate = null;
if ( event.getCompletedDate() != null )
{
completedDate = DateUtils.parseDate( event.getCompletedDate() );
}
programStageInstanceService.completeProgramStageInstance( programStageInstance,
importOptions.isSkipNotifications(), i18nManager.getI18nFormat(), completedDate );
if ( !importOptions.isSkipNotifications() )
{
eventPublisher.publishEvent( new ProgramStageInstanceCompletedEvent( this, programStageInstance ) );
}
}
else if ( event.getStatus() == EventStatus.SKIPPED )
{
programStageInstance.setStatus( EventStatus.SKIPPED );
}
else if ( event.getStatus() == EventStatus.SCHEDULE )
{
programStageInstance.setStatus( EventStatus.SCHEDULE );
}
programStageInstance.setDueDate( dueDate );
programStageInstance.setOrganisationUnit( organisationUnit );
programStageInstance.setGeometry( event.getGeometry() );
Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() );
if ( program == null )
{
return new ImportSummary( ImportStatus.ERROR, "Program '" + event.getProgram() + "' for event '" + event.getEvent() + "' was not found." );
}
if ( importOptions.getUser() == null || !importOptions.getUser().isAuthorized( Authorities.F_EDIT_EXPIRED.getAuthority() ) )
{
validateExpiryDays( event, program, programStageInstance );
}
CategoryOptionCombo aoc = null;
if ( (event.getAttributeCategoryOptions() != null && program.getCategoryCombo() != null)
|| event.getAttributeOptionCombo() != null )
{
IdScheme idScheme = importOptions.getIdSchemes().getCategoryOptionIdScheme();
try
{
aoc = getAttributeOptionCombo( program.getCategoryCombo(),
event.getAttributeCategoryOptions(), event.getAttributeOptionCombo(), idScheme );
}
catch ( IllegalQueryException ex )
{
importSummary.setStatus( ImportStatus.ERROR );
importSummary.getConflicts().add( new ImportConflict( ex.getMessage(), event.getAttributeCategoryOptions() ) );
return importSummary.incrementIgnored();
}
}
if ( aoc != null && aoc.isDefault() && program.getCategoryCombo() != null && !program.getCategoryCombo().isDefault() )
{
importSummary.setStatus( ImportStatus.ERROR );
importSummary.getConflicts().add( new ImportConflict( "attributeOptionCombo", "Default attribute option combo is not allowed since program has non-default category combo" ) );
return importSummary.incrementIgnored();
}
if ( aoc != null )
{
programStageInstance.setAttributeOptionCombo( aoc );
}
if ( event.getGeometry() != null )
{
if ( programStageInstance.getProgramStage().getFeatureType().equals( FeatureType.NONE ) ||
!programStageInstance.getProgramStage().getFeatureType().value().equals( event.getGeometry().getGeometryType() ) )
{
return new ImportSummary( ImportStatus.ERROR, "Geometry (" + event.getGeometry().getGeometryType() +
") does not conform to the feature type (" + programStageInstance.getProgramStage().getFeatureType().value() +
") specified for the program stage: " + programStageInstance.getProgramStage().getUid() );
}
}
else if ( event.getCoordinate() != null && event.getCoordinate().hasLatitudeLongitude() )
{
Coordinate coordinate = event.getCoordinate();
try
{
event
.setGeometry( GeoUtils.getGeoJsonPoint( coordinate.getLongitude(), coordinate.getLatitude() ) );
}
catch ( IOException e )
{
return new ImportSummary( ImportStatus.ERROR,
"Invalid longitude or latitude for property 'coordinates'." );
}
}
programStageInstanceService.updateProgramStageInstance( programStageInstance );
saveTrackedEntityComment( programStageInstance, event, storedBy );
updateTrackedEntityInstance( programStageInstance, importOptions.getUser() );
Set<TrackedEntityDataValue> dataValues = new HashSet<>(
dataValueService.getTrackedEntityDataValues( programStageInstance ) );
Map<String, TrackedEntityDataValue> dataElementToValueMap = getDataElementDataValueMap( dataValues );
Map<String, DataElement> newDataElements = new HashMap<>();
ImportSummary validationResult = validateDataValues( event, programStageInstance, dataElementToValueMap,
newDataElements, importSummary, importOptions, singleValue );
if ( validationResult.getStatus() == ImportStatus.ERROR )
{
return validationResult;
}
for ( DataValue dataValue : event.getDataValues() )
{
DataElement dataElement;
// The element was already saved so make an update
if ( dataElementToValueMap.containsKey( dataValue.getDataElement() ) )
{
TrackedEntityDataValue teiDataValue = dataElementToValueMap.get( dataValue.getDataElement() );
dataElement = teiDataValue.getDataElement();
if ( StringUtils.isEmpty( dataValue.getValue() ) && dataElement.isFileType()
&& !StringUtils.isEmpty( teiDataValue.getValue() ) )
{
fileResourceService.deleteFileResource( teiDataValue.getValue() );
}
teiDataValue.setValue( dataValue.getValue() );
teiDataValue.setProvidedElsewhere( dataValue.getProvidedElsewhere() );
dataValueService.updateTrackedEntityDataValue( teiDataValue );
// Marking that this data value was a part of an update so it should not be removed
dataValues.remove( teiDataValue );
}
// Value is not present so consider it a new and save
else
{
dataElement = newDataElements.get( dataValue.getDataElement() );
saveDataValue( programStageInstance, event.getStoredBy(), dataElement, dataValue.getValue(),
dataValue.getProvidedElsewhere(), null, null );
}
if ( !importOptions.isSkipNotifications() )
{
eventPublisher.publishEvent( new DataValueUpdatedEvent( this, programStageInstance ) );
}
}
if ( !singleValue )
{
dataValues.forEach( dataValueService::deleteTrackedEntityDataValue );
}
importSummary.incrementUpdated();
return importSummary;
}
@Override
public void updateEventForNote( Event event )
{
ProgramStageInstance programStageInstance = programStageInstanceService
.getProgramStageInstance( event.getEvent() );
if ( programStageInstance == null )
{
return;
}
User currentUser = currentUserService.getCurrentUser();
saveTrackedEntityComment( programStageInstance, event,
getStoredBy( event, null, currentUser != null ? currentUser.getUsername() : "[Unknown]" ) );
updateTrackedEntityInstance( programStageInstance, currentUser );
}
@Override
public void updateEventForEventDate( Event event )
{
ProgramStageInstance programStageInstance = programStageInstanceService
.getProgramStageInstance( event.getEvent() );
if ( programStageInstance == null )
{
return;
}
List<String> errors = trackerAccessManager.canWrite( currentUserService.getCurrentUser(), programStageInstance );
if ( !errors.isEmpty() )
{
return;
}
Date executionDate = new Date();
if ( event.getEventDate() != null )
{
executionDate = DateUtils.parseDate( event.getEventDate() );
}
if ( event.getStatus() == EventStatus.COMPLETED )
{
programStageInstance.setStatus( EventStatus.COMPLETED );
}
else
{
programStageInstance.setStatus( EventStatus.VISITED );
}
ImportOptions importOptions = new ImportOptions();
OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() );
if ( organisationUnit == null )
{
organisationUnit = programStageInstance.getOrganisationUnit();
}
programStageInstance.setOrganisationUnit( organisationUnit );
programStageInstance.setExecutionDate( executionDate );
programStageInstanceService.updateProgramStageInstance( programStageInstance );
}
@Override
public void updateEventsSyncTimestamp( List<String> eventsUIDs, Date lastSynchronized )
{
programStageInstanceService.updateProgramStageInstancesSyncTimestamp( eventsUIDs, lastSynchronized );
}
// DELETE
@Override
public ImportSummary deleteEvent( String uid )
{
boolean existsEvent = programStageInstanceService.programStageInstanceExists( uid );
if ( existsEvent )
{
ProgramStageInstance programStageInstance = programStageInstanceService.getProgramStageInstance( uid );
List<String> errors = trackerAccessManager.canWrite( currentUserService.getCurrentUser(), programStageInstance );
if ( !errors.isEmpty() )
{
return new ImportSummary( ImportStatus.ERROR, errors.toString() ).incrementIgnored();
}
programStageInstanceService.deleteProgramStageInstance( programStageInstance );
if ( programStageInstance.getProgramStage().getProgram().isRegistration() )
{
entityInstanceService.updateTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance() );
}
return new ImportSummary( ImportStatus.SUCCESS, "Deletion of event " + uid + " was successful" ).incrementDeleted();
}
else
{
return new ImportSummary( ImportStatus.SUCCESS, "Event " + uid + " cannot be deleted as it is not present in the system" ).incrementIgnored();
}
}
@Override
public ImportSummaries deleteEvents( List<String> uids, boolean clearSession )
{
ImportSummaries importSummaries = new ImportSummaries();
int counter = 0;
for ( String uid : uids )
{
importSummaries.addImportSummary( deleteEvent( uid ) );
if ( clearSession && counter % FLUSH_FREQUENCY == 0 )
{
clearSession();
}
counter++;
}
return importSummaries;
}
// HELPERS
private void prepareCaches( User user, List<Event> events )
{
// prepare caches
Collection<String> orgUnits = events.stream().map( Event::getOrgUnit ).collect( Collectors.toSet() );
if ( !orgUnits.isEmpty() )
{
Query query = Query.from( schemaService.getDynamicSchema( OrganisationUnit.class ) );
query.setUser( user );
query.add( Restrictions.in( "id", orgUnits ) );
queryService.query( query ).forEach( ou -> organisationUnitCache.put( ou.getUid(), (OrganisationUnit) ou ) );
}
Collection<String> dataElements = new HashSet<>();
events.forEach( e -> e.getDataValues().forEach( v -> dataElements.add( v.getDataElement() ) ) );
if ( !dataElements.isEmpty() )
{
Query query = Query.from( schemaService.getDynamicSchema( DataElement.class ) );
query.setUser( user );
query.add( Restrictions.in( "id", dataElements ) );
queryService.query( query ).forEach( de -> dataElementCache.put( de.getUid(), (DataElement) de ) );
}
}
private List<OrganisationUnit> getOrganisationUnits( EventSearchParams params )
{
List<OrganisationUnit> organisationUnits = new ArrayList<>();
OrganisationUnit orgUnit = params.getOrgUnit();
OrganisationUnitSelectionMode orgUnitSelectionMode = params.getOrgUnitSelectionMode();
if ( params.getOrgUnit() != null )
{
if ( OrganisationUnitSelectionMode.DESCENDANTS.equals( orgUnitSelectionMode ) )
{
organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( orgUnit.getUid() ) );
}
else if ( OrganisationUnitSelectionMode.CHILDREN.equals( orgUnitSelectionMode ) )
{
organisationUnits.add( orgUnit );
organisationUnits.addAll( orgUnit.getChildren() );
}
else // SELECTED
{
organisationUnits.add( orgUnit );
}
}
return organisationUnits;
}
private boolean doValidationOfMandatoryAttributes( User user )
{
return user == null || !user.isAuthorized( Authorities.F_IGNORE_TRACKER_REQUIRED_VALUE_VALIDATION.getAuthority() );
}
private Set<String> validatePresenceOfMandatoryDataElements(Event event, ProgramStageInstance programStageInstance, ImportSummary importSummary, boolean isSingleValueUpdate) {
ValidationStrategy validationStrategy = programStageInstance.getProgramStage().getValidationStrategy();
Set<String> mandatoryDataElements = new HashSet<>( );
if ( validationStrategy == ValidationStrategy.ON_UPDATE_AND_INSERT ||
(validationStrategy == ValidationStrategy.ON_COMPLETE && event.getStatus() == EventStatus.COMPLETED) )
{
//I am filling the set only if I know that I will do the validation. Otherwise, it would be waste of resources
mandatoryDataElements = programStageInstance.getProgramStage().getProgramStageDataElements().stream()
.filter( psde -> psde.isCompulsory() )
.map( psde -> psde.getDataElement().getUid() )
.collect( Collectors.toSet() );
Set<String> presentDataElements = event.getDataValues().stream()
.map( dv -> dv.getDataElement() )
.collect( Collectors.toSet());
// When the request is update, then only changed data values can be in the payload and so I should take into
// account also already stored data values in order to make correct decision. Basically, this situation happens when
// only 1 dataValue is updated and /events/{uid}/{dataElementUid} endpoint is leveraged.
if ( isSingleValueUpdate ) {
presentDataElements.addAll(
programStageInstance.getDataValues().stream()
.filter( dv -> !StringUtils.isEmpty( dv.getValue() ))
.map( dv -> dv.getDataElement().getUid() )
.collect( Collectors.toSet()));
}
Set<String> notPresentMandatoryDataElements = Sets.difference( mandatoryDataElements, presentDataElements );
if ( notPresentMandatoryDataElements.size() > 0 )
{
notPresentMandatoryDataElements.forEach( deUid -> importSummary.getConflicts().add( new ImportConflict( deUid, "value_required_but_not_provided" ) ) );
importSummary.incrementIgnored();
importSummary.setStatus( ImportStatus.ERROR );
}
}
return mandatoryDataElements;
}
private ImportSummary validateDataValues( Event event, ProgramStageInstance programStageInstance,
Map<String, TrackedEntityDataValue> dataElementToValueMap, Map<String, DataElement> newDataElements,
ImportSummary importSummary, ImportOptions importOptions, boolean isSingleValueUpdate )
{
boolean validateMandatoryAttributes = doValidationOfMandatoryAttributes( importOptions.getUser() );
Set<String> mandatoryDataElements = new HashSet<>( );
if (validateMandatoryAttributes)
{
mandatoryDataElements = validatePresenceOfMandatoryDataElements( event, programStageInstance, importSummary, isSingleValueUpdate );
if ( importSummary.getStatus() == ImportStatus.ERROR )
{
return importSummary;
}
}
// Loop through values, if only one validation problem occurs -> FAIL
for ( DataValue dataValue : event.getDataValues() )
{
DataElement dataElement;
if ( dataElementToValueMap.containsKey( dataValue.getDataElement() ) )
{
dataElement = dataElementToValueMap.get( dataValue.getDataElement() ).getDataElement();
}
else
{
dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(), dataValue.getDataElement() );
// This can happen if a wrong data element identifier is provided
if ( dataElement == null )
{
String descMsg = "Data element " + dataValue.getDataElement() + " doesn't exist in the system. Please, provide correct data element";
importSummary.setStatus( ImportStatus.ERROR );
importSummary.setDescription( descMsg );
return importSummary;
}
newDataElements.put( dataValue.getDataElement(), dataElement );
}
// Return error if one or more values fail validation
if ( !validateDataValue( programStageInstance, importOptions.getUser(), dataElement, dataValue.getValue(), event.getStatus(), mandatoryDataElements, validateMandatoryAttributes, importSummary ) )
{
return importSummary;
}
}
return importSummary;
}
private boolean validateDataValue( ProgramStageInstance programStageInstance, User user, DataElement dataElement,
String value, EventStatus eventStatus, Set<String> mandatoryDataElements, boolean validateMandatoryAttributes, ImportSummary importSummary )
{
String status = ValidationUtils.dataValueIsValid( value, dataElement );
if ( status != null )
{
importSummary.getConflicts().add( new ImportConflict( dataElement.getUid(), status ) );
importSummary.incrementIgnored();
importSummary.setStatus( ImportStatus.ERROR );
return false;
}
if (validateMandatoryAttributes)
{
ValidationStrategy validationStrategy = programStageInstance.getProgramStage().getValidationStrategy();
if ( (validationStrategy == ValidationStrategy.ON_UPDATE_AND_INSERT ||
(validationStrategy == ValidationStrategy.ON_COMPLETE && eventStatus == EventStatus.COMPLETED)) &&
(mandatoryDataElements.contains( dataElement.getUid() ) && (StringUtils.isEmpty( value ) || "null".equals( value ))) )
{
importSummary.getConflicts().add( new ImportConflict( dataElement.getUid(), "value_required_but_not_provided" ) );
importSummary.incrementIgnored();
importSummary.setStatus( ImportStatus.ERROR );
return false;
}
}
List<String> errors = trackerAccessManager.canWrite( user,
new TrackedEntityDataValue( programStageInstance, dataElement, value ) );
if ( !errors.isEmpty() )
{
errors.forEach( error -> importSummary.getConflicts().add( new ImportConflict( dataElement.getUid(), error ) ) );
importSummary.setStatus( ImportStatus.ERROR );
importSummary.incrementIgnored();
return false;
}
return true;
}
private ImportSummary saveEvent( Program program, ProgramInstance programInstance, ProgramStage programStage,
ProgramStageInstance programStageInstance, OrganisationUnit organisationUnit, Event event,
ImportOptions importOptions )
{
Assert.notNull( program, "Program cannot be null" );
Assert.notNull( programInstance, "Program instance cannot be null" );
Assert.notNull( programStage, "Program stage cannot be null" );
ImportSummary importSummary = new ImportSummary( event.getEvent() );
importOptions = updateImportOptions( importOptions );
boolean existingEvent = programStageInstance != null;
boolean dryRun = importOptions.isDryRun();
Date executionDate = null;
if ( event.getEventDate() != null )
{
executionDate = DateUtils.parseDate( event.getEventDate() );
}
Date dueDate = new Date();
if ( event.getDueDate() != null )
{
dueDate = DateUtils.parseDate( event.getDueDate() );
}
String storedBy = getStoredBy( event, importSummary, importOptions.getUser() != null ? importOptions.getUser().getUsername() : "[Unknown]" );
String completedBy = getCompletedBy( event, importSummary, importOptions.getUser() != null ? importOptions.getUser().getUsername() : "[Unknown]" );
CategoryOptionCombo aoc = null;
if ( (event.getAttributeCategoryOptions() != null && program.getCategoryCombo() != null)
|| event.getAttributeOptionCombo() != null )
{
IdScheme idScheme = importOptions.getIdSchemes().getCategoryOptionIdScheme();
try
{
aoc = getAttributeOptionCombo( program.getCategoryCombo(), event.getAttributeCategoryOptions(),
event.getAttributeOptionCombo(), idScheme );
}
catch ( IllegalQueryException ex )
{
importSummary.getConflicts().add( new ImportConflict( ex.getMessage(), event.getAttributeCategoryOptions() ) );
importSummary.setStatus( ImportStatus.ERROR );
return importSummary.incrementIgnored();
}
}
else
{
aoc = (CategoryOptionCombo) getDefaultObject( CategoryOptionCombo.class );
}
if ( aoc != null && aoc.isDefault() && program.getCategoryCombo() != null && !program.getCategoryCombo().isDefault() )
{
importSummary.getConflicts().add( new ImportConflict( "attributeOptionCombo", "Default attribute option combo is not allowed since program has non-default category combo" ) );
importSummary.setStatus( ImportStatus.ERROR );
return importSummary.incrementIgnored();
}
List<String> errors = trackerAccessManager.canWrite( importOptions.getUser(), aoc );
if ( !errors.isEmpty() )
{
importSummary.setStatus( ImportStatus.ERROR );
importSummary.getConflicts().addAll( errors.stream().map( s -> new ImportConflict( "CategoryOptionCombo", s ) ).collect( Collectors.toList() ) );
importSummary.incrementIgnored();
return importSummary;
}
if ( !dryRun )
{
if ( programStageInstance == null )
{
programStageInstance = createProgramStageInstance( event, programStage, programInstance,
organisationUnit, dueDate, executionDate, event.getStatus().getValue(),
completedBy, storedBy, event.getEvent(), aoc, importOptions );
}
else
{
updateProgramStageInstance( event, programStage, programInstance, organisationUnit, dueDate,
executionDate, event.getStatus().getValue(), completedBy,
programStageInstance, aoc, importOptions );
}
saveTrackedEntityComment( programStageInstance, event, storedBy );
updateTrackedEntityInstance( programStageInstance, importOptions.getUser() );
importSummary.setReference( programStageInstance.getUid() );
}
Map<String, TrackedEntityDataValue> dataElementValueMap = Maps.newHashMap();
if ( existingEvent )
{
dataElementValueMap = getDataElementDataValueMap(
dataValueService.getTrackedEntityDataValues( programStageInstance ) );
}
boolean validateMandatoryAttributes = doValidationOfMandatoryAttributes( importOptions.getUser() );
Set<String> mandatoryDataElements = new HashSet<>( );
if (validateMandatoryAttributes)
{
mandatoryDataElements = validatePresenceOfMandatoryDataElements( event, programStageInstance, importSummary, false );
if ( importSummary.getStatus() == ImportStatus.ERROR )
{
return importSummary;
}
}
for ( DataValue dataValue : event.getDataValues() )
{
DataElement dataElement;
if ( dataElementValueMap.containsKey( dataValue.getDataElement() ) )
{
dataElement = dataElementValueMap.get( dataValue.getDataElement() ).getDataElement();
}
else
{
dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(),
dataValue.getDataElement() );
}
if ( dataElement != null )
{
if ( validateDataValue( programStageInstance, importOptions.getUser(), dataElement, dataValue.getValue(), event.getStatus(), mandatoryDataElements, validateMandatoryAttributes, importSummary ) )
{
String dataValueStoredBy = dataValue.getStoredBy() != null ? dataValue.getStoredBy() : storedBy;
if ( !dryRun )
{
TrackedEntityDataValue existingDataValue = dataElementValueMap.get( dataValue.getDataElement() );
saveDataValue( programStageInstance, dataValueStoredBy, dataElement, dataValue.getValue(),
dataValue.getProvidedElsewhere(), existingDataValue, importSummary );
}
}
}
else
{
importSummary.getConflicts().add( new ImportConflict( "dataElement", dataValue.getDataElement() + " is not a valid data element" ) );
importSummary.getImportCount().incrementIgnored();
}
}
sendProgramNotification( programStageInstance, importOptions );
importSummary.setStatus( importSummary.getConflicts().isEmpty() ? ImportStatus.SUCCESS : ImportStatus.ERROR );
return importSummary;
}
private void sendProgramNotification( ProgramStageInstance programStageInstance, ImportOptions importOptions )
{
if ( !importOptions.isSkipNotifications() )
{
if ( programStageInstance.isCompleted() )
{
programNotificationPublisher.publishEvent( programStageInstance, ProgramNotificationEventType.PROGRAM_STAGE_COMPLETION );
}
eventPublisher.publishEvent( new ProgramStageInstanceScheduledEvent( this, programStageInstance ) );
}
}
private void saveDataValue( ProgramStageInstance programStageInstance, String storedBy, DataElement dataElement,
String value, Boolean providedElsewhere, TrackedEntityDataValue dataValue, ImportSummary importSummary )
{
if ( value != null && value.trim().length() == 0 )
{
value = null;
}
if ( value != null )
{
if ( dataValue == null )
{
dataValue = new TrackedEntityDataValue( programStageInstance, dataElement, value );
dataValue.setStoredBy( storedBy );
dataValue.setProvidedElsewhere( providedElsewhere );
dataValueService.saveTrackedEntityDataValue( dataValue );
programStageInstance.getDataValues().add( dataValue );
if ( importSummary != null )
{
importSummary.getImportCount().incrementImported();
}
}
else
{
dataValue.setValue( value );
dataValue.setStoredBy( storedBy );
dataValue.setProvidedElsewhere( providedElsewhere );
dataValueService.updateTrackedEntityDataValue( dataValue );
if ( importSummary != null )
{
importSummary.getImportCount().incrementUpdated();
}
}
}
else if ( dataValue != null )
{
dataValueService.deleteTrackedEntityDataValue( dataValue );
if ( importSummary != null )
{
importSummary.getImportCount().incrementDeleted();
}
}
}
private ProgramStageInstance createProgramStageInstance( Event event, ProgramStage programStage,
ProgramInstance programInstance, OrganisationUnit organisationUnit, Date dueDate, Date executionDate,
int status, String completedBy, String storeBy, String programStageInstanceIdentifier,
CategoryOptionCombo aoc, ImportOptions importOptions )
{
ProgramStageInstance programStageInstance = new ProgramStageInstance();
if ( importOptions.getIdSchemes().getProgramStageInstanceIdScheme().equals( IdScheme.UID ) )
{
programStageInstance
.setUid( CodeGenerator.isValidUid( programStageInstanceIdentifier ) ? programStageInstanceIdentifier
: CodeGenerator.generateUid() );
}
else if ( importOptions.getIdSchemes().getProgramStageInstanceIdScheme().equals( IdScheme.CODE ) )
{
programStageInstance.setUid( CodeGenerator.generateUid() );
programStageInstance.setCode( programStageInstanceIdentifier );
}
programStageInstance.setStoredBy( storeBy );
updateProgramStageInstance( event, programStage, programInstance, organisationUnit, dueDate, executionDate,
status, completedBy, programStageInstance, aoc, importOptions );
return programStageInstance;
}
private void updateProgramStageInstance( Event event, ProgramStage programStage, ProgramInstance programInstance,
OrganisationUnit organisationUnit, Date dueDate, Date executionDate, int status,
String completedBy, ProgramStageInstance programStageInstance, CategoryOptionCombo aoc,
ImportOptions importOptions )
{
programStageInstance.setProgramInstance( programInstance );
programStageInstance.setProgramStage( programStage );
programStageInstance.setDueDate( dueDate );
programStageInstance.setExecutionDate( executionDate );
programStageInstance.setOrganisationUnit( organisationUnit );
programStageInstance.setAttributeOptionCombo( aoc );
programStageInstance.setGeometry( event.getGeometry() );
updateDateFields( event, programStageInstance );
programStageInstance.setStatus( EventStatus.fromInt( status ) );
if ( programStageInstance.getId() == 0 )
{
programStageInstance.setAutoFields();
programStageInstanceService.addProgramStageInstance( programStageInstance );
}
else
{
programStageInstanceService.updateProgramStageInstance( programStageInstance );
}
if ( programStageInstance.isCompleted() )
{
Date completedDate = null;
if ( event.getCompletedDate() != null )
{
completedDate = DateUtils.parseDate( event.getCompletedDate() );
}
programStageInstance.setCompletedBy( completedBy );
programStageInstanceService.completeProgramStageInstance( programStageInstance,
importOptions.isSkipNotifications(), i18nManager.getI18nFormat(), completedDate );
}
}
private void saveTrackedEntityComment( ProgramStageInstance programStageInstance, Event event, String storedBy )
{
for ( Note note : event.getNotes() )
{
String noteUid = CodeGenerator.isValidUid( note.getNote() ) ? note.getNote() : CodeGenerator.generateUid();
if ( !commentService.trackedEntityCommentExists( noteUid ) && !StringUtils.isEmpty( note.getValue() ) )
{
TrackedEntityComment comment = new TrackedEntityComment();
comment.setUid( noteUid );
comment.setCommentText( note.getValue() );
comment.setCreator( StringUtils.isEmpty( note.getStoredBy() ) ? User.getSafeUsername( storedBy ) : note.getStoredBy() );
Date created = DateUtils.parseDate( note.getStoredDate() );
comment.setCreated( created );
commentService.addTrackedEntityComment( comment );
programStageInstance.getComments().add( comment );
programStageInstanceService.updateProgramStageInstance( programStageInstance );
}
}
}
private String getCompletedBy( Event event, ImportSummary importSummary, String fallbackUsername )
{
String completedBy = event.getCompletedBy();
if ( StringUtils.isEmpty( completedBy ) )
{
completedBy = User.getSafeUsername( fallbackUsername );
}
else if ( completedBy.length() >= 31 )
{
if ( importSummary != null )
{
importSummary.getConflicts().add( new ImportConflict( "completed by",
completedBy + " is more than 31 characters, using current username instead" ) );
}
completedBy = User.getSafeUsername( fallbackUsername );
}
return completedBy;
}
private String getStoredBy( Event event, ImportSummary importSummary, String fallbackUsername )
{
String storedBy = event.getStoredBy();
if ( StringUtils.isEmpty( storedBy ) )
{
storedBy = User.getSafeUsername( fallbackUsername );
}
else if ( storedBy.length() >= 31 )
{
if ( importSummary != null )
{
importSummary.getConflicts().add( new ImportConflict( "stored by",
storedBy + " is more than 31 characters, using current username instead" ) );
}
storedBy = User.getSafeUsername( fallbackUsername );
}
return storedBy;
}
private Map<String, TrackedEntityDataValue> getDataElementDataValueMap(
Collection<TrackedEntityDataValue> dataValues )
{
return dataValues.stream().collect( Collectors.toMap( dv -> dv.getDataElement().getUid(), dv -> dv ) );
}
private OrganisationUnit getOrganisationUnit( IdSchemes idSchemes, String id )
{
return organisationUnitCache.get( id,
() -> manager.getObject( OrganisationUnit.class, idSchemes.getOrgUnitIdScheme(), id ) );
}
private Program getProgram( IdScheme idScheme, String id )
{
return programCache.get( id, () -> manager.getObject( Program.class, idScheme, id ) );
}
private ProgramStage getProgramStage( IdScheme idScheme, String id )
{
return programStageCache.get( id, () -> manager.getObject( ProgramStage.class, idScheme, id ) );
}
private DataElement getDataElement( IdScheme idScheme, String id )
{
return dataElementCache.get( id, () -> manager.getObject( DataElement.class, idScheme, id ) );
}
private CategoryOption getCategoryOption( IdScheme idScheme, String id )
{
return categoryOptionCache.get( id, () -> manager.getObject( CategoryOption.class, idScheme, id ) );
}
private CategoryOptionCombo getCategoryOptionCombo( IdScheme idScheme, String id )
{
return categoryOptionComboCache.get( id, () -> manager.getObject( CategoryOptionCombo.class, idScheme, id ) );
}
private CategoryOptionCombo getAttributeOptionCombo( String key, CategoryCombo categoryCombo,
Set<CategoryOption> categoryOptions )
{
return attributeOptionComboCache.get( key,
() -> categoryService.getCategoryOptionCombo( categoryCombo, categoryOptions ) );
}
private List<ProgramInstance> getActiveProgramInstances( String key, Program program )
{
return activeProgramInstanceCache.get( key, () -> {
return programInstanceService.getProgramInstances( program, ProgramStatus.ACTIVE );
} );
}
private IdentifiableObject getDefaultObject( Class<? extends IdentifiableObject> key )
{
return defaultObjectsCache.get( key, () -> manager.getByName( CategoryOptionCombo.class , "default" ) );
}
@Override
public void validate( EventSearchParams params )
throws IllegalQueryException
{
String violation = null;
if ( params == null )
{
throw new IllegalQueryException( "Query parameters can not be empty" );
}
if ( params.getProgram() == null && params.getOrgUnit() == null && params.getTrackedEntityInstance() == null
&& params.getEvents().isEmpty() )
{
violation = "At least one of the following query parameters are required: orgUnit, program, trackedEntityInstance or event";
}
if ( violation != null )
{
log.warn( "Validation failed: " + violation );
throw new IllegalQueryException( violation );
}
}
private void validateExpiryDays( Event event, Program program, ProgramStageInstance programStageInstance )
{
if ( program != null )
{
if ( program.getCompleteEventsExpiryDays() > 0 )
{
if ( event.getStatus() == EventStatus.COMPLETED
|| programStageInstance != null && programStageInstance.getStatus() == EventStatus.COMPLETED )
{
Date referenceDate = null;
if ( programStageInstance != null )
{
referenceDate = programStageInstance.getCompletedDate();
}
else
{
if ( event.getCompletedDate() != null )
{
referenceDate = DateUtils.parseDate( event.getCompletedDate() );
}
}
if ( referenceDate == null )
{
throw new IllegalQueryException( "Event needs to have completed date" );
}
if ( (new Date()).after(
DateUtils.getDateAfterAddition( referenceDate, program.getCompleteEventsExpiryDays() ) ) )
{
throw new IllegalQueryException(
"The event's completness date has expired. Not possible to make changes to this event" );
}
}
}
PeriodType periodType = program.getExpiryPeriodType();
if ( periodType != null && program.getExpiryDays() > 0 )
{
if ( programStageInstance != null )
{
Date today = new Date();
if ( programStageInstance.getExecutionDate() == null )
{
throw new IllegalQueryException( "Event needs to have event date" );
}
Period period = periodType.createPeriod( programStageInstance.getExecutionDate() );
if ( today.after( DateUtils.getDateAfterAddition( period.getEndDate(), program.getExpiryDays() ) ) )
{
throw new IllegalQueryException( "The program's expiry date has passed. It is not possible to make changes to this event" );
}
}
else
{
String referenceDate = event.getEventDate() != null ? event.getEventDate()
: event.getDueDate() != null ? event.getDueDate() : null;
if ( referenceDate == null )
{
throw new IllegalQueryException( "Event needs to have at least one (event or schedule) date" );
}
Period period = periodType.createPeriod( new Date() );
if ( DateUtils.parseDate( referenceDate ).before( period.getStartDate() ) )
{
throw new IllegalQueryException( "The event's date belongs to an expired period. It is not possble to create such event" );
}
}
}
}
}
private QueryItem getQueryItem( String item )
{
String[] split = item.split( DimensionalObject.DIMENSION_NAME_SEP );
if ( split == null || split.length % 2 != 1 )
{
throw new IllegalQueryException( "Query item or filter is invalid: " + item );
}
QueryItem queryItem = getItem( split[0] );
if ( split.length > 1 )
{
for ( int i = 1; i < split.length; i += 2 )
{
QueryOperator operator = QueryOperator.fromString( split[i] );
queryItem.getFilters().add( new QueryFilter( operator, split[i + 1] ) );
}
}
return queryItem;
}
private QueryItem getItem( String item )
{
DataElement de = dataElementService.getDataElement( item );
if ( de == null )
{
throw new IllegalQueryException( "Dataelement does not exist: " + item );
}
return new QueryItem( de, null, de.getValueType(), de.getAggregationType(), de.getOptionSet() );
}
private void clearSession()
{
organisationUnitCache.clear();
programCache.clear();
programStageCache.clear();
dataElementCache.clear();
categoryOptionCache.clear();
categoryOptionComboCache.clear();
attributeOptionComboCache.clear();
activeProgramInstanceCache.clear();
defaultObjectsCache.clear();
dbmsManager.clearSession();
}
private void updateDateFields( Event event, ProgramStageInstance programStageInstance )
{
programStageInstance.setAutoFields();
Date createdAtClient = DateUtils.parseDate( event.getCreatedAtClient() );
if ( createdAtClient != null )
{
programStageInstance.setCreatedAtClient( createdAtClient );
}
String lastUpdatedAtClient = event.getLastUpdatedAtClient();
if ( lastUpdatedAtClient != null )
{
programStageInstance.setLastUpdatedAtClient( DateUtils.parseDate( lastUpdatedAtClient ) );
}
}
private void updateTrackedEntityInstance( ProgramStageInstance programStageInstance, User user )
{
updateTrackedEntityInstance( Lists.newArrayList( programStageInstance ), user );
}
private void updateTrackedEntityInstance( List<ProgramStageInstance> programStageInstances, User user )
{
Set<ProgramInstance> programInstances = new HashSet<>();
Set<TrackedEntityInstance> trackedEntityInstances = new HashSet<>();
for ( ProgramStageInstance programStageInstance : programStageInstances )
{
if ( programStageInstance.getProgramInstance() != null )
{
programInstances.add( programStageInstance.getProgramInstance() );
if ( programStageInstance.getProgramInstance().getEntityInstance() != null )
{
trackedEntityInstances.add( programStageInstance.getProgramInstance().getEntityInstance() );
}
}
}
programInstances.forEach( pi -> manager.update( pi, user ) );
trackedEntityInstances.forEach( tei -> manager.update( tei, user ) );
}
private CategoryOptionCombo getAttributeOptionCombo( CategoryCombo categoryCombo, String cp,
String attributeOptionCombo, IdScheme idScheme )
{
Set<String> opts = TextUtils.splitToArray( cp, TextUtils.SEMICOLON );
return getAttributeOptionCombo( categoryCombo, opts, attributeOptionCombo, idScheme );
}
private CategoryOptionCombo getAttributeOptionCombo( CategoryCombo categoryCombo, Set<String> opts,
String attributeOptionCombo, IdScheme idScheme )
{
if ( categoryCombo == null )
{
throw new IllegalQueryException( "Illegal category combo" );
}
// Attribute category options validation
CategoryOptionCombo attrOptCombo = null;
if ( opts != null )
{
Set<CategoryOption> categoryOptions = new HashSet<>();
for ( String uid : opts )
{
CategoryOption categoryOption = getCategoryOption( idScheme, uid );
if ( categoryOption == null )
{
throw new IllegalQueryException( "Illegal category option identifier: " + uid );
}
categoryOptions.add( categoryOption );
}
List<String> options = Lists.newArrayList( opts );
Collections.sort( options );
String cacheKey = categoryCombo.getUid() + "-" + Joiner.on( "-" ).join( options );
attrOptCombo = getAttributeOptionCombo( cacheKey, categoryCombo, categoryOptions );
if ( attrOptCombo == null )
{
throw new IllegalQueryException( "Attribute option combo does not exist for given category combo and category options" );
}
}
else if ( attributeOptionCombo != null )
{
attrOptCombo = getCategoryOptionCombo( idScheme, attributeOptionCombo );
}
// Fall back to default category option combination
if ( attrOptCombo == null )
{
attrOptCombo = (CategoryOptionCombo) getDefaultObject( CategoryOptionCombo.class );
}
if ( attrOptCombo == null )
{
throw new IllegalQueryException( "Default attribute option combo does not exist" );
}
return attrOptCombo;
}
protected ImportOptions updateImportOptions( ImportOptions importOptions )
{
if ( importOptions == null )
{
importOptions = new ImportOptions();
}
if ( importOptions.getUser() == null )
{
importOptions.setUser( currentUserService.getCurrentUser() );
}
return importOptions;
}
protected void reloadUser( ImportOptions importOptions )
{
if ( importOptions == null || importOptions.getUser() == null )
{
return;
}
importOptions.setUser( userService.getUser( importOptions.getUser().getId() ) );
}
} |
package opendap.bes;
import opendap.bes.dap2Responders.BesApi;
import opendap.io.HyraxStringEncoding;
import opendap.logging.Timer;
import opendap.logging.Procedure;
import opendap.ppt.OPeNDAPClient;
import opendap.ppt.PPTException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class BES {
private Logger log;
private BESConfig config;
private ArrayBlockingQueue<OPeNDAPClient> clientQueue;
private ConcurrentHashMap<String, OPeNDAPClient> clientsMap;
private ReentrantLock clientCheckoutLock;
private Semaphore clientCheckOutFlag;
private ReentrantLock clientsMapLock;
private int totalClients;
private ReentrantLock adminLock;
private AdminInfo administratorInfo;
private String supportEmail;
private ReentrantLock versionDocLock;
private Document serverVersionDocument;
private static final Namespace BES_NS = opendap.namespaces.BES.BES_NS;
private static final Namespace BES_ADMIN_NS = opendap.namespaces.BES.BES_ADMIN_NS;
private static final String BES_ADMIN_COMMAND = "BesAdminCmd";
private static final String BES_ADMIN_SET_LOG_CONTEXT = "SetLogContext";
private static final String BES_ADMIN_GET_CONFIG = "GetConfig";
private static final String BES_ADMIN_SET_CONFIG = "SetConfig";
private static final String BES_ADMIN_TAIL_LOG = "TailLog";
private int MAX_COMMAND_ATTEMPTS = 2;
public BES(BESConfig config) {
log = org.slf4j.LoggerFactory.getLogger(getClass());
this.config = config.copy();
clientQueue = new ArrayBlockingQueue<>(getMaxClients(), true);
clientsMap = new ConcurrentHashMap<>();
clientCheckoutLock = new ReentrantLock(true);
clientCheckOutFlag = new Semaphore(getMaxClients(), true);
clientsMapLock = new ReentrantLock(true);
totalClients = 0;
adminLock = new ReentrantLock(true);
administratorInfo= null;
supportEmail = null;
versionDocLock = new ReentrantLock(true);
serverVersionDocument = null;
log.debug("BES built with configuration:\n{}", this.config);
}
public AdminInfo getAdministratorInfo() throws JDOMException, BESError, PPTException, IOException {
if(administratorInfo==null){
adminLock.lock();
try {
if(administratorInfo==null) {
administratorInfo = retrieveAdminInfo();
}
}
finally {
adminLock.unlock();
}
}
return new AdminInfo(administratorInfo);
}
private AdminInfo retrieveAdminInfo() throws JDOMException, BESError, PPTException, IOException {
Document showBesKeyCmd = BesApi.getShowBesKeyRequestDocument(BesApi.BES_SERVER_ADMINISTRATOR_KEY);
Document response = new Document();
besTransaction(showBesKeyCmd,response);
Element showBesKey = response.getRootElement().getChild("showBesKey",BES_NS);
showBesKey.detach();
Map<String,String> pmap = BesApi.processBesParameterMap(showBesKey);
return new AdminInfo(pmap);
}
public String getSupportEmail(){
if(supportEmail==null){
adminLock.lock();
try {
if(supportEmail==null) {
supportEmail = retrieveSupportEmail();
}
}
finally {
adminLock.unlock();
}
}
return supportEmail;
}
private String retrieveSupportEmail() {
String emailAddress = BesApi.DEFAULT_SUPPORT_EMAIL_ADDRESS;
Document showBesKeyCmd = BesApi.getShowBesKeyRequestDocument(BesApi.BES_SUPPORT_EMAIL_KEY);
Document response = new Document();
try {
besTransaction(showBesKeyCmd,response);
Element showBesKey = response.getRootElement().getChild("showBesKey",BES_NS);
if(showBesKey!=null){
if(log.isDebugEnabled()) {
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
log.debug("BES Support Email Key for \"{}\"\n{}",getPrefix(), xmlo.outputString(showBesKey));
}
Element value = showBesKey.getChild(BesApi.VALUE,opendap.namespaces.BES.BES_NS);
if(value!=null){
emailAddress = value.getTextTrim();
}
}
}
catch (PPTException | IOException | JDOMException | BESError e) {
log.error("Failed to get {} from BES. Message: {}", BesApi.BES_SUPPORT_EMAIL_KEY,e.getMessage());
}
return emailAddress;
}
public List<BesConfigurationModule> getConfigurationModules() throws BesAdminFail {
ArrayList<BesConfigurationModule> configurationModules = new ArrayList<>();
String configString = getConfiguration(null);
ByteArrayInputStream bais = new ByteArrayInputStream(configString.getBytes( HyraxStringEncoding.getCharset()));
try {
Document confDoc = opendap.xml.Util.getDocument(bais);
Element root = confDoc.getRootElement();
List moduleConfigs = root.getChildren("BesConfig", BES.BES_ADMIN_NS);
for (Object o : moduleConfigs) {
Element moduleConfigElement = (Element) o;
BesConfigurationModule bm = new BesConfigurationModule(moduleConfigElement);
configurationModules.add(bm);
}
} catch (JDOMException e) {
log.error("Failed to parse BES response. Msg: {}", e.getMessage());
} catch (IOException e) {
log.error("Failed to ingest BES response. Msg: {}", e.getMessage());
}
return configurationModules;
}
/**
* Checks to see if it's possible to communicate with the BES.
* @return True if communication is with the besdaemon (aka admin port) port. False otherwise.
*
*/
public boolean checkBesAdminConnection() {
boolean besIsOk = true;
//@todo Make and use a specially designed BES command!
try {
getConfiguration(null);
} catch (BesAdminFail besAdminFail) {
log.error(besAdminFail.getMessage());
besIsOk = false;
}
return besIsOk;
}
public int getAdminPort() {
return config.getAdminPort();
}
public boolean isAdminPortConfigured() {
return config.getAdminPort() > 0;
}
public int getPort() {
return config.getPort();
}
public String getHost() {
return config.getHost();
}
public int getTimeout() {
return config.getTimeOut();
}
public String getPrefix() {
return config.getPrefix();
}
public String getNickName() {
return config.getBesName();
}
public void setNickName(String name) {
config.setBesName(name);
}
public int getMaxClients() {
return config.getMaxClients();
}
public int getMaxResponseSize() {
return config.getMaxResponseSize();
}
public TreeMap<String, BesLogger> getBesLoggers() throws BesAdminFail {
TreeMap<String, BesLogger> besLoggers = new TreeMap<>();
String getLogContextsCmd = getSimpleBesAdminCommand("GetLogContexts");
String besResponse = executeBesAdminCommand(getLogContextsCmd);
ByteArrayInputStream bais = new ByteArrayInputStream(besResponse.getBytes( HyraxStringEncoding.getCharset()));
SAXBuilder saxBuilder = new SAXBuilder(false);
try {
Document loggerContextsDoc = saxBuilder.build(bais);
List loggers = loggerContextsDoc.getRootElement().getChildren("LogContext", BES_ADMIN_NS);
Iterator i = loggers.iterator();
while (i.hasNext()) {
Element logger = (Element) i.next();
String name = logger.getAttributeValue("name");
String state = logger.getAttributeValue("state");
if (name != null && state != null)
besLoggers.put(name, new BesLogger(name, state));
else
log.error("BES responded with unrecognized content structure. Response: {}", besResponse);
}
} catch (JDOMException e) {
log.error("Failed to parse BES response! Msg: {}", e.getMessage());
} catch (IOException e) {
log.error("Failed to read BES response! Msg: {}", e.getMessage());
}
return besLoggers;
}
public String getLoggerState(String loggerName) throws BesAdminFail {
SortedMap<String, BesLogger> besLoggers = getBesLoggers();
BesLogger logger = besLoggers.get(loggerName);
if (logger != null && logger.getIsEnabled())
return "on";
return "off";
}
public String setLoggerState(String loggerName, String loggerState) throws BesAdminFail {
String setLoggerStateCmd = getSetBesLoggersStateCommand(loggerName, loggerState);
String besResponse = executeBesAdminCommand(setLoggerStateCmd);
ByteArrayInputStream bais = new ByteArrayInputStream(besResponse.getBytes( HyraxStringEncoding.getCharset()));
SAXBuilder saxBuilder = new SAXBuilder(false);
String status = besResponse;
try {
Document besResponseDoc = saxBuilder.build(bais);
Element statusElement = besResponseDoc.getRootElement().getChild("OK", BES_ADMIN_NS);
if (statusElement != null)
status = new StringBuilder().append("OK: The BES logger '").append(loggerName).append("' has been set to ").append(loggerState).toString();
} catch (JDOMException e) {
log.error("Failed to parse BES response! Msg: {}", e.getMessage());
} catch (IOException e) {
log.error("Failed to read BES response! Msg: {}", e.getMessage());
}
return status;
}
/**
*
* @param loggerName
* @param loggerState
* @return
*/
public String getSetBesLoggersStateCommand(String loggerName, String loggerState) {
Element docRoot = new Element(BES_ADMIN_COMMAND, BES_ADMIN_NS);
Element cmd = new Element(BES_ADMIN_SET_LOG_CONTEXT, BES_ADMIN_NS);
cmd.setAttribute("name", loggerName);
cmd.setAttribute("state", loggerState);
docRoot.addContent(cmd);
Document besCmdDoc = new Document(docRoot);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(besCmdDoc);
}
/*********************************************************************
* BES LOGGER BEGIN
*/
public static class BesLogger {
public BesLogger(String name, boolean enabled) {
loggerName = name;
isEnabled = enabled;
}
public BesLogger(String name, String enabled) {
loggerName = name;
if (enabled != null && enabled.equalsIgnoreCase("on"))
isEnabled = true;
else
isEnabled = false;
}
boolean isEnabled;
public boolean getIsEnabled() {
return isEnabled;
}
public void setIsEnabled(boolean enabled) {
isEnabled = enabled;
}
String loggerName;
public String getName() {
return loggerName;
}
public void setName(String name) {
loggerName = name;
}
}
public int getBesClientCount() {
return clientsMap.size();
}
public Enumeration<OPeNDAPClient> getClients() {
return clientsMap.elements();
}
public String toString() {
return "[BES prefix: " + getPrefix() +
" host: " + getHost() +
" port: " + getPort() +
" maxClients: " + getMaxClients() +
" maxClientCommands: " + config.getMaxCommands() +
"]";
}
public String executeBesAdminCommand(String besCmd) throws BesAdminFail {
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!isAdminPortConfigured()) {
sb.append("BES Admin Service is not configured! Port number for admin connection has not been set!");
return sb.toString();
}
OPeNDAPClient admin = null;
adminLock.lock();
try {
try {
log.debug("Getting new admin client...");
admin = new OPeNDAPClient();
log.debug("Starting new admin client. Host: {} Port: {}", getHost(), getAdminPort());
admin.startClient(getHost(), getAdminPort(), getTimeout());
log.debug("BES admin client started, sending command:\n{}", besCmd);
admin.executeCommand(besCmd, baos, baos);
String besResponse;
try {
besResponse = baos.toString(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
besResponse = "FAILED to encode BES response as " + StandardCharsets.UTF_8.name();
}
log.debug("BES returned:\n{}", besResponse);
return besResponse;
} catch (PPTException e) {
sb.append("Failed to execute BES command. Message: ")
.append(e.getMessage());
throw new BesAdminFail("Failed to execute BES command. Message: " + e.getMessage(), e);
} finally {
if (admin != null) {
try {
admin.shutdownClient(false);
} catch (PPTException e) {
sb.append("FAILED TO SHUTDOWN CLIENT! Msg: ").append(e.getMessage());
admin.killClient();
}
}
}
}
finally {
adminLock.unlock();
}
}
public String start() throws BesAdminFail {
String cmd = getStartCommand();
return executeBesAdminCommand(cmd);
}
public String stopNow() throws BesAdminFail {
String cmd = getStopNowCommand();
return executeBesAdminCommand(cmd);
}
public String getStartCommand() {
return getSimpleBesAdminCommand("Start");
}
public String getStopNowCommand() {
return getSimpleBesAdminCommand("StopNow");
}
public String stopNice(long timeOut) throws BesAdminFail {
StringBuilder sb = new StringBuilder();
long stopNiceMinTimeOut = 1000;
if (timeOut < stopNiceMinTimeOut)
timeOut = stopNiceMinTimeOut;
long stopNiceMaxTimeOut = 30000;
if (timeOut > stopNiceMaxTimeOut)
timeOut = stopNiceMaxTimeOut;
String besResponse = null;
String msg = "Attempting to acquire client checkOut lock...";
log.info(msg);
sb.append(msg).append("\n");
clientCheckoutLock.lock();
try {
Date startTime = new Date();
boolean done = false;
msg = "Attempting to acquire all BES clientsMap...";
log.info(msg);
sb.append(msg).append("\n");
while (!done) {
Collection<OPeNDAPClient> clients = clientsMap.values();
boolean allClientsAcquired = true;
for (OPeNDAPClient client : clients) {
boolean inQue = clientQueue.remove(client);
if (!inQue) {
allClientsAcquired = false;
} else {
msg = "Shutting down client connection '" + client.getID() + "'...";
log.info(msg);
sb.append(msg).append("\n");
try {
discardClient(client);
msg = "Client connection '" + client.getID() + "'shutdown normally";
log.info(msg);
sb.append(msg).append("\n");
} catch (PPTException e) {
msg = "Shutdown FAILED for client connection '" + client.getID() + "'Trying to kill connection.";
log.info(msg);
sb.append(msg).append("\n");
client.killClient();
msg = "Killed client connection '" + client.getID() + "'.";
log.info(msg);
sb.append(msg).append("\n");
}
msg = "Removing client connection '" + client.getID() + "' from clientsMap list.";
log.info(msg);
sb.append(msg).append("\n");
clientsMap.remove(client.getID());
}
}
if (!allClientsAcquired) {
Date endTime = new Date();
long elapsedTime = endTime.getTime() - startTime.getTime();
if (elapsedTime > timeOut) {
done = true;
msg = "Timeout Has Expired. Shutting down BES NOW...";
log.info(msg);
sb.append(msg).append("\n");
} else {
msg = "Did not acquire all clientsMap. Sleeping...";
log.info(msg);
sb.append(msg).append("\n");
Thread.sleep(timeOut / 3);
}
} else {
done = true;
msg = "Stopped all BES client connections.";
log.info(msg);
sb.append(msg).append("\n");
}
}
msg = "Stopping BES...";
log.info(msg);
sb.append(msg).append("\n");
besResponse = stopNow();
}
catch (InterruptedException e) {
sb.append(e.getMessage());
Thread.currentThread().interrupt();
}
finally {
sb.append("Releasing client checkout lock...").append("\n");
log.info("{}",sb);
clientCheckoutLock.unlock();
}
return besResponse;
}
public String getConfiguration(String moduleName) throws BesAdminFail {
String cmd = getGetConfigurationCommand(moduleName);
return executeBesAdminCommand(cmd);
}
public String setConfiguration(String moduleName, String configuration) throws BesAdminFail {
String cmd = getSetConfigurationCommand(moduleName, configuration);
return executeBesAdminCommand(cmd);
}
public String getGetConfigurationCommand(String moduleName) {
Element docRoot = new Element(BES_ADMIN_COMMAND, BES_ADMIN_NS);
Element cmd = new Element(BES_ADMIN_GET_CONFIG, BES_ADMIN_NS);
if (moduleName != null)
cmd.setAttribute("module", moduleName);
docRoot.addContent(cmd);
Document besCmdDoc = new Document(docRoot);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(besCmdDoc);
}
public String getSetConfigurationCommand(String moduleName, String configuration) {
Element docRoot = new Element(BES_ADMIN_COMMAND, BES_ADMIN_NS);
Element cmd = new Element(BES_ADMIN_SET_CONFIG, BES_ADMIN_NS);
if (moduleName != null)
cmd.setAttribute("module", moduleName);
cmd.setText(configuration);
docRoot.addContent(cmd);
Document besCmdDoc = new Document(docRoot);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(besCmdDoc);
}
public String getLog(String lines) throws BesAdminFail {
String cmd = getGetLogCommand(lines);
return executeBesAdminCommand(cmd);
}
public String getGetLogCommand(String lines) {
Element docRoot = new Element(BES_ADMIN_COMMAND, BES_ADMIN_NS);
Element cmd = new Element(BES_ADMIN_TAIL_LOG, BES_ADMIN_NS);
if (lines != null)
cmd.setAttribute("lines", lines);
docRoot.addContent(cmd);
Document besCmdDoc = new Document(docRoot);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(besCmdDoc);
}
public String getSimpleBesAdminCommand(String besCmd) {
Element docRoot = new Element(BES_ADMIN_COMMAND, BES_ADMIN_NS);
Element cmd = new Element(besCmd, BES_ADMIN_NS);
docRoot.addContent(cmd);
Document besCmdDoc = new Document(docRoot);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(besCmdDoc);
}
public Document getVersionDocument() throws BESError, JDOMException, IOException, BadConfigurationException, PPTException {
// Lock the resource.
versionDocLock.lock();
try {
// Have we cached it already?
if (serverVersionDocument == null) {
// Nope? Then Cache it!
cacheServerVersionDocument();
if (log.isInfoEnabled()) {
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
log.info("BES Version Document: \n{}", xmlo.outputString(serverVersionDocument));
}
}
}
finally {
// Unlock the resource.
versionDocLock.unlock();
}
// Return a copy so nobody can break our stuff!
return (Document) serverVersionDocument.clone();
}
/**
* Helper method that adds the bes client identifier to the request ID.
* @param request
* @param oc
* @throws IOException
*/
private void tweakRequestId(Document request, OPeNDAPClient oc) throws IOException {
Element reqElement = request.getRootElement();
if(reqElement==null){
throw new IOException("The BES Request document must have a root element!");
}
String reqID = reqElement.getAttributeValue(BesApi.REQUEST_ID);
if(reqID==null)
reqID="";
reqID += "[bes_client:"+oc.getID()+"]";
reqElement.setAttribute(BesApi.REQUEST_ID,reqID);
}
/**
* Executes a command/response transaction with the BES
*
* @param request The BES request document.
* @param response The document into which the BES response will be placed. If the passed Document object contains
* conent, then the content will be discarded.
* @return true if the request is successful, false if there is a problem fulfilling the request.
* @throws IOException
* @throws PPTException
* @throws JDOMException
*/
public void besTransaction(Document request, Document response )
throws IOException, PPTException, JDOMException, BESError {
log.debug("besTransaction() - BEGIN.");
int attempts = 0;
boolean besTrouble;
PPTException pptException = null;
BESError besFatalError;
SAXBuilder sb = new SAXBuilder();
Document doc;
do {
besTrouble = false;
pptException = null;
besFatalError = null;
OPeNDAPClient oc = getClient();
if (oc == null) {
String msg = "FAILED to retrieve valid OPeNDAPClient (connection to BES)!";
log.error("besTransaction() - {}", msg);
throw new IOException(msg);
}
tweakRequestId(request, oc);
if (log.isDebugEnabled()) {
log.debug("besTransaction() request document: \n{}
}
Logger besCommandLogger = LoggerFactory.getLogger("BesCommandLog");
if (besCommandLogger.isInfoEnabled()) {
besCommandLogger.info("BES COMMAND ({})\n{}\n", new Date(), showRequest(request));
}
Procedure timedProc = Timer.start();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream()) {
if (oc.sendRequest(request, baos, erros)) {
log.debug("besTransaction() The BES returned this document:\n{}", baos);
if (baos.size() != 0) {
doc = sb.build(new ByteArrayInputStream(baos.toByteArray()));
// Get the root element.
Element root = doc.getRootElement();
// Detach it from the document
root.detach();
// Pitch the root element that came with the passed catalog.
// (There may not be one but whatever...)
response.detachRootElement();
// Set the root element to be the one sent from the BES.
response.setRootElement(root);
}
} else {
log.debug("BES returned this ERROR document:\n
BESError besError;
if (erros.size() != 0) {
ByteArrayInputStream bais = new ByteArrayInputStream(erros.toByteArray());
besError = new BESError(bais);
// This logging statement is turned down to debug because otherwise when the OLFS probes the
// the BES in an effort to distinguish requests for files in the BES catalog from DAP and catalog
// requests the log gets filled with spurious errors. When we eventually implement a showPathInfo()
// method/model for that will allow the OLFS to do this in a more efficient and non error
// producing manner we should also:
// @TODO Promote this to log.error()
log.debug("besTransaction() - BES Transaction received a BESError Object. Msg: {}", besError.getMessage());
int besErrCode = besError.getBesErrorCode();
if (besErrCode == BESError.INTERNAL_FATAL_ERROR || besErrCode == BESError.TIME_OUT) {
besTrouble = true;
}
} else {
String reqId = request.getRootElement().getAttributeValue(BesApi.REQUEST_ID);
Document errDoc = getMissingBesResponseErrorDoc(reqId);
besError = new BESError(errDoc);
}
int besErrCode = besError.getBesErrorCode();
// If the BES experienced a fatal error then we know we have
// to dump the connection to the child besListener.
if (besErrCode == BESError.INTERNAL_FATAL_ERROR || besErrCode == BESError.TIME_OUT) {
besTrouble = true;
besFatalError = besError;
}
else {
// If the error is not fatal then we just throw it and move on.
throw besError;
}
}
} catch (PPTException e) {
besTrouble = true;
log.debug("OLFS Encountered a PPT Problem!", e);
String msg = "Problem with OPeNDAPClient. OPeNDAPClient executed " + oc.getCommandCount() + " commands";
log.error(msg);
e.setErrorMessage(msg);
pptException = e;
} finally {
returnClient(oc, besTrouble);
Timer.stop(timedProc);
log.debug("besTransaction() - END.");
}
}
while(besTrouble && attempts < MAX_COMMAND_ATTEMPTS);
if(besTrouble){
if(besFatalError != null)
throw besFatalError;
if(pptException != null)
throw pptException;
}
log.debug("END");
}
/**
* Executes a command/response transaction with the BES
*
* @param request The BES request document.
* @param os The outputstream to write the BES response to.
* any error information will be written to the OutputStream err.
* @throws BadConfigurationException
* @throws IOException
* @throws PPTException
*/
public void besTransaction(Document request, OutputStream os)
throws IOException, PPTException, BESError {
log.debug("BEGIN");
int attempts = 0;
boolean besTrouble;
PPTException pptException;
BESError besFatalError;
do {
besTrouble = false;
pptException = null;
besFatalError = null;
OPeNDAPClient oc = getClient();
if(oc==null){
String msg = "FAILED to retrieve a valid OPeNDAPClient instance! "+
"BES Prefix: "+getPrefix()+" BES NickName: "+getNickName()+" BES Host: "+getHost();
log.error(msg);
throw new IOException(msg);
}
tweakRequestId(request,oc);
if(log.isDebugEnabled()) {
log.debug("besTransaction() request document: \n
}
Logger besCommandLogger = LoggerFactory.getLogger("BesCommandLog");
if(besCommandLogger.isInfoEnabled()){
besCommandLogger.info("BES COMMAND ({})\n{}\n",new Date(),showRequest(request));
}
Procedure timedProc = Timer.start();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
boolean result = oc.sendRequest(request, os, baos);
log.debug("besTransaction() - Completed.");
if (!result) {
log.debug("BESError: \n{}", baos.toString(HyraxStringEncoding.getCharset().name()));
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BESError besError = new BESError(bais);
log.error("besTransaction() - BES Transaction received a BESError Object. Msg: {}", besError.getMessage());
int besErrCode = besError.getBesErrorCode();
// If the BES experienced a fatal error then we know we have
// to dump the connection to the child besListener.
if (besErrCode == BESError.INTERNAL_FATAL_ERROR || besErrCode == BESError.TIME_OUT) {
besTrouble = true;
besFatalError = besError;
}
else {
// If the error is not fatal then we just throw it and move on.
throw besError;
}
}
} catch (PPTException e) {
besTrouble = true;
String msg = "Problem encountered with BES connection. Message: '" + e.getMessage() + "' " +
"OPeNDAPClient executed " + oc.getCommandCount() + " prior commands.";
log.error(msg);
e.setErrorMessage(msg);
pptException = e;
} finally {
returnClient(oc, besTrouble);
Timer.stop(timedProc);
}
attempts++;
}
while(besTrouble && attempts < MAX_COMMAND_ATTEMPTS);
if(besTrouble){
if(besFatalError != null)
throw besFatalError;
if(pptException != null)
throw pptException;
}
log.debug("END");
}
String showRequest(Document request) throws IOException{
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(request);
}
private Document getMissingBesResponseErrorDoc(String reqId){
Element errorResponse = new Element("response",BES_NS);
Element bes = new Element("BES",BES_NS);
Element besError = new Element("BESError",BES_NS);
Element type = new Element("Type",BES_NS);
Element message = new Element("Message",BES_NS);
Element admin = new Element("Administrator",BES_NS);
errorResponse.addNamespaceDeclaration(BES_NS);
errorResponse.setAttribute(BesApi.REQUEST_ID, reqId);
type.setText("1");
message.setText("BES returned an empty error document! That's a bad thing!");
admin.setText("UNKNOWN Administrator - BES Error response was empty!");
besError.addContent(type);
besError.addContent(message);
besError.addContent(admin);
bes.addContent(besError);
errorResponse.addContent(bes);
return new Document(errorResponse);
}
/**
* @throws IOException
* @throws PPTException
* @throws BadConfigurationException
* @throws JDOMException
* @throws BESError
*/
private void cacheServerVersionDocument() throws IOException,
PPTException,
BadConfigurationException,
JDOMException,
BESError {
log.debug("Getting Server Version Document.");
Document version = new Document();
BesApi besApi = new BesApi();
besApi.getBesVersion(getPrefix(), version);
Element root = version.getRootElement();
if(root==null)
throw new IOException("BES version response was emtpy! No root element");
Element ver = root.getChild("showVersion", BES_NS);
if(ver==null)
throw new IOException("BES version response was emtpy! No showVersion element");
// Disconnect it from it's parent.
ver.detach();
ver.setName("BES");
ver.setAttribute("prefix", getPrefix());
if(getNickName()!=null)
ver.setAttribute("name",getNickName());
version.detachRootElement();
version.setRootElement(ver);
serverVersionDocument = version;
}
public String trimPrefix(String dataset) {
String trim;
if (getPrefix().equals("/")) {
trim = dataset;
}
else {
trim = dataset.substring(getPrefix().length());
}
return trim;
}
/**
* The pool of availableInChunk OPeNDAPClient connections starts empty. When this
* method is called the pool is checked. If no client is availableInChunk, and the
* number of clientsMap has not reached the cap, then a new one is made,
* started, and returned. If no client is availableInChunk and the cap has been
* reached then this method will BLOCK until a client becomes availableInChunk.
* If a client is availableInChunk, it is returned.
*
* @return The next availableInChunk OPeNDAPClient.
* @throws opendap.ppt.PPTException .
* @throws BadConfigurationException .
*/
public OPeNDAPClient getClient()
throws PPTException {
OPeNDAPClient besClient=null;
clientCheckoutLock.lock();
try {
// Acquiring this semaphore is what limits the number
// of clientsMap that will be in the pool. The number of
// semaphores available is set to MaxClients.
clientCheckOutFlag.acquire();
log.debug("clientQueue size: '{}'", clientQueue.size());
if (clientQueue.isEmpty()) {
besClient = getNewClient();
} else {
// Get a client from the client pool.
besClient = clientQueue.take();
log.debug("getClient() - Retrieved BES Client (id:{}) from Pool.", besClient.getID());
// If the bes connection is closed, or the client just is not connected, pitch the client
// and make a new one, if you can...
if(besClient.isClosed() || !besClient.isConnected()){
log.warn("getClient() - BES Client (id:{}) appears to be dead, discarding...",besClient.getID());
discardClient(besClient);
besClient = getNewClient();
}
}
return besClient;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Whoops! Thread Interrupted!: {}", e.getMessage());
if (besClient != null) {
log.error("Attempting to discard BES Client (id:{}) ", besClient.getID());
discardClient(besClient);
clientCheckOutFlag.release(); // Release the client permit because this client is hosed...
}
throw new PPTException(e);
} finally {
clientCheckoutLock.unlock();
}
}
private OPeNDAPClient getNewClient() throws PPTException, InterruptedException {
// Make a new OPeNDAClient to connect to the BES
OPeNDAPClient besClient = new OPeNDAPClient();
log.debug("Made new BES Client. (id:{}) Starting Client.",besClient.getID());
// Start the client by opening the PPT connection to the BES.
try {
besClient.startClient(getHost(), getPort(), getTimeout());
log.debug("BES Client started. (id:{})",besClient.getID());
}
catch (PPTException ppte){
clientCheckOutFlag.release(); // Release the client permit because this client is hosed...
String msg ="BES Client Failed To Start. Message: '" + ppte.getMessage()+"' ";
besClient.setID(new Date().toString() + msg);
log.error(msg);
throw new PPTException(msg,ppte);
}
// Add it to the client pool
try {
clientsMapLock.lock();
String clientId = (getNickName()==null?getPrefix():getNickName());
if(clientId.isEmpty())
clientId = "besC";
clientId += "-" + totalClients;
besClient.setID(clientId);
clientsMap.put(clientId, besClient);
totalClients++;
log.debug("New BES Client assigned ID: {}", besClient.getID());
} finally {
clientsMapLock.unlock();
}
return besClient;
}
/**
* When a piece of code is done using an OPeNDAPClient, it should return it
* to the pool using this method.
*
* @param dapClient The OPeNDAPClient to return to the client pool.
* @param discard Pitch it, it's broken.
* @throws PPTException .
*/
public void returnClient(OPeNDAPClient dapClient, boolean discard) throws PPTException {
if (dapClient == null)
return;
try {
if (discard) {
discardClient(dapClient);
} else {
checkInClient(dapClient);
}
} catch (PPTException e) {
String msg = "Problem with OPeNDAPClient, discarding.";
log.error(msg);
try {
clientsMapLock.lock();
clientsMap.remove(dapClient.getID());
} finally {
clientsMapLock.unlock();
}
throw new PPTException(msg, e);
} finally {
clientCheckOutFlag.release();
}
}
private void checkInClient(OPeNDAPClient dapClient) throws PPTException {
if (config.getMaxCommands() > 0 && dapClient.getCommandCount() > config.getMaxCommands()) {
discardClient(dapClient);
if(log.isDebugEnabled()) {
String msg = "checkInClient() This instance of OPeNDAPClient (id:" +
dapClient.getID() + ") has " +
"excecuted " + dapClient.getCommandCount() +
" commands which is in excess of the maximum command " +
"limit of " + config.getMaxCommands() + ", discarding client.";
log.debug(msg);
}
} else {
if (clientQueue.offer(dapClient)) {
log.debug("Returned OPeNDAPClient (id:{}) to Client Pool.", dapClient.getID());
} else {
log.error("OUCH! OUCH! OUCH! The Pool is " +
"full and I need to check in a client! This Should " +
"NEVER Happen!");
}
}
}
private void discardClient(OPeNDAPClient dapClient) throws PPTException {
// By failing to put the client into the queue and
// removing the client from the clientsMap Map the client is
// discarded.
if(dapClient != null){
log.debug("Discarding OPeNDAPClient (id:{})", dapClient.getID());
try {
clientsMapLock.lock();
if (dapClient.getID() != null)
clientsMap.remove(dapClient.getID());
} finally {
clientsMapLock.unlock();
}
if (dapClient.isRunning()) {
shutdownClient(dapClient);
}
}
else {
log.error("Received a null valued OPeNDAPClient reference.");
}
}
private void shutdownClient(OPeNDAPClient oc) {
try {
log.debug("Shutting down client...");
oc.shutdownClient();
log.debug("Client shutdown.");
} catch (PPTException e) {
log.error("Failed to shutdown OPeNDAPClient (id:{}) msg: {}",oc.getID(), e.getMessage());
}
}
/**
* This method is meant to be called at program exit. It waits until all
* clientsMap are checked into the pool and then gracefully shuts down each
* client's connection to the BES.
*/
public void destroy() {
boolean nicely = false;
boolean gotClientCheckoutLock = false;
try {
if (clientCheckoutLock.tryLock(10, TimeUnit.SECONDS)) {
gotClientCheckoutLock = true;
log.debug("Attempting to acquire all client permits...");
if (clientCheckOutFlag.tryAcquire(getMaxClients(), 10, TimeUnit.SECONDS)) {
log.debug("All {} client permits acquired.",getMaxClients());
log.debug("There are {} client(s) to shutdown.", clientQueue.size());
int i = 0;
while (!clientQueue.isEmpty()) {
OPeNDAPClient odc = clientQueue.take();
log.debug("Retrieved OPeNDAPClient[{}] (id:{}) from queue.",i++,odc.getID());
shutdownClient(odc);
}
clientCheckOutFlag.release(getMaxClients());
nicely = true;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("OUCH! Interrupted while shutting down BESPool", e);
} finally {
if (gotClientCheckoutLock)
clientCheckoutLock.unlock();
}
if (!nicely) {
log.debug("Timed Out. Destroying BES Clients.");
try {
clientsMapLock.lock();
for (OPeNDAPClient oc: clientsMap.values()) {
if (oc != null) {
log.debug("Killing BES Client (id:{})", oc.getID());
oc.killClient();
} else {
log.error("Retrieved a 'null' BES Client instance from clientsMap collection!");
}
}
} finally {
clientsMapLock.unlock();
}
}
}
} |
package openccsensors.common.helper;
import java.util.HashMap;
import java.util.Map;
import openccsensors.common.core.OCSLog;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import forestry.api.*;// f the police
import forestry.api.apiculture.IAlleleBeeSpecies;
import forestry.api.apiculture.IBee;
import forestry.api.apiculture.IBeeGenome;
import forestry.api.apiculture.IBeeInterface;
public class InventoryHelper {
public static Map invToMap(IInventory inventory) {
HashMap map = new HashMap();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
map.put(i + 1, itemstackToMap(inventory.getStackInSlot(i)));
}
return map;
}
public static Map itemstackToMap(ItemStack itemstack) {
HashMap map = new HashMap();
if (itemstack == null) {
map.put("Name", "empty");
map.put("Size", 0);
map.put("Damagevalue", 0);
map.put("MaxStack", 64);
return map; // empty item
}
else{
Item item = itemstack.getItem();
map.put("Name", InventoryHelper.getNameForItemStack(itemstack));
map.put("RawName", InventoryHelper.getRawNameForStack(itemstack));
map.put("Size", itemstack.stackSize);
map.put("DamageValue", itemstack.getItemDamage());
map.put("MaxStack", itemstack.getMaxStackSize());
if(BeeHelper.isBee(itemstack)){
try{
map = BeeHelper.beeMap(itemstack, map);
}catch(Exception e){}
}
}
/*
* temporarily disabled if (itemstack.hasTagCompound()) { map.put("nbt",
* NetworkHelper.NBTToMap(itemstack.getTagCompound())); }
*/
return map;
}
public static String getNameForItemStack(ItemStack is) {
String name = "Unknown";
try {
name = is.getDisplayName();
}catch(Exception e) {
try {
name = is.getItemName();
}catch(Exception e2) {
}
}
return name;
}
public static String getRawNameForStack(ItemStack is) {
String rawName = "unknown";
try {
rawName = is.getItemName().toLowerCase();
}catch(Exception e) {
}
try {
if (rawName.length() - rawName.replaceAll("\\.", "").length() == 0) {
String packageName = is.getItem().getClass().getName().toLowerCase();
String[] packageLevels = packageName.split("\\.");
if (!rawName.startsWith(packageLevels[0]) && packageLevels.length > 1) {
rawName = packageLevels[0] + "." + rawName;
}
}
}catch(Exception e) {
}
return rawName;
}
} |
package com.jaamsim.render;
//import com.jaamsim.math.*;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.nio.IntBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.media.nativewindow.NativeWindowFactory;
import javax.media.opengl.DebugGL4bc;
import javax.media.opengl.GL;
import javax.media.opengl.GL2GL3;
import javax.media.opengl.GL3;
import javax.media.opengl.GL4bc;
import javax.media.opengl.GLAnimatorControl;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLException;
import javax.media.opengl.GLProfile;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.MeshFiles.MeshData;
import com.jaamsim.font.OverlayString;
import com.jaamsim.font.TessFont;
import com.jaamsim.math.AABB;
import com.jaamsim.math.Color4d;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.render.util.ExceptionLogger;
import com.jaamsim.ui.LogBox;
import com.jogamp.common.util.VersionNumber;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.event.WindowListener;
import com.jogamp.newt.event.WindowUpdateEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.sandwell.JavaSimulation.ColourInput;
/**
* The central renderer for JaamSim Renderer, Contains references to all context
* specific data (like shader caches)
*
* @author Matt.Chudleigh
*
*/
public class Renderer implements GLAnimatorControl {
public enum ShaderHandle {
FONT, HULL, OVERLAY_FONT, OVERLAY_FLAT, DEBUG, SKYBOX
}
static private Object idLock = new Object();
static private int nextID = 1;
/**
* Get a system wide unique ID
* @return
*/
public static int getAssetID() {
synchronized(idLock) {
return nextID++;
}
}
private static boolean USE_DEBUG_GL = true;
public static int DIFF_TEX_FLAG = 1;
public static int NUM_MESH_SHADERS = 2; // Should be 2^(max_flag)
private EnumMap<ShaderHandle, Shader> shaders;
private Shader[] meshShaders = new Shader[NUM_MESH_SHADERS];
private GLContext sharedContext = null;
Map<Integer, Integer> sharedVaoMap = new HashMap<Integer, Integer>();
int sharedContextID = getAssetID();
GLWindow dummyWindow;
private GLCapabilities caps = null;
private TexCache texCache = new TexCache(this);
// An initalization time flag specifying if the 'safest' graphical techniques should be used
private boolean safeGraphics;
private final Thread renderThread;
private final Object rendererLock = new Object();
private final Map<MeshProtoKey, MeshProto> protoCache;
private final Map<TessFontKey, TessFont> fontCache;
private final HashMap<Integer, RenderWindow> openWindows;
private final HashMap<Integer, Camera> cameras;
private final Queue<RenderMessage> renderMessages = new ArrayDeque<RenderMessage>();
private final AtomicBoolean displayNeeded = new AtomicBoolean(true);
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final AtomicBoolean fatalError = new AtomicBoolean(false);
private String errorString; // This is the string that caused the fatal error
private StackTraceElement[] fatalStackTrace; // the stack trace from the fatal error
private final ExceptionLogger exceptionLogger;
private TessFontKey defaultFontKey = new TessFontKey(Font.SANS_SERIF, Font.PLAIN);
private TessFontKey defaultBoldFontKey = new TessFontKey(Font.SANS_SERIF, Font.BOLD);
private final Object sceneLock = new Object();
private ArrayList<RenderProxy> proxyScene = new ArrayList<RenderProxy>();
private boolean allowDelayedTextures;
private double sceneTimeMS;
private double loopTimeMS;
private final Object settingsLock = new Object();
private boolean showDebugInfo = false;
private long usedVRAM = 0;
// A flag to track JOGL's GLAnimatorControl pause feature
private boolean isPaused = false;
// This may not be the best way to cache this
private GLContext drawContext = null;
private Skybox skybox;
private MeshData badData;
private MeshProto badProto;
// A cache of the current scene, needed by the individual windows to render
private ArrayList<Renderable> currentScene = new ArrayList<Renderable>();
private ArrayList<OverlayRenderable> currentOverlay = new ArrayList<OverlayRenderable>();
public Renderer(boolean safeGraphics) throws RenderException {
this.safeGraphics = safeGraphics;
protoCache = new HashMap<MeshProtoKey, MeshProto>();
fontCache = new HashMap<TessFontKey, TessFont>();
exceptionLogger = new ExceptionLogger(1); // Print the call stack on the first exception of any kind
openWindows = new HashMap<Integer, RenderWindow>();
cameras = new HashMap<Integer, Camera>();
renderThread = new Thread(new Runnable() {
@Override
public void run() {
mainRenderLoop();
}
}, "RenderThread");
renderThread.start();
}
private void mainRenderLoop() {
//long startNanos = System.nanoTime();
try {
// GLProfile.initSingleton();
GLProfile glp = GLProfile.get(GLProfile.GL2GL3);
caps = new GLCapabilities(glp);
caps.setSampleBuffers(true);
caps.setNumSamples(4);
caps.setDepthBits(24);
// Create a dummy window
dummyWindow = GLWindow.create(caps);
dummyWindow.setSize(128, 128);
dummyWindow.setPosition(-2000, -2000);
// This is unfortunately necessary due to JOGL's (newt's?) involved
// startup code
// I can not find a way to make a context valid without a visible window
dummyWindow.setVisible(true);
sharedContext = dummyWindow.getContext();
assert (sharedContext != null);
dummyWindow.setVisible(false);
// long endNanos = System.nanoTime();
// long ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("Creating shared context at:" + ms + "ms");
checkForIntelDriver();
initSharedContext();
// Notify the main thread we're done
synchronized (initialized) {
initialized.set(true);
initialized.notifyAll();
}
} catch (Exception e) {
fatalError.set(true);
errorString = e.getLocalizedMessage();
fatalStackTrace = e.getStackTrace();
LogBox.renderLog("Renderer encountered a fatal error:");
LogBox.renderLogException(e);
} finally {
if (sharedContext != null && sharedContext.isCurrent())
sharedContext.release();
}
// endNanos = System.nanoTime();
// ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("Started renderer loop after:" + ms + "ms");
long lastLoopEnd = System.nanoTime();
// Add a custom shutdown hook to make sure we're finished closing before JOGL tries to shutdown
NativeWindowFactory.addCustomShutdownHook(true, new Runnable() {
@Override
public void run() {
// Block JOGL shutting down until we're dead
shutdown();
while (renderThread.isAlive()) {
synchronized (this) {
try {
queueRedraw(); // Just in case the render thread got stalled somewhere
wait(50);
} catch (InterruptedException ex) {}
}
}
}
});
while (!shutdown.get()) {
try {
// If a fatal error was encountered, clean up the renderer
if (fatalError.get()) {
// We should clean up everything we can, then die
try {
for (Entry<Integer, RenderWindow> entry : openWindows.entrySet()){
entry.getValue().getGLWindowRef().destroy();
entry.getValue().getAWTFrameRef().dispose();
}
} catch(Exception e) {} // Ignore any exceptions, this is just a best effort cleanup
try {
dummyWindow.destroy();
sharedContext.destroy();
dummyWindow = null;
sharedContext = null;
openWindows.clear();
currentScene = null;
currentOverlay = null;
caps = null;
fontCache.clear();
protoCache.clear();
shaders.clear();
} catch (Exception e) { }
break; // Exiting the loop will end the thread
}
// Run all render messages
RenderMessage message;
boolean moreMessages = false;
do {
// Only lock the queue while reading messages, release it while
// processing them
message = null;
synchronized (renderMessages) {
if (!renderMessages.isEmpty()) {
message = renderMessages.remove();
moreMessages = !renderMessages.isEmpty();
}
}
if (message != null) {
try {
handleMessage(message);
} catch (Throwable t) {
// Log this error but continue processing
logException(t);
}
}
} while (moreMessages);
if (displayNeeded.compareAndSet(true, false)) {
updateRenderableScene();
// Defensive copy the window list (in case a window is closed while we render)
HashMap<Integer, RenderWindow> winds;
synchronized (openWindows) {
winds = new HashMap<Integer, RenderWindow>(openWindows);
}
if (!isPaused) {
for (RenderWindow wind : winds.values()) {
try {
GLContext context = wind.getGLWindowRef().getContext();
if (context != null && !shutdown.get())
{
wind.getGLWindowRef().display();
}
} catch (Throwable t) {
// Log it, but move on to the other windows
logException(t);
}
}
}
}
long loopEnd = System.nanoTime();
loopTimeMS = (loopEnd - lastLoopEnd) / 1000000;
lastLoopEnd = loopEnd;
try {
synchronized (displayNeeded) {
if (!displayNeeded.get()) {
displayNeeded.wait();
}
}
} catch (InterruptedException e) {
// Let's loop anyway...
}
} catch (Throwable t) {
// Any other unexpected exceptions...
logException(t);
}
}
}
/**
* Returns the shader object for this handle, should only be called from the render thread (during a render)
* @param h
* @return
*/
public Shader getShader(ShaderHandle h) {
return shaders.get(h);
}
public Shader getMeshShader(int flags) {
assert(flags < NUM_MESH_SHADERS);
return meshShaders[flags];
}
/**
* Returns the MeshProto for the supplied key, should only be called from the render thread (during a render)
* @param key
* @return
*/
public MeshProto getProto(MeshProtoKey key) {
MeshProto proto = protoCache.get(key);
if (proto == null) {
// This prototype needs to be lazily loaded
loadMeshProtoImp(key);
}
return protoCache.get(key);
}
public TessFont getTessFont(TessFontKey key) {
if (!fontCache.containsKey(key)) {
loadTessFontImp(key); // Try lazy initialization for now
}
return fontCache.get(key);
}
public void setScene(ArrayList<RenderProxy> scene) {
synchronized (sceneLock) {
proxyScene = scene;
}
}
public void queueRedraw() {
synchronized(displayNeeded) {
displayNeeded.set(true);
displayNeeded.notifyAll();
}
}
private void addRenderMessage(RenderMessage msg) {
synchronized(renderMessages) {
renderMessages.add(msg);
queueRedraw();
}
}
public void setCameraInfoForWindow(int windowID, CameraInfo info) {
synchronized (renderMessages) {
addRenderMessage(new SetCameraMessage(windowID, info));
}
}
private void setCameraInfoImp(SetCameraMessage mes) {
synchronized (openWindows) {
Camera cam = cameras.get(mes.windowID);
if (cam == null) {
// Bad windowID
throw new RuntimeException("Bad window ID");
}
cam.setInfo(mes.cameraInfo);
}
}
/**
* Call this from any thread to shutdown the Renderer, will return
* immediately but the renderer will shutdown after the next redraw
*/
public void shutdown() {
shutdown.set(true);
queueRedraw();
}
public GL2GL3 getGL() {
return drawContext.getGL().getGL2GL3();
}
/**
* Get a list of all the IDs of currently open windows
* @return
*/
public ArrayList<Integer> getOpenWindowIDs() {
synchronized(openWindows) {
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int id : openWindows.keySet()) {
ret.add(id);
}
return ret;
}
}
public String getWindowName(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return null;
}
return win.getName();
}
}
public Frame getAWTFrame(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return null;
}
return win.getAWTFrameRef();
}
}
public void focusWindow(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return;
}
win.getAWTFrameRef().setExtendedState(Frame.NORMAL);
win.getAWTFrameRef().toFront();
}
}
/**
* Construct a new window (a NEWT window specifically)
*
* @param width
* @param height
* @return
*/
private void createWindowImp(CreateWindowMessage message) {
RenderGLListener listener = new RenderGLListener();
RenderWindow window = new RenderWindow(message.x, message.y,
message.width, message.height,
message.title, message.name,
sharedContext,
caps, listener,
message.icon,
message.windowID,
message.viewID,
message.listener);
listener.setWindow(window);
Camera camera = new Camera(Math.PI/3.0, 1, 0.1, 1000);
synchronized (openWindows) {
openWindows.put(message.windowID, window);
cameras.put(message.windowID, camera);
}
window.getGLWindowRef().setAnimator(this);
GLWindowListener wl = new GLWindowListener(window.getWindowID());
window.getGLWindowRef().addWindowListener(wl);
window.getAWTFrameRef().addComponentListener(wl);
window.getGLWindowRef().addMouseListener(new MouseHandler(window, message.listener));
window.getGLWindowRef().addKeyListener(message.listener);
window.getAWTFrameRef().setVisible(true);
queueRedraw();
}
public int createWindow(int x, int y, int width, int height, int viewID, String title, String name, Image icon,
WindowInteractionListener listener) {
synchronized (renderMessages) {
int windowID = getAssetID();
addRenderMessage(new CreateWindowMessage(x, y, width, height, title,
name, windowID, viewID, icon, listener));
return windowID;
}
}
public void setWindowDebugInfo(int windowID, String debugString, ArrayList<Long> debugIDs) {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w != null) {
w.setDebugString(debugString);
w.setDebugIDs(debugIDs);
}
}
}
public void closeWindow(int windowID) {
synchronized (renderMessages) {
addRenderMessage(new CloseWindowMessage(windowID));
}
}
private void closeWindowImp(CloseWindowMessage msg) {
RenderWindow window;
synchronized(openWindows) {
window = openWindows.get(msg.windowID);
if (window == null) {
return;
}
}
windowCleanup(msg.windowID);
window.getGLWindowRef().destroy();
window.getAWTFrameRef().dispose();
}
private String readSource(String file) {
URL res = Renderer.class.getResource(file);
StringBuilder source = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(res.openStream()));
while (true) {
String line = reader.readLine();
if (line == null) break;
source.append(line).append("\n");
}
reader.close();
reader = null;
}
catch (IOException e) {}
return source.toString();
}
private void createShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl) {
String vertsrc = readSource(vert);
String fragsrc = readSource(frag);
Shader s = new Shader(vertsrc, fragsrc, gl);
if (s.isGood()) {
shaders.put(sh, s);
return;
}
String failure = s.getFailureLog();
throw new RenderException("Shader failed: " + sh.toString() + " " + failure);
}
private void createCoreShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl, String version) {
String vertsrc = readSource(vert).replaceAll("@VERSION@", version);
String fragsrc = readSource(frag).replaceAll("@VERSION@", version);
Shader s = new Shader(vertsrc, fragsrc, gl);
if (s.isGood()) {
shaders.put(sh, s);
return;
}
String failure = s.getFailureLog();
throw new RenderException("Shader failed: " + sh.toString() + " " + failure);
}
private String getMeshShaderDefines(int i) {
StringBuilder defines = new StringBuilder();
if ((i & DIFF_TEX_FLAG) != 0) {
defines.append("#define DIFF_TEX\n");
}
return defines.toString();
}
/**
* Create and compile all the shaders
*/
private void initShaders(GL2GL3 gl) throws RenderException {
shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class);
String vert, frag;
vert = "/resources/shaders/font.vert";
frag = "/resources/shaders/font.frag";
createShader(ShaderHandle.FONT, vert, frag, gl);
vert = "/resources/shaders/hull.vert";
frag = "/resources/shaders/hull.frag";
createShader(ShaderHandle.HULL, vert, frag, gl);
vert = "/resources/shaders/overlay-font.vert";
frag = "/resources/shaders/overlay-font.frag";
createShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl);
vert = "/resources/shaders/overlay-flat.vert";
frag = "/resources/shaders/overlay-flat.frag";
createShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl);
vert = "/resources/shaders/debug.vert";
frag = "/resources/shaders/debug.frag";
createShader(ShaderHandle.DEBUG, vert, frag, gl);
vert = "/resources/shaders/skybox.vert";
frag = "/resources/shaders/skybox.frag";
createShader(ShaderHandle.SKYBOX, vert, frag, gl);
String meshVertSrc = readSource("/resources/shaders/flat.vert");
String meshFragSrc = readSource("/resources/shaders/flat.frag");
// Create the mesh shaders
for (int i = 0; i < NUM_MESH_SHADERS; ++i) {
String defines = getMeshShaderDefines(i);
String definedFragSrc = meshFragSrc.replaceAll("@DEFINES@", defines);
Shader s = new Shader(meshVertSrc, definedFragSrc, gl);
if (!s.isGood()) {
String failure = s.getFailureLog();
throw new RenderException("Mesh Shader failed, flags: " + i + " " + failure);
}
meshShaders[i] = s;
}
}
/**
* Create and compile all the shaders
*/
private void initCoreShaders(GL2GL3 gl, String version) throws RenderException {
shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class);
String vert, frag;
vert = "/resources/shaders_core/font.vert";
frag = "/resources/shaders_core/font.frag";
createCoreShader(ShaderHandle.FONT, vert, frag, gl, version);
vert = "/resources/shaders_core/hull.vert";
frag = "/resources/shaders_core/hull.frag";
createCoreShader(ShaderHandle.HULL, vert, frag, gl, version);
vert = "/resources/shaders_core/overlay-font.vert";
frag = "/resources/shaders_core/overlay-font.frag";
createCoreShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl, version);
vert = "/resources/shaders_core/overlay-flat.vert";
frag = "/resources/shaders_core/overlay-flat.frag";
createCoreShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl, version);
vert = "/resources/shaders_core/debug.vert";
frag = "/resources/shaders_core/debug.frag";
createCoreShader(ShaderHandle.DEBUG, vert, frag, gl, version);
vert = "/resources/shaders_core/skybox.vert";
frag = "/resources/shaders_core/skybox.frag";
createCoreShader(ShaderHandle.SKYBOX, vert, frag, gl, version);
String meshVertSrc = readSource("/resources/shaders_core/flat.vert").replaceAll("@VERSION@", version);
String meshFragSrc = readSource("/resources/shaders_core/flat.frag").replaceAll("@VERSION@", version);
// Create the mesh shaders
for (int i = 0; i < NUM_MESH_SHADERS; ++i) {
String defines = getMeshShaderDefines(i);
String definedFragSrc = meshFragSrc.replaceAll("@DEFINES@", defines);
Shader s = new Shader(meshVertSrc, definedFragSrc, gl);
if (!s.isGood()) {
String failure = s.getFailureLog();
throw new RenderException("Mesh Shader failed, flags: " + i + " " + failure);
}
meshShaders[i] = s;
}
}
/**
* Basic message dispatch
*
* @param message
*/
private void handleMessage(RenderMessage message) {
assert (Thread.currentThread() == renderThread);
if (message instanceof CreateWindowMessage) {
createWindowImp((CreateWindowMessage) message);
return;
}
if (message instanceof SetCameraMessage) {
setCameraInfoImp((SetCameraMessage) message);
return;
}
if (message instanceof OffScreenMessage) {
offScreenImp((OffScreenMessage) message);
return;
}
if (message instanceof CloseWindowMessage) {
closeWindowImp((CloseWindowMessage) message);
return;
}
if (message instanceof CreateOffscreenTargetMessage) {
populateOffscreenTarget(((CreateOffscreenTargetMessage)message).target);
}
if (message instanceof FreeOffscreenTargetMessage) {
freeOffscreenTargetImp(((FreeOffscreenTargetMessage)message).target);
}
}
private void initSharedContext() {
assert (Thread.currentThread() == renderThread);
assert (drawContext == null);
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
if (USE_DEBUG_GL) {
sharedContext.setGL(new DebugGL4bc((GL4bc)sharedContext.getGL().getGL2GL3()));
}
LogBox.formatRenderLog("Found OpenGL version: %s", sharedContext.getGLVersion());
LogBox.formatRenderLog("Found GLSL: %s", sharedContext.getGLSLVersionString());
VersionNumber vn = sharedContext.getGLVersionNumber();
boolean isCore = sharedContext.isGLCoreProfile();
LogBox.formatRenderLog("OpenGL Major: %d Minor: %d IsCore:%s", vn.getMajor(), vn.getMinor(), isCore);
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
if (!isCore)
initShaders(gl);
else
initCoreShaders(gl, sharedContext.getGLSLVersionString());
// Sub system specific intitializations
DebugUtils.init(this, gl);
Polygon.init(this, gl);
MeshProto.init(this, gl);
texCache.init(gl);
// Load the bad mesh proto
badData = MeshDataCache.getBadMesh();
badProto = new MeshProto(badData, safeGraphics, !safeGraphics);
badProto.loadGPUAssets(gl, this);
skybox = new Skybox();
sharedContext.release();
}
private void loadMeshProtoImp(final MeshProtoKey key) {
//long startNanos = System.nanoTime();
assert(drawContext == null || !drawContext.isCurrent());
if (protoCache.get(key) != null) {
return; // This mesh has already been loaded
}
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
MeshProto proto;
MeshData data = MeshDataCache.getMeshData(key);
if (data == badData) {
proto = badProto;
} else {
proto = new MeshProto(data, safeGraphics, !safeGraphics);
assert (proto != null);
proto.loadGPUAssets(gl, this);
if (!proto.isLoadedGPU()) {
// This did not load cleanly, clear it out and use the default bad mesh asset
proto.freeResources(gl);
LogBox.formatRenderLog("Could not load GPU assset: %s\n", key.getURL().toString());
proto = badProto;
}
}
protoCache.put(key, proto);
sharedContext.release();
// long endNanos = System.nanoTime();
// long ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("LoadMeshProtoImp time:" + ms + "ms");
}
private void loadTessFontImp(TessFontKey key) {
if (fontCache.get(key) != null) {
return; // This font has already been loaded
}
TessFont tf = new TessFont(key);
fontCache.put(key, tf);
}
public int generateVAO(int contextID, GL2GL3 gl) {
assert(Thread.currentThread() == renderThread);
int[] vaos = new int[1];
gl.glGenVertexArrays(1, vaos, 0);
int vao = vaos[0];
synchronized(openWindows) {
RenderWindow wind = openWindows.get(contextID);
if (wind != null) {
wind.addVAO(vao);
}
}
return vao;
}
// Recreate the internal scene based on external input
private void updateRenderableScene() {
synchronized (sceneLock) {
long sceneStart = System.nanoTime();
currentScene = new ArrayList<Renderable>();
currentOverlay = new ArrayList<OverlayRenderable>();
for (RenderProxy proxy : proxyScene) {
proxy.collectRenderables(this, currentScene);
proxy.collectOverlayRenderables(this, currentOverlay);
}
long sceneTime = System.nanoTime() - sceneStart;
sceneTimeMS = sceneTime / 1000000.0;
}
}
public static class PickResult {
public double dist;
public long pickingID;
public PickResult(double dist, long pickingID) {
this.dist = dist;
this.pickingID = pickingID;
}
}
/**
* Cast the provided ray into the current scene and return the list of bounds collisions
* @param ray
* @return
*/
public List<PickResult> pick(Ray pickRay, int viewID, boolean precise) {
synchronized(openWindows) {
ArrayList<PickResult> ret = new ArrayList<PickResult>();
if (currentScene == null) {
return ret;
}
Camera cam = null;
for (RenderWindow wind : openWindows.values()) {
if (wind.getViewID() == viewID) {
cam = cameras.get(wind.getWindowID());
break;
}
}
if (cam == null) {
// Invalid view
return ret;
}
// Do not update the scene while a pick is underway
synchronized (sceneLock) {
for (Renderable r : currentScene) {
double rayDist = r.getCollisionDist(pickRay, precise);
if (rayDist >= 0.0) {
if (r.renderForView(viewID, cam)) {
ret.add(new PickResult(rayDist, r.getPickingID()));
}
}
}
return ret;
}
}
}
public static class WindowMouseInfo {
public int x, y;
public int width, height;
public int viewableX, viewableY;
public boolean mouseInWindow;
public CameraInfo cameraInfo;
}
/**
* Get Window specific information about the mouse. This is very useful for picking on the App side
* @param windowID
* @return
*/
public WindowMouseInfo getMouseInfo(int windowID) {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w == null) {
return null; // Not a valid window ID, or the window has closed
}
WindowMouseInfo info = new WindowMouseInfo();
info.x = w.getMouseX();
info.y = w.getMouseY();
info.width = w.getViewableWidth();
info.height = w.getViewableHeight();
info.viewableX = w.getViewableX();
info.viewableY = w.getViewableY();
info.mouseInWindow = w.isMouseInWindow();
info.cameraInfo = cameras.get(windowID).getInfo();
return info;
}
}
public CameraInfo getCameraInfo(int windowID) {
synchronized(openWindows) {
Camera cam = cameras.get(windowID);
if (cam == null) {
return null; // Not a valid window ID
}
return cam.getInfo();
}
}
// Common cleanup code for window closing. Applies to both user closed and programatically closed windows
private void windowCleanup(int windowID) {
RenderWindow w;
synchronized(openWindows) {
w = openWindows.get(windowID);
if (w == null) {
return;
}
openWindows.remove(windowID);
}
w.getAWTFrameRef().setVisible(false);
w.getGLWindowRef().destroy();
// Fire the window closing callback
w.getWindowListener().windowClosing();
}
private class GLWindowListener implements WindowListener, ComponentListener {
private int windowID;
public GLWindowListener(int id) {
windowID = id;
}
private WindowInteractionListener getListener() {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w == null) {
return null; // Not a valid window ID, or the window has closed
}
return w.getWindowListener();
}
}
@Override
public void windowDestroyNotify(WindowEvent we) {
windowCleanup(windowID);
}
@Override
public void windowDestroyed(WindowEvent arg0) {
}
@Override
public void windowGainedFocus(WindowEvent arg0) {
WindowInteractionListener listener = getListener();
if (listener != null) {
listener.windowGainedFocus();
}
}
@Override
public void windowLostFocus(WindowEvent arg0) {
}
@Override
public void windowMoved(WindowEvent arg0) {
}
@Override
public void windowRepaint(WindowUpdateEvent arg0) {
}
@Override
public void windowResized(WindowEvent arg0) {
}
private void updateWindowSizeAndPos() {
RenderWindow w;
synchronized(openWindows) {
w = openWindows.get(windowID);
if (w == null) {
return;
}
}
w.getWindowListener().windowMoved(w.getWindowX(), w.getWindowY(), w.getWindowWidth(), w.getWindowHeight());
}
@Override
public void componentHidden(ComponentEvent arg0) {
}
@Override
public void componentMoved(ComponentEvent arg0) {
updateWindowSizeAndPos();
}
@Override
public void componentResized(ComponentEvent arg0) {
updateWindowSizeAndPos();
}
@Override
public void componentShown(ComponentEvent arg0) {
}
}
private class RenderGLListener implements GLEventListener {
private RenderWindow window;
private long lastFrameNanos = 0;
public void setWindow(RenderWindow win) {
window = win;
}
@Override
public void init(GLAutoDrawable drawable) {
synchronized (rendererLock) {
// Per window initialization
if (USE_DEBUG_GL) {
drawable.setGL(new DebugGL4bc((GL4bc)drawable.getGL().getGL2GL3()));
}
GL2GL3 gl = drawable.getGL().getGL2GL3();
// Some of this is probably redundant, but here goes
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glClearDepth(1.0);
gl.glDepthFunc(GL2GL3.GL_LEQUAL);
gl.glEnable(GL2GL3.GL_CULL_FACE);
gl.glCullFace(GL2GL3.GL_BACK);
gl.glEnable(GL.GL_MULTISAMPLE);
gl.glBlendEquationSeparate(GL2GL3.GL_FUNC_ADD, GL2GL3.GL_MAX);
gl.glBlendFuncSeparate(GL2GL3.GL_SRC_ALPHA, GL2GL3.GL_ONE_MINUS_SRC_ALPHA, GL2GL3.GL_ONE, GL2GL3.GL_ONE);
}
}
@Override
public void dispose(GLAutoDrawable drawable) {
synchronized (rendererLock) {
GL2GL3 gl = drawable.getGL().getGL2GL3();
ArrayList<Integer> vaoArray = window.getVAOs();
int[] vaos = new int[vaoArray.size()];
int index = 0;
for (int vao : vaoArray) {
vaos[index++] = vao;
}
if (vaos.length > 0) {
gl.glDeleteVertexArrays(vaos.length, vaos, 0);
}
}
}
@Override
public void display(GLAutoDrawable drawable) {
synchronized (rendererLock) {
Camera cam = cameras.get(window.getWindowID());
// The ray of the current mouse position (or null if the mouse is not hovering over the window)
Ray pickRay = RenderUtils.getPickRay(getMouseInfo(window.getWindowID()));
PerfInfo pi = new PerfInfo();
long startNanos = System.nanoTime();
allowDelayedTextures = true;
// Cache the current scene. This way we don't need to lock it for the full render
ArrayList<Renderable> scene = new ArrayList<Renderable>(currentScene.size());
ArrayList<OverlayRenderable> overlay = new ArrayList<OverlayRenderable>(currentOverlay.size());
synchronized(sceneLock) {
scene.addAll(currentScene);
overlay.addAll(currentOverlay);
}
renderScene(drawable.getContext(), window.getWindowID(),
scene, overlay,
cam, window.getViewableWidth(), window.getViewableHeight(),
pickRay, window.getViewID(), pi);
GL2GL3 gl = drawable.getContext().getGL().getGL2GL3(); // Just to clean up the code below
boolean showDebug;
synchronized(settingsLock) {
showDebug = showDebugInfo;
}
if (showDebug) {
// Draw a window specific performance counter
gl.glDisable(GL2GL3.GL_DEPTH_TEST);
drawContext = drawable.getContext();
StringBuilder perf = new StringBuilder();
perf.append( String.format( "Objects Culled: %s", pi.objectsCulled) );
perf.append( String.format( " VRAM (MB): %.0f", usedVRAM/(1024.0*1024.0)) );
perf.append( String.format( " Frame time (ms): %.3f", lastFrameNanos/1000000.0) );
perf.append( String.format( " SceneTime (ms): %.3f", sceneTimeMS) );
perf.append( String.format( " Loop Time (ms): %.3f", loopTimeMS) );
TessFont defFont = getTessFont(defaultBoldFontKey);
OverlayString os = new OverlayString(defFont, perf.toString(), ColourInput.BLACK,
10, 10, 15, false, false, DisplayModel.ALWAYS);
os.render(window.getWindowID(), Renderer.this,
window.getViewableWidth(), window.getViewableHeight(), cam, null);
// Also draw this window's debug string
os = new OverlayString(defFont, window.getDebugString(), ColourInput.BLACK,
10, 10, 30, false, false, DisplayModel.ALWAYS);
os.render(window.getWindowID(), Renderer.this,
window.getViewableWidth(), window.getViewableHeight(), cam, null);
drawContext = null;
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
}
gl.glFinish();
long endNanos = System.nanoTime();
lastFrameNanos = endNanos - startNanos;
}
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height) {
//_window.resized(width, height);
Camera cam = cameras.get(window.getWindowID());
cam.setAspectRatio((double) width / (double) height);
}
}
/**
* Abstract base type for internal renderer messages
*/
private static class RenderMessage {
@SuppressWarnings("unused")
public long queueTime = System.nanoTime();
}
private static class CreateWindowMessage extends RenderMessage {
public int x, y;
public int width, height;
public String title, name;
public WindowInteractionListener listener;
public int windowID, viewID;
public Image icon;
public CreateWindowMessage(int x, int y, int width, int height, String title,
String name, int windowID, int viewID, Image icon, WindowInteractionListener listener) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.title = title;
this.name = name;
this.listener = listener;
this.windowID = windowID;
this.viewID = viewID;
this.icon = icon;
}
}
private static class SetCameraMessage extends RenderMessage {
public int windowID;
public CameraInfo cameraInfo;
public SetCameraMessage(int windowID, CameraInfo cameraInfo) {
this.windowID = windowID;
this.cameraInfo = cameraInfo;
}
}
private static class OffScreenMessage extends RenderMessage {
public ArrayList<RenderProxy> scene;
public int viewID;
public Camera cam;
public int width, height;
public Future<BufferedImage> result;
public OffscreenTarget target;
OffScreenMessage(ArrayList<RenderProxy> s, int vID, Camera c, int w, int h, Future<BufferedImage> r, OffscreenTarget t) {
scene = s; viewID = vID; cam = c; width = w; height = h; result = r;
target = t;
}
}
private static class CloseWindowMessage extends RenderMessage {
public int windowID;
public CloseWindowMessage(int id) {
windowID = id;
}
}
private static class CreateOffscreenTargetMessage extends RenderMessage {
public OffscreenTarget target;
}
private static class FreeOffscreenTargetMessage extends RenderMessage {
public OffscreenTarget target;
}
public TexCache getTexCache() {
return texCache;
}
public static boolean debugDrawHulls() {
return false;
}
public static boolean debugDrawAABBs() {
return false;
}
public static boolean debugDrawArmatures() {
return false;
}
public boolean isInitialized() {
return initialized.get() && !fatalError.get();
}
public boolean hasFatalError() {
return fatalError.get();
}
public String getErrorString() {
return errorString;
}
public StackTraceElement[] getFatalStackTrace() {
return fatalStackTrace;
}
public TessFontKey getDefaultFont() {
return defaultFontKey;
}
public boolean allowDelayedTextures() {
return allowDelayedTextures;
}
private void logException(Throwable t) {
exceptionLogger.logException(t);
// For now print a synopsis for all exceptions thrown
printExceptionLog();
LogBox.renderLogException(t);
}
private void printExceptionLog() {
LogBox.renderLog("Exceptions from Renderer: ");
exceptionLogger.printExceptionLog();
LogBox.renderLog("");
}
/**
* Queue up an off screen rendering
* @param scene
* @param cam
* @param width
* @param height
* @return
*/
public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, int viewID, CameraInfo camInfo,
int width, int height, Runnable runWhenDone, OffscreenTarget target) {
Future<BufferedImage> result = new Future<BufferedImage>(runWhenDone);
Camera cam = new Camera(camInfo, (double)width/(double)height);
synchronized (renderMessages) {
addRenderMessage(new OffScreenMessage(scene, viewID, cam, width, height, result, target));
}
queueRedraw();
return result;
}
public OffscreenTarget createOffscreenTarget(int width, int height) {
OffscreenTarget ret = new OffscreenTarget(width, height);
synchronized (renderMessages) {
CreateOffscreenTargetMessage msg = new CreateOffscreenTargetMessage();
msg.target = ret;
addRenderMessage(msg);
}
return ret;
}
public void freeOffscreenTarget(OffscreenTarget target) {
synchronized (renderMessages) {
FreeOffscreenTargetMessage msg = new FreeOffscreenTargetMessage();
msg.target = target;
addRenderMessage(msg);
}
}
/**
* Create the resources for an OffscreenTarget
*/
private void populateOffscreenTarget(OffscreenTarget target) {
int width = target.getWidth();
int height = target.getHeight();
sharedContext.makeCurrent();
GL3 gl = sharedContext.getGL().getGL3(); // Just to clean up the code below
// This does not support opengl 3, so for now we don't support off screen rendering
if (gl == null) {
sharedContext.release();
return;
}
// Create a new frame buffer for this draw operation
int[] temp = new int[2];
gl.glGenFramebuffers(2, temp, 0);
int drawFBO = temp[0];
int blitFBO = temp[1];
gl.glGenTextures(2, temp, 0);
int drawTex = temp[0];
int blitTex = temp[1];
gl.glGenRenderbuffers(1, temp, 0);
int depthBuf = temp[0];
gl.glBindTexture(GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex);
gl.glTexImage2DMultisample(GL3.GL_TEXTURE_2D_MULTISAMPLE, 4, GL2GL3.GL_RGBA8, width, height, true);
gl.glBindRenderbuffer(GL2GL3.GL_RENDERBUFFER, depthBuf);
gl.glRenderbufferStorageMultisample(GL2GL3.GL_RENDERBUFFER, 4, GL2GL3.GL_DEPTH_COMPONENT, width, height);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, drawFBO);
gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex, 0);
gl.glFramebufferRenderbuffer(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_DEPTH_ATTACHMENT, GL2GL3.GL_RENDERBUFFER, depthBuf);
int fbStatus = gl.glCheckFramebufferStatus(GL2GL3.GL_FRAMEBUFFER);
assert(fbStatus == GL2GL3.GL_FRAMEBUFFER_COMPLETE);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, blitTex);
gl.glTexImage2D(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_RGBA8, width, height,
0, GL2GL3.GL_RGBA, GL2GL3.GL_BYTE, null);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, blitFBO);
gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D, blitTex, 0);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, 0);
target.load(drawFBO, drawTex, depthBuf, blitFBO, blitTex);
sharedContext.release();
}
private void freeOffscreenTargetImp(OffscreenTarget target) {
if (!target.isLoaded()) {
return; // Nothing to free
}
sharedContext.makeCurrent();
GL2GL3 gl = sharedContext.getGL().getGL2GL3(); // Just to clean up the code below
int[] temp = new int[2];
temp[0] = target.getDrawFBO();
temp[1] = target.getBlitFBO();
gl.glDeleteFramebuffers(2, temp, 0);
temp[0] = target.getDrawTex();
temp[1] = target.getBlitTex();
gl.glDeleteTextures(2, temp, 0);
temp[0] = target.getDepthBuffer();
gl.glDeleteRenderbuffers(1, temp, 0);
target.free();
sharedContext.release();
}
private void offScreenImp(OffScreenMessage message) {
synchronized(rendererLock) {
try {
boolean isTempTarget;
OffscreenTarget target;
if (message.target == null) {
isTempTarget = true;
target = new OffscreenTarget(message.width, message.height);
populateOffscreenTarget(target);
} else {
isTempTarget = false;
target = message.target;
assert(target.getWidth() == message.width);
assert(target.getHeight() == message.height);
}
int width = message.width;
int height = message.height;
if (!target.isLoaded()) {
message.result.setFailed("Contexted not loaded. Is OpenGL 3 supported?");
return;
}
assert(target.isLoaded());
// Collect the renderables
ArrayList<Renderable> renderables;
ArrayList<OverlayRenderable> overlay;
if (message.scene != null) {
renderables = new ArrayList<Renderable>();
overlay = new ArrayList<OverlayRenderable>();
for (RenderProxy p : message.scene) {
p.collectRenderables(this, renderables);
p.collectOverlayRenderables(this, overlay);
}
} else {
// Use the current current scene if one is not provided
synchronized(sceneLock) {
renderables = new ArrayList<Renderable>(currentScene);
overlay = new ArrayList<OverlayRenderable>(currentOverlay);
}
}
sharedContext.makeCurrent();
GL2GL3 gl = sharedContext.getGL().getGL2GL3(); // Just to clean up the code below
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getDrawFBO());
gl.glClearColor(0, 0, 0, 0);
gl.glViewport(0, 0, width, height);
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
gl.glDepthFunc(GL2GL3.GL_LEQUAL);
allowDelayedTextures = false;
PerfInfo perfInfo = new PerfInfo();
// Okay, now actually render this thing...
renderScene(sharedContext, sharedContextID, renderables, overlay, message.cam,
width, height, null, message.viewID, perfInfo);
gl.glFinish();
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getBlitFBO());
gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, target.getDrawFBO());
gl.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL2GL3.GL_COLOR_BUFFER_BIT, GL2GL3.GL_NEAREST);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, target.getBlitTex());
IntBuffer pixels = target.getPixelBuffer();
gl.glGetTexImage(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_BGRA, GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV, pixels);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, 0);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int h = 0; h < height; ++h) {
// Set this one scan line at a time, in the opposite order as java is y down
img.setRGB(0, h, width, 1, pixels.array(), (height - 1 - h) * width, width);
}
message.result.setComplete(img);
// Clean up
gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0);
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0);
if (isTempTarget) {
freeOffscreenTargetImp(target);
}
} catch (GLException ex){
message.result.setFailed(ex.getMessage());
} finally {
if (sharedContext.isCurrent())
sharedContext.release();
}
} // synchronized(_rendererLock)
}
/**
* Returns true if the current thread is this renderer's render thread
* @return
*/
public boolean isRenderThread() {
return (Thread.currentThread() == renderThread);
}
private static class PerfInfo {
public int objectsCulled = 0;
}
private static class TransSortable implements Comparable<TransSortable> {
public Renderable r;
public double dist;
@Override
public int compareTo(TransSortable o) {
// Sort such that largest distance sorts to front of list
// by reversing argument order in compare.
return Double.compare(o.dist, this.dist);
}
}
private void renderScene(GLContext context, int contextID,
List<Renderable> scene, List<OverlayRenderable> overlay,
Camera cam, int width, int height, Ray pickRay,
int viewID, PerfInfo perfInfo) {
final Vec4d viewDir = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
cam.getViewDir(viewDir);
final Vec3d temp = new Vec3d();
assert (drawContext == null);
drawContext = context;
GL2GL3 gl = drawContext.getGL().getGL2GL3(); // Just to clean up the code below
gl.glClear(GL2GL3.GL_COLOR_BUFFER_BIT
| GL2GL3.GL_DEPTH_BUFFER_BIT);
// The 'height' of a pixel 1 unit from the viewer
double unitPixelHeight = 2 * Math.tan(cam.getFOV()/2.0) / height;
ArrayList<TransSortable> transparents = new ArrayList<TransSortable>();
if (scene == null)
return;
for (Renderable r : scene) {
AABB bounds = r.getBoundsRef();
double dist = cam.distToBounds(bounds);
if (!r.renderForView(viewID, cam)) {
continue;
}
if (!cam.collides(bounds)) {
++perfInfo.objectsCulled;
continue;
}
double apparentSize = 2 * bounds.radius.mag3() / Math.abs(dist);
if (apparentSize < unitPixelHeight) {
// This object is too small to draw
++perfInfo.objectsCulled;
continue;
}
if (r.hasTransparent()) {
// Defer rendering of transparent objects
TransSortable ts = new TransSortable();
ts.r = r;
temp.set3(r.getBoundsRef().center);
temp.sub3(cam.getTransformRef().getTransRef());
ts.dist = temp.dot3(viewDir);
transparents.add(ts);
}
r.render(contextID, this, cam, pickRay);
}
gl.glEnable(GL2GL3.GL_BLEND);
gl.glDepthMask(false);
// Draw the skybox after
skybox.setTexture(cam.getInfoRef().skyboxTexture);
skybox.render(contextID, this, cam);
Collections.sort(transparents);
for (TransSortable ts : transparents) {
AABB bounds = ts.r.getBoundsRef();
if (!cam.collides(bounds)) {
++perfInfo.objectsCulled;
continue;
}
ts.r.renderTransparent(contextID, this, cam, pickRay);
}
gl.glDisable(GL2GL3.GL_BLEND);
gl.glDepthMask(true);
// Debug render AABBs
if (debugDrawAABBs())
{
Color4d yellow = new Color4d(1, 1, 0, 1.0d);
Color4d red = new Color4d(1, 0, 0, 1.0d);
for (Renderable r : scene) {
Color4d aabbColor = yellow;
if (pickRay != null && r.getBoundsRef().collisionDist(pickRay) > 0) {
aabbColor = red;
}
DebugUtils.renderAABB(contextID, this, r.getBoundsRef(), aabbColor, cam);
}
} // for renderables
// Now draw the overlay
gl.glDisable(GL2GL3.GL_DEPTH_TEST);
if (overlay != null) {
for (OverlayRenderable r : overlay) {
if (!r.renderForView(viewID, cam)) {
continue;
}
r.render(contextID, this, width, height, cam, pickRay);
}
}
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
gl.glBindVertexArray(0);
drawContext = null;
}
public void usingVRAM(long bytes) {
usedVRAM += bytes;
}
// Below are functions inherited from GLAnimatorControl
// the interface is a bit of a mess and there's a lot here we don't need
@Override
public long getFPSStartTime() {
// Not supported
assert(false);
return 0;
}
@Override
public float getLastFPS() {
// Not supported
return 0;
}
@Override
public long getLastFPSPeriod() {
// Not supported
return 0;
}
@Override
public long getLastFPSUpdateTime() {
// Not supported
return 0;
}
@Override
public float getTotalFPS() {
// Not supported
return 0;
}
@Override
public long getTotalFPSDuration() {
// Not supported
return 0;
}
@Override
public int getTotalFPSFrames() {
// Not supported
return 0;
}
@Override
public int getUpdateFPSFrames() {
// Not supported
return 0;
}
@Override
public void resetFPSCounter() {
// Not supported
}
@Override
public void setUpdateFPSFrames(int arg0, PrintStream arg1) {
// Not supported
}
@Override
public void add(GLAutoDrawable arg0) {
// Not supported
assert(false);
}
@Override
public Thread getThread() {
return renderThread;
}
@Override
public boolean isAnimating() {
queueRedraw();
return true;
}
@Override
public boolean isPaused() {
synchronized (rendererLock) { // Make sure we aren't currently rendering
return isPaused;
}
}
@Override
public boolean isStarted() {
return true;
}
@Override
public boolean pause() {
synchronized(rendererLock) {
isPaused = true;
return true;
}
}
@Override
public void remove(GLAutoDrawable arg0) {
// Not supported
assert(false);
}
@Override
public boolean resume() {
isPaused = false;
queueRedraw();
return true;
}
@Override
public boolean start() {
// Not supported
assert(false);
return false;
}
@Override
public boolean stop() {
// Not supported
assert(false);
return false;
}
private void checkForIntelDriver() {
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
String vendorString = gl.glGetString(GL2GL3.GL_VENDOR).toLowerCase();
boolean intelDriver = vendorString.indexOf("intel") != -1;
if (intelDriver) {
safeGraphics = true;
}
sharedContext.release();
}
public void setDebugInfo(boolean showDebug) {
synchronized(settingsLock) {
showDebugInfo = showDebug;
}
}
} |
package com.loomcom.symon;
import com.loomcom.symon.devices.Memory;
import com.loomcom.symon.exceptions.FifoUnderrunException;
import com.loomcom.symon.exceptions.MemoryAccessException;
import com.loomcom.symon.exceptions.MemoryRangeException;
import com.loomcom.symon.exceptions.SymonException;
import com.loomcom.symon.machines.Machine;
import com.loomcom.symon.ui.*;
import com.loomcom.symon.ui.Console;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Symon Simulator Interface and Control.
* <p/>
* This class provides a control and I/O system for the simulated 6502 system.
* It includes the simulated CPU itself, as well as 32KB of RAM, 16KB of ROM,
* and a simulated ACIA for serial I/O. The ACIA is attached to a dumb terminal
* with a basic 80x25 character display.
*/
public class Simulator {
// UI constants
private static final int DEFAULT_FONT_SIZE = 12;
private static final Font DEFAULT_FONT = new Font(Font.MONOSPACED, Font.PLAIN, DEFAULT_FONT_SIZE);
private static final int CONSOLE_BORDER_WIDTH = 10;
// Since it is very expensive to update the UI with Swing's Event Dispatch Thread, we can't afford
// to refresh the status view on every simulated clock cycle. Instead, we will only refresh the status view
// after this number of steps when running normally.
// Since we're simulating a 1MHz 6502 here, we have a 1 us delay between steps. Setting this to 20000
// should give us a status update about every 100 ms.
// TODO: Work around the event dispatch thread with custom painting code instead of relying on Swing.
private static final int MAX_STEPS_BETWEEN_UPDATES = 20000;
private final static Logger logger = Logger.getLogger(Simulator.class.getName());
// The simulated machine
private Machine machine;
// Number of CPU steps between CRT repaints.
// TODO: Dynamically refresh the value at runtime based on performance figures to reach ~ 30fps.
private long stepsBetweenCrtcRefreshes = 2500;
// A counter to keep track of the number of UI updates that have been
// requested
private int stepsSinceLastUpdate = 0;
private int stepsSinceLastCrtcRefresh = 0;
// The number of steps to run per click of the "Step" button
private int stepsPerClick = 1;
/**
* The Main Window is the primary control point for the simulator.
* It is in charge of the menu, and sub-windows. It also shows the
* CPU status at all times.
*/
private JFrame mainWindow;
/**
* The Trace Window shows the most recent 50,000 CPU states.
*/
private TraceLog traceLog;
/**
* The Memory Window shows the contents of one page of memory.
*/
private MemoryWindow memoryWindow;
private VideoWindow videoWindow;
private SimulatorMenu menuBar;
private RunLoop runLoop;
private Console console;
private StatusPanel statusPane;
private JButton runStopButton;
private JButton stepButton;
private JButton resetButton;
private JComboBox<String> stepCountBox;
private JFileChooser fileChooser;
private PreferencesDialog preferences;
private final Object commandMonitorObject = new Object();
private MAIN_CMD command = MAIN_CMD.NONE;
public static enum MAIN_CMD {
NONE,
SELECTMACHINE
}
/**
* The list of step counts that will appear in the "Step" drop-down.
*/
private static final String[] STEPS = {"1", "5", "10", "20", "50", "100"};
public Simulator(Class machineClass) throws Exception {
this.machine = (Machine) machineClass.getConstructors()[0].newInstance();
}
/**
* Display the main simulator UI.
*/
public void createAndShowUi() throws IOException {
mainWindow = new JFrame();
mainWindow.setTitle("Symon 6502 Simulator");
mainWindow.setResizable(false);
mainWindow.getContentPane().setLayout(new BorderLayout());
// UI components used for I/O.
this.console = new com.loomcom.symon.ui.Console(80, 25, DEFAULT_FONT);
this.statusPane = new StatusPanel();
console.setBorderWidth(CONSOLE_BORDER_WIDTH);
// File Chooser
fileChooser = new JFileChooser(System.getProperty("user.dir"));
preferences = new PreferencesDialog(mainWindow, true);
// Panel for Console and Buttons
JPanel consoleContainer = new JPanel();
JPanel buttonContainer = new JPanel();
consoleContainer.setLayout(new BorderLayout());
consoleContainer.setBorder(new EmptyBorder(10, 10, 10, 0));
buttonContainer.setLayout(new FlowLayout());
runStopButton = new JButton("Run");
stepButton = new JButton("Step");
resetButton = new JButton("Reset");
stepCountBox = new JComboBox<String>(STEPS);
stepCountBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
JComboBox cb = (JComboBox) actionEvent.getSource();
stepsPerClick = Integer.parseInt((String) cb.getSelectedItem());
} catch (NumberFormatException ex) {
stepsPerClick = 1;
stepCountBox.setSelectedIndex(0);
}
}
});
buttonContainer.add(runStopButton);
buttonContainer.add(stepButton);
buttonContainer.add(stepCountBox);
buttonContainer.add(resetButton);
// Left side - console
consoleContainer.add(console, BorderLayout.CENTER);
mainWindow.getContentPane().add(consoleContainer, BorderLayout.LINE_START);
// Right side - status pane
mainWindow.getContentPane().add(statusPane, BorderLayout.LINE_END);
// Bottom - buttons.
mainWindow.getContentPane().add(buttonContainer, BorderLayout.PAGE_END);
runStopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if (runLoop != null && runLoop.isRunning()) {
handleStop();
} else {
handleStart();
}
}
});
stepButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
handleStep(stepsPerClick);
}
});
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
handleReset(false);
}
});
// Prepare the log window
traceLog = new TraceLog();
// Prepare the memory window
memoryWindow = new MemoryWindow(machine.getBus());
// Composite Video and 6545 CRTC
if(machine.getCrtc() != null) {
videoWindow = new VideoWindow(machine.getCrtc(), 2, 2);
}
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// The Menu. This comes last, because it relies on other components having
// already been initialized.
menuBar = new SimulatorMenu();
mainWindow.setJMenuBar(menuBar);
mainWindow.pack();
mainWindow.setVisible(true);
console.requestFocus();
handleReset(false);
}
public MAIN_CMD waitForCommand() {
synchronized(commandMonitorObject) {
try {
commandMonitorObject.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
return command;
}
private void handleStart() {
// Shift focus to the console.
console.requestFocus();
// Spin up the new run loop
runLoop = new RunLoop();
runLoop.start();
traceLog.simulatorDidStart();
}
private void handleStop() {
runLoop.requestStop();
runLoop.interrupt();
runLoop = null;
}
/*
* Perform a reset.
*/
private void handleReset(boolean isColdReset) {
if (runLoop != null && runLoop.isRunning()) {
runLoop.requestStop();
runLoop.interrupt();
runLoop = null;
}
try {
logger.log(Level.INFO, "Reset requested. Resetting CPU.");
// Reset and clear memory
machine.getCpu().reset();
// Clear the console.
console.reset();
// Reset the trace log.
traceLog.reset();
// If we're doing a cold reset, clear the memory.
// TODO: Clear memory
// Update status.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState(machine.getCpu());
memoryWindow.updateState();
}
});
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Exception during simulator reset: " + ex.getMessage());
}
}
/**
* Step the requested number of times, and immediately refresh the UI.
*/
private void handleStep(int numSteps) {
try {
for (int i = 0; i < numSteps; i++) {
step();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (traceLog.isVisible()) {
traceLog.refresh();
}
statusPane.updateState(machine.getCpu());
memoryWindow.updateState();
}
});
} catch (SymonException ex) {
logger.log(Level.SEVERE, "Exception during simulator step: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
* Perform a single step of the simulated system.
*/
private void step() throws MemoryAccessException {
machine.getCpu().step();
traceLog.append(machine.getCpu().getCpuState());
// Read from the ACIA and immediately update the console if there's
// output ready.
if (machine.getAcia().hasTxChar()) {
// This is thread-safe
console.print(Character.toString((char) machine.getAcia().txRead()));
console.repaint();
}
// If a key has been pressed, fill the ACIA.
// TODO: Interrupt handling.
try {
if (console.hasInput()) {
machine.getAcia().rxWrite((int) console.readInputChar());
}
} catch (FifoUnderrunException ex) {
logger.severe("Console type-ahead buffer underrun!");
}
if (videoWindow != null && stepsSinceLastCrtcRefresh++ > stepsBetweenCrtcRefreshes) {
stepsSinceLastCrtcRefresh = 0;
}
// This is a very expensive update, and we're doing it without
// a delay, so we don't want to overwhelm the Swing event processing thread
// with requests. Limit the number of ui updates that can be performed.
if (stepsSinceLastUpdate++ > MAX_STEPS_BETWEEN_UPDATES) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState(machine.getCpu());
memoryWindow.updateState();
}
});
stepsSinceLastUpdate = 0;
}
}
/**
* Load a program into memory at the simulatorDidStart address.
*/
private void loadProgram(byte[] program, int startAddress) throws MemoryAccessException {
int addr = startAddress, i;
for (i = 0; i < program.length; i++) {
machine.getBus().write(addr++, program[i] & 0xff);
}
logger.log(Level.INFO, "Loaded " + i + " bytes at address 0x" +
Integer.toString(startAddress, 16));
// After loading, be sure to reset and
// Reset (but don't clear memory, naturally)
machine.getCpu().reset();
// Reset the stack program counter
machine.getCpu().setProgramCounter(preferences.getProgramStartAddress());
// Immediately update the UI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState(machine.getCpu());
memoryWindow.updateState();
}
});
}
/**
* The main run thread.
*/
class RunLoop extends Thread {
private boolean isRunning = false;
public boolean isRunning() {
return isRunning;
}
public void requestStop() {
isRunning = false;
}
public void run() {
logger.log(Level.INFO, "Starting main run loop.");
isRunning = true;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Don't allow step while the simulator is running
stepButton.setEnabled(false);
stepCountBox.setEnabled(false);
menuBar.simulatorDidStart();
// Toggle the state of the run button
runStopButton.setText("Stop");
}
});
try {
do {
step();
} while (shouldContinue());
} catch (SymonException ex) {
logger.log(Level.SEVERE, "Exception in main simulator run thread. Exiting run.");
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusPane.updateState(machine.getCpu());
memoryWindow.updateState();
runStopButton.setText("Run");
stepButton.setEnabled(true);
stepCountBox.setEnabled(true);
if (traceLog.isVisible()) {
traceLog.refresh();
}
menuBar.simulatorDidStop();
traceLog.simulatorDidStop();
// TODO: Update memory window, if frame is visible.
}
});
isRunning = false;
}
/**
* Returns true if the run loop should proceed to the next step.
*
* @return True if the run loop should proceed to the next step.
*/
private boolean shouldContinue() {
return isRunning && !(preferences.getHaltOnBreak() && machine.getCpu().getInstruction() == 0x00);
}
}
class LoadProgramAction extends AbstractAction {
public LoadProgramAction() {
super("Load Program...", null);
putValue(SHORT_DESCRIPTION, "Load a program into memory");
putValue(MNEMONIC_KEY, KeyEvent.VK_L);
}
public void actionPerformed(ActionEvent actionEvent) {
// TODO: Error dialogs on failure.
try {
int retVal = fileChooser.showOpenDialog(mainWindow);
if (retVal == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
if (f.canRead()) {
long fileSize = f.length();
if (fileSize > machine.getMemorySize()) {
throw new IOException("Program will not fit in available memory.");
} else {
byte[] program = new byte[(int) fileSize];
int i = 0;
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while (dis.available() != 0) {
program[i++] = dis.readByte();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.reset();
}
});
// Now load the program at the starting address.
loadProgram(program, preferences.getProgramStartAddress());
}
}
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to read program file: " + ex.getMessage());
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Memory access error loading program: " + ex.getMessage());
}
}
}
class LoadRomAction extends AbstractAction {
public LoadRomAction() {
super("Load ROM...", null);
putValue(SHORT_DESCRIPTION, "Load a ROM image");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
public void actionPerformed(ActionEvent actionEvent) {
// TODO: Error dialogs on failure.
try {
int retVal = fileChooser.showOpenDialog(mainWindow);
if (retVal == JFileChooser.APPROVE_OPTION) {
File romFile = fileChooser.getSelectedFile();
if (romFile.canRead()) {
long fileSize = romFile.length();
if (fileSize != machine.getRomSize()) {
throw new IOException("ROM file must be exactly " + String.valueOf(machine.getRomSize()) + " bytes.");
} else {
// Load the new ROM image
Memory rom = Memory.makeROM(machine.getRomBase(), machine.getRomBase() + machine.getRomSize() - 1, romFile);
machine.setRom(rom);
// Now, reset
machine.getCpu().reset();
logger.log(Level.INFO, "ROM File `" + romFile.getName() + "' loaded at " +
String.format("0x%04X", machine.getRomBase()));
}
}
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to read ROM file: " + ex.getMessage());
} catch (MemoryRangeException ex) {
logger.log(Level.SEVERE, "Memory range error while loading ROM file: " + ex.getMessage());
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Memory access error while loading ROM file: " + ex.getMessage());
}
}
}
class ShowPrefsAction extends AbstractAction {
public ShowPrefsAction() {
super("Preferences...", null);
putValue(SHORT_DESCRIPTION, "Show Preferences Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
}
public void actionPerformed(ActionEvent actionEvent) {
preferences.getDialog().setVisible(true);
}
}
class SelectMachineAction extends AbstractAction {
Simulator simulator;
public SelectMachineAction() {
super("Switch emulated machine...", null);
putValue(SHORT_DESCRIPTION, "Select the type of the machine to be emulated");
putValue(MNEMONIC_KEY, KeyEvent.VK_M);
}
public void actionPerformed(ActionEvent actionEvent) {
if(runLoop != null) {
runLoop.requestStop();
}
memoryWindow.dispose();
traceLog.dispose();
if(videoWindow != null) {
videoWindow.dispose();
}
mainWindow.dispose();
command = MAIN_CMD.SELECTMACHINE;
synchronized(commandMonitorObject) {
commandMonitorObject.notifyAll();
}
}
}
class QuitAction extends AbstractAction {
public QuitAction() {
super("Quit", null);
putValue(SHORT_DESCRIPTION, "Exit the Simulator");
putValue(MNEMONIC_KEY, KeyEvent.VK_Q);
}
public void actionPerformed(ActionEvent actionEvent) {
if (runLoop != null && runLoop.isRunning()) {
runLoop.requestStop();
runLoop.interrupt();
}
System.exit(0);
}
}
class SetFontAction extends AbstractAction {
private int size;
public SetFontAction(int size) {
super(Integer.toString(size) + " pt", null);
this.size = size;
putValue(SHORT_DESCRIPTION, "Set font to " + Integer.toString(size) + "pt.");
}
public void actionPerformed(ActionEvent actionEvent) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.setFont(new Font("Monospaced", Font.PLAIN, size));
mainWindow.pack();
}
});
}
}
class ToggleTraceWindowAction extends AbstractAction {
public ToggleTraceWindowAction() {
super("Trace Log", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Trace Log Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (traceLog) {
if (traceLog.isVisible()) {
traceLog.setVisible(false);
} else {
traceLog.refresh();
traceLog.setVisible(true);
}
}
}
}
class ToggleMemoryWindowAction extends AbstractAction {
public ToggleMemoryWindowAction() {
super("Memory Window", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Memory Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (memoryWindow) {
if (memoryWindow.isVisible()) {
memoryWindow.setVisible(false);
} else {
memoryWindow.setVisible(true);
}
}
}
}
class ToggleVideoWindowAction extends AbstractAction {
public ToggleVideoWindowAction() {
super("Video Window", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Video Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (videoWindow) {
if (videoWindow.isVisible()) {
videoWindow.setVisible(false);
} else {
videoWindow.setVisible(true);
}
}
}
}
class SimulatorMenu extends JMenuBar {
// Menu Items
private JMenuItem loadProgramItem;
private JMenuItem loadRomItem;
/**
* Create a new SimulatorMenu instance.
*/
public SimulatorMenu() {
initMenu();
}
/**
* Disable menu items that should not be available during simulator execution.
*/
public void simulatorDidStart() {
loadProgramItem.setEnabled(false);
loadRomItem.setEnabled(false);
}
/**
* Enable menu items that should be available while the simulator is stopped.
*/
public void simulatorDidStop() {
loadProgramItem.setEnabled(true);
loadRomItem.setEnabled(true);
}
private void initMenu() {
/*
* File Menu
*/
JMenu fileMenu = new JMenu("File");
loadProgramItem = new JMenuItem(new LoadProgramAction());
loadRomItem = new JMenuItem(new LoadRomAction());
JMenuItem prefsItem = new JMenuItem(new ShowPrefsAction());
JMenuItem selectMachineItem = new JMenuItem(new SelectMachineAction());
JMenuItem quitItem = new JMenuItem(new QuitAction());
fileMenu.add(loadProgramItem);
fileMenu.add(loadRomItem);
fileMenu.add(prefsItem);
fileMenu.add(selectMachineItem);
fileMenu.add(quitItem);
add(fileMenu);
/*
* View Menu
*/
JMenu viewMenu = new JMenu("View");
JMenu fontSubMenu = new JMenu("Console Font Size");
ButtonGroup fontSizeGroup = new ButtonGroup();
makeFontSizeMenuItem(10, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(11, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(12, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(13, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(14, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(15, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(16, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(17, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(18, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(19, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(20, fontSubMenu, fontSizeGroup);
viewMenu.add(fontSubMenu);
final JCheckBoxMenuItem showTraceLog = new JCheckBoxMenuItem(new ToggleTraceWindowAction());
// Un-check the menu item if the user closes the window directly
traceLog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showTraceLog.setSelected(false);
}
});
viewMenu.add(showTraceLog);
final JCheckBoxMenuItem showMemoryTable = new JCheckBoxMenuItem(new ToggleMemoryWindowAction());
// Un-check the menu item if the user closes the window directly
memoryWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showMemoryTable.setSelected(false);
}
});
viewMenu.add(showMemoryTable);
if(videoWindow != null) {
final JCheckBoxMenuItem showVideoWindow = new JCheckBoxMenuItem(new ToggleVideoWindowAction());
videoWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showVideoWindow.setSelected(false);
}
});
viewMenu.add(showVideoWindow);
}
add(viewMenu);
}
private void makeFontSizeMenuItem(int size, JMenu fontSubMenu, ButtonGroup group) {
Action action = new SetFontAction(size);
JCheckBoxMenuItem item = new JCheckBoxMenuItem(action);
item.setSelected(size == DEFAULT_FONT_SIZE);
fontSubMenu.add(item);
group.add(item);
}
}
} |
package org.appsroid.fxpro.library;
import android.app.ActivityManager;
import android.content.Context;
public class MemoryManagement {
/**
* Gets available memory to load image
*/
public static float free(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() - 24;
if (memoryClass < 1) memoryClass = 1;
return (float) memoryClass;
}
} |
package org.cleartk.srl.propbank;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.collection.CollectionReader_ImplBase;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.FileUtils;
import org.apache.uima.util.Progress;
import org.apache.uima.util.ProgressImpl;
import org.cleartk.ViewNames;
import org.cleartk.corpus.penntreebank.PennTreebankReader;
import org.cleartk.srl.propbank.util.Propbank;
import org.cleartk.util.ListSpecification;
import org.cleartk.util.UIMAUtil;
import org.cleartk.util.ViewURIUtil;
public class PropbankGoldReader extends CollectionReader_ImplBase {
/**
* "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_PROPBANK_FILE"
* is a required, single, string parameter that points to propbank data
* (e.g. "propbank-1.0/props.txt").
*/
public static final String PARAM_PROPBANK_FILE = "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_PROPBANK_FILE";
/**
*
* "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_PENNTREEBANK_DIRECTORY"
* is a required, single, string parameter that points to the PennTreebank
* corpus. The directory should contain subdirectories corresponding to the
* sections (e.g. "00", "01", etc.) That is, if a local copy of PennTreebank
* sits at C:\Data\PTB\wsj\mrg, then the the subdirectory
* C:\Data\PTB\wsj\mrg\00 should exist. There are 24 sections in PTB
* corresponding to the directories 00, 01, 02, ... 24.
*/
public static final String PARAM_PENNTREEBANK_DIRECTORY = "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_PENNTREEBANK_DIRECTORY";
/**
* "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_WSJ_SECTIONS" is a
* required, single, string parameter that determines which sections of WSJ
* will be used. The format allows for comma-separated section numbers and
* section ranges, for example "02,07-12,16".
*/
public static final String PARAM_WSJ_SECTIONS = "org.cleartk.srl.propbank.PropbankGoldReader.PARAM_WSJ_SECTIONS";
/**
* holds all of the propbank data from props.txt. One entry per line in the
* file
*/
protected LinkedList<String> propbankData;
protected File treebankDirectory;
protected LinkedList<File> treebankFiles;
protected int totalTreebankFiles = 0;
protected ListSpecification wsjSections;
@Override
public void initialize() throws ResourceInitializationException {
try {
this.wsjSections = new ListSpecification((String) UIMAUtil.getRequiredConfigParameterValue(
getUimaContext(), PARAM_WSJ_SECTIONS));
File propbankFile = new File((String) UIMAUtil.getRequiredConfigParameterValue(getUimaContext(), PARAM_PROPBANK_FILE));
BufferedReader reader = new BufferedReader(new FileReader(propbankFile));
propbankData = new LinkedList<String>();
String line;
while ((line = reader.readLine()) != null) {
propbankData.add(line);
}
Collections.sort(propbankData);
this.treebankFiles = new LinkedList<File>();
treebankDirectory = new File(((String) UIMAUtil.getRequiredConfigParameterValue(getUimaContext(), PARAM_PENNTREEBANK_DIRECTORY)));
//don't forget that the paths in props.txt have "wsj" in the name.
File wsjDirectory = new File(treebankDirectory, "wsj");
PennTreebankReader.collectSections(wsjDirectory, this.treebankFiles, this.wsjSections);
Collections.sort(treebankFiles);
this.totalTreebankFiles = treebankFiles.size();
super.initialize();
} catch (FileNotFoundException fnfe) {
throw new ResourceInitializationException(fnfe);
} catch (IOException ioe) {
throw new ResourceInitializationException(ioe);
}
}
/**
* Reads the next file and stores its text in <b>cas</b> as the
* "TreebankView" SOFA. Then stores the corresponding Propbank entries in
* the "PropbankView" SOFA.
*
* @param cas
*
* @throws IOException
* @throws CollectionException
*/
public void getNext(CAS cas) throws IOException, CollectionException {
JCas tbView, pbView;
try {
tbView = cas.createView(ViewNames.TREEBANK).getJCas();
pbView = cas.createView(ViewNames.PROPBANK).getJCas();
} catch (CASException ce) {
throw new CollectionException(ce);
}
File treebankFile = treebankFiles.removeFirst();
ViewURIUtil.setURI(cas, treebankFile.getPath());
StringBuffer propbankText = new StringBuffer();
/*
* The logic here is rather fragile and should be rewritten and/or unit tested.
* I changed the code so that the comparison is between the canonical paths. (PVO)
*/
while (propbankData.size() > 0) {
File nextPbFile = new File(treebankDirectory.getPath()
+ File.separator
+ Propbank.filenameFromString(propbankData.getFirst()))
.getCanonicalFile();
int c = treebankFile.getCanonicalFile().compareTo(nextPbFile);
if (c < 0) {
break;
} else if (c > 0) {
propbankData.removeFirst();
continue;
}
propbankText.append(propbankData.removeFirst() + "\n");
}
tbView.setSofaDataString(FileUtils.file2String(treebankFile), "text/plain");
pbView.setSofaDataString(propbankText.toString(), "text/plain");
}
public void close() throws IOException {
}
public Progress[] getProgress() {
return new Progress[] { new ProgressImpl(totalTreebankFiles
- treebankFiles.size(), totalTreebankFiles, Progress.ENTITIES) };
}
public boolean hasNext() throws IOException, CollectionException {
if (treebankFiles.size() > 0)
return true;
else
return false;
}
} |
package org.concord.datagraph.state;
import org.concord.data.state.OTDataProducer;
import org.concord.data.state.OTDataStore;
import org.concord.framework.otrunk.OTObjectInterface;
public interface OTDataGraphable extends OTObjectInterface
{
public static int DEFAULT_color = 0x00FF0000;
public int getColor();
public void setColor(int color);
public static boolean DEFAULT_connectPoints = true;
public boolean getConnectPoints();
public void setConnectPoints(boolean flag);
public static boolean DEFAULT_drawMarks = true;
public boolean getDrawMarks();
public void setDrawMarks(boolean flag);
public static boolean DEFAULT_controllable = false;
public boolean getControllable();
public void setControllable(boolean flag);
public static boolean DEFAULT_drawing = false;
public boolean getDrawing();
public void setDrawing(boolean flag);
public static boolean DEFAULT_allowHide = true;
public boolean getAllowHide();
public void setAllowHide(boolean flag);
public OTDataStore getDataStore();
public void setDataStore(OTDataStore store);
public OTDataProducer getDataProducer();
public void setDataProducer(OTDataProducer producer);
public static int DEFAULT_xColumn = 0;
public int getXColumn();
public void setXColumn(int xCol);
public static int DEFAULT_yColumn = 1;
public int getYColumn();
public void setYColumn(int yCol);
public static boolean DEFAULT_locked = false;
public boolean getLocked();
public void setLocked(boolean locked);
public static float DEFAULT_lineWidth = 2.0f;
public float getLineWidth();
public void setLineWidth(float w);
} |
package com.pump.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* A set of static methods relating to reflection.
*
*/
public class Reflection {
/**
* Uses reflection to retrieve a static field from a class.
*
* @return null if an error occurred retrieving this value
*/
public static Object getFieldValue(String className, String fieldName) {
try {
Class<?> c = Class.forName(className);
Field f = c.getField(fieldName);
return f.get(null);
} catch (Throwable t) {
return null;
}
}
/**
* Return an array of objects based on a comma-separated description of its
* contents.
*/
protected static Object[] parseCommaSeparatedList(String arguments) {
if (arguments.trim().length() == 0)
return new Object[] {};
List<String> listElements = new ArrayList<String>();
Stack<Character> constructs = new Stack<Character>();
int startingIndex = 0;
for (int i = 0; i < arguments.length(); i++) {
char ch = arguments.charAt(i);
if (ch == ',' && constructs.size() == 0) {
listElements.add(arguments.substring(startingIndex, i));
startingIndex = i + 1;
} else if (ch == '('
&& (constructs.size() == 0 || constructs.peek() != '"')) {
constructs.add('(');
} else if (ch == ')' && constructs.size() > 0
&& constructs.peek() == '(') {
constructs.pop();
} else if (ch == '"') {
if (constructs.size() > 0 && constructs.peek() == '"') {
constructs.pop();
} else {
constructs.add('"');
}
} else if (ch == '\\' && constructs.size() > 0
&& constructs.peek() == '"') {
i++;
}
}
listElements.add(arguments.substring(startingIndex));
Object[] returnValue = new Object[listElements.size()];
for (int a = 0; a < returnValue.length; a++) {
returnValue[a] = parse(listElements.get(a).trim());
}
return returnValue;
}
static Pattern longPattern = Pattern.compile("\\d+L");
static Pattern intPattern = Pattern.compile("\\d+");
static Pattern floatPattern = Pattern.compile("[0-9]*\\.?[0-9]+");
static Pattern fieldPattern = Pattern
.compile("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*");
static Pattern newPattern = Pattern
.compile("new\\s+([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*\\(\\s*.*\\s*\\)");
static Pattern methodPattern = Pattern
.compile("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*\\(\\s*.*\\s*\\)");
static Pattern stringPattern = Pattern.compile("\"[\\.|[^\"]]*\"");
/**
* Parse an object as null, an int, a long, a float, a String, a static
* field, or "new xyz(..)" (where ".." looks recursively for a
* comma-separated list of arguments)).
* <p>
* For example, you can call: <br>
* <code>parse( "new Color( 255, 0, 128 )" );</code> <br>
* <code>parse( "new com.pump.swing.resources.ArrowIcon( javax.swing.SwingConstants.EAST, 24, 24 )" );</code>
* <br>
* <code>parse( "new com.pump.swing.resources.TriangleIcon( javax.swing.SwingConstants.EAST, 24, 24, new Color(0)" );</code>
* <p>
* The class name/constants must be fully qualified.
*/
public static Object parse(final String input) {
String string = input.trim();
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
} else if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
} else if ("null".equalsIgnoreCase(string)) {
return null;
} else if (intPattern.matcher(string).matches()) {
return Integer.parseInt(string);
} else if (longPattern.matcher(string).matches()) {
return Long.parseLong(string);
} else if (floatPattern.matcher(string).matches()) {
return Float.parseFloat(string);
} else if (stringPattern.matcher(string).matches()) {
return string.substring(1, string.length() - 1);
} else if (newPattern.matcher(string).matches()) {
string = string.substring(3).trim();
int i1 = string.indexOf('(');
int i2 = string.lastIndexOf(')');
String className = string.substring(0, i1);
String arguments = string.substring(i1 + 1, i2);
try {
Class<?> t = Class.forName(className);
return construct(t, arguments);
} catch (ClassNotFoundException | SecurityException
| IllegalArgumentException e) {
throw new RuntimeException("An error occurred parsing \""
+ input + "\" as a field.", e);
}
} else if (methodPattern.matcher(string).matches()) {
int i1 = string.indexOf('(');
int i2 = string.lastIndexOf(')');
String lhs = string.substring(0, i1);
String arguments = string.substring(i1 + 1, i2);
i1 = lhs.lastIndexOf('.');
String className = lhs.substring(0, i1);
String methodName = lhs.substring(i1 + 1);
Object obj = null;
try {
Class<?> t = null;
List<String> fieldNames = new ArrayList<String>();
while (t == null) {
try {
t = Class.forName(className);
} catch (ClassNotFoundException e) {
int i = className.lastIndexOf('.');
if (i == -1) {
break;
}
String fieldName = className.substring(i + 1);
className = className.substring(0, i);
fieldNames.add(fieldName);
}
}
for (int a = 0; a < fieldNames.size(); a++) {
if (obj != null)
t = obj.getClass();
obj = t.getField(fieldNames.get(0)).get(obj);
}
if (obj != null)
t = obj.getClass();
Method[] m = t.getMethods();
for (int a = 0; a < m.length; a++) {
// TODO: consider overloaded method names, similar to how
// we look for the best-fit constructor
boolean isStatic = (m[a].getModifiers() | Modifier.STATIC) > 0;
if (m[a].getName().equals(methodName) && isStatic) {
return m[a].invoke(obj,
parseCommaSeparatedList(arguments));
}
}
} catch (SecurityException | IllegalArgumentException
| IllegalAccessException | InvocationTargetException
| NoSuchFieldException e) {
throw new RuntimeException("An error occurred parsing \""
+ input + "\" as a method.", e);
}
throw new RuntimeException("Unrecognized method for " + input
+ "\"");
} else if (fieldPattern.matcher(string).matches()) {
int i = string.lastIndexOf('.');
String className = string.substring(0, i);
if (className.length() == 0)
throw new RuntimeException(
"Unrecognized argument \""
+ input
+ "\". An attempt was made to parse as a field name, but no identifying class name was found.");
String fieldName = string.substring(i + 1);
try {
Class<?> t = Class.forName(className);
if (fieldName.equals("class"))
return t;
Field f = t.getDeclaredField(fieldName);
if ((f.getModifiers() & Modifier.STATIC) == 0)
throw new RuntimeException(
"Unrecognized argument \""
+ input
+ "\". An attempt was made to parse as a field name, the field used was not static.");
return f.get(null);
} catch (ClassNotFoundException | NoSuchFieldException
| SecurityException | IllegalArgumentException
| IllegalAccessException e) {
throw new RuntimeException("An error occurred parsing \""
+ input + "\" as a field.", e);
}
}
throw new RuntimeException("Unrecognized argument \"" + input + "\"");
}
/**
* This constructs an instance of t if a constructor is found that matches
* the arguments provided. This will not identify a varargs constructor. If
* multiple constructors match the arguments provided, this method will
* choose one to use
*
* @param t
* the type of class to construct.
* @param arguments
* a comma separated list of simple arguments, such as
* primitives, strings, or static fields.
* @return a new instance of t created using the arguments provided, or an
* exception will be thrown.
*/
protected static <T> T construct(Class<T> t, String arguments) {
Object[] argumentObjects = parseCommaSeparatedList(arguments);
Constructor<?>[] constructors = t.getDeclaredConstructors();
class IncompatibleArgumentsException extends Exception {
private static final long serialVersionUID = 1L;
}
class Match implements Comparable<Match> {
Constructor<?> constructor;
Object[] literalArguments;
Object[] convertedArguments;
double score = 0;
Match(Constructor<?> constructor, Class<?>[] idealArgTypes,
Object[] arguments) throws IncompatibleArgumentsException {
this.constructor = constructor;
this.literalArguments = arguments;
this.convertedArguments = new Object[literalArguments.length];
for (int a = 0; a < idealArgTypes.length; a++) {
Class<?> currentClass = arguments[a] == null ? null
: arguments[a].getClass();
if (idealArgTypes[a].equals(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isInteger(idealArgTypes[a])
&& isInteger(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isLong(idealArgTypes[a]) && isLong(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isFloat(idealArgTypes[a])
&& isFloat(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isShort(idealArgTypes[a])
&& isShort(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isChar(idealArgTypes[a]) && isChar(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if (isBoolean(idealArgTypes[a])
&& isBoolean(currentClass)) {
score += 1;
convertedArguments[a] = arguments[a];
} else if ((!idealArgTypes[a].isPrimitive())
&& currentClass == null) {
score += .95;
convertedArguments[a] = null;
} else if (idealArgTypes[a].isAssignableFrom(currentClass)) {
score += .5;
convertedArguments[a] = arguments[a];
} else if (isLong(idealArgTypes[a])
&& isInteger(currentClass)) {
score += .25;
convertedArguments[a] = new Long(
((Integer) arguments[a]).longValue());
} else if (isDouble(idealArgTypes[a])
&& isInteger(currentClass)) {
score += .25;
convertedArguments[a] = new Double(
((Integer) arguments[a]).doubleValue());
} else if (isFloat(idealArgTypes[a])
&& isInteger(currentClass)) {
score += .25;
convertedArguments[a] = new Float(
((Integer) arguments[a]).floatValue());
} else if (isShort(idealArgTypes[a])
&& isInteger(currentClass)) {
score += .25;
convertedArguments[a] = new Short(
((Integer) arguments[a]).shortValue());
} else if (isDouble(idealArgTypes[a])
&& isFloat(currentClass)) {
score += .15;
convertedArguments[a] = new Double(
((Float) arguments[a]).doubleValue());
} else {
throw new IncompatibleArgumentsException();
}
}
score = score / ((double) idealArgTypes.length);
}
private boolean isInteger(Class<?> c) {
return Integer.TYPE.equals(c) || Integer.class.equals(c);
}
private boolean isLong(Class<?> c) {
return Long.TYPE.equals(c) || Long.class.equals(c);
}
private boolean isDouble(Class<?> c) {
return Double.TYPE.equals(c) || Double.class.equals(c);
}
private boolean isFloat(Class<?> c) {
return Float.TYPE.equals(c) || Float.class.equals(c);
}
private boolean isShort(Class<?> c) {
return Short.TYPE.equals(c) || Short.class.equals(c);
}
private boolean isChar(Class<?> c) {
return Character.TYPE.equals(c) || Character.class.equals(c);
}
private boolean isBoolean(Class<?> c) {
return Boolean.TYPE.equals(c) || Boolean.class.equals(c);
}
@Override
public int compareTo(Match o) {
if (score < o.score) {
return -1;
}
if (score > o.score) {
return 1;
}
return 0;
}
}
SortedSet<Match> matches = new TreeSet<Match>();
for (Constructor<?> constructor : constructors) {
Class<?>[] argT = constructor.getParameterTypes();
if (argT.length == argumentObjects.length) {
try {
matches.add(new Match(constructor, argT, argumentObjects));
} catch (IncompatibleArgumentsException e) {
// keep searching
}
}
}
if (matches.size() > 0) {
try {
Match match = matches.last();
match.constructor.setAccessible(true);
return (T) match.constructor
.newInstance(match.convertedArguments);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(
"an error occurred invoking a constructor for "
+ t.getName() + " using \"" + arguments + "\"",
e);
}
}
throw new RuntimeException("no constructor for " + t.getName()
+ " was found that matched \"" + arguments + "\"");
}
/**
* This object is returned by <code>invokeMethod(..)</code> when an error
* occurs.
*/
public static final Object INVOCATION_ERROR = new Object();
/**
* This uses reflection to call a method that may not exist in the compiling
* JVM, or is otherwise inaccessible.
*
* @return INVOCATION_ERROR if an error occurs (details are printed to the
* console), or the return value of the invocation.
*/
public static Object invokeMethod(Class<?> c, Object obj,
String methodName, Object... arguments) {
if(c==null && obj!=null)
c = obj.getClass();
try {
while (c != null) {
Method[] methods = c.getDeclaredMethods();
for (int a = 0; a < methods.length; a++) {
if (methods[a].getName().equals(methodName)) {
methods[a].setAccessible(true);
try {
return methods[a].invoke(obj, arguments);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
c = c.getSuperclass();
}
} catch (Throwable t) {
t.printStackTrace();
}
return INVOCATION_ERROR;
}
/**
* This debugging tool combs through a class and tells you what public
* static field has the value you've provided.
* <P>
* For example, you can call: <BR>
* <code>nameStaticField(BufferedImage.class,new Integer(BufferedImage.TYPE_INT_ARGB))</code>
* <BR>
* And this method will return "TYPE_INT_ARGB".
*
* @param c
* the class of interest
* @param value
* the value. Primitives must be wrapped.
* @return the string of the field with that value, or <code>null</code> if
* not hits were found. (Or if multiple hits were found, this
* returns a list of possible matches.)
*/
public static String nameStaticField(Class<?> c, Object value) {
Field[] f = c.getDeclaredFields();
List<Field> v = new ArrayList<>();
for (int a = 0; a < f.length; a++) {
if ((f[a].getModifiers() & Modifier.STATIC) > 0) {
try {
f[a].setAccessible(true);
Object obj = f[a].get(null);
if (obj != null && obj.equals(value)) {
v.add(f[a]);
}
} catch (IllegalAccessException e) {
}
}
}
if (v.size() == 0)
return null;
if (v.size() == 1) {
return (v.get(0)).getName();
}
// uh-oh, more than 1 field equalled the desired value...
// could be the case a static float and a static int both
// point to the number 1?
int a = 0;
while (a < v.size()) {
try {
Object obj = (v.get(a)).get(null);
if (obj.getClass().equals(value.getClass()) == false) {
v.remove(a);
} else {
a++;
}
} catch (IllegalAccessException e) {
return "An unexpected error occurred the second time I tried to access a field.";
}
}
if (v.size() == 1) {
return (v.get(0)).getName();
} else if (v.size() > 1) {
return describe(v);
}
// last attempt:
for (a = 0; a < v.size(); a++) {
try {
Object obj = (v.get(a)).get(null);
if (obj.getClass().isInstance(value)) {
return (v.get(a)).getName();
}
} catch (IllegalAccessException e) {
return "An unexpected error occurred the second time I tried to access a field.";
}
}
return describe(v);
}
private static String describe(List<Field> v) {
// we failed. try to give helpful info:
String s = "[ " + (v.get(0)).getName();
for (int a = 1; a < v.size(); a++) {
s += ", " + (v.get(a)).getName();
}
s += " ]";
return s;
}
} |
package com.rox.emu.P6502;
/**
* A representation of the 6502 CPU registers
*
* @author rossdrew
*/
public class Registers {
public static final int REG_ACCUMULATOR = 0;
public static final int REG_PC_HIGH = 1;
public static final int REG_PC_LOW = 2;
public static final int REG_SP = 3;
public static final int REG_STATUS = 4;
private final String[] registerNames = new String[] {"Accumulator", "", "", "Program Counter Hi", "Program Counter Low", "", "Stack Pointer", "Status Flags"};
public static final int STATUS_FLAG_CARRY = 0x1;
public static final int CARRY_INDICATOR_BIT = 0x100;
public static final int STATUS_FLAG_ZERO = 0x2;
public static final int STATUS_FLAG_IRQ_DISABLE = 0x4;
public static final int STATUS_FLAG_DEC = 0x8;
public static final int STATUS_FLAG_BREAK = 0x10;
public static final int STATUS_FLAG_UNUSED = 0x20;
public static final int STATUS_FLAG_OVERFLOW = 0x40;
public static final int STATUS_FLAG_NEGATIVE = 0x80;
private int register[] = new int[8];
public void setRegister(int registerID, int val){
int byteSizeValue = val & 0xFFFF00;
System.out.println("Setting (R)" + register[registerID] + " to " + byteSizeValue);
register[registerID] = byteSizeValue;
}
public void setPC(int wordPC){
register[REG_PC_HIGH] = wordPC >> 8;
register[REG_PC_LOW] = wordPC & 0xFF;
System.out.println("Program Counter being set to " + wordPC + " [ " + getRegister(REG_PC_HIGH) + " | " + getRegister(REG_PC_LOW) + " ]");
}
public int getPC(){
return (getRegister(REG_PC_HIGH) << 8) | getRegister(REG_PC_LOW);
}
public String getRegisterName(int registerID){
return registerNames[registerID];
}
public int getRegister(int registerID){
return register[registerID];
}
public void setFlag(int flagID) {
System.out.println("Setting (F)'" + flagID + "'");
register[REG_STATUS] = register[REG_STATUS] | flagID;
}
/**
* Bitwise clear flag by OR-ing the int carrying flags to be cleared
* then AND-ing with status flag register.
*
* Clear bit 1 (place value 2)
* 0000 0010
* NOT > 1111 1101
* AND(R) > xxxx xx0x
*
* @param flagValue int with bits to clear, turned on
*/
public void clearFlag(int flagValue){
System.out.println("Clearing (F)'" + flagValue + "'");
register[REG_STATUS] = (~flagValue) & register[REG_STATUS];
}
public boolean[] getStatusFlags(){
boolean[] flags = new boolean[8];
flags[0] = (register[REG_STATUS] & STATUS_FLAG_CARRY) == STATUS_FLAG_CARRY;
flags[1] = (register[REG_STATUS] & STATUS_FLAG_ZERO) == STATUS_FLAG_ZERO;
flags[2] = (register[REG_STATUS] & STATUS_FLAG_IRQ_DISABLE) == STATUS_FLAG_IRQ_DISABLE;
flags[3] = (register[REG_STATUS] & STATUS_FLAG_DEC) == STATUS_FLAG_DEC;
flags[4] = (register[REG_STATUS] & STATUS_FLAG_BREAK) == STATUS_FLAG_BREAK;
flags[5] = (register[REG_STATUS] & STATUS_FLAG_UNUSED) == STATUS_FLAG_UNUSED;
flags[6] = (register[REG_STATUS] & STATUS_FLAG_OVERFLOW) == STATUS_FLAG_OVERFLOW;
flags[7] = (register[REG_STATUS] & STATUS_FLAG_NEGATIVE) == STATUS_FLAG_NEGATIVE;
return flags;
}
public int getNextProgramCounter(){
final int originalPC = getPC();
final int incrementedPC = originalPC + 1;
setRegister(REG_PC_HIGH, incrementedPC & 0xFF00);
setRegister(REG_PC_LOW, incrementedPC & 0x00FF);
System.out.println("Program Counter now " + incrementedPC);
return incrementedPC;
}
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Provides utility routines to simplify obtaining randomized values.
*
* <p>Each instance of Randoms contains an underlying {@link java.util.Random} instance and is
* only as thread-safe as that is. If you wish to have a private stream of pseudorandom numbers,
* use the {@link #with} factory.
*/
public class Randoms
{
/** A default Randoms that is thread-safe and can be safely shared by any caller. */
public static final Randoms RAND = with(new Random());
/**
* A factory to create a new Randoms object.
*/
public static Randoms with (Random rand)
{
return new Randoms(rand);
}
/**
* Get a thread-local Randoms instance that will not contend with any other thread
* for random number generation.
*
* <p><b>Note:</b> This method will return a Randoms instance that is not thread-safe.
* It can generate random values with less overhead, however it may be dangerous to share
* the reference. Instead you should probably always use it immediately as in the following
* example:
* <pre style="code">
* Puppy pick = Randoms.threadLocal().pick(Puppy.LITTER, null);
* </pre>
*/
public static Randoms threadLocal ()
{
return _localRandoms.get();
}
public int getInt (int high)
{
return _r.nextInt(high);
}
public int getInRange (int low, int high)
{
return low + _r.nextInt(high - low);
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>0.0</code> (inclusive) and the <code>high</code> (exclusive).
*
* @param high the high value limiting the random number sought.
*/
public float getFloat (float high)
{
return _r.nextFloat() * high;
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*/
public float getInRange (float low, float high)
{
return low + (_r.nextFloat() * (high - low));
}
public boolean getChance (int n)
{
return (0 == _r.nextInt(n));
}
/**
* Has a probability <code>p</code> of returning true.
*/
public boolean getProbability (float p)
{
return _r.nextFloat() < p;
}
/**
* Returns <code>true</code> or <code>false</code> with approximately even probability.
*/
public boolean getBoolean ()
{
return _r.nextBoolean();
}
/**
* Returns a pseudorandom, normally distributed <code>float</code> value around the
* <code>mean</code> with the standard deviation <code>dev</code>.
*/
public float getNormal (float mean, float dev)
{
return (float)_r.nextGaussian() * dev + mean;
}
public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty)
{
T pick = ifEmpty;
double r = _r.nextDouble();
double total = 0.0;
for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) {
double weight = entry.getValue().doubleValue();
if (weight > 0.0) {
total += weight;
if ((r * total) < weight) {
pick = entry.getKey();
}
} else if (weight < 0.0) {
throw new IllegalArgumentException("Weight less than 0: " + entry);
} // else: weight == 0.0 is OK
}
return pick;
}
@Deprecated
public <T> T getWeighted (Map<T, ? extends Number> valuesToWeights)
{
// TODO: validate each weight to ensure it's not below 0
double sum = Folds.sum(0.0, valuesToWeights.values());
if (sum <= 0) {
throw new IllegalArgumentException("The sum of the weights is not positive");
}
// TODO: iterate all entries once, similarly to picking from an Iterable?
double d = _r.nextDouble() * sum;
for (Map.Entry<T, ? extends Number> entry : valuesToWeights.entrySet()) {
d -= entry.getValue().doubleValue();
if (d < 0) {
return entry.getKey();
}
}
// TODO: due to rounding error when iteratively subtract doubles, it might
// be possible to fall out of the loop here. Remember the highest-weighted entry
// and return it? (returning the last entry could be incorrect if it had a weight of 0).
throw new AssertionError("Not possible");
}
/**
* Pick a random element from the specified Iterator, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> because the total size of the Iterator is not known,
* the random number generator is queried after the second element and every element
* thereafter.
*
* @throws NullPointerException if the iterator is null.
*/
public <T> T pick (Iterator<? extends T> iterator, T ifEmpty)
{
if (!iterator.hasNext()) {
return ifEmpty;
}
T pick = iterator.next();
for (int count = 2; iterator.hasNext(); count++) {
T next = iterator.next();
if (0 == _r.nextInt(count)) {
pick = next;
}
}
return pick;
}
/**
* Pick a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator, Object)}
* with the Iterable's Iterator.
*
* @throws NullPointerException if the iterable is null.
*/
public <T> T pick (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, false);
}
/**
* Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, two Iterators are created from the Iterable
* and a random number is generated after the second element and all beyond.
*
* @throws NullPointerException if the iterable is null.
* @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator
* does not support {@link Iterator#remove()}.
*/
public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, true);
}
/**
* Construct a Randoms.
*/
protected Randoms (Random rand)
{
_r = rand;
}
/**
* Shared code for pick and pluck.
*/
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove)
{
if (iterable instanceof Collection) {
// optimized path for Collection
@SuppressWarnings("unchecked")
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
@SuppressWarnings("unchecked")
List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
if (remove) { // ternary conditional causes warning here with javac 1.6, :(
return list.remove(idx);
}
return list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
// catch up lagIt so that it has just returned 'pick' as well
for ( ; lag > 0; lag
lagIt.next();
}
}
}
lagIt.remove(); // remove 'pick' from the lagging iterator
return pick;
}
/** The random number generator. */
protected final Random _r;
/** A ThreadLocal for accessing a thread-local version of Randoms. */
protected static final ThreadLocal<Randoms> _localRandoms = new ThreadLocal<Randoms>() {
@Override
public Randoms initialValue () {
return with(new ThreadLocalRandom());
}
};
protected static class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
*/
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
@SuppressWarnings("unused")
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
super();
initialized = true;
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setSeed(long seed) {
if (initialized)
throw new UnsupportedOperationException();
rnd = (seed ^ multiplier) & mask;
}
@Override
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48-bits));
}
// as of JDK 1.6, this method does not exist in java.util.Random
// public int nextInt(int least, int bound) {
// if (least >= bound)
// return nextInt(bound - least) + least;
public long nextLong(long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
// Divide n by two until small enough for nextInt. On each
// iteration (at most 31 of them but usually much less),
// randomly choose both whether to include high bit in result
// (offset) and whether to continue with the lower vs upper
// half (which makes a difference only if odd).
long offset = 0;
while (n >= Integer.MAX_VALUE) {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0)
offset += n - nextn;
n = nextn;
}
return offset + nextInt((int) n);
}
public long nextLong(long least, long bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextLong(bound - least) + least;
}
public double nextDouble(double n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
return nextDouble() * n;
}
public double nextDouble(double least, double bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextDouble() * (bound - least) + least;
}
private static final long serialVersionUID = -5851777807851030925L;
}
} |
package com.soklet.archive;
import static com.soklet.util.IoUtils.copyStreamCloseAfterwards;
import static com.soklet.util.PathUtils.allFilesInDirectory;
import static com.soklet.util.StringUtils.trimToNull;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.UUID.randomUUID;
import static java.util.logging.Level.WARNING;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
import static java.util.stream.Collectors.toSet;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.soklet.json.JSONObject;
import com.soklet.util.IoUtils;
import com.soklet.util.PathUtils;
import com.soklet.web.HashedUrlManifest;
import com.soklet.web.HashedUrlManifest.PersistenceFormat;
public class Archiver {
private static final Set<Path> DEFAULT_PATHS_TO_EXCLUDE = unmodifiableSet(new HashSet<Path>() {
{
add(Paths.get(".git"));
}
});
private final Path archiveFile;
private final Set<ArchivePath> archivePaths;
private final Set<Path> pathsToExclude;
private final Optional<StaticFileConfiguration> staticFileConfiguration;
private final Optional<MavenSupport> mavenSupport;
private final Optional<ArchiveSupportOperation> preProcessOperation;
private final Optional<ArchiveSupportOperation> postProcessOperation;
private final Optional<FileAlterationOperation> fileAlterationOperation;
private final Logger logger = Logger.getLogger(Archiver.class.getName());
protected Archiver(Builder builder) {
requireNonNull(builder);
this.archiveFile = builder.archiveFile;
this.archivePaths = builder.archivePaths;
this.pathsToExclude = builder.pathsToExclude;
this.staticFileConfiguration = builder.staticFileConfiguration;
this.mavenSupport = builder.mavenSupport;
this.preProcessOperation = builder.preProcessOperation;
this.postProcessOperation = builder.postProcessOperation;
this.fileAlterationOperation = builder.fileAlterationOperation;
// Enforce relative paths
for (ArchivePath archivePath : archivePaths) {
if (archivePath.sourcePath().isAbsolute())
throw new IllegalArgumentException(format(
"Archive paths cannot be absolute, they must be relative. Offending source path was %s",
archivePath.sourcePath()));
if (archivePath.destinationDirectory().isAbsolute())
throw new IllegalArgumentException(format(
"Archive paths cannot be absolute, they must be relative. Offending destination directory was %s",
archivePath.destinationDirectory()));
}
if (staticFileConfiguration().isPresent()) {
if (staticFileConfiguration().get().rootDirectory().isAbsolute())
throw new IllegalArgumentException(format(
"Static file root directory path cannot be absolute, it must be relative. Offending directory path was %s",
staticFileConfiguration().get().rootDirectory()));
if (staticFileConfiguration().get().hashedUrlManifestJsFile().isPresent()
&& staticFileConfiguration().get().hashedUrlManifestJsFile().get().isAbsolute())
throw new IllegalArgumentException(format(
"Hashed URL manifest JS file path cannot be absolute, it must be relative. Offending file path was %s",
staticFileConfiguration().get().hashedUrlManifestJsFile().get()));
}
}
public void run() throws Exception {
logger.info(format("Creating archive %s...", archiveFile()));
Path temporaryDirectory =
Files.createTempDirectory(format("com.soklet.%s-%s-", getClass().getSimpleName(), randomUUID()));
Optional<Path> temporaryStaticFileRootDirectory = Optional.empty();
if (staticFileConfiguration().isPresent()) {
Path relativeStaticFileRootDirectory =
Paths.get(".").toAbsolutePath().getParent()
.relativize(staticFileConfiguration.get().rootDirectory().toAbsolutePath());
temporaryStaticFileRootDirectory = Optional.of(temporaryDirectory.resolve(relativeStaticFileRootDirectory));
}
try {
// Copy everything over to our temporary working directory
logger.info("Copying files to temporary directory...");
PathUtils.copyDirectory(Paths.get("."), temporaryDirectory, pathsToExclude);
// Run any client-supplied preprocessing code (for example, compile LESS files into CSS)
if (preProcessOperation().isPresent()) {
logger.info("Performing pre-processing operation...");
preProcessOperation().get().perform(this, temporaryDirectory);
}
// Run any Maven tasks (for example, build and extract dependency JARs for inclusion in archive)
if (mavenSupport().isPresent()) {
logger.info("Performing Maven operations...");
performMavenSupport(mavenSupport.get(), temporaryDirectory);
}
// Permit client code to modify files in-place (for example, compress JS and CSS)
if (fileAlterationOperation().isPresent()) {
logger.info("Performing file alteration operation...");
performFileAlterations(temporaryDirectory);
}
// Hash static files and store off the manifest
Optional<Path> hashedUrlManifestFile = Optional.empty();
if (temporaryStaticFileRootDirectory.isPresent()) {
logger.info("Performing static file hashing...");
// 1. Do the hashing
HashedUrlManifest hashedUrlManifest = performStaticFileHashing(temporaryStaticFileRootDirectory.get());
// 2. Write the manifest to disk for inclusion in the archive
hashedUrlManifestFile = Optional.of(temporaryDirectory.resolve(HashedUrlManifest.defaultManifestFile()));
try (OutputStream outputStream = Files.newOutputStream(hashedUrlManifestFile.get())) {
hashedUrlManifest.writeToOutputStream(outputStream, PersistenceFormat.PRETTY_PRINTED);
}
// 3. Create gzipped versions of static files as appropriate
logger.info("GZIPping static files...");
for (Path staticFile : PathUtils.allFilesInDirectory(temporaryStaticFileRootDirectory.get())) {
if (!shouldZipStaticFile(staticFile)) continue;
Path gzippedFile = Paths.get(format("%s.gz", staticFile.toAbsolutePath()));
try (InputStream inputStream = Files.newInputStream(staticFile);
GZIPOutputStream outputStream = new GZIPOutputStream(Files.newOutputStream(gzippedFile))) {
IoUtils.copyStream(inputStream, outputStream);
outputStream.flush();
}
}
}
// Run any client-supplied postprocessing code
if (postProcessOperation().isPresent()) {
logger.info("Performing post-processing operation...");
postProcessOperation().get().perform(this, temporaryDirectory);
}
// Re-root the provided archive paths to point to the temporary directory
Set<ArchivePath> workingArchivePaths = archivePaths().stream().map(archivePath -> {
Path sourcePath = temporaryDirectory.resolve(archivePath.sourcePath());
return ArchivePaths.get(sourcePath, archivePath.destinationDirectory());
}).collect(toSet());
// If we generated a hashed url manifest, add it to the archive
if (hashedUrlManifestFile.isPresent())
workingArchivePaths.add(ArchivePaths.get(hashedUrlManifestFile.get(), Paths.get(".")));
// Finally - create the archive
createZip(archiveFile(), extractFilesFromarchivePaths(workingArchivePaths));
logger.info(format("Archive %s was created successfully.", archiveFile));
} finally {
PathUtils.deleteDirectory(temporaryDirectory);
}
}
protected void createZip(Path archiveFile, Set<ArchivePath> archivePathsToInclude) {
requireNonNull(archiveFile);
requireNonNull(archivePathsToInclude);
logger.info(format("Assembling %s...", archiveFile));
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(archiveFile.toFile());
} catch (IOException e) {
throw new UncheckedIOException(format("Unable to create zip archive %s", archiveFile), e);
}
ZipOutputStream zipOutputStream = null;
Function<ArchivePath, String> zipEntryNameProvider =
(archivePath) -> format("%s/%s", archivePath.destinationDirectory(), archivePath.sourcePath().getFileName());
try {
zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.setLevel(9);
// Zip root is the name of the archive without the extension, e.g. "app.zip" would be "app".
String zipRoot = archiveFile.getFileName().toString();
int indexOfPeriod = zipRoot.indexOf(".");
if (indexOfPeriod != -1 && zipRoot.length() > 1) zipRoot = zipRoot.substring(0, indexOfPeriod);
SortedSet<ArchivePath> sortedarchivePathsToInclude = new TreeSet<ArchivePath>(new Comparator<ArchivePath>() {
@Override
public int compare(ArchivePath archivePath1, ArchivePath archivePath2) {
return zipEntryNameProvider.apply(archivePath1).compareTo(zipEntryNameProvider.apply(archivePath2));
}
});
sortedarchivePathsToInclude.addAll(archivePathsToInclude);
for (ArchivePath archivePath : sortedarchivePathsToInclude) {
String zipEntryName = zipEntryNameProvider.apply(archivePath);
logger.fine(format("Adding %s...", zipEntryName));
zipOutputStream.putNextEntry(new ZipEntry(format("%s/%s", zipRoot, zipEntryName)));
zipOutputStream.write(Files.readAllBytes(archivePath.sourcePath()));
}
zipOutputStream.flush();
} catch (IOException e) {
throw new UncheckedIOException(format("An error occurred while creating archive %s", archiveFile), e);
} finally {
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e) {
logger.log(WARNING, format("Unable to close %s. Continuing on...", ZipOutputStream.class.getSimpleName()), e);
}
}
}
}
protected Set<ArchivePath> extractFilesFromarchivePaths(Set<ArchivePath> pathsToInclude) {
requireNonNull(pathsToInclude);
Set<ArchivePath> filesToInclude = new HashSet<>();
pathsToInclude.forEach(archivePath -> {
if (Files.exists(archivePath.sourcePath())) {
if (Files.isDirectory(archivePath.sourcePath())) {
try {
Files.walk(archivePath.sourcePath()).forEach(
childPath -> {
if (!Files.isDirectory(childPath)) {
Path destinationDirectory =
Paths.get(format("%s/%s", archivePath.destinationDirectory(), archivePath.sourcePath()
.relativize(childPath)));
if (destinationDirectory.getParent() != null)
destinationDirectory = destinationDirectory.getParent();
filesToInclude.add(ArchivePaths.get(childPath, destinationDirectory));
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} else {
filesToInclude.add(archivePath);
}
}
});
return filesToInclude;
}
protected void performFileAlterations(Path workingDirectory) throws IOException {
requireNonNull(workingDirectory);
if (!Files.exists(workingDirectory))
throw new IllegalArgumentException(format("Directory %s does not exist!", workingDirectory.toAbsolutePath()));
if (!Files.isDirectory(workingDirectory))
throw new IllegalArgumentException(format("%s is not a directory!", workingDirectory.toAbsolutePath()));
PathUtils.walkDirectory(workingDirectory, (file) -> {
try {
Optional<InputStream> alteredFile = fileAlterationOperation().get().alterFile(this, workingDirectory, file);
// TODO: need to document that we will close the InputStream - the caller is not responsible for that
if (alteredFile.isPresent()) copyStreamCloseAfterwards(alteredFile.get(), Files.newOutputStream(file));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(format("Unable to alter file %s", file.toAbsolutePath()), e);
}
} );
}
protected HashedUrlManifest performStaticFileHashing(Path staticFileRootDirectory) throws IOException {
requireNonNull(staticFileRootDirectory);
if (!Files.exists(staticFileRootDirectory))
throw new IllegalArgumentException(format("Directory %s does not exist!",
staticFileRootDirectory.toAbsolutePath()));
if (!Files.isDirectory(staticFileRootDirectory))
throw new IllegalArgumentException(format("%s is not a directory!", staticFileRootDirectory.toAbsolutePath()));
Map<String, String> hashedUrlsByUrl = new HashMap<>();
Optional<Path> hashedUrlManifestJsFile = Optional.empty();
if (staticFileConfiguration().get().hashedUrlManifestJsFile().isPresent())
hashedUrlManifestJsFile =
Optional.of(staticFileRootDirectory.resolve(staticFileConfiguration().get().hashedUrlManifestJsFile().get()));
// Step 1: hash everything but CSS files (we rewrite those next) and the preexisting manifest file (if present)
for (Path file : allFilesInDirectory(staticFileRootDirectory)) {
// Ignore CSS
if (isCssFile(file)) continue;
// Ignore preexisting manifest
if (hashedUrlManifestJsFile.isPresent() && file.equals(hashedUrlManifestJsFile.get())) continue;
HashedFileUrlMapping hashedFileUrlMapping = createHashedFile(file, staticFileRootDirectory);
hashedUrlsByUrl.put(hashedFileUrlMapping.url(), hashedFileUrlMapping.hashedUrl());
}
// Step 2: rewrite CSS files with manifest created in step 1
for (Path file : allFilesInDirectory(staticFileRootDirectory))
if (isCssFile(file)) rewriteCssUrls(file, staticFileRootDirectory, new HashedUrlManifest(hashedUrlsByUrl));
// Step 3: add final CSS file hashes to manifest created in step 1
for (Path file : allFilesInDirectory(staticFileRootDirectory)) {
if (!isCssFile(file)) continue;
HashedFileUrlMapping hashedFileUrlMapping = createHashedFile(file, staticFileRootDirectory);
hashedUrlsByUrl.put(hashedFileUrlMapping.url(), hashedFileUrlMapping.hashedUrl());
}
// Step 4 (optional): create JS manifest, which includes a reference to itself (chicken-and-egg)
if (staticFileConfiguration().get().hashedUrlManifestJsFile().isPresent()) {
// First, compute the hash of the manifest
HashedUrlManifest hashedUrlManifest = new HashedUrlManifest(hashedUrlsByUrl);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
hashedUrlManifest.writeToOutputStream(byteArrayOutputStream, PersistenceFormat.COMPACT);
byteArrayOutputStream.flush();
// Figure out the mapping between the manifest URL and its hashed counterpart
String precomputedManifestFileHash =
staticFileConfiguration().get().fileHasher().hash(byteArrayOutputStream.toByteArray());
Path manifestFile =
staticFileRootDirectory.resolve(staticFileConfiguration().get().hashedUrlManifestJsFile().get());
String hashedManifestFilename =
staticFileConfiguration().get().filenameHasher().hashFilename(manifestFile, precomputedManifestFileHash);
Path relativeManifestFile = staticFileRootDirectory.getParent().relativize(manifestFile);
Path relativeHashedManifestFile =
staticFileRootDirectory.getParent().relativize(Paths.get(hashedManifestFilename));
Map<String, Object> hashedUrlsByUrlForJson = new HashMap<>(hashedUrlManifest.hashedUrlsByUrl());
hashedUrlsByUrlForJson.put(format("/%s", relativeManifestFile), format("/%s", relativeHashedManifestFile));
// Create the manifest JS content
JSONObject jsonObject = new JSONObject(hashedUrlsByUrlForJson);
// TODO: let clients provide a method to hook this for arbitrary formatting
String hashedUrlManifestJsFileContents =
format("(function(scope){if(!scope.soklet)scope.soklet={};scope.soklet.hashedUrls=%s;})(this);", jsonObject);
// Finally, write the manifest JS to disk
Files.write(manifestFile, hashedUrlManifestJsFileContents.getBytes(UTF_8));
HashedFileUrlMapping hashedFileUrlMapping =
createHashedFile(manifestFile, staticFileRootDirectory, Optional.of(precomputedManifestFileHash));
hashedUrlsByUrl.put(hashedFileUrlMapping.url(), hashedFileUrlMapping.hashedUrl());
}
return new HashedUrlManifest(hashedUrlsByUrl);
}
protected HashedFileUrlMapping createHashedFile(Path file, Path staticFileRootDirectory) throws IOException {
requireNonNull(file);
requireNonNull(staticFileRootDirectory);
return createHashedFile(file, staticFileRootDirectory, Optional.empty());
}
protected HashedFileUrlMapping createHashedFile(Path file, Path staticFileRootDirectory,
Optional<String> precomputedHash) throws IOException {
requireNonNull(file);
requireNonNull(staticFileRootDirectory);
requireNonNull(precomputedHash);
if (!Files.exists(file))
throw new IllegalArgumentException(format("File %s does not exist!", file.toAbsolutePath()));
if (Files.isDirectory(file))
throw new IllegalArgumentException(format("%s is a directory!", file.toAbsolutePath()));
if (!Files.exists(staticFileRootDirectory))
throw new IllegalArgumentException(format("Directory %s does not exist!",
staticFileRootDirectory.toAbsolutePath()));
if (!Files.isDirectory(staticFileRootDirectory))
throw new IllegalArgumentException(format("%s is not a directory!", staticFileRootDirectory.toAbsolutePath()));
String hash = precomputedHash.orElse(staticFileConfiguration().get().fileHasher().hash(Files.readAllBytes(file)));
String hashedFilename = staticFileConfiguration().get().filenameHasher().hashFilename(file, hash);
// Keep track of mapping between static URLs and hashed counterparts
Path relativeStaticFile = staticFileRootDirectory.getParent().relativize(file);
Path relativeHashedStaticFile = staticFileRootDirectory.getParent().relativize(Paths.get(hashedFilename));
copyStreamCloseAfterwards(Files.newInputStream(file), Files.newOutputStream(Paths.get(hashedFilename)));
return new HashedFileUrlMapping(format("/%s", relativeStaticFile), format("/%s", relativeHashedStaticFile));
}
protected static class HashedFileUrlMapping {
private final String url;
private final String hashedUrl;
public HashedFileUrlMapping(String url, String hashedUrl) {
this.url = requireNonNull(url);
this.hashedUrl = requireNonNull(hashedUrl);
}
@Override
public String toString() {
return format("%s{url=%s, hashedUrl=%s}", getClass().getSimpleName(), url(), hashedUrl());
}
public String url() {
return this.url;
}
public String hashedUrl() {
return this.hashedUrl;
}
}
protected boolean isCssFile(Path file) {
requireNonNull(file);
return file.getFileName().toString().toLowerCase(ENGLISH).endsWith(".css");
}
protected void performMavenSupport(MavenSupport mavenSupport, Path workingDirectory) {
requireNonNull(mavenSupport);
requireNonNull(workingDirectory);
ArchiverProcess mavenArchiverProcess = new ArchiverProcess(mavenSupport.mavenExecutableFile(), workingDirectory);
mavenArchiverProcess.execute(mavenSupport().get().cleanArguments());
mavenArchiverProcess.execute(mavenSupport().get().compileArguments());
mavenArchiverProcess.execute(mavenSupport().get().dependenciesArguments());
}
public static Builder forArchiveFile(Path archiveFile) {
return new Builder(archiveFile);
}
protected void rewriteCssUrls(Path cssFile, Path staticFileRootDirectory, HashedUrlManifest hashedUrlManifest)
throws IOException {
requireNonNull(cssFile);
requireNonNull(hashedUrlManifest);
if (!Files.exists(cssFile))
throw new IllegalArgumentException(format("CSS file %s does not exist!", cssFile.toAbsolutePath()));
if (Files.isDirectory(cssFile))
throw new IllegalArgumentException(format("%s is a directory!", cssFile.toAbsolutePath()));
String css = new String(Files.readAllBytes(cssFile), UTF_8);
String cssFileRelativeFilename =
staticFileConfiguration().get().rootDirectory().getFileName()
.resolve(staticFileRootDirectory.relativize(cssFile)).toString();
// Don't use StringBuilder as regex methods like appendTail require a StringBuffer
StringBuffer stringBuffer = new StringBuffer();
Pattern cssUrlPattern = createCssUrlPattern();
Matcher matcher = cssUrlPattern.matcher(css);
while (matcher.find()) {
// Is true if this a match on something like @import "/static/test.css";
boolean processingImportUrl = false;
String originalUrl = matcher.group(1);
if (matcher.group(2) != null) {
originalUrl = matcher.group(2);
processingImportUrl = true;
} else if (matcher.group(3) != null) {
originalUrl = matcher.group(3);
processingImportUrl = true;
}
String url = originalUrl;
boolean dataUrl = false;
// Try to expand relative URL components.
// Since full expansion of relative components is a lot of work and tricky, we have to enforce some basic rules
// like any relative URL must start with "../" (URLs like "/static/../whatever.png" are not
// permitted) and you can't nest relative paths (URLs like "../../test/../whatever.png" are not permitted).
if (url.startsWith("../")) {
String temporaryUrl = url;
int relativePathCount = 0;
while (temporaryUrl.startsWith("../")) {
++relativePathCount;
temporaryUrl = temporaryUrl.substring(3);
}
// Rejects URLs like "../../test/../whatever.png"
if (temporaryUrl.contains("../")) {
logger.warning(format(
"URL '%s' has nested relative path component[s] so we can't process it. Issue is in %s", url,
cssFileRelativeFilename));
} else {
// Rewrite relative URLs, e.g. ../images/test.jpg
Path parentDirectory = cssFile.getParent();
for (int i = 0; i < relativePathCount; ++i)
parentDirectory = parentDirectory.getParent();
Path resolvedRelativeFile =
staticFileRootDirectory.getFileName().resolve(staticFileRootDirectory.relativize(parentDirectory))
.resolve(Paths.get(temporaryUrl));
url = format("/%s", resolvedRelativeFile.toString());
logger.fine(format("Relative URL %s was rewritten to %s in %s", originalUrl, url, cssFileRelativeFilename));
}
} else if (url.contains("../")) {
// Rejects URLs like "/static/../whatever.png"
logger.warning(format(
"URL '%s' has relative path component[s] which do not start with ../ so we can't process it. Issue is in %s",
url, cssFileRelativeFilename));
} else if (url.toLowerCase(ENGLISH).startsWith("data:")) {
dataUrl = true;
} else if (!url.startsWith("/")) {
// Rewrite same-directory URLs, e.g. images/test.jpg
Path parentDirectory = cssFile.getParent();
Path resolvedRelativeFile =
staticFileRootDirectory.getFileName().resolve(staticFileRootDirectory.relativize(parentDirectory))
.resolve(Paths.get(url));
url = format("/%s", resolvedRelativeFile.toString());
logger.fine(format("Relative URL %s was rewritten to %s in %s", originalUrl, url, cssFileRelativeFilename));
}
String cleanedUrl = url;
// Clean up - see comments on createCssUrlPattern() to see why.
// TODO: fix the pattern so we don't have to do this.
int indexOfQuestionMark = cleanedUrl.indexOf("?");
if (indexOfQuestionMark > 0) cleanedUrl = cleanedUrl.substring(0, indexOfQuestionMark);
int indexOfHash = cleanedUrl.indexOf("
if (indexOfHash > 0) cleanedUrl = cleanedUrl.substring(0, indexOfHash);
Optional<String> hashedUrl = hashedUrlManifest.hashedUrl(cleanedUrl);
String rewrittenUrl = url;
if (hashedUrl.isPresent()) {
rewrittenUrl = url.replace(cleanedUrl, hashedUrl.get());
logger.fine(format("Rewrote CSS URL reference '%s' to '%s' in %s", originalUrl, rewrittenUrl,
cssFileRelativeFilename));
} else if (!dataUrl && !processingImportUrl) {
logger.warning(format("Unable to resolve CSS URL reference '%s' in %s", originalUrl, cssFileRelativeFilename));
}
String replacement;
boolean isAbsoluteUrl = originalUrl.startsWith("http:") || originalUrl.startsWith("https:") || originalUrl.startsWith(":
if(isAbsoluteUrl)
rewrittenUrl = originalUrl;
if (processingImportUrl) {
if(!isAbsoluteUrl)
logger.warning(format(
"Warning: CSS @import statements are not fully supported yet. Detected @import of %s in %s", originalUrl,
cssFileRelativeFilename));
replacement = format("@import \"%s\";", rewrittenUrl);
} else {
replacement = format("url(\"%s\")", rewrittenUrl);
}
matcher.appendReplacement(stringBuffer, replacement);
}
matcher.appendTail(stringBuffer);
String rewrittenFileContents = stringBuffer.toString();
try {
Files.write(cssFile, rewrittenFileContents.getBytes(UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(format("Unable to write rewritten CSS file %s", cssFileRelativeFilename), e);
}
}
protected Pattern createCssUrlPattern() {
// TODO: use a better regex, currently it fails in these cases.
// This is OK since we work around it manually, but would be good to fix once and for all in the pattern.
// src: url("/static/fonts/example/myfont.eot?#iefix") format('embedded-opentype')
// will match as
// /static/fonts/example/myfont.eot?#iefix
// instead of
// /static/fonts/example/myfont.eot
// and
// url("/static/fonts/example/myfont.svg#ExampleRegular")
// will match as
// /static/fonts/example/myfont.svg#ExampleRegular
// instead of
// /static/fonts/example/myfont.svg
String cssUrlPattern = "url\\s*\\(\\s*['\"]?(.+?)\\s*['\"]?\\s*\\)";
String cssImportUrlPattern = "@import\\s+['\"](.+?)['\"].*;";
String alternateCssImportUrlPattern = "@import\\s+url\\(\\s*['\"](.+?)['\"]\\).*;";
return compile(format("%s|%s|%s", cssUrlPattern, cssImportUrlPattern, alternateCssImportUrlPattern),
CASE_INSENSITIVE);
}
protected boolean shouldZipStaticFile(Path staticFile) {
requireNonNull(staticFile);
String filename = staticFile.getFileName().toString().toLowerCase(ENGLISH);
int lastIndexOfFileSeparator = filename.lastIndexOf(File.separator);
int lastIndexOfPeriod = filename.lastIndexOf(".");
if (lastIndexOfPeriod == -1 || filename.endsWith(".") || lastIndexOfFileSeparator > lastIndexOfPeriod) return true;
String extension = filename.substring(lastIndexOfPeriod + 1);
return !staticFileConfiguration().get().unzippableExtensions().contains(extension);
}
public static class Builder {
private final Path archiveFile;
private Set<ArchivePath> archivePaths = emptySet();
private Set<Path> pathsToExclude = defaultPathsToExclude();
private Optional<StaticFileConfiguration> staticFileConfiguration = Optional.empty();
private Optional<MavenSupport> mavenSupport = Optional.empty();
private Optional<ArchiveSupportOperation> preProcessOperation = Optional.empty();
private Optional<ArchiveSupportOperation> postProcessOperation = Optional.empty();
private Optional<FileAlterationOperation> fileAlterationOperation = Optional.empty();
protected Builder(Path archiveFile) {
this.archiveFile = requireNonNull(archiveFile);
}
public Builder archivePaths(Set<ArchivePath> archivePaths) {
this.archivePaths = unmodifiableSet(new HashSet<>(requireNonNull(archivePaths)));
return this;
}
public Builder pathsToExclude(Set<Path> pathsToExclude) {
this.pathsToExclude = unmodifiableSet(new HashSet<>(requireNonNull(pathsToExclude)));
return this;
}
public Builder staticFileConfiguration(StaticFileConfiguration staticFileConfiguration) {
this.staticFileConfiguration = Optional.ofNullable(staticFileConfiguration);
return this;
}
public Builder mavenSupport() {
this.mavenSupport = Optional.of(MavenSupport.standard());
return this;
}
public Builder mavenSupport(MavenSupport mavenSupport) {
this.mavenSupport = Optional.ofNullable(mavenSupport);
return this;
}
public Builder preProcessOperation(ArchiveSupportOperation preProcessOperation) {
this.preProcessOperation = Optional.ofNullable(preProcessOperation);
return this;
}
public Builder postProcessOperation(ArchiveSupportOperation postProcessOperation) {
this.postProcessOperation = Optional.ofNullable(postProcessOperation);
return this;
}
public Builder fileAlterationOperation(FileAlterationOperation fileAlterationOperation) {
this.fileAlterationOperation = Optional.ofNullable(fileAlterationOperation);
return this;
}
public Archiver build() {
return new Archiver(this);
}
}
public static class MavenSupport {
private final Path mavenExecutableFile;
private final List<String> cleanArguments;
private final List<String> compileArguments;
private final List<String> dependenciesArguments;
protected MavenSupport(Builder builder) {
requireNonNull(builder);
this.mavenExecutableFile = builder.mavenExecutableFile;
this.cleanArguments = builder.cleanArguments;
this.compileArguments = builder.compileArguments;
this.dependenciesArguments = builder.dependenciesArguments;
}
public static Builder newBuilder() {
return new Builder();
}
public static MavenSupport standard() {
return new MavenSupport(newBuilder());
}
public static class Builder {
private Path mavenExecutableFile;
private List<String> cleanArguments;
private List<String> compileArguments;
private List<String> dependenciesArguments;
protected Builder() {
this.cleanArguments = unmodifiableList(new ArrayList<String>() {
{
add("clean");
}
});
this.compileArguments = unmodifiableList(new ArrayList<String>() {
{
add("compile");
}
});
this.dependenciesArguments = unmodifiableList(new ArrayList<String>() {
{
add("-DincludeScope=runtime");
add("dependency:copy-dependencies");
}
});
// TODO: support configuration of this through code as well
String mavenHome = trimToNull(System.getProperty("soklet.MAVEN_HOME"));
if (mavenHome == null) mavenHome = trimToNull(System.getenv("MAVEN_HOME"));
if (mavenHome == null) mavenHome = trimToNull(System.getenv("M2_HOME"));
if (mavenHome == null)
throw new ArchiveException(
"In order to determine the absolute path to your mvn executable, the soklet.MAVEN_HOME system property "
+ "or either the M2_HOME or MAVEN_HOME environment variables must be defined");
this.mavenExecutableFile = Paths.get(format("%s/bin/mvn", mavenHome));
}
public Builder mavenExecutableFile(Path mavenExecutableFile) {
this.mavenExecutableFile = requireNonNull(mavenExecutableFile);
return this;
}
public Builder cleanArguments(Function<List<String>, List<String>> function) {
this.cleanArguments = unmodifiableList(new ArrayList<>(requireNonNull(function.apply(this.cleanArguments))));
return this;
}
public Builder compileArguments(Function<List<String>, List<String>> function) {
this.compileArguments =
unmodifiableList(new ArrayList<>(requireNonNull(function.apply(this.compileArguments))));
return this;
}
public Builder dependenciesArguments(Function<List<String>, List<String>> function) {
this.dependenciesArguments =
unmodifiableList(new ArrayList<>(requireNonNull(function.apply(this.dependenciesArguments))));
return this;
}
public MavenSupport build() {
return new MavenSupport(this);
}
}
public List<String> cleanArguments() {
return this.cleanArguments;
}
public List<String> compileArguments() {
return this.compileArguments;
}
public List<String> dependenciesArguments() {
return this.dependenciesArguments;
}
public Path mavenExecutableFile() {
return this.mavenExecutableFile;
}
}
public static Set<Path> defaultPathsToExclude() {
return DEFAULT_PATHS_TO_EXCLUDE;
}
public Path archiveFile() {
return this.archiveFile;
}
public Set<ArchivePath> archivePaths() {
return this.archivePaths;
}
public Set<Path> pathsToExclude() {
return this.pathsToExclude;
}
public Optional<StaticFileConfiguration> staticFileConfiguration() {
return this.staticFileConfiguration;
}
public Optional<MavenSupport> mavenSupport() {
return this.mavenSupport;
}
public Optional<ArchiveSupportOperation> preProcessOperation() {
return this.preProcessOperation;
}
public Optional<ArchiveSupportOperation> postProcessOperation() {
return this.postProcessOperation;
}
public Optional<FileAlterationOperation> fileAlterationOperation() {
return this.fileAlterationOperation;
}
public static class StaticFileConfiguration {
public static final Set<String> DEFAULT_UNZIPPABLE_EXTENSIONS = unmodifiableSet(new HashSet<String>() {
{
// Image
add("png");
add("jpeg");
add("jpg");
add("gif");
// Audio
add("aif");
add("m4a");
add("m4v");
add("mp3");
add("mp4");
add("mpa");
add("wma");
}
});
public static final Hasher DEFAULT_FILE_HASHER = (bytes) -> {
requireNonNull(bytes);
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException("Unable to create hasher", e);
}
byte[] hashBytes = messageDigest.digest(bytes);
StringBuilder stringBuilder = new StringBuilder(2 * hashBytes.length);
for (byte b : hashBytes) {
stringBuilder.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
stringBuilder.append("0123456789ABCDEF".charAt((b & 0x0F)));
}
return stringBuilder.toString();
};
public static final FilenameHasher DEFAULT_FILENAME_HASHER = (file, hash) -> {
requireNonNull(file);
requireNonNull(hash);
String filename = file.toAbsolutePath().toString();
int lastIndexOfFileSeparator = filename.lastIndexOf(File.separator);
int lastIndexOfPeriod = filename.lastIndexOf(".");
// Handles files with no extensions
if (lastIndexOfPeriod == -1 || lastIndexOfFileSeparator > lastIndexOfPeriod)
return format("%s.%s", filename, hash);
// Handles files that end with a dot
if (filename.endsWith(".")) return format("%s%s", filename, hash);
// Default behavior
return format("%s.%s%s", filename.substring(0, lastIndexOfPeriod), hash, filename.substring(lastIndexOfPeriod));
};
private final Path rootDirectory;
private final Optional<Path> hashedUrlManifestJsFile;
private final Hasher fileHasher;
private final FilenameHasher filenameHasher;
private final Set<String> unzippableExtensions;
protected StaticFileConfiguration(Builder builder) {
this.rootDirectory = builder.rootDirectory;
this.hashedUrlManifestJsFile = builder.hashedUrlManifestJsFile;
this.fileHasher = builder.fileHasher;
this.filenameHasher = builder.filenameHasher;
this.unzippableExtensions = builder.unzippableExtensions;
}
public static Builder forRootDirectory(Path rootDirectory) {
requireNonNull(rootDirectory);
return new Builder(rootDirectory);
}
public static class Builder {
private final Path rootDirectory;
private Optional<Path> hashedUrlManifestJsFile = Optional.empty();
private Hasher fileHasher = DEFAULT_FILE_HASHER;
private FilenameHasher filenameHasher = DEFAULT_FILENAME_HASHER;
private Set<String> unzippableExtensions = DEFAULT_UNZIPPABLE_EXTENSIONS;
private Builder(Path rootDirectory) {
this.rootDirectory = requireNonNull(rootDirectory);
}
public Builder hashedUrlManifestJsFile(Path hashedUrlManifestJsFile) {
this.hashedUrlManifestJsFile = Optional.ofNullable(hashedUrlManifestJsFile);
return this;
}
public Builder fileHasher(Hasher fileHasher) {
this.fileHasher = requireNonNull(fileHasher);
return this;
}
public Builder filenameHasher(FilenameHasher filenameHasher) {
this.filenameHasher = requireNonNull(filenameHasher);
return this;
}
public Builder unzippableExtensions(Set<String> unzippableExtensions) {
this.unzippableExtensions = unmodifiableSet(new HashSet<>(requireNonNull(unzippableExtensions)));
return this;
}
public StaticFileConfiguration build() {
return new StaticFileConfiguration(this);
}
}
public Path rootDirectory() {
return this.rootDirectory;
}
public Optional<Path> hashedUrlManifestJsFile() {
return this.hashedUrlManifestJsFile;
}
public Hasher fileHasher() {
return this.fileHasher;
}
public FilenameHasher filenameHasher() {
return this.filenameHasher;
}
public Set<String> unzippableExtensions() {
return this.unzippableExtensions;
}
}
@FunctionalInterface
public interface ArchiveSupportOperation {
/**
* Executes an operation which supports archive creation.
*
* @param archiver
* the {@link Archiver} currently running
* @param workingDirectory
* the temporary directory context in which the {@link Archiver} is working
* @throws Exception
* if an error occurs while executing the archive support operation
*/
void perform(Archiver archiver, Path workingDirectory) throws Exception;
}
@FunctionalInterface
public interface FileAlterationOperation {
/**
* Executes an operation which (possibly) alters a file.
*
* @param archiver
* the {@link Archiver} currently running
* @param workingDirectory
* the temporary directory context in which the {@link Archiver} is working
* @param file
* the file to (possibly) alter
* @return bytes for the altered file, or empty if the file does not need to be altered
* @throws Exception
* if an error occurs while altering the file
*/
Optional<InputStream> alterFile(Archiver archiver, Path workingDirectory, Path file) throws Exception;
}
@FunctionalInterface
public interface Hasher {
String hash(byte[] data);
}
@FunctionalInterface
public interface FilenameHasher {
String hashFilename(Path file, String hash);
}
} |
// Colors.java
package imagej.util;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public final class Colors {
public static final ColorRGB ALICEBLUE = new ColorRGB(240, 248, 255);
public static final ColorRGB ANTIQUEWHITE = new ColorRGB(250, 235, 215);
public static final ColorRGB AQUA = new ColorRGB(0, 255, 255);
public static final ColorRGB AQUAMARINE = new ColorRGB(127, 255, 212);
public static final ColorRGB AZURE = new ColorRGB(240, 255, 255);
public static final ColorRGB BEIGE = new ColorRGB(245, 245, 220);
public static final ColorRGB BISQUE = new ColorRGB(255, 228, 196);
public static final ColorRGB BLACK = new ColorRGB(0, 0, 0);
public static final ColorRGB BLANCHEDALMOND = new ColorRGB(255, 235, 205);
public static final ColorRGB BLUE = new ColorRGB(0, 0, 255);
public static final ColorRGB BLUEVIOLET = new ColorRGB(138, 43, 226);
public static final ColorRGB BROWN = new ColorRGB(165, 42, 42);
public static final ColorRGB BURLYWOOD = new ColorRGB(222, 184, 135);
public static final ColorRGB CADETBLUE = new ColorRGB(95, 158, 160);
public static final ColorRGB CHARTREUSE = new ColorRGB(127, 255, 0);
public static final ColorRGB CHOCOLATE = new ColorRGB(210, 105, 30);
public static final ColorRGB CORAL = new ColorRGB(255, 127, 80);
public static final ColorRGB CORNFLOWERBLUE = new ColorRGB(100, 149, 237);
public static final ColorRGB CORNSILK = new ColorRGB(255, 248, 220);
public static final ColorRGB CRIMSON = new ColorRGB(220, 20, 60);
public static final ColorRGB CYAN = new ColorRGB(0, 255, 255);
public static final ColorRGB DARKBLUE = new ColorRGB(0, 0, 139);
public static final ColorRGB DARKCYAN = new ColorRGB(0, 139, 139);
public static final ColorRGB DARKGOLDENROD = new ColorRGB(184, 134, 11);
public static final ColorRGB DARKGRAY = new ColorRGB(169, 169, 169);
public static final ColorRGB DARKGREEN = new ColorRGB(0, 100, 0);
public static final ColorRGB DARKGREY = DARKGRAY;
public static final ColorRGB DARKKHAKI = new ColorRGB(189, 183, 107);
public static final ColorRGB DARKMAGENTA = new ColorRGB(139, 0, 139);
public static final ColorRGB DARKOLIVEGREEN = new ColorRGB(85, 107, 47);
public static final ColorRGB DARKORANGE = new ColorRGB(255, 140, 0);
public static final ColorRGB DARKORCHID = new ColorRGB(153, 50, 204);
public static final ColorRGB DARKRED = new ColorRGB(139, 0, 0);
public static final ColorRGB DARKSALMON = new ColorRGB(233, 150, 122);
public static final ColorRGB DARKSEAGREEN = new ColorRGB(143, 188, 143);
public static final ColorRGB DARKSLATEBLUE = new ColorRGB(72, 61, 139);
public static final ColorRGB DARKSLATEGRAY = new ColorRGB(47, 79, 79);
public static final ColorRGB DARKSLATEGREY = DARKSLATEGRAY;
public static final ColorRGB DARKTURQUOISE = new ColorRGB(0, 206, 209);
public static final ColorRGB DARKVIOLET = new ColorRGB(148, 0, 211);
public static final ColorRGB DEEPPINK = new ColorRGB(255, 20, 147);
public static final ColorRGB DEEPSKYBLUE = new ColorRGB(0, 191, 255);
public static final ColorRGB DIMGRAY = new ColorRGB(105, 105, 105);
public static final ColorRGB DIMGREY = DIMGRAY;
public static final ColorRGB DODGERBLUE = new ColorRGB(30, 144, 255);
public static final ColorRGB FIREBRICK = new ColorRGB(178, 34, 34);
public static final ColorRGB FLORALWHITE = new ColorRGB(255, 250, 240);
public static final ColorRGB FORESTGREEN = new ColorRGB(34, 139, 34);
public static final ColorRGB FUCHSIA = new ColorRGB(255, 0, 255);
public static final ColorRGB GAINSBORO = new ColorRGB(220, 220, 220);
public static final ColorRGB GHOSTWHITE = new ColorRGB(248, 248, 255);
public static final ColorRGB GOLD = new ColorRGB(255, 215, 0);
public static final ColorRGB GOLDENROD = new ColorRGB(218, 165, 32);
public static final ColorRGB GRAY = new ColorRGB(128, 128, 128);
public static final ColorRGB GREEN = new ColorRGB(0, 128, 0);
public static final ColorRGB GREENYELLOW = new ColorRGB(173, 255, 47);
public static final ColorRGB GREY = GRAY;
public static final ColorRGB HONEYDEW = new ColorRGB(240, 255, 240);
public static final ColorRGB HOTPINK = new ColorRGB(255, 105, 180);
public static final ColorRGB INDIANRED = new ColorRGB(205, 92, 92);
public static final ColorRGB INDIGO = new ColorRGB(75, 0, 130);
public static final ColorRGB IVORY = new ColorRGB(255, 255, 240);
public static final ColorRGB KHAKI = new ColorRGB(240, 230, 140);
public static final ColorRGB LAVENDER = new ColorRGB(230, 230, 250);
public static final ColorRGB LAVENDERBLUSH = new ColorRGB(255, 240, 245);
public static final ColorRGB LAWNGREEN = new ColorRGB(124, 252, 0);
public static final ColorRGB LEMONCHIFFON = new ColorRGB(255, 250, 205);
public static final ColorRGB LIGHTBLUE = new ColorRGB(173, 216, 230);
public static final ColorRGB LIGHTCORAL = new ColorRGB(240, 128, 128);
public static final ColorRGB LIGHTCYAN = new ColorRGB(224, 255, 255);
public static final ColorRGB LIGHTGOLDENRODYELLOW = new ColorRGB(250, 250,
210);
public static final ColorRGB LIGHTGRAY = new ColorRGB(211, 211, 211);
public static final ColorRGB LIGHTGREEN = new ColorRGB(144, 238, 144);
public static final ColorRGB LIGHTGREY = LIGHTGRAY;
public static final ColorRGB LIGHTPINK = new ColorRGB(255, 182, 193);
public static final ColorRGB LIGHTSALMON = new ColorRGB(255, 160, 122);
public static final ColorRGB LIGHTSEAGREEN = new ColorRGB(32, 178, 170);
public static final ColorRGB LIGHTSKYBLUE = new ColorRGB(135, 206, 250);
public static final ColorRGB LIGHTSLATEGRAY = new ColorRGB(119, 136, 153);
public static final ColorRGB LIGHTSLATEGREY = LIGHTSLATEGRAY;
public static final ColorRGB LIGHTSTEELBLUE = new ColorRGB(176, 196, 222);
public static final ColorRGB LIGHTYELLOW = new ColorRGB(255, 255, 224);
public static final ColorRGB LIME = new ColorRGB(0, 255, 0);
public static final ColorRGB LIMEGREEN = new ColorRGB(50, 205, 50);
public static final ColorRGB LINEN = new ColorRGB(250, 240, 230);
public static final ColorRGB MAGENTA = new ColorRGB(255, 0, 255);
public static final ColorRGB MAROON = new ColorRGB(128, 0, 0);
public static final ColorRGB MEDIUMAQUAMARINE = new ColorRGB(102, 205, 170);
public static final ColorRGB MEDIUMBLUE = new ColorRGB(0, 0, 205);
public static final ColorRGB MEDIUMORCHID = new ColorRGB(186, 85, 211);
public static final ColorRGB MEDIUMPURPLE = new ColorRGB(147, 112, 219);
public static final ColorRGB MEDIUMSEAGREEN = new ColorRGB(60, 179, 113);
public static final ColorRGB MEDIUMSLATEBLUE = new ColorRGB(123, 104, 238);
public static final ColorRGB MEDIUMSPRINGGREEN = new ColorRGB(0, 250, 154);
public static final ColorRGB MEDIUMTURQUOISE = new ColorRGB(72, 209, 204);
public static final ColorRGB MEDIUMVIOLETRED = new ColorRGB(199, 21, 133);
public static final ColorRGB MIDNIGHTBLUE = new ColorRGB(25, 25, 112);
public static final ColorRGB MINTCREAM = new ColorRGB(245, 255, 250);
public static final ColorRGB MISTYROSE = new ColorRGB(255, 228, 225);
public static final ColorRGB MOCCASIN = new ColorRGB(255, 228, 181);
public static final ColorRGB NAVAJOWHITE = new ColorRGB(255, 222, 173);
public static final ColorRGB NAVY = new ColorRGB(0, 0, 128);
public static final ColorRGB OLDLACE = new ColorRGB(253, 245, 230);
public static final ColorRGB OLIVE = new ColorRGB(128, 128, 0);
public static final ColorRGB OLIVEDRAB = new ColorRGB(107, 142, 35);
public static final ColorRGB ORANGE = new ColorRGB(255, 165, 0);
public static final ColorRGB ORANGERED = new ColorRGB(255, 69, 0);
public static final ColorRGB ORCHID = new ColorRGB(218, 112, 214);
public static final ColorRGB PALEGOLDENROD = new ColorRGB(238, 232, 170);
public static final ColorRGB PALEGREEN = new ColorRGB(152, 251, 152);
public static final ColorRGB PALETURQUOISE = new ColorRGB(175, 238, 238);
public static final ColorRGB PALEVIOLETRED = new ColorRGB(219, 112, 147);
public static final ColorRGB PAPAYAWHIP = new ColorRGB(255, 239, 213);
public static final ColorRGB PEACHPUFF = new ColorRGB(255, 218, 185);
public static final ColorRGB PERU = new ColorRGB(205, 133, 63);
public static final ColorRGB PINK = new ColorRGB(255, 192, 203);
public static final ColorRGB PLUM = new ColorRGB(221, 160, 221);
public static final ColorRGB POWDERBLUE = new ColorRGB(176, 224, 230);
public static final ColorRGB PURPLE = new ColorRGB(128, 0, 128);
public static final ColorRGB RED = new ColorRGB(255, 0, 0);
public static final ColorRGB ROSYBROWN = new ColorRGB(188, 143, 143);
public static final ColorRGB ROYALBLUE = new ColorRGB(65, 105, 225);
public static final ColorRGB SADDLEBROWN = new ColorRGB(139, 69, 19);
public static final ColorRGB SALMON = new ColorRGB(250, 128, 114);
public static final ColorRGB SANDYBROWN = new ColorRGB(244, 164, 96);
public static final ColorRGB SEAGREEN = new ColorRGB(46, 139, 87);
public static final ColorRGB SEASHELL = new ColorRGB(255, 245, 238);
public static final ColorRGB SIENNA = new ColorRGB(160, 82, 45);
public static final ColorRGB SILVER = new ColorRGB(192, 192, 192);
public static final ColorRGB SKYBLUE = new ColorRGB(135, 206, 235);
public static final ColorRGB SLATEBLUE = new ColorRGB(106, 90, 205);
public static final ColorRGB SLATEGRAY = new ColorRGB(112, 128, 144);
public static final ColorRGB SLATEGREY = SLATEGRAY;
public static final ColorRGB SNOW = new ColorRGB(255, 250, 250);
public static final ColorRGB SPRINGGREEN = new ColorRGB(0, 255, 127);
public static final ColorRGB STEELBLUE = new ColorRGB(70, 130, 180);
public static final ColorRGB TAN = new ColorRGB(210, 180, 140);
public static final ColorRGB TEAL = new ColorRGB(0, 128, 128);
public static final ColorRGB THISTLE = new ColorRGB(216, 191, 216);
public static final ColorRGB TOMATO = new ColorRGB(255, 99, 71);
public static final ColorRGB TURQUOISE = new ColorRGB(64, 224, 208);
public static final ColorRGB VIOLET = new ColorRGB(238, 130, 238);
public static final ColorRGB WHEAT = new ColorRGB(245, 222, 179);
public static final ColorRGB WHITE = new ColorRGB(255, 255, 255);
public static final ColorRGB WHITESMOKE = new ColorRGB(245, 245, 245);
public static final ColorRGB YELLOW = new ColorRGB(255, 255, 0);
public static final ColorRGB YELLOWGREEN = new ColorRGB(154, 205, 50);
private static final Map<String, ColorRGB> COLORS =
new HashMap<String, ColorRGB>();
static {
for (final Field f : Colors.class.getDeclaredFields()) {
final Object value;
try {
value = f.get(null);
}
catch (final IllegalArgumentException e) {
continue;
}
catch (final IllegalAccessException e) {
continue;
}
if (!(value instanceof ColorRGB)) continue; // not a color
final ColorRGB color = (ColorRGB) value;
COLORS.put(f.getName().toLowerCase(), color);
}
}
private Colors() {
// prevent instantiation of utility class
}
/**
* Gets the preset color with the given name. For example,
* <code>Colors.get("red")</code> will return {@link Colors#RED}.
*/
public static ColorRGB getColor(final String name) {
return COLORS.get(name);
}
/** Gets the name of the preset matching the given color. */
public static String getName(final ColorRGB color) {
if (color == null) return null;
for (final String name : COLORS.keySet()) {
final ColorRGB value = COLORS.get(name);
if (color.equals(value)) return name;
}
return null;
}
/** Gets the table of all preset colors. */
public static Map<String, ColorRGB> map() {
return Collections.unmodifiableMap(COLORS);
}
/** Gets the list of all preset colors. */
public static Collection<ColorRGB> values() {
return COLORS.values();
}
/** Returns the preset color closest to a given color. The definition of
* closest is the nearest color in RGB space. */
public static ColorRGB getClosestPresetColor(ColorRGB color) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
ColorRGB bestSoFar = null;
double distance = Double.POSITIVE_INFINITY;
boolean firstPass = true;
for (ColorRGB presetColor : COLORS.values()) {
if (firstPass) {
bestSoFar = presetColor;
firstPass = false;
}
else { // not first pass
double dr = (presetColor.getRed() - r);
double dg = (presetColor.getGreen() - g);
double db = (presetColor.getBlue() - b);
double thisDist = dr*dr + dg*dg + db*db;
if (thisDist < distance) {
bestSoFar = presetColor;
distance = thisDist;
}
}
}
return bestSoFar;
}
} |
package com.tectonica.util;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
public class KryoUtil
{
private static class KryoBox
{
final Kryo kryo;
final Output output;
public KryoBox()
{
kryo = new Kryo();
configure(kryo);
output = new Output(1024, -1);
}
}
public static interface Configurator
{
void configure(Kryo kryo);
}
private static Configurator defaultConfigurator = new Configurator()
{
@Override
public void configure(Kryo kryo)
{
kryo.setReferences(false); // faster, but not suitable when cross-references are used (especially cyclic)
// kryo.setDefaultSerializer(CompatibleFieldSerializer.class);
}
};
private static void configure(Kryo kryo)
{
// TODO: allow an SPI for custom configuration
defaultConfigurator.configure(kryo);
}
private static ThreadLocal<KryoBox> kryos = new ThreadLocal<KryoBox>()
{
protected KryoBox initialValue()
{
return new KryoBox();
}
};
public static byte[] objToBytes(Object obj)
{
KryoBox kryoBox = kryos.get();
kryoBox.output.clear();
kryoBox.kryo.writeObject(kryoBox.output, obj);
return kryoBox.output.toBytes();
}
public static <V> V bytesToObj(byte[] bytes, Class<V> clz)
{
return kryos.get().kryo.readObject(new Input(bytes), clz);
}
public static <V> V copyOf(V obj)
{
return kryos.get().kryo.copy(obj);
}
private static Kryo kryo = new Kryo();
private static Output output = new Output(1024, -1);
static
{
configure(kryo);
}
public static byte[] objToBytes_SingleThreaded(Object obj)
{
output.clear();
kryo.writeObject(output, obj);
return output.toBytes();
}
public static <V> V bytesToObj_SingleThreaded(byte[] bytes, Class<V> clz)
{
return kryo.readObject(new Input(bytes), clz);
}
public static <V> V copyOf_SingleThreaded(V obj)
{
return kryo.copy(obj);
}
} |
/*
* $Id: ConfigurationPropTreeImpl.java,v 1.9 2010-04-05 17:05:51 pgust Exp $
*/
package org.lockss.config;
import java.io.*;
import java.util.*;
import org.lockss.util.*;
/** <code>ConfigurationPropTreeImpl</code> represents the config parameters
* as a {@link org.lockss.util.PropertyTree}
*/
public class ConfigurationPropTreeImpl extends Configuration {
private PropertyTree props;
private boolean isSealed = false;
ConfigurationPropTreeImpl() {
super();
props = new PropertyTree();
}
private ConfigurationPropTreeImpl(PropertyTree tree) {
super();
props = tree;
}
PropertyTree getPropertyTree() {
return props;
}
public boolean store(OutputStream ostr, String header) throws IOException {
SortedProperties.fromProperties(props).store(ostr, header);
// props.store(ostr, header);
return true;
}
/**
* Reset this instance.
*/
void reset() {
super.reset();
props.clear();
}
/** Return the set of keys whose values differ.
* This operation is transitive: c1.differentKeys(c2) yields the same
* result as c2.differentKeys(c1).
*
* @param otherConfig the config to compare with. May be null.
*/
public Set<String> differentKeys(Configuration otherConfig) {
if (this == otherConfig) {
return Collections.EMPTY_SET;
}
PropertyTree otherTree = (otherConfig == null) ?
new PropertyTree() : ((ConfigurationPropTreeImpl)otherConfig).getPropertyTree();
return PropUtil.differentKeysAndPrefixes(getPropertyTree(), otherTree);
}
public boolean containsKey(String key) {
return props.containsKey(key);
}
public String get(String key) {
return (String)props.get(key);
}
/**
* Return a list of values for the given key.
*/
public List getList(String key) {
List propList = null;
try {
Object o = props.get(key);
if (o != null) {
if (o instanceof List) {
propList = (List)o;
} else {
propList = StringUtil.breakAt((String)o, ';', 0, true);
}
} else {
propList = Collections.EMPTY_LIST;
}
} catch (ClassCastException ex) {
// The client requested a list of something that wasn't actually a list.
// Throw an exception
throw new IllegalArgumentException("Key does not hold a list value: " + key);
}
return propList;
}
public void put(String key, String val) {
if (isSealed) {
throw new IllegalStateException("Can't modify sealed configuration");
}
props.setProperty(key, val);
}
/** Remove the value associated with <code>key</code>.
* @param key the config key to remove
*/
public void remove(String key) {
if (isSealed) {
throw new IllegalStateException("Can't modify sealed configuration");
}
props.remove(key);
}
public void seal() {
isSealed = true;
// also seal the title database
Tdb tdb = getTdb();
if (tdb != null) {
tdb.seal();
}
}
public boolean isSealed() {
return isSealed;
}
public Configuration getConfigTree(String key) {
PropertyTree tree = props.getTree(key);
if (tree == null) {
return null;
}
Configuration res = new ConfigurationPropTreeImpl(tree);
if (isSealed()) {
res.seal();
}
return res;
}
public Set keySet() {
return Collections.unmodifiableSet(props.keySet());
}
public Iterator keyIterator() {
return keySet().iterator();
}
public Iterator nodeIterator() {
return possiblyEmptyIterator(props.getNodes());
}
public Iterator nodeIterator(String key) {
return possiblyEmptyIterator(props.getNodes(key));
}
private Iterator possiblyEmptyIterator(Enumeration en) {
if (en != null) {
return new EnumerationIterator(en);
} else {
return CollectionUtil.EMPTY_ITERATOR;
}
}
public String toString() {
return getPropertyTree().toString();
}
} |
package com.test.util;
import io.selendroid.SelendroidCapabilities;
import io.selendroid.SelendroidDriver;
import io.selendroid.device.DeviceTargetPlatform;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.testng.Assert;
public class CommonMethods {
// public SelendroidCapabilities capa;
public WebDriver driver;
final String pathSeparator = File.separator;
public static final String NATIVE_APP = "NATIVE_APP";
public static final String WEBVIEW = "WEBVIEW";
public static final String appId = "io.selendroid.testapp:0.5.1";
public void startApplication() throws Exception {
SelendroidCapabilities capa = SelendroidCapabilities.device(
DeviceTargetPlatform.ANDROID17, appId);
driver = new SelendroidDriver("http://localhost:5555/wd/hub", capa);
}
public void killApp() {
driver.quit();
}
public void openStartActivity() {
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String activityClass = "io.selendroid.testapp." + "HomeScreenActivity";
driver.switchTo().window(NATIVE_APP);
driver.get("and-activity://" + activityClass);
}
public void assertInputField(String objectId) {
WebElement inputField = driver.findElement(By.id(objectId));
Assert.assertEquals("true", inputField.getAttribute("enabled"));
}
public void clickButton(String objectButtonId) {
WebElement button = driver.findElement(By.id(objectButtonId));
button.click();
}
public void assertTextPresent(String ID, String element) {
Assert.assertEquals(element, driver.findElement(By.id(ID)).getText());
}
protected void takeScreenShot() throws Exception {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot) augmentedDriver)
.getScreenshotAs(OutputType.FILE);
String nameScreenshot = UUID.randomUUID().toString() + ".png";
File directory = new File(".");
String newFileNamePath = directory.getCanonicalPath() + pathSeparator
+ "target" + pathSeparator + "jbehave" + pathSeparator
+ "screenshots" + pathSeparator + nameScreenshot;
FileUtils.copyFile(screenshot, new File(newFileNamePath));
// return newFileNamePath;
/*
* Reporter.log(message + "<br/><a href='file:///" + path +
* "'> <img src='file:///" + path +
* "' height='100' width='100'/> </a>");
*/
}
/*
* protected String getPath() throws IOException { File directory = new
* File(".");
*
* String newFileNamePath = directory.getCanonicalPath() + pathSeparator +
* "target" + pathSeparator + "jbehave" + pathSeparator + "screenshots" +
* pathSeparator + nameScreenshot; return newFileNamePath; }
*/
public void clickByID(String ID) {
driver.findElement(By.id(ID)).click();
}
public void inputByID(String ID, String sendParam) {
driver.findElement(By.id(ID)).sendKeys(sendParam);
}
} |
package edu.cuny.citytech.refactoring.common.tests;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.Logger;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
@SuppressWarnings("restriction")
public abstract class RefactoringTest extends org.eclipse.jdt.ui.tests.refactoring.RefactoringTest {
/**
* The name of the directory containing resources under the project
* directory.
*/
private static final String RESOURCE_PATH = "resources";
public RefactoringTest(String name) {
super(name);
}
private static void assertFailedPrecondition(RefactoringStatus initialStatus, RefactoringStatus finalStatus) {
assertTrue("Precondition was supposed to fail.", !initialStatus.isOK() || !finalStatus.isOK());
}
protected void assertFailedPrecondition(IMethod... methods) throws CoreException {
Refactoring refactoring = getRefactoring(methods);
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertFailedPrecondition(initialStatus, finalStatus);
}
protected abstract Logger getLogger(); // TODO: Should use built-in Eclipse
// logger.
/**
* Returns the refactoring to be tested.
*
* @param methods
* The methods to refactor.
* @param cu
* The compilation unit being tested. Can be null.
* @return The refactoring to be tested.
* @throws JavaModelException
*/
protected abstract Refactoring getRefactoring(IMethod... methods) throws JavaModelException; // TODO:
// Should
// use
// createRefactoring().
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jdt.ui.tests.refactoring.RefactoringTest#getFileContents(java
* .lang.String) Had to override this method because, since this plug-in is
* a fragment (at least I think that this is the reason), it doesn't have an
* activator and the bundle is resolving to the eclipse refactoring test
* bundle.
*/
@Override
public String getFileContents(String fileName) throws IOException {
Path path = Paths.get(RESOURCE_PATH, fileName);
Path absolutePath = path.toAbsolutePath();
byte[] encoded = Files.readAllBytes(absolutePath);
return new String(encoded, Charset.defaultCharset());
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jdt.ui.tests.refactoring.RefactoringTest#createCUfromTestFile
* (org.eclipse.jdt.core.IPackageFragment, java.lang.String)
*/
@Override
protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName) throws Exception {
ICompilationUnit unit = super.createCUfromTestFile(pack, cuName);
if (!unit.isStructureKnown())
throw new IllegalArgumentException(cuName + " has structural errors.");
else
return unit;
}
private void helperFail(String typeName, String outerMethodName, String[] outerSignature, String innerTypeName,
String[] methodNames, String[][] signatures) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), typeName);
IType type = getType(cu, typeName);
if (outerMethodName != null) {
IMethod method = type.getMethod(outerMethodName, outerSignature);
if (innerTypeName != null) {
type = method.getType(innerTypeName, 1); // get the local type
} else {
type = method.getType("", 1); // get the anonymous type.
}
} else if (innerTypeName != null) {
type = type.getType(innerTypeName); // get the member type.
}
IMethod[] methods = getMethods(type, methodNames, signatures);
assertFailedPrecondition(methods);
}
protected void helperFail(String outerMethodName, String[] outerSignature, String innerTypeName,
String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", outerMethodName, outerSignature, innerTypeName, methodNames, signatures);
}
/**
* Check for a failed precondition for a case with an inner type.
*
* @param outerMethodName
* The method declaring the anonymous type.
* @param outerSignature
* The signature of the method declaring the anonymous type.
* @param methodNames
* The methods in the anonymous type.
* @param signatures
* The signatures of the methods in the anonymous type.
* @throws Exception
*/
protected void helperFail(String outerMethodName, String[] outerSignature, String[] methodNames,
String[][] signatures) throws Exception {
helperFail("A", outerMethodName, outerSignature, null, methodNames, signatures);
}
protected void helperFail(String innerTypeName, String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", null, null, innerTypeName, methodNames, signatures);
}
/**
* Check for failed precondition for a simple case.
*
* @param methodNames
* The methods to test.
* @param signatures
* Their signatures.
* @throws Exception
*/
protected void helperFail(String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", null, null, null, methodNames, signatures);
}
/**
* Check for failed preconditions for the case where there is no input.
*
* @throws Exception
*/
protected void helperFail() throws Exception {
helperFail("A", null, null);
}
protected void helperPass(String[] methodNames, String[][] signatures) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
IMethod[] methods = getMethods(type, methodNames, signatures);
Refactoring refactoring = getRefactoring(methods);
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.", initialStatus.isOK() && finalStatus.isOK());
performChange(refactoring, false);
String expected = getFileContents(getOutputTestFileName("A"));
String actual = cu.getSource();
assertEqualLines(expected, actual);
}
/**
* Test methods in two classes, namely, A and B.
*/
protected void helperPass(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.", initialStatus.isOK() && finalStatus.isOK());
performChange(refactoring, false);
String expected = getFileContents(getOutputTestFileName("A"));
String actual = cu.getSource();
assertEqualLines(expected, actual);
}
/**
* Test methods in two classes, namely, A and B, with no fatal errors.
*/
protected void helperPassNoFatal(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.",
!initialStatus.hasFatalError() && !finalStatus.hasFatalError());
performChange(refactoring, false);
String expected = getFileContents(getOutputTestFileName("A"));
String actual = cu.getSource();
assertEqualLines(expected, actual);
}
/**
* Test methods in three classes, namely, A, B, and C, with no fatal errors.
*/
protected void helperPassNoFatal(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2, String[] methodNames3, String[][] signatures3) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
type = getType(cu, "C");
Collections.addAll(methodSet, getMethods(type, methodNames3, signatures3));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.",
!initialStatus.hasFatalError() && !finalStatus.hasFatalError());
performChange(refactoring, false);
String expected = getFileContents(getOutputTestFileName("A"));
String actual = cu.getSource();
assertEqualLines(expected, actual);
}
public void testPlainMethod() throws Exception {
helperPass(new String[] { "m" }, new String[][] { new String[0] });
}
} |
package com.twiki.tools;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class PDFSplitter {
public static void splitPage(File pdfIn, Map<Integer, String> rangePages, File pdfOutFolder) throws IOException {
if (!pdfOutFolder.exists() || pdfOutFolder.isFile()) {
throw new IOException("Folder is not existed");
}
List<Integer> indexPages = Lists.newArrayList(rangePages.keySet());
Collections.sort(indexPages);
String name = FilenameUtils.getBaseName(pdfIn.getName());
File bookFolder = new File(pdfOutFolder, name);
bookFolder.mkdir();
PDDocument document = PDDocument.load(pdfIn);
Splitter splitter = new Splitter() {
protected boolean splitAtPage(int pageNumber) {
return indexPages.contains(pageNumber);
}
};
List<PDDocument> splittedDocuments = splitter.split(document);
for (PDDocument pdDocument : splittedDocuments) {
int index = splittedDocuments.indexOf(pdDocument);
int fromPage = index == 0 ? 0 : indexPages.get(index - 1);
int toPage = (index == splittedDocuments.size() - 1) ? document.getNumberOfPages() : indexPages.get(index);
// String filename = String.format("%02d_%s_%s-%s_%s.pdf", index, name, fromPage + 1, toPage, rangePages.get(indexPages.get(index)));
String filename = String.format("%02d_%s.pdf", index, rangePages.get(indexPages.get(index)));
// String filename = String.format("%s.pdf", rangePages.get(indexPages.get(index)));
pdDocument.save(new File(bookFolder, filename));
}
}
public static void main(String[] args) throws IOException {
File pdfIn = new File("D:\\books\\english\\Writing Academic English, 4th Edition.pdf");
ImmutableMap<Integer, String> indexs = ImmutableMap.<Integer, String>builder()
.put(7, "Table of Content")
.put(10, "Preface")
.put(1 + 10, "PART I_WRITING A PARAGRAPH")
.put(17 + 10, "Chapter 1_Paragraph Structure")
.put(38 + 10, "Chapter 2_Unity and Coherence")
.put(54 + 10, "Chapter 3_Supporting Details Facts, Quotations, and Statistics")
.put(55 + 10, "Part II_ WRITING AN ESSAY")
.put(80 + 10, "Chapter 4_From Paragraph to Essay")
.put(93 + 10, "Chapter 5_Chronological Order_ Process Essays")
.put(110 + 10, "Chapter 6_Cause,Effect essays")
.put(126 + 10, "Chapter 7_Comparison,Contrast Essay")
.put(141 + 10, "Chapter 8_Paraphrase and Summary")
.put(160 + 10, "Chapter 9_Argumentative Essay")
.put(161 + 10, "Part III_SENTENCE STRUCTURE")
.put(178 + 10, "Chapter 10_Types of Sentences")
.put(193 + 10, "Chapter 11_Using Parallel Structures and Fixing Sentence Problems")
.put(209 + 10, "Chapter 12_Noun Clauses")
.put(229 + 10, "Chapter 13_Adverb Clauses")
.put(249 + 10, "Chapter 14_Adjective Clauses")
.put(264 + 10, "Chapter 15_Participial Phrases")
.put(279 + 10, "Appendix A_ The Process of Academic Writing")
.put(290 + 10, "Appendix B_Punctuation Rules")
.put(299 + 10, "Appendix C_Charts of Connecting Words and Transition Signals")
.put(302 + 10, "Appendix D_Editing Symbols")
.put(312 + 10, "Appendix E_Research and Documentation of Sources")
.put(330 + 10, "Appendix F_Self-Editing and Peer-Editing Worksheets")
.put(345, "Index and Credit")
.build();
splitPage(pdfIn, indexs, new File("D:\\books\\english"));
}
} |
package org.maltparser.core.config;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import org.maltparser.core.config.version.Versioning;
import org.maltparser.core.exception.MaltChainedException;
import org.maltparser.core.helper.HashSet;
import org.maltparser.core.helper.SystemInfo;
import org.maltparser.core.helper.SystemLogger;
import org.maltparser.core.helper.URLFinder;
import org.maltparser.core.io.dataformat.DataFormatInstance;
import org.maltparser.core.io.dataformat.DataFormatManager;
import org.maltparser.core.io.dataformat.DataFormatSpecification.DataStructure;
import org.maltparser.core.io.dataformat.DataFormatSpecification.Dependency;
import org.maltparser.core.options.OptionManager;
import org.maltparser.core.symbol.SymbolTableHandler;
import org.maltparser.core.symbol.hash.HashSymbolTableHandler;
import org.maltparser.core.symbol.parse.ParseSymbolTableHandler;
/**
* This class contains methods for handle the configuration directory.
*
* @author Johan Hall
*/
public class ConfigurationDir {
protected static final int BUFFER = 4096;
protected File configDirectory;
protected String name;
protected String type;
protected File workingDirectory;
protected URL url;
protected int containerIndex;
protected BufferedWriter infoFile = null;
protected String createdByMaltParserVersion;
private SymbolTableHandler symbolTables;
private DataFormatManager dataFormatManager;
private HashMap<String,DataFormatInstance> dataFormatInstances;
private URL inputFormatURL;
private URL outputFormatURL;
/**
* Creates a configuration directory from a mco-file specified by an URL.
*
* @param url an URL to a mco-file
* @throws MaltChainedException
*/
public ConfigurationDir(URL url) throws MaltChainedException {
initWorkingDirectory();
setUrl(url);
initNameNTypeFromInfoFile(url);
// initData();
}
/**
* Creates a new configuration directory or a configuration directory from a mco-file
*
* @param name the name of the configuration
* @param type the type of configuration
* @param containerIndex the container index
* @throws MaltChainedException
*/
public ConfigurationDir(String name, String type, int containerIndex) throws MaltChainedException {
setContainerIndex(containerIndex);
initWorkingDirectory();
if (name != null && name.length() > 0 && type != null && type.length() > 0) {
setName(name);
setType(type);
} else {
throw new ConfigurationException("The configuration name is not specified. ");
}
setConfigDirectory(new File(workingDirectory.getPath()+File.separator+getName()));
String mode = OptionManager.instance().getOptionValue(containerIndex, "config", "flowchart").toString().trim();
if (mode.equals("parse")) {
// During parsing also search for the MaltParser configuration file in the class path
File mcoPath = new File(workingDirectory.getPath()+File.separator+getName()+".mco");
if (!mcoPath.exists()) {
String classpath = System.getProperty("java.class.path");
String[] items = classpath.split(System.getProperty("path.separator"));
boolean found = false;
for (String item : items) {
File candidateDir = new File(item);
if (candidateDir.exists() && candidateDir.isDirectory()) {
File candidateConfigFile = new File(candidateDir.getPath()+File.separator+getName()+".mco");
if (candidateConfigFile.exists()) {
initWorkingDirectory(candidateDir.getPath());
setConfigDirectory(new File(workingDirectory.getPath()+File.separator+getName()));
found = true;
break;
}
}
}
if (found == false) {
throw new ConfigurationException("Couldn't find the MaltParser configuration file: " + getName()+".mco");
}
}
try {
url = mcoPath.toURI().toURL();
} catch (MalformedURLException e) {
// should never happen
throw new ConfigurationException("File path could not be represented as a URL.");
}
}
}
public void initDataFormat() throws MaltChainedException {
String inputFormatName = OptionManager.instance().getOptionValue(containerIndex, "input", "format").toString().trim();
String outputFormatName = OptionManager.instance().getOptionValue(containerIndex, "output", "format").toString().trim();
final URLFinder f = new URLFinder();
if (configDirectory != null && configDirectory.exists()) {
if (outputFormatName.length() == 0 || inputFormatName.equals(outputFormatName)) {
URL inputFormatURL = f.findURLinJars(inputFormatName);
if (inputFormatURL != null) {
outputFormatName = inputFormatName = this.copyToConfig(inputFormatURL);
} else {
outputFormatName = inputFormatName = this.copyToConfig(inputFormatName);
}
} else {
URL inputFormatURL = f.findURLinJars(inputFormatName);
if (inputFormatURL != null) {
inputFormatName = this.copyToConfig(inputFormatURL);
} else {
inputFormatName = this.copyToConfig(inputFormatName);
}
URL outputFormatURL = f.findURLinJars(outputFormatName);
if (inputFormatURL != null) {
outputFormatName = this.copyToConfig(outputFormatURL);
} else {
outputFormatName = this.copyToConfig(outputFormatName);
}
}
OptionManager.instance().overloadOptionValue(containerIndex, "input", "format", inputFormatName);
} else {
if (outputFormatName.length() == 0) {
outputFormatName = inputFormatName;
}
}
dataFormatInstances = new HashMap<String, DataFormatInstance>(3);
inputFormatURL = findURL(inputFormatName);
outputFormatURL = findURL(outputFormatName);
if (outputFormatURL != null) {
try {
InputStream is = outputFormatURL.openStream();
} catch (FileNotFoundException e) {
outputFormatURL = f.findURL(outputFormatName);
} catch (IOException e) {
outputFormatURL = f.findURL(outputFormatName);
}
} else {
outputFormatURL = f.findURL(outputFormatName);
}
dataFormatManager = new DataFormatManager(inputFormatURL, outputFormatURL);
String mode = OptionManager.instance().getOptionValue(containerIndex, "config", "flowchart").toString().trim();
if (mode.equals("parse")) {
symbolTables = new ParseSymbolTableHandler(new HashSymbolTableHandler());
// symbolTables = new TrieSymbolTableHandler(TrieSymbolTableHandler.ADD_NEW_TO_TRIE);
} else {
symbolTables = new HashSymbolTableHandler();
}
if (dataFormatManager.getInputDataFormatSpec().getDataStructure() == DataStructure.PHRASE) {
if (mode.equals("learn")) {
Set<Dependency> deps = dataFormatManager.getInputDataFormatSpec().getDependencies();
for (Dependency dep : deps) {
URL depFormatURL = f.findURLinJars(dep.getUrlString());
if (depFormatURL != null) {
this.copyToConfig(depFormatURL);
} else {
this.copyToConfig(dep.getUrlString());
}
}
}
else if (mode.equals("parse")) {
Set<Dependency> deps = dataFormatManager.getInputDataFormatSpec().getDependencies();
String nullValueStategy = OptionManager.instance().getOptionValue(containerIndex, "singlemalt", "null_value").toString();
for (Dependency dep : deps) {
// URL depFormatURL = f.findURLinJars(dep.getUrlString());
DataFormatInstance dataFormatInstance = dataFormatManager.getDataFormatSpec(dep.getDependentOn()).createDataFormatInstance(symbolTables, nullValueStategy);
addDataFormatInstance(dataFormatManager.getDataFormatSpec(dep.getDependentOn()).getDataFormatName(), dataFormatInstance);
dataFormatManager.setInputDataFormatSpec(dataFormatManager.getDataFormatSpec(dep.getDependentOn()));
// dataFormatManager.setOutputDataFormatSpec(dataFormatManager.getDataFormatSpec(dep.getDependentOn()));
}
}
}
}
private URL findURL(String specModelFileName) throws MaltChainedException {
URL url = null;
File specFile = this.getFile(specModelFileName);
if (specFile.exists()) {
try {
url = new URL("file:///"+specFile.getAbsolutePath());
} catch (MalformedURLException e) {
throw new MaltChainedException("Malformed URL: "+specFile, e);
}
} else {
url = this.getConfigFileEntryURL(specModelFileName);
}
return url;
}
/**
* Creates an output stream writer, where the corresponding file will be included in the configuration directory
*
* @param fileName a file name
* @param charSet a char set
* @return an output stream writer for writing to a file within the configuration directory
* @throws MaltChainedException
*/
public OutputStreamWriter getOutputStreamWriter(String fileName, String charSet) throws MaltChainedException {
try {
return new OutputStreamWriter(new FileOutputStream(configDirectory.getPath()+File.separator+fileName), charSet);
} catch (FileNotFoundException e) {
throw new ConfigurationException("The file '"+fileName+"' cannot be created. ", e);
} catch (UnsupportedEncodingException e) {
throw new ConfigurationException("The char set '"+charSet+"' is not supported. ", e);
}
}
/**
* Creates an output stream writer, where the corresponding file will be included in the
* configuration directory. Uses UTF-8 for character encoding.
*
* @param fileName a file name
* @return an output stream writer for writing to a file within the configuration directory
* @throws MaltChainedException
*/
public OutputStreamWriter getOutputStreamWriter(String fileName) throws MaltChainedException {
try {
return new OutputStreamWriter(new FileOutputStream(configDirectory.getPath()+File.separator+fileName, true), "UTF-8");
} catch (FileNotFoundException e) {
throw new ConfigurationException("The file '"+fileName+"' cannot be created. ", e);
} catch (UnsupportedEncodingException e) {
throw new ConfigurationException("The char set 'UTF-8' is not supported. ", e);
}
}
/**
* This method acts the same as getOutputStreamWriter with the difference that the writer append in the file
* if it already exists instead of deleting the previous content before starting to write.
*
* @param fileName a file name
* @return an output stream writer for writing to a file within the configuration directory
* @throws MaltChainedException
*/
public OutputStreamWriter getAppendOutputStreamWriter(String fileName) throws MaltChainedException {
try {
return new OutputStreamWriter(new FileOutputStream(configDirectory.getPath()+File.separator+fileName, true), "UTF-8");
} catch (FileNotFoundException e) {
throw new ConfigurationException("The file '"+fileName+"' cannot be created. ", e);
} catch (UnsupportedEncodingException e) {
throw new ConfigurationException("The char set 'UTF-8' is not supported. ", e);
}
}
/**
* Creates an input stream reader for reading a file within the configuration directory
*
* @param fileName a file name
* @param charSet a char set
* @return an input stream reader for reading a file within the configuration directory
* @throws MaltChainedException
*/
public InputStreamReader getInputStreamReader(String fileName, String charSet) throws MaltChainedException {
try {
return new InputStreamReader(new FileInputStream(configDirectory.getPath()+File.separator+fileName), charSet);
} catch (FileNotFoundException e) {
throw new ConfigurationException("The file '"+fileName+"' cannot be found. ", e);
} catch (UnsupportedEncodingException e) {
throw new ConfigurationException("The char set '"+charSet+"' is not supported. ", e);
}
}
/**
* Creates an input stream reader for reading a file within the configuration directory.
* Uses UTF-8 for character encoding.
*
* @param fileName a file name
* @return an input stream reader for reading a file within the configuration directory
* @throws MaltChainedException
*/
public InputStreamReader getInputStreamReader(String fileName) throws MaltChainedException {
return getInputStreamReader(fileName, "UTF-8");
}
public JarFile getConfigJarfile() throws MaltChainedException {
JarFile mcoFile = null;
if (url != null && !url.toString().startsWith("jar")) {
// New solution
try {
JarURLConnection conn = (JarURLConnection)new URL("jar:" + url.toString() + "!/").openConnection();
mcoFile = conn.getJarFile();
} catch (IOException e) {
throw new ConfigurationException("The mco-file '"+url+"' cannot be found. ", e);
}
} else {
// Old solution: Can load files from the mco-file within a jar-file
File mcoPath = new File(workingDirectory.getPath()+File.separator+getName()+".mco");
try {
mcoFile = new JarFile(mcoPath.getAbsolutePath());
} catch (IOException e) {
throw new ConfigurationException("The mco-file '"+mcoPath+"' cannot be found. ", e);
}
}
if (mcoFile == null) {
throw new ConfigurationException("The mco-file cannot be found. ");
}
return mcoFile;
}
public JarEntry getConfigFileEntry(String fileName) throws MaltChainedException {
JarFile mcoFile = getConfigJarfile();
JarEntry entry = mcoFile.getJarEntry(getName()+'/'+fileName);
if (entry == null) {
entry = mcoFile.getJarEntry(getName()+'\\'+fileName);
}
return entry;
}
public InputStream getInputStreamFromConfigFileEntry(String fileName) throws MaltChainedException {
JarFile mcoFile = getConfigJarfile();
JarEntry entry = getConfigFileEntry(fileName);
try {
if (entry == null) {
throw new FileNotFoundException();
}
return mcoFile.getInputStream(entry);
} catch (FileNotFoundException e) {
throw new ConfigurationException("The file entry '"+fileName+"' in the mco file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be found. ", e);
} catch (IOException e) {
throw new ConfigurationException("The file entry '"+fileName+"' in the mco file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be loaded. ", e);
}
}
public InputStreamReader getInputStreamReaderFromConfigFileEntry(String fileName, String charSet) throws MaltChainedException {
try {
return new InputStreamReader(getInputStreamFromConfigFileEntry(fileName), charSet);
} catch (UnsupportedEncodingException e) {
throw new ConfigurationException("The char set '"+charSet+"' is not supported. ", e);
}
}
public InputStreamReader getInputStreamReaderFromConfigFile(String fileName) throws MaltChainedException {
return getInputStreamReaderFromConfigFileEntry(fileName, "UTF-8");
}
/**
* Returns a file handler object of a file within the configuration directory
*
* @param fileName a file name
* @return a file handler object of a file within the configuration directory
* @throws MaltChainedException
*/
public File getFile(String fileName) throws MaltChainedException {
return new File(configDirectory.getPath()+File.separator+fileName);
}
public URL getConfigFileEntryURL(String fileName) throws MaltChainedException {
if (url != null && !url.toString().startsWith("jar")) {
// New solution
try {
URL url = new URL("jar:"+this.url.toString()+"!/"+getName()+'/'+fileName + "\n");
try {
InputStream is = url.openStream();
is.close();
} catch (IOException e) {
url = new URL("jar:"+this.url.toString()+"!/"+getName()+'\\'+fileName + "\n");
}
return url;
} catch (MalformedURLException e) {
throw new ConfigurationException("Couldn't find the URL '" +"jar:"+this.url.toString()+"!/"+getName()+'/'+fileName+ "'", e);
}
} else {
// Old solution: Can load files from the mco-file within a jar-file
File mcoPath = new File(workingDirectory.getPath()+File.separator+getName()+".mco");
try {
if (!mcoPath.exists()) {
throw new ConfigurationException("Couldn't find mco-file '" +mcoPath.getAbsolutePath()+ "'");
}
URL url = new URL("jar:"+new URL("file", null, mcoPath.getAbsolutePath())+"!/"+getName()+'/'+fileName + "\n");
try {
InputStream is = url.openStream();
is.close();
} catch (IOException e) {
url = new URL("jar:"+new URL("file", null, mcoPath.getAbsolutePath())+"!/"+getName()+'\\'+fileName + "\n");
}
return url;
} catch (MalformedURLException e) {
throw new ConfigurationException("Couldn't find the URL '" +"jar:"+mcoPath.getAbsolutePath()+"!/"+getName()+'/'+fileName+ "'", e);
}
}
}
/**
* Copies a file into the configuration directory.
*
* @param source a path to file
* @throws MaltChainedException
*/
public String copyToConfig(File source) throws MaltChainedException {
byte[] readBuffer = new byte[BUFFER];
String destination = configDirectory.getPath()+File.separator+source.getName();
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destination), BUFFER);
int n = 0;
while ((n = bis.read(readBuffer, 0, BUFFER)) != -1) {
bos.write(readBuffer, 0, n);
}
bos.flush();
bos.close();
bis.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("The source file '"+source+"' cannot be found or the destination file '"+destination+"' cannot be created when coping the file. ", e);
} catch (IOException e) {
throw new ConfigurationException("The source file '"+source+"' cannot be copied to destination '"+destination+"'. ", e);
}
return source.getName();
}
public String copyToConfig(String fileUrl) throws MaltChainedException {
final URLFinder f = new URLFinder();
URL url = f.findURL(fileUrl);
if (url == null) {
throw new ConfigurationException("The file or URL '"+fileUrl+"' could not be found. ");
}
return copyToConfig(url);
}
public String copyToConfig(URL url) throws MaltChainedException {
if (url == null) {
throw new ConfigurationException("URL could not be found. ");
}
byte[] readBuffer = new byte[BUFFER];
String destFileName = url.getPath();
int indexSlash = destFileName.lastIndexOf('/');
if (indexSlash == -1) {
indexSlash = destFileName.lastIndexOf('\\');
}
if (indexSlash != -1) {
destFileName = destFileName.substring(indexSlash+1);
}
String destination = configDirectory.getPath()+File.separator+destFileName;
try {
BufferedInputStream bis = new BufferedInputStream(url.openStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destination), BUFFER);
int n = 0;
while ((n = bis.read(readBuffer, 0, BUFFER)) != -1) {
bos.write(readBuffer, 0, n);
}
bos.flush();
bos.close();
bis.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("The destination file '"+destination+"' cannot be created when coping the file. ", e);
} catch (IOException e) {
throw new ConfigurationException("The URL '"+url+"' cannot be copied to destination '"+destination+"'. ", e);
}
return destFileName;
}
/**
* Removes the configuration directory, if it exists and it contains a .info file.
*
* @throws MaltChainedException
*/
public void deleteConfigDirectory() throws MaltChainedException {
if (!configDirectory.exists()) {
return;
}
File infoFile = new File(configDirectory.getPath()+File.separator+getName()+"_"+getType()+".info");
if (infoFile.exists()) {
deleteConfigDirectory(configDirectory);
} else {
throw new ConfigurationException("There exists a directory that is not a MaltParser configuration directory. ");
}
}
private void deleteConfigDirectory(File directory) throws MaltChainedException {
if (directory.exists()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteConfigDirectory(files[i]);
} else {
files[i].delete();
}
}
} else {
throw new ConfigurationException("The directory '"+directory.getPath()+ "' cannot be found. ");
}
directory.delete();
}
/**
* Returns a file handler object for the configuration directory
*
* @return a file handler object for the configuration directory
*/
public File getConfigDirectory() {
return configDirectory;
}
protected void setConfigDirectory(File dir) {
this.configDirectory = dir;
}
/**
* Creates the configuration directory
*
* @throws MaltChainedException
*/
public void createConfigDirectory() throws MaltChainedException {
checkConfigDirectory();
configDirectory.mkdir();
createInfoFile();
}
protected void checkConfigDirectory() throws MaltChainedException {
if (configDirectory.exists() && !configDirectory.isDirectory()) {
throw new ConfigurationException("The configuration directory name already exists and is not a directory. ");
}
if (configDirectory.exists()) {
deleteConfigDirectory();
}
}
protected void createInfoFile() throws MaltChainedException {
infoFile = new BufferedWriter(getOutputStreamWriter(getName()+"_"+getType()+".info"));
try {
infoFile.write("CONFIGURATION\n");
infoFile.write("Configuration name: "+getName()+"\n");
infoFile.write("Configuration type: "+getType()+"\n");
infoFile.write("Created: "+new Date(System.currentTimeMillis())+"\n");
infoFile.write("\nSYSTEM\n");
infoFile.write("Operating system architecture: "+System.getProperty("os.arch")+"\n");
infoFile.write("Operating system name: "+System.getProperty("os.name")+"\n");
infoFile.write("JRE vendor name: "+System.getProperty("java.vendor")+"\n");
infoFile.write("JRE version number: "+System.getProperty("java.version")+"\n");
infoFile.write("\nMALTPARSER\n");
infoFile.write("Version: "+SystemInfo.getVersion()+"\n");
infoFile.write("Build date: "+SystemInfo.getBuildDate()+"\n");
Set<String> excludeGroups = new HashSet<String>();
excludeGroups.add("system");
infoFile.write("\nSETTINGS\n");
infoFile.write(OptionManager.instance().toStringPrettyValues(containerIndex, excludeGroups));
infoFile.flush();
} catch (IOException e) {
throw new ConfigurationException("Could not create the maltparser info file. ");
}
}
/**
* Returns a writer to the configuration information file
*
* @return a writer to the configuration information file
* @throws MaltChainedException
*/
public BufferedWriter getInfoFileWriter() throws MaltChainedException {
return infoFile;
}
/**
* Creates the malt configuration file (.mco). This file is compressed.
*
* @throws MaltChainedException
*/
public void createConfigFile() throws MaltChainedException {
try {
JarOutputStream jos = new JarOutputStream(new FileOutputStream(workingDirectory.getPath()+File.separator+getName()+".mco"));
// configLogger.info("Creates configuration file '"+workingDirectory.getPath()+File.separator+getName()+".mco' ...\n");
createConfigFile(configDirectory.getPath(), jos);
jos.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("The maltparser configurtation file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be found. ", e);
} catch (IOException e) {
throw new ConfigurationException("The maltparser configurtation file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be created. ", e);
}
}
private void createConfigFile(String directory, JarOutputStream jos) throws MaltChainedException {
byte[] readBuffer = new byte[BUFFER];
try {
File zipDir = new File(directory);
String[] dirList = zipDir.list();
int bytesIn = 0;
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
String filePath = f.getPath();
createConfigFile(filePath, jos);
continue;
}
FileInputStream fis = new FileInputStream(f);
String entryPath = f.getPath().substring(workingDirectory.getPath().length()+1);
entryPath = entryPath.replace('\\', '/');
JarEntry entry = new JarEntry(entryPath);
jos.putNextEntry(entry);
while ((bytesIn = fis.read(readBuffer)) != -1) {
jos.write(readBuffer, 0, bytesIn);
}
fis.close();
}
} catch (FileNotFoundException e) {
throw new ConfigurationException("The directory '"+directory+"' cannot be found. ", e);
} catch (IOException e) {
throw new ConfigurationException("The directory '"+directory+"' cannot be compressed into a mco file. ", e);
}
}
public void copyConfigFile(File in, File out, Versioning versioning) throws MaltChainedException {
try {
JarFile jar = new JarFile(in);
JarOutputStream tempJar = new JarOutputStream(new FileOutputStream(out));
byte[] buffer = new byte[BUFFER];
int bytesRead;
final StringBuilder sb = new StringBuilder();
final URLFinder f = new URLFinder();
for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements(); ) {
JarEntry inEntry = (JarEntry) entries.nextElement();
InputStream entryStream = jar.getInputStream(inEntry);
JarEntry outEntry = versioning.getJarEntry(inEntry);
if (!versioning.hasChanges(inEntry, outEntry)) {
tempJar.putNextEntry(outEntry);
while ((bytesRead = entryStream.read(buffer)) != -1) {
tempJar.write(buffer, 0, bytesRead);
}
} else {
tempJar.putNextEntry(outEntry);
BufferedReader br = new BufferedReader(new InputStreamReader(entryStream));
String line = null;
sb.setLength(0);
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
String outString = versioning.modifyJarEntry(inEntry, outEntry, sb);
tempJar.write(outString.getBytes());
}
}
if (versioning.getFeatureModelXML() != null && versioning.getFeatureModelXML().startsWith("/appdata")) {
int index = versioning.getFeatureModelXML().lastIndexOf('/');
BufferedInputStream bis = new BufferedInputStream(f.findURLinJars(versioning.getFeatureModelXML()).openStream());
tempJar.putNextEntry(new JarEntry(versioning.getNewConfigName()+"/" +versioning.getFeatureModelXML().substring(index+1)));
int n = 0;
while ((n = bis.read(buffer, 0, BUFFER)) != -1) {
tempJar.write(buffer, 0, n);
}
bis.close();
}
if (versioning.getInputFormatXML() != null && versioning.getInputFormatXML().startsWith("/appdata")) {
int index = versioning.getInputFormatXML().lastIndexOf('/');
BufferedInputStream bis = new BufferedInputStream(f.findURLinJars(versioning.getInputFormatXML()).openStream());
tempJar.putNextEntry(new JarEntry(versioning.getNewConfigName()+"/" +versioning.getInputFormatXML().substring(index+1)));
int n = 0;
while ((n = bis.read(buffer, 0, BUFFER)) != -1) {
tempJar.write(buffer, 0, n);
}
bis.close();
}
tempJar.flush();
tempJar.close();
jar.close();
} catch (IOException e) {
throw new ConfigurationException("", e);
}
}
protected void initNameNTypeFromInfoFile(URL url) throws MaltChainedException {
if (url == null) {
throw new ConfigurationException("The URL cannot be found. ");
}
try {
JarEntry je;
JarInputStream jis = new JarInputStream(url.openConnection().getInputStream());
while ((je = jis.getNextJarEntry()) != null) {
String entryName = je.getName();
if (entryName.endsWith(".info")) {
int indexUnderScore = entryName.lastIndexOf('_');
int indexSeparator = entryName.lastIndexOf(File.separator);
if (indexSeparator == -1) {
indexSeparator = entryName.lastIndexOf('/');
}
if (indexSeparator == -1) {
indexSeparator = entryName.lastIndexOf('\\');
}
int indexDot = entryName.lastIndexOf('.');
if (indexUnderScore == -1 || indexDot == -1) {
throw new ConfigurationException("Could not find the configuration name and type from the URL '"+url.toString()+"'. ");
}
setName(entryName.substring(indexSeparator+1, indexUnderScore));
setType(entryName.substring(indexUnderScore+1, indexDot));
setConfigDirectory(new File(workingDirectory.getPath()+File.separator+getName()));
jis.close();
return;
}
}
} catch (IOException e) {
throw new ConfigurationException("Could not find the configuration name and type from the URL '"+url.toString()+"'. ", e);
}
}
/**
* Prints the content of the configuration information file to the system logger
*
* @throws MaltChainedException
*/
public void echoInfoFile() throws MaltChainedException {
checkConfigDirectory();
JarInputStream jis;
try {
if (url == null) {
jis = new JarInputStream(new FileInputStream(workingDirectory.getPath()+File.separator+getName()+".mco"));
} else {
jis = new JarInputStream(url.openConnection().getInputStream());
}
JarEntry je;
while ((je = jis.getNextJarEntry()) != null) {
String entryName = je.getName();
if (entryName.endsWith(getName()+"_"+getType()+".info")) {
int c;
while ((c = jis.read()) != -1) {
SystemLogger.logger().info((char)c);
}
}
}
jis.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could not print configuration information file. The configuration file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be found. ", e);
} catch (IOException e) {
throw new ConfigurationException("Could not print configuration information file. ", e);
}
}
/**
* Unpacks the malt configuration file (.mco).
*
* @throws MaltChainedException
*/
public void unpackConfigFile() throws MaltChainedException {
checkConfigDirectory();
JarInputStream jis;
try {
if (url == null) {
jis = new JarInputStream(new FileInputStream(workingDirectory.getPath()+File.separator+getName()+".mco"));
} else {
jis = new JarInputStream(url.openConnection().getInputStream());
}
unpackConfigFile(jis);
jis.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could not unpack configuration. The configuration file '"+workingDirectory.getPath()+File.separator+getName()+".mco"+"' cannot be found. ", e);
} catch (IOException e) {
if (configDirectory.exists()) {
deleteConfigDirectory();
}
throw new ConfigurationException("Could not unpack configuration. ", e);
}
initCreatedByMaltParserVersionFromInfoFile();
}
protected void unpackConfigFile(JarInputStream jis) throws MaltChainedException {
try {
JarEntry je;
byte[] readBuffer = new byte[BUFFER];
SortedSet<String> directoryCache = new TreeSet<String>();
while ((je = jis.getNextJarEntry()) != null) {
String entryName = je.getName();
if (entryName.startsWith("/")) {
entryName = entryName.substring(1);
}
if (entryName.endsWith(File.separator) || entryName.endsWith("/")) {
return;
}
int index = -1;
if (File.separator.equals("\\")) {
entryName = entryName.replace('/', '\\');
index = entryName.lastIndexOf("\\");
} else if (File.separator.equals("/")) {
entryName = entryName.replace('\\', '/');
index = entryName.lastIndexOf("/");
}
if (index > 0) {
String dirName = entryName.substring(0, index);
if (!directoryCache.contains(dirName)) {
File directory = new File(workingDirectory.getPath()+File.separator+dirName);
if (!(directory.exists() && directory.isDirectory())) {
if (!directory.mkdirs()) {
throw new ConfigurationException("Unable to make directory '" + dirName +"'. ");
}
directoryCache.add(dirName);
}
}
}
if (new File(workingDirectory.getPath()+File.separator+entryName).isDirectory() && new File(workingDirectory.getPath()+File.separator+entryName).exists()) {
continue;
}
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(workingDirectory.getPath()+File.separator+entryName), BUFFER);
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could not unpack configuration. The file '"+workingDirectory.getPath()+File.separator+entryName+"' cannot be unpacked. ", e);
}
int n = 0;
while ((n = jis.read(readBuffer, 0, BUFFER)) != -1) {
bos.write(readBuffer, 0, n);
}
bos.flush();
bos.close();
}
} catch (IOException e) {
throw new ConfigurationException("Could not unpack configuration. ", e);
}
}
/**
* Returns the name of the configuration directory
*
* @return the name of the configuration directory
*/
public String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
/**
* Returns the type of the configuration directory
*
* @return the type of the configuration directory
*/
public String getType() {
return type;
}
protected void setType(String type) {
this.type = type;
}
/**
* Returns a file handler object for the working directory
*
* @return a file handler object for the working directory
*/
public File getWorkingDirectory() {
return workingDirectory;
}
/**
* Initialize the working directory
*
* @throws MaltChainedException
*/
public void initWorkingDirectory() throws MaltChainedException {
try {
initWorkingDirectory(OptionManager.instance().getOptionValue(containerIndex, "config", "workingdir").toString());
} catch (NullPointerException e) {
throw new ConfigurationException("The configuration cannot be found.", e);
}
}
/**
* Initialize the working directory according to the path. If the path is equals to "user.dir" or current directory, then the current directory
* will be the working directory.
*
* @param pathPrefixString the path to the working directory
* @throws MaltChainedException
*/
public void initWorkingDirectory(String pathPrefixString) throws MaltChainedException {
if (pathPrefixString == null || pathPrefixString.equalsIgnoreCase("user.dir") || pathPrefixString.equalsIgnoreCase(".")) {
workingDirectory = new File(System.getProperty("user.dir"));
} else {
workingDirectory = new File(pathPrefixString);
}
if (workingDirectory == null || !workingDirectory.isDirectory()) {
new ConfigurationException("The specified working directory '"+pathPrefixString+"' is not a directory. ");
}
}
/**
* Returns the URL to the malt configuration file (.mco)
*
* @return the URL to the malt configuration file (.mco)
*/
public URL getUrl() {
return url;
}
protected void setUrl(URL url) {
this.url = url;
}
/**
* Returns the option container index
*
* @return the option container index
*/
public int getContainerIndex() {
return containerIndex;
}
/**
* Sets the option container index
*
* @param containerIndex a option container index
*/
public void setContainerIndex(int containerIndex) {
this.containerIndex = containerIndex;
}
/**
* Returns the version number of MaltParser which created the malt configuration file (.mco)
*
* @return the version number of MaltParser which created the malt configuration file (.mco)
*/
public String getCreatedByMaltParserVersion() {
return createdByMaltParserVersion;
}
/**
* Sets the version number of MaltParser which created the malt configuration file (.mco)
*
* @param createdByMaltParserVersion a version number of MaltParser
*/
public void setCreatedByMaltParserVersion(String createdByMaltParserVersion) {
this.createdByMaltParserVersion = createdByMaltParserVersion;
}
public void initCreatedByMaltParserVersionFromInfoFile() throws MaltChainedException {
try {
BufferedReader br = new BufferedReader(getInputStreamReaderFromConfigFileEntry(getName()+"_"+getType()+".info", "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("Version: ")) {
setCreatedByMaltParserVersion(line.substring(31));
break;
}
}
br.close();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could not retrieve the version number of the MaltParser configuration.", e);
} catch (IOException e) {
throw new ConfigurationException("Could not retrieve the version number of the MaltParser configuration.", e);
}
}
public void versioning() throws MaltChainedException {
initCreatedByMaltParserVersionFromInfoFile();
SystemLogger.logger().info("\nCurrent version : " + SystemInfo.getVersion() + "\n");
SystemLogger.logger().info("Parser model version : " + createdByMaltParserVersion + "\n");
if (SystemInfo.getVersion() == null) {
throw new ConfigurationException("Couln't determine the version of MaltParser");
} else if (createdByMaltParserVersion == null) {
throw new ConfigurationException("Couln't determine the version of the parser model");
} else if (SystemInfo.getVersion().equals(createdByMaltParserVersion)) {
SystemLogger.logger().info("The parser model "+getName()+".mco has already the same version as the current version of MaltParser. \n");
return;
}
File mcoPath = new File(workingDirectory.getPath()+File.separator+getName()+".mco");
File newMcoPath = new File(workingDirectory.getPath()+File.separator+getName()+"."+SystemInfo.getVersion().trim()+".mco");
Versioning versioning = new Versioning(name, type, mcoPath, createdByMaltParserVersion);
if (!versioning.support(createdByMaltParserVersion)) {
SystemLogger.logger().warn("The parser model '"+ name+ ".mco' is created by MaltParser "+getCreatedByMaltParserVersion()+", which cannot be converted to a MaltParser "+SystemInfo.getVersion()+" parser model.\n");
SystemLogger.logger().warn("Please retrain the parser model with MaltParser "+SystemInfo.getVersion() +" or download MaltParser "+getCreatedByMaltParserVersion()+" from http://maltparser.org/download.html\n");
return;
}
SystemLogger.logger().info("Converts the parser model '"+ mcoPath.getName()+ "' into '"+newMcoPath.getName()+"'....\n");
copyConfigFile(mcoPath, newMcoPath, versioning);
}
protected void checkNConvertConfigVersion() throws MaltChainedException {
if (createdByMaltParserVersion.startsWith("1.0")) {
SystemLogger.logger().info(" Converts the MaltParser configuration ");
SystemLogger.logger().info("1.0");
SystemLogger.logger().info(" to ");
SystemLogger.logger().info(SystemInfo.getVersion());
SystemLogger.logger().info("\n");
File[] configFiles = configDirectory.listFiles();
for (int i = 0, n = configFiles.length; i < n; i++) {
if (configFiles[i].getName().endsWith(".mod")) {
configFiles[i].renameTo(new File(configDirectory.getPath()+File.separator+"odm0."+configFiles[i].getName()));
}
if (configFiles[i].getName().endsWith(getName()+".dsm")) {
configFiles[i].renameTo(new File(configDirectory.getPath()+File.separator+"odm0.dsm"));
}
if (configFiles[i].getName().equals("savedoptions.sop")) {
configFiles[i].renameTo(new File(configDirectory.getPath()+File.separator+"savedoptions.sop.old"));
}
if (configFiles[i].getName().equals("symboltables.sym")) {
configFiles[i].renameTo(new File(configDirectory.getPath()+File.separator+"symboltables.sym.old"));
}
}
try {
BufferedReader br = new BufferedReader(new FileReader(configDirectory.getPath()+File.separator+"savedoptions.sop.old"));
BufferedWriter bw = new BufferedWriter(new FileWriter(configDirectory.getPath()+File.separator+"savedoptions.sop"));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("0\tguide\tprediction_strategy")) {
bw.write("0\tguide\tdecision_settings\tT.TRANS+A.DEPREL\n");
} else {
bw.write(line);
bw.write('\n');
}
}
br.close();
bw.flush();
bw.close();
new File(configDirectory.getPath()+File.separator+"savedoptions.sop.old").delete();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could convert savedoptions.sop version 1.0.4 to version 1.1. ", e);
} catch (IOException e) {
throw new ConfigurationException("Could convert savedoptions.sop version 1.0.4 to version 1.1. ", e);
}
try {
BufferedReader br = new BufferedReader(new FileReader(configDirectory.getPath()+File.separator+"symboltables.sym.old"));
BufferedWriter bw = new BufferedWriter(new FileWriter(configDirectory.getPath()+File.separator+"symboltables.sym"));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("AllCombinedClassTable")) {
bw.write("T.TRANS+A.DEPREL\n");
} else {
bw.write(line);
bw.write('\n');
}
}
br.close();
bw.flush();
bw.close();
new File(configDirectory.getPath()+File.separator+"symboltables.sym.old").delete();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could convert symboltables.sym version 1.0.4 to version 1.1. ", e);
} catch (IOException e) {
throw new ConfigurationException("Could convert symboltables.sym version 1.0.4 to version 1.1. ", e);
}
}
if (!createdByMaltParserVersion.startsWith("1.3")) {
SystemLogger.logger().info(" Converts the MaltParser configuration ");
SystemLogger.logger().info(createdByMaltParserVersion);
SystemLogger.logger().info(" to ");
SystemLogger.logger().info(SystemInfo.getVersion());
SystemLogger.logger().info("\n");
new File(configDirectory.getPath()+File.separator+"savedoptions.sop").renameTo(new File(configDirectory.getPath()+File.separator+"savedoptions.sop.old"));
try {
BufferedReader br = new BufferedReader(new FileReader(configDirectory.getPath()+File.separator+"savedoptions.sop.old"));
BufferedWriter bw = new BufferedWriter(new FileWriter(configDirectory.getPath()+File.separator+"savedoptions.sop"));
String line;
while ((line = br.readLine()) != null) {
int index = line.indexOf('\t');
int container = 0;
if (index > -1) {
container = Integer.parseInt(line.substring(0,index));
}
if (line.startsWith(container+"\tnivre\tpost_processing")) {
} else if (line.startsWith(container+"\tmalt0.4\tbehavior")) {
if (line.endsWith("true")) {
SystemLogger.logger().info("MaltParser 1.3 doesn't support MaltParser 0.4 emulation.");
br.close();
bw.flush();
bw.close();
deleteConfigDirectory();
System.exit(0);
}
} else if (line.startsWith(container+"\tsinglemalt\tparsing_algorithm")) {
bw.write(container);
bw.write("\tsinglemalt\tparsing_algorithm\t");
if (line.endsWith("NivreStandard")) {
bw.write("class org.maltparser.parser.algorithm.nivre.NivreArcStandardFactory");
} else if (line.endsWith("NivreEager")) {
bw.write("class org.maltparser.parser.algorithm.nivre.NivreArcEagerFactory");
} else if (line.endsWith("CovingtonNonProjective")) {
bw.write("class org.maltparser.parser.algorithm.covington.CovingtonNonProjFactory");
} else if (line.endsWith("CovingtonProjective")) {
bw.write("class org.maltparser.parser.algorithm.covington.CovingtonProjFactory");
}
bw.write('\n');
} else {
bw.write(line);
bw.write('\n');
}
}
br.close();
bw.flush();
bw.close();
new File(configDirectory.getPath()+File.separator+"savedoptions.sop.old").delete();
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could convert savedoptions.sop version 1.0.4 to version 1.1. ", e);
} catch (IOException e) {
throw new ConfigurationException("Could convert savedoptions.sop version 1.0.4 to version 1.1. ", e);
}
}
}
/**
* Terminates the configuration directory
*
* @throws MaltChainedException
*/
public void terminate() throws MaltChainedException {
if (infoFile != null) {
try {
infoFile.flush();
infoFile.close();
} catch (IOException e) {
throw new ConfigurationException("Could not close configuration information file. ", e);
}
}
symbolTables = null;
// configuration = null;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
try {
if (infoFile != null) {
infoFile.flush();
infoFile.close();
}
} finally {
super.finalize();
}
}
public SymbolTableHandler getSymbolTables() {
return symbolTables;
}
public void setSymbolTables(SymbolTableHandler symbolTables) {
this.symbolTables = symbolTables;
}
public DataFormatManager getDataFormatManager() {
return dataFormatManager;
}
public void setDataFormatManager(DataFormatManager dataFormatManager) {
this.dataFormatManager = dataFormatManager;
}
public Set<String> getDataFormatInstanceKeys() {
return dataFormatInstances.keySet();
}
public boolean addDataFormatInstance(String key, DataFormatInstance dataFormatInstance) {
if (!dataFormatInstances.containsKey(key)) {
dataFormatInstances.put(key, dataFormatInstance);
return true;
}
return false;
}
public DataFormatInstance getDataFormatInstance(String key) {
return dataFormatInstances.get(key);
}
public int sizeDataFormatInstance() {
return dataFormatInstances.size();
}
public DataFormatInstance getInputDataFormatInstance() {
return dataFormatInstances.get(dataFormatManager.getInputDataFormatSpec().getDataFormatName());
}
public URL getInputFormatURL() {
return inputFormatURL;
}
public URL getOutputFormatURL() {
return outputFormatURL;
}
} |
package edu.cuny.citytech.refactoring.common.tests;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
@SuppressWarnings("restriction")
public abstract class RefactoringTest extends org.eclipse.jdt.ui.tests.refactoring.RefactoringTest {
private static final String REPLACE_EXPECTED_WITH_ACTUAL_KEY = "edu.cuny.citytech.refactoring.common.tests.replaceExpectedWithActual";
/**
* The name of the directory containing resources under the project
* directory.
*/
private static final String RESOURCE_PATH = "resources";
/**
* True if the expected output should be replaced with the actual output.
* Useful to creating new or updated test data and false otherwise.
*/
private boolean replaceExpectedWithActual;
/**
* Creates a new {@link RefactoringTest}.
*
* @param name
* The name of the test.
* @param replaceExpectedWithActual
* True if the expected output should be replaced with the actual
* output.
* @see org.eclipse.jdt.ui.tests.refactoring.RefactoringTest
*/
public RefactoringTest(String name, boolean replaceExpectedWithActual) {
super(name);
this.replaceExpectedWithActual = replaceExpectedWithActual;
}
/**
* Creates a new {@link RefactoringTest}.
*
* @param name
* The name of the test.
* @see org.eclipse.jdt.ui.tests.refactoring.RefactoringTest
*/
public RefactoringTest(String name) {
super(name);
String replaceProperty = System.getenv(REPLACE_EXPECTED_WITH_ACTUAL_KEY);
if (replaceProperty != null)
this.replaceExpectedWithActual = Boolean.valueOf(replaceProperty);
}
private static void assertFailedPrecondition(RefactoringStatus initialStatus, RefactoringStatus finalStatus) {
assertTrue("Precondition was supposed to fail.", !initialStatus.isOK() || !finalStatus.isOK());
}
protected void assertFailedPrecondition(IMethod... methods) throws CoreException {
Refactoring refactoring = getRefactoring(methods);
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertFailedPrecondition(initialStatus, finalStatus);
}
protected abstract Logger getLogger(); // TODO: Should use built-in Eclipse
// logger.
/**
* Returns the refactoring to be tested.
*
* @param methods
* The methods to refactor.
* @param cu
* The compilation unit being tested. Can be null.
* @return The refactoring to be tested.
* @throws JavaModelException
*/
protected abstract Refactoring getRefactoring(IMethod... methods) throws JavaModelException; // TODO:
// Should
// use
// createRefactoring().
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jdt.ui.tests.refactoring.RefactoringTest#getFileContents(java
* .lang.String) Had to override this method because, since this plug-in is
* a fragment (at least I think that this is the reason), it doesn't have an
* activator and the bundle is resolving to the eclipse refactoring test
* bundle.
*/
@Override
public String getFileContents(String fileName) throws IOException {
Path absolutePath = getAbsolutionPath(fileName);
byte[] encoded = Files.readAllBytes(absolutePath);
return new String(encoded, Charset.defaultCharset());
}
private Path getAbsolutionPath(String fileName) {
Path path = Paths.get(RESOURCE_PATH, fileName);
Path absolutePath = path.toAbsolutePath();
return absolutePath;
}
public void setFileContents(String fileName, String contents) throws IOException {
Path absolutePath = getAbsolutionPath(fileName);
Files.write(absolutePath, contents.getBytes());
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jdt.ui.tests.refactoring.RefactoringTest#createCUfromTestFile
* (org.eclipse.jdt.core.IPackageFragment, java.lang.String)
*/
@Override
protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName) throws Exception {
ICompilationUnit unit = super.createCUfromTestFile(pack, cuName);
if (!unit.isStructureKnown())
throw new IllegalArgumentException(cuName + " has structural errors.");
else
return unit;
}
private void helperFail(String typeName, String outerMethodName, String[] outerSignature, String innerTypeName,
String[] methodNames, String[][] signatures) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), typeName);
IType type = getType(cu, typeName);
if (outerMethodName != null) {
IMethod method = type.getMethod(outerMethodName, outerSignature);
if (innerTypeName != null) {
type = method.getType(innerTypeName, 1); // get the local type
} else {
type = method.getType("", 1); // get the anonymous type.
}
} else if (innerTypeName != null) {
type = type.getType(innerTypeName); // get the member type.
}
IMethod[] methods = getMethods(type, methodNames, signatures);
assertFailedPrecondition(methods);
}
protected void helperFail(String outerMethodName, String[] outerSignature, String innerTypeName,
String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", outerMethodName, outerSignature, innerTypeName, methodNames, signatures);
}
/**
* Check for a failed precondition for a case with an inner type.
*
* @param outerMethodName
* The method declaring the anonymous type.
* @param outerSignature
* The signature of the method declaring the anonymous type.
* @param methodNames
* The methods in the anonymous type.
* @param signatures
* The signatures of the methods in the anonymous type.
* @throws Exception
*/
protected void helperFail(String outerMethodName, String[] outerSignature, String[] methodNames,
String[][] signatures) throws Exception {
helperFail("A", outerMethodName, outerSignature, null, methodNames, signatures);
}
protected void helperFail(String innerTypeName, String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", null, null, innerTypeName, methodNames, signatures);
}
protected void helperPass(String innerTypeName, String[] methodNames, String[][] signatures) throws Exception {
helperPass("A", null, null, innerTypeName, methodNames, signatures);
}
/**
* Check for failed precondition for a simple case.
*
* @param methodNames
* The methods to test.
* @param signatures
* Their signatures.
* @throws Exception
*/
protected void helperFail(String[] methodNames, String[][] signatures) throws Exception {
helperFail("A", null, null, null, methodNames, signatures);
}
/**
* Check for failed preconditions for the case where there is no input.
*
* @throws Exception
*/
protected void helperFail() throws Exception {
helperFail("A", null, null);
}
protected void helperPass(String[] methodNames, String[][] signatures) throws Exception {
helperPass(methodNames, signatures, true);
}
protected void helperPass(String[] methodNames, String[][] signatures, boolean testCompilation) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
IMethod[] methods = getMethods(type, methodNames, signatures);
helperPass(cu, methods, testCompilation);
}
private void helperPass(ICompilationUnit cu, IMethod[] methods)
throws JavaModelException, CoreException, Exception, IOException {
helperPass(cu, methods, true);
}
private void helperPass(ICompilationUnit cu, IMethod[] methods, boolean testCompilation)
throws JavaModelException, CoreException, Exception, IOException {
Refactoring refactoring = getRefactoring(methods);
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.", initialStatus.isOK() && finalStatus.isOK());
performChange(refactoring, false);
String outputTestFileName = getOutputTestFileName("A");
String actual = cu.getSource();
if (testCompilation)
assertTrue("Actual output should compile.", compiles(actual));
if (this.replaceExpectedWithActual)
setFileContents(outputTestFileName, actual);
String expected = getFileContents(outputTestFileName);
assertEqualLines(expected, actual);
}
private static boolean compiles(String source) throws IOException {
// Save source in .java file.
Path root = Files.createTempDirectory(null);
File sourceFile = new File(root.toFile(), "p/A.java");
sourceFile.getParentFile().mkdirs();
Files.write(sourceFile.toPath(), source.getBytes());
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
return compiler.run(null, null, null, sourceFile.getPath()) == 0;
}
private void helperPass(String typeName, String outerMethodName, String[] outerSignature, String innerTypeName,
String[] methodNames, String[][] signatures) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), typeName);
IType type = getType(cu, typeName);
if (outerMethodName != null) {
IMethod method = type.getMethod(outerMethodName, outerSignature);
if (innerTypeName != null) {
type = method.getType(innerTypeName, 1); // get the local type
} else {
type = method.getType("", 1); // get the anonymous type.
}
} else if (innerTypeName != null) {
type = type.getType(innerTypeName); // get the member type.
}
IMethod[] methods = getMethods(type, methodNames, signatures);
helperPass(cu, methods);
}
/**
* Test methods in two classes, namely, A and B.
*/
protected void helperPass(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.", initialStatus.isOK() && finalStatus.isOK());
performChange(refactoring, false);
String outputTestFileName = getOutputTestFileName("A");
String actual = cu.getSource();
assertTrue("Actual output should compile.", compiles(actual));
if (this.replaceExpectedWithActual)
setFileContents(outputTestFileName, actual);
String expected = getFileContents(outputTestFileName);
assertEqualLines(expected, actual);
}
/**
* Test methods in two classes, namely, A and B, with no fatal errors.
*/
protected void helperPassNoFatal(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.",
!initialStatus.hasFatalError() && !finalStatus.hasFatalError());
performChange(refactoring, false);
String outputTestFileName = getOutputTestFileName("A");
String actual = cu.getSource();
assertTrue("Actual output should compile.", compiles(actual));
if (this.replaceExpectedWithActual)
setFileContents(outputTestFileName, actual);
String expected = getFileContents(outputTestFileName);
assertEqualLines(expected, actual);
}
/**
* Test methods in three classes, namely, A, B, and C, with no fatal errors.
*/
protected void helperPassNoFatal(String[] methodNames1, String[][] signatures1, String[] methodNames2,
String[][] signatures2, String[] methodNames3, String[][] signatures3) throws Exception {
ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
IType type = getType(cu, "A");
Set<IMethod> methodSet = new LinkedHashSet<>();
Collections.addAll(methodSet, getMethods(type, methodNames1, signatures1));
type = getType(cu, "B");
Collections.addAll(methodSet, getMethods(type, methodNames2, signatures2));
type = getType(cu, "C");
Collections.addAll(methodSet, getMethods(type, methodNames3, signatures3));
Refactoring refactoring = getRefactoring(methodSet.toArray(new IMethod[methodSet.size()]));
RefactoringStatus initialStatus = refactoring.checkInitialConditions(new NullProgressMonitor());
getLogger().info("Initial status: " + initialStatus);
RefactoringStatus finalStatus = refactoring.checkFinalConditions(new NullProgressMonitor());
getLogger().info("Final status: " + finalStatus);
assertTrue("Precondition was supposed to pass.",
!initialStatus.hasFatalError() && !finalStatus.hasFatalError());
performChange(refactoring, false);
String outputTestFileName = getOutputTestFileName("A");
String actual = cu.getSource();
assertTrue("Actual output should compile.", compiles(actual));
if (this.replaceExpectedWithActual)
setFileContents(outputTestFileName, actual);
String expected = getFileContents(outputTestFileName);
assertEqualLines(expected, actual);
}
public void testPlainMethod() throws Exception {
helperPass(new String[] { "m" }, new String[][] { new String[0] });
}
} |
package com.vader;
import com.vader.analyzer.TextProperties;
import com.vader.util.Utils;
import java.io.IOException;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class SentimentAnalyzer {
private static Logger logger = Logger.getLogger(SentimentAnalyzer.class);
private String text;
private TextProperties textProperties;
private HashMap<String, Float> polarity;
/**
* Default constructor without arguments. Use case:
* <pre>
* ...
* <code>
* String s = "VADER is smart, handsome, and funny!";
* System.out.println(s);
* SentimentAnalyzer sa = new SentimentAnalyzer();
* sa.setText(s);
* System.out.println(sa.getSentimentPolarity().toString());
* </code>
* ...
* </pre>
*/
public SentimentAnalyzer() {
text = null;
textProperties = null;
polarity = null;
}
/**
* One-argument constructor with text set. Use case:
* <pre>
* ...
* <code>
* String s = "VADER is smart, handsome, and funny!";
* System.out.println(s);
* SentimentAnalyzer sa = new SentimentAnalyzer(s);
* System.out.println(sa.getSentimentPolarity().toString());
* </code>
* ...
* </pre>
* @param s The text sample intended for sentiment analysis.
* @throws IOException
*/
public SentimentAnalyzer(String s) throws IOException {
setText(s);
polarity = null;
}
/**
* Sets the text sample intended for sentiment analysis and does
* all the text properties preprocessing.
* @param s The text sample.
* @throws IOException
*/
public void setText(String s) throws IOException {
text = s;
textProperties = new TextProperties(s);
}
/**
* Gets the current text sample intended for sentiment analysis.
* @return The text sample.
*/
public String getText() {
return text;
}
/**
* Does the sentiment analysis of the current text sample, sets
* and returns the polarity values.
* @deprecated As of release 1.1, replaced by {@link #getSentimentPolarity()}
*/
@Deprecated public void analyse() {
polarity = getSentiment();
}
/**
* Does the sentiment analysis of the current text sample, sets
* and returns the polarity values.
* @return The list of positive, neutral, negative, and compound name-value pairs.
*/
public HashMap<String, Float> getSentimentPolarity() {
polarity = getSentiment();
return polarity;
}
/**
* Gets the polarity of the current text sample sentiment analysis.
* @return The list of positive, neutral, negative, and compound name-value pairs.
* @see #getSentimentPolarity()
*/
public HashMap<String, Float> getPolarity() {
return polarity;
}
private float valenceModifier(String precedingWord, float currentValence) {
float scalar = 0.0f;
String precedingWordLower = precedingWord.toLowerCase();
if (Utils.BOOSTER_DICTIONARY.containsKey(precedingWordLower)) {
scalar = Utils.BOOSTER_DICTIONARY.get(precedingWordLower);
if (currentValence < 0.0)
scalar *= -1.0;
if (Utils.isUpper(precedingWord) && textProperties.isCapDIff())
scalar = (currentValence > 0.0) ? scalar + Utils.ALL_CAPS_BOOSTER_SCORE : scalar - Utils.ALL_CAPS_BOOSTER_SCORE;
}
return scalar;
}
private int pythonIndexToJavaIndex(int pythonIndex) {
return textProperties.getWordsAndEmoticons().size() - Math.abs(pythonIndex);
}
private float checkForNever(float currentValence, int startI, int i, int closeTokenIndex) {
ArrayList<String> wordsAndEmoticons = textProperties.getWordsAndEmoticons();
if (startI == 0) {
if (isNegative(new ArrayList<>(Collections.singletonList(wordsAndEmoticons.get(i - 1))))) {
currentValence *= Utils.N_SCALAR;
}
}
if (startI == 1) {
String wordAtDistanceTwoLeft = wordsAndEmoticons.get(i - 2);
String wordAtDistanceOneLeft = wordsAndEmoticons.get(i - 1);
if ((wordAtDistanceTwoLeft.equals("never")) && (wordAtDistanceOneLeft.equals("so") || (wordAtDistanceOneLeft.equals("this")))) {
currentValence *= 1.5f;
} else if (isNegative(new ArrayList<>(Collections.singletonList(wordsAndEmoticons.get(closeTokenIndex))))) {
currentValence *= Utils.N_SCALAR;
}
}
if (startI == 2) {
String wordAtDistanceThreeLeft = wordsAndEmoticons.get(i - 3);
String wordAtDistanceTwoLeft = wordsAndEmoticons.get(i - 2);
String wordAtDistanceOneLeft = wordsAndEmoticons.get(i - 1);
if ((wordAtDistanceThreeLeft.equals("never")) &&
(wordAtDistanceTwoLeft.equals("so") || wordAtDistanceTwoLeft.equals("this")) ||
(wordAtDistanceOneLeft.equals("so") || wordAtDistanceOneLeft.equals("this"))) {
currentValence *= 1.25f;
} else if (isNegative(new ArrayList<>(Collections.singletonList(wordsAndEmoticons.get(closeTokenIndex))))) {
currentValence *= Utils.N_SCALAR;
}
}
return currentValence;
}
private float checkForIdioms(float currentValence, int i) {
ArrayList<String> wordsAndEmoticons = textProperties.getWordsAndEmoticons();
final String leftBiGramFromCurrent = String.format("%s %s", wordsAndEmoticons.get(i - 1), wordsAndEmoticons.get(i));
final String leftTriGramFromCurrent = String.format("%s %s %s", wordsAndEmoticons.get(i - 2), wordsAndEmoticons.get(i - 1), wordsAndEmoticons.get(i));
final String leftBiGramFromOnePrevious = String.format("%s %s", wordsAndEmoticons.get(i - 2), wordsAndEmoticons.get(i - 1));
final String leftTriGramFromOnePrevious = String.format("%s %s %s", wordsAndEmoticons.get(i - 3), wordsAndEmoticons.get(i - 2), wordsAndEmoticons.get(i - 1));
final String leftBiGramFromTwoPrevious = String.format("%s %s", wordsAndEmoticons.get(i - 3), wordsAndEmoticons.get(i - 2));
ArrayList<String> leftGramSequences = new ArrayList<String>() {{
add(leftBiGramFromCurrent);
add(leftTriGramFromCurrent);
add(leftBiGramFromOnePrevious);
add(leftTriGramFromOnePrevious);
add(leftBiGramFromTwoPrevious);
}};
if (logger.isDebugEnabled())
logger.debug("Grams: " + leftGramSequences);
for (String leftGramSequence : leftGramSequences) {
if (Utils.SENTIMENT_LADEN_IDIOMS.containsKey(leftGramSequence)) {
currentValence = Utils.SENTIMENT_LADEN_IDIOMS.get(leftGramSequence);
break;
}
}
if (wordsAndEmoticons.size() - 1 > i) {
final String rightBiGramFromCurrent = String.format("%s %s", wordsAndEmoticons.get(i), wordsAndEmoticons.get(i + 1));
if (Utils.SENTIMENT_LADEN_IDIOMS.containsKey(rightBiGramFromCurrent))
currentValence = Utils.SENTIMENT_LADEN_IDIOMS.get(rightBiGramFromCurrent);
}
if (wordsAndEmoticons.size() - 1 > i + 1) {
final String rightTriGramFromCurrent = String.format("%s %s %s", wordsAndEmoticons.get(i), wordsAndEmoticons.get(i + 1), wordsAndEmoticons.get(i + 2));
if (Utils.SENTIMENT_LADEN_IDIOMS.containsKey(rightTriGramFromCurrent))
currentValence = Utils.SENTIMENT_LADEN_IDIOMS.get(rightTriGramFromCurrent);
}
if (Utils.BOOSTER_DICTIONARY.containsKey(leftBiGramFromTwoPrevious) || Utils.BOOSTER_DICTIONARY.containsKey(leftBiGramFromOnePrevious))
currentValence += Utils.DAMPENER_WORD_DECREMENT;
return currentValence;
}
private HashMap<String, Float> getSentiment() {
ArrayList<Float> sentiments = new ArrayList<>();
ArrayList<String> wordsAndEmoticons = textProperties.getWordsAndEmoticons();
for (String item : wordsAndEmoticons) {
float currentValence = 0.0f;
int i = wordsAndEmoticons.indexOf(item);
logger.debug("Current token, \"" + item + "\" with index, i = " + i);
logger.debug("Sentiment State before \"kind of\" processing: " + sentiments);
if (i < wordsAndEmoticons.size() - 1 &&
item.toLowerCase().equals("kind") &&
wordsAndEmoticons.get(i + 1).toLowerCase().equals("of") ||
Utils.BOOSTER_DICTIONARY.containsKey(item.toLowerCase())) {
sentiments.add(currentValence);
continue;
}
logger.debug("Sentiment State after \"kind of\" processing: " + sentiments);
logger.debug(String.format("Current Valence is %f for \"%s\"", currentValence, item));
String currentItemLower = item.toLowerCase();
if (Utils.WORD_VALENCE_DICTIONARY.containsKey(currentItemLower)) {
currentValence = Utils.WORD_VALENCE_DICTIONARY.get(currentItemLower);
logger.debug(Utils.isUpper(item));
logger.debug(textProperties.isCapDIff());
logger.debug((Utils.isUpper(item) && textProperties.isCapDIff()) + "\t" + item + "\t" + textProperties.isCapDIff());
if (Utils.isUpper(item) && textProperties.isCapDIff()) {
currentValence = (currentValence > 0.0) ? currentValence + Utils.ALL_CAPS_BOOSTER_SCORE : currentValence - Utils.ALL_CAPS_BOOSTER_SCORE;
}
logger.debug(String.format("Current Valence post all CAPS checks: %f", currentValence));
int startI = 0;
float gramBasedValence = 0.0f;
while (startI < 3) {
int closeTokenIndex = i - (startI + 1);
if (closeTokenIndex < 0)
closeTokenIndex = pythonIndexToJavaIndex(closeTokenIndex);
if ((i > startI) && !Utils.WORD_VALENCE_DICTIONARY.containsKey(wordsAndEmoticons.get(closeTokenIndex).toLowerCase())) {
logger.debug(String.format("Current Valence pre gramBasedValence: %f", currentValence));
gramBasedValence = valenceModifier(wordsAndEmoticons.get(closeTokenIndex), currentValence);
logger.debug(String.format("Current Valence post gramBasedValence: %f", currentValence));
if (startI == 1 && gramBasedValence != 0.0f)
gramBasedValence *= 0.95f;
if (startI == 2 && gramBasedValence != 0.0f)
gramBasedValence *= 0.9f;
currentValence += gramBasedValence;
logger.debug(String.format("Current Valence post gramBasedValence and distance boosting: %f", currentValence));
currentValence = checkForNever(currentValence, startI, i, closeTokenIndex);
logger.debug(String.format("Current Valence post \"never\" check: %f", currentValence));
if (startI == 2) {
currentValence = checkForIdioms(currentValence, i);
logger.debug(String.format("Current Valence post Idiom check: %f", currentValence));
}
}
startI++;
}
if (i > 1 && !Utils.WORD_VALENCE_DICTIONARY.containsKey(wordsAndEmoticons.get(i - 1).toLowerCase()) && wordsAndEmoticons.get(i - 1).toLowerCase().equals("least")) {
if (!(wordsAndEmoticons.get(i - 2).toLowerCase().equals("at") || wordsAndEmoticons.get(i - 2).toLowerCase().equals("very")))
currentValence *= Utils.N_SCALAR;
} else if (i > 0 && !Utils.WORD_VALENCE_DICTIONARY.containsKey(wordsAndEmoticons.get(i - 1).toLowerCase()) && wordsAndEmoticons.get(i - 1).equals("least")) {
currentValence *= Utils.N_SCALAR;
}
}
sentiments.add(currentValence);
}
if (logger.isDebugEnabled())
logger.debug("Sentiment state after first pass through tokens: " + sentiments);
sentiments = checkConjunctionBut(wordsAndEmoticons, sentiments);
if (logger.isDebugEnabled())
logger.debug("Sentiment state after checking conjunctions: " + sentiments);
return polarityScores(sentiments);
}
private ArrayList<Float> siftSentimentScores(ArrayList<Float> currentSentimentState) {
float positiveSentimentScore = 0.0f;
float negativeSentimentScore = 0.0f;
int neutralSentimentCount = 0;
for (Float valence : currentSentimentState) {
if (valence > 0.0f)
positiveSentimentScore = positiveSentimentScore + valence + 1.0f;
else if (valence < 0.0f)
negativeSentimentScore = negativeSentimentScore + valence - 1.0f;
else
neutralSentimentCount += 1;
}
return new ArrayList<>(Arrays.asList(
positiveSentimentScore,
negativeSentimentScore,
(float) neutralSentimentCount)
);
}
private HashMap<String, Float> polarityScores(ArrayList<Float> currentSentimentState) {
if (!currentSentimentState.isEmpty()) {
float totalValence = 0.0f;
for (Float valence : currentSentimentState)
totalValence += valence;
logger.debug("Total valence: " + totalValence);
float punctuationAmplifier = boostByPunctuation();
if (totalValence > 0.0f)
totalValence += boostByPunctuation();
else if (totalValence < 0.0f)
totalValence -= boostByPunctuation();
logger.debug("Total valence after boost/damp by punctuation: " + totalValence);
float compoundPolarity = normalizeScore(totalValence);
logger.debug("Final token-wise sentiment state: " + currentSentimentState);
ArrayList<Float> siftedScores = siftSentimentScores(currentSentimentState);
float positiveSentimentScore = siftedScores.get(0);
float negativeSentimentScore = siftedScores.get(1);
int neutralSentimentCount = Math.round(siftedScores.get(2));
logger.debug(String.format("Post Sift Sentiment Scores: %s %s %s", positiveSentimentScore, negativeSentimentScore, neutralSentimentCount));
if (positiveSentimentScore > Math.abs(negativeSentimentScore))
positiveSentimentScore += punctuationAmplifier;
else if (positiveSentimentScore < Math.abs(negativeSentimentScore))
negativeSentimentScore -= punctuationAmplifier;
float normalizationFactor = positiveSentimentScore + Math.abs(negativeSentimentScore)
+ neutralSentimentCount;
logger.debug("Normalization Factor: " + normalizationFactor);
logger.debug(String.format("Pre-Normalized Scores: %s %s %s %s",
Math.abs(positiveSentimentScore),
Math.abs(negativeSentimentScore),
Math.abs(neutralSentimentCount),
compoundPolarity
));
logger.debug(String.format("Pre-Round Scores: %s %s %s %s",
Math.abs(positiveSentimentScore / normalizationFactor),
Math.abs(negativeSentimentScore / normalizationFactor),
Math.abs(neutralSentimentCount / normalizationFactor),
compoundPolarity
));
final float normalizedPositivePolarity = roundDecimal(Math.abs(positiveSentimentScore / normalizationFactor), 3);
final float normalizedNegativePolarity = roundDecimal(Math.abs(negativeSentimentScore / normalizationFactor), 3);
final float normalizedNeutralPolarity = roundDecimal(Math.abs(neutralSentimentCount / normalizationFactor), 3);
final float normalizedCompoundPolarity = roundDecimal(compoundPolarity, 4);
return new HashMap<String, Float>() {{
put("compound", normalizedCompoundPolarity);
put("positive", normalizedPositivePolarity);
put("negative", normalizedNegativePolarity);
put("neutral", normalizedNeutralPolarity);
}};
} else {
return new HashMap<String, Float>() {{
put("compound", 0.0f);
put("positive", 0.0f);
put("negative", 0.0f);
put("neutral", 0.0f);
}};
}
}
private float boostByPunctuation() {
return boostByExclamation() + boostByQuestionMark();
}
private float boostByExclamation() {
int exclamationCount = StringUtils.countMatches(text, "!");
return Math.min(exclamationCount, 4) * Utils.EXCLAMATION_BOOST;
}
private float boostByQuestionMark() {
int questionMarkCount = StringUtils.countMatches(text, "?");
float questionMarkAmplifier = 0.0f;
if (questionMarkCount > 1)
questionMarkAmplifier = (questionMarkCount <= 3) ? questionMarkCount * Utils.QUESTION_BOOST_COUNT_3 : Utils.QUESTION_BOOST;
return questionMarkAmplifier;
}
private ArrayList<Float> checkConjunctionBut(ArrayList<String> inputTokens, ArrayList<Float> currentSentimentState) {
if (inputTokens.contains("but") || inputTokens.contains("BUT")) {
int index = inputTokens.indexOf("but");
if (index == -1)
index = inputTokens.indexOf("BUT");
for (Float valence : currentSentimentState) {
int currentValenceIndex = currentSentimentState.indexOf(valence);
if (currentValenceIndex < index) {
currentSentimentState.set(currentValenceIndex, valence * 0.5f);
} else if (currentValenceIndex > index) {
currentSentimentState.set(currentValenceIndex, valence * 1.5f);
}
}
}
return currentSentimentState;
}
private boolean hasAtLeast(ArrayList<String> tokenList) {
if (tokenList.contains("least")) {
int index = tokenList.indexOf("least");
if (index > 0 && tokenList.get(index - 1).equals("at"))
return true;
}
return false;
}
private boolean hasContraction(ArrayList<String> tokenList) {
for (String s : tokenList) {
if (s.endsWith("n't"))
return true;
}
return false;
}
private boolean hasNegativeWord(ArrayList<String> tokenList, ArrayList<String> newNegWords) {
for (String newNegWord : newNegWords) {
if (tokenList.contains(newNegWord))
return true;
}
return false;
}
private boolean isNegative(ArrayList<String> tokenList, ArrayList<String> newNegWords, boolean checkContractions) {
newNegWords.addAll(Utils.NEGATIVE_WORDS);
boolean result = hasNegativeWord(tokenList, newNegWords) || hasAtLeast(tokenList);
if (checkContractions)
return result;
return result || hasContraction(tokenList);
}
private boolean isNegative(ArrayList<String> tokenList, ArrayList<String> newNegWords) {
newNegWords.addAll(Utils.NEGATIVE_WORDS);
return hasNegativeWord(tokenList, newNegWords) || hasAtLeast(tokenList) || hasContraction(tokenList);
}
private boolean isNegative(ArrayList<String> tokenList) {
return hasNegativeWord(tokenList, Utils.NEGATIVE_WORDS) || hasAtLeast(tokenList) || hasContraction(tokenList);
}
private float normalizeScore(float score, float alpha) {
double normalizedScore = score / Math.sqrt((score * score) + alpha);
return (float) normalizedScore;
}
private float normalizeScore(float score) {
double normalizedScore = score / Math.sqrt((score * score) + 15.0f);
return (float) normalizedScore;
}
private static float roundDecimal(float currentValue, int roundTo) {
float n = (float) Math.pow(10.0, (double) roundTo);
float number = Math.round(currentValue * n);
return number / n;
}
} |
package net.smoofyuniverse.epi.stats;
import com.fasterxml.jackson.core.*;
import net.smoofyuniverse.common.util.StringUtil;
import net.smoofyuniverse.epi.api.PlayerInfo;
import org.mariuszgromada.math.mxparser.Argument;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class RankingList {
public static final int CURRENT_VERSION = 5, MINIMUM_VERSION = 1;
private static final JsonFactory factory = new JsonFactory();
private Map<String, Ranking> rankings = new TreeMap<>();
private Set<String> extensions = new HashSet<>();
private DataCollection collection;
public RankingList(DataCollection col) {
this.collection = col;
}
private RankingList() {}
public DataCollection getCollection() {
return this.collection;
}
public Optional<Ranking> get(String name) {
return Optional.ofNullable(this.rankings.get(name));
}
public Ranking getOrCreate(String name) {
Ranking r = this.rankings.get(name);
if (r == null) {
r = new Ranking(this, name);
this.rankings.put(name, r);
int i = name.indexOf('_');
if (i != -1)
this.extensions.add(name.substring(i + 1));
} else
r.descending = false;
return r;
}
public void copy(String name, String newName) {
Ranking r = this.rankings.get(name);
if (r != null)
this.rankings.put(newName, r.copy(newName));
}
public void move(String name, String newName) {
Ranking r = this.rankings.remove(name);
if (r != null)
this.rankings.put(newName, r.copy(newName));
}
public Collection<Ranking> getRankings() {
return this.rankings.values();
}
public List<Ranking> list(Predicate<String> predicate) {
List<Ranking> l = new ArrayList<>();
for (Ranking r : this.rankings.values()) {
if (predicate.test(r.name))
l.add(r);
}
return l;
}
public int remove(Predicate<String> predicate) {
int count = 0;
Iterator<Ranking> it = this.rankings.values().iterator();
while (it.hasNext()) {
if (predicate.test(it.next().name)) {
it.remove();
count++;
}
}
return count;
}
public Argument[] getAllArguments(AtomicInteger player) {
Argument[] args = new Argument[this.rankings.size() * 2 + this.extensions.size()];
int i = 0;
for (Ranking r : this.rankings.values()) {
args[i++] = new PlayerDependantArgument(r.name, player, r::getValue);
args[i++] = new PlayerDependantArgument("rank_" + r.name, player, p -> {
int rank = r.getRank(p);
return rank == -1 ? Double.NaN : rank + 1;
});
}
for (String s : this.extensions)
args[i++] = new PlayerDependantArgument("total_" + s, player, p -> total(s, p));
return args;
}
public double total(String extension, int player) {
return total((s) -> {
int i = s.indexOf('_');
return i != -1 && s.substring(i + 1).equals(extension);
}, player);
}
public double total(Predicate<String> predicate, int player) {
double total = 0;
for (Ranking r : this.rankings.values()) {
if (predicate.test(r.name))
total += r.getValue(player);
}
return total;
}
public Argument[] getArguments(String expression, AtomicInteger player) {
List<Argument> args = new ArrayList<>();
boolean rank_ = expression.contains("rank_"), total_ = expression.contains("total_");
for (Ranking r : this.rankings.values()) {
if (!expression.contains(r.name))
continue;
args.add(new PlayerDependantArgument(r.name, player, r::getValue));
if (rank_ && expression.contains("rank_" + r.name)) {
args.add(new PlayerDependantArgument("rank_" + r.name, player, p -> {
int rank = r.getRank(p);
return rank == -1 ? Double.NaN : rank + 1;
}));
}
}
if (total_) {
for (String s : this.extensions) {
if (expression.contains("total_" + s))
args.add(new PlayerDependantArgument("total_" + s, player, p -> total(s, p)));
}
}
return args.toArray(new Argument[args.size()]);
}
public void save(Path file) throws IOException {
String fn = file.getFileName().toString();
if (fn.endsWith(".json")) {
try (JsonGenerator json = factory.createGenerator(Files.newOutputStream(file))) {
json.useDefaultPrettyPrinter();
saveJSON(json);
}
} else if (fn.endsWith(".csv")) {
try (BufferedWriter out = Files.newBufferedWriter(file)) {
saveCSV(out);
}
} else {
try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(file))) {
save(out);
}
}
}
public void saveJSON(JsonGenerator json) throws IOException {
json.writeStartObject();
json.writeFieldName("format_version");
json.writeNumber(CURRENT_VERSION);
boolean useIntervals = this.collection.containsIntervals();
json.writeFieldName("players");
json.writeStartArray();
int total = getPlayerCount();
for (int i = 0; i < total; i++) {
PlayerInfo p = getPlayer(i);
json.writeStartObject();
json.writeFieldName("id");
if (p.id == null)
json.writeNull();
else
json.writeString(p.id.toString());
json.writeFieldName("name");
json.writeString(p.name);
if (useIntervals) {
json.writeFieldName("dates");
json.writeStartArray();
json.writeString(StringUtil.DATETIME_FORMAT.format(p.startDate));
json.writeString(StringUtil.DATETIME_FORMAT.format(p.endDate));
json.writeEndArray();
} else {
json.writeFieldName("date");
json.writeString(StringUtil.DATETIME_FORMAT.format(p.endDate));
}
json.writeEndObject();
}
json.writeEndArray();
json.writeFieldName("rankings");
json.writeStartArray();
for (Ranking r : this.rankings.values()) {
json.writeStartObject();
json.writeFieldName("name");
json.writeString(r.name);
json.writeFieldName("descending");
json.writeBoolean(r.descending);
json.writeFieldName("content");
json.writeStartArray();
for (int p : r.collection().originalOrder()) {
json.writeNumber(p);
json.writeNumber(r.getValue(p));
}
json.writeEndArray();
json.writeEndObject();
}
json.writeEndArray();
json.writeEndObject();
}
public void saveCSV(BufferedWriter out) throws IOException {
out.write("Dates");
out.newLine();
if (this.collection.containsIntervals()) {
out.write("Début");
StringUtil.DATETIME_FORMAT.formatTo(this.collection.getMinStartDate(), out);
out.write(',');
StringUtil.DATETIME_FORMAT.formatTo(this.collection.getMaxStartDate(), out);
out.newLine();
}
out.write("Fin");
out.write(',');
StringUtil.DATETIME_FORMAT.formatTo(this.collection.getMinEndDate(), out);
out.write(',');
StringUtil.DATETIME_FORMAT.formatTo(this.collection.getMaxEndDate(), out);
out.newLine();
Ranking[] rankings = new Ranking[this.rankings.size()];
Iterator<Integer>[] iterators = new Iterator[rankings.length];
out.write("Classement");
int i = 0;
for (Ranking r : this.rankings.values()) {
out.write(',');
out.write("Joueur");
out.write(',');
out.write(r.name);
rankings[i] = r;
iterators[i++] = r.collection().iterator();
}
int total = getPlayerCount();
for (int rank = 0; rank < total; rank++) {
out.newLine();
out.write(Integer.toString(rank +1));
for (i = 0; i < rankings.length; i++) {
Iterator<Integer> it = iterators[i];
if (it.hasNext()) {
int p = it.next();
out.write(',');
out.write(getPlayer(p).name);
out.write(',');
out.write(Double.toString(rankings[i].getValue(p)));
} else {
out.write(",,");
}
}
}
}
public void save(DataOutputStream out) throws IOException {
out.writeInt(CURRENT_VERSION);
GZIPOutputStream zip = new GZIPOutputStream(out);
out = new DataOutputStream(zip);
boolean useIntervals = this.collection.containsIntervals();
out.writeBoolean(useIntervals);
int total = getPlayerCount();
out.writeInt(total);
for (int i = 0; i < total; i++) {
PlayerInfo p = getPlayer(i);
if (p.id == null) {
out.writeLong(0);
out.writeLong(0);
} else {
out.writeLong(p.id.getMostSignificantBits());
out.writeLong(p.id.getLeastSignificantBits());
}
out.writeUTF(p.name);
if (useIntervals)
out.writeLong(p.startDate.toEpochMilli());
out.writeLong(p.endDate.toEpochMilli());
}
out.writeInt(this.rankings.size());
for (Ranking r : this.rankings.values()) {
out.writeUTF(r.name);
out.writeBoolean(r.descending);
out.writeInt(r.size());
for (int p : r.collection().originalOrder()) {
out.writeInt(p);
out.writeDouble(r.getValue(p));
}
}
zip.finish();
}
public int getPlayerCount() {
return this.collection.getPlayerCount();
}
public PlayerInfo getPlayer(int p) {
return this.collection.getPlayer(p);
}
public static RankingList read(Path file) throws IOException {
String fn = file.getFileName().toString();
if (!Files.exists(file))
throw new FileNotFoundException(fn);
if (fn.endsWith(".json")) {
try (JsonParser json = factory.createParser(Files.newInputStream(file))) {
return readJSON(json);
}
} else {
try (DataInputStream in = new DataInputStream(Files.newInputStream(file))) {
return read(in);
}
}
}
public static RankingList readJSON(JsonParser json) throws IOException {
if (json.nextToken() != JsonToken.START_OBJECT)
throw new JsonParseException(json, "Expected to start a new object");
RankingList l = new RankingList();
int version = -1;
Instant date = null;
while (json.nextToken() != JsonToken.END_OBJECT) {
String field = json.getCurrentName();
if (version == -1) {
if (!field.equals("format_version") || json.nextToken() != JsonToken.VALUE_NUMBER_INT)
throw new IOException("Format version not provided");
version = json.getIntValue();
if (version > CURRENT_VERSION || version < MINIMUM_VERSION)
throw new IOException("Invalid format version: " + version);
continue;
}
if (version == 1 && field.equals("date")) {
if (json.nextToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'date' was expected to be a string");
date = Instant.from(StringUtil.DATETIME_FORMAT.parse(json.getValueAsString()));
continue;
}
if (field.equals("players")) {
if (json.nextToken() != JsonToken.START_ARRAY)
throw new JsonParseException(json, "Field 'players' was expected to be an array");
List<PlayerInfo> players = new ArrayList<>();
if (version == 1) {
if (date == null)
throw new IllegalStateException("Date was not provided");
while (json.nextToken() != JsonToken.END_ARRAY) {
if (json.currentToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'players' was expected to contains strings");
players.add(new PlayerInfo(json.getValueAsString(), null, null, date));
}
} else {
while (json.nextToken() != JsonToken.END_ARRAY) {
if (json.currentToken() != JsonToken.START_OBJECT)
throw new JsonParseException(json, "Expected to start a new player object");
UUID id = null;
String name = null;
Instant startDate = null, endDate = null;
while (json.nextToken() != JsonToken.END_OBJECT) {
String field2 = json.getCurrentName();
if (field2.equals("id")) {
if (json.nextToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'id' of a player was expected to be a string");
id = UUID.fromString(json.getValueAsString());
continue;
}
if (field2.equals("name")) {
if (json.nextToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'name' of a player was expected to be a string");
name = json.getValueAsString();
continue;
}
if (field2.equals("dates")) {
if (json.nextToken() != JsonToken.START_ARRAY)
throw new JsonParseException(json, "Field 'dates' of a player was expected to be an array");
List<Instant> dates = new ArrayList<>();
while (json.nextToken() != JsonToken.END_ARRAY) {
if (json.currentToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'dates' of a player was expected to contains strings");
dates.add(Instant.from(StringUtil.DATETIME_FORMAT.parse(json.getValueAsString())));
}
startDate = dates.get(0);
endDate = dates.get(1);
continue;
}
if (field2.equals("date")) {
if (json.nextToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'date' of a player was expected to be a string");
endDate = Instant.from(StringUtil.DATETIME_FORMAT.parse(json.getValueAsString()));
continue;
}
json.nextToken();
json.skipChildren();
}
if (name == null)
throw new IllegalArgumentException("Field 'name' is missing");
if (id == null)
throw new IllegalArgumentException("Field 'id' is missing");
if (endDate == null)
throw new IllegalArgumentException("Field 'dates' is missing");
players.add(new PlayerInfo(name, id, startDate, endDate));
}
}
l.collection = new DataCollection(players.toArray(new PlayerInfo[players.size()]));
continue;
}
if (field.equals("rankings")) {
if (json.nextToken() != JsonToken.START_ARRAY)
throw new JsonParseException(json, "Field 'rankings' was expected to be an array");
while (json.nextToken() != JsonToken.END_ARRAY) {
if (json.currentToken() != JsonToken.START_OBJECT)
throw new JsonParseException(json, "Expected to start a new ranking object");
String name = null;
Boolean descending = null;
List<Integer> players = null;
List<Double> values = null;
while (json.nextToken() != JsonToken.END_OBJECT) {
String field2 = json.getCurrentName();
try {
if (field2.equals("name")) {
if (json.nextToken() != JsonToken.VALUE_STRING)
throw new JsonParseException(json, "Field 'name' of a ranking was expected to be a string");
name = json.getValueAsString();
continue;
}
if (field2.equals("descending")) {
if (json.nextToken() != JsonToken.VALUE_FALSE && json.currentToken() != JsonToken.VALUE_TRUE)
throw new JsonParseException(json, "Field 'descending' of a ranking was expected to be a boolean");
descending = json.getValueAsBoolean();
continue;
}
if (field2.equals("content")) {
if (json.nextToken() != JsonToken.START_ARRAY)
throw new JsonParseException(json, "Field 'content' of a ranking was expected to be an array");
players = new ArrayList<>();
values = new ArrayList<>();
while (json.nextToken() != JsonToken.END_ARRAY) {
players.add(json.getIntValue());
json.nextToken();
values.add(json.getDoubleValue());
}
continue;
}
} finally {
if (name != null && descending != null && players != null && values != null) {
Ranking r = new Ranking(l, name);
for (int i = 0; i < players.size(); i++)
r.put(players.get(i), values.get(i));
r.descending = descending;
l.rankings.put(r.name, r);
name = null;
descending = null;
players = null;
values = null;
}
}
json.nextToken();
json.skipChildren();
}
}
continue;
}
json.nextToken();
json.skipChildren();
}
if (l.collection == null)
throw new IllegalStateException("Players was not provided");
return l;
}
public static RankingList read(DataInputStream in) throws IOException {
int version = in.readInt();
if (version > CURRENT_VERSION || version < MINIMUM_VERSION)
throw new IOException("Invalid format version: " + version);
if (version >= 5)
in = new DataInputStream(new GZIPInputStream(in));
PlayerInfo[] players;
if (version == 1) {
Instant date = Instant.ofEpochMilli(in.readLong());
players = new PlayerInfo[in.readInt()];
for (int i = 0; i < players.length; i++) {
players[i] = new PlayerInfo(in.readUTF(), null, null, date);
}
} else {
boolean useIntervals = version >= 4 && in.readBoolean();
players = new PlayerInfo[in.readInt()];
for (int i = 0; i < players.length; i++) {
long most = in.readLong(), least = in.readLong();
UUID id = (most != 0 || least != 0) ? new UUID(most, least) : null;
String name = in.readUTF();
Instant startDate = useIntervals ? Instant.ofEpochMilli(in.readLong()) : null;
Instant endDate = Instant.ofEpochMilli(in.readLong());
players[i] = new PlayerInfo(name, id, startDate, endDate);
}
}
RankingList l = new RankingList(new DataCollection(players));
int rankings = in.readInt();
for (int i = 0; i < rankings; i++) {
Ranking r = new Ranking(l, in.readUTF());
boolean d = in.readBoolean();
int size = version == 2 ? players.length : in.readInt();
for (int p = 0; p < size; p++)
r.put(in.readInt(), in.readDouble());
r.descending = d;
l.rankings.put(r.name, r);
}
return l;
}
} |
package org.metawatch.manager.widgets;
import java.util.ArrayList;
import java.util.Map;
import org.metawatch.manager.FontCache;
import org.metawatch.manager.MetaWatchService;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.Monitors.LocationData;
import org.metawatch.manager.Monitors.WeatherData;
import org.metawatch.manager.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.text.Layout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
public class WeatherWidget implements InternalWidget {
public final static String id_0 = "weather_24_32";
final static String desc_0 = "Current Weather (24x32)";
public final static String id_1 = "weather_96_32";
final static String desc_1 = "Current Weather (96x32)";
public final static String id_2 = "weather_fc_96_32";
final static String desc_2 = "Weather Forecast (96x32)";
public final static String id_3 = "moon_24_32";
final static String desc_3 = "Moon Phase (24x32)";
public final static String id_4 = "weather_80_16";
final static String desc_4 = "Current Weather (80x16)";
public final static String id_5 = "moon_16_16";
final static String desc_5 = "Moon Phase (16x16)";
public final static String id_6 = "weather_fc_80_16";
final static String desc_6 = "Weather Forecast (80x16)";
private Context context = null;
private TextPaint paintSmall;
private TextPaint paintSmallOutline;
private TextPaint paintLarge;
private TextPaint paintLargeOutline;
private TextPaint paintSmallNumerals;
private TextPaint paintSmallNumeralsOutline;
public void init(Context context, ArrayList<CharSequence> widgetIds) {
this.context = context;
paintSmall = new TextPaint();
paintSmall.setColor(Color.BLACK);
paintSmall.setTextSize(FontCache.instance(context).Small.size);
paintSmall.setTypeface(FontCache.instance(context).Small.face);
paintSmallOutline = new TextPaint();
paintSmallOutline.setColor(Color.WHITE);
paintSmallOutline.setTextSize(FontCache.instance(context).Small.size);
paintSmallOutline.setTypeface(FontCache.instance(context).Small.face);
paintLarge = new TextPaint();
paintLarge.setColor(Color.BLACK);
paintLarge.setTextSize(FontCache.instance(context).Large.size);
paintLarge.setTypeface(FontCache.instance(context).Large.face);
paintLargeOutline = new TextPaint();
paintLargeOutline.setColor(Color.WHITE);
paintLargeOutline.setTextSize(FontCache.instance(context).Large.size);
paintLargeOutline.setTypeface(FontCache.instance(context).Large.face);
paintSmallNumerals = new TextPaint();
paintSmallNumerals.setColor(Color.BLACK);
paintSmallNumerals.setTextSize(FontCache.instance(context).SmallNumerals.size);
paintSmallNumerals.setTypeface(FontCache.instance(context).SmallNumerals.face);
paintSmallNumeralsOutline = new TextPaint();
paintSmallNumeralsOutline.setColor(Color.WHITE);
paintSmallNumeralsOutline.setTextSize(FontCache.instance(context).SmallNumerals.size);
paintSmallNumeralsOutline.setTypeface(FontCache.instance(context).SmallNumerals.face);
}
public void shutdown() {
paintSmall = null;
}
public void refresh(ArrayList<CharSequence> widgetIds) {
}
public void get(ArrayList<CharSequence> widgetIds, Map<String,WidgetData> result) {
if(context ==null)
return;
if(widgetIds == null || widgetIds.contains(id_0)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_0;
widget.description = desc_0;
widget.width = 24;
widget.height = 32;
widget.bitmap = draw0();
widget.priority = calcPriority();
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_1)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_1;
widget.description = desc_1;
widget.width = 96;
widget.height = 32;
widget.bitmap = draw1();
widget.priority = calcPriority();
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_2)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_2;
widget.description = desc_2;
widget.width = 96;
widget.height = 32;
widget.bitmap = draw2();
widget.priority = calcPriority();
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_3)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_3;
widget.description = desc_3;
widget.width = 24;
widget.height = 32;
widget.bitmap = draw3();
widget.priority = WeatherData.moonPercentIlluminated !=-1 ? calcPriority() : -1;
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_4)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_4;
widget.description = desc_4;
widget.width = 80;
widget.height = 16;
widget.bitmap = draw4();
widget.priority = calcPriority();
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_5)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_5;
widget.description = desc_5;
widget.width = 16;
widget.height = 16;
widget.bitmap = draw5();
widget.priority = WeatherData.moonPercentIlluminated !=-1 ? calcPriority() : -1;
result.put(widget.id, widget);
}
if(widgetIds == null || widgetIds.contains(id_6)) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.id = id_6;
widget.description = desc_6;
widget.width = 80;
widget.height = 16;
widget.bitmap = draw6();
widget.priority = calcPriority();
result.put(widget.id, widget);
}
}
private int calcPriority()
{
if(Preferences.weatherProvider == MetaWatchService.WeatherProvider.DISABLED)
return -1;
return WeatherData.received ? 1 : 0;
}
private Bitmap draw0() {
Bitmap bitmap = Bitmap.createBitmap(24, 32, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
if (WeatherData.received) {
// icon
Bitmap image = Utils.loadBitmapFromAssets(context, WeatherData.icon);
canvas.drawBitmap(image, 0, 4, null);
// temperatures
if (WeatherData.celsius) {
Utils.drawOutlinedText(WeatherData.temp+"C", canvas, 0, 7, paintSmall, paintSmallOutline);
}
else {
Utils.drawOutlinedText(WeatherData.temp+"F", canvas, 0, 7, paintSmall, paintSmallOutline);
}
paintLarge.setTextAlign(Paint.Align.LEFT);
Utils.drawOutlinedText("H "+WeatherData.forecast[0].tempHigh, canvas, 0, 25, paintSmall, paintSmallOutline);
Utils.drawOutlinedText("L "+WeatherData.forecast[0].tempLow, canvas, 0, 31, paintSmall, paintSmallOutline);
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Wait", 12, 16, paintSmall);
paintSmall.setTextAlign(Paint.Align.LEFT);
}
return bitmap;
}
private Bitmap draw1() {
Bitmap bitmap = Bitmap.createBitmap(96, 32, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
if (WeatherData.received) {
// icon
Bitmap image = Utils.loadBitmapFromAssets(context, WeatherData.icon);
if (Preferences.overlayWeatherText)
canvas.drawBitmap(image, 36, 5, null);
else
canvas.drawBitmap(image, 34, 1, null);
// condition
if (Preferences.overlayWeatherText)
Utils.drawWrappedOutlinedText(WeatherData.condition, canvas, 1, 2, 60, paintSmall, paintSmallOutline, Layout.Alignment.ALIGN_NORMAL);
else
Utils.drawWrappedOutlinedText(WeatherData.condition, canvas, 1, 2, 34, paintSmall, paintSmallOutline, Layout.Alignment.ALIGN_NORMAL);
// temperatures
paintLarge.setTextAlign(Paint.Align.RIGHT);
paintLargeOutline.setTextAlign(Paint.Align.RIGHT);
Utils.drawOutlinedText(WeatherData.temp, canvas, 82, 13, paintLarge, paintLargeOutline);
if (WeatherData.celsius) {
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 82, 7, paintSmall);
canvas.drawText("C", 95, 13, paintLarge);
}
else {
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 83, 7, paintSmall);
canvas.drawText("F", 95, 13, paintLarge);
}
paintLarge.setTextAlign(Paint.Align.LEFT);
if (WeatherData.forecast!=null) {
canvas.drawText("High", 64, 23, paintSmall);
canvas.drawText("Low", 64, 31, paintSmall);
paintSmall.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.forecast[0].tempHigh, 95, 23, paintSmall);
canvas.drawText(WeatherData.forecast[0].tempLow, 95, 31, paintSmall);
paintSmall.setTextAlign(Paint.Align.LEFT);
}
Utils.drawOutlinedText((String) TextUtils.ellipsize(WeatherData.locationName, paintSmall, 63, TruncateAt.END), canvas, 1, 31, paintSmall, paintSmallOutline);
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 48, 18, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 48, 18, paintSmall);
}
}
else {
canvas.drawText("No data", 48, 18, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
return bitmap;
}
private Bitmap draw2() {
Bitmap bitmap = Bitmap.createBitmap(96, 32, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
paintSmall.setTextAlign(Align.LEFT);
paintSmallOutline.setTextAlign(Align.LEFT);
if (WeatherData.received && WeatherData.forecast.length>3) {
int weatherIndex = 0;
if(WeatherData.forecast.length>4)
weatherIndex = 1; // Start with tomorrow's weather if we've got enough entries
for (int i=0;i<4;++i) {
int x = i*24;
Bitmap image = Utils.loadBitmapFromAssets(context, WeatherData.forecast[weatherIndex].icon);
canvas.drawBitmap(image, x, 4, null);
Utils.drawOutlinedText(WeatherData.forecast[weatherIndex].day, canvas, x, 6, paintSmall, paintSmallOutline);
Utils.drawOutlinedText("H "+WeatherData.forecast[weatherIndex].tempHigh, canvas, x, 25, paintSmall, paintSmallOutline);
Utils.drawOutlinedText("L "+WeatherData.forecast[weatherIndex].tempLow, canvas, x, 31, paintSmall, paintSmallOutline);
weatherIndex++;
}
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 48, 18, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 48, 18, paintSmall);
}
}
else {
canvas.drawText("No data", 48, 18, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
return bitmap;
}
final static int[] phaseImage = {0,0,1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,5,5,5,6,6,7,7,7,7,0,0};
private Bitmap draw3() {
Bitmap bitmap = Bitmap.createBitmap(24, 32, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
paintSmall.setTextAlign(Paint.Align.CENTER);
final boolean shouldInvert = Preferences.invertLCD || (MetaWatchService.watchType == MetaWatchService.WatchType.ANALOG);
if (WeatherData.received && WeatherData.ageOfMoon!=-1) {
int moonPhase = WeatherData.ageOfMoon;
int moonImage = phaseImage[moonPhase];
int x = 0-(moonImage*24);
Bitmap image = shouldInvert ? Utils.loadBitmapFromAssets(context, "moon-inv.bmp") : Utils.loadBitmapFromAssets(context, "moon.bmp");
canvas.drawBitmap(image, x, 0, null);
canvas.drawText(Integer.toString(WeatherData.moonPercentIlluminated)+"%", 12, 30, paintSmall);
} else {
canvas.drawText("Wait", 12, 16, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
return bitmap;
}
private Bitmap draw4() {
Bitmap bitmap = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
if (WeatherData.received) {
// icon
String smallIcon = WeatherData.icon.replace(".bmp", "_12.bmp");
Bitmap image = Utils.loadBitmapFromAssets(context, smallIcon);
canvas.drawBitmap(image, 46, 2, null);
// condition
Utils.drawWrappedOutlinedText(WeatherData.condition, canvas, 0, 0, 60, paintSmall, paintSmallOutline, Layout.Alignment.ALIGN_NORMAL);
// temperatures
paintSmall.setTextAlign(Paint.Align.RIGHT);
paintSmallOutline.setTextAlign(Paint.Align.RIGHT);
StringBuilder string = new StringBuilder();
string.append(WeatherData.temp);
if (WeatherData.celsius) {
string.append("C");
}
else {
string.append("F");
}
Utils.drawOutlinedText(string.toString(), canvas, 80, 5, paintSmall, paintSmallOutline);
if (WeatherData.forecast!=null) {
string = new StringBuilder();
string.append(WeatherData.forecast[0].tempHigh);
string.append("/");
string.append(WeatherData.forecast[0].tempLow);
Utils.drawOutlinedText(string.toString(), canvas, 80, 16, paintSmall, paintSmallOutline);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
paintSmallOutline.setTextAlign(Paint.Align.LEFT);
Utils.drawOutlinedText((String) TextUtils.ellipsize(WeatherData.locationName, paintSmall, 47, TruncateAt.END), canvas, 0, 16, paintSmall, paintSmallOutline);
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 40, 9, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 40, 9, paintSmall);
}
}
else {
canvas.drawText("No data", 40, 9, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
return bitmap;
}
private Bitmap draw5() {
Bitmap bitmap = Bitmap.createBitmap(16, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
final boolean shouldInvert = Preferences.invertLCD || (MetaWatchService.watchType == MetaWatchService.WatchType.ANALOG);
paintSmall.setTextAlign(Paint.Align.CENTER);
if (WeatherData.received && WeatherData.ageOfMoon!=-1) {
int moonPhase = WeatherData.ageOfMoon;
int moonImage = phaseImage[moonPhase];
int x = 0-(moonImage*16);
Bitmap image = shouldInvert ? Utils.loadBitmapFromAssets(context, "moon-inv_10.bmp") : Utils.loadBitmapFromAssets(context, "moon_10.bmp");
canvas.drawBitmap(image, x, 0, null);
} else {
canvas.drawText("--", 8, 9, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
return bitmap;
}
private Bitmap draw6() {
Bitmap bitmap = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
paintSmall.setTextAlign(Align.LEFT);
paintSmallOutline.setTextAlign(Align.LEFT);
if (WeatherData.received && WeatherData.forecast.length>3) {
int weatherIndex = 0;
if(WeatherData.forecast.length>3)
weatherIndex = 1; // Start with tomorrow's weather if we've got enough entries
for (int i=0;i<3;++i) {
int x = i*26;
final String smallIcon = WeatherData.forecast[weatherIndex].icon.replace(".bmp", "_12.bmp");
Bitmap image = Utils.loadBitmapFromAssets(context, smallIcon);
canvas.drawBitmap(image, x+12, 0, null);
Utils.drawOutlinedText(WeatherData.forecast[weatherIndex].day.substring(0, 2), canvas, x+1, 6, paintSmall, paintSmallOutline);
StringBuilder hilow = new StringBuilder();
hilow.append(WeatherData.forecast[weatherIndex].tempHigh);
hilow.append("/");
hilow.append(WeatherData.forecast[weatherIndex].tempLow);
Utils.drawOutlinedText(hilow.toString(), canvas, x+1, 16, paintSmallNumerals, paintSmallNumeralsOutline);
weatherIndex++;
}
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 48, 18, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 48, 18, paintSmall);
}
}
else {
canvas.drawText("No data", 48, 18, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
return bitmap;
}
} |
package com.vtence.molecule;
import com.vtence.molecule.helpers.Charsets;
import com.vtence.molecule.helpers.Headers;
import com.vtence.molecule.helpers.Streams;
import com.vtence.molecule.http.AcceptLanguage;
import com.vtence.molecule.http.ContentType;
import com.vtence.molecule.http.Cookie;
import com.vtence.molecule.http.HttpMethod;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static com.vtence.molecule.http.HeaderNames.CONTENT_LENGTH;
import static java.lang.Long.parseLong;
/**
* Holds client request information and maintains attributes during the request lifecycle.
*
* Information includes body, headers, parameters, cookies, locale.
*/
public class Request {
private final Headers headers = new Headers();
private final Map<String, Cookie> cookies = new LinkedHashMap<String, Cookie>();
private final Map<String, List<String>> parameters = new LinkedHashMap<String, List<String>>();
private final Map<Object, Object> attributes = new HashMap<Object, Object>();
private String uri;
private String path;
private String ip;
private int port;
private String hostName;
private String protocol;
private InputStream input;
private HttpMethod method;
private boolean secure;
private long timestamp;
public Request() {}
/**
* Reads the uri of this request.
*
* @return the request uri
*/
public String uri() {
return uri;
}
/**
* Changes the uri of this request.
*
* @param uri the new uri
*/
public Request uri(String uri) {
this.uri = uri;
return this;
}
/**
* Reads the path of this request.
*
* @return the request path
*/
public String path() {
return path;
}
/**
* Changes the path of this request.
*
* @param path the new path
*/
public Request path(String path) {
this.path = path;
return this;
}
/**
* Reads the ip of the remote client of this request.
*
* @return the remote client ip
*/
public String remoteIp() {
return ip;
}
/**
* Changes the ip of the remote client of this request.
*
* @param ip the new ip
*/
public Request remoteIp(String ip) {
this.ip = ip;
return this;
}
/**
* Reads the hostname of the remote client of this request.
*
* @return the remote client hostname
*/
public String remoteHost() {
return hostName;
}
/**
* Changes the hostname of the remote client of this request.
*
* @param hostName the new hostname
*/
public Request remoteHost(String hostName) {
this.hostName = hostName;
return this;
}
/**
* Reads the port of the remote client of this request.
*
* @return the remote client port
*/
public int remotePort() {
return port;
}
/**
* Changes the port of the remote client of this request.
*
* @param port the new port
*/
public Request remotePort(int port) {
this.port = port;
return this;
}
/**
* Reads the protocol of this request.
*
* @return the request protocol
*/
public String protocol() {
return protocol;
}
/**
* Changes the protocol of this request.
*
* @param protocol the new protocol
*/
public Request protocol(String protocol) {
this.protocol = protocol;
return this;
}
/**
* Indicates if this request was done over a secure connection, such as SSL.
*
* @return true if the request was transferred securely
*/
public boolean secure() {
return secure;
}
/**
* Changes the secure state of this request, which indicates if the request was done over a secure channel.
*
* @param secure the new state
*/
public Request secure(boolean secure) {
this.secure = secure;
return this;
}
/**
* Indicates the time in milliseconds when this request was received.
*
* @return the time the request arrived at
*/
public long timestamp() {
return timestamp;
}
/**
* Changes the timestamp of this request.
*
* @param time the new timestamp
*/
public Request timestamp(long time) {
timestamp = time;
return this;
}
/**
* Indicates the HTTP method with which this request was made (e.g. GET, POST, PUT, etc.).
*
* @return the request HTTP method
*/
public HttpMethod method() {
return method;
}
/**
* Changes the HTTP method of this request by name. Method name is case-insensitive and must refer to
* one of the {@link com.vtence.molecule.http.HttpMethod}s.
*
* @param methodName the new method name
*/
public Request method(String methodName) {
return method(HttpMethod.valueOf(methodName));
}
/**
* Changes the HTTP method of this request.
* Method must refer to one of the {@link com.vtence.molecule.http.HttpMethod}s. Matching is done case insensitively.
*
* @param method the new method
*/
public Request method(HttpMethod method) {
this.method = method;
return this;
}
/**
* Provides the text body of this request.
*
* @return the text that makes up the body
*/
public String body() throws IOException {
return new String(bodyContent(), charset());
}
/**
* Provides the body of this request as an array of bytes.
*
* @return the bytes content of the body
*/
public byte[] bodyContent() throws IOException {
return Streams.toBytes(bodyStream());
}
/**
* Provides the body of this request as an {@link java.io.InputStream}.
*
* @return the stream of bytes that make up the body
*/
public InputStream bodyStream() {
return input;
}
/**
* Changes the body of this request.
*
* Note that this will not affect the list of parameters that might have been sent with the original
* body as POST parameters.
*
* @param body the new body as a string
*/
public Request body(String body) {
return body(body.getBytes(charset()));
}
/**
* Changes the body of this request.
*
* Note that this will not affect the list of parameters that might have been sent with the original
* body as POST parameters.
*
* @param content the new body content as an array of bytes
*/
public Request body(byte[] content) {
this.input = new ByteArrayInputStream(content);
return this;
}
/**
* Changes the body of this request.
*
* Note that this will not affect the list of parameters that might have been sent with the original
* body as POST parameters.
*
* @param input the new body content as an array of bytes
*/
public Request body(InputStream input) {
this.input = input;
return this;
}
/**
* Provides the charset used in the body of this request.
* The charset is read from the <code>Content-Type</code> header.
*
* @return the charset of this request or null if <pre>Content-Type</pre> is missing.
*/
public Charset charset() {
ContentType contentType = ContentType.of(this);
if (contentType == null || contentType.charset() == null) {
return Charsets.ISO_8859_1;
}
return contentType.charset();
}
/**
* Checks for the presence of a specific HTTP message header in this request.
*
* @param name the name of header to check
* @return true if the header was set
*/
public boolean hasHeader(String name) {
return headers.has(name);
}
/**
* Gets the value of the specified header sent with this request. The name is case insensitive.
*
* <p>
* In case there are multiple headers with that name, a comma separated list of values is returned.
* </p>
*
* This method returns a null value if the request does not include any header of the specified name.
*
* @param name the name of the header to retrieve
* @return the value of the header
*/
public String header(String name) {
return headers.get(name);
}
/**
* Gets all the header names sent with this request. If the request has no header, the set will be empty.
* <p>
* Note that the names are provided as originally set on the request.
* Modifications to the provided set are safe and will not affect the request.
* </p>
*
* @return a set containing all the header names sent, which might be empty
*/
public Set<String> headerNames() {
return headers.names();
}
/**
* Gets the list of all the values sent with this request under the specified header.
* The name is case insensitive.
*
* <p>
* Some headers can be sent by clients as several headers - each with a different value - rather than sending
* the header as a comma separated list.
* </p>
*
* If the request does not include any header of the specified name, the list is empty.
* Modifications to the provided list are safe and will not affect the request.
*
* @param name the name header of the header to retrieve
* @return the list of values of the header
*/
public List<String> headers(String name) {
return headers.list(name);
}
/**
* Adds an HTTP message header to this request. The new value will be added to the list
* of existing values for that header name.
*
* @param name the name of the header to be added
* @param value the value the header will have
*/
public Request addHeader(String name, String value) {
headers.add(name, value);
return this;
}
/**
* Sets an HTTP message header on this request. The new value will replace existing values for that header name.
*
* @param name the name of the header to set
* @param value the value the header will have
*/
public Request header(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Removes the value of the specified header on this request. The name is case insensitive.
*
* <p>
* In case there are multiple headers with that name, all values are removed.
* </p>
*
* @param name the name of the header to remove
*/
public Request removeHeader(String name) {
headers.remove(name);
return this;
}
/**
* Checks if a cookie with a specific name was sent with this request.
*
* Note that changing the Cookie header of the request will not cause the cookies to change. To change the cookies,
* use {@link Request#cookie(String, String)} and {@link Request#removeCookie(String)}.
*
* @see Request#cookie(com.vtence.molecule.http.Cookie)
* @param name the name of the cookie to check
* @return true if the cookie was sent
*/
public boolean hasCookie(String name) {
return cookies.containsKey(name);
}
/**
* Retrieves the value of a cookie sent with this request under a specific name.
*
* If the cookie exists as an HTTP header then it's value is returned, otherwise a null value is returned.
*
* @param name name of the cookie to acquire
* @return the value of the cookie with that name or null
*/
public String cookieValue(String name) {
Cookie cookie = cookie(name);
return cookie != null ? cookie.value() : null;
}
/**
* Retrieves a cookie sent with this request under a specific name.
*
* If the cookie exists as an HTTP header then it is returned
* as a <code>Cookie</code> object - with the name, value, path as well as the optional domain part.
*
* @param name the name of the cookie to acquire
* @return the cookie with that name or null
*/
public Cookie cookie(String name) {
return cookies.get(name);
}
/**
* Retrieves the list of all cookies sent with this request.
*
* If the cookie exists as an HTTP header then it is returned
* as a <code>Cookie</code> object - with the name, value, path as well as the optional domain part.
*
* Note that the list is safe for modification, it will not affect the request.
*
* @return the list of cookies sent
*/
public List<Cookie> cookies() {
return new ArrayList<Cookie>(cookies.values());
}
/**
* Sets a cookie with a specific name and value. If a cookie with that name already exists,
* it is replaced by the new value.
*
* Note that this will not affect the Cookie header that has been set with the request.
*
* @param name the name of the cookie to set
* @param value the value of the cookie to set
*/
public Request cookie(String name, String value) {
return cookie(new Cookie(name, value));
}
/**
* Sets a cookie on this request. If a cookie with the same name already exists, it is replaced by the new cookie.
*
* Note that this will not affect the Cookie header that has been set with the request.
*
* @param cookie the cookie to set
*/
public Request cookie(Cookie cookie) {
cookies.put(cookie.name(), cookie);
return this;
}
/**
* Removes a cookie with a specific name from this request. If no cookie with that name exists, the operation
* does nothing.
*
* Note that this will not affect the Cookie header that has been set with the request.
*
* @param name the name of the cookie to remove
*/
public Request removeCookie(String name) {
cookies.remove(name);
return this;
}
/**
* Reads the value of the Content-Length header sent as part of this request. If the Content-Length
* header is missing, the value -1 is returned.
*
* @return the Content-Length header value as a long or -1
*/
public long contentLength() {
String value = header(CONTENT_LENGTH);
return value != null ? parseLong(value) : -1;
}
/**
* Reads the value of the Content-Type header sent as part of this request. If the Content-Type
* header is missing, a null value is returned.
*
* @return the Content-Type header or null
*/
public String contentType() {
ContentType contentType = ContentType.of(this);
return contentType != null ? contentType.mediaType() : null;
}
/**
* Gets the value of a specific parameter of this request, or null if the parameter does not exist.
*
* If the parameter has more than one value, the first one is returned.
*
* <p>Request parameters are contained in the query string or posted form data.</p>
*
* <p>
* Note that changing the body of the request will not cause the parameters to change. To change the request
* parameters, use {@link Request#addParameter(String, String)} and {@link Request#removeParameter(String)}.
* </p>
*
* @param name the name of the parameter
* @return the parameter value or null
*/
public String parameter(String name) {
List<String> values = parameters(name);
return values.isEmpty() ? null : values.get(values.size() - 1);
}
/**
* Gets the list of values of a specific parameter of this request. If the parameter does not exist, the list will
* be empty. The returned list is safe for modification and will not affect the request.
*
* <p>Request parameters are contained in the query string or posted form data.</p>
*
* <p>
* Note that changing the body of the request will not cause the parameters to change. To change the request
* parameters, use {@link Request#addParameter(String, String)} and {@link Request#removeParameter(String)}.
* </p>
*
* @param name the name of the parameter
* @return the list of that parameter's values
*/
public List<String> parameters(String name) {
return parameters.containsKey(name) ? new ArrayList<String>(parameters.get(name)) : new ArrayList<String>();
}
/**
* Returns the names of all the parameters contained in this request.
* If the request has no parameter, the method returns an empty Set. The returned
* Set is safe for modification and will not affect the request.
*
* <p>
* Parameters are taken from the query or HTTP form posting.
* </p>
*
* <p>
* Note that changing the body of the request will not cause the parameters to change. To change the request
* parameters, use {@link Request#addParameter(String, String)} and {@link Request#removeParameter(String)}.
* </p>
*
* @return the set of parameter names
*/
public Set<String> parameterNames() {
return new LinkedHashSet<String>(parameters.keySet());
}
/**
* Returns a Map of all the parameters contained in this request. If the request has no parameters,
* the map will be empty. The Map is not modifiable.
*
* <p>
* Parameters are taken from the query or HTTP form posting.
* </p>
*
* <p>
* Note that changing the body of the request will not cause the parameters to change. To change the request
* parameters, use {@link Request#addParameter(String, String)} and {@link Request#removeParameter(String)}.
* </p>
*
* @return a map containing all the request parameters
*/
public Map<String, List<String>> allParameters() {
return Collections.unmodifiableMap(parameters);
}
/**
* Adds a parameter value to this request. If a parameter with the same name already exists,
* the new value is appended to this list of values for that parameter.
*
* @param name the parameter name
* @param value the parameter value
*/
public Request addParameter(String name, String value) {
if (!parameters.containsKey(name)) {
parameters.put(name, new ArrayList<String>());
}
parameters.get(name).add(value);
return this;
}
/**
* Removes a parameter from this request. This removes all values for that parameter from the request.
*
* @param name the parameter name
*/
public Request removeParameter(String name) {
parameters.remove(name);
return this;
}
@SuppressWarnings("unchecked")
public <T> T attribute(Object key) {
return (T) attributes.get(key);
}
public Request attribute(Object key, Object value) {
attributes.put(key, value);
return this;
}
public Set<Object> attributeNames() {
return new HashSet<Object>(attributes.keySet());
}
public Object removeAttribute(Object key) {
return attributes.remove(key);
}
public Map<Object, Object> attributes() {
return Collections.unmodifiableMap(attributes);
}
public Locale locale() {
List<Locale> locales = locales();
return locales.isEmpty() ? null : locales.get(0);
}
public List<Locale> locales() {
return AcceptLanguage.of(this).locales();
}
} |
package com.exedio.cope.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.exedio.cope.Model;
/**
* A filter for starting/closing cope transactions.
*
* In order to use it, you have to deploy the filter in your <tt>web.xml</tt>,
* providing the name of the cope model via an init-parameter.
* Typically, your <tt>web.xml</tt> would contain a snippet like this:
* <pre>
* <filter>
* <filter-name>TransactionFilter</filter-name>
* <filter-class>com.exedio.cope.util.TransactionFilter</filter-class>
* <init-param>
* <param-name>model</param-name>
* <param-value>{@link com.exedio.cope.Model com.bigbusiness.shop.Main#model}</param-value>
* </init-param>
* </filter>
* <filter-mapping>
* <filter-name>TransactionFilter</filter-name>
* <url-pattern>*.do</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping>
* </pre>
*
* @author Stephan Frisch, exedio GmbH
*/
public final class TransactionFilter implements Filter
{
private Model model;
private String transactionName = getClass().getName();
public void init(FilterConfig config) throws ServletException
{
model = ServletUtil.getModel(config);
final String transactionNameParameter = config.getInitParameter("transactionName");
if(transactionNameParameter!=null)
transactionName = transactionNameParameter;
}
public void doFilter(
final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws IOException, ServletException
{
try
{
model.startTransaction(transactionName);
chain.doFilter(request, response);
model.commit();
}
catch(Exception e)
{
model.rollback();
}
finally
{
model.rollbackIfNotCommitted();
}
}
public void destroy()
{
// empty implementation
}
} |
package net.wurstclient.features.mods;
import net.wurstclient.compatibility.WMinecraft;
import net.wurstclient.events.listeners.UpdateListener;
@Mod.Info(description = "Automatically swims like a dolphin.",
name = "Dolphin",
tags = "AutoSwim, auto swim",
help = "Mods/Dolphin")
@Mod.Bypasses
public final class DolphinMod extends Mod implements UpdateListener
{
@Override
public void onEnable()
{
wurst.events.add(UpdateListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(UpdateListener.class, this);
}
@Override
public void onUpdate()
{
if(WMinecraft.getPlayer().isInWater()
&& !mc.gameSettings.keyBindSneak.pressed)
WMinecraft.getPlayer().motionY += 0.04;
}
} |
package org.nschmidt.ldparteditor.text;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import org.nschmidt.ldparteditor.data.BFC;
import org.nschmidt.ldparteditor.data.DatFile;
import org.nschmidt.ldparteditor.data.GColour;
import org.nschmidt.ldparteditor.data.GData;
import org.nschmidt.ldparteditor.data.GData1;
import org.nschmidt.ldparteditor.data.GData2;
import org.nschmidt.ldparteditor.data.GData3;
import org.nschmidt.ldparteditor.data.GData4;
import org.nschmidt.ldparteditor.data.GData5;
import org.nschmidt.ldparteditor.data.GDataBFC;
import org.nschmidt.ldparteditor.data.GDataCSG;
import org.nschmidt.ldparteditor.data.GDataTEX;
import org.nschmidt.ldparteditor.data.GTexture;
import org.nschmidt.ldparteditor.data.TexMeta;
import org.nschmidt.ldparteditor.data.TexType;
import org.nschmidt.ldparteditor.data.Vertex;
import org.nschmidt.ldparteditor.data.colour.GCDithered;
import org.nschmidt.ldparteditor.enums.Threshold;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.workbench.WorkbenchManager;
/**
* @author nils
*
*/
public enum TexMapParser {
INSTANCE;
private static final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
public static GDataTEX parseGeometry(String line, int depth, float r, float g, float b, float a, GData1 gData1, Matrix4f pMatrix, Set<String> alreadyParsed, DatFile datFile) {
String tline = line.replaceAll("0\\s+\\Q!:\\E\\s+", ""); //$NON-NLS-1$ //$NON-NLS-2$
GData data = parseLine(tline, depth, r, g, b, a, gData1, pMatrix, alreadyParsed, datFile);
return new GDataTEX(data, line, TexMeta.GEOMETRY, null);
}
public static GDataTEX parseTEXMAP(String[] data_segments, String line, GData1 parent, DatFile datFile) {
int segs = data_segments.length;
if (segs == 3) {
if (data_segments[2].equals("END")) { //$NON-NLS-1$
return new GDataTEX(null, line, TexMeta.END, null);
} else if (data_segments[2].equals("FALLBACK")) { //$NON-NLS-1$
return new GDataTEX(null, line, TexMeta.FALLBACK, null);
}
} else if (segs > 3) {
Vector4f v1 = new Vector4f();
Vector4f v2 = new Vector4f();
Vector4f v3 = new Vector4f();
float a = 0f;
float b = 0f;
TexMeta meta = data_segments[2].equals("START") ? TexMeta.START : data_segments[2].equals("NEXT") ? TexMeta.NEXT : null; //$NON-NLS-1$ //$NON-NLS-2$
if (meta != null && data_segments[3].equals("PLANAR") || data_segments[3].equals("CYLINDRICAL") || data_segments[3].equals("SPHERICAL")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (segs > 13) {
String texture = ""; //$NON-NLS-1$
String glossmap = null;
TexType type;
try {
v1.setX(Float.parseFloat(data_segments[4]) * 1000f);
v1.setY(Float.parseFloat(data_segments[5]) * 1000f);
v1.setZ(Float.parseFloat(data_segments[6]) * 1000f);
v1.setW(1f);
v2.setX(Float.parseFloat(data_segments[7]) * 1000f);
v2.setY(Float.parseFloat(data_segments[8]) * 1000f);
v2.setZ(Float.parseFloat(data_segments[9]) * 1000f);
v2.setW(1f);
v3.setX(Float.parseFloat(data_segments[10]) * 1000f);
v3.setY(Float.parseFloat(data_segments[11]) * 1000f);
v3.setZ(Float.parseFloat(data_segments[12]) * 1000f);
v3.setW(1f);
} catch (Exception e) {
return null;
}
Matrix4f.transform(parent.getProductMatrix(), v1, v1);
Matrix4f.transform(parent.getProductMatrix(), v2, v2);
Matrix4f.transform(parent.getProductMatrix(), v3, v3);
StringBuilder tex = new StringBuilder();
StringBuilder gloss = new StringBuilder();
final int len = line.length();
final int target;
boolean whitespace1 = false;
boolean whitespace2 = false;
if (data_segments[3].equals("PLANAR")) { //$NON-NLS-1$
type = TexType.PLANAR;
target = 14;
} else if (data_segments[3].equals("CYLINDRICAL")) { //$NON-NLS-1$
if (segs > 14) {
try {
a = (float) (Float.parseFloat(data_segments[13]) / 360f * Math.PI);
if (a <= 0f || a > Math.PI * 2f)
return null;
} catch (Exception e) {
return null;
}
} else {
return null;
}
type = TexType.CYLINDRICAL;
target = 15;
} else {
if (segs > 15) {
try {
a = (float) (Float.parseFloat(data_segments[13]) / 360f * Math.PI);
if (a <= 0f || a > Math.PI * 2f)
return null;
b = (float) (Float.parseFloat(data_segments[14]) / 360f * Math.PI);
if (b <= 0f || b > Math.PI * 2f)
return null;
} catch (Exception e) {
return null;
}
} else {
return null;
}
type = TexType.SPHERICAL;
target = 16;
}
int mode = 0;
int counter = 0;
for (int i = 0; i < len; i++) {
String sub = line.substring(i, i + 1);
switch (mode) {
case 0: // Parse initial whitespace
if (sub.matches("\\S")) { //$NON-NLS-1$
mode = 1;
}
case 1: // Parse non-whitespace (first letter)
if (sub.matches("\\S")) { //$NON-NLS-1$
counter++;
if (counter == target) {
if (sub.equals("\"")) { //$NON-NLS-1$
mode = 4;
sub = ""; //$NON-NLS-1$
} else {
mode = 3;
}
} else {
mode = 2;
}
}
break;
case 2: // Parse non-whitespace (rest)
if (sub.matches("\\s")) { //$NON-NLS-1$
mode = 1;
}
break;
}
switch (mode) {
case 3: // Parse texture till whitespace
if (sub.matches("\\S")) { //$NON-NLS-1$
tex.append(sub);
} else {
whitespace1 = true;
mode = 5;
}
break;
case 4: // Parse texture till "
if (sub.equals("\"")) { //$NON-NLS-1$
mode = 5;
} else {
tex.append(sub);
}
break;
case 5: // Additional whitespace
if (sub.matches("\\S")) { //$NON-NLS-1$
if (whitespace1)
mode = 6;
} else {
whitespace1 = true;
break;
}
case 6: // GLOSSMAP
if (sub.equals("G"))mode = 7; //$NON-NLS-1$
break;
case 7: // GLOSSMAP
if (sub.equals("L"))mode = 8; //$NON-NLS-1$
break;
case 8: // GLOSSMAP
if (sub.equals("O"))mode = 9; //$NON-NLS-1$
break;
case 9: // GLOSSMAP
if (sub.equals("S"))mode = 10; //$NON-NLS-1$
break;
case 10: // GLOSSMAP
if (sub.equals("S"))mode = 11; //$NON-NLS-1$
break;
case 11: // GLOSSMAP
if (sub.equals("M"))mode = 12; //$NON-NLS-1$
break;
case 12: // GLOSSMAP
if (sub.equals("A"))mode = 13; //$NON-NLS-1$
break;
case 13: // GLOSSMAP
if (sub.equals("P"))mode = 14; //$NON-NLS-1$
break;
case 14: // Additional whitespace between GLOSSMAP and
// glossmap-path
if (sub.matches("\\S")) { //$NON-NLS-1$
if (whitespace2)
mode = 15;
} else {
whitespace2 = true;
}
break;
}
switch (mode) {
case 15:
if (sub.matches("\\S")) { //$NON-NLS-1$
if (sub.equals("\"")) { //$NON-NLS-1$
mode = 17;
sub = ""; //$NON-NLS-1$
} else {
mode = 16;
}
}
break;
}
switch (mode) {
case 16: // Parse texture till whitespace
if (sub.matches("\\S")) { //$NON-NLS-1$
gloss.append(sub);
} else {
mode = 18;
}
break;
case 17: // Parse texture till "
if (sub.equals("\"")) { //$NON-NLS-1$
mode = 18;
} else {
gloss.append(sub);
}
break;
}
}
texture = tex.toString();
glossmap = gloss.toString();
if (glossmap.isEmpty())
glossmap = null;
return new GDataTEX(null, line, meta, new GTexture(type, texture, glossmap, 1, new Vector3f(v1.x, v1.y, v1.z), new Vector3f(v2.x, v2.y, v2.z), new Vector3f(v3.x, v3.y, v3.z), a, b));
}
}
}
return null;
}
public static GData parseLine(String line, int depth, float r, float g, float b, float a, GData1 gData1, Matrix4f pMatrix, Set<String> alreadyParsed, DatFile df) {
final String[] data_segments = WHITESPACE.split(line.trim());
return parseLine(data_segments, line, depth, r, g, b, a, gData1, pMatrix, alreadyParsed, df);
}
// What follows now is a very minimalistic DAT file parser (<500LOC)
private static GColour cValue = new GColour();
private static final Vector3f start = new Vector3f();
private static final Vector3f end = new Vector3f();
private static final Vector3f vertexA = new Vector3f();
private static final Vector3f vertexB = new Vector3f();
private static final Vector3f vertexC = new Vector3f();
private static final Vector3f vertexD = new Vector3f();
private static final Vector3f controlI = new Vector3f();
private static final Vector3f controlII = new Vector3f();
public static GData parseLine(String[] data_segments, String line, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) {
// Get the linetype
int linetype = 0;
char c;
if (!(data_segments.length > 0 && data_segments[0].length() == 1 && Character.isDigit(c = data_segments[0].charAt(0)))) {
return null;
}
linetype = Character.getNumericValue(c);
// Parse the line according to its type
switch (linetype) {
case 0:
return parse_Comment(line, data_segments, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile);
case 1:
return parse_Reference(data_segments, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile);
case 2:
return parse_Line(data_segments, r, g, b, a, parent);
case 3:
return parse_Triangle(data_segments, r, g, b, a, parent);
case 4:
return parse_Quad(data_segments, r, g, b, a, parent);
case 5:
return parse_Condline(data_segments, r, g, b, a, parent);
}
return null;
}
private static GColour validateColour(String arg, float r, float g, float b, float a) {
int colourValue;
try {
colourValue = Integer.parseInt(arg);
switch (colourValue) {
case 16:
cValue.set(16, r, g, b, a);
break;
case 24:
cValue.set(24, View.line_Colour_r[0], View.line_Colour_g[0], View.line_Colour_b[0], 1f);
break;
default:
if (View.hasLDConfigColour(colourValue)) {
GColour colour = View.getLDConfigColour(colourValue);
cValue.set(colour);
} else {
int A = colourValue - 256 >> 4;
int B = colourValue - 256 & 0x0F;
if (View.hasLDConfigColour(A) && View.hasLDConfigColour(B)) {
GColour colourA = View.getLDConfigColour(A);
GColour colourB = View.getLDConfigColour(B);
GColour ditheredColour = new GColour(
colourValue,
(colourA.getR() + colourB.getR()) / 2f,
(colourA.getG() + colourB.getG()) / 2f,
(colourA.getB() + colourB.getB()) / 2f,
1f, new GCDithered());
cValue.set(ditheredColour);
break;
}
return null;
}
break;
}
} catch (NumberFormatException nfe) {
if (arg.length() == 9 && arg.substring(0, 3).equals("0x2")) { //$NON-NLS-1$
cValue.setA(1f);
try {
cValue.setR(Integer.parseInt(arg.substring(3, 5), 16) / 255f);
cValue.setG(Integer.parseInt(arg.substring(5, 7), 16) / 255f);
cValue.setB(Integer.parseInt(arg.substring(7, 9), 16) / 255f);
} catch (NumberFormatException nfe2) {
return null;
}
cValue.setColourNumber(-1);
cValue.setType(null);
} else {
return null;
}
}
return cValue;
}
private static GData parse_Comment(String line, String[] data_segments, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) {
line = WHITESPACE.matcher(line).replaceAll(" ").trim(); //$NON-NLS-1$
if (line.startsWith("0 !: ")) { //$NON-NLS-1$
GData newLPEmetaTag = TexMapParser.parseGeometry(line, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile);
return newLPEmetaTag;
} else if (line.startsWith("0 !TEXMAP ")) { //$NON-NLS-1$
GData newLPEmetaTag = TexMapParser.parseTEXMAP(data_segments, line, parent, datFile);
return newLPEmetaTag;
} else if (line.startsWith("0 BFC ")) { //$NON-NLS-1$
if (line.startsWith("INVERTNEXT", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.INVERTNEXT);
} else if (line.startsWith("CERTIFY CCW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CCW_CLIP);
} else if (line.startsWith("CERTIFY CW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CW_CLIP);
} else if (line.startsWith("CERTIFY", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CCW_CLIP);
} else if (line.startsWith("NOCERTIFY", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.NOCERTIFY);
} else if (line.startsWith("CCW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CCW);
} else if (line.startsWith("CW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CW);
} else if (line.startsWith("NOCLIP", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.NOCLIP);
} else if (line.startsWith("CLIP CCW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CCW_CLIP);
} else if (line.startsWith("CLIP CW", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CW_CLIP);
} else if (line.startsWith("CCW CLIP", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CCW_CLIP);
} else if (line.startsWith("CW CLIP", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CW_CLIP);
} else if (line.startsWith("CLIP", 6)) { //$NON-NLS-1$
return new GDataBFC(BFC.CLIP);
} else {
return null;
}
} else {
return null;
}
}
private static GData parse_Reference(String[] data_segments, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) {
if (data_segments.length < 15) {
return null;
} else {
GColour colour = validateColour(data_segments[1], r, g, b, a);
if (colour == null)
return null;
Matrix4f tMatrix = new Matrix4f();
float det = 0;
try {
tMatrix.m30 = Float.parseFloat(data_segments[2]) * 1000f;
tMatrix.m31 = Float.parseFloat(data_segments[3]) * 1000f;
tMatrix.m32 = Float.parseFloat(data_segments[4]) * 1000f;
tMatrix.m00 = Float.parseFloat(data_segments[5]);
tMatrix.m10 = Float.parseFloat(data_segments[6]);
tMatrix.m20 = Float.parseFloat(data_segments[7]);
tMatrix.m01 = Float.parseFloat(data_segments[8]);
tMatrix.m11 = Float.parseFloat(data_segments[9]);
tMatrix.m21 = Float.parseFloat(data_segments[10]);
tMatrix.m02 = Float.parseFloat(data_segments[11]);
tMatrix.m12 = Float.parseFloat(data_segments[12]);
tMatrix.m22 = Float.parseFloat(data_segments[13]);
} catch (NumberFormatException nfe) {
return null;
}
tMatrix.m33 = 1f;
det = tMatrix.determinant();
if (Math.abs(det) < Threshold.singularity_determinant)
return null;
// [WARNING] Check file existance
boolean fileExists = true;
StringBuilder sb = new StringBuilder();
for (int s = 14; s < data_segments.length - 1; s++) {
sb.append(data_segments[s]);
sb.append(" "); //$NON-NLS-1$
}
sb.append(data_segments[data_segments.length - 1]);
String shortFilename = sb.toString();
shortFilename = shortFilename.toLowerCase(Locale.ENGLISH);
try {
shortFilename = shortFilename.replaceAll("s\\\\", "S" + File.separator).replaceAll("\\\\", File.separator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} catch (Exception e) {
// Workaround for windows OS / JVM BUG
shortFilename = shortFilename.replace("s\\\\", "S" + File.separator).replace("\\\\", File.separator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (alreadyParsed.contains(shortFilename)) {
if (!View.DUMMY_REFERENCE.equals(parent))
parent.firstRef.setRecursive(true);
return null;
} else {
alreadyParsed.add(shortFilename);
}
String shortFilename2 = shortFilename.startsWith("S" + File.separator) ? "s" + shortFilename.substring(1) : shortFilename; //$NON-NLS-1$ //$NON-NLS-2$
String shortFilename3 = shortFilename.startsWith("S" + File.separator) ? shortFilename.substring(2) : shortFilename; //$NON-NLS-1$
File fileToOpen = null;
String[] prefix;
if (datFile != null && !datFile.isProjectFile() && !View.DUMMY_DATFILE.equals(datFile)) {
File dff = new File(datFile.getOldName()).getParentFile();
if (dff != null && dff.exists() && dff.isDirectory()) {
prefix = new String[]{dff.getAbsolutePath(), Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()};
} else {
prefix = new String[]{Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()};
}
} else {
prefix = new String[]{Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()};
}
String[] middle = new String[]{File.separator + "PARTS", File.separator + "parts", File.separator + "P", File.separator + "p"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
String[] suffix = new String[]{File.separator + shortFilename, File.separator + shortFilename2, File.separator + shortFilename3};
for (int a1 = 0; a1 < prefix.length; a1++) {
String s1 = prefix[a1];
for (int a2 = 0; a2 < middle.length; a2++) {
String s2 = middle[a2];
for (int a3 = 0; a3 < suffix.length; a3++) {
String s3 = suffix[a3];
File f = new File(s1 + s2 + s3);
fileExists = f.exists() && f.isFile();
if (fileExists) {
fileToOpen = f;
break;
}
}
if (fileExists) break;
}
if (fileExists) break;
}
ArrayList<String> lines = null;
String absoluteFilename = null;
// MARK Virtual file check for project files...
boolean isVirtual = false;
for (DatFile df : Project.getUnsavedFiles()) {
String fn = df.getNewName();
for (int a1 = 0; a1 < prefix.length; a1++) {
String s1 = prefix[a1];
for (int a2 = 0; a2 < middle.length; a2++) {
String s2 = middle[a2];
for (int a3 = 0; a3 < suffix.length; a3++) {
String s3 = suffix[a3];
if (fn.equals(s1 + s2 + s3)) {
lines = new ArrayList<String>(4096);
lines.addAll(Arrays.asList(df.getText().split(StringHelper.getLineDelimiter())));
absoluteFilename = fn;
isVirtual = true;
break;
}
}
if (isVirtual) break;
}
if (isVirtual) break;
}
if (isVirtual) break;
}
if (isVirtual) {
Matrix4f destMatrix = new Matrix4f();
Matrix4f.mul(productMatrix, tMatrix, destMatrix);
GDataCSG.forceRecompile();
final GData1 result = new GData1(colour.getColourNumber(), colour.getR(), colour.getG(), colour.getB(), colour.getA(), tMatrix, lines, absoluteFilename, sb.toString(), depth, det < 0,
destMatrix, parent.firstRef, alreadyParsed, parent, datFile);
if (result != null && result.firstRef.isRecursive()) {
return null;
}
alreadyParsed.remove(shortFilename);
return result;
} else if (!fileExists) {
return null;
} else {
absoluteFilename = fileToOpen.getAbsolutePath();
UTF8BufferedReader reader;
String line = null;
lines = new ArrayList<String>(4096);
try {
reader = new UTF8BufferedReader(absoluteFilename);
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
lines.add(line);
}
reader.close();
} catch (FileNotFoundException e1) {
return null;
} catch (LDParsingException e1) {
return null;
} catch (UnsupportedEncodingException e1) {
return null;
}
Matrix4f destMatrix = new Matrix4f();
Matrix4f.mul(productMatrix, tMatrix, destMatrix);
GDataCSG.forceRecompile();
final GData1 result = new GData1(colour.getColourNumber(), colour.getR(), colour.getG(), colour.getB(), colour.getA(), tMatrix, lines, absoluteFilename, sb.toString(), depth, det < 0,
destMatrix, parent.firstRef, alreadyParsed, parent, datFile);
alreadyParsed.remove(shortFilename);
if (result != null && result.firstRef.isRecursive()) {
return null;
}
return result;
}
}
}
private static GData parse_Line(String[] data_segments, float r, float g, float b, float a, GData1 parent) {
if (data_segments.length != 8) {
return null;
} else {
GColour colour = validateColour(data_segments[1], r, g, b, a);
if (colour == null)
return null;
try {
start.setX(Float.parseFloat(data_segments[2]));
start.setY(Float.parseFloat(data_segments[3]));
start.setZ(Float.parseFloat(data_segments[4]));
end.setX(Float.parseFloat(data_segments[5]));
end.setY(Float.parseFloat(data_segments[6]));
end.setZ(Float.parseFloat(data_segments[7]));
} catch (NumberFormatException nfe) {
return null;
}
if (Vector3f.sub(start, end, null).length() < Threshold.identical_vertex_distance.floatValue()) {
return null;
}
return new GData2(new Vertex(start.x * 1000f, start.y * 1000f, start.z * 1000f, false), new Vertex(end.x * 1000f, end.y * 1000f, end.z * 1000f, false), colour, parent);
}
}
private static GData parse_Triangle(String[] data_segments, float r, float g, float b, float a, GData1 parent) {
if (data_segments.length != 11) {
return null;
} else {
GColour colour = validateColour(data_segments[1], r, g, b, a);
if (colour == null)
return null;
try {
vertexA.setX(Float.parseFloat(data_segments[2]));
vertexA.setY(Float.parseFloat(data_segments[3]));
vertexA.setZ(Float.parseFloat(data_segments[4]));
vertexB.setX(Float.parseFloat(data_segments[5]));
vertexB.setY(Float.parseFloat(data_segments[6]));
vertexB.setZ(Float.parseFloat(data_segments[7]));
vertexC.setX(Float.parseFloat(data_segments[8]));
vertexC.setY(Float.parseFloat(data_segments[9]));
} catch (NumberFormatException nfe) {
return null;
}
try {
vertexC.setZ(Float.parseFloat(data_segments[10]));
} catch (NumberFormatException nfe) {
return null;
}
return new GData3(new Vertex(vertexA.x * 1000f, vertexA.y * 1000f, vertexA.z * 1000f, false), new Vertex(vertexB.x * 1000f, vertexB.y * 1000f, vertexB.z * 1000f, false), new Vertex(vertexC.x * 1000f,
vertexC.y * 1000f, vertexC.z * 1000f, false), parent, colour);
}
}
private static GData parse_Quad(String[] data_segments, float r, float g, float b, float a, GData1 parent) {
if (data_segments.length != 14) {
return null;
} else {
GColour colour = validateColour(data_segments[1], r, g, b, a);
if (colour == null)
return null;
try {
vertexA.setX(Float.parseFloat(data_segments[2]));
vertexA.setY(Float.parseFloat(data_segments[3]));
vertexA.setZ(Float.parseFloat(data_segments[4]));
vertexB.setX(Float.parseFloat(data_segments[5]));
vertexB.setY(Float.parseFloat(data_segments[6]));
vertexB.setZ(Float.parseFloat(data_segments[7]));
vertexC.setX(Float.parseFloat(data_segments[8]));
vertexC.setY(Float.parseFloat(data_segments[9]));
vertexC.setZ(Float.parseFloat(data_segments[10]));
vertexD.setX(Float.parseFloat(data_segments[11]));
vertexD.setY(Float.parseFloat(data_segments[12]));
vertexD.setZ(Float.parseFloat(data_segments[13]));
} catch (NumberFormatException nfe) {
return null;
}
return new GData4(new Vertex(vertexA.x * 1000f, vertexA.y * 1000f, vertexA.z * 1000f, false), new Vertex(vertexB.x * 1000f, vertexB.y * 1000f, vertexB.z * 1000f, false), new Vertex(vertexC.x * 1000f,
vertexC.y * 1000f, vertexC.z * 1000f, false), new Vertex(vertexD.x * 1000f, vertexD.y * 1000f, vertexD.z * 1000f, false), parent, colour);
}
}
private static GData parse_Condline(String[] data_segments, float r, float g, float b, float a, GData1 parent) {
if (data_segments.length != 14) {
return null;
} else {
GColour colour = validateColour(data_segments[1], r, g, b, a);
if (colour == null)
return null;
try {
start.setX(Float.parseFloat(data_segments[2]));
start.setY(Float.parseFloat(data_segments[3]));
start.setZ(Float.parseFloat(data_segments[4]));
end.setX(Float.parseFloat(data_segments[5]));
end.setY(Float.parseFloat(data_segments[6]));
end.setZ(Float.parseFloat(data_segments[7]));
controlI.setX(Float.parseFloat(data_segments[8]));
controlI.setY(Float.parseFloat(data_segments[9]));
controlI.setZ(Float.parseFloat(data_segments[10]));
controlII.setX(Float.parseFloat(data_segments[11]));
controlII.setY(Float.parseFloat(data_segments[12]));
controlII.setZ(Float.parseFloat(data_segments[13]));
} catch (NumberFormatException nfe) {
return null;
}
final float epsilon = Threshold.identical_vertex_distance.floatValue();
if (Vector3f.sub(start, end, null).length() < epsilon || Vector3f.sub(controlI, controlII, null).length() < epsilon) {
return null;
}
return new GData5(new Vertex(start.x * 1000f, start.y * 1000f, start.z * 1000f, false), new Vertex(end.x * 1000f, end.y * 1000f, end.z * 1000f, false), new Vertex(controlI.x * 1000f,
controlI.y * 1000f, controlI.z * 1000f, false), new Vertex(controlII.x * 1000f, controlII.y * 1000f, controlII.z * 1000f, false), colour, parent);
}
}
} |
package com.xqbase.coyote.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Conf {
public static boolean DEBUG = false;
private static String rootDir = null, confDir = null, logDir = null;
static {
for (String argument : ManagementFactory.
getRuntimeMXBean().getInputArguments()) {
if (argument.startsWith("-agentlib:jdwp")) {
DEBUG = true;
break;
}
}
Properties p = load("Conf");
confDir = p.getProperty("conf_dir");
logDir = p.getProperty("log_dir");
}
private static void load(Properties p, String path) {
try (FileInputStream in = new FileInputStream(path)) {
p.load(in);
} catch (FileNotFoundException e) {
// Ignored
} catch (IOException e) {
Log.w(e.getMessage());
}
}
private static String getConfPath(String name, String confDir_) {
return confDir_ == null ? getAbsolutePath("conf/" + name + ".properties") :
(confDir_.endsWith("/") ? confDir_ : confDir_ + "/") +
name + ".properties";
}
private static Class<?> getParentClass() {
for (StackTraceElement ste : new Throwable().getStackTrace()) {
String className = ste.getClassName();
if (!className.equals(Conf.class.getName())) {
try {
return Class.forName(className);
} catch (ReflectiveOperationException e) {
Log.e(e);
return Conf.class;
}
}
}
return Conf.class;
}
public static synchronized void chdir(String path) {
if (path != null) {
rootDir = new File(getAbsolutePath(path)).getAbsolutePath();
}
}
public static synchronized String getAbsolutePath(String path) {
try {
if (rootDir == null) {
Class<?> parentClass = getParentClass();
String classFile = parentClass.getName().replace('.', '/') + ".class";
URL url = parentClass.getResource("/" + classFile);
if (url == null) {
return null;
}
if (url.getProtocol().equals("jar")) {
rootDir = url.getPath();
int i = rootDir.lastIndexOf('!');
if (i >= 0) {
rootDir = rootDir.substring(0, i);
}
rootDir = new File(new URL(rootDir).toURI()).getParent();
} else {
rootDir = new File(url.toURI()).getPath();
rootDir = rootDir.substring(0, rootDir.length() - classFile.length());
if (rootDir.endsWith(File.separator)) {
rootDir = rootDir.substring(0, rootDir.length() - 1);
}
}
rootDir = new File(rootDir).getParent();
}
return new File(rootDir + File.separator + path).getCanonicalPath();
} catch (IOException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static Logger openLogger(String name, int limit, int count) {
Logger logger = Logger.getAnonymousLogger();
logger.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
if (DEBUG) {
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
logger.addHandler(handler);
}
FileHandler handler;
try {
String logDir_ = logDir == null ? getAbsolutePath("logs") : logDir;
new File(logDir_).mkdirs();
String pattern = (logDir_.endsWith("/") ? logDir_ : logDir_ + "/") +
name + "%g.log";
handler = new FileHandler(pattern, limit, count, true);
} catch (IOException e) {
throw new RuntimeException(e);
}
handler.setFormatter(new SimpleFormatter());
handler.setLevel(Level.ALL);
logger.addHandler(handler);
return logger;
}
public static void closeLogger(Logger logger) {
for (Handler handler : logger.getHandlers()) {
logger.removeHandler(handler);
handler.close();
}
}
public static Properties load(String name) {
Properties p = new Properties();
InputStream in = getParentClass().getResourceAsStream("/" + name + ".properties");
if (in != null) {
try {
p.load(in);
} catch (IOException e) {
Log.w(e.getMessage());
}
}
load(p, getConfPath(name, null));
if (confDir != null) {
load(p, getConfPath(name, confDir));
}
return p;
}
} |
package org.eclipse.che.ide.workspace.perspectives.general;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.ide.api.constraints.Constraints;
import org.eclipse.che.ide.api.event.ActivePartChangedEvent;
import org.eclipse.che.ide.api.event.ActivePartChangedHandler;
import org.eclipse.che.ide.api.mvp.Presenter;
import org.eclipse.che.ide.api.parts.PartPresenter;
import org.eclipse.che.ide.api.parts.PartStack;
import org.eclipse.che.ide.api.parts.PartStackType;
import static org.eclipse.che.ide.api.parts.PartStackType.EDITING;
import org.eclipse.che.ide.api.parts.PartStackView;
import org.eclipse.che.ide.api.parts.Perspective;
import org.eclipse.che.ide.api.parts.PerspectiveView;
import org.eclipse.che.ide.api.parts.base.MaximizePartEvent;
import org.eclipse.che.ide.workspace.PartStackPresenterFactory;
import org.eclipse.che.ide.workspace.PartStackViewFactory;
import org.eclipse.che.ide.workspace.WorkBenchControllerFactory;
import org.eclipse.che.ide.workspace.WorkBenchPartController;
import org.eclipse.che.providers.DynaProvider;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.eclipse.che.ide.api.parts.PartStackType.INFORMATION;
import static org.eclipse.che.ide.api.parts.PartStackType.NAVIGATION;
import static org.eclipse.che.ide.api.parts.PartStackType.TOOLING;
import static org.eclipse.che.ide.api.parts.PartStackView.TabPosition.BELOW;
import static org.eclipse.che.ide.api.parts.PartStackView.TabPosition.LEFT;
import static org.eclipse.che.ide.api.parts.PartStackView.TabPosition.RIGHT;
/**
* The class which contains general business logic for all perspectives.
*
* @author Dmitry Shnurenko
*/
//TODO need rewrite this, remove direct dependency on PerspectiveViewImpl and other GWT Widgets
public abstract class AbstractPerspective implements Presenter, Perspective,
ActivePartChangedHandler, MaximizePartEvent.Handler,
PerspectiveView.ActionDelegate, PartStack.ActionDelegate {
/** The default size for the part. */
private static final double DEFAULT_PART_SIZE = 260;
/** The minimum allowable size for the part. */
private static final int MIN_PART_SIZE = 100;
protected final Map<PartStackType, PartStack> partStacks;
protected final PerspectiveViewImpl view;
private final String perspectiveId;
private final DynaProvider dynaProvider;
private final WorkBenchPartController leftPartController;
private final WorkBenchPartController rightPartController;
private final WorkBenchPartController belowPartController;
private PartPresenter activePart;
private PartPresenter activePartBeforeChangePerspective;
private PartStack maximizedPartStack;
protected AbstractPerspective(@NotNull String perspectiveId,
@NotNull PerspectiveViewImpl view,
@NotNull PartStackPresenterFactory stackPresenterFactory,
@NotNull PartStackViewFactory partViewFactory,
@NotNull WorkBenchControllerFactory controllerFactory,
@NotNull EventBus eventBus,
@NotNull DynaProvider dynaProvider) {
this.view = view;
this.perspectiveId = perspectiveId;
this.dynaProvider = dynaProvider;
this.partStacks = new HashMap<>();
view.setDelegate(this);
PartStackView navigationView = partViewFactory.create(LEFT, view.getLeftPanel());
leftPartController = controllerFactory.createController(view.getSplitPanel(), view.getNavigationPanel());
PartStack navigationPartStack = stackPresenterFactory.create(navigationView, leftPartController);
navigationPartStack.setDelegate(this);
partStacks.put(NAVIGATION, navigationPartStack);
PartStackView informationView = partViewFactory.create(BELOW, view.getBottomPanel());
belowPartController = controllerFactory.createController(view.getSplitPanel(), view.getInformationPanel());
PartStack informationStack = stackPresenterFactory.create(informationView, belowPartController);
informationStack.setDelegate(this);
partStacks.put(INFORMATION, informationStack);
PartStackView toolingView = partViewFactory.create(RIGHT, view.getRightPanel());
rightPartController = controllerFactory.createController(view.getSplitPanel(), view.getToolPanel());
PartStack toolingPartStack = stackPresenterFactory.create(toolingView, rightPartController);
toolingPartStack.setDelegate(this);
partStacks.put(TOOLING, toolingPartStack);
eventBus.addHandler(ActivePartChangedEvent.TYPE, this);
eventBus.addHandler(MaximizePartEvent.TYPE, this);
}
/**
* Opens previous active tab on current perspective.
*
* @param partStackType
* part type on which need open previous active part
*/
protected void openActivePart(@NotNull PartStackType partStackType) {
PartStack partStack = partStacks.get(partStackType);
partStack.openPreviousActivePart();
}
@Override
public void storeState() {
activePartBeforeChangePerspective = activePart;
if (activePartBeforeChangePerspective != null) {
activePartBeforeChangePerspective.storeState();
}
}
@Override
public void restoreState() {
if (activePartBeforeChangePerspective != null) {
setActivePart(activePartBeforeChangePerspective);
activePartBeforeChangePerspective.restoreState();
}
}
@Override
public void onActivePartChanged(ActivePartChangedEvent event) {
activePart = event.getActivePart();
}
/** {@inheritDoc} */
@Override
public void removePart(@NotNull PartPresenter part) {
PartStack destPartStack = findPartStackByPart(part);
if (destPartStack != null) {
destPartStack.removePart(part);
}
}
/** {@inheritDoc} */
@Override
public void hidePart(@NotNull PartPresenter part) {
PartStack destPartStack = findPartStackByPart(part);
if (destPartStack != null) {
destPartStack.minimize();
}
}
/** {@inheritDoc} */
@Override
public void maximizeCentralPartStack() {
onMaximize(partStacks.get(EDITING));
}
/** {@inheritDoc} */
@Override
public void maximizeLeftPartStack() {
onMaximize(partStacks.get(NAVIGATION));
}
/** {@inheritDoc} */
@Override
public void maximizeRightPartStack() {
onMaximize(partStacks.get(TOOLING));
}
/** {@inheritDoc} */
@Override
public void maximizeBottomPartStack() {
onMaximize(partStacks.get(INFORMATION));
}
@Override
public void onMaximizePart(MaximizePartEvent event) {
PartStack partStack = findPartStackByPart(event.getPart());
if (partStack == null) {
return;
}
if (partStack.getPartStackState() == PartStack.State.MAXIMIZED) {
onRestore(partStack);
} else {
onMaximize(partStack);
}
}
@Override
public void onMaximize(PartStack partStack) {
if (partStack == null) {
return;
}
if (partStack.equals(maximizedPartStack)) {
return;
}
maximizedPartStack = partStack;
for (PartStack ps : partStacks.values()) {
if (!ps.equals(partStack)) {
ps.collapse();
}
}
partStack.maximize();
}
@Override
public void onRestore(PartStack partStack) {
for (PartStack ps : partStacks.values()) {
ps.restore();
}
maximizedPartStack = null;
}
/** {@inheritDoc} */
@Override
public void restore() {
onRestore(null);
}
/** {@inheritDoc} */
@Override
public void setActivePart(@NotNull PartPresenter part) {
PartStack destPartStack = findPartStackByPart(part);
if (destPartStack != null) {
destPartStack.setActivePart(part);
}
}
/** {@inheritDoc} */
@Override
public void setActivePart(@NotNull PartPresenter part, @NotNull PartStackType type) {
PartStack destPartStack = partStacks.get(type);
destPartStack.setActivePart(part);
}
/**
* Find parent PartStack for given Part
*
* @param part
* part for which need find parent
* @return Parent PartStackPresenter or null if part not registered
*/
public PartStack findPartStackByPart(@NotNull PartPresenter part) {
for (PartStackType partStackType : PartStackType.values()) {
if (partStacks.get(partStackType).containsPart(part)) {
return partStacks.get(partStackType);
}
}
return null;
}
/** {@inheritDoc} */
@Override
public void addPart(@NotNull PartPresenter part, @NotNull PartStackType type) {
addPart(part, type, null);
}
/** {@inheritDoc} */
@Override
public void addPart(@NotNull PartPresenter part, @NotNull PartStackType type, @Nullable Constraints constraint) {
PartStack destPartStack = partStacks.get(type);
List<String> rules = part.getRules();
if (rules.isEmpty() || rules.contains(perspectiveId)) {
destPartStack.addPart(part, constraint);
return;
}
}
@Override
public void onResize(int width, int height) {
if (maximizedPartStack != null) {
maximizedPartStack.maximize();
}
}
/** {@inheritDoc} */
@Override
@Nullable
public PartStack getPartStack(@NotNull PartStackType type) {
return partStacks.get(type);
}
@Override
public JsonObject getState() {
JsonObject state = Json.createObject();
JsonObject partStacks = Json.createObject();
state.put("ACTIVE_PART", activePart.getClass().getName());
state.put("PART_STACKS", partStacks);
partStacks.put(PartStackType.INFORMATION.name(), getPartStackState(this.partStacks.get(INFORMATION), belowPartController));
partStacks.put(PartStackType.NAVIGATION.name(), getPartStackState(this.partStacks.get(NAVIGATION), leftPartController));
partStacks.put(PartStackType.TOOLING.name(), getPartStackState(this.partStacks.get(TOOLING), rightPartController));
return state;
}
private JsonObject getPartStackState(PartStack partStack, WorkBenchPartController partController) {
JsonObject state = Json.createObject();
state.put("SIZE", partController.getSize());
if (partStack.getParts().isEmpty()) {
state.put("HIDDEN", true);
} else {
if (partStack.getActivePart() != null) {
state.put("ACTIVE_PART", partStack.getActivePart().getClass().getName());
}
state.put("HIDDEN", partController.isHidden());
JsonArray parts = Json.createArray();
state.put("PARTS", parts);
int i = 0;
for (PartPresenter entry : partStack.getParts()) {
JsonObject presenterState = Json.createObject();
presenterState.put("CLASS", entry.getClass().getName());
parts.set(i++, presenterState);
}
}
return state;
}
@Override
public void loadState(@NotNull JsonObject state) {
if (state.hasKey("PART_STACKS")) {
JsonObject part_stacks = state.getObject("PART_STACKS");
for (String partStackType : part_stacks.keys()) {
JsonObject partStack = part_stacks.getObject(partStackType);
switch (PartStackType.valueOf(partStackType)) {
case INFORMATION:
restorePartController(partStacks.get(INFORMATION), belowPartController, partStack);
break;
case NAVIGATION:
restorePartController(partStacks.get(NAVIGATION), leftPartController, partStack);
break;
case TOOLING:
restorePartController(partStacks.get(TOOLING), rightPartController, partStack);
break;
}
}
}
// restore perspective's active part
if (state.hasKey("ACTIVE_PART")) {
String activePart = state.getString("ACTIVE_PART");
Provider<PartPresenter> provider = dynaProvider.getProvider(activePart);
if (provider != null) {
setActivePart(provider.get());
}
}
}
private void restorePartController(PartStack partStack, WorkBenchPartController controller, JsonObject partStackJSON) {
if (partStackJSON.hasKey("PARTS")) {
JsonArray parts = partStackJSON.get("PARTS");
for (int i = 0; i < parts.length(); i++) {
JsonObject value = parts.get(i);
if (value.hasKey("CLASS")) {
String className = value.getString("CLASS");
Provider<PartPresenter> provider = dynaProvider.getProvider(className);
if (provider != null) {
PartPresenter partPresenter = provider.get();
if (!partStack.containsPart(partPresenter)) {
partStack.addPart(partPresenter);
}
}
}
}
}
// restore part stack's active part
if (partStackJSON.hasKey("ACTIVE_PART")) {
String activePart = partStackJSON.getString("ACTIVE_PART");
Provider<PartPresenter> provider = dynaProvider.getProvider(activePart);
if (provider != null) {
partStack.setActivePart(provider.get());
}
}
//hide part stack if it has no parts
if (partStack.getParts().isEmpty()) {
controller.setHidden(true);
return;
}
if (partStackJSON.hasKey("HIDDEN") && partStackJSON.getBoolean("HIDDEN")) {
partStack.minimize();
return;
}
if (partStackJSON.hasKey("SIZE")) {
double size = partStackJSON.getNumber("SIZE");
// Size of the part must not be less 100 pixels.
if (size < MIN_PART_SIZE) {
size = DEFAULT_PART_SIZE;
}
controller.setSize(size);
}
}
} |
package no.nordicsemi.android.dfu;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import no.nordicsemi.android.dfu.exception.HexFileValidationException;
public class HexInputStream extends FilterInputStream {
private final int LINE_LENGTH = 20;
private final byte[] localBuf;
private int localPos;
private int pos;
private int size;
private int lastAddress;
private int available, bytesRead;
private int MBRsize;
/**
* Creates the HEX Input Stream. The constructor calculates the size of the BIN content which is available through {@link #sizeInBytes()}. If HEX file is invalid then the bin size is 0.
*
* @param in
* the input stream to read from
* @param trim
* if <code>true</code> the bin data will be trimmed. All data from addresses < 0x1000 will be skipped. In the Soft Device 7.0.0 it's MBR space and this HEX fragment should not be
* transmitted. However, other DFU implementations (f.e. without Soft Device) may require uploading the whole file.
* @throws HexFileValidationException
* if HEX file is invalid. F.e. there is no semicolon (':') on the beginning of each line.
* @throws IOException
* if the stream is closed or another IOException occurs.
*/
protected HexInputStream(final InputStream in, final int mbrSize) throws HexFileValidationException, IOException {
super(new BufferedInputStream(in));
this.localBuf = new byte[LINE_LENGTH];
this.localPos = LINE_LENGTH; // we are at the end of the local buffer, new one must be obtained
this.size = localBuf.length;
this.lastAddress = 0;
this.MBRsize = mbrSize;
this.available = calculateBinSize(mbrSize);
}
protected HexInputStream(final byte[] data, final int mbrSize) throws HexFileValidationException, IOException {
super(new ByteArrayInputStream(data));
this.localBuf = new byte[LINE_LENGTH];
this.localPos = LINE_LENGTH; // we are at the end of the local buffer, new one must be obtained
this.size = localBuf.length;
this.lastAddress = 0;
this.MBRsize = mbrSize;
this.available = calculateBinSize(mbrSize);
}
private int calculateBinSize(final int mbrSize) throws IOException {
int binSize = 0;
final InputStream in = this.in;
in.mark(in.available());
int b, lineSize, offset, type;
int lastBaseAddress = 0; // last Base Address, default 0
int lastAddress = 0;
try {
b = in.read();
while (true) {
checkComma(b);
lineSize = readByte(in); // reading the length of the data in this line
offset = readAddress(in);// reading the offset
type = readByte(in); // reading the line type
switch (type) {
case 0x01:
// end of file
return binSize;
case 0x04: {
// extended linear address record
/*
* The HEX file may contain jump to different addresses. The MSB of LBA (Linear Base Address) is given using the line type 4.
* We only support files where bytes are located together, no jumps are allowed. Therefore the newULBA may be only lastULBA + 1 (or any, if this is the first line of the HEX)
*/
final int newULBA = readAddress(in);
if (binSize > 0 && newULBA != (lastBaseAddress >> 16) + 1)
return binSize;
lastBaseAddress = newULBA << 16;
in.skip(2 /* check sum */);
break;
}
case 0x02: {
// extended segment address record
final int newSBA = readAddress(in) << 4;
if (binSize > 0 && (newSBA >> 16) != (lastBaseAddress >> 16) + 1)
return binSize;
lastBaseAddress = newSBA;
in.skip(2 /* check sum */);
break;
}
case 0x00:
// data type line
lastAddress = lastBaseAddress + offset;
if (lastAddress >= mbrSize) // we must skip all data from below last MBR address (default 0x1000) as those are the MBR. The Soft Device starts at the end of MBR (0x1000), the app and bootloader farther more
binSize += lineSize;
// no break!
default:
in.skip(lineSize * 2 /* 2 hex per one byte */+ 2 /* check sum */);
break;
}
// skip end of line
while (true) {
b = in.read();
if (b != '\n' && b != '\r') {
break;
}
}
}
} finally {
in.reset();
}
}
@Override
public int available() {
return available - bytesRead;
}
/**
* Fills the buffer with next bytes from the stream.
*
* @return the size of the buffer
* @throws IOException
*/
public int readPacket(byte[] buffer) throws HexFileValidationException, IOException {
int i = 0;
while (i < buffer.length) {
if (localPos < size) {
buffer[i++] = localBuf[localPos++];
continue;
}
bytesRead += size = readLine();
if (size == 0)
break; // end of file reached
}
return i;
}
@Override
public int read() throws IOException {
throw new UnsupportedOperationException("Please, use readPacket() method instead");
}
@Override
public int read(byte[] buffer) throws IOException {
return readPacket(buffer);
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
throw new UnsupportedOperationException("Please, use readPacket() method instead");
}
/**
* Returns the total number of bytes.
*
* @return total number of bytes available
*/
public int sizeInBytes() {
return available;
}
/**
* Returns the total number of packets with given size that are needed to get all available data
*
* @param packetSize
* the maximum packet size
* @return the number of packets needed to get all the content
* @throws IOException
*/
public int sizeInPackets(final int packetSize) throws IOException {
final int sizeInBytes = sizeInBytes();
return sizeInBytes / packetSize + ((sizeInBytes % packetSize) > 0 ? 1 : 0);
}
/**
* Reads new line from the input stream. Input stream must be a HEX file. The first line is always skipped.
*
* @return the number of data bytes in the new line. 0 if end of file.
* @throws IOException
* if this stream is closed or another IOException occurs.
*/
private int readLine() throws IOException {
// end of file reached
if (pos == -1)
return 0;
final InputStream in = this.in;
// temporary value
int b = 0;
int lineSize, type, offset;
do {
// skip end of line
while (true) {
b = in.read();
pos++;
if (b != '\n' && b != '\r') {
break;
}
}
/*
* Each line starts with comma (':')
* Data is written in HEX, so each 2 ASCII letters give one byte.
* After the comma there is one byte (2 HEX signs) with line length (normally 10 -> 0x10 -> 16 bytes -> 32 HEX characters)
* After that there is a 4 byte of an address. This part may be skipped.
* There is a packet type after the address (1 byte = 2 HEX characters). 00 is the valid data. Other values can be skipped when
* converting to BIN file.
* Then goes n bytes of data followed by 1 byte (2 HEX chars) of checksum, which is also skipped in BIN file.
*/
checkComma(b); // checking the comma at the beginning
lineSize = readByte(in); // reading the length of the data in this line
pos += 2;
offset = readAddress(in);// reading the offset
pos += 4;
type = readByte(in); // reading the line type
pos += 2;
// if the line type is no longer data type (0x00), we've reached the end of the file
switch (type) {
case 0x00:
// data type
if (lastAddress + offset < MBRsize) { // skip MBR
type = -1; // some other than 0
pos += in.skip(lineSize * 2 /* 2 hex per one byte */+ 2 /* check sum */);
}
break;
case 0x01:
// end of file
pos = -1;
return 0;
case 0x02: {
// extended segment address
final int address = readAddress(in) << 4;
pos += 4;
if (bytesRead > 0 && (address >> 16) != (lastAddress >> 16) + 1)
return 0;
lastAddress = address;
pos += in.skip(2 /* check sum */);
break;
}
case 0x04: {
// extended linear address
final int address = readAddress(in);
pos += 4;
if (bytesRead > 0 && address != (lastAddress >> 16) + 1)
return 0;
lastAddress = address << 16;
pos += in.skip(2 /* check sum */);
break;
}
default:
pos += in.skip(lineSize * 2 /* 2 hex per one byte */+ 2 /* check sum */);
break;
}
} while (type != 0);
// otherwise read lineSize bytes or fill the whole buffer
for (int i = 0; i < localBuf.length && i < lineSize; ++i) {
b = readByte(in);
pos += 2;
localBuf[i] = (byte) b;
}
pos += in.skip(2); // skip the checksum
localPos = 0;
return lineSize;
}
@Override
public synchronized void reset() throws IOException {
super.reset();
pos = 0;
bytesRead = 0;
localPos = 0;
}
private void checkComma(final int comma) throws HexFileValidationException {
if (comma != ':')
throw new HexFileValidationException("Not a HEX file");
}
private int readByte(final InputStream in) throws IOException {
final int first = asciiToInt(in.read());
final int second = asciiToInt(in.read());
return first << 4 | second;
}
private int readAddress(final InputStream in) throws IOException {
return readByte(in) << 8 | readByte(in);
}
private int asciiToInt(final int ascii) {
if (ascii >= 'A')
return ascii - 0x37;
if (ascii >= '0')
return ascii - '0';
return -1;
}
} |
package cronapi.database;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.google.gson.JsonObject;
import cronapi.QueryManager;
import cronapi.RestClient;
import cronapi.Utils;
import cronapi.Var;
import cronapi.i18n.Messages;
import cronapi.rest.security.CronappSecurity;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.Type;
import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.DescriptorQueryManager;
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.eclipse.persistence.internal.jpa.jpql.HermesParser;
import org.eclipse.persistence.internal.jpa.metamodel.EntityTypeImpl;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority;
/**
* Class database manipulation, responsible for querying, inserting,
* updating and deleting database data procedurally, allowing paged
* navigation and setting page size.
*
* @author robson.ataide
* @version 1.0
* @since 2017-04-26
*/
public class DataSource implements JsonSerializable {
private String entity;
private String simpleEntity;
private Class domainClass;
private String filter;
private Var[] params;
private int pageSize;
private Page page;
private int index;
private int current;
private Pageable pageRequest;
private Object insertedElement = null;
private EntityManager customEntityManager;
private DataSourceFilter dsFilter;
private boolean multiTenant = true;
/**
* Init a datasource with a page size equals 100
*
* @param entity - full name of entitiy class like String
*/
public DataSource(String entity) {
this(entity, 100);
}
public DataSource(JsonObject query) {
this(query.get("entityFullName").getAsString(), 100);
QueryManager.checkMultiTenant(query, this);
}
/**
* Init a datasource with a page size equals 100, and custom entity manager
*
* @param entity - full name of entitiy class like String
* @param entityManager - custom entity manager
*/
public DataSource(String entity, EntityManager entityManager) {
this(entity, 100);
this.customEntityManager = entityManager;
}
/**
* Init a datasource setting a page size
*
* @param entity - full name of entitiy class like String
* @param pageSize - page size of a Pageable object retrieved from repository
*/
public DataSource(String entity, int pageSize) {
CronappDescriptorQueryManager.enableMultitenant();
this.entity = entity;
this.simpleEntity = entity.substring(entity.lastIndexOf(".") + 1);
this.pageSize = pageSize;
this.pageRequest = new PageRequest(0, pageSize);
// initialize dependencies and necessaries objects
this.instantiateRepository();
}
private EntityManager getEntityManager(Class domainClass) {
EntityManager em;
if (customEntityManager != null)
em = customEntityManager;
else
em = TransactionManager.getEntityManager(domainClass);
enableTenantToogle(em);
return em;
}
public Class getDomainClass() {
return domainClass;
}
public String getSimpleEntity() {
return simpleEntity;
}
public String getEntity() {
return entity;
}
/**
* Retrieve repository from entity
*
* @throws RuntimeException when repository not fount, entity passed not found or cast repository
*/
private void instantiateRepository() {
try {
domainClass = Class.forName(this.entity);
} catch (ClassNotFoundException cnfex) {
throw new RuntimeException(cnfex);
}
}
private List<String> parseParams(String SQL) {
final String delims = " \n\r\t.(){},+:=!";
final String quots = "\'";
String token = "";
boolean isQuoted = false;
List<String> tokens = new LinkedList<>();
for (int i = 0; i < SQL.length(); i++) {
if (quots.indexOf(SQL.charAt(i)) != -1) {
isQuoted = token.length() == 0;
}
if (delims.indexOf(SQL.charAt(i)) == -1 || isQuoted) {
token += SQL.charAt(i);
} else {
if (token.length() > 0) {
if (token.startsWith(":"))
tokens.add(token.substring(1));
token = "";
isQuoted = false;
}
if (SQL.charAt(i) == ':') {
token = ":";
}
}
}
if (token.length() > 0) {
if (token.startsWith(":"))
tokens.add(token.substring(1));
}
return tokens;
}
private void enableTenantToogle(EntityManager em) {
try {
for (EntityType type : em.getMetamodel().getEntities()) {
DescriptorQueryManager old = ((EntityTypeImpl) type).getDescriptor().getQueryManager();
ClassDescriptor desc = ((EntityTypeImpl) type).getDescriptor();
if (desc.getMultitenantPolicy() != null && !(desc.getMultitenantPolicy() instanceof CronappMultitenantPolicy)) {
desc.setMultitenantPolicy(new CronappMultitenantPolicy(desc.getMultitenantPolicy()));
}
if (CronappDescriptorQueryManager.needProxy(old)) {
desc.setQueryManager(CronappDescriptorQueryManager.build(old));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void startMultitenant(EntityManager em) {
if (!multiTenant) {
CronappDescriptorQueryManager.disableMultitenant();
}
}
private void endMultitetant() {
if (!multiTenant) {
CronappDescriptorQueryManager.enableMultitenant();
}
}
/**
* Retrieve objects from database using repository when filter is null or empty,
* if filter not null or is not empty, this method uses entityManager and create a
* jpql instruction.
*
* @return a array of Object
*/
public Object[] fetch() {
String jpql = this.filter;
Var[] params = this.params;
if (jpql == null) {
jpql = "select e from " + simpleEntity + " e";
}
boolean containsNoTenant = jpql.contains("/*notenant*/");
jpql = jpql.replace("/*notenant*/", "");
if (containsNoTenant) {
multiTenant = false;
}
if (dsFilter != null) {
dsFilter.applyTo(domainClass, jpql, params);
params = dsFilter.getAppliedParams();
jpql = dsFilter.getAppliedJpql();
}
try {
boolean namedParams = params.length > 0 && params[0].getId() != null;
List<String> parsedParams = parseParams(jpql);
int o = 0;
for (String param : parsedParams) {
jpql = jpql.replaceFirst(":" + param, ":param" + o);
o++;
}
Map<String, Var> paramsValues = null;
if (namedParams) {
paramsValues = new LinkedHashMap<>();
for (Var p : params) {
paramsValues.put(p.getId(), p);
}
}
EntityManager em = getEntityManager(domainClass);
startMultitenant(em);
AbstractSession session = (AbstractSession) ((EntityManagerImpl) em.getDelegate()).getActiveSession();
DatabaseQuery dbQuery = EJBQueryImpl.buildEJBQLDatabaseQuery("customQuery", jpql, session, (Enum) null, (Map) null, session.getDatasourcePlatform().getConversionManager().getLoader());
HermesParser parser = new HermesParser();
DatabaseQuery queryParsed = parser.buildQuery(jpql, session);
TypedQuery<?> query = new EJBQueryImpl(dbQuery, (EntityManagerImpl) em.getDelegate());
List<Class> argsTypes = queryParsed.getArgumentTypes();
List<String> argsNames = queryParsed.getArguments();
for (String name : argsNames) {
query.setParameter(name, null);
}
if (namedParams) {
for (int i = 0; i < parsedParams.size(); i++) {
String paramName = "param" + i;
String realParamName = parsedParams.get(i);
if (paramsValues != null) {
Var value = paramsValues.get(realParamName);
if (value != null) {
int idx = argsNames.indexOf(paramName);
query.setParameter(paramName, value.getObject(argsTypes.get(idx)));
}
}
}
} else {
for (int i = 0; i < parsedParams.size(); i++) {
String param = "param" + i;
Var p = null;
if (i <= params.length - 1) {
p = params[i];
}
if (p != null) {
int idx = argsNames.indexOf(param);
query.setParameter(param, p.getObject(argsTypes.get(idx)));
} else {
query.setParameter(param, null);
}
}
}
if (this.pageRequest != null) {
query.setFirstResult(this.pageRequest.getPageNumber() * this.pageRequest.getPageSize());
query.setMaxResults(this.pageRequest.getPageSize());
}
List<?> resultsInPage = query.getResultList();
this.page = new PageImpl(resultsInPage, this.pageRequest, 0);
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
enableMultiTenant();
}
// has data, moves cursor to first position
if (this.page.getNumberOfElements() > 0)
this.current = 0;
return this.page.getContent().toArray();
}
public EntityMetadata getMetadata() {
return new EntityMetadata(domainClass);
}
/**
* Create a new instance of entity and add a
* results and set current (index) for his position
*/
public void insert() {
try {
this.insertedElement = this.domainClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Object toObject(Map<?, ?> values) {
try {
Object insertedElement = this.domainClass.newInstance();
for (Object key : values.keySet()) {
Utils.updateFieldOnFiltered(insertedElement, key.toString(), values.get(key));
}
return insertedElement;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void insert(Object value) {
try {
if (value instanceof Var)
value = ((Var) value).getObject();
if (value instanceof Map) {
this.insertedElement = this.domainClass.newInstance();
Map<?, ?> values = (Map<?, ?>) value;
for (Object key : values.keySet()) {
try {
updateField(key.toString(), values.get(key));
} catch (Exception e) {
}
}
} else {
this.insertedElement = value;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Object save() {
return save(true);
}
private void processCloudFields(Object toSaveParam) {
Object toSave;
if (toSaveParam != null) {
toSave = toSaveParam;
} else if (this.insertedElement != null) {
toSave = this.insertedElement;
} else {
toSave = this.getObject();
}
if (toSave != null) {
Utils.processCloudFields(toSave);
}
}
/**
* Saves the object in the current index or a new object when has insertedElement
*/
public Object save(boolean returnCursorAfterInsert) {
try {
processCloudFields(null);
Object toSave;
Object saved;
EntityManager em = getEntityManager(domainClass);
try {
startMultitenant(em);
if (!em.getTransaction().isActive()) {
em.getTransaction().begin();
}
if (this.insertedElement != null) {
toSave = this.insertedElement;
if (returnCursorAfterInsert)
this.insertedElement = null;
em.persist(toSave);
} else
toSave = this.getObject();
saved = em.merge(toSave);
if (toSave.getClass().getAnnotation(Multitenant.class) != null) {
em.flush();
if (multiTenant) {
em.refresh(toSave);
}
}
} finally {
endMultitetant();
}
return saved;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void delete(Var[] primaryKeys) {
insert();
int i = 0;
Var[] params = new Var[primaryKeys.length];
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
String jpql = " DELETE FROM " + entity.substring(entity.lastIndexOf(".") + 1) + " WHERE ";
List<TypeKey> keys = getKeys(type);
boolean first = true;
for (TypeKey key : keys) {
if (!first) {
jpql += " AND ";
}
first = false;
jpql += "" + key.name + " = :p" + i;
params[i] = Var.valueOf("p" + i, primaryKeys[i].getObject(key.field.getType().getJavaType()));
i++;
}
execute(jpql, params);
}
/**
* Removes the object in the current index
*/
public void delete() {
EntityManager em = getEntityManager(domainClass);
try {
Object toRemove = this.getObject();
startMultitenant(em);
if (!em.getTransaction().isActive()) {
em.getTransaction().begin();
}
// returns managed instance
toRemove = em.merge(toRemove);
em.remove(toRemove);
if (!multiTenant) {
em.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
endMultitetant();
}
}
/**
* Update a field from object in the current index
*
* @param fieldName - attributte name in entity
* @param fieldValue - value that replaced or inserted in field name passed
*/
public void updateField(String fieldName, Object fieldValue) {
Utils.updateFieldOnFiltered(getObject(), fieldName, fieldValue);
}
/**
* Update fields from object in the current index
*
* @param fields - bidimensional array like fields
* sample: { {"name", "Paul"}, {"age", "21"} }
* @thows RuntimeException if a field is not accessible through a set method
*/
public void updateFields(Var... fields) {
for (Var field : fields) {
updateField(field.getId(), field.getObject());
}
}
public void filterByPk(Var[] params) {
filter(null, new PageRequest(1, 1), params);
}
public void filter(Var data, Var[] extraParams) {
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
int i = 0;
String jpql = " select e FROM " + entity.substring(entity.lastIndexOf(".") + 1) + " e WHERE ";
Vector<Var> params = new Vector<>();
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
if (i > 0) {
jpql += " AND ";
}
jpql += "e." + field.getName() + " = :p" + i;
params.add(Var.valueOf("p" + i, data.getField(field.getName()).getObject(field.getType().getJavaType())));
i++;
}
}
if (extraParams != null) {
for (Var p : extraParams) {
jpql += "e." + p.getId() + " = :p" + i;
params.add(Var.valueOf("p" + i, p.getObject()));
i++;
}
}
Var[] arr = params.toArray(new Var[params.size()]);
filter(jpql, arr);
}
public void update(Var data) {
try {
List<String> fieldsByteHeaderSignature = cronapi.Utils.getFieldsWithAnnotationByteHeaderSignature(domainClass);
LinkedList<String> fields = data.keySet();
for (String key : fields) {
if (!fieldsByteHeaderSignature.contains(key) || isFieldByteWithoutHeader(key, data.getField(key))) {
if (!key.equalsIgnoreCase(Class.class.getSimpleName())) {
try {
this.updateField(key, data.getField(key));
} catch (Exception e) {
//NoCommand
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean isFieldByteWithoutHeader(String fieldName, Object fieldValue) {
boolean result = false;
if (fieldValue instanceof Var) {
if (((Var) fieldValue).getObject() == null)
return true;
else if (cronapi.util.StorageService.isTempFileJson(((Var) fieldValue).getObject().toString()))
return true;
}
Method setMethod = Utils.findMethod(getObject(), "set" + fieldName);
if (setMethod != null) {
if (fieldValue instanceof Var) {
fieldValue = ((Var) fieldValue).getObject(setMethod.getParameterTypes()[0]);
} else {
Var tVar = Var.valueOf(fieldValue);
fieldValue = tVar.getObject(setMethod.getParameterTypes()[0]);
}
Object header = cronapi.util.StorageService.getFileBytesMetadata((byte[]) fieldValue);
result = (header == null);
}
return result;
}
/**
* Return object in current index
*
* @return Object from database in current position
*/
public Object getObject() {
if (this.insertedElement != null)
return this.insertedElement;
if (this.current < 0 || this.current > this.page.getContent().size() - 1)
return null;
return this.page.getContent().get(this.current);
}
/**
* Return field passed from object in current index
*
* @return Object value of field passed
* @thows RuntimeException if a field is not accessible through a set method
*/
public Object getObject(String fieldName) {
try {
Method getMethod = Utils.findMethod(getObject(), "get" + fieldName);
if (getMethod != null)
return getMethod.invoke(getObject());
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Moves the index for next position, in pageable case,
* looking for next page and so on
*/
public void next() {
if (this.page.getNumberOfElements() > (this.current + 1))
this.current++;
else {
if (this.page.hasNext()) {
this.pageRequest = this.page.nextPageable();
this.fetch();
this.current = 0;
} else {
this.current = -1;
}
}
}
/**
* Moves the index for next position, in pageable case,
* looking for next page and so on
*/
public void nextOnPage() {
this.current++;
}
/**
* Verify if can moves the index for next position,
* in pageable case, looking for next page and so on
*
* @return boolean true if has next, false else
*/
public boolean hasNext() {
if (this.page.getNumberOfElements() > (this.current + 1))
return true;
else {
if (this.page.hasNext()) {
return true;
} else {
return false;
}
}
}
public boolean hasData() {
return getObject() != null;
}
/**
* Moves the index for previous position, in pageable case,
* looking for next page and so on
*
* @return boolean true if has previous, false else
*/
public boolean previous() {
if (this.current - 1 >= 0) {
this.current
} else {
if (this.page.hasPrevious()) {
this.pageRequest = this.page.previousPageable();
this.fetch();
this.current = this.page.getNumberOfElements() - 1;
} else {
return false;
}
}
return true;
}
public void setCurrent(int current) {
this.current = current;
}
public int getCurrent() {
return this.current;
}
/**
* Gets a Pageable object retrieved from repository
*
* @return pageable from repository, returns null when fetched by filter
*/
public Page getPage() {
return this.page;
}
/**
* Create a new page request with size passed
*
* @param pageSize size of page request
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
this.pageRequest = new PageRequest(0, pageSize);
this.current = -1;
}
/**
* Fetch objects from database by a filter
*
* @param filter jpql instruction like a namedQuery
* @param params parameters used in jpql instruction
*/
public void filter(String filter, Var... params) {
this.filter = filter;
this.params = params;
this.pageRequest = new PageRequest(0, pageSize);
this.current = -1;
this.fetch();
}
public void setDataSourceFilter(DataSourceFilter dsFilter) {
this.dsFilter = dsFilter;
}
public void filter(String filter, PageRequest pageRequest, Var... params) {
if (filter == null) {
if (params.length > 0) {
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
int i = 0;
String jpql = "Select e from " + simpleEntity + " e where (";
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
if (i > 0) {
jpql += " and ";
}
jpql += "e." + field.getName() + " = :p" + i;
params[i].setId("p" + i);
i++;
}
}
jpql += ")";
filter = jpql;
} else {
filter = "Select e from " + simpleEntity + " e ";
}
} else {
List<String> parsedParams = parseParams(filter);
if (params.length > parsedParams.size() && domainClass != null) {
String alias = JPQLConverter.getAliasFromSql(filter);
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
int i = 0;
String filterForId = " (";
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
if (i > 0) {
filterForId += " and ";
}
filterForId += alias + "." + field.getName() + " = :id" + i;
i++;
}
}
filterForId += ")";
if (filter.toLowerCase().indexOf("where") > -1)
filterForId = " and " + filterForId;
else
filterForId = " where " + filterForId;
filter = Utils.addFilterInSQLClause(filter, filterForId);
}
}
this.params = params;
this.filter = filter;
this.pageRequest = pageRequest;
this.current = -1;
this.fetch();
}
private Class forName(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
private Object newInstance(String name) {
try {
return Class.forName(name).newInstance();
} catch (Exception e) {
return null;
}
}
private static class TypeKey {
String name;
SingularAttribute field;
}
private Set getAjustedAttributes(EntityType type) {
Set<SingularAttribute> attributes = type.getAttributes();
Set<SingularAttribute> attrs = new LinkedHashSet<SingularAttribute>();
for (int i = 0; i < type.getJavaType().getDeclaredFields().length; i++) {
for (SingularAttribute attr : attributes) {
if (attr.getName().equalsIgnoreCase(type.getJavaType().getDeclaredFields()[i].getName())) {
attrs.add(attr);
break;
}
}
;
}
return attrs;
}
private void addKeys(EntityManager em, EntityType type, String parent, List<TypeKey> keys) {
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
if (field.getType().getPersistenceType() == Type.PersistenceType.BASIC) {
TypeKey key = new TypeKey();
key.name = parent == null ? field.getName() : parent + "." + field.getName();
key.field = field;
keys.add(key);
} else {
EntityType subType = (EntityType) field.getType();
addKeys(em, subType, (parent == null ? field.getName() : parent + "." + field.getName()), keys);
}
}
}
}
private List<TypeKey> getKeys(EntityType type) {
EntityManager em = getEntityManager(domainClass);
List<TypeKey> keys = new LinkedList<>();
addKeys(em, type, null, keys);
return keys;
}
public void deleteRelation(String refId, Var[] primaryKeys, Var[] relationKeys) {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(refId);
EntityManager em = getEntityManager(domainClass);
int i = 0;
String jpql = null;
Var[] params = null;
if (relationMetadata.getAssossiationName() != null) {
params = new Var[relationKeys.length + primaryKeys.length];
jpql = " DELETE FROM " + relationMetadata.gettAssossiationSimpleName() + " WHERE ";
EntityType type = em.getMetamodel().entity(domainClass);
List<TypeKey> keys = getKeys(type);
for (TypeKey key : keys) {
if (i > 0) {
jpql += " AND ";
}
jpql += relationMetadata.getAssociationAttribute().getName() + "." + key.name + " = :p" + i;
params[i] = Var.valueOf("p" + i, primaryKeys[i].getObject(key.field.getType().getJavaType()));
i++;
}
int v = 0;
type = em.getMetamodel().entity(forName(relationMetadata.getAssossiationName()));
keys = getKeys(type);
for (TypeKey key : keys) {
if (i > 0) {
jpql += " AND ";
}
jpql += relationMetadata.getAttribute().getName() + "." + key.name + " = :p" + i;
params[i] = Var.valueOf("p" + i, relationKeys[v].getObject(key.field.getType().getJavaType()));
i++;
v++;
}
} else {
params = new Var[relationKeys.length];
jpql = " DELETE FROM " + relationMetadata.getSimpleName() + " WHERE ";
EntityType type = em.getMetamodel().entity(forName(relationMetadata.getName()));
List<TypeKey> keys = getKeys(type);
for (TypeKey key : keys) {
if (i > 0) {
jpql += " AND ";
}
jpql += "" + key.name + " = :p" + i;
params[i] = Var.valueOf("p" + i, relationKeys[i].getObject(key.field.getType().getJavaType()));
i++;
}
}
execute(jpql, params);
}
public Object insertRelation(String refId, Map<?, ?> data, Var... primaryKeys) {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(refId);
EntityManager em = getEntityManager(domainClass);
Object result = null;
try {
startMultitenant(em);
filter(null, new PageRequest(0, 100), primaryKeys);
Object insertion = null;
if (relationMetadata.getAssossiationName() != null) {
insertion = this.newInstance(relationMetadata.getAssossiationName());
Utils.updateFieldOnFiltered(insertion, relationMetadata.getAttribute().getName(),
Var.valueOf(data).getObject(forName(relationMetadata.getName())));
Utils.updateFieldOnFiltered(insertion, relationMetadata.getAssociationAttribute().getName(), getObject());
result = getObject();
} else {
insertion = Var.valueOf(data).getObject(forName(relationMetadata.getName()));
Utils.updateFieldOnFiltered(insertion, relationMetadata.getAttribute().getName(), getObject());
result = insertion;
}
processCloudFields(insertion);
if (!em.getTransaction().isActive()) {
em.getTransaction().begin();
}
em.persist(insertion);
if (!multiTenant) {
em.flush();
}
} finally {
endMultitetant();
}
return result;
}
public void resolveRelation(String refId) {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(refId);
if (relationMetadata.getAssossiationName() != null) {
try {
domainClass = Class.forName(relationMetadata.getAttribute().getJavaType().getName());
} catch (ClassNotFoundException e) {
}
} else {
try {
domainClass = Class.forName(relationMetadata.getName());
} catch (ClassNotFoundException e) {
}
}
}
public void filterByRelation(String refId, PageRequest pageRequest, Var... primaryKeys) {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(refId);
EntityManager em = getEntityManager(domainClass);
EntityType type = null;
String name = null;
String selectAttr = "";
String filterAttr = relationMetadata.getAttribute().getName();
type = em.getMetamodel().entity(domainClass);
if (relationMetadata.getAssossiationName() != null) {
name = relationMetadata.gettAssossiationSimpleName();
selectAttr = "." + relationMetadata.getAttribute().getName();
filterAttr = relationMetadata.getAssociationAttribute().getName();
try {
domainClass = Class.forName(relationMetadata.getAttribute().getJavaType().getName());
} catch (ClassNotFoundException e) {
}
} else {
name = relationMetadata.getSimpleName();
try {
domainClass = Class.forName(relationMetadata.getName());
} catch (ClassNotFoundException e) {
}
}
int i = 0;
String jpql = "Select e" + selectAttr + " from " + name + " e where ";
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
if (i > 0) {
jpql += " and ";
}
jpql += "e." + filterAttr + "." + field.getName() + " = :p" + i;
primaryKeys[i].setId("p" + i);
}
}
filter(jpql, pageRequest, primaryKeys);
}
/**
* Clean Datasource and to free up allocated memory
*/
public void clear() {
this.pageRequest = new PageRequest(0, 100);
this.current = -1;
this.page = null;
}
private Object createAndSetFieldsDomain(List<String> parsedParams, TypedQuery<?> strQuery, Var... params) {
try {
Object instanceForUpdate = this.domainClass.newInstance();
int i = 0;
for (String param : parsedParams) {
Var p = null;
if (i <= params.length - 1) {
p = params[i];
}
if (p != null) {
if (p.getId() != null) {
Utils.updateField(instanceForUpdate, p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType()));
} else {
Utils.updateField(instanceForUpdate, param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType()));
}
} else {
Utils.updateField(instanceForUpdate, param, null);
}
i++;
}
return instanceForUpdate;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Execute Query
*
* @param query - JPQL instruction for filter objects to remove
* @param params - Bidimentional array with params name and params value
*/
public void execute(String query, Var... params) {
EntityManager em = getEntityManager(domainClass);
try {
startMultitenant(em);
try {
TypedQuery<?> strQuery = em.createQuery(query, domainClass);
int i = 0;
List<String> parsedParams = parseParams(query);
if (!query.trim().startsWith("DELETE")) {
Object instanceForUpdate = createAndSetFieldsDomain(parsedParams, strQuery, params);
processCloudFields(instanceForUpdate);
for (String param : parsedParams) {
Var p = null;
if (i <= params.length - 1) {
p = params[i];
}
if (p != null) {
if (p.getId() != null) {
//strQuery.setParameter(p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType()));
strQuery.setParameter(p.getId(), Utils.getFieldValue(instanceForUpdate, p.getId()));
} else {
// strQuery.setParameter(param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType()));
strQuery.setParameter(param, Utils.getFieldValue(instanceForUpdate, parsedParams.get(i)));
}
} else {
strQuery.setParameter(param, null);
}
i++;
}
} else {
for (String param : parsedParams) {
Var p = null;
if (i <= params.length - 1) {
p = params[i];
}
if (p != null) {
if (p.getId() != null) {
strQuery.setParameter(p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType()));
} else {
strQuery.setParameter(param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType()));
}
} else {
strQuery.setParameter(param, null);
}
i++;
}
}
try {
if (!em.getTransaction().isActive()) {
em.getTransaction().begin();
}
strQuery.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} finally {
endMultitetant();
}
}
public Var getTotalElements() {
return new Var(this.page.getTotalElements());
}
@Override
public String toString() {
if (this.page != null) {
return this.page.getContent().toString();
} else {
return "[]";
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeObject(this.page.getContent());
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer)
throws IOException {
gen.writeObject(this.page.getContent());
}
public void checkRESTSecurity(String method) throws Exception {
checkRESTSecurity(domainClass, method);
}
public void checkRESTSecurity(String relationId, String method) throws Exception {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(relationId);
checkRESTSecurity(Class.forName(relationMetadata.getName()), method);
}
public String getRelationEntity(String relationId) throws Exception {
EntityMetadata metadata = getMetadata();
RelationMetadata relationMetadata = metadata.getRelations().get(relationId);
return relationMetadata.getName();
}
private void checkRESTSecurity(Class clazz, String method) throws Exception {
Annotation security = clazz.getAnnotation(CronappSecurity.class);
boolean authorized = false;
if (security instanceof CronappSecurity) {
CronappSecurity cronappSecurity = (CronappSecurity) security;
Method methodPermission = cronappSecurity.getClass().getMethod(method.toLowerCase());
if (methodPermission != null) {
String value = (String) methodPermission.invoke(cronappSecurity);
if (value == null || value.trim().isEmpty()) {
value = "authenticated";
}
String[] authorities = value.trim().split(";");
for (String role : authorities) {
if (role.equalsIgnoreCase("authenticated")) {
authorized = RestClient.getRestClient().getUser() != null;
if (authorized)
break;
}
if (role.equalsIgnoreCase("permitAll") || role.equalsIgnoreCase("public")) {
authorized = true;
break;
}
for (GrantedAuthority authority : RestClient.getRestClient().getAuthorities()) {
if (role.equalsIgnoreCase(authority.getAuthority())) {
authorized = true;
break;
}
}
if (authorized)
break;
}
}
}
if (!authorized) {
throw new RuntimeException(Messages.getString("notAllowed"));
}
}
public void disableMultiTenant() {
this.multiTenant = false;
}
public void enableMultiTenant() {
this.multiTenant = true;
}
public String getFilter() {
return this.filter;
}
public Var getIds() {
if (getObject() == null) {
return Var.VAR_NULL;
}
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
LinkedList result = new LinkedList<>();
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
result.add(getObject(field.getName()));
}
}
return Var.valueOf(result);
}
public Var getId() {
if (getObject() == null) {
return Var.VAR_NULL;
}
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
return Var.valueOf(getObject(field.getName()));
}
}
return Var.VAR_NULL;
}
public Object getObjectWithId(Var[] ids) {
EntityManager em = getEntityManager(domainClass);
EntityType type = em.getMetamodel().entity(domainClass);
Object instanceDomain = null;
try {
instanceDomain = domainClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
int i = 0;
for (Object obj : getAjustedAttributes(type)) {
SingularAttribute field = (SingularAttribute) obj;
if (field.isId()) {
Utils.updateField(instanceDomain, field.getName(), ids[i].getObject(field.getType().getJavaType()));
i++;
}
}
return instanceDomain;
}
public void validate(String jpql) {
EntityManager em = getEntityManager(domainClass);
AbstractSession session = (AbstractSession) ((EntityManagerImpl) em.getDelegate()).getActiveSession();
HermesParser parser = new HermesParser();
try {
parser.buildQuery(jpql, session);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
package org.innovateuk.ifs.testdata.builders;
import org.innovateuk.ifs.application.resource.*;
import org.innovateuk.ifs.category.domain.InnovationArea;
import org.innovateuk.ifs.category.domain.ResearchCategory;
import org.innovateuk.ifs.commons.error.ValidationMessages;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.invite.builder.ApplicationInviteResourceBuilder;
import org.innovateuk.ifs.invite.domain.ApplicationInvite;
import org.innovateuk.ifs.invite.resource.ApplicationInviteResource;
import org.innovateuk.ifs.invite.resource.ApplicationKtaInviteResource;
import org.innovateuk.ifs.invite.resource.InviteOrganisationResource;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.question.resource.QuestionSetupType;
import org.innovateuk.ifs.testdata.builders.data.ApplicationData;
import org.innovateuk.ifs.user.resource.UserResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.invite.builder.ApplicationInviteResourceBuilder.newApplicationInviteResource;
import static org.innovateuk.ifs.invite.builder.InviteOrganisationResourceBuilder.newInviteOrganisationResource;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.*;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
/**
* Generates an Application for a Competition. Additionally generates finances for each Organisation on the Application
*/
public class ApplicationDataBuilder extends BaseDataBuilder<ApplicationData, ApplicationDataBuilder> {
private static final String KTA_EMAIL = "hermen.mermen@ktn-uk.test";
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBuilder.class);
public ApplicationDataBuilder withCompetition(CompetitionResource competition) {
return with(data -> data.setCompetition(competition));
}
public ApplicationDataBuilder withBasicDetails(UserResource leadApplicant, String applicationName, String researchCategory, boolean resubmission, long organisationId, boolean enableForEOI) {
return with(data -> doAs(leadApplicant, () -> {
ApplicationResource created = applicationService.createApplicationByApplicationNameForUserIdAndCompetitionId(
applicationName, data.getCompetition().getId(), leadApplicant.getId(), organisationId).
getSuccess();
created.setResubmission(resubmission);
created.setEnableForEOI(enableForEOI);
ValidationMessages validationMessages = applicationService.saveApplicationDetails(created.getId(), created)
.getSuccess();
ResearchCategory category = researchCategoryRepository.findByName(researchCategory);
applicationResearchCategoryService.setResearchCategory(created.getId(), category.getId());
data.setLeadApplicant(leadApplicant);
data.setApplication(created);
}));
}
public ApplicationDataBuilder withInnovationArea(String innovationAreaName) {
return asLeadApplicant(data -> {
if (innovationAreaName.equals("NOT_APPLICABLE")) {
applicationInnovationAreaService.setNoInnovationAreaApplies(data.getApplication().getId());
} else if (!innovationAreaName.isEmpty()) {
InnovationArea innovationArea = innovationAreaRepository.findByName(innovationAreaName);
applicationInnovationAreaService.setInnovationArea(data.getApplication().getId(), innovationArea.getId())
.getSuccess();
}
});
}
public ApplicationDataBuilder markApplicationDetailsComplete(boolean markAsComplete) {
return markQuestionComplete(markAsComplete, APPLICATION_DETAILS);
}
public ApplicationDataBuilder markEdiComplete(boolean markAsComplete) {
return markQuestionComplete(markAsComplete, EQUALITY_DIVERSITY_INCLUSION);
}
public ApplicationDataBuilder markNorthernIrelandDeclarationComplete(boolean markAsComplete) {
return markQuestionComplete(markAsComplete, NORTHERN_IRELAND_DECLARATION);
}
public ApplicationDataBuilder markApplicationTeamComplete(boolean markAsComplete) {
return markQuestionComplete(markAsComplete, APPLICATION_TEAM);
}
public ApplicationDataBuilder markResearchCategoryComplete(boolean markAsComplete) {
return markQuestionComplete(markAsComplete, RESEARCH_CATEGORY);
}
private ApplicationDataBuilder markQuestionComplete(boolean markAsComplete, QuestionSetupType type) {
return asLeadApplicant(data -> {
if (markAsComplete && EQUALITY_DIVERSITY_INCLUSION != type) {
QuestionResource questionResource = simpleFindFirst(questionService.findByCompetition(data
.getCompetition()
.getId())
.getSuccess(),
x -> type.equals(x.getQuestionSetupType())).get();
questionStatusService.markAsCompleteNoValidate(new QuestionApplicationCompositeId(questionResource.getId(), data
.getApplication()
.getId()),
retrieveLeadApplicant(data.getApplication().getId()).getId())
.getSuccess();
}
});
}
public ApplicationDataBuilder withStartDate(LocalDate startDate) {
return asLeadApplicant(data -> doApplicationDetailsUpdate(data, application -> application.setStartDate(startDate)));
}
public ApplicationDataBuilder withDurationInMonths(long durationInMonths) {
return asLeadApplicant(data -> doApplicationDetailsUpdate(data, application ->
application.setDurationInMonths(durationInMonths)));
}
public ApplicationDataBuilder inviteCollaborator(UserResource collaborator, Organisation organisation) {
return asLeadApplicant(data -> {
ApplicationInviteResource singleInvite = doInviteCollaborator(data, organisation.getName(),
Optional.of(collaborator.getId()), collaborator.getEmail(), collaborator.getName(), Optional.empty());
doAs(systemRegistrar(), () -> acceptApplicationInviteService.acceptInvite(singleInvite.getHash(), collaborator.getId(), Optional.of(organisation.getId())));
});
}
public ApplicationDataBuilder inviteKta() {
return asLeadApplicant(data -> {
ktaInviteService.saveKtaInvite(new ApplicationKtaInviteResource(KTA_EMAIL, data.getApplication().getId())).getSuccess();
ApplicationKtaInviteResource invite = ktaInviteService.getKtaInviteByApplication(data.getApplication().getId()).getSuccess();
doAs(retrieveUserByEmail(KTA_EMAIL), () -> ktaInviteService.acceptInvite(invite.getHash()));
});
}
public ApplicationDataBuilder inviteCollaboratorNotYetRegistered(String email, String hash, String name, String organisationName) {
return asLeadApplicant(data -> doInviteCollaborator(data, organisationName, Optional.empty(), email, name, Optional.of(hash)));
}
public ApplicationDataBuilder withFinances(UnaryOperator<ApplicationFinanceDataBuilder>... builderFns) {
return withFinances(asList(builderFns));
}
public ApplicationDataBuilder withFinances(List<UnaryOperator<ApplicationFinanceDataBuilder>> builderFns) {
return with(data -> {
ApplicationFinanceDataBuilder baseFinanceBuilder = ApplicationFinanceDataBuilder.newApplicationFinanceData(serviceLocator).
withApplication(data.getApplication()).
withCompetition(data.getCompetition());
builderFns.forEach(fn -> fn.apply(baseFinanceBuilder).build());
});
}
public ApplicationDataBuilder beginApplication() {
return asLeadApplicant(data ->
applicationService.updateApplicationState(data.getApplication().getId(), ApplicationState.OPENED).
getSuccess());
}
public ApplicationDataBuilder submitApplication() {
return asLeadApplicant(data -> {
applicationService.updateApplicationState(data.getApplication().getId(), ApplicationState.SUBMITTED).
getSuccess();
applicationService.saveApplicationSubmitDateTime(data.getApplication().getId(), ZonedDateTime.now()).getSuccess();
applicationNotificationService.sendNotificationApplicationSubmitted(data.getApplication().getId()).getSuccess();
});
}
public ApplicationDataBuilder markApplicationIneligible(String ineligibleReason) {
return asCompAdmin(data -> {
IneligibleOutcomeResource reason = new IneligibleOutcomeResource(ineligibleReason);
applicationService.markAsIneligible(data.getApplication().getId(), ineligibleOutcomeMapper.mapToDomain(reason));
});
}
public ApplicationDataBuilder informApplicationIneligible() {
return asCompAdmin(data -> {
ApplicationIneligibleSendResource resource = new ApplicationIneligibleSendResource("subject", "content");
applicationNotificationService.informIneligible(data.getApplication().getId(), resource);
});
}
private ApplicationInviteResource doInviteCollaborator(ApplicationData data, String organisationName, Optional<Long> userId, String email, String name, Optional<String> hash) {
ApplicationInviteResourceBuilder baseApplicationInviteBuilder =
userId.map(id -> newApplicationInviteResource().withUsers(id)).orElse(newApplicationInviteResource());
List<Organisation> organisations = organisationRepository.findDistinctByProcessRolesUserId(data.getLeadApplicant().getId());
Organisation leadOrganisation = organisations.get(0);
List<ApplicationInviteResource> applicationInvite = baseApplicationInviteBuilder.
withApplication(data.getApplication().getId()).
withName(name).
withEmail(email).
withLeadApplicant(data.getLeadApplicant().getName()).
withLeadApplicantEmail(data.getLeadApplicant().getEmail()).
withLeadOrganisation(leadOrganisation.getName()).
withCompetitionId(data.getCompetition().getId()).
build(1);
applicationInviteService.createApplicationInvites(newInviteOrganisationResource().
withOrganisationName(organisationName).
withInviteResources(applicationInvite).
build(), Optional.of(data.getApplication().getId())).getSuccess();
List<InviteOrganisationResource> invites = applicationInviteService.getInvitesByApplication(data.getApplication().getId()).getSuccess();
InviteOrganisationResource newInvite = simpleFindFirst(invites, i -> simpleFindFirst(i.getInviteResources(), r -> r.getEmail().equals(email)).isPresent()).get();
ApplicationInviteResource usersInvite = simpleFindFirst(newInvite.getInviteResources(), r -> r.getEmail().equals(email)).get();
hash.ifPresent(h -> {
ApplicationInvite saved = applicationInviteRepository.findById(usersInvite.getId()).get();
saved.setHash(h);
applicationInviteRepository.save(saved);
usersInvite.setHash(h);
});
return usersInvite;
}
private ApplicationDataBuilder asLeadApplicant(Consumer<ApplicationData> action) {
return with(data -> doAs(data.getLeadApplicant(), () -> action.accept(data)));
}
private void doApplicationDetailsUpdate(ApplicationData data, Consumer<ApplicationResource> updateFn) {
ApplicationResource application =
applicationService.getApplicationById(data.getApplication().getId()).getSuccess();
updateFn.accept(application);
applicationService.saveApplicationDetails(application.getId(), application);
data.setApplication(application);
}
public static ApplicationDataBuilder newApplicationData(ServiceLocator serviceLocator) {
return new ApplicationDataBuilder(emptyList(), serviceLocator);
}
private ApplicationDataBuilder(List<BiConsumer<Integer, ApplicationData>> multiActions,
ServiceLocator serviceLocator) {
super(multiActions, serviceLocator);
}
@Override
protected ApplicationDataBuilder createNewBuilderWithActions(List<BiConsumer<Integer, ApplicationData>> actions) {
return new ApplicationDataBuilder(actions, serviceLocator);
}
@Override
protected ApplicationData createInitial() {
return new ApplicationData();
}
public ApplicationDataBuilder withExistingApplication(ApplicationData applicationData) {
return with(data -> {
data.setApplication(applicationData.getApplication());
data.setCompetition(applicationData.getCompetition());
data.setLeadApplicant(applicationData.getLeadApplicant());
});
}
@Override
protected void postProcess(int index, ApplicationData instance) {
super.postProcess(index, instance);
LOG.info("Created Application '{}'", instance.getApplication().getName());
}
} |
package com.vip.saturn.it.impl;
import com.vip.saturn.it.AbstractSaturnIT;
import com.vip.saturn.it.JobType;
import com.vip.saturn.it.job.LongtimeJavaJob;
import com.vip.saturn.job.internal.config.JobConfiguration;
import com.vip.saturn.job.internal.execution.ExecutionNode;
import com.vip.saturn.job.internal.sharding.ShardingNode;
import com.vip.saturn.job.internal.storage.JobNodePath;
import com.vip.saturn.job.utils.ItemUtils;
import org.junit.*;
import org.junit.runners.MethodSorters;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class FailoverIT extends AbstractSaturnIT {
@BeforeClass
public static void setUp() throws Exception {
startSaturnConsoleList(1);
}
@AfterClass
public static void tearDown() throws Exception {
stopExecutorListGracefully();
stopSaturnConsoleList();
}
@Before
public void before() {
LongtimeJavaJob.statusMap.clear();
}
@After
public void after() {
LongtimeJavaJob.statusMap.clear();
}
/**
* 1Executorfailoversharding Executor >
*/
@Test
public void test_A_JavaJob() throws Exception {
startExecutorList(3);
final int shardCount = 2;
final String jobName = "failoverITJobJava1";
failover(shardCount, jobName);
stopExecutorListGracefully();
}
/**
* 2failover Executor =
*/
@Test
public void test_B_JavaJob() throws Exception {
startExecutorList(2);
final int shardCount = 2;
final String jobName = "failoverITJobJava2";
failover(shardCount, jobName);
stopExecutorListGracefully();
}
/**
* 3failoverfailover
*/
@Test
public void test_C_JavaJob() throws Exception {
startExecutorList(2);
final int shardCount = 2;
final String jobName = "failoverITJobJava3";
failoverWithDisabled(shardCount, jobName, 2);
stopExecutorListGracefully();
}
/**
* executorjava
*/
@Test
public void test_D_disabledJavaJobStillBeAborted() throws Exception {
startExecutorList(2);
final int shardCount = 2;
final String jobName = "failoverITJobJava4";
failoverWithDisabled(shardCount, jobName, 1);
stopExecutorListGracefully();
}
private void failover(final int shardCount, final String jobName) throws Exception {
for (int i = 0; i < shardCount; i++) {
String key = jobName + "_" + i;
LongtimeJavaJob.JobStatus status = new LongtimeJavaJob.JobStatus();
status.runningCount = 0;
status.sleepSeconds = 10;
status.finished = false;
status.timeout = false;
LongtimeJavaJob.statusMap.put(key, status);
}
// 1 10S
final JobConfiguration jobConfiguration = new JobConfiguration(jobName);
jobConfiguration.setCron("0 0 1 1 * ?");
jobConfiguration.setJobType(JobType.JAVA_JOB.toString());
jobConfiguration.setJobClass(LongtimeJavaJob.class.getCanonicalName());
jobConfiguration.setShardingTotalCount(shardCount);
jobConfiguration.setShardingItemParameters("0=0,1=1,2=2");
addJob(jobConfiguration);
Thread.sleep(1000);
enableJob(jobConfiguration.getJobName());
Thread.sleep(2000);
runAtOnce(jobName);
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
for (int j = 0; j < shardCount; j++) {
if (!regCenter
.isExisted(JobNodePath.getNodeFullPath(jobName, ExecutionNode.getRunningNode(j)))) {
return false;
}
}
return true;
}
}, 6);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
Thread.sleep(2000);
final List<Integer> items = ItemUtils.toItemList(regCenter.getDirectly(JobNodePath
.getNodeFullPath(jobName, ShardingNode.getShardingNode(saturnExecutorList.get(0).getExecutorName()))));
// 4 executorexecutor
stopExecutor(0);
System.out.println("items:" + items);
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
for (Integer item : items) {
if (!isFailoverAssigned(jobConfiguration, item)) {
return false;
}
}
return true;
}
}, 20);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
Thread.sleep(1000);
// 5 executor KILL
for (Integer item : items) {
String key = jobName + "_" + item;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (!status.finished || status.killed == 0) {
fail("should finish and killed");
}
status.runningCount = 0;
}
// 6 executor
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
for (int j = 0; j < shardCount; j++) {
String key = jobName + "_" + j;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (status.runningCount <= 0) {
return false;
}
}
return true;
}
}, 60);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
disableJob(jobConfiguration.getJobName());
Thread.sleep(1000);
removeJob(jobConfiguration.getJobName());
Thread.sleep(2000);
LongtimeJavaJob.statusMap.clear();
}
/**
* failoverfailover
*/
private void failoverWithDisabled(final int shardCount, final String jobName, final int disableTime)
throws Exception {
for (int i = 0; i < shardCount; i++) {
String key = jobName + "_" + i;
LongtimeJavaJob.JobStatus status = new LongtimeJavaJob.JobStatus();
status.runningCount = 0;
status.sleepSeconds = 20;
status.finished = false;
status.timeout = false;
LongtimeJavaJob.statusMap.put(key, status);
}
// 1 10S
final JobConfiguration jobConfiguration = new JobConfiguration(jobName);
jobConfiguration.setCron("0 0 1 1 * ?");
jobConfiguration.setJobType(JobType.JAVA_JOB.toString());
jobConfiguration.setJobClass(LongtimeJavaJob.class.getCanonicalName());
jobConfiguration.setShardingTotalCount(shardCount);
jobConfiguration.setShardingItemParameters("0=0,1=1,2=2");
addJob(jobConfiguration);
Thread.sleep(1000);
enableJob(jobConfiguration.getJobName());
Thread.sleep(2000);
runAtOnce(jobName);
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
for (int j = 0; j < shardCount; j++) {
if (!regCenter
.isExisted(JobNodePath.getNodeFullPath(jobName, ExecutionNode.getRunningNode(j)))) {
return false;
}
}
return true;
}
}, 6);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
Thread.sleep(2000);
final String firstExecutorName = saturnExecutorList.get(0).getExecutorName();
final List<Integer> items = ItemUtils.toItemList(regCenter
.getDirectly(JobNodePath.getNodeFullPath(jobName, ShardingNode.getShardingNode(firstExecutorName))));
final String secondExecutorName = saturnExecutorList.get(1).getExecutorName();
final List<Integer> items2 = ItemUtils.toItemList(regCenter
.getDirectly(JobNodePath.getNodeFullPath(jobName, ShardingNode.getShardingNode(secondExecutorName))));
if (disableTime == 1) {
disableJob(jobName);
}
// 4 executorexecutor
stopExecutor(0);
System.out.println("items:" + items);
// 5 Executor
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
if (isOnline(firstExecutorName)) {// Executor
return false;
}
return true;
}
}, 20);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// 6 executor KILL
for (Integer item : items) {
String key = jobName + "_" + item;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (!status.finished || status.killed == 0) {
fail("should finish and killed");
}
status.runningCount = 0;
}
// 7 executor2runningCount0
for (Integer item : items2) {
String key = jobName + "_" + item;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (status.finished || status.killed > 0 || status.timeout) {
fail("should running");
}
if (status.runningCount != 0) {
fail("runningCount should be 0");
}
}
if (disableTime == 2) {
disableJob(jobName);
}
// 9 executor2
try {
waitForFinish(new FinishCheck() {
@Override
public boolean docheck() {
for (Integer item : items2) {
String key = jobName + "_" + item;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (!status.finished) {
return false;
}
}
return true;
}
}, 20);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// 10 failover
assertThat(noFailoverItems(jobConfiguration));
for (Integer item : items) {
assertThat(isFailoverAssigned(jobConfiguration, item)).isEqualTo(false);
}
// 11 executor2
Thread.sleep(2000);
for (Integer item : items2) {
String key = jobName + "_" + item;
LongtimeJavaJob.JobStatus status = LongtimeJavaJob.statusMap.get(key);
if (status.runningCount != 1) {
fail("runningCount should be 1");
}
}
disableJob(jobConfiguration.getJobName());
Thread.sleep(1000);
removeJob(jobConfiguration.getJobName());
Thread.sleep(2000);
LongtimeJavaJob.statusMap.clear();
}
} |
package de.adito.irradiate;
import de.adito.irradiate.common.FilteredValueException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* IParticle-Impl
*/
class Particle<T> implements IParticle<T>
{
private ISample<T> sample;
Particle(ISample<T> pSample)
{
sample = pSample;
}
@Override
public IParticle<T> value(Consumer<? super T> pOnValue)
{
Objects.nonNull(sample);
AbstractDetector<T> detector = new AbstractDetector<T>()
{
@Override
public void hit(T pValue)
{
pOnValue.accept(pValue);
}
};
sample.accept(detector);
sample.addDetector(detector);
return this;
}
@Override
public IParticle<T> error(Consumer<Throwable> pOnThrowable)
{
Objects.nonNull(sample);
AbstractDetector<T> detector = new AbstractDetector<T>()
{
@Override
public void failure(Throwable pThrowable)
{
pOnThrowable.accept(pThrowable);
}
};
sample.accept(detector);
sample.addDetector(detector);
return this;
}
@Override
public IParticle<T> filter(Predicate<? super T> pPredicate)
{
Objects.nonNull(sample);
return new Particle<>(sample.addDetector(new _DetectorSampleFilter(pPredicate)));
}
@Override
public <R> IParticle<R> map(Function<? super T, ? extends R> pFunction)
{
Objects.nonNull(sample);
return new Particle<>(sample.addDetector(new _DetectorSampleMap<>(pFunction)));
}
@Override
public <R> IParticle<R> transform(IParticleTransformer<T, R> pParticleTransformer)
{
Objects.nonNull(sample);
return new Particle<>(sample.addDetector(new _DetectorSampleTransform<>(pParticleTransformer)));
}
public <R> IParticle<R> sequence(Function<T, IEmitter<R>> pFunction)
{
Objects.nonNull(sample);
_DetectorSampleSequence<R> detectorSample = new _DetectorSampleSequence<>(pFunction);
sample.addDetector(detectorSample);
return detectorSample.getParticle();
}
@Override
public Supplier<T> toSupplier(IDetector<T> pOnChange)
{
Objects.nonNull(sample);
return new Supplier<T>()
{
private AtomicReference<IDetector<T>> detectorRef = new AtomicReference<>();
private T value;
@Override
public T get()
{
boolean updated = detectorRef.compareAndSet(null, new AbstractDetector<T>()
{
@Override
public void hit(T pValue)
{
value = pValue;
}
});
if (updated)
{
IDetector<T> detector = detectorRef.get();
sample.accept(detector);
sample.addDetector(detector);
if (pOnChange != null)
sample.addDetector(pOnChange);
}
return value;
}
};
}
@Override
public void disintegrate()
{
if (sample != null) {
sample.disintegrate();
sample = null;
}
}
/**
* DetectorSample implementation for filtering.
*/
private class _DetectorSampleFilter extends DetectorSample<T, T>
{
private Predicate<? super T> predicate;
_DetectorSampleFilter(Predicate<? super T> pPredicate)
{
super(sample);
predicate = pPredicate;
}
@Override
public void passHit(IDetector<T> pDetector, T pValue, boolean pIsInitial)
{
if (pDetector != null)
{
if (predicate.test(pValue))
pDetector.hit(pValue);
else
pDetector.failure(new FilteredValueException(pValue));
}
}
}
/**
* DetectorSample implementation for mapping.
*/
private class _DetectorSampleMap<R> extends DetectorSample<T, R>
{
private Function<? super T, ? extends R> function;
_DetectorSampleMap(Function<? super T, ? extends R> pFunction)
{
super(sample);
function = pFunction;
}
@Override
public void passHit(IDetector<R> pDetector, T pValue, boolean pIsInitial)
{
if (pDetector != null)
pDetector.hit(function.apply(pValue));
}
}
/**
* DetectorSample implementation for transforming.
*/
private class _DetectorSampleTransform<R> extends DetectorSample<T, R>
{
private IParticleTransformer<T, R> particleTransformer;
_DetectorSampleTransform(IParticleTransformer<T, R> pParticleTransformer)
{
super(sample);
particleTransformer = pParticleTransformer;
}
@Override
public void passHit(IDetector<R> pDetector, T pValue, boolean pIsInitial)
{
particleTransformer.passHit(pDetector, pValue, pIsInitial);
}
@Override
public void passFailure(IDetector<R> pDetector, Throwable pThrowable, boolean pIsInitial)
{
particleTransformer.passFailure(pDetector, pThrowable, pIsInitial);
}
}
/**
* DetectorSample implementation for sequences.
*/
private class _DetectorSampleSequence<R> extends AbstractDetectorSample<T, R>
{
private final Function<T, IEmitter<R>> function;
private IEmitter<R> emitter;
private ISample<R> ps;
private _DS detectorSample;
_DetectorSampleSequence(Function<T, IEmitter<R>> pFunction)
{
function = pFunction;
detectorSample = new _DS();
}
@Override
public void hit(T pValue)
{
_updateEmitter(pValue);
}
@Override
public void failure(Throwable pThrowable)
{
detectorSample.failure(pThrowable);
}
@Override
public void accept(IDetector<R> pDetector)
{
sample.accept(new IDetector<T>()
{
@Override
public void hit(T pValue)
{
_updateEmitter(pValue);
if (ps == null)
pDetector.failure(new RuntimeException("no detector"));
else
ps.accept(pDetector);
}
@Override
public void failure(Throwable pThrowable)
{
pDetector.failure(pThrowable);
}
});
}
private void _updateEmitter(T pValue)
{
IEmitter<R> e = function.apply(pValue);
if (!Objects.equals(emitter, e))
{
emitter = e;
ISample<R> sample = ((Particle<R>) emitter.watch()).sample;
if (!Objects.equals(ps, sample))
{
if (ps != null)
ps.disintegrate();
ps = sample;
ps.addDetector(detectorSample);
ps.accept(detectorSample);
}
}
}
IParticle<R> getParticle()
{
return new Particle<>(detectorSample);
}
/**
* Outer detector
*/
private class _DS extends AbstractDetectorSample<R, R>
{
@Override
public void hit(R pValue)
{
new TransmittingDetector().hit(pValue);
}
@Override
public void failure(Throwable pThrowable)
{
new TransmittingDetector().failure(pThrowable);
}
@Override
public void accept(IDetector<R> pDetector)
{
_DetectorSampleSequence.this.accept(pDetector);
}
}
}
} |
package com.worth.ifs.application;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.worth.ifs.Application;
import com.worth.ifs.application.finance.service.FinanceRowService;
import com.worth.ifs.application.finance.service.FinanceService;
import com.worth.ifs.application.form.ApplicationForm;
import com.worth.ifs.application.form.validation.ApplicationStartDateValidator;
import com.worth.ifs.application.model.OpenFinanceSectionSectionModelPopulator;
import com.worth.ifs.application.model.OpenSectionModelPopulator;
import com.worth.ifs.application.model.QuestionModelPopulator;
import com.worth.ifs.application.resource.*;
import com.worth.ifs.commons.error.Error;
import com.worth.ifs.commons.rest.RestResult;
import com.worth.ifs.commons.rest.ValidationMessages;
import com.worth.ifs.competition.resource.CompetitionResource;
import com.worth.ifs.controller.ValidationHandler;
import com.worth.ifs.exception.AutosaveElementException;
import com.worth.ifs.exception.BigDecimalNumberFormatException;
import com.worth.ifs.exception.IntegerNumberFormatException;
import com.worth.ifs.exception.UnableToReadUploadedFile;
import com.worth.ifs.file.resource.FileEntryResource;
import com.worth.ifs.finance.resource.cost.FinanceRowItem;
import com.worth.ifs.form.resource.FormInputResource;
import com.worth.ifs.form.service.FormInputService;
import com.worth.ifs.model.OrganisationDetailsModelPopulator;
import com.worth.ifs.profiling.ProfileExecution;
import com.worth.ifs.user.resource.OrganisationResource;
import com.worth.ifs.user.resource.ProcessRoleResource;
import com.worth.ifs.user.resource.UserResource;
import com.worth.ifs.util.AjaxResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import static com.worth.ifs.application.resource.SectionType.FINANCE;
import static com.worth.ifs.commons.error.Error.fieldError;
import static com.worth.ifs.commons.error.ErrorConverterFactory.toField;
import static com.worth.ifs.commons.rest.ValidationMessages.*;
import static com.worth.ifs.controller.ErrorLookupHelper.lookupErrorMessageResourceBundleEntries;
import static com.worth.ifs.controller.ErrorLookupHelper.lookupErrorMessageResourceBundleEntry;
import static com.worth.ifs.file.controller.FileDownloadControllerUtils.getFileResponseEntity;
import static com.worth.ifs.util.CollectionFunctions.simpleFilter;
import static com.worth.ifs.util.CollectionFunctions.simpleMap;
import static com.worth.ifs.util.HttpUtils.requestParameterPresent;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.springframework.util.StringUtils.hasText;
/**
* This controller will handle all requests that are related to the application form.
*/
@Controller
@RequestMapping(ApplicationFormController.APPLICATION_BASE_URL+"{applicationId}/form")
public class ApplicationFormController extends AbstractApplicationController {
private static final Log LOG = LogFactory.getLog(ApplicationFormController.class);
@Autowired
private FinanceRowService financeRowService;
@Autowired
private FormInputService formInputService;
@Autowired
private FinanceService financeService;
@Autowired
private MessageSource messageSource;
@Autowired
private QuestionModelPopulator questionModelPopulator;
@Autowired
private OpenSectionModelPopulator openSectionModel;
@Autowired
private OrganisationDetailsModelPopulator organisationDetailsModelPopulator;
@Autowired
private OpenFinanceSectionSectionModelPopulator openFinanceSectionModel;
@InitBinder
protected void initBinder(WebDataBinder dataBinder, WebRequest webRequest) {
dataBinder.registerCustomEditor(String.class, new StringMultipartFileEditor());
}
@ProfileExecution
@RequestMapping(value = {QUESTION_URL + "{"+QUESTION_ID+"}", QUESTION_URL + "edit/{"+QUESTION_ID+"}"}, method = RequestMethod.GET)
public String showQuestion(@ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
@SuppressWarnings("unused") ValidationHandler validationHandler,
Model model,
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable(QUESTION_ID) final Long questionId,
HttpServletRequest request) {
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
questionModelPopulator.populateModel(questionId, applicationId, user, model, form);
organisationDetailsModelPopulator.populateModel(model, applicationId);
return APPLICATION_FORM;
}
@ProfileExecution
@RequestMapping(value = QUESTION_URL + "{"+QUESTION_ID+"}/forminput/{formInputId}/download", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<ByteArrayResource> downloadApplicationFinanceFile(
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable("formInputId") final Long formInputId,
HttpServletRequest request) {
final UserResource user = userAuthenticationService.getAuthenticatedUser(request);
ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), applicationId);
final ByteArrayResource resource = formInputResponseService.getFile(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException();
final FormInputResponseFileEntryResource fileDetails = formInputResponseService.getFileDetails(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException();
return getFileResponseEntity(resource, fileDetails.getFileEntryResource());
}
@RequestMapping(value = "/{applicationFinanceId}/finance-download", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<ByteArrayResource> downloadApplicationFinanceFile(
@PathVariable("applicationFinanceId") final Long applicationFinanceId) {
final ByteArrayResource resource = financeService.getFinanceDocumentByApplicationFinance(applicationFinanceId).getSuccessObjectOrThrowException();
final FileEntryResource fileDetails = financeService.getFinanceEntryByApplicationFinanceId(applicationFinanceId).getSuccessObjectOrThrowException();
return getFileResponseEntity(resource, fileDetails);
}
@ProfileExecution
@RequestMapping(value = SECTION_URL + "{sectionId}", method = RequestMethod.GET)
public String applicationFormWithOpenSection(@Valid @ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form, BindingResult bindingResult, Model model,
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable("sectionId") final Long sectionId,
HttpServletRequest request) {
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
ApplicationResource application = applicationService.getById(applicationId);
List<SectionResource> allSections = sectionService.getAllByCompetitionId(application.getCompetition());
SectionResource section = simpleFilter(allSections, s -> sectionId.equals(s.getId())).get(0);
if (FINANCE.equals(section.getType())) {
openFinanceSectionModel.populateModel(form, model, application, section, user, bindingResult, allSections);
} else {
openSectionModel.populateModel(form, model, application, section, user, bindingResult, allSections);
}
return APPLICATION_FORM;
}
private void addFormAttributes(ApplicationResource application,
CompetitionResource competition,
Optional<SectionResource> section,
UserResource user, Model model,
ApplicationForm form, Optional<QuestionResource> question,
Optional<List<FormInputResource>> formInputs,
List<ProcessRoleResource> userApplicationRoles){
addApplicationDetails(application, competition, user.getId(), section, question.map(q -> q.getId()), model, form, userApplicationRoles);
organisationDetailsModelPopulator.populateModel(model, application.getId(), userApplicationRoles);
addNavigation(question.orElse(null), application.getId(), model);
Map<Long, List<FormInputResource>> questionFormInputs = new HashMap<>();
if(question.isPresent()) {
questionFormInputs.put(question.get().getId(), formInputs.orElse(null));
}
model.addAttribute("currentQuestion", question.orElse(null));
model.addAttribute("questionFormInputs", questionFormInputs);
model.addAttribute("currentUser", user);
model.addAttribute("form", form);
if(question.isPresent()) {
model.addAttribute("title", question.get().getShortName());
}
}
@ProfileExecution
@RequestMapping(value = {QUESTION_URL + "{"+QUESTION_ID+"}", QUESTION_URL + "edit/{"+QUESTION_ID+"}"}, method = RequestMethod.POST)
public String questionFormSubmit(@Valid @ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
@SuppressWarnings("unused") ValidationHandler validationHandler,
Model model,
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable(QUESTION_ID) final Long questionId,
HttpServletRequest request,
HttpServletResponse response) {
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
Map<String, String[]> params = request.getParameterMap();
// Check if the request is to just open edit view or to save
if(params.containsKey(EDIT_QUESTION)){
ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), applicationId);
if (processRole != null) {
questionService.markAsInComplete(questionId, applicationId, processRole.getId());
} else {
LOG.error("Not able to find process role for user " + user.getName() + " for application id " + applicationId);
}
return showQuestion(form, bindingResult, validationHandler, model, applicationId, questionId, request);
} else {
QuestionResource question = questionService.getById(questionId);
SectionResource section = sectionService.getSectionByQuestionId(questionId);
ApplicationResource application = applicationService.getById(applicationId);
CompetitionResource competition = competitionService.getById(application.getCompetition());
List<ProcessRoleResource> userApplicationRoles = processRoleService.findProcessRolesByApplicationId(application.getId());
List<FormInputResource> formInputs = formInputService.findApplicationInputsByQuestion(questionId);
if (params.containsKey(ASSIGN_QUESTION_PARAM)) {
assignQuestion(applicationId, request);
cookieFlashMessageFilter.setFlashMessage(response, "assignedQuestion");
}
ValidationMessages errors = new ValidationMessages();
if (isAllowedToUpdateQuestion(questionId, applicationId, user.getId()) || isMarkQuestionRequest(params)) {
/* Start save action */
errors.addAll(saveApplicationForm(application, competition, form, applicationId, null, question, request, response));
}
model.addAttribute("form", form);
/* End save action */
if (errors.hasErrors() && isMarkQuestionRequest(params)) {
validationHandler.addAnyErrors(errors);
this.addFormAttributes(application, competition, Optional.ofNullable(section), user, model, form,
Optional.ofNullable(question), Optional.ofNullable(formInputs), userApplicationRoles);
model.addAttribute("currentUser", user);
addUserDetails(model, application, user.getId());
addNavigation(question, applicationId, model);
return APPLICATION_FORM;
} else {
return getRedirectUrl(request, applicationId);
}
}
}
private Boolean isAllowedToUpdateQuestion(Long questionId, Long applicationId, Long userId) {
List<QuestionStatusResource> questionStatuses = questionService.findQuestionStatusesByQuestionAndApplicationId(questionId, applicationId);
return questionStatuses.isEmpty() || questionStatuses.stream()
.anyMatch(questionStatusResource -> (
questionStatusResource.getAssignee() == null || questionStatusResource.getAssigneeUserId().equals(userId))
&& (questionStatusResource.getMarkedAsComplete() == null || !questionStatusResource.getMarkedAsComplete()));
}
private String getRedirectUrl(HttpServletRequest request, Long applicationId) {
if (request.getParameter("submit-section") == null
&& (request.getParameter(ASSIGN_QUESTION_PARAM) != null ||
request.getParameter(MARK_AS_INCOMPLETE) != null ||
request.getParameter(MARK_SECTION_AS_INCOMPLETE) != null ||
request.getParameter(ADD_COST) != null ||
request.getParameter(REMOVE_COST) != null ||
request.getParameter(MARK_AS_COMPLETE) != null ||
request.getParameter(REMOVE_UPLOADED_FILE) != null ||
request.getParameter(UPLOAD_FILE) != null ||
request.getParameter(EDIT_QUESTION) != null)) {
// user did a action, just display the same page.
LOG.debug("redirect: " + request.getRequestURI());
return "redirect:" + request.getRequestURI();
} else {
// add redirect, to make sure the user cannot resubmit the form by refreshing the page.
LOG.debug("default redirect: ");
return "redirect:" + APPLICATION_BASE_URL + applicationId;
}
}
@RequestMapping(value = "/add_cost/{"+QUESTION_ID+"}")
public String addCostRow(@ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form,
BindingResult bindingResult,
Model model,
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable(QUESTION_ID) final Long questionId,
HttpServletRequest request) {
FinanceRowItem costItem = addCost(applicationId, questionId, request);
String type = costItem.getCostType().getType();
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
Set<Long> markedAsComplete = new TreeSet<>();
model.addAttribute("markedAsComplete", markedAsComplete);
String organisationType = organisationService.getOrganisationType(user.getId(), applicationId);
financeHandler.getFinanceModelManager(organisationType).addCost(model, costItem, applicationId, user.getId(), questionId, type);
form.setBindingResult(bindingResult);
return String.format("finance/finance :: %s_row", type);
}
@RequestMapping(value = "/remove_cost/{costId}")
public @ResponseBody String removeCostRow(@PathVariable("costId") final Long costId) throws JsonProcessingException {
financeRowService.delete(costId);
AjaxResult ajaxResult = new AjaxResult(HttpStatus.OK, "true");
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ajaxResult);
}
private FinanceRowItem addCost(Long applicationId, Long questionId, HttpServletRequest request) {
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
String organisationType = organisationService.getOrganisationType(user.getId(), applicationId);
return financeHandler.getFinanceFormHandler(organisationType).addCostWithoutPersisting(applicationId, user.getId(), questionId);
}
private ValidationMessages saveApplicationForm(ApplicationResource application,
CompetitionResource competition,
ApplicationForm form,
Long applicationId, Long sectionId, QuestionResource question,
HttpServletRequest request,
HttpServletResponse response) {
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), applicationId);
// Check if action is mark as complete. Check empty values if so, ignore otherwise. (INFUND-1222)
Map<String, String[]> params = request.getParameterMap();
logSaveApplicationDetails(params);
boolean ignoreEmpty = (!params.containsKey(MARK_AS_COMPLETE)) && (!params.containsKey(MARK_SECTION_AS_COMPLETE));
ValidationMessages errors = new ValidationMessages();
SectionResource selectedSection = null;
if (sectionId != null) {
selectedSection = getSelectedSection(competition.getSections(), sectionId);
if (isMarkSectionAsCompleteRequest(params)) {
application.setStateAidAgreed(form.isStateAidAgreed());
} else if (isMarkSectionAsIncompleteRequest(params) && selectedSection.getType() == SectionType.FINANCE) {
application.setStateAidAgreed(Boolean.FALSE);
}
}
// Prevent saving question when it's a unmark question request (INFUND-2936)
if(!isMarkQuestionAsInCompleteRequest(params)) {
if (question != null) {
errors.addAll(saveQuestionResponses(request, singletonList(question), user.getId(), processRole.getId(), application.getId(), ignoreEmpty));
} else {
List<QuestionResource> questions = simpleMap(selectedSection.getQuestions(), questionService::getById);
errors.addAll(saveQuestionResponses(request, questions, user.getId(), processRole.getId(), application.getId(), ignoreEmpty));
}
}
errors.addAll(validationApplicationStartDate(request));
setApplicationDetails(application, form.getApplication());
if(userIsLeadApplicant(application, user.getId())) {
applicationService.save(application);
}
if(!isMarkSectionAsIncompleteRequest(params)) {
String organisationType = organisationService.getOrganisationType(user.getId(), applicationId);
errors.addAll(financeHandler.getFinanceFormHandler(organisationType).update(request, user.getId(), applicationId));
}
if(isMarkQuestionRequest(params)) {
errors.addAll(handleApplicationDetailsMarkCompletedRequest(application, request, response, processRole, errors));
} else if(isMarkSectionRequest(params)){
errors.addAll(handleMarkSectionRequest(application, competition, sectionId, request, response, processRole, errors));
}
if (errors.hasErrors()) {
errors.setErrors(sortValidationMessages(errors));
}
cookieFlashMessageFilter.setFlashMessage(response, "applicationSaved");
return errors;
}
private List<Error> sortValidationMessages(ValidationMessages errors) {
List<Error> sortedErrors = errors.getErrors().stream().filter(error ->
error.getErrorKey().equals("application.validation.MarkAsCompleteFailed")).collect(toList());
sortedErrors.addAll(errors.getErrors());
return sortedErrors.parallelStream().distinct().collect(toList());
}
private void logSaveApplicationDetails(Map<String, String[]> params) {
params.forEach((key, value) -> LOG.debug(String.format("saveApplicationForm key %s => value %s", key, value[0])));
}
private ValidationMessages validationApplicationStartDate(HttpServletRequest request) {
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(request, "");
new ApplicationStartDateValidator().validate(request, bindingResult);
return fromBindingResult(bindingResult);
}
private ValidationMessages handleApplicationDetailsMarkCompletedRequest(ApplicationResource application, HttpServletRequest request, HttpServletResponse response, ProcessRoleResource processRole, ValidationMessages errorsSoFar) {
if (errorsSoFar.hasErrors()) {
return new ValidationMessages(fieldError("formInput[application]", "", "application.validation.MarkAsCompleteFailed"));
} else {
ValidationMessages messages = new ValidationMessages();
List<ValidationMessages> applicationMessages = markApplicationQuestions(application, processRole.getId(), request, response, errorsSoFar);
if (collectValidationMessages(applicationMessages).hasErrors()) {
messages.addError(fieldError("formInput[application]", "", "application.validation.MarkAsCompleteFailed"));
messages.addAll(handleApplicationDetailsValidationMessages(applicationMessages, application));
}
return messages;
}
}
private ValidationMessages handleApplicationDetailsValidationMessages(List<ValidationMessages> applicationMessages, ApplicationResource application) {
ValidationMessages toFieldErrors = new ValidationMessages();
applicationMessages.forEach(validationMessage ->
validationMessage.getErrors().stream()
.filter(Objects::nonNull)
.filter(e -> hasText(e.getErrorKey()))
.forEach(e -> {
if (validationMessage.getObjectName().equals("target")) {
if (hasText(e.getErrorKey())) {
toFieldErrors.addError(fieldError("formInput[application." + validationMessage.getObjectId() + "-" + e.getFieldName() + "]", e.getFieldRejectedValue(), e.getErrorKey()));
if (e.getErrorKey().equals("durationInMonths")) {
application.setDurationInMonths(null);
}
}
}
}));
return toFieldErrors;
}
private ValidationMessages handleMarkSectionRequest(ApplicationResource application, CompetitionResource competition, Long sectionId, HttpServletRequest request, HttpServletResponse response, ProcessRoleResource processRole, ValidationMessages errorsSoFar) {
ValidationMessages messages = new ValidationMessages();
if (errorsSoFar.hasErrors()) {
messages.addError(fieldError("formInput[cost]", "", "application.validation.MarkAsCompleteFailed"));
} else {
SectionResource selectedSection = getSelectedSection(competition.getSections(), sectionId);
List<ValidationMessages> financeErrorsMark = markAllQuestionsInSection(application, selectedSection, processRole.getId(), request);
if (collectValidationMessages(financeErrorsMark).hasErrors()) {
messages.addError(fieldError("formInput[cost]", "", "application.validation.MarkAsCompleteFailed"));
messages.addAll(handleMarkSectionValidationMessages(financeErrorsMark));
}
}
return messages;
}
private ValidationMessages handleMarkSectionValidationMessages(List<ValidationMessages> financeErrorsMark) {
ValidationMessages toFieldErrors = new ValidationMessages();
financeErrorsMark.forEach(validationMessage ->
validationMessage.getErrors().stream()
.filter(Objects::nonNull)
.filter(e -> hasText(e.getErrorKey()))
.forEach(e -> {
if (validationMessage.getObjectName().equals("costItem")) {
if (hasText(e.getErrorKey())) {
toFieldErrors.addError(fieldError("formInput[cost-" + validationMessage.getObjectId() + "-" + e.getFieldName() + "]", e));
} else {
toFieldErrors.addError(fieldError("formInput[cost-" + validationMessage.getObjectId() + "]", e));
}
} else {
toFieldErrors.addError(fieldError("formInput[" + validationMessage.getObjectId() + "]", e));
}
})
);
return toFieldErrors;
}
private List<ValidationMessages> markAllQuestionsInSection(ApplicationResource application,
SectionResource selectedSection,
Long processRoleId,
HttpServletRequest request) {
Map<String, String[]> params = request.getParameterMap();
String action = params.containsKey(MARK_SECTION_AS_COMPLETE) ? MARK_AS_COMPLETE : MARK_AS_INCOMPLETE;
if(action.equals(MARK_AS_COMPLETE)){
return sectionService.markAsComplete(selectedSection.getId(), application.getId(), processRoleId);
}else{
sectionService.markAsInComplete(selectedSection.getId(), application.getId(), processRoleId);
}
return emptyList();
}
private boolean isMarkQuestionRequest(@NotNull Map<String, String[]> params){
return params.containsKey(MARK_AS_COMPLETE) || params.containsKey(MARK_AS_INCOMPLETE);
}
private boolean isMarkQuestionAsInCompleteRequest(@NotNull Map<String, String[]> params){
return params.containsKey(MARK_AS_INCOMPLETE);
}
private boolean isMarkSectionRequest(@NotNull Map<String, String[]> params){
return params.containsKey(MARK_SECTION_AS_COMPLETE) || params.containsKey(MARK_SECTION_AS_INCOMPLETE);
}
private boolean isMarkSectionAsIncompleteRequest(@NotNull Map<String, String[]> params){
return params.containsKey(MARK_SECTION_AS_INCOMPLETE);
}
private boolean isMarkSectionAsCompleteRequest(@NotNull Map<String, String[]> params){
return params.containsKey(MARK_SECTION_AS_COMPLETE);
}
private boolean isSubmitSectionRequest(@NotNull Map<String, String[]> params){
return params.containsKey(SUBMIT_SECTION);
}
private SectionResource getSelectedSection(List<Long> sectionIds, Long sectionId) {
return sectionIds.stream()
.map(sectionService::getById)
.filter(x -> x.getId().equals(sectionId))
.findFirst()
.get();
}
private List<ValidationMessages> markApplicationQuestions(ApplicationResource application, Long processRoleId, HttpServletRequest request, HttpServletResponse response, ValidationMessages errorsSoFar) {
if (processRoleId == null) {
return emptyList();
}
Map<String, String[]> params = request.getParameterMap();
if (params.containsKey(MARK_AS_COMPLETE)) {
Long questionId = Long.valueOf(request.getParameter(MARK_AS_COMPLETE));
List<ValidationMessages> markAsCompleteErrors = questionService.markAsComplete(questionId, application.getId(), processRoleId);
if (collectValidationMessages(markAsCompleteErrors).hasErrors()) {
questionService.markAsInComplete(questionId, application.getId(), processRoleId);
}
else {
cookieFlashMessageFilter.setFlashMessage(response, "applicationSaved");
}
if (errorsSoFar.hasFieldErrors(questionId + "")) {
markAsCompleteErrors.add(new ValidationMessages(fieldError(questionId + "", "", "mark.as.complete.invalid.data.exists")));
}
return markAsCompleteErrors;
} else if (params.containsKey(MARK_AS_INCOMPLETE)) {
Long questionId = Long.valueOf(request.getParameter(MARK_AS_INCOMPLETE));
questionService.markAsInComplete(questionId, application.getId(), processRoleId);
}
return emptyList();
}
/**
* This method is for the post request when the users clicks the input[type=submit] button.
* This is also used when the user clicks the 'mark-as-complete' button or reassigns a question to another user.
*/
@ProfileExecution
@RequestMapping(value = SECTION_URL + "{sectionId}", method = RequestMethod.POST)
public String applicationFormSubmit(@Valid @ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form,
BindingResult bindingResult, ValidationHandler validationHandler,
Model model,
@PathVariable(APPLICATION_ID) final Long applicationId,
@PathVariable("sectionId") final Long sectionId,
HttpServletRequest request,
HttpServletResponse response) {
logSaveApplicationBindingErrors(validationHandler);
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
ApplicationResource application = applicationService.getById(applicationId);
CompetitionResource competition = competitionService.getById(application.getCompetition());
SectionResource section = sectionService.getById(sectionId);
if (section.getType() == SectionType.FINANCE &&
!validFinanceTermsForMarkAsComplete(request, form, bindingResult, section, application, competition, user, model)) {
return APPLICATION_FORM;
}
Map<String, String[]> params = request.getParameterMap();
ValidationMessages saveApplicationErrors = saveApplicationForm(application, competition, form, applicationId, sectionId, null, request, response);
logSaveApplicationErrors(bindingResult);
if (params.containsKey(ASSIGN_QUESTION_PARAM)) {
assignQuestion(applicationId, request);
cookieFlashMessageFilter.setFlashMessage(response, "assignedQuestion");
}
model.addAttribute("form", form);
if(saveApplicationErrors.hasErrors()){
validationHandler.addAnyErrors(saveApplicationErrors);
setReturnToApplicationFormData(section, application, competition, user, model, form, applicationId);
return APPLICATION_FORM;
} else {
return getRedirectUrl(request, applicationId);
}
}
private void setReturnToApplicationFormData(SectionResource section, ApplicationResource application, CompetitionResource competition,
UserResource user, Model model, ApplicationForm form, Long applicationId) {
addApplicationAndSectionsInternalWithOrgDetails(application, competition, user.getId(), Optional.ofNullable(section), model, form);
addOrganisationAndUserFinanceDetails(competition.getId(), application.getId(), user, model, form);
addNavigation(section, applicationId, model);
List<ProcessRoleResource> userApplicationRoles = processRoleService.findProcessRolesByApplicationId(application.getId());
Optional<OrganisationResource> userOrganisation = getUserOrganisation(user.getId(), userApplicationRoles);
addCompletedDetails(model, application, userOrganisation);
}
private boolean validFinanceTermsForMarkAsComplete(HttpServletRequest request, ApplicationForm form,
BindingResult bindingResult, SectionResource section, ApplicationResource application,
CompetitionResource competition, UserResource user, Model model
) {
if (isMarkSectionAsCompleteRequest(request.getParameterMap())) {
if (!form.isTermsAgreed()) {
bindingResult.rejectValue(TERMS_AGREED_KEY, "APPLICATION_AGREE_TERMS_AND_CONDITIONS");
setReturnToApplicationFormData(section, application, competition, user, model, form, application.getId());
return false;
} else if (!form.isStateAidAgreed()) {
bindingResult.rejectValue(STATE_AID_AGREED_KEY, "APPLICATION_AGREE_STATE_AID_CONDITIONS");
setReturnToApplicationFormData(section, application, competition, user, model, form, application.getId());
return false;
}
}
return true;
}
private void logSaveApplicationBindingErrors(ValidationHandler validationHandler) {
if(LOG.isDebugEnabled())
validationHandler.getAllErrors().forEach(e -> LOG.debug("Validations on application : " + e.getObjectName() + " v: " + e.getDefaultMessage()));
}
private void logSaveApplicationErrors(BindingResult bindingResult) {
if(LOG.isDebugEnabled()){
bindingResult.getFieldErrors().forEach(e -> LOG.debug("Remote validation field: " + e.getObjectName() + " v: " + e.getField() + " v: " + e.getDefaultMessage()));
bindingResult.getGlobalErrors().forEach(e -> LOG.debug("Remote validation global: " + e.getObjectName()+ " v: " + e.getCode() + " v: " + e.getDefaultMessage()));
}
}
private ValidationMessages saveQuestionResponses(HttpServletRequest request,
List<QuestionResource> questions,
Long userId,
Long processRoleId,
Long applicationId,
boolean ignoreEmpty) {
final Map<String, String[]> params = request.getParameterMap();
ValidationMessages errors = new ValidationMessages();
errors.addAll(saveNonFileUploadQuestions(questions, params, request, userId, applicationId, ignoreEmpty));
errors.addAll(saveFileUploadQuestionsIfAny(questions, params, request, applicationId, processRoleId));
return errors;
}
private ValidationMessages saveNonFileUploadQuestions(List<QuestionResource> questions,
Map<String, String[]> params,
HttpServletRequest request,
Long userId,
Long applicationId,
boolean ignoreEmpty) {
ValidationMessages allErrors = new ValidationMessages();
questions.stream()
.forEach(question ->
{
List<FormInputResource> formInputs = formInputService.findApplicationInputsByQuestion(question.getId());
formInputs
.stream()
.filter(formInput1 -> !"fileupload".equals(formInput1.getFormInputTypeTitle()))
.forEach(formInput -> {
String formInputKey = "formInput[" + formInput.getId() + "]";
requestParameterPresent(formInputKey, request).ifPresent(value -> {
ValidationMessages errors = formInputResponseService.save(userId, applicationId, formInput.getId(), value, ignoreEmpty);
allErrors.addAll(errors, toField(formInputKey));
});
});
}
);
return allErrors;
}
private ValidationMessages saveFileUploadQuestionsIfAny(List<QuestionResource> questions,
final Map<String, String[]> params,
HttpServletRequest request,
Long applicationId,
Long processRoleId) {
ValidationMessages allErrors = new ValidationMessages();
questions.stream()
.forEach(question -> {
List<FormInputResource> formInputs = formInputService.findApplicationInputsByQuestion(question.getId());
formInputs
.stream()
.filter(formInput1 -> "fileupload".equals(formInput1.getFormInputTypeTitle()) && request instanceof StandardMultipartHttpServletRequest)
.forEach(formInput ->
allErrors.addAll(processFormInput(formInput.getId(), params, applicationId, processRoleId, request))
);
});
return allErrors;
}
private ValidationMessages processFormInput(Long formInputId, Map<String, String[]> params, Long applicationId, Long processRoleId, HttpServletRequest request){
if (params.containsKey(REMOVE_UPLOADED_FILE)) {
formInputResponseService.removeFile(formInputId, applicationId, processRoleId).getSuccessObjectOrThrowException();
return noErrors();
} else {
final Map<String, MultipartFile> fileMap = ((StandardMultipartHttpServletRequest) request).getFileMap();
final MultipartFile file = fileMap.get("formInput[" + formInputId + "]");
if (file != null && !file.isEmpty()) {
try {
RestResult<FileEntryResource> result = formInputResponseService.createFile(formInputId,
applicationId,
processRoleId,
file.getContentType(),
file.getSize(),
file.getOriginalFilename(),
file.getBytes());
if (result.isFailure()) {
ValidationMessages errors = new ValidationMessages();
result.getFailure().getErrors().forEach(e -> {
errors.addError(fieldError("formInput[" + formInputId + "]", e.getFieldRejectedValue(), e.getErrorKey()));
});
return errors;
}
} catch (IOException e) {
LOG.error(e);
throw new UnableToReadUploadedFile();
}
}
}
return noErrors();
}
/**
* Set the submitted values, if not null. If they are null, then probably the form field was not in the current html form.
* @param application
* @param updatedApplication
*/
private void setApplicationDetails(ApplicationResource application, ApplicationResource updatedApplication) {
if (updatedApplication == null) {
return;
}
if (updatedApplication.getName() != null) {
LOG.debug("setApplicationDetails: " + updatedApplication.getName());
application.setName(updatedApplication.getName());
}
setResubmissionDetails(application, updatedApplication);
if (updatedApplication.getStartDate() != null) {
LOG.debug("setApplicationDetails date 123: " + updatedApplication.getStartDate().toString());
if (updatedApplication.getStartDate().isEqual(LocalDate.MIN)
|| updatedApplication.getStartDate().isBefore(LocalDate.now())) {
// user submitted a empty date field or date before today
application.setStartDate(null);
} else{
application.setStartDate(updatedApplication.getStartDate());
}
} else {
application.setStartDate(null);
}
if (updatedApplication.getDurationInMonths() != null) {
LOG.debug("setApplicationDetails: " + updatedApplication.getDurationInMonths());
application.setDurationInMonths(updatedApplication.getDurationInMonths());
}
else {
application.setDurationInMonths(null);
}
}
/**
* Set the submitted details relating to resubmission of applications.
* @param application
* @param updatedApplication
*/
private void setResubmissionDetails(ApplicationResource application, ApplicationResource updatedApplication) {
if (updatedApplication.getResubmission() != null) {
LOG.debug("setApplicationDetails: resubmission " + updatedApplication.getResubmission());
application.setResubmission(updatedApplication.getResubmission());
if (updatedApplication.getResubmission()) {
application.setPreviousApplicationNumber(updatedApplication.getPreviousApplicationNumber());
application.setPreviousApplicationTitle(updatedApplication.getPreviousApplicationTitle());
} else {
application.setPreviousApplicationNumber(null);
application.setPreviousApplicationTitle(null);
}
}
}
/**
* This method is for supporting ajax saving from the application form.
*/
@ProfileExecution
@RequestMapping(value = "/saveFormElement", method = RequestMethod.POST)
@ResponseBody
public JsonNode saveFormElement(@RequestParam("formInputId") String inputIdentifier,
@RequestParam("value") String value,
@PathVariable(APPLICATION_ID) Long applicationId,
HttpServletRequest request) {
List<String> errors = new ArrayList<>();
Long fieldId = null;
try {
String fieldName = request.getParameter("fieldName");
LOG.info(String.format("saveFormElement: %s / %s", fieldName, value));
UserResource user = userAuthenticationService.getAuthenticatedUser(request);
StoreFieldResult storeFieldResult = storeField(applicationId, user.getId(), fieldName, inputIdentifier, value);
errors = storeFieldResult.getErrors();
fieldId = storeFieldResult.getFieldId();
if (!errors.isEmpty()) {
return this.createJsonObjectNode(false, errors, fieldId);
} else {
return this.createJsonObjectNode(true, null, fieldId);
}
} catch (Exception e) {
AutosaveElementException ex = new AutosaveElementException(inputIdentifier, value, applicationId, e);
handleAutosaveException(errors, e, ex);
return this.createJsonObjectNode(false, errors, fieldId);
}
}
private void handleAutosaveException(List<String> errors, Exception e, AutosaveElementException ex) {
List<Object> args = new ArrayList<>();
args.add(ex.getErrorMessage());
if(e.getClass().equals(IntegerNumberFormatException.class) || e.getClass().equals(BigDecimalNumberFormatException.class)){
errors.add(lookupErrorMessageResourceBundleEntry(messageSource, e.getMessage(), args));
}else{
LOG.error("Got a exception on autosave : "+ e.getMessage());
LOG.debug("Autosave exception: ", e);
errors.add(ex.getErrorMessage());
}
}
private StoreFieldResult storeField(Long applicationId, Long userId, String fieldName, String inputIdentifier, String value) {
String organisationType = organisationService.getOrganisationType(userId, applicationId);
if (fieldName.startsWith("application.")) {
// this does not need id
List<String> errors = this.saveApplicationDetails(applicationId, fieldName, value);
return new StoreFieldResult(errors);
} else if (inputIdentifier.startsWith("financePosition-") || fieldName.startsWith("financePosition-")) {
financeHandler.getFinanceFormHandler(organisationType).updateFinancePosition(userId, applicationId, fieldName, value);
return new StoreFieldResult();
} else if (inputIdentifier.startsWith("cost-") || fieldName.startsWith("cost-")) {
ValidationMessages validationMessages = financeHandler.getFinanceFormHandler(organisationType).storeCost(userId, applicationId, fieldName, value);
if(validationMessages == null || validationMessages.getErrors() == null || validationMessages.getErrors().isEmpty()){
LOG.debug("no errors");
if(validationMessages == null) {
return new StoreFieldResult();
} else {
return new StoreFieldResult(validationMessages.getObjectId());
}
} else {
String[] fieldNameParts = fieldName.split("-");
// fieldname = other_costs-description-34-219
List<String> errors = validationMessages.getErrors()
.stream()
.peek(e -> LOG.debug(String.format("Compare: %s => %s ", fieldName.toLowerCase(), e.getFieldName().toLowerCase())))
.filter(e -> fieldNameParts[1].toLowerCase().contains(e.getFieldName().toLowerCase())) // filter out the messages that are related to other fields.
.map(this::lookupErrorMessage)
.collect(toList());
return new StoreFieldResult(validationMessages.getObjectId(), errors);
}
} else {
Long formInputId = Long.valueOf(inputIdentifier);
ValidationMessages saveErrors = formInputResponseService.save(userId, applicationId, formInputId, value, false);
List<String> lookedUpErrorMessages = lookupErrorMessageResourceBundleEntries(messageSource, saveErrors);
return new StoreFieldResult(lookedUpErrorMessages);
}
}
private String lookupErrorMessage(Error e) {
return lookupErrorMessageResourceBundleEntry(messageSource, e);
}
private ObjectNode createJsonObjectNode(boolean success, List<String> errors, Long fieldId) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("success", success ? "true" : "false");
if (!success) {
ArrayNode errorsNode = mapper.createArrayNode();
errors.stream().forEach(errorsNode::add);
node.set("validation_errors", errorsNode);
}
if(fieldId != null) {
node.set("field_id", new LongNode(fieldId));
}
return node;
}
private List<String> saveApplicationDetails(Long applicationId, String fieldName, String value) {
List<String> errors = new ArrayList<>();
ApplicationResource application = applicationService.getById(applicationId);
if ("application.name".equals(fieldName)) {
String trimmedValue = value.trim();
if (StringUtils.isEmpty(trimmedValue)) {
errors.add("Please enter the full title of the project");
} else {
application.setName(trimmedValue);
applicationService.save(application);
}
} else if (fieldName.startsWith("application.durationInMonths")) {
Long durationInMonth = Long.valueOf(value);
if (durationInMonth < 1L || durationInMonth > 36L) {
errors.add("Your project should last between 1 and 36 months");
application.setDurationInMonths(durationInMonth);
} else {
application.setDurationInMonths(durationInMonth);
applicationService.save(application);
}
} else if (fieldName.startsWith(APPLICATION_START_DATE)) {
errors = this.saveApplicationStartDate(application, fieldName, value);
} else if (fieldName.equals("application.resubmission")) {
application.setResubmission(Boolean.valueOf(value));
applicationService.save(application);
} else if (fieldName.equals("application.previousApplicationNumber")) {
application.setPreviousApplicationNumber(value);
applicationService.save(application);
} else if (fieldName.equals("application.previousApplicationTitle")) {
application.setPreviousApplicationTitle(value);
applicationService.save(application);
}
return errors;
}
private List<String> saveApplicationStartDate(ApplicationResource application, String fieldName, String value) {
List<String> errors = new ArrayList<>();
LocalDate startDate = application.getStartDate();
if (fieldName.endsWith(".dayOfMonth")) {
startDate = LocalDate.of(startDate.getYear(), startDate.getMonth(), Integer.parseInt(value));
} else if (fieldName.endsWith(".monthValue")) {
startDate = LocalDate.of(startDate.getYear(), Integer.parseInt(value), startDate.getDayOfMonth());
} else if (fieldName.endsWith(".year")) {
startDate = LocalDate.of(Integer.parseInt(value), startDate.getMonth(), startDate.getDayOfMonth());
} else if ("application.startDate".equals(fieldName)){
String[] parts = value.split("-");
startDate = LocalDate.of(Integer.parseInt(parts[2]), Integer.parseInt(parts[1]), Integer.parseInt(parts[0]));
}
if (startDate.isBefore(LocalDate.now())) {
errors.add("Please enter a future date");
startDate = null;
}else{
LOG.debug("Save startdate: "+ startDate.toString());
}
application.setStartDate(startDate);
applicationService.save(application);
return errors;
}
private void assignQuestion(@PathVariable(APPLICATION_ID) final Long applicationId,
HttpServletRequest request) {
assignQuestion(request, applicationId);
}
private void addApplicationAndSectionsInternalWithOrgDetails(final ApplicationResource application, final CompetitionResource competition, final Long userId, Optional<SectionResource> section, final Model model, final ApplicationForm form) {
organisationDetailsModelPopulator.populateModel(model, application.getId());
addApplicationAndSections(application, competition, userId, section, Optional.empty(), model, form);
}
private static class StoreFieldResult {
private Long fieldId;
private List<String> errors = new ArrayList<>();
public StoreFieldResult() {
}
public StoreFieldResult(Long fieldId) {
this.fieldId = fieldId;
}
public StoreFieldResult(List<String> errors) {
this.errors = errors;
}
public StoreFieldResult(Long fieldId, List<String> errors) {
this.fieldId = fieldId;
this.errors = errors;
}
public List<String> getErrors() {
return errors;
}
public Long getFieldId() {
return fieldId;
}
}
} |
package org.apache.xerces.impl.v2;
/**
* Store schema particle declaration.
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class XSParticleDecl {
// types of particles
public static final short PARTICLE_EMPTY = 0;
public static final short PARTICLE_ELEMENT = 1;
public static final short PARTICLE_WILDCARD = 2;
public static final short PARTICLE_CHOICE = 3;
public static final short PARTICLE_SEQUENCE = 4;
public static final short PARTICLE_ALL = 5;
public static final short PARTICLE_ZERO_OR_ONE = 6;
public static final short PARTICLE_ZERO_OR_MORE = 7;
public static final short PARTICLE_ONE_OR_MORE = 8;
// type of the particle
public short fType = PARTICLE_EMPTY;
// left-hand value of the particle
// for PARTICLE_ELEMENT : the element decl
// for PARTICLE_WILDCARD: the wildcard decl
// for PARTICLE_CHOICE/SEQUENCE/ALL: the particle of the first child
// for PARTICLE_?*+: the child particle
public Object fValue = null;
// for PARTICLE_CHOICE/SEQUENCE/ALL: the particle of the other child
public Object fOtherValue = null;
// minimum occurrence of this particle
public int fMinOccurs = 1;
// maximum occurrence of this particle
public int fMaxOccurs = 1;
private final StringBuffer fBuffer = new StringBuffer();
public String toString() {
// build fBuffering
fBuffer.setLength(0);
appendParticle(fBuffer);
fBuffer.append(" with minOccurs="+fMinOccurs +", maxOccurs="+fMaxOccurs);
return fBuffer.toString();
}
public boolean emptiable() {
return false;
}
void appendParticle(StringBuffer fBuffer) {
switch (fType) {
case PARTICLE_EMPTY:
fBuffer.append("EMPTY");
break;
case PARTICLE_ELEMENT:
case PARTICLE_WILDCARD:
fBuffer.append('(');
fBuffer.append(fValue.toString());
fBuffer.append(')');
break;
case PARTICLE_CHOICE:
case PARTICLE_SEQUENCE:
case PARTICLE_ALL:
if (fType == PARTICLE_ALL)
fBuffer.append("all(");
else
fBuffer.append('(');
fBuffer.append(fValue.toString());
if (fOtherValue != null) {
if (fType == PARTICLE_CHOICE)
fBuffer.append('|');
else
fBuffer.append(',');
fBuffer.append(fOtherValue.toString());
}
fBuffer.append(')');
break;
case PARTICLE_ZERO_OR_ONE:
case PARTICLE_ZERO_OR_MORE:
case PARTICLE_ONE_OR_MORE:
fBuffer.append('(');
fBuffer.append(fValue.toString());
fBuffer.append(')');
if (fType == PARTICLE_ZERO_OR_ONE)
fBuffer.append('?');
if (fType == PARTICLE_ZERO_OR_MORE)
fBuffer.append('*');
if (fType == PARTICLE_ONE_OR_MORE)
fBuffer.append('+');
break;
}
}
} // class XSParticle |
package org.torproject.jtor.socks.impl;
import java.io.IOException;
import java.net.Socket;
import org.torproject.jtor.data.IPv4Address;
public abstract class SocksRequest {
private final Socket socket;
private byte[] addressData;
private IPv4Address address;
private String hostname;
private int port;
protected SocksRequest(Socket socket) {
this.socket = socket;
}
abstract public void readRequest();
abstract public boolean isConnectRequest();
abstract void sendError() throws IOException;
abstract void sendSuccess() throws IOException;
abstract void sendConnectionRefused() throws IOException;
public int getPort() {
return port;
}
public IPv4Address getAddress() {
return address;
}
public boolean hasHostname() {
return hostname != null;
}
public String getHostname() {
return hostname;
}
protected void setPortData(byte[] data) {
if(data.length != 2)
throw new SocksRequestException();
port = ((data[0] & 0xFF) << 8) | (data[1] & 0xFF);
}
protected void setIPv4AddressData(byte[] data) {
if(data.length != 4)
throw new SocksRequestException();
addressData = data;
int addressValue = 0;
for(byte b: addressData) {
addressValue <<= 8;
addressValue |= (b & 0xFF);
}
address = new IPv4Address(addressValue);
}
protected void setHostname(String name) {
hostname = name;
}
protected byte[] readPortData() {
final byte[] data = new byte[2];
readAll(data, 0, 2);
return data;
}
protected byte[] readIPv4AddressData() {
final byte[] data = new byte[4];
readAll(data);
return data;
}
protected byte[] readIPv6AddressData() {
final byte[] data = new byte[16];
readAll(data);
return data;
}
protected String readNullTerminatedString() {
try {
final StringBuilder sb = new StringBuilder();
while(true) {
final int c = socket.getInputStream().read();
if(c == -1)
throw new SocksRequestException();
if(c == 0)
return sb.toString();
char ch = (char) c;
sb.append(ch);
}
} catch (IOException e) {
throw new SocksRequestException(e);
}
}
protected int readByte() {
try {
final int n = socket.getInputStream().read();
if(n == -1)
throw new SocksRequestException();
return n;
} catch (IOException e) {
throw new SocksRequestException(e);
}
}
protected void readAll(byte[] buffer) {
readAll(buffer, 0, buffer.length);
}
protected void readAll(byte[] buffer, int offset, int length) {
try {
while(length > 0) {
int n = socket.getInputStream().read(buffer, offset, length);
if(n == -1)
throw new SocksRequestException();
offset += n;
length -= n;
}
} catch (IOException e) {
throw new SocksRequestException(e);
}
}
protected void socketWrite(byte[] buffer) throws IOException {
socket.getOutputStream().write(buffer);
}
} |
package edu.cmu.lti.bic.sbs.evaluator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import edu.cmu.lti.bic.sbs.engine.Engine;
import edu.cmu.lti.bic.sbs.gson.Drug;
import edu.cmu.lti.bic.sbs.gson.Patient;
import edu.cmu.lti.bic.sbs.gson.Prescription;
import edu.cmu.lti.bic.sbs.gson.Tool;
import edu.cmu.lti.bic.sbs.simulator.MedicalParameter;
// Test class
class BloodPressure implements MedicalParameter {
}
/**
*
* @author victorzhao, xings, ryan sun
*
*/
public class Evaluator {
private double score;
private Path actual;
private Path goldStandard;
private Step currentStep;
private ScoreDP scoreDP;
private long baseTimeInMills = 0;
private String userName;
// private String report;
public Evaluator(Engine engine) {
this.engine = engine;
actual = new Path();
currentStep = new Step();
actual.setTag("Actual");
initGoden();
scoreDP = new ScoreDP();
baseTimeInMills = Calendar.getInstance().getTimeInMillis();
}
/**
* Initialize Golden Standard Path
*
*/
private void initGoden() {
goldStandard = new Path();
goldStandard.setTag("Gold Standard");
goldStandard.add(new Step(new Patient(), new Prescription(), new Tool("codeblue", "Call Code",
0), (int)Calendar.getInstance().getTimeInMillis()));
goldStandard.add(new Step(new Patient(), new Prescription(), new Tool("OxygenMask",
"Face Mask", 100), (int)Calendar.getInstance().getTimeInMillis()));
goldStandard
.add(new Step(new Patient(), new Prescription(new Drug("naloxone", "Naloxone", "naloxone"),
200.0, "mcg"), new Tool(), (int)Calendar.getInstance().getTimeInMillis()));
}
class Report {
double score;
String report;
}
/**
* called by engine to receive the medPara
*
* @param medPara
* , MedicalParameter is an interface in simulator package
*/
public void receivePara(MedicalParameter medPara) {
System.out.println("evaluator.ReceivePara called by engine!");
}
private Engine engine;
// private String report;
// overloading the constructor to support initialize with engine parameter
public void receive(Patient patient, Calendar time) {
currentStep.setPatient(patient);
int curTime = (int)(Calendar.getInstance().getTimeInMillis() - baseTimeInMills);
System.out.print(curTime);
currentStep.setTime(curTime);
System.out.println("Patient added");
updateStep();
}
public void receive(Prescription prescription, Calendar time) {
currentStep.setPrescription(prescription);
int curTime = (int)(Calendar.getInstance().getTimeInMillis() - baseTimeInMills);
currentStep.setTime(curTime);
System.out.println("Evaluator: USER ACTION: USE DRUG:" + prescription.getDrug().getName());
updateStep();
}
public void receive(String name){
this.userName = name;
}
/**
* called by engine to receive the Equipment variables
*
* @param tool
* Equipment is a Class defined in gson package
* @param time
* time used
*/
public void receive(Tool tool, Calendar time) {
currentStep.setTool(tool);
int curTime = (int)(Calendar.getInstance().getTimeInMillis() - baseTimeInMills);
currentStep.setTime(curTime);
System.out.println("Evaluator: USER ACTION: USE TOOL:" + tool.getName());
updateStep();
}
public void receive(Calendar time) {
int curTime = (int)(Calendar.getInstance().getTimeInMillis() - baseTimeInMills);
currentStep.setTime(curTime);
updateStep();
}
public void regularUpdate(Patient p, Calendar time) {
currentStep.setPatient(p);
int curTime = (int)(Calendar.getInstance().getTimeInMillis() - baseTimeInMills);
currentStep.setTime(curTime);
if (isSimEnd()) {
calculateScore();
engine.simOver(score, generateReport());
}
}
public State lastHealthyState(){
int i = actual.size() - 1;
while(actual.get(i).getPatient().isConditionBad()){
i
if (i < 0) return null;
}
Step lastHealthy = actual.get(i);
State result = new State();
result.setPatient(lastHealthy.getPatient());
while(i >= 0){
result.getPrescriptions().add(actual.get(i).getPrescription());
result.getTools().add(actual.get(i).getTool());
}
return result;
}
public boolean isSimEnd() {
if (actual.size() == 0) return false;
int timeNow = currentStep.getTime();
int timeLast = actual.get(actual.size() - 1).getTime();
Patient p = currentStep.getPatient();
return 60000 < timeNow-timeLast && (p.isConditionStable() || p.isConditionBad());
}
/**
* called by engine to receive the Equipment variables
*
* @param tool
* Equipment is a Class defined in gson package
* @param time
* time used
*/
public void calculateScore() {
scoreDP.scoreDP(goldStandard, actual);
score = this.getPatientScore();
}
public void calculateScorePending() {
scoreDP.scoreDPpending(goldStandard, actual);
score = this.getPatientScore();
}
public double getScore() {
return score;
}
public double getPatientScore(){
return actual.patientScore();
}
public void updateStep() {
if (currentStep.isComplete()) {
actual.add(currentStep);
currentStep = new Step();
}
}
public String toString() {
return "The score is " + score;
}
public void setInitialTime(Calendar initTime) {
}
private String generateReport() {
PrintWriter writer = null;
try {
writer = new PrintWriter("src/test/resources/report.json", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gson gson = new Gson();
Report r = new Report();
r.report = this.toString();
r.score = this.score;
String report = gson.toJson(r);
writer.println(report);
writer.close();
// Add the traceback information
StringBuilder sb = new StringBuilder(report);
sb.append("\n");
sb.append("Patient score is: ");
sb.append(getPatientScore());
sb.append("\n");
sb.append("The user's correct actions are :" + "\n");
for (Step s : scoreDP.getBacktrack()) {
sb.append(s.getStep());
// sb.append("\n");
}
System.out.println(sb.toString());
// generate the txt report
String reportTxt = txtReportGenerator(score);
// TODO: Set the patient score.
// Where can I set the patie<nt score??
return reportTxt;
}
public static Path loadGS(String filepath) throws Exception{
String str;
try {
File file = new File(filepath);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
str = new String(data, "UTF-8");
} catch (Exception e) {
throw e;
}
Gson gson = new Gson();
Path gs;
try {
gs = gson.fromJson(str, Path.class);
} catch (JsonSyntaxException e) {
throw new Exception(e);
}
return gs;
}
private String txtReportGenerator(double score){
String outputFile = "Report.txt";
StringBuilder output = new StringBuilder();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile, false));
output.append("Here is the report for ");
output.append(userName + ":" + "\n");
output.append("The final score " + userName + " get is : "
+ String.format("%.2f\n", score));
output.append("The helpful steps and details "
+ userName + " did is listed below : \n");
output.append("Action Time\t Drug Used\t\t Drug Dose\t Drug Unit\t\t Action\n");
for (Step s : scoreDP.getBacktrack()) {
output.append(s.getStep());
// sb.append("\n");
}
output.append("\nThe actual steps and details "
+ userName + " did are listed below : \n");
output.append("Action Time\t Drug Used\t\t Drug Dose\t Drug Unit\t\t Action\n");
for (Step s : actual) {
output.append(s.getStep());
// sb.append("\n");
}
output.append("\n The suggested actions are listed below : \n");
output.append("Action Time\t Drug Used\t\t Drug Dose\t Drug Unit\t\t Action\n");
for (Step s : goldStandard) {
output.append(s.getStep());
// sb.append("\n");
}
// Print the patient state
if (actual.getBpHighTime()>0)
output.append("The patient\'s blood pressure is too high for " +actual.getBpHighTime()+ " seconds\n");
if (actual.getBpLowTime()>0)
output.append("The patient\'s blood pressure is too low for " +actual.getBpLowTime()+ " seconds\n");
if(actual.getHrHighTime()>0)
output.append("The patient\'s heart rate is too high for " +actual.getHrHighTime()+ " seconds\n");
if(actual.getHrLowTime()>0)
output.append("The patient\'s heart rate is too low for " +actual.getHrLowTime()+ " seconds\n");
if(actual.getOlTime()>0)
output.append("The patient\'s oxygen level is too low for " +actual.getOlTime()+ " seconds\n");
if(actual.getRrHighTime()>0)
output.append("The patient\'s respiratory rate is too high for " +actual.getRrHighTime()+ " seconds\n");
if(actual.getRrLowTime()>0)
output.append("The patient\'s respiratory rate is too low for " +actual.getRrLowTime()+ " seconds\n");
bw.write(output.toString());
System.out.println(output);
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
// Main method for testing
public static void main(String[] args) {
// Test for generate the path gson for Xing Sun to write the json file.
Gson gson = new Gson();
ArrayList<Step> a = new ArrayList<Step>();
a.add(new Step(new Patient(), new Prescription(), new Tool("codeblue", "Call Code",
0), (int)Calendar.getInstance().getTimeInMillis()));
a.add(new Step(new Patient(), new Prescription(), new Tool("codeblue", "Call Code",
0), (int)Calendar.getInstance().getTimeInMillis()));
a.add(new Step(new Patient(), new Prescription(), new Tool("codeblue", "Call Code",
0), (int)Calendar.getInstance().getTimeInMillis()));
System.out.println(gson.toJson(a));
}
} |
package org.apache.xerces.impl.xs;
/**
* Store schema particle declaration.
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class XSParticleDecl {
// types of particles
public static final short PARTICLE_EMPTY = 0;
public static final short PARTICLE_ELEMENT = 1;
public static final short PARTICLE_WILDCARD = 2;
public static final short PARTICLE_CHOICE = 3;
public static final short PARTICLE_SEQUENCE = 4;
public static final short PARTICLE_ALL = 5;
public static final short PARTICLE_ZERO_OR_ONE = 6;
public static final short PARTICLE_ZERO_OR_MORE = 7;
public static final short PARTICLE_ONE_OR_MORE = 8;
// type of the particle
public short fType = PARTICLE_EMPTY;
// left-hand value of the particle
// for PARTICLE_ELEMENT : the element decl
// for PARTICLE_WILDCARD: the wildcard decl
// for PARTICLE_CHOICE/SEQUENCE/ALL: the particle of the first child
// for PARTICLE_?*+: the child particle
public Object fValue = null;
// for PARTICLE_CHOICE/SEQUENCE/ALL: the particle of the other child
public Object fOtherValue = null;
// minimum occurrence of this particle
public int fMinOccurs = 1;
// maximum occurrence of this particle
public int fMaxOccurs = 1;
// clone this decl
public XSParticleDecl clone(boolean deep) {
XSParticleDecl particle = new XSParticleDecl();
particle.fType = fType;
particle.fMinOccurs = fMinOccurs;
particle.fMaxOccurs = fMaxOccurs;
particle.fDescription = fDescription;
// if it's not a deep clone, or it's a leaf particle
// just copy value and other value
if (!deep ||
fType == PARTICLE_EMPTY ||
fType == PARTICLE_ELEMENT ||
fType == PARTICLE_WILDCARD) {
particle.fValue = fValue;
particle.fOtherValue = fOtherValue;
}
// otherwise, we have to make clones of value and other value
else {
if (fValue != null) {
particle.fValue = ((XSParticleDecl)fValue).clone(deep);
}
else {
particle.fValue = null;
}
if (fOtherValue != null) {
particle.fOtherValue = ((XSParticleDecl)fOtherValue).clone(deep);
}
else {
particle.fOtherValue = null;
}
}
return particle;
}
/**
* 3.9.6 Schema Component Constraint: Particle Emptiable
* whether this particle is emptible
*/
public boolean emptiable() {
return minEffectiveTotalRange() == 0;
}
public boolean isEmpty() {
if (fType==PARTICLE_ELEMENT || fType==PARTICLE_WILDCARD) return false;
if (fType==PARTICLE_EMPTY) return true;
boolean leftIsEmpty = (fValue==null || ((XSParticleDecl)fValue).isEmpty());
boolean rightIsEmpty = (fOtherValue==null ||
((XSParticleDecl)fOtherValue).isEmpty());
return (leftIsEmpty && rightIsEmpty) ;
}
/**
* 3.8.6 Effective Total Range (all and sequence) and
* Effective Total Range (choice)
* The following methods are used to return min/max range for a particle.
* They are not exactly the same as it's described in the spec, but all the
* values from the spec are retrievable by these methods.
*/
public int minEffectiveTotalRange() {
switch (fType) {
case PARTICLE_ALL:
case PARTICLE_SEQUENCE:
return minEffectiveTotalRangeAllSeq();
case PARTICLE_CHOICE:
return minEffectiveTotalRangeChoice();
default:
return fMinOccurs;
}
}
private int minEffectiveTotalRangeAllSeq() {
int fromLeft = ((XSParticleDecl)fValue).minEffectiveTotalRange();
if (fOtherValue != null)
fromLeft += ((XSParticleDecl)fOtherValue).minEffectiveTotalRange();
return fMinOccurs * fromLeft;
}
private int minEffectiveTotalRangeChoice() {
int fromLeft = ((XSParticleDecl)fValue).minEffectiveTotalRange();
if (fOtherValue != null) {
int fromRight = ((XSParticleDecl)fOtherValue).minEffectiveTotalRange();
if (fromRight < fromLeft)
fromLeft = fromRight;
}
return fMinOccurs * fromLeft;
}
public int maxEffectiveTotalRange() {
switch (fType) {
case PARTICLE_ALL:
case PARTICLE_SEQUENCE:
return maxEffectiveTotalRangeAllSeq();
case PARTICLE_CHOICE:
return maxEffectiveTotalRangeChoice();
default:
return fMaxOccurs;
}
}
private int maxEffectiveTotalRangeAllSeq() {
int fromLeft = ((XSParticleDecl)fValue).maxEffectiveTotalRange();
if (fromLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
if (fOtherValue != null) {
int fromRight = ((XSParticleDecl)fOtherValue).maxEffectiveTotalRange();
if (fromRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
fromLeft += fromRight;
}
if (fromLeft != 0 && fMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
return fMaxOccurs * fromLeft;
}
private int maxEffectiveTotalRangeChoice() {
int fromLeft = ((XSParticleDecl)fValue).maxEffectiveTotalRange();
if (fromLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
if (fOtherValue != null) {
int fromRight = ((XSParticleDecl)fOtherValue).maxEffectiveTotalRange();
if (fromRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
if (fromRight < fromLeft)
fromLeft = fromRight;
}
if (fromLeft != 0 && fMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
return fMaxOccurs * fromLeft;
}
/**
* get the string description of this particle
*/
private String fDescription = null;
public String toString() {
if (fDescription == null) {
StringBuffer buffer = new StringBuffer();
appendParticle(buffer);
if (!(fMinOccurs == 0 && fMaxOccurs == 0 ||
fMinOccurs == 1 && fMaxOccurs == 1)) {
buffer.append("{" + fMinOccurs);
if (fMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)
buffer.append("-UNBOUNDED");
else if (fMinOccurs != fMaxOccurs)
buffer.append("-" + fMaxOccurs);
buffer.append("}");
}
fDescription = buffer.toString();
}
return fDescription;
}
/**
* append the string description of this particle to the string buffer
* this is for error message.
*/
void appendParticle(StringBuffer fBuffer) {
switch (fType) {
case PARTICLE_EMPTY:
fBuffer.append("EMPTY");
break;
case PARTICLE_ELEMENT:
case PARTICLE_WILDCARD:
fBuffer.append('(');
fBuffer.append(fValue.toString());
fBuffer.append(')');
break;
case PARTICLE_CHOICE:
case PARTICLE_SEQUENCE:
case PARTICLE_ALL:
if (fOtherValue == null) {
fBuffer.append(fValue.toString());
} else {
if (fType == PARTICLE_ALL)
fBuffer.append("all(");
else
fBuffer.append('(');
fBuffer.append(fValue.toString());
if (fType == PARTICLE_CHOICE)
fBuffer.append('|');
else
fBuffer.append(',');
fBuffer.append(fOtherValue.toString());
fBuffer.append(')');
}
break;
}
}
public void reset(){
fType = PARTICLE_EMPTY;
fValue = null;
fOtherValue = null;
fMinOccurs = 1;
fMaxOccurs = 1;
}
} // class XSParticle |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.