answer
stringlengths
17
10.2M
package org.codejargon.fluentjdbc.internal.query; import org.codejargon.fluentjdbc.api.FluentJdbcException; import org.codejargon.fluentjdbc.internal.query.namedparameter.NamedTransformedSql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import java.util.Optional; class PreparedStatementFactory { private final QueryConfig config; PreparedStatementFactory(QueryConfig config) { this.config = config; } PreparedStatement createSingle(Connection con, SingleQuerySpecification querySpec) throws SQLException { SqlAndParams sqlAndParams = querySpec.sqlAndParams(config); PreparedStatement statement = prepareStatement(con, sqlAndParams.sql()); singleQueryCustomization(statement, querySpec); assignParams(statement, sqlAndParams.params()); return statement; } PreparedStatement createBatch(Connection con, String sql) throws SQLException { return prepareStatement(con, sql); } PreparedStatement createBatch(Connection con, NamedTransformedSql namedTransformedSql) throws SQLException { return prepareStatement(con, namedTransformedSql.sql()); } void assignParams(PreparedStatement statement, List<Object> params) throws SQLException { config.paramAssigner.assignParams(statement, params); } private void singleQueryCustomization(PreparedStatement statement, SingleQuerySpecification querySpec) throws SQLException { if(querySpec.select.isPresent()) { selectCustomization(statement, querySpec); } } private void selectCustomization(PreparedStatement statement, SingleQuerySpecification querySpec) throws SQLException { selectFetchSize(statement, querySpec.select.get().fetchSize); maxResults(statement, querySpec.select.get().maxRows); } private void selectFetchSize(PreparedStatement statement, Optional<Integer> selectFetchSize) throws SQLException { Optional<Integer> activeFetchSize = config.fetchSize(selectFetchSize); if (activeFetchSize.isPresent()) { statement.setFetchSize(activeFetchSize.get()); } } private void maxResults(PreparedStatement statement, Optional<Long> maxResults) throws SQLException { if(maxResults.isPresent()) { if(maxResults.get() > Integer.MAX_VALUE) { setLargeMaxRows(statement, maxResults); } else { statement.setMaxRows((int) maxResults.get().longValue()); } } } private void setLargeMaxRows(PreparedStatement statement, Optional<Long> maxResults) throws SQLException { try { statement.setLargeMaxRows(maxResults.get()); } catch(SQLException e) { throw new FluentJdbcException( String.format( "The JDBC driver %s doesn't support setLargeMaxRows(). Set max results <= Integer.MAX_VALUE", statement.getConnection().getMetaData().getDriverName()) ); } } private PreparedStatement prepareStatement(Connection con, String sql) throws SQLException { return con.prepareStatement(sql); } }
package com.tinkerpop.gremlin.structure.io.graphson; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; import java.util.Optional; public class GraphSONObjectMapper extends ObjectMapper { public GraphSONObjectMapper() { this(null, false); } public GraphSONObjectMapper(final SimpleModule custom) { this(custom, false); } public GraphSONObjectMapper(final SimpleModule custom, final boolean loadExternalModules) { disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // this provider toStrings all unknown classes and converts keys in Map objects that are Object to String. final DefaultSerializerProvider provider = new GraphSONSerializerProvider(); provider.setDefaultKeySerializer(new GraphSONModule.GraphSONKeySerializer()); setSerializerProvider(provider); registerModule(new GraphSONModule()); Optional.ofNullable(custom).ifPresent(this::registerModule); // plugin external serialization modules if (loadExternalModules) findAndRegisterModules(); } }
package com.tinkerpop.gremlin.driver.ser; import com.tinkerpop.gremlin.driver.MessageSerializer; import com.tinkerpop.gremlin.driver.message.ResponseMessage; import com.tinkerpop.gremlin.driver.message.ResponseStatusCode; import com.tinkerpop.gremlin.structure.Compare; import com.tinkerpop.gremlin.structure.Edge; import com.tinkerpop.gremlin.structure.Graph; import com.tinkerpop.gremlin.structure.Vertex; import com.tinkerpop.gremlin.structure.util.detached.DetachedEdge; import com.tinkerpop.gremlin.structure.util.detached.DetachedVertex; import com.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory; import com.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import com.tinkerpop.gremlin.util.StreamFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class KryoMessageSerializerV1d0Test { private UUID requestId = UUID.fromString("6457272A-4018-4538-B9AE-08DD5DDC0AA1"); private ResponseMessage.Builder responseMessageBuilder = ResponseMessage.build(requestId); private static ByteBufAllocator allocator = UnpooledByteBufAllocator.DEFAULT; public MessageSerializer serializer = new KryoMessageSerializerV1d0(); @Test public void serializeIterable() throws Exception { final ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(100); final ResponseMessage response = convert(list); assertCommon(response); final List<Integer> deserializedFunList = (List<Integer>) response.getResult().getData(); assertEquals(2, deserializedFunList.size()); assertEquals(new Integer(1), deserializedFunList.get(0)); assertEquals(new Integer(100), deserializedFunList.get(1)); } @Test public void serializeIterableWithNull() throws Exception { final ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(null); list.add(100); final ResponseMessage response = convert(list); assertCommon(response); final List<Integer> deserializedFunList = (List<Integer>) response.getResult().getData(); assertEquals(3, deserializedFunList.size()); assertEquals(new Integer(1), deserializedFunList.get(0)); assertNull(deserializedFunList.get(1)); assertEquals(new Integer(100), deserializedFunList.get(2)); } @Test public void serializeMap() throws Exception { final Map<String, Object> map = new HashMap<>(); final Map<String, String> innerMap = new HashMap<>(); innerMap.put("a", "b"); map.put("x", 1); map.put("y", "some"); map.put("z", innerMap); final ResponseMessage response = convert(map); assertCommon(response); final Map<String, Object> deserializedMap = (Map<String, Object>) response.getResult().getData(); assertEquals(3, deserializedMap.size()); assertEquals(1, deserializedMap.get("x")); assertEquals("some", deserializedMap.get("y")); final Map<String, String> deserializedInnerMap = (Map<String, String>) deserializedMap.get("z"); assertEquals(1, deserializedInnerMap.size()); assertEquals("b", deserializedInnerMap.get("a")); } @Test public void serializeEdge() throws Exception { final Graph g = TinkerGraph.open(); final Vertex v1 = g.addVertex(); final Vertex v2 = g.addVertex(); final Edge e = v1.addEdge("test", v2); e.property("abc", 123); final Iterable<Edge> iterable = g.E().toList(); final ResponseMessage response = convert(iterable); assertCommon(response); final List<DetachedEdge> edgeList = (List<DetachedEdge>) response.getResult().getData(); assertEquals(1, edgeList.size()); final DetachedEdge deserialiedEdge = edgeList.get(0); assertEquals(2l, deserialiedEdge.id()); assertEquals("test", deserialiedEdge.label()); assertEquals(new Integer(123), (Integer) deserialiedEdge.value("abc")); assertEquals(1, StreamFactory.stream(deserialiedEdge.properties()).count()); assertEquals(0l, deserialiedEdge.outV().id().next()); assertEquals(Vertex.DEFAULT_LABEL, deserialiedEdge.outV().label().next()); assertEquals(1l, deserialiedEdge.inV().id().next()); assertEquals(Vertex.DEFAULT_LABEL, deserialiedEdge.inV().label().next()); } @Test public void serializeVertexWithEmbeddedMap() throws Exception { final Graph g = TinkerGraph.open(); final Vertex v = g.addVertex(); final Map<String, Object> map = new HashMap<>(); map.put("x", 500); map.put("y", "some"); final ArrayList<Object> friends = new ArrayList<>(); friends.add("x"); friends.add(5); friends.add(map); v.property("friends", friends); final List list = g.V().toList(); final ResponseMessage response = convert(list); assertCommon(response); final List<DetachedVertex> vertexList = (List<DetachedVertex>) response.getResult().getData(); assertEquals(1, vertexList.size()); final DetachedVertex deserializedVertex = vertexList.get(0); assertEquals(0l, deserializedVertex.id()); assertEquals(Vertex.DEFAULT_LABEL, deserializedVertex.label()); assertEquals(1, deserializedVertex.properties().count().next().intValue()); final List<Object> deserializedInnerList = deserializedVertex.value("friends"); assertEquals(3, deserializedInnerList.size()); assertEquals("x", deserializedInnerList.get(0)); assertEquals(5, deserializedInnerList.get(1)); final Map<String, Object> deserializedInnerInnerMap = (Map<String, Object>) deserializedInnerList.get(2); assertEquals(2, deserializedInnerInnerMap.size()); assertEquals(500, deserializedInnerInnerMap.get("x")); assertEquals("some", deserializedInnerInnerMap.get("y")); } @Test public void serializeToMapWithElementForKey() throws Exception { final TinkerGraph g = TinkerFactory.createClassic(); final Map<Vertex, Integer> map = new HashMap<>(); map.put(g.V().<Vertex>has("name", Compare.EQUAL, "marko").next(), 1000); final ResponseMessage response = convert(map); assertCommon(response); final Map<Vertex, Integer> deserializedMap = (Map<Vertex, Integer>) response.getResult().getData(); assertEquals(1, deserializedMap.size()); final Vertex deserializedMarko = deserializedMap.keySet().iterator().next(); assertEquals("marko", deserializedMarko.value("name").toString()); assertEquals(1, deserializedMarko.id()); assertEquals(Vertex.DEFAULT_LABEL, deserializedMarko.label()); assertEquals(new Integer(29), (Integer) deserializedMarko.value("age")); assertEquals(2, StreamFactory.stream(deserializedMarko.properties()).count()); assertEquals(new Integer(1000), deserializedMap.values().iterator().next()); } @Test public void serializeFullResponseMessage() throws Exception { final UUID id = UUID.randomUUID(); final Map<String,Object> metaData = new HashMap<>(); metaData.put("test", "this"); metaData.put("one", 1); final Map<String,Object> attributes = new HashMap<>(); attributes.put("test", "that"); attributes.put("two", 2); final ResponseMessage response = ResponseMessage.build(id) .responseMetaData(metaData) .code(ResponseStatusCode.SUCCESS) .result("some-result") .statusAttributes(attributes) .statusMessage("worked") .create(); final ByteBuf bb = serializer.serializeResponseAsBinary(response, allocator); final ResponseMessage deserialized = serializer.deserializeResponse(bb); assertEquals(id, deserialized.getRequestId()); assertEquals("this", deserialized.getResult().getMeta().get("test")); assertEquals(1, deserialized.getResult().getMeta().get("one")); assertEquals("some-result", deserialized.getResult().getData()); assertEquals("that", deserialized.getStatus().getAttributes().get("test")); assertEquals(2, deserialized.getStatus().getAttributes().get("two")); assertEquals(ResponseStatusCode.SUCCESS.getValue(), deserialized.getStatus().getCode().getValue()); assertEquals("worked", deserialized.getStatus().getMessage()); } private void assertCommon(final ResponseMessage response) { assertEquals(requestId, response.getRequestId()); assertEquals(ResponseStatusCode.SUCCESS, response.getStatus().getCode()); } private ResponseMessage convert(final Object toSerialize) throws SerializationException { final ByteBuf bb = serializer.serializeResponseAsBinary(responseMessageBuilder.result(toSerialize).create(), allocator); return serializer.deserializeResponse(bb); } }
package org.genericsystem.distributed.cacheonserver.ui.table; import java.util.Arrays; import java.util.List; import java.util.function.Function; import javafx.collections.ObservableList; import org.genericsystem.common.Generic; import org.genericsystem.distributed.ui.models.GenericCompositeModel; import org.genericsystem.distributed.ui.models.GenericModel; /** * @author Nicolas Feybesse * */ public class TypeTableModel extends GenericCompositeModel<InstanceRowModel> { public TypeTableModel(Generic generic, List<Function<Generic[], ObservableList<Generic>>> observableListExtractors) { this(generic, observableListExtractors, InstanceRowModel::new, GenericCompositeModel<GenericModel>::new, GenericModel::new); } public TypeTableModel(Generic generic, Function<Generic, String> stringExtractor, ObservableList<Generic> attributes) { this(generic, stringExtractor, Arrays.<Function<Generic[], ObservableList<Generic>>> asList(generics -> generics[0].getObservableSubInstances(), generics -> attributes, generics -> generics[0].getObservableHolders(generics[1])), InstanceRowModel::new, GenericCompositeModel<GenericModel>::new, GenericModel::new); } public TypeTableModel(Generic generic, List<Function<Generic[], ObservableList<Generic>>> observableListExtractors, Function<CompositeConf<GenericCompositeModel<GenericModel>>, InstanceRowModel> rowBuilder, Function<CompositeConf<GenericModel>, GenericCompositeModel<GenericModel>> cellBuilder, Function<Generic, GenericModel> subCellBuilder) { this(generic, g -> GenericModel.SIMPLE_CLASS_EXTRACTOR.apply(g) + "(s) Management", observableListExtractors, rowBuilder, cellBuilder, subCellBuilder); } public TypeTableModel(Generic generic, List<Function<Generic, String>> stringExtractors, List<Function<Generic[], ObservableList<Generic>>> observableListExtractors, Function<CompositeConf<GenericCompositeModel<GenericModel>>, InstanceRowModel> rowBuilder, Function<CompositeConf<GenericModel>, GenericCompositeModel<GenericModel>> cellBuilder, Function<Generic, GenericModel> subCellBuilder) { super(new CompositeConf<>(generic, stringExtractors.get(0), observableListExtractors.get(0))); init(buildBuilder(rowBuilder, cellBuilder, stringExtractors, observableListExtractors, subCellBuilder)); } public static Function<Generic, GenericCompositeModel<?>> getBuilder(List<Function<CompositeConf<GenericCompositeModel<?>>, GenericCompositeModel<?>>> builders, List<Function<Generic, String>> stringExtractors, List<Function<Generic[], ObservableList<Generic>>> observableListExtractors) { Function<Generic, GenericCompositeModel<?>> subCellBuild = holder -> builders.get(3).apply(new CompositeConf<>(holder, stringExtractors.get(3), observableListExtractors.get(3), null)); Function<Generic, GenericCompositeModel<?>> cellBuild = attribute -> builders.get(2).apply(new CompositeConf<>(attribute, stringExtractors.get(2), observableListExtractors.get(2), subCellBuild)); Function<Generic, GenericCompositeModel<?>> rowBuild = instance -> builders.get(1).apply(new CompositeConf<>(instance, stringExtractors.get(1), observableListExtractors.get(1), cellBuild)); Function<Generic, GenericCompositeModel<?>> tableBuild = type -> builders.get(0).apply(new CompositeConf<>(type, stringExtractors.get(0), observableListExtractors.get(0), rowBuild)); return tableBuild; } }
package org.jboss.as.console.client.shared.subsys.picketlink; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.SplitLayoutPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ProvidesKey; import com.google.inject.Inject; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.NameTokens; import org.jboss.as.console.client.core.SuspendableViewImpl; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.preview.PreviewContent; import org.jboss.as.console.client.preview.PreviewContentFactory; import org.jboss.as.console.client.widgets.nav.v3.ClearFinderSelectionEvent; import org.jboss.as.console.client.widgets.nav.v3.ColumnManager; import org.jboss.as.console.client.widgets.nav.v3.ContextualCommand; import org.jboss.as.console.client.widgets.nav.v3.FinderColumn; import org.jboss.as.console.client.widgets.nav.v3.MenuDelegate; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; import org.jboss.dmr.client.Property; import java.util.List; import static org.jboss.as.console.client.shared.subsys.picketlink.PicketLinkDirectory.FEDERATION_REQUEST_PARAM; import static org.jboss.as.console.client.shared.subsys.picketlink.PicketLinkDirectory.SERVICE_PROVIDER_REQUEST_PARAM; import static org.jboss.as.console.client.widgets.nav.v3.FinderColumn.FinderId.CONFIGURATION; import static org.jboss.as.console.client.widgets.nav.v3.MenuDelegate.Role.Navigation; import static org.jboss.as.console.client.widgets.nav.v3.MenuDelegate.Role.Operation; /** * @author Harald Pehl */ public class PicketLinkFinderView extends SuspendableViewImpl implements PicketLinkFinder.MyView { interface Template extends SafeHtmlTemplates { @Template("<div class=\"{0}\">{1}</div>") SafeHtml item(String cssClass, String title); @Template("<div class='preview-content'><h1>{0}</h1><ul>" + "<li>Identity Provider: {1}</li>" + "<li>Security Domain: {2}</li>" + "<li>URL: {3}</li>" + "</ul></div>") SafeHtml federationPreview(String name, String identityProvider, String securityDomain, String url); @Template("<div class='preview-content'><h1>{0}</h1><ul>" + "<li>Security Domain: {1}</li>" + "<li>URL: {2}</li>" + "</ul></div>") SafeHtml serviceProviderPreview(String name, String securityDomain, String url); } private static final Template TEMPLATE = GWT.create(Template.class); private final PlaceManager placeManager; private final PreviewContentFactory contentFactory; private PicketLinkFinder presenter; private LayoutPanel previewCanvas; private ColumnManager columnManager; private FinderColumn<Property> federationsColumn; private Widget federationsColumnWidget; private FinderColumn<Property> serviceProviderColumn; private Widget serviceProviderColumnWidget; @Inject public PicketLinkFinderView(final PlaceManager placeManager, final PreviewContentFactory contentFactory) { this.placeManager = placeManager; this.contentFactory = contentFactory; } @Override @SuppressWarnings("unchecked") public Widget createWidget() { previewCanvas = new LayoutPanel(); SplitLayoutPanel layout = new SplitLayoutPanel(2); columnManager = new ColumnManager(layout, CONFIGURATION); serviceProviderColumn = new FinderColumn<>(CONFIGURATION, "Service Provider", new FinderColumn.Display<Property>() { @Override public boolean isFolder(final Property data) { return false; } @Override public SafeHtml render(final String baseCss, final Property data) { return TEMPLATE.item(baseCss, data.getName()); } @Override public String rowCss(final Property data) { return ""; } }, new ProvidesKey<Property>() { @Override public Object getKey(final Property data) { return data.getName(); } }, presenter.getProxy().getNameToken()); serviceProviderColumn.setTopMenuItems( new MenuDelegate<>(Console.CONSTANTS.common_label_add(), (ContextualCommand<Property>) item -> presenter.launchAddServiceProviderDialog(federationsColumn.getSelectedItem().getName()), Operation)); serviceProviderColumn.setMenuItems( new MenuDelegate<>(Console.CONSTANTS.common_label_view(), (ContextualCommand<Property>) item -> { PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.PicketLinkServiceProvider) .with(FEDERATION_REQUEST_PARAM, federationsColumn.getSelectedItem().getName()) .with(SERVICE_PROVIDER_REQUEST_PARAM, item.getName()) .build(); placeManager.revealRelativePlace(placeRequest); }, Navigation), new MenuDelegate<>(Console.CONSTANTS.common_label_delete(), (ContextualCommand<Property>) item -> { if (serviceProviderColumn.hasSelectedItem()) { Property selectedItem = serviceProviderColumn.getSelectedItem(); Feedback.confirm(Console.MESSAGES.deleteTitle("Service Provider"), Console.MESSAGES.deleteConfirm(selectedItem.getName()), isConfirmed -> { if (isConfirmed) { presenter.removeServiceProvider( federationsColumn.getSelectedItem().getName(), selectedItem); } }); } }, Operation)); serviceProviderColumn.addSelectionChangeHandler(selectionChangeEvent -> { if (serviceProviderColumn.hasSelectedItem()) { columnManager.updateActiveSelection(serviceProviderColumnWidget); } }); serviceProviderColumn.setPreviewFactory((data, callback) -> { String name = data.getName(); ModelNode serviceProvider = data.getValue(); String securityDomain = serviceProvider.get("security-domain").asString(); String url = serviceProvider.get("url").asString(); callback.onSuccess(TEMPLATE.serviceProviderPreview(name, securityDomain, url)); }); serviceProviderColumnWidget = serviceProviderColumn.asWidget(); federationsColumn = new FinderColumn<>(CONFIGURATION, "Federation", new FinderColumn.Display<Property>() { @Override public boolean isFolder(final Property data) { return true; } @Override public SafeHtml render(final String baseCss, final Property data) { return TEMPLATE.item(baseCss, data.getName()); } @Override public String rowCss(final Property data) { return ""; } }, new ProvidesKey<Property>() { @Override public Object getKey(final Property data) { return data.getName(); } }, presenter.getProxy().getNameToken()); federationsColumn.setTopMenuItems( new MenuDelegate<>(Console.CONSTANTS.common_label_add(), (ContextualCommand<Property>) item -> presenter.launchAddFederationDialog(), Operation)); federationsColumn.setMenuItems( new MenuDelegate<>(Console.CONSTANTS.common_label_view(), (ContextualCommand<Property>) item -> { PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.PicketLinkFederation) .with(FEDERATION_REQUEST_PARAM, item.getName()).build(); placeManager.revealRelativePlace(placeRequest); }, Navigation), new MenuDelegate<>(Console.CONSTANTS.common_label_delete(), (ContextualCommand<Property>) item -> { if (federationsColumn.hasSelectedItem()) { Property selectedItem = federationsColumn.getSelectedItem(); Feedback.confirm(Console.MESSAGES.deleteTitle("Federation"), Console.MESSAGES.deleteConfirm(selectedItem.getName()), isConfirmed -> { if (isConfirmed) { presenter.removeFederation(selectedItem); } }); } }, Operation)); federationsColumn.addSelectionChangeHandler(selectionChangeEvent -> { columnManager.reduceColumnsTo(1); if (federationsColumn.hasSelectedItem()) { columnManager.updateActiveSelection(federationsColumnWidget); columnManager.appendColumn(serviceProviderColumnWidget); presenter.readServiceProvider(federationsColumn.getSelectedItem().getName()); } else { startupContent(contentFactory); } }); federationsColumn.setPreviewFactory((data, callback) -> { String name = data.getName(); String identityProvider = "n/a"; String securityDomain = "n/a"; String url = "n/a"; if (data.getValue().get("identity-provider").isDefined()) { Property property = data.getValue().get("identity-provider").asProperty(); identityProvider = property.getName(); securityDomain = property.getValue().get("security-domain").asString(); url = property.getValue().get("url").asString(); } callback.onSuccess(TEMPLATE.federationPreview(name, identityProvider, securityDomain, url)); }); federationsColumnWidget = federationsColumn.asWidget(); columnManager.addWest(federationsColumnWidget); columnManager.addWest(serviceProviderColumnWidget); columnManager.add(previewCanvas); columnManager.setInitialVisible(1); return layout; } @Override public void setPresenter(final PicketLinkFinder presenter) { this.presenter = presenter; } @Override public void updateFederations(final List<Property> federations) { federationsColumn.updateFrom(federations); } @Override public void updateServiceProvider(final List<Property> serviceProvider) { serviceProviderColumn.updateFrom(serviceProvider); } @Override public void setPreview(final SafeHtml html) { Scheduler.get().scheduleDeferred(() -> { previewCanvas.clear(); previewCanvas.add(new HTML(html)); }); } @Override public void toggleScrolling(final boolean enforceScrolling, final int requiredWidth) { columnManager.toogleScrolling(enforceScrolling, requiredWidth); } public void clearActiveSelection(final ClearFinderSelectionEvent event) { federationsColumnWidget.getElement().removeClassName("active"); serviceProviderColumnWidget.getElement().removeClassName("active"); } private void startupContent(PreviewContentFactory contentFactory) { contentFactory.createContent(PreviewContent.INSTANCE.picketlink_federations(), new SimpleCallback<SafeHtml>() { @Override public void onSuccess(SafeHtml previewContent) { setPreview(previewContent); } } ); } }
package com.inepex.ineom.shared.assistedobject; import com.inepex.ineom.shared.AssistedObjectHandler; import com.inepex.ineom.shared.AssistedObjectHandlerFactory; import com.inepex.ineom.shared.IFConsts; import com.inepex.ineom.shared.IneList; import com.inepex.ineom.shared.PropHandler; import com.inepex.ineom.shared.Relation; import com.inepex.ineom.shared.descriptor.fdesc.FDesc; import com.inepex.ineom.shared.descriptor.fdesc.RelationFDesc; import com.inepex.ineom.shared.descriptorstore.DescriptorStore; public class AssistedObjectBuilderFactoryBase{ protected final DescriptorStore descStore; protected final AssistedObjectHandlerFactory aoHandlerFactory; protected final PropHandler propHandler; public AssistedObjectBuilderFactoryBase(DescriptorStore descStore, AssistedObjectHandlerFactory aoHandlerFactory, PropHandler propHandler) { this.descStore = descStore; this.aoHandlerFactory = aoHandlerFactory; this.propHandler = propHandler; } @SuppressWarnings("unchecked") protected class BuilderBase<T> { protected final AssistedObjectHandler ao; protected final T object; protected BuilderBase(AssistedObjectHandler ao) { this.ao=ao; object = (T)this; } public T set(String key, Boolean value){ ao.set(key, value); return object; } public T set(String key, Double value){ ao.set(key, value); return object; } public T set(String key, IneList value){ ao.set(key, value); return object; } public T set(String key, Long value) { ao.set(key, value); return object; } public T set(String key, Relation value){ ao.set(key, value); return object; } public T set(String key, String relationKey, String value){ checkAndCreateRelation(key); aoHandlerFactory.createHandler(ao.getRelation(key).getKvo()).set(relationKey, value); return object; } public T set(String key, String relationKey, Long value){ checkAndCreateRelation(key); aoHandlerFactory.createHandler(ao.getRelation(key).getKvo()).set(relationKey, value); if (relationKey.equals(IFConsts.KEY_ID)) ao.getRelation(key).setId(value); return object; } public T set(String key, String relationKey, Boolean value){ checkAndCreateRelation(key); aoHandlerFactory.createHandler(ao.getRelation(key).getKvo()).set(relationKey, value); return object; } public T set(String key, String relationKey, Double value){ checkAndCreateRelation(key); aoHandlerFactory.createHandler(ao.getRelation(key).getKvo()).set(relationKey, value); return object; } private void checkAndCreateRelation(String key){ if (ao.getRelation(key) == null){ FDesc fDesc = descStore.getOD(ao.getDescriptorName()).getField(key); String relDesc = ((RelationFDesc)fDesc).getRelatedDescriptorName(); Relation rel = new Relation(aoHandlerFactory.createHandler(relDesc).getAssistedObject()); ao.set(key, rel); } } public T set(String key, String value){ ao.set(key, value); return object; } public T prop(String group, String key, String value){ propHandler.setProp(ao.getAssistedObject(), group, key, value); return object; } public T prop(String group, String key, Boolean value){ propHandler.setProp(ao.getAssistedObject(), group, key, value); return object; } } }
package org.intermine.dataloader; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import junit.framework.Test; import org.intermine.model.InterMineObject; import org.intermine.model.testmodel.Address; import org.intermine.model.testmodel.Bank; import org.intermine.model.testmodel.Broke; import org.intermine.model.testmodel.CEO; import org.intermine.model.testmodel.Company; import org.intermine.model.testmodel.Contractor; import org.intermine.model.testmodel.Department; import org.intermine.model.testmodel.Employee; import org.intermine.model.testmodel.Manager; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.SetupDataTestCase; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.objectstore.query.SingletonResults; import org.intermine.testing.OneTimeTestCase; import org.intermine.util.DynamicUtil; import org.intermine.util.IntToIntMap; public class IntegrationWriterDataTrackingImplTest extends SetupDataTestCase { protected static ObjectStoreWriter writer; protected static ObjectStore os; protected static IntegrationWriterDataTrackingImpl iw; protected boolean doIds; public IntegrationWriterDataTrackingImplTest(String arg) { super(arg); doIds = true; } public static Test suite() { return OneTimeTestCase.buildSuite(IntegrationWriterDataTrackingImplTest.class); } public void setUp() throws Exception { super.setUp(); strictTestQueries = false; if (iw.isInTransaction()) { iw.abortTransaction(); } storeData(); iw.idMap.clear(); iw.skeletons.clear(); iw.beginTransaction(); iw.setEof(new HintingFetcher(iw.getObjectStoreWriter().getObjectStore(), iw)); } public void tearDown() throws Exception { super.tearDown(); iw.commitTransaction(); iw.getDataTracker().clear(); removeDataFromStore(); iw.idMap.clear(); } public static void oneTimeSetUp() throws Exception { SetupDataTestCase.oneTimeSetUp(); iw = (IntegrationWriterDataTrackingImpl) IntegrationWriterFactory.getIntegrationWriter("integration.unittestmulti"); writer = (ObjectStoreWriterInterMineImpl) iw.getObjectStoreWriter(); os = iw.getObjectStore(); } public static void oneTimeTearDown() throws Exception { iw.close(); SetupDataTestCase.oneTimeTearDown(); } public static void storeData() throws Exception { if (iw == null) { throw new NullPointerException("iw must be set before trying to store data"); } long start = new Date().getTime(); try { iw.beginTransaction(); Source source = iw.getMainSource("storedata"); Source skelSource = iw.getSkeletonSource("storedata"); //DataTracking.precacheObjects(new HashSet(data.values()), iw.getDataTracker()); Iterator iter = data.entrySet().iterator(); while (iter.hasNext()) { InterMineObject o = (InterMineObject) ((Map.Entry) iter.next()) .getValue(); iw.store(o, source, skelSource); } //DataTracking.releasePrecached(iw.getDataTracker()); iw.commitTransaction(); } catch (Exception e) { iw.abortTransaction(); throw new Exception(e); } System.out.println("Took " + (new Date().getTime() - start) + " ms to set up data and VACUUM ANALYZE"); } public static void removeDataFromStore() throws Exception { removeDataFromStore(writer); } public static void removeDataFromStore(ObjectStoreWriter writer) throws Exception { System.out.println("Removing data from store"); long start = new Date().getTime(); if (writer == null) { throw new NullPointerException("writer must be set before trying to remove data"); } try { writer.beginTransaction(); Query q = new Query(); QueryClass qc = new QueryClass(InterMineObject.class); q.addFrom(qc); q.addToSelect(qc); Set dataToRemove = new SingletonResults(q, writer.getObjectStore(), writer.getObjectStore().getSequence()); Iterator iter = dataToRemove.iterator(); while (iter.hasNext()) { InterMineObject toDelete = (InterMineObject) iter.next(); writer.delete(toDelete); } writer.commitTransaction(); } catch (Exception e) { writer.abortTransaction(); throw e; } System.out.println("Took " + (new Date().getTime() - start) + " ms to remove data from store"); } // Not doing the Query tests here public void executeTest(String type) throws Exception { } public void testStoreObject() throws Exception { Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); a.setAddress("Company Street, AVille"); c.setAddress(a); c.setName("CompanyC"); c.setVatNumber(100); if (doIds) { c.setId(new Integer(1)); a.setId(new Integer(2)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(c, source, skelSource); // method we are testing Company example = (Company) iw.getObjectByExample(c, Collections.singleton("name")); assertNotNull("example from db should not be null", example); assertEquals(c.getVatNumber(), example.getVatNumber()); assertEquals(c.getName(), example.getName()); assertNotNull(example.getAddress()); assertEquals(c.getAddress().getAddress(), example.getAddress().getAddress()); Company c2 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); c2.setName("CompanyA"); Company example2 = (Company) iw.getObjectByExample(c2, Collections.singleton("name")); assertEquals(example.getAddress(), example2.getAddress()); } public void testUpdateObjectField() throws Exception { Employee e = new Employee(); Department d = new Department(); Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); e.setName("EmployeeA2"); e.setAge(32); e.setEnd(2); e.setFullTime(true); e.setDepartment(d); d.setName("DepartmentA1"); d.setCompany(c); c.setVatNumber(1234); if (doIds) { e.setId(new Integer(1)); d.setId(new Integer(2)); } Source source = iw.getMainSource("testsource3"); Source skelSource = iw.getSkeletonSource("testsource3"); iw.store(e, source, skelSource); iw.store(d, source, skelSource); iw.store(c, source, skelSource); Employee re = (Employee) iw.getObjectByExample(e, Collections.singleton("name")); assertNotNull("Object from db should not be null", re); assertEquals(32, re.getAge()); assertEquals(2, re.getEnd()); assertTrue(re.getFullTime()); assertNotNull(re.getAddress()); assertNotNull(re.getDepartment()); } public void testUpdateObjectOneToOne() throws Exception { Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); Address a2 = new Address(); CEO ceo = new CEO(); a.setAddress("Company Street, AVille"); c.setAddress(a); c.setName("CompanyA"); c.setVatNumber(100); c.setCEO(ceo); a2.setAddress("Employee Street, BVille"); ceo.setName("EmployeeB1"); ceo.setSeniority(new Integer(76321)); ceo.setFullTime(true); ceo.setSalary(45000); ceo.setAge(40); ceo.setCompany(c); ceo.setAddress(a2); if (doIds) { c.setId(new Integer(1)); a.setId(new Integer(2)); a2.setId(new Integer(3)); ceo.setId(new Integer(4)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(c, source, skelSource); // method we are testing Company rc = (Company) iw.getObjectByExample(c, Collections.singleton("name")); assertNotNull("Object from db should not be null", rc); assertEquals(c.getVatNumber(), rc.getVatNumber()); CEO rceo = rc.getCEO(); assertNotNull(rceo); assertEquals(ceo.getName(), rceo.getName()); assertNotNull(rceo.getCompany()); assertEquals(rc, rceo.getCompany()); Company exampleOC = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); exampleOC.setName("CompanyB"); Company oc = (Company) iw.getObjectByExample(exampleOC, Collections.singleton("name")); assertNotNull(oc); assertNull(oc.getCEO()); } public void testUpdateObjectOneToOne2() throws Exception { Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); { Company companyA = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); CEO ceoA = new CEO(); Address companyAAddress = new Address(); Address ceoAAddress = new Address(); companyAAddress.setAddress("Company Street, AVille"); companyA.setAddress(companyAAddress); companyA.setName("CompanyA"); companyA.setVatNumber(1234); companyA.setCEO(ceoA); ceoAAddress.setAddress("Employee Street, AVille"); ceoA.setAddress(ceoAAddress); ceoA.setSeniority(new Integer(876234)); ceoA.setName("Fred"); ceoA.setFullTime(false); ceoA.setSalary(1); ceoA.setAge(101); ceoA.setCompany(companyA); if (doIds) { companyA.setId(new Integer(1)); ceoA.setId(new Integer(2)); companyAAddress.setId(new Integer(3)); ceoAAddress.setId(new Integer(4)); } iw.store(companyA, source, skelSource); iw.store(ceoA, source, skelSource); iw.store(companyAAddress, source, skelSource); iw.store(ceoAAddress, source, skelSource); } Company exampleCompanyA = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); exampleCompanyA.setName("CompanyA"); Company exampleCompanyB = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); exampleCompanyB.setName("CompanyB"); CEO exampleCEOA = new CEO(); exampleCEOA.setName("Fred"); CEO exampleCEOB = new CEO(); exampleCEOB.setName("EmployeeB1"); Company rCompanyA = (Company) iw.getObjectByExample(exampleCompanyA, Collections.singleton("name")); Company rCompanyB = (Company) iw.getObjectByExample(exampleCompanyB, Collections.singleton("name")); CEO rCEOA = (CEO) iw.getObjectByExample(exampleCEOA, Collections.singleton("name")); CEO rCEOB = (CEO) iw.getObjectByExample(exampleCEOB, Collections.singleton("name")); assertNotNull(rCompanyA); assertNotNull(rCompanyB); assertNotNull(rCEOA); assertNotNull(rCEOB); assertEquals(rCompanyA, rCEOA.getCompany()); assertEquals(rCompanyB, rCEOB.getCompany()); assertEquals(rCEOA, rCompanyA.getCEO()); assertEquals(rCEOB, rCompanyB.getCEO()); Source source2 = iw.getMainSource("testsource2"); Source skelSource2 = iw.getSkeletonSource("testsource2"); { Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); Address a2 = new Address(); CEO ceo = new CEO(); a.setAddress("Company Street, AVille"); c.setAddress(a); c.setName("CompanyA"); c.setVatNumber(100); c.setCEO(ceo); a2.setAddress("Employee Street, BVille"); ceo.setName("EmployeeB1"); ceo.setSeniority(new Integer(76321)); ceo.setFullTime(true); ceo.setSalary(45000); ceo.setAge(40); ceo.setCompany(c); ceo.setAddress(a2); if (doIds) { c.setId(new Integer(1)); a.setId(new Integer(2)); a2.setId(new Integer(3)); ceo.setId(new Integer(4)); } iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); iw.store(c, source2, skelSource2); // method we are testing // Change to \ } rCompanyA = (Company) iw.getObjectByExample(exampleCompanyA, Collections.singleton("name")); rCompanyB = (Company) iw.getObjectByExample(exampleCompanyB, Collections.singleton("name")); rCEOA = (CEO) iw.getObjectByExample(exampleCEOA, Collections.singleton("name")); rCEOB = (CEO) iw.getObjectByExample(exampleCEOB, Collections.singleton("name")); assertNotNull(rCompanyA); assertNotNull(rCompanyB); assertNotNull(rCEOA); assertNotNull(rCEOB); assertEquals(null, rCEOA.getCompany()); assertEquals(rCompanyA, rCEOB.getCompany()); assertEquals(rCEOB, rCompanyA.getCEO()); assertEquals(null, rCompanyB.getCEO()); } public void testUpdateObjectOneToOneNull() throws Exception { Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); a.setAddress("Company Street, BVille"); c.setAddress(a); c.setName("CompanyB"); c.setVatNumber(100); if (doIds) { c.setId(new Integer(1)); a.setId(new Integer(2)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(c, source, skelSource); // method we are testing Company result = (Company) iw.getObjectByExample(c, Collections.singleton("name")); assertNotNull("Object from db should not be null", result); assertEquals(c.getVatNumber(), result.getVatNumber()); assertNull(result.getCEO()); CEO ceo = new CEO(); ceo.setName("EmployeeB1"); CEO result2 = (CEO) iw.getObjectByExample(ceo, Collections.singleton("name")); assertNotNull(result2); assertNull(result2.getCompany()); } public void testUpdateObjectManyToOne() throws Exception { Manager e = new Manager(); Department d = new Department(); Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); Address a2 = new Address(); a.setAddress("Company Street, BVille"); c.setName("CompanyB"); c.setAddress(a); c.addDepartments(d); d.setName("DepartmentB1"); d.setCompany(c); e.setName("EmployeeA1"); e.setDepartment(d); d.addEmployees(e); e.setAge(10); e.setFullTime(true); e.setSeniority(new Integer(876123)); a2.setAddress("Employee Street, AVille"); e.setAddress(a2); if (doIds) { e.setId(new Integer(1)); d.setId(new Integer(2)); c.setId(new Integer(3)); a.setId(new Integer(4)); a2.setId(new Integer(5)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(e, source, skelSource); // method we are testing Employee re = (Employee) iw.getObjectByExample(e, Collections.singleton("name")); assertNotNull(re); Department rd = re.getDepartment(); assertNotNull(rd); // Employee has a department assertEquals(d.getName(), rd.getName()); // Department is the right one assertTrue(rd.getEmployees().contains(re)); // And that department has the employee Department exampleOD = new Department(); exampleOD.setName("DepartmentA1"); Department od = (Department) iw.getObjectByExample(exampleOD, Collections.singleton("name")); assertNotNull(od); // The old department exists assertTrue(!od.getEmployees().contains(re));// And does not have the employee } public void testUpdateObjectManyToOneNull() throws Exception { Manager e = new Manager(); Address a2 = new Address(); e.setName("EmployeeA1"); e.setDepartment(null); e.setAge(10); e.setFullTime(true); e.setSeniority(new Integer(876123)); a2.setAddress("Employee Street, AVille"); e.setAddress(a2); if (doIds) { e.setId(new Integer(1)); a2.setId(new Integer(2)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(e, source, skelSource); // method we are testing Employee re = (Employee) iw.getObjectByExample(e, Collections.singleton("name")); assertNotNull(re); assertNull(re.getDepartment()); // Employee no longer has a department Department exampleOD = new Department(); exampleOD.setName("DepartmentA1"); Department od = (Department) iw.getObjectByExample(exampleOD, Collections.singleton("name")); assertNotNull(od); // The old department exists assertTrue(!od.getEmployees().contains(re));// And does not have the employee } public void testUpdateObjectOneToMany() throws Exception { Manager e = new Manager(); Department d = new Department(); Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a = new Address(); Address a2 = new Address(); a.setAddress("Company Street, BVille"); c.setName("CompanyB"); c.setAddress(a); c.addDepartments(d); d.setName("DepartmentB1"); d.setCompany(c); d.addEmployees(e); e.setDepartment(d); e.setName("EmployeeA1"); e.setAge(10); e.setFullTime(true); e.setSeniority(new Integer(876123)); a2.setAddress("Employee Street, AVille"); e.setAddress(a2); if (doIds) { e.setId(new Integer(1)); d.setId(new Integer(2)); c.setId(new Integer(3)); a.setId(new Integer(4)); a2.setId(new Integer(5)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(d, source, skelSource); // method we are testing Department rd = (Department) iw.getObjectByExample(d, Collections.singleton("name")); Employee re = (Employee) iw.getObjectByExample(e, Collections.singleton("name")); assertNotNull(rd); assertNotNull(re); // because the Integration Writer assumes that you will later on go and store the rest of // the objects (and sort out the mess). //assertTrue(rd.getEmployees().contains(re)); // Department has the employee //assertEquals(re.getDepartment(), rd); // And Employees department is the right one //Department exampleOD = new Department(); //exampleOD.setName("DepartmentA1"); //Department od = (Department) iw.getObjectByExample(exampleOD, Collections.singleton("name")); //assertNotNull(od); // The old department exists //assertTrue(!od.getEmployees().contains(re));// And does not have the employee } public void testUpdateObjectManyToMany() throws Exception { Contractor con = new Contractor(); Address companyAAddress = new Address(); Company companyA = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); companyAAddress.setAddress("Company Street, AVille"); companyA.setAddress(companyAAddress); companyA.setName("CompanyA"); con.setName("ContractorZ"); con.addCompanys(companyA); companyA.addContractors(con); if (doIds) { con.setId(new Integer(1)); companyAAddress.setId(new Integer(2)); companyA.setId(new Integer(3)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(con, source, skelSource); // method we are testing Company rca = (Company) iw.getObjectByExample(companyA, Collections.singleton("name")); Contractor rcon = (Contractor) iw.getObjectByExample(con, Collections.singleton("name")); assertNotNull(rca); assertNotNull(rcon); assertTrue(rca.getContractors().contains(rcon)); assertTrue(rcon.getCompanys().contains(rca)); Source source2 = iw.getMainSource("testsource2"); Source skelSource2 = iw.getSkeletonSource("testsource2"); Address companyBAddress = new Address(); Company companyB = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); companyBAddress.setAddress("Company Street, BVille"); companyB.setAddress(companyBAddress); companyB.setName("CompanyB"); con.addCompanys(companyB); companyB.addContractors(con); if (doIds) { con.setId(new Integer(1)); companyBAddress.setId(new Integer(4)); companyB.setId(new Integer(5)); } iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); iw.store(con, source2, skelSource2); rca = (Company) iw.getObjectByExample(companyA, Collections.singleton("name")); Company rcb = (Company) iw.getObjectByExample(companyB, Collections.singleton("name")); rcon = (Contractor) iw.getObjectByExample(con, Collections.singleton("name")); assertNotNull(rca); assertNotNull(rcb); assertNotNull(rcon); assertTrue(rca.getContractors().contains(rcon)); assertTrue(rcon.getCompanys().contains(rca)); assertTrue(rcb.getContractors().contains(rcon)); assertTrue(rcon.getCompanys().contains(rcb)); } public void testUpdateObjectManyToManyWithMerge() throws Exception { // Add a duplicate CompanyA and ContractorA, plus a ContractorD only attached to the duplicate CompanyA, and a ContractorC only attached to the original CompanyA. Address exampleCAA = new Address(); exampleCAA.setAddress("Company Street, AVille"); Address dbCAA = (Address) iw.getObjectByExample(exampleCAA, Collections.singleton("address")); Company ca = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); ca.setAddress(dbCAA); ca.setName("CompanyA"); Contractor exampleConA = new Contractor(); exampleConA.setName("ContractorA"); Contractor dbConA = (Contractor) iw.getObjectByExample(exampleConA, Collections.singleton("name")); ca.addContractors(dbConA); Contractor exampleConB = new Contractor(); exampleConB.setName("ContractorB"); Contractor dbConB = (Contractor) iw.getObjectByExample(exampleConB, Collections.singleton("name")); ca.addContractors(dbConB); Contractor conA = new Contractor(); ca.addContractors(conA); conA.setName("ContractorA"); conA.setSeniority(new Integer(128764)); conA.addCompanys(ca); Company exampleCA = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); exampleCA.setName("CompanyA"); Company dbCA = (Company) iw.getObjectByExample(exampleCA, Collections.singleton("name")); conA.addCompanys(dbCA); Company exampleCB = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); exampleCB.setName("CompanyB"); Company dbCB = (Company) iw.getObjectByExample(exampleCB, Collections.singleton("name")); conA.addCompanys(dbCB); Contractor conC = new Contractor(); conC.setName("ContractorC"); conC.setSeniority(new Integer(2784112)); conC.addCompanys(dbCA); Contractor conD = new Contractor(); conD.setName("ContractorD"); conD.setSeniority(new Integer(276423341)); conD.addCompanys(ca); if (doIds) { ca.setId(new Integer(1)); conA.setId(new Integer(2)); conC.setId(new Integer(3)); conD.setId(new Integer(4)); } iw.store(ca); iw.store(conA); iw.store(conC); iw.store(conD); Source source = iw.getMainSource("testsource"); DataTracker dataTracker = iw.getDataTracker(); dataTracker.clearObj(ca.getId()); dataTracker.setSource(ca.getId(), "name", source); dataTracker.setSource(ca.getId(), "address", source); dataTracker.setSource(ca.getId(), "vatNumber", source); dataTracker.setSource(ca.getId(), "CEO", source); dataTracker.clearObj(conA.getId()); dataTracker.setSource(conA.getId(), "personalAddress", source); dataTracker.setSource(conA.getId(), "businessAddress", source); dataTracker.setSource(conA.getId(), "name", source); dataTracker.setSource(conA.getId(), "seniority", source); dataTracker.clearObj(conC.getId()); dataTracker.setSource(conC.getId(), "personalAddress", source); dataTracker.setSource(conC.getId(), "businessAddress", source); dataTracker.setSource(conC.getId(), "name", source); dataTracker.setSource(conC.getId(), "seniority", source); dataTracker.clearObj(conD.getId()); dataTracker.setSource(conD.getId(), "personalAddress", source); dataTracker.setSource(conD.getId(), "businessAddress", source); dataTracker.setSource(conD.getId(), "name", source); dataTracker.setSource(conD.getId(), "seniority", source); // Now set up a standard store operation that will set off a object merge. Contractor con = new Contractor(); Address companyAAddress = new Address(); Company companyA = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); companyAAddress.setAddress("Company Street, AVille"); companyA.setAddress(companyAAddress); companyA.setName("CompanyA"); con.setName("ContractorZ"); con.addCompanys(companyA); companyA.addContractors(con); if (doIds) { con.setId(new Integer(5)); companyAAddress.setId(new Integer(6)); companyA.setId(new Integer(7)); } Source source2 = iw.getMainSource("testsource2"); Source skelSource2 = iw.getSkeletonSource("testsource2"); // Make sure there are currently multiple copies of CompanyA and ContractorA. try { Company rca = (Company) iw.getObjectByExample(companyA, Collections.singleton("name")); fail("Expected an exception, because there are multiple objects matching this pattern"); } catch (IllegalArgumentException e) { } try { Contractor rconA = (Contractor) iw.getObjectByExample(conA, Collections.singleton("name")); fail("Expected an exception, because there are multiple objects matching this pattern"); } catch (IllegalArgumentException e) { } iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); iw.store(con, source2, skelSource2); // method we are testing // Get objects (and test that there is only one copy of everything). Company rca = (Company) iw.getObjectByExample(companyA, Collections.singleton("name")); Contractor rconC = (Contractor) iw.getObjectByExample(conC, Collections.singleton("name")); Contractor rconD = (Contractor) iw.getObjectByExample(conD, Collections.singleton("name")); Contractor rconZ = (Contractor) iw.getObjectByExample(con, Collections.singleton("name")); assertNotNull(rca); assertNotNull(rconC); assertNotNull(rconD); assertNotNull(rconZ); // Test that everything is in the right collections. assertTrue(rca.getContractors().contains(rconC)); assertTrue(rca.getContractors().contains(rconD)); assertTrue(rca.getContractors().contains(rconZ)); assertTrue(rconC.getCompanys().contains(rca)); assertTrue(rconD.getCompanys().contains(rca)); assertTrue(rconZ.getCompanys().contains(rca)); conA.setCompanys(new HashSet()); iw.store(conA, source2, skelSource2); Contractor rconA = (Contractor) iw.getObjectByExample(conA, Collections.singleton("name")); assertNotNull(rconA); assertTrue(rca.getContractors().contains(rconA)); assertTrue(rconA.getCompanys().contains(rca)); } public void testAddClass() throws Exception { Employee e = (Employee) DynamicUtil.createObject(new HashSet(Arrays.asList(new Class[] {Employee.class, Broke.class}))); e.setName("EmployeeA1"); ((Broke) e).setDebt(8762); if (doIds) { e.setId(new Integer(1)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(e, source, skelSource); // method we are testing InterMineObject re = iw.getObjectByExample(e, Collections.singleton("name")); assertNotNull(re); assertTrue(re instanceof Broke); assertTrue(re instanceof Employee); assertTrue(re instanceof Manager); assertEquals(8762, ((Broke) re).getDebt()); assertEquals(new Integer(876123), ((Manager) re).getSeniority()); } public void testSourceWithMultipleCopies() throws Exception { Employee e1 = new Employee(); e1.setName("EmployeeA1"); Employee e2 = new Employee(); e2.setName("EmployeeA1"); if (doIds) { e1.setId(new Integer(1)); e2.setId(new Integer(2)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(e1, source, skelSource); try { iw.store(e2, source, skelSource); fail("Expected: IllegalArgumentException"); } catch (RuntimeException e) { } } public void testMergeWithSuperclass() throws Exception { Manager e1 = new Manager(); e1.setName("EmployeeA2"); e1.setTitle("Mr."); if (doIds) { e1.setId(new Integer(1)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(e1, source, skelSource); Employee e2 = new Employee(); e2.setName("EmployeeA2"); Manager e3 = (Manager) iw.getObjectByExample(e2, Collections.singleton("name")); assertEquals("Mr.", e3.getTitle()); assertEquals("EmployeeA2", e3.getName()); } public void testMergeWithDifferentFields() throws Exception { Query q = new Query(); QueryClass qc = new QueryClass(Company.class); q.addFrom(qc); q.addToSelect(qc); ConstraintSet cs = new ConstraintSet(ConstraintOp.OR); cs.addConstraint(new SimpleConstraint(new QueryField(qc, "name"), ConstraintOp.EQUALS, new QueryValue("CompanyZ"))); cs.addConstraint(new SimpleConstraint(new QueryField(qc, "vatNumber"), ConstraintOp.EQUALS, new QueryValue(new Integer(876213)))); q.setConstraint(cs); Company c2 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a2 = new Address(); Company c3 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Company c4 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); Address a4 = new Address(); c2.setName("CompanyZ"); c2.setAddress(a2); a2.setAddress("Flibble"); c3.setVatNumber(876213); c4.setName("CompanyZ"); c4.setAddress(a4); a4.setAddress("Flibble"); c4.setVatNumber(876213); if (doIds) { c2.setId(new Integer(1)); a2.setId(new Integer(2)); c3.setId(new Integer(1)); c4.setId(new Integer(1)); a4.setId(new Integer(2)); } assertEquals(0, (new SingletonResults(q, iw, iw.getSequence())).size()); Source source2 = iw.getMainSource("testsource2"); Source skelSource2 = iw.getSkeletonSource("testsource2"); iw.store(c2, source2, skelSource2); iw.store(a2, source2, skelSource2); iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); assertEquals(1, (new SingletonResults(q, iw, iw.getSequence())).size()); Source source3 = iw.getMainSource("testsource3"); Source skelSource3 = iw.getSkeletonSource("testsource3"); iw.store(c3, source3, skelSource3); iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); assertEquals(2, (new SingletonResults(q, iw, iw.getSequence())).size()); Source source4 = iw.getMainSource("testsource4"); Source skelSource4 = iw.getSkeletonSource("testsource4"); iw.store(c4, source4, skelSource4); iw.store(a4, source4, skelSource4); iw.idMap.clear(); iw.commitTransaction(); iw.beginTransaction(); assertEquals(DataLoaderHelper.createPKQuery(iw.getModel(), c4, source4, iw.idMap, null, false).toString(), 1, (new SingletonResults(q, iw, iw.getSequence())).size()); } // a bug existed whereby storing a skeleton then a real object retrieved and failed to materialise // a ProxyReference - failing a check that a field being processed was a member of the class public void testStoreObjectAfterSkeleton() throws Exception { // CompanyA is in db with source "storedata" // source "testsource3" has a lower priority than "storedata" Company c = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); c.setVatNumber(1234); Department d = new Department(); d.setCompany(c); d.setName("new_department"); if (doIds) { c.setId(new Integer(1)); d.setId(new Integer(3)); } Source source = iw.getMainSource("testsource3"); Source skelSource = iw.getSkeletonSource("testsource3"); Company before = (Company) iw.getObjectByExample(c, Collections.singleton("vatNumber")); assertNotNull("before example from db should not be null", before); // storing the dept should store CompanyA as a skeleton iw.store(d, source, skelSource); // method we are testing iw.store(c, source, skelSource); // method we are testing // assert that storing a CompanyA with no vatNumber does not overwrite // the existing higher priority value Company after = (Company) iw.getObjectByExample(c, Collections.singleton("vatNumber")); assertNotNull("after example from db should not be null", after); assertEquals(before.getVatNumber(), after.getVatNumber()); assertEquals(before.getName(), after.getName()); assertEquals(before.getAddress().getAddress(), after.getAddress().getAddress()); } public void testGetEquivalentObjects() throws Exception { Bank b = (Bank) DynamicUtil.createObject(Collections.singleton(Bank.class)); b.setName("bank1"); Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); Set objects = iw.getEquivalentObjects(b, source); System.out.println(objects); assertTrue(objects.isEmpty()); } public void testSkeletonsNoException() throws Exception { Address a = (Address) DynamicUtil.createObject(Collections.singleton(Address.class)); a.setAddress("address1"); if (doIds) { a.setId(new Integer(1)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(a, source, skelSource, IntegrationWriterDataTrackingImpl.SKELETON); assertTrue(iw.skeletons.size() == 1); iw.store(a, source, skelSource, IntegrationWriterDataTrackingImpl.SOURCE); assertTrue(iw.skeletons.size() == 0); } public void testSkeletonsException() throws Exception { Address a = (Address) DynamicUtil.createObject(Collections.singleton(Address.class)); a.setAddress("address1"); if (doIds) { a.setId(new Integer(1)); } IntegrationWriterDataTrackingImpl iw2 = (IntegrationWriterDataTrackingImpl) IntegrationWriterFactory.getIntegrationWriter("integration.unittestmulti"); ObjectStoreWriter writer2 = (ObjectStoreWriterInterMineImpl) iw2.getObjectStoreWriter(); Source source = iw2.getMainSource("testsource"); Source skelSource = iw2.getSkeletonSource("testsource"); iw2.store(a, source, skelSource, IntegrationWriterDataTrackingImpl.SKELETON); assertTrue(iw2.skeletons.size() == 1); try { iw2.close(); fail("Expected exception because not all skeletons replaced by real objects"); } catch (ObjectStoreException e) { } finally { iw2 = (IntegrationWriterDataTrackingImpl) IntegrationWriterFactory.getIntegrationWriter("integration.unittestmulti"); try { writer2 = (ObjectStoreWriterInterMineImpl) iw2.getObjectStoreWriter(); removeDataFromStore(writer2); } finally { iw2.close(); } } } public void testCircularRecursionBug() throws Exception { Department d = new Department(); Manager m = new Manager(); d.setManager(m); m.setDepartment(d); d.setName("Bob"); m.setName("Fred"); if (doIds) { d.setId(new Integer(1)); m.setId(new Integer(2)); } Source source = iw.getMainSource("testsource"); Source skelSource = iw.getSkeletonSource("testsource"); iw.store(m, source, skelSource); Query q = new Query(); QueryClass qc = new QueryClass(Manager.class); q.addFrom(qc); q.addToSelect(qc); q.setConstraint(new SimpleConstraint(new QueryField(qc, "name"), ConstraintOp.EQUALS, new QueryValue("Fred"))); SingletonResults r = new SingletonResults(q, iw, iw.getSequence()); assertEquals("Results: " + r, 1, r.size()); Manager rm = (Manager) r.get(0); assertNotNull(rm); Department rd = rm.getDepartment(); assertNotNull(rd); assertEquals(d.getName(), rd.getName()); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addFrom(qc2); q2.addToSelect(qc2); q2.setConstraint(new SimpleConstraint(new QueryField(qc2, "name"), ConstraintOp.EQUALS, new QueryValue("Bob"))); SingletonResults r2 = new SingletonResults(q2, iw, iw.getSequence()); assertEquals("Results: " + r2, 1, r2.size()); } }
package stategraph; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import javax.swing.JOptionPane; import parser.Parser; import biomodelsim.BioSim; import lhpn2sbml.parser.ExprTree; import lhpn2sbml.parser.LhpnFile; public class StateGraph implements Runnable { private HashMap<String, LinkedList<State>> stateGraph; private ArrayList<String> variables; private LhpnFile lhpn; private boolean stop; private String markovResults; private Parser probData; public StateGraph(LhpnFile lhpn) { this.lhpn = lhpn; stop = false; markovResults = null; } public void buildStateGraph() { stateGraph = new HashMap<String, LinkedList<State>>(); variables = new ArrayList<String>(); for (String var : lhpn.getBooleanVars()) { variables.add(var); } for (String var : lhpn.getIntVars()) { variables.add(var); } HashMap<String, String> allVariables = new HashMap<String, String>(); for (String var : lhpn.getBooleanVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getContVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getIntVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } ArrayList<String> markedPlaces = new ArrayList<String>(); for (String place : lhpn.getPlaceList()) { if (lhpn.getPlace(place).isMarked()) { markedPlaces.add(place); } } LinkedList<State> markings = new LinkedList<State>(); int counter = 0; State state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); Stack<Transition> transitionsToFire = new Stack<Transition>(); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } while (transitionsToFire.size() != 0 && !stop) { Transition fire = transitionsToFire.pop(); markedPlaces = fire.getMarkedPlaces(); allVariables = copyAllVariables(fire.getParent().getVariables()); for (String place : lhpn.getPreset(fire.getTransition())) { markedPlaces.remove(place); } for (String place : lhpn.getPostset(fire.getTransition())) { markedPlaces.add(place); } for (String key : allVariables.keySet()) { if (lhpn.getBoolAssignTree(fire.getTransition(), key) != null) { double eval = lhpn.getBoolAssignTree(fire.getTransition(), key).evaluateExpr(allVariables); if (eval == 0.0) { allVariables.put(key, "false"); } else { allVariables.put(key, "true"); } } if (lhpn.getContAssignTree(fire.getTransition(), key) != null) { allVariables.put(key, "" + lhpn.getContAssignTree(fire.getTransition(), key).evaluateExpr(allVariables)); } if (lhpn.getIntAssignTree(fire.getTransition(), key) != null) { allVariables.put(key, "" + ((int) lhpn.getIntAssignTree(fire.getTransition(), key).evaluateExpr(allVariables))); } } if (!stateGraph.containsKey(createStateVector(variables, allVariables))) { markings = new LinkedList<State>(); state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); fire.getParent().addNextState(state, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()), fire.getTransition()); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } } else { markings = stateGraph.get(createStateVector(variables, allVariables)); boolean add = true; boolean same = true; for (State mark : markings) { for (String place : mark.getMarkings()) { if (!markedPlaces.contains(place)) { same = false; } } for (String place : markedPlaces) { boolean contains = false; for (String place2 : mark.getMarkings()) { if (place2.equals(place)) { contains = true; } } if (!contains) { same = false; } } if (same) { add = false; fire.getParent().addNextState(mark, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()), fire.getTransition()); } same = true; } if (add) { state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); fire.getParent().addNextState(state, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()), fire.getTransition()); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } } } } } public boolean canPerformMarkovianAnalysis() { for (String trans : lhpn.getTransitionList()) { if (!lhpn.isExpTransitionRateTree(trans)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has transitions without exponential delay.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } for (String var : lhpn.getVariables()) { if (lhpn.isRandomBoolAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lhpn.isRandomContAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lhpn.isRandomIntAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } } } if (lhpn.getContVars().length > 0) { JOptionPane.showMessageDialog(BioSim.frame, "LPN contains continuous variables.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } return true; } public boolean performTransientMarkovianAnalysis(double timeLimit, double timeStep, double error, String[] condition) { if (!canPerformMarkovianAnalysis()) { stop = true; return false; } else if (condition != null) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); dataLabels.add("~(" + condition[0] + ")&~(" + condition[1] + ")"); dataLabels.add(condition[1]); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); probData = new Parser(dataLabels, data); State initial = getInitialState(); if (initial != null) { initial.setCurrentProb(1.0); initial.setPiProb(1.0); double lowerbound = 0; if (!condition[2].equals("")) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition[2]); expr.intexpr_L(condition[2]); lowerbound = Math.min(expr.evaluateExpr(null), timeLimit); pruneStateGraph("~(" + condition[0] + ")"); for (double i = 0; i < lowerbound; i += timeStep) { double step = Math.min(timeStep, lowerbound - i); if (!performTransientMarkovianAnalysis(step, error)) { return false; } probData.getData().get(0).add(i + timeStep); double prob = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok("~(" + condition[0] + ")"); expr.intexpr_L("~(" + condition[0] + ")"); if (expr.evaluateExpr(m.getVariables()) == 1.0) { prob += m.getCurrentProb(); } } } probData.getData().get(1).add(prob * 100); probData.getData().get(2).add(0.0); } } else { pruneStateGraph("~(" + condition[0] + ")"); } ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition[3]); expr.intexpr_L(condition[3]); double upperbound = Math.min(expr.evaluateExpr(null) - lowerbound, timeLimit - lowerbound); pruneStateGraph(condition[1]); for (double i = 0; i < upperbound; i += timeStep) { double step = Math.min(timeStep, upperbound - i); if (!performTransientMarkovianAnalysis(step, error)) { return false; } probData.getData().get(0).add(lowerbound + i + timeStep); double failureProb = 0; double successProb = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree failureExpr = new ExprTree(lhpn); failureExpr.token = failureExpr.intexpr_gettok("~(" + condition[0] + ")&~(" + condition[1] + ")"); failureExpr.intexpr_L("~(" + condition[0] + ")&~(" + condition[1] + ")"); ExprTree successExpr = new ExprTree(lhpn); successExpr.token = successExpr.intexpr_gettok(condition[1]); successExpr.intexpr_L(condition[1]); if (failureExpr.evaluateExpr(m.getVariables()) == 1.0) { failureProb += m.getCurrentProb(); } else if (successExpr.evaluateExpr(m.getVariables()) == 1.0) { successProb += m.getCurrentProb(); } } } probData.getData().get(1).add(failureProb * 100); probData.getData().get(2).add(successProb * 100); } HashMap<String, Double> output = new HashMap<String, Double>(); double failureProb = 0; double successProb = 0; double timelimitProb = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree failureExpr = new ExprTree(lhpn); failureExpr.token = failureExpr.intexpr_gettok("~(" + condition[0] + ")&~(" + condition[1] + ")"); failureExpr.intexpr_L("~(" + condition[0] + ")&~(" + condition[1] + ")"); ExprTree successExpr = new ExprTree(lhpn); successExpr.token = successExpr.intexpr_gettok(condition[1]); successExpr.intexpr_L(condition[1]); if (failureExpr.evaluateExpr(m.getVariables()) == 1.0) { failureProb += m.getCurrentProb(); } else if (successExpr.evaluateExpr(m.getVariables()) == 1.0) { successProb += m.getCurrentProb(); } else { timelimitProb += m.getCurrentProb(); } } } output.put("~(" + condition[0].trim() + ")&~(" + condition[1].trim() + ")", failureProb); output.put(condition[1].trim(), successProb); output.put("timelimit", timelimitProb); String result1 = "#total"; String result2 = "1.0"; for (String s : output.keySet()) { result1 += " " + s; result2 += " " + output.get(s); } markovResults = result1 + "\n" + result2 + "\n"; return true; } else { return false; } } else { boolean stop = false; for (double i = 0; i < timeLimit; i += timeStep) { double step = Math.min(timeStep, timeLimit - i); stop = !performTransientMarkovianAnalysis(step, error); if (stop) { return false; } } return !stop; } } private boolean performTransientMarkovianAnalysis(double timeLimit, double error) { if (timeLimit == 0.0) { return true; } // Compute Gamma double Gamma = 0; if (!stop) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { Gamma = Math.max(m.getTransitionSum(0.0, null), Gamma); } } } else { return false; } // Compute K int K = 0; double xi = 1; double delta = 1; double eta = (1 - error) / (Math.pow(Math.E, ((0 - Gamma) * timeLimit))); while (delta < eta && !stop) { K = K + 1; xi = xi * ((Gamma * timeLimit) / K); delta = delta + xi; } if (stop) { return false; } // Approximate pi(t) for (int k = 1; k <= K && !stop; k++) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { double nextProb = m.getCurrentProb() * (1 - (m.getTransitionSum(0.0, null) / Gamma)); for (StateTransitionPair prev : m.getPrevStatesWithTrans()) { // if (lhpn.getTransitionRateTree(prev.getTransition()) != null) { // prob = // lhpn.getTransitionRateTree(prev.getTransition()).evaluateExpr(prev.getState().getVariables()); nextProb += (prev.getState().getCurrentProb() * (prev.getTransition() / Gamma)); } m.setNextProb(nextProb * ((Gamma * timeLimit) / k)); m.setPiProb(m.getPiProb() + m.getNextProb()); } } if (stop) { return false; } for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setCurrentProbToNext(); } } } if (!stop) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setPiProb(m.getPiProb() * (Math.pow(Math.E, ((0 - Gamma) * timeLimit)))); m.setCurrentProbToPi(); } } } if (stop) { return false; } return true; } public void pruneStateGraph(String condition) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition); expr.intexpr_L(condition); if (expr.evaluateExpr(m.getVariables()) == 1.0) { for (State s : m.getNextStates()) { ArrayList<StateTransitionPair> newTrans = new ArrayList<StateTransitionPair>(); for (StateTransitionPair trans : s.getPrevStatesWithTrans()) { if (trans.getState() != m) { newTrans.add(trans); } } s.setPrevStatesWithTrans(newTrans.toArray(new StateTransitionPair[0])); } m.setNextStatesWithTrans(new StateTransitionPair[0]); } m.setTransitionSum(-1); } } } public boolean performSteadyStateMarkovianAnalysis(double tolerance, ArrayList<String> conditions) { if (!canPerformMarkovianAnalysis()) { stop = true; return false; } else { State initial = getInitialState(); if (initial != null && !stop) { resetColorsForMarkovianAnalysis(); int period = findPeriod(initial); if (period == 0) { period = 1; } int step = 0; initial.setCurrentProb(1.0); boolean done = false; if (!stop) { do { step++; step = step % period; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (m.getColor() % period == step) { double nextProb = 0.0; for (StateTransitionPair prev : m.getPrevStatesWithTrans()) { double transProb = 0.0; transProb += prev.getTransition(); // if (lhpn.getTransitionRateTree(prev.getTransition()) != // null) { // if (lhpn.getTransitionRateTree(prev.getTransition()) != // null) { // (!lhpn.isExpTransitionRateTree(prev // .getTransition()) // lhpn.getDelayTree(prev.getTransition()) // .evaluateExpr(null) == 0) { // transProb = 1.0; // else { // transProb = // lhpn.getTransitionRateTree(prev.getTransition()).evaluateExpr( // prev.getState().getVariables()); // else { // transProb = 1.0; double transitionSum = prev.getState().getTransitionSum(1.0, m); if (transitionSum != 0) { transProb = (transProb / transitionSum); } else { transProb = 0.0; } nextProb += (prev.getState().getCurrentProb() * transProb); if (stop) { return false; } } if (nextProb != 0.0) { m.setNextProb(nextProb); } } if (stop) { return false; } } if (stop) { return false; } } boolean change = false; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (m.getColor() % period == step) { if ((m.getCurrentProb() != 0) && (Math.abs(((m.getCurrentProb() - m.getNextProb())) / m.getCurrentProb()) > tolerance)) { change = true; } else if (m.getCurrentProb() == 0 && m.getNextProb() > tolerance) { change = true; } m.setCurrentProbToNext(); } if (stop) { return false; } } if (stop) { return false; } } if (!change) { done = true; } } while (!done && !stop); } if (!stop) { double totalProb = 0.0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { double transitionSum = m.getTransitionSum(1.0, null); if (transitionSum != 0.0) { m.setCurrentProb((m.getCurrentProb() / period) / transitionSum); } totalProb += m.getCurrentProb(); if (stop) { return false; } } if (stop) { return false; } } for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (totalProb != 0.0) { m.setCurrentProb(m.getCurrentProb() / totalProb); } if (stop) { return false; } } if (stop) { return false; } } resetColors(); HashMap<String, Double> output = new HashMap<String, Double>(); if (conditions != null && !stop) { for (String cond : conditions) { double prob = 0; // for (String ss : s.split("&&")) { // if (ss.split("->").length == 2) { // String[] states = ss.split("->"); // for (String state : stateGraph.keySet()) { // for (State m : stateGraph.get(state)) { // ExprTree expr = new ExprTree(lhpn); // expr.token = expr.intexpr_gettok(states[0]); // expr.intexpr_L(states[0]); // if (expr.evaluateExpr(m.getVariables()) == 1.0) { // for (StateTransitionPair nextState : m // .getNextStatesWithTrans()) { // ExprTree nextExpr = new ExprTree(lhpn); // nextExpr.token = nextExpr // .intexpr_gettok(states[1]); // nextExpr.intexpr_L(states[1]); // if (nextExpr.evaluateExpr(nextState.getState() // .getVariables()) == 1.0) { // prob += (m.getCurrentProb() * (lhpn // .getTransitionRateTree( // nextState.getTransition()) // .evaluateExpr(m.getVariables()) / m // .getTransitionSum(1.0, null))); // if (stop) { // return false; // if (stop) { // return false; // if (stop) { // return false; // else { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(cond); expr.intexpr_L(cond); if (expr.evaluateExpr(m.getVariables()) == 1.0) { prob += m.getCurrentProb(); } } } output.put(cond.trim(), prob); } String result1 = "#total"; String result2 = "1.0"; for (String s : output.keySet()) { result1 += " " + s; result2 += " " + output.get(s); } markovResults = result1 + "\n" + result2 + "\n"; } } } return true; } } public String getMarkovResults() { return markovResults; } public boolean outputTSD(String filename) { if (probData != null) { probData.outputTSD(filename); return true; } return false; } private int findPeriod(State state) { if (stop) { return 0; } int period = 0; int color = 0; state.setColor(color); color = state.getColor() + 1; Queue<State> unVisitedStates = new LinkedList<State>(); for (State s : state.getNextStates()) { if (s.getColor() == -1) { s.setColor(color); unVisitedStates.add(s); } else { if (period == 0) { period = (state.getColor() - s.getColor() + 1); } else { period = gcd(state.getColor() - s.getColor() + 1, period); } } if (stop) { return 0; } } while (!unVisitedStates.isEmpty() && !stop) { state = unVisitedStates.poll(); color = state.getColor() + 1; for (State s : state.getNextStates()) { if (s.getColor() == -1) { s.setColor(color); unVisitedStates.add(s); } else { if (period == 0) { period = (state.getColor() - s.getColor() + 1); } else { period = gcd(state.getColor() - s.getColor() + 1, period); } } if (stop) { return 0; } } } return period; } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private void resetColorsForMarkovianAnalysis() { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setColor(-1); if (stop) { return; } } if (stop) { return; } } } public void resetColors() { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setColor(0); if (stop) { return; } } if (stop) { return; } } } public State getInitialState() { HashMap<String, String> allVariables = new HashMap<String, String>(); for (String var : lhpn.getBooleanVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getContVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getIntVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (State s : stateGraph.get(createStateVector(variables, allVariables))) { if (s.getID().equals("S0")) { return s; } } return null; } public HashMap<String, LinkedList<State>> getStateGraph() { return stateGraph; } public int getNumberOfStates() { int count = 0; for (String s : stateGraph.keySet()) { for (int i = 0; i < stateGraph.get(s).size(); i++) { count++; } } return count; } private ArrayList<String> copyArrayList(ArrayList<String> original) { ArrayList<String> copy = new ArrayList<String>(); for (String element : original) { copy.add(element); } return copy; } private HashMap<String, String> copyAllVariables(HashMap<String, String> original) { HashMap<String, String> copy = new HashMap<String, String>(); for (String s : original.keySet()) { copy.put(s, original.get(s)); } return copy; } private String createStateVector(ArrayList<String> variables, HashMap<String, String> allVariables) { String vector = ""; for (String s : variables) { if (allVariables.get(s).toLowerCase().equals("true")) { vector += "1,"; } else if (allVariables.get(s).toLowerCase().equals("false")) { vector += "0,"; } else { vector += allVariables.get(s) + ","; } } if (vector.length() > 0) { vector = vector.substring(0, vector.length() - 1); } return vector; } public void outputStateGraph(String file, boolean withProbs) { try { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(6); num.setGroupingUsed(false); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("digraph G {\n"); for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (withProbs) { out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + state + ">\\nProb = " + num.format(m.getCurrentProb()) + "\"]\n"); } else { out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + state + ">\"]\n"); } for (StateTransitionPair next : m.getNextStatesWithTrans()) { /* * System.out.println(m.getID() + " -> " + next.getState().getID() + * " [label=\"" + next.getTransition() + "\\n"); * System.out.println(m.getTransitionSum()); * System.out.println(lhpn.getTransitionRateTree( next.getTransition * ()).evaluateExpr(m.getVariables())); */ out.write(m.getID() + " -> " + next.getState().getID() + " [label=\"" + next.getTransitionName() + "\\n" + num.format(next.getTransition()) + "\"]\n"); // if (lhpn.getTransitionRateTree(next.getTransition()) != null) { // out.write(m.getID() // + next.getState().getID() // + " [label=\"" // + next.getTransition() // num.format((lhpn.getTransitionRateTree(next.getTransition()).evaluateExpr(m // .getVariables()) /* // * / m . getTransitionSum ( ) // */)) + "\"]\n"); // else { // out.write(m.getID() + " -> " + next.getState().getID() + // " [label=\"" + next.getTransition() + "\"]\n"); } } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error outputting state graph as dot file."); } } public void stop() { stop = true; } public boolean getStop() { return stop; } private class Transition { private String transition; private ArrayList<String> markedPlaces; private State parent; private Transition(String transition, ArrayList<String> markedPlaces, State parent) { this.transition = transition; this.markedPlaces = markedPlaces; this.parent = parent; } private String getTransition() { return transition; } private ArrayList<String> getMarkedPlaces() { return markedPlaces; } private State getParent() { return parent; } } private class StateTransitionPair { private double transition; private String transitionName; private State state; private StateTransitionPair(State state, double transition, String transitionName) { this.state = state; this.transition = transition; this.transitionName = transitionName; } private State getState() { return state; } private double getTransition() { return transition; } private String getTransitionName() { return transitionName; } } public class State { private String[] markings; private StateTransitionPair[] nextStates; private StateTransitionPair[] prevStates; private String stateVector; private String id; private int color; private double currentProb; private double nextProb; private double piProb; private HashMap<String, String> variables; private double transitionSum; public State(String[] markings, StateTransitionPair[] nextStates, String id, String stateVector, HashMap<String, String> variables) { this.markings = markings; this.nextStates = nextStates; prevStates = new StateTransitionPair[0]; this.id = id; this.stateVector = stateVector; color = 0; currentProb = 0.0; nextProb = 0.0; this.variables = variables; transitionSum = -1; } private String getID() { return id; } private HashMap<String, String> getVariables() { return variables; } private String[] getMarkings() { return markings; } private void setCurrentProb(double probability) { currentProb = probability; } private double getCurrentProb() { return currentProb; } private void setNextProb(double probability) { nextProb = probability; } private double getNextProb() { return nextProb; } private void setPiProb(double probability) { piProb = probability; } private double getPiProb() { return piProb; } private void setCurrentProbToNext() { currentProb = nextProb; } private void setCurrentProbToPi() { currentProb = piProb; } private void setTransitionSum(double transitionSum) { this.transitionSum = transitionSum; } private double getTransitionSum(double noRate, State n) { if (transitionSum == -1) { transitionSum = 0; for (StateTransitionPair next : nextStates) { transitionSum += next.getTransition(); // if (lhpn.getTransitionRateTree(next.getTransition()) != null) { // (!lhpn.isExpTransitionRateTree(next.getTransition()) // lhpn.getDelayTree(next.getTransition()).evaluateExpr(null) // if (n == null || next.equals(n)) { // return 1.0; // else { // return 0.0; // else { // transitionSum += // lhpn.getTransitionRateTree(next.getTransition()).evaluateExpr(variables); // else { // transitionSum += noRate; } } return transitionSum; } private StateTransitionPair[] getNextStatesWithTrans() { return nextStates; } private StateTransitionPair[] getPrevStatesWithTrans() { return prevStates; } public State[] getNextStates() { ArrayList<State> next = new ArrayList<State>(); for (StateTransitionPair st : nextStates) { next.add(st.getState()); } return next.toArray(new State[0]); } public State[] getPrevStates() { ArrayList<State> next = new ArrayList<State>(); for (StateTransitionPair st : prevStates) { next.add(st.getState()); } return next.toArray(new State[0]); } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getStateVector() { return stateVector; } private void addNextState(State nextState, double transition, String transitionName) { StateTransitionPair[] newNextStates = new StateTransitionPair[nextStates.length + 1]; for (int i = 0; i < nextStates.length; i++) { newNextStates[i] = nextStates[i]; } newNextStates[newNextStates.length - 1] = new StateTransitionPair(nextState, transition, transitionName); nextStates = newNextStates; nextState.addPreviousState(this, transition, transitionName); } private void addPreviousState(State prevState, double transition, String transitionName) { StateTransitionPair[] newPrevStates = new StateTransitionPair[prevStates.length + 1]; for (int i = 0; i < prevStates.length; i++) { newPrevStates[i] = prevStates[i]; } newPrevStates[newPrevStates.length - 1] = new StateTransitionPair(prevState, transition, transitionName); prevStates = newPrevStates; } private void setNextStatesWithTrans(StateTransitionPair[] trans) { nextStates = trans; } private void setPrevStatesWithTrans(StateTransitionPair[] trans) { prevStates = trans; } } public void run() { } }
package psidev.psi.mi.jami.xml.model.extension.xml300; import com.sun.xml.bind.Locatable; import com.sun.xml.bind.annotation.XmlLocation; import org.xml.sax.Locator; import psidev.psi.mi.jami.datasource.FileSourceContext; import psidev.psi.mi.jami.datasource.FileSourceLocator; import psidev.psi.mi.jami.model.CvTerm; import psidev.psi.mi.jami.model.Experiment; import psidev.psi.mi.jami.model.VariableParameterValueSet; import psidev.psi.mi.jami.xml.cache.PsiXmlIdCache; import psidev.psi.mi.jami.xml.model.extension.AbstractXmlInteractionEvidence; import psidev.psi.mi.jami.xml.model.extension.ExtendedPsiXmlExperiment; import psidev.psi.mi.jami.xml.model.extension.PsiXmlLocator; import psidev.psi.mi.jami.xml.model.reference.AbstractExperimentRef; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Xml implementation of InteractionEvidence * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>08/10/13</pre> */ @XmlRootElement(name = "interaction", namespace = "http://psi.hupo.org/mi/mif300") @XmlAccessorType(XmlAccessType.NONE) public class XmlInteractionEvidence extends AbstractXmlInteractionEvidence implements ExtendedPsiXmlInteractionEvidence { private JAXBVariableParameterValueSetWrapper jaxbVariableParameterValueSetWrapper; private JAXBCausalRelationshipWrapper jaxbCausalRelationshipWrapper; /** * <p>Constructor for XmlInteractionEvidence.</p> */ public XmlInteractionEvidence() { super(); } /** * <p>Constructor for XmlInteractionEvidence.</p> * * @param shortName a {@link java.lang.String} object. */ public XmlInteractionEvidence(String shortName) { super(shortName); } /** * <p>Constructor for XmlInteractionEvidence.</p> * * @param shortName a {@link java.lang.String} object. * @param type a {@link psidev.psi.mi.jami.model.CvTerm} object. */ public XmlInteractionEvidence(String shortName, CvTerm type) { super(shortName, type); } /** {@inheritDoc} */ @Override public Collection<VariableParameterValueSet> getVariableParameterValues() { if (this.jaxbVariableParameterValueSetWrapper == null){ this.jaxbVariableParameterValueSetWrapper = new JAXBVariableParameterValueSetWrapper(); } return this.jaxbVariableParameterValueSetWrapper.variableValueSets; } /** {@inheritDoc} */ @Override public List<ExtendedPsiXmlCausalRelationship> getCausalRelationships() { if (this.jaxbCausalRelationshipWrapper == null){ this.jaxbCausalRelationshipWrapper = new JAXBCausalRelationshipWrapper(); } return this.jaxbCausalRelationshipWrapper.causalRelationships; } /** * <p>setJAXBVariableParameterValueSetWrapper.</p> * * @param jaxbVariableValueList a {@link psidev.psi.mi.jami.xml.model.extension.xml300.XmlInteractionEvidence.JAXBVariableParameterValueSetWrapper} object. */ @XmlElement(name = "experimentalVariableValueList") public void setJAXBVariableParameterValueSetWrapper(JAXBVariableParameterValueSetWrapper jaxbVariableValueList) { this.jaxbVariableParameterValueSetWrapper = jaxbVariableValueList; } /** * <p>setJAXBCausalRelationshipWrapper.</p> * * @param jaxbCausalRelationshipWrapper a {@link psidev.psi.mi.jami.xml.model.extension.xml300.XmlInteractionEvidence.JAXBCausalRelationshipWrapper} object. */ @XmlElement(name="causalRelationshipList") public void setJAXBCausalRelationshipWrapper(JAXBCausalRelationshipWrapper jaxbCausalRelationshipWrapper) { this.jaxbCausalRelationshipWrapper = jaxbCausalRelationshipWrapper; } ////////////////////////////////////////////////////////////////// classes @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = "experimentListType") public static class JAXBExperimentWrapper implements Locatable, FileSourceContext{ private List<ExtendedPsiXmlExperiment> jaxbExperiments; private PsiXmlLocator sourceLocator; @XmlLocation @XmlTransient private Locator locator; private List<Experiment> experiments; private JAXBExperimentRefList jaxbExperimentRefList; private psidev.psi.mi.jami.xml.model.extension.ExtendedPsiXmlInteractionEvidence parent; public JAXBExperimentWrapper(){ this.experiments = new ArrayList<Experiment>(); } @XmlElement(name="experimentDescription", required = true, type = XmlExperiment.class) public List<ExtendedPsiXmlExperiment> getJAXBExperimentDescriptions() { if (jaxbExperiments == null){ jaxbExperiments = new ArrayList<ExtendedPsiXmlExperiment>(); } return jaxbExperiments; } @XmlElement(name="experimentRef", required = true, type = Integer.class) public List<Integer> getJAXBExperimentRefs() { if (this.jaxbExperimentRefList == null){ this.jaxbExperimentRefList = new JAXBExperimentRefList(); } return jaxbExperimentRefList; } @Override public Locator sourceLocation() { return (Locator)getSourceLocator(); } public FileSourceLocator getSourceLocator() { if (sourceLocator == null && locator != null){ sourceLocator = new PsiXmlLocator(locator.getLineNumber(), locator.getColumnNumber(), null); } return sourceLocator; } public void setSourceLocator(FileSourceLocator sourceLocator) { if (sourceLocator == null){ this.sourceLocator = null; } else if (sourceLocator instanceof PsiXmlLocator){ this.sourceLocator = (PsiXmlLocator)sourceLocator; } else { this.sourceLocator = new PsiXmlLocator(sourceLocator.getLineNumber(), sourceLocator.getCharNumber(), null); } } @Override public String toString() { return "Interaction Experiment List: "+(getSourceLocator() != null ? getSourceLocator().toString():super.toString()); } ////////////////////////////////////////////////// Inner classes of ExperimentList /** * The experiment ref list used by JAXB to populate experiment refs */ private class JAXBExperimentRefList extends ArrayList<Integer>{ public JAXBExperimentRefList(){ super(); } @Override public boolean add(Integer val) { if (val == null){ return false; } return experiments.add(new JAXBExperimentRefList.ExperimentRef(val)); } @Override public boolean addAll(Collection<? extends Integer> c) { if (c == null){ return false; } boolean added = false; for (Integer a : c){ if (add(a)){ added = true; } } return added; } @Override public void add(int index, Integer element) { addToSpecificIndex(index, element); } @Override public boolean addAll(int index, Collection<? extends Integer> c) { int newIndex = index; if (c == null){ return false; } boolean add = false; for (Integer a : c){ if (addToSpecificIndex(newIndex, a)){ newIndex++; add = true; } } return add; } private boolean addToSpecificIndex(int index, Integer val) { if (val == null){ return false; } experiments.add(index, new JAXBExperimentRefList.ExperimentRef(val)); return true; } @Override public String toString() { return "Interaction Experiment Reference List: "+(getSourceLocator() != null ? getSourceLocator().toString():super.toString()); } /** * Experiment ref for experimental interactor */ private class ExperimentRef extends AbstractExperimentRef { public ExperimentRef(int ref) { super(ref); } public boolean resolve(PsiXmlIdCache parsedObjects) { if (parsedObjects.containsExperiment(this.ref)){ Experiment obj = parsedObjects.getExperiment(this.ref); if (obj == null){ return false; } else if (obj instanceof ExtendedPsiXmlExperiment){ ExtendedPsiXmlExperiment exp = (ExtendedPsiXmlExperiment)obj; experiments.remove(this); experiments.add(exp); exp.getInteractionEvidences().add(parent); return true; } else { experiments.remove(this); experiments.add(obj); obj.getInteractionEvidences().add(parent); return true; } } return false; } @Override public String toString() { return "Interaction Experiment Reference: "+(ref+(getSourceLocator() != null ? ", "+getSourceLocator().toString():super.toString())); } public FileSourceLocator getSourceLocator() { return sourceLocator; } public void setSourceLocator(FileSourceLocator locator) { throw new UnsupportedOperationException("Cannot set the source locator of an experiment ref"); } } } } @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = "variableParameterValueSetList") public static class JAXBVariableParameterValueSetWrapper implements Locatable, FileSourceContext { private PsiXmlLocator sourceLocator; @XmlLocation @XmlTransient private Locator locator; private List<VariableParameterValueSet> variableValueSets; public JAXBVariableParameterValueSetWrapper(){ initialiseVariableValueSets(); } public JAXBVariableParameterValueSetWrapper(List<VariableParameterValueSet> values){ this.variableValueSets = values; } @Override public Locator sourceLocation() { return (Locator)getSourceLocator(); } public FileSourceLocator getSourceLocator() { if (sourceLocator == null && locator != null){ sourceLocator = new PsiXmlLocator(locator.getLineNumber(), locator.getColumnNumber(), null); } return sourceLocator; } public void setSourceLocator(FileSourceLocator sourceLocator) { if (sourceLocator == null){ this.sourceLocator = null; } else if (sourceLocator instanceof PsiXmlLocator){ this.sourceLocator = (PsiXmlLocator)sourceLocator; } else { this.sourceLocator = new PsiXmlLocator(sourceLocator.getLineNumber(), sourceLocator.getCharNumber(), null); } } protected void initialiseVariableValueSets(){ this.variableValueSets = new ArrayList<VariableParameterValueSet>(); } @XmlElement(type=XmlVariableParameterValueSet.class, name="experimentalVariableValues", required = true) public List<VariableParameterValueSet> getJAXBVariableParameterValues() { return this.variableValueSets; } @Override public String toString() { return "Experimental Variable parameter values : "+(getSourceLocator() != null ? getSourceLocator().toString():super.toString()); } } @XmlAccessorType(XmlAccessType.NONE) @XmlType(name="experimentalCausalRelationshipWrapper") public static class JAXBCausalRelationshipWrapper implements Locatable, FileSourceContext { private PsiXmlLocator sourceLocator; @XmlLocation @XmlTransient private Locator locator; private List<ExtendedPsiXmlCausalRelationship> causalRelationships; public JAXBCausalRelationshipWrapper(){ initialiseCausalRelationships(); } @Override public Locator sourceLocation() { return (Locator)getSourceLocator(); } public FileSourceLocator getSourceLocator() { if (sourceLocator == null && locator != null){ sourceLocator = new PsiXmlLocator(locator.getLineNumber(), locator.getColumnNumber(), null); } return sourceLocator; } public void setSourceLocator(FileSourceLocator sourceLocator) { if (sourceLocator == null){ this.sourceLocator = null; } else if (sourceLocator instanceof PsiXmlLocator){ this.sourceLocator = (PsiXmlLocator)sourceLocator; } else { this.sourceLocator = new PsiXmlLocator(sourceLocator.getLineNumber(), sourceLocator.getCharNumber(), null); } } @XmlElement(name = "causalRelationship", type = XmlCausalRelationship.class, required = true) public List<ExtendedPsiXmlCausalRelationship> getJAXBCausalRelationships() { return this.causalRelationships; } protected void initialiseCausalRelationships(){ this.causalRelationships = new ArrayList<ExtendedPsiXmlCausalRelationship>(); } @Override public String toString() { return "CausalRelationship List: "+(getSourceLocator() != null ? getSourceLocator().toString():super.toString()); } } }
package org.jtrim.taskgraph.basic; /** * Defines factory methods for {@code TaskExecutionRestrictionStrategyFactory} implementations. * * @see RestrictableTaskGraphExecutor * @see TaskExecutionRestrictionStrategyFactory */ public final class TaskExecutionRestrictionStrategies { /** * Returns a strategy which will allow executing tasks as soon as possible. * * @return a strategy which will allow executing tasks as soon as possible. This * method never returns {@code null}. */ public static TaskExecutionRestrictionStrategyFactory eagerStrategy() { return EagerTaskExecutionRestrictionStrategyBuilder.EAGER; } /** * Returns a strategy which will limit the number of scheduled nodes based * on how many leaf nodes are still retained. The strategy makes the following * assumptions: * <ul> * <li>All leaf nodes' output require the same amount of resources.</li> * <li>Non-zero resource cost is 1.</li> * <li>The output of non leaf nodes resource need is negligible.</li> * </ul> * With these assumptions, the returned strategy will ensure that the * given resource constraint is mostly met during the task graph execution. This * constraint might be broken in the following way: * <ul> * <li> * If the graph is executable with this constraint, the resource constraint * will be exceeded by less than maximum number of leafs a node in the graph * retains (i.e., the number of direct or indirect leaf dependencies it has). * </li> * <li> * The strategy will break the constraint, if breaking the constraint is necessary to * make the graph executable. * </li> * </ul> * * @param maxRetainedLeafNodes the maximum allowed resource usage of the graph execution. * This argument must be at least 1. * @return a strategy which will limit the number of scheduled nodes based * on how many leaf nodes are still retained. This method never returns {@code null}. */ public static TaskExecutionRestrictionStrategyFactory weakLeafsOfEndNodeRestrictingStrategy( int maxRetainedLeafNodes) { return new WeakLeafsOfEndNodeRestrictingStrategy(maxRetainedLeafNodes); } private TaskExecutionRestrictionStrategies() { throw new AssertionError(); } }
package org.kurento.tutorial.crowddetector; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.kurento.client.EventListener; import org.kurento.client.MediaPipeline; import org.kurento.client.WebRtcEndpoint; import org.kurento.client.KurentoClient; import org.kurento.module.crowddetector.CrowdDetectorDirectionEvent; import org.kurento.module.crowddetector.CrowdDetectorFilter; import org.kurento.module.crowddetector.CrowdDetectorFluidityEvent; import org.kurento.module.crowddetector.CrowdDetectorOccupancyEvent; import org.kurento.module.crowddetector.RegionOfInterest; import org.kurento.module.crowddetector.RegionOfInterestConfig; import org.kurento.module.crowddetector.RelativePoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; /** * Magic Mirror handler (application and media logic). * * @author Boni Garcia (bgarcia@gsyc.es) * @author David Fernandez (d.fernandezlop@gmail.com) * @since 5.0.0 */ public class CrowdDetectorHandler extends TextWebSocketHandler { private final Logger log = LoggerFactory .getLogger(CrowdDetectorHandler.class); private static final Gson gson = new GsonBuilder().create(); private final ConcurrentHashMap<String, MediaPipeline> pipelines = new ConcurrentHashMap<String, MediaPipeline>(); @Autowired private KurentoClient kurento; @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class); log.debug("Incoming message: {}", jsonMessage); switch (jsonMessage.get("id").getAsString()) { case "start": start(session, jsonMessage); break; case "stop": String sessionId = session.getId(); if (pipelines.containsKey(sessionId)) { pipelines.get(sessionId).release(); pipelines.remove(sessionId); } break; default: sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString()); break; } } private void start(final WebSocketSession session, JsonObject jsonMessage) { try { // Media Logic (Media Pipeline and Elements) MediaPipeline pipeline = kurento.createMediaPipeline(); pipelines.put(session.getId(), pipeline); WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline) .build(); List<RegionOfInterest> rois = new ArrayList<>(); List<RelativePoint> points = new ArrayList<RelativePoint>(); points.add(new RelativePoint(0, 0)); points.add(new RelativePoint(0.5F, 0)); points.add(new RelativePoint(0.5F, 0.5F)); points.add(new RelativePoint(0, 0.5F)); RegionOfInterestConfig config = new RegionOfInterestConfig(); config.setFluidityLevelMin(10); config.setFluidityLevelMed(35); config.setFluidityLevelMax(65); config.setFluidityNumFramesToEvent(5); config.setOccupancyLevelMin(10); config.setOccupancyLevelMed(35); config.setOccupancyLevelMax(65); config.setOccupancyNumFramesToEvent(5); config.setSendOpticalFlowEvent(false); config.setOpticalFlowNumFramesToEvent(3); config.setOpticalFlowNumFramesToReset(3); config.setOpticalFlowAngleOffset(0); rois.add(new RegionOfInterest(points, config, "roi0")); CrowdDetectorFilter crowdDetectorFilter = new CrowdDetectorFilter.Builder( pipeline, rois).build(); webRtcEndpoint.connect(crowdDetectorFilter); crowdDetectorFilter.connect(webRtcEndpoint); // addEventListener to crowddetector crowdDetectorFilter .addCrowdDetectorDirectionListener(new EventListener<CrowdDetectorDirectionEvent>() { @Override public void onEvent(CrowdDetectorDirectionEvent event) { JsonObject response = new JsonObject(); response.addProperty("id", "directionEvent"); response.addProperty("roiId", event.getRoiID()); response.addProperty("angle", event.getDirectionAngle()); try { session.sendMessage(new TextMessage(response .toString())); } catch (Throwable t) { sendError(session, t.getMessage()); } } }); crowdDetectorFilter .addCrowdDetectorFluidityListener(new EventListener<CrowdDetectorFluidityEvent>() { @Override public void onEvent(CrowdDetectorFluidityEvent event) { JsonObject response = new JsonObject(); response.addProperty("id", "fluidityEvent"); response.addProperty("roiId", event.getRoiID()); response.addProperty("level", event.getFluidityLevel()); response.addProperty("percentage", event.getFluidityPercentage()); try { session.sendMessage(new TextMessage(response .toString())); } catch (Throwable t) { sendError(session, t.getMessage()); } } }); crowdDetectorFilter .addCrowdDetectorOccupancyListener(new EventListener<CrowdDetectorOccupancyEvent>() { @Override public void onEvent(CrowdDetectorOccupancyEvent event) { JsonObject response = new JsonObject(); response.addProperty("id", "occupancyEvent"); response.addProperty("roiId", event.getRoiID()); response.addProperty("level", event.getOccupancyLevel()); response.addProperty("percentage", event.getOccupancyPercentage()); try { session.sendMessage(new TextMessage(response .toString())); } catch (Throwable t) { sendError(session, t.getMessage()); } } }); // SDP negotiation (offer and answer) String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); // Sending response back to client JsonObject response = new JsonObject(); response.addProperty("id", "startResponse"); response.addProperty("sdpAnswer", sdpAnswer); session.sendMessage(new TextMessage(response.toString())); } catch (Throwable t) { sendError(session, t.getMessage()); } } private void sendError(WebSocketSession session, String message) { try { JsonObject response = new JsonObject(); response.addProperty("id", "error"); response.addProperty("message", message); session.sendMessage(new TextMessage(response.toString())); } catch (IOException e) { log.error("Exception sending message", e); } } }
package org.languagetool.tagging.de; import morfologik.stemming.Dictionary; import morfologik.stemming.DictionaryLookup; import morfologik.stemming.WordData; import org.junit.Test; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import java.io.IOException; import java.util.*; import static org.junit.Assert.*; @SuppressWarnings("ConstantConditions") public class GermanTaggerTest { @Test public void testTagger() throws IOException { GermanTagger tagger = new GermanTagger(); AnalyzedTokenReadings aToken = tagger.lookup("Haus"); assertEquals("Haus[Haus/SUB:AKK:SIN:NEU, Haus/SUB:DAT:SIN:NEU, Haus/SUB:NOM:SIN:NEU]", toSortedString(aToken)); assertEquals("Haus", aToken.getReadings().get(0).getLemma()); assertEquals("Haus", aToken.getReadings().get(1).getLemma()); assertEquals("Haus", aToken.getReadings().get(2).getLemma()); AnalyzedTokenReadings aToken2 = tagger.lookup("Hauses"); assertEquals("Hauses[Haus/SUB:GEN:SIN:NEU]", toSortedString(aToken2)); assertEquals("Haus", aToken2.getReadings().get(0).getLemma()); assertNull(tagger.lookup("hauses")); assertNull(tagger.lookup("Groß")); assertEquals("Lieblingsbuchstabe[Lieblingsbuchstabe/SUB:NOM:SIN:MAS]", toSortedString(tagger.lookup("Lieblingsbuchstabe"))); AnalyzedTokenReadings aToken3 = tagger.lookup("großer"); assertEquals("großer[groß/ADJ:DAT:SIN:FEM:GRU:SOL, groß/ADJ:GEN:PLU:FEM:GRU:SOL, groß/ADJ:GEN:PLU:MAS:GRU:SOL, " + "groß/ADJ:GEN:PLU:NEU:GRU:SOL, groß/ADJ:GEN:SIN:FEM:GRU:SOL, groß/ADJ:NOM:SIN:MAS:GRU:IND, " + "groß/ADJ:NOM:SIN:MAS:GRU:SOL]", toSortedString(tagger.lookup("großer"))); assertEquals("groß", aToken3.getReadings().get(0).getLemma()); // checks for github issue #635: Some German verbs on the beginning of a sentences are identified only as substantive assertTrue(tagger.tag(Collections.singletonList("Haben"), true).toString().contains("VER")); assertTrue(tagger.tag(Collections.singletonList("Können"), true).toString().contains("VER")); assertTrue(tagger.tag(Collections.singletonList("Gerade"), true).toString().contains("ADJ")); // from both german.dict and added.txt: AnalyzedTokenReadings aToken4 = tagger.lookup("Interessen"); assertEquals("Interessen[Interesse/SUB:AKK:PLU:NEU, Interesse/SUB:DAT:PLU:NEU, " + "Interesse/SUB:GEN:PLU:NEU, Interesse/SUB:NOM:PLU:NEU]", toSortedString(aToken4)); assertEquals("Interesse", aToken4.getReadings().get(0).getLemma()); assertEquals("Interesse", aToken4.getReadings().get(1).getLemma()); assertEquals("Interesse", aToken4.getReadings().get(2).getLemma()); assertEquals("Interesse", aToken4.getReadings().get(3).getLemma()); // words that are not in the dictionary but that are recognized thanks to noun splitting: AnalyzedTokenReadings aToken5 = tagger.lookup("Donaudampfschiff"); assertEquals("Donaudampfschiff[Donaudampfschiff/SUB:AKK:SIN:NEU, Donaudampfschiff/SUB:DAT:SIN:NEU, " + "Donaudampfschiff/SUB:NOM:SIN:NEU]", toSortedString(aToken5)); assertEquals("Donaudampfschiff", aToken5.getReadings().get(0).getLemma()); assertEquals("Donaudampfschiff", aToken5.getReadings().get(1).getLemma()); AnalyzedTokenReadings aToken6 = tagger.lookup("Häuserkämpfe"); assertEquals("Häuserkämpfe[Häuserkampf/SUB:AKK:PLU:MAS, Häuserkampf/SUB:GEN:PLU:MAS, Häuserkampf/SUB:NOM:PLU:MAS]", toSortedString(aToken6)); assertEquals("Häuserkampf", aToken6.getReadings().get(0).getLemma()); assertEquals("Häuserkampf", aToken6.getReadings().get(1).getLemma()); assertEquals("Häuserkampf", aToken6.getReadings().get(2).getLemma()); AnalyzedTokenReadings aToken7 = tagger.lookup("Häuserkampfes"); assertEquals("Häuserkampfes[Häuserkampf/SUB:GEN:SIN:MAS]", toSortedString(aToken7)); assertEquals("Häuserkampf", aToken7.getReadings().get(0).getLemma()); AnalyzedTokenReadings aToken8 = tagger.lookup("Häuserkampfs"); assertEquals("Häuserkampfs[Häuserkampf/SUB:GEN:SIN:MAS]", toSortedString(aToken8)); assertEquals("Häuserkampf", aToken8.getReadings().get(0).getLemma()); AnalyzedTokenReadings aToken9 = tagger.lookup("Lieblingsfarben"); assertEquals("Lieblingsfarben[Lieblingsfarbe/SUB:AKK:PLU:FEM, Lieblingsfarbe/SUB:DAT:PLU:FEM, " + "Lieblingsfarbe/SUB:GEN:PLU:FEM, Lieblingsfarbe/SUB:NOM:PLU:FEM]", toSortedString(aToken9)); assertEquals("Lieblingsfarbe", aToken9.getReadings().get(0).getLemma()); AnalyzedTokenReadings aToken10 = tagger.lookup("Autolieblingsfarben"); assertEquals("Autolieblingsfarben[Autolieblingsfarbe/SUB:AKK:PLU:FEM, Autolieblingsfarbe/SUB:DAT:PLU:FEM, " + "Autolieblingsfarbe/SUB:GEN:PLU:FEM, Autolieblingsfarbe/SUB:NOM:PLU:FEM]", toSortedString(aToken10)); assertEquals("Autolieblingsfarbe", aToken10.getReadings().get(0).getLemma()); AnalyzedTokenReadings aToken11 = tagger.lookup("übrigbleibst"); assertEquals("übrigbleibst[übrigbleiben/VER:2:SIN:PRÄ:NON:NEB]", toSortedString(aToken11)); assertEquals("übrigbleiben", aToken11.getReadings().get(0).getLemma()); } // make sure we use the version of the POS data that was extended with post spelling reform data @Test public void testExtendedTagger() throws IOException { GermanTagger tagger = new GermanTagger(); assertEquals("Kuß[Kuß/SUB:AKK:SIN:MAS, Kuß/SUB:DAT:SIN:MAS, Kuß/SUB:NOM:SIN:MAS]", toSortedString(tagger.lookup("Kuß"))); assertEquals("Kuss[Kuss/SUB:AKK:SIN:MAS, Kuss/SUB:DAT:SIN:MAS, Kuss/SUB:NOM:SIN:MAS]", toSortedString(tagger.lookup("Kuss"))); assertEquals("Haß[Haß/SUB:AKK:SIN:MAS, Haß/SUB:DAT:SIN:MAS, Haß/SUB:NOM:SIN:MAS]", toSortedString(tagger.lookup("Haß"))); assertEquals("Hass[Hass/SUB:AKK:SIN:MAS, Hass/SUB:DAT:SIN:MAS, Hass/SUB:NOM:SIN:MAS]", toSortedString(tagger.lookup("Hass"))); assertEquals("muß[müssen/VER:MOD:1:SIN:PRÄ, müssen/VER:MOD:3:SIN:PRÄ]", toSortedString(tagger.lookup("muß"))); assertEquals("muss[müssen/VER:MOD:1:SIN:PRÄ, müssen/VER:MOD:3:SIN:PRÄ]", toSortedString(tagger.lookup("muss"))); } @Test public void testTaggerBaseforms() throws IOException { GermanTagger tagger = new GermanTagger(); List<AnalyzedToken> readings1 = tagger.lookup("übrigbleibst").getReadings(); assertEquals(1, readings1.size()); assertEquals("übrigbleiben", readings1.get(0).getLemma()); List<AnalyzedToken> readings2 = tagger.lookup("Haus").getReadings(); assertEquals(3, readings2.size()); assertEquals("Haus", readings2.get(0).getLemma()); assertEquals("Haus", readings2.get(1).getLemma()); assertEquals("Haus", readings2.get(2).getLemma()); List<AnalyzedToken> readings3 = tagger.lookup("Häuser").getReadings(); assertEquals(3, readings3.size()); assertEquals("Haus", readings3.get(0).getLemma()); assertEquals("Haus", readings3.get(1).getLemma()); assertEquals("Haus", readings3.get(2).getLemma()); } @Test public void testTaggerDashLinkedWords() throws IOException { GermanTagger tagger = new GermanTagger(); List<AnalyzedToken> readings1 = tagger.lookup("SSL-Zertifikat").getReadings(); assertEquals(3, readings1.size()); assertEquals("Zertifikat", readings1.get(0).getLemma()); List<AnalyzedToken> readings2 = tagger.lookup("H-Milch").getReadings(); assertEquals(4, readings2.size()); assertEquals("Milch", readings2.get(0).getLemma()); List<AnalyzedToken> readings3 = tagger.lookup("Entweder-oder").getReadings(); assertEquals(8, readings3.size()); assertEquals("Entweder-oder", readings3.get(0).getLemma()); List<AnalyzedToken> readings4 = tagger.lookup("100-m-Lauf").getReadings(); assertEquals(3, readings4.size()); assertEquals("Lauf", readings4.get(0).getLemma()); } @Test public void testTag() throws IOException { GermanTagger tagger = new GermanTagger(); List<String> upperCaseWord = Arrays.asList("Das"); List<AnalyzedTokenReadings> readings = tagger.tag(upperCaseWord, false); assertEquals("[Das[Das/null*]]", readings.toString()); List<AnalyzedTokenReadings> readings2 = tagger.tag(upperCaseWord, true); assertTrue(readings2.toString().startsWith("[Das[der/ART:")); } @Test public void testTagWithManualDictExtension() throws IOException { // words not originally in Morphy but added in LT 1.8 (moved from added.txt to german.dict) GermanTagger tagger = new GermanTagger(); List<AnalyzedTokenReadings> readings = tagger.tag(Collections.singletonList("Wichtigtuerinnen")); assertEquals("[Wichtigtuerinnen[Wichtigtuerin/SUB:AKK:PLU:FEM*," + "Wichtigtuerin/SUB:DAT:PLU:FEM*,Wichtigtuerin/SUB:GEN:PLU:FEM*,Wichtigtuerin/SUB:NOM:PLU:FEM*]]", readings.toString()); } @Test public void testDictionary() throws IOException { Dictionary dictionary = Dictionary.read( JLanguageTool.getDataBroker().getFromResourceDirAsUrl("/de/german.dict")); DictionaryLookup dl = new DictionaryLookup(dictionary); for (WordData wd : dl) { if (wd.getTag() == null || wd.getTag().length() == 0) { System.err.println("**** Warning: the word " + wd.getWord() + "/" + wd.getStem() + " lacks a POS tag in the dictionary."); } } } /** * Returns a string representation like {@code toString()}, but sorts * the elements alphabetically. */ private String toSortedString(AnalyzedTokenReadings tokenReadings) { StringBuilder sb = new StringBuilder(tokenReadings.getToken()); Set<String> elements = new TreeSet<>(); sb.append('['); for (AnalyzedToken reading : tokenReadings) { if (!elements.contains(reading.toString())) { elements.add(reading.toString()); } } sb.append(String.join(", ", elements)); sb.append(']'); return sb.toString(); } }
package org.silverpeas.process.annotation; import com.stratelia.webactiv.util.ActionType; import com.stratelia.webactiv.util.WAPrimaryKey; import org.silverpeas.process.io.file.DummyHandledFile; import org.silverpeas.process.io.file.FileHandler; import org.silverpeas.process.management.AbstractFileProcess; import org.silverpeas.process.management.ProcessExecutionContext; import org.silverpeas.process.session.ProcessSession; import java.util.List; import java.util.Map; public class SimulationElementConversionProcess extends AbstractFileProcess<ProcessExecutionContext> { private final Map<Class<SimulationElement>, List<SimulationElement>> elements; private final WAPrimaryKey targetPK; private final ActionType actionType; /** * Default constructor. * @param elements * @param targetPK * @param actionType */ SimulationElementConversionProcess( final Map<Class<SimulationElement>, List<SimulationElement>> elements, final WAPrimaryKey targetPK, final ActionType actionType) { this.elements = elements; this.targetPK = targetPK; this.actionType = actionType; } @SuppressWarnings("unchecked") @Override public void processFiles(final ProcessExecutionContext processExecutionProcess, final ProcessSession session, final FileHandler fileHandler) throws Exception { // Converting each element for (Map.Entry<Class<SimulationElement>, List<SimulationElement>> typeElements : elements .entrySet()) { // Getting the right converter according to the type of elements DummyHandledFileConverter<? extends SimulationElement> converter = DummyHandledFileConverterRegistration.getConverter(typeElements.getKey()); // Technical assertion if (converter == null) { throw new AssertionError( "SimulationElementConversionProcess.processFiles : converter is null " + "(converter must exist for a type of element)"); } // Convert elements and add each one converted to the file handler List<DummyHandledFile> handledFiles = converter.convert((List) typeElements.getValue(), targetPK, actionType); for (DummyHandledFile dummyHandledFile : handledFiles) { fileHandler.addDummyHandledFile(dummyHandledFile); } } } }
package org.cytoscape.view.manual.internal.rotate; import org.cytoscape.math.xform.AffineTransform3D; import org.cytoscape.math.xform.AxisRotation3D; import org.cytoscape.math.xform.Translation3D; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNode; import org.cytoscape.view.manual.internal.layout.algorithm.MutablePolyEdgeGraphLayout; public final class RotationLayouter { private final MutablePolyEdgeGraphLayout m_graph; private Translation3D m_translationToOrig; private Translation3D m_translationFromOrig; public RotationLayouter(MutablePolyEdgeGraphLayout graph) { m_graph = graph; double xMin = Double.MAX_VALUE; double xMax = Double.MIN_VALUE; double yMin = Double.MAX_VALUE; double yMax = Double.MIN_VALUE; for ( CyEdge edge : m_graph.edges() ) { if (!(m_graph.isMovableNode(edge.getSource()) && m_graph.isMovableNode(edge.getTarget()))) continue; /* TODO support anchors final int numAnchors = m_graph.getNumAnchors(edge); for (int j = 0; j < numAnchors; j++) { double anchXPosition = m_graph.getAnchorPosition(edge, j, true); double anchYPosition = m_graph.getAnchorPosition(edge, j, false); xMin = Math.min(xMin, anchXPosition); xMax = Math.max(xMax, anchXPosition); yMin = Math.min(yMin, anchYPosition); yMax = Math.max(yMax, anchYPosition); } */ } for ( CyNode node : m_graph.nodes() ) { if (!m_graph.isMovableNode(node)) continue; double nodeXPosition = m_graph.getNodePosition(node, true); double nodeYPosition = m_graph.getNodePosition(node, false); xMin = Math.min(xMin, nodeXPosition); xMax = Math.max(xMax, nodeXPosition); yMin = Math.min(yMin, nodeYPosition); yMax = Math.max(yMax, nodeYPosition); } if (xMax < 0) // Nothing is movable. return; final double xRectCenter = (xMin + xMax) / 2.0d; final double yRectCenter = (yMin + yMax) / 2.0d; double rectWidth = xMax - xMin; double rectHeight = yMax - yMin; double hypotenuse = 0.5d * Math.sqrt((rectWidth * rectWidth) + (rectHeight * rectHeight)); if (((xRectCenter - hypotenuse) < 0.0d) || ((xRectCenter + hypotenuse) > m_graph.getMaxWidth()) || ((yRectCenter - hypotenuse) < 0.0d) || ((yRectCenter + hypotenuse) > m_graph.getMaxHeight())) return; m_translationToOrig = new Translation3D(-xRectCenter, -yRectCenter, 0.0d); m_translationFromOrig = new Translation3D(xRectCenter, yRectCenter, 0.0d); } private final double[] m_pointBuff = new double[3]; public void rotateGraph(double radians) { if (m_translationToOrig == null) return; final AffineTransform3D xform = m_translationToOrig.concatenatePost( (new AxisRotation3D(AxisRotation3D.Z_AXIS, radians)) .concatenatePost(m_translationFromOrig)); for ( CyNode node : m_graph.nodes() ) { if (!m_graph.isMovableNode(node)) continue; m_pointBuff[0] = m_graph.getNodePosition(node, true); m_pointBuff[1] = m_graph.getNodePosition(node, false); m_pointBuff[2] = 0.0d; xform.transformArr(m_pointBuff); m_graph.setNodePosition(node, m_pointBuff[0], m_pointBuff[1]); } for ( CyEdge edge : m_graph.edges() ) { if (!(m_graph.isMovableNode(edge.getSource()) && m_graph.isMovableNode(edge.getTarget()))) continue; /* TODO support anchors final int numAnchors = m_graph.getNumAnchors(edge); for (int j = 0; j < numAnchors; j++) { m_pointBuff[0] = m_graph.getAnchorPosition(edge, j, true); m_pointBuff[1] = m_graph.getAnchorPosition(edge, j, false); m_pointBuff[2] = 0.0d; xform.transformArr(m_pointBuff); m_graph.setAnchorPosition(edge, j, m_pointBuff[0], m_pointBuff[1]); } */ } } }
package org.eclipse.birt.report.model.simpleapi; import org.eclipse.birt.report.model.api.SortElementHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.simpleapi.ISortElement; import org.eclipse.birt.report.model.elements.interfaces.ISortElementModel; public class SortElement extends DesignElement implements ISortElement { /** * Default constructor. * * @param handle */ public SortElement( SortElementHandle handle ) { super( handle ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.ISortElement#getDirection() */ public String getDirection( ) { return ( (SortElementHandle) handle ).getDirection( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.simpleapi.ISortElement#getKey() */ public String getKey( ) { return ( (SortElementHandle) handle ).getKey( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.ISortElement#setDirection * (java.lang.String) */ public void setDirection( String direction ) throws SemanticException { setProperty( ISortElementModel.DIRECTION_PROP, direction ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.api.simpleapi.ISortElement#setKey(java. * lang.String) */ public void setKey( String key ) throws SemanticException { setProperty( ISortElementModel.KEY_PROP, key ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.motechproject.mobile.itests; import org.motechproject.mobile.imp.serivce.IMPService; import org.motechproject.mobile.omi.service.OMIService; import org.motechproject.mobile.omp.service.MessagingService; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Properties; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.mobile.core.model.IncomingMessageResponse; import org.motechproject.ws.ContactNumberType; import org.motechproject.ws.MediaType; import org.motechproject.ws.MessageStatus; import org.motechproject.ws.NameValuePair; import org.motechproject.ws.Patient; import org.motechproject.ws.mobile.MessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /** * Integration tests for the MessageServiceImpl class * * @author Kofi A. Asamoah (yoofi@dreamoval.com) * Date Created Aug 10, 2009 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:WEB-INF/webapp-config.xml","classpath:META-INF/client-config.xml"}) public class MessageServiceImplITCase { Properties testProps; @Resource MessageService client; @Autowired OMIService omiService; @Autowired MessagingService smsService; @Autowired IMPService impService; public MessageServiceImplITCase() { } @Before public void setUp(){ testProps = new Properties(); try{ testProps.load(getClass().getResourceAsStream("/test.properties")); } catch(IOException ex){ System.out.print(ex); } } /** * Test of sendPatientMessage method, of class MessageServiceImpl. */ @Test public void testSendPatientMessage() { System.out.println("sendPatientMessage"); String messageId = "testId1"; NameValuePair attrib = new NameValuePair("PatientFirstName", "Tester"); NameValuePair attrib2 = new NameValuePair("DueDate", "now"); NameValuePair[] personalInfo = new NameValuePair[]{attrib, attrib2}; Date serviceDate = new Date(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, 1); Date endDate = cal.getTime(); String patientNumber = testProps.getProperty("patientNumber", "000000000000"); ContactNumberType patientNumberType = ContactNumberType.PERSONAL; MediaType messageType = MediaType.TEXT; MessageStatus result = client.sendPatientMessage(messageId, personalInfo, patientNumber, patientNumberType, "en", messageType, 2L, serviceDate, endDate, "123456789"); assertEquals(result, MessageStatus.QUEUED); } /** * Test of sendPatientMessage method, of class MessageServiceImpl. */ @Test public void testSendPatientMessage_NullInfo() { System.out.println("sendPatientMessage with null personalInfo"); String messageId = "testId2"; Date serviceDate = new Date(); String patientNumber = testProps.getProperty("patientNumber", "000000000000"); ContactNumberType patientNumberType = ContactNumberType.PERSONAL; MediaType messageType = MediaType.TEXT; MessageStatus result = client.sendPatientMessage(messageId, null, patientNumber, patientNumberType, "nan", messageType, 3L, serviceDate, serviceDate, "123456789"); assertEquals(result, MessageStatus.QUEUED); } /** * Test of sendPatientMessage method, of class MessageServiceImpl. */ @Test public void testSendPatientMessage_NullDate() { System.out.println("sendPatientMessage with null dates"); String messageId = "testId3"; NameValuePair attrib = new NameValuePair("PatientFirstName", "Tester"); NameValuePair attrib2 = new NameValuePair("DueDate", "now"); NameValuePair[] personalInfo = new NameValuePair[]{attrib, attrib2}; String patientNumber = testProps.getProperty("patientNumber", "000000000000"); ContactNumberType patientNumberType = ContactNumberType.PERSONAL; MediaType messageType = MediaType.TEXT; MessageStatus result = client.sendPatientMessage(messageId, personalInfo, patientNumber, patientNumberType, "kas", messageType, 4L, null, null, "123456789"); assertEquals(result, MessageStatus.PENDING); } /** * Test of sendCHPSMessage method of MessageServiceImpl class. */ @Test public void testSendCHPSMessage() { System.out.println("sendCHPSMessage"); String messageId = "testId4"; String workerNumber = testProps.getProperty("workerNumber", "000000000000"); Date serviceDate = new Date(); MediaType messageType = MediaType.TEXT; NameValuePair attrib = new NameValuePair("Test", "Test"); NameValuePair[] personalInfo = new NameValuePair[]{attrib}; Patient patient = new Patient(); patient.setPreferredName("Test patient"); patient.setMotechId("TS000000001"); Patient[] patientList = new Patient[]{patient}; MessageStatus result = client.sendCHPSMessage(messageId, personalInfo, workerNumber, patientList, "en", messageType, 5L, serviceDate, serviceDate); assertEquals(result, MessageStatus.QUEUED); } /** * Test of sendCHPSMessage method of MessageServiceImpl class. */ @Test public void testSendCHPSMessage_NullInfo() { System.out.println("sendCHPSMessage with null personalInfo"); String messageId = "testId5"; String workerNumber = testProps.getProperty("workerNumber", "000000000000"); Date serviceDate = new Date(); MediaType messageType = MediaType.TEXT; Patient patient = new Patient(); patient.setPreferredName("Test patient"); patient.setMotechId("TS000000001"); Patient[] patientList = new Patient[]{patient}; MessageStatus result = client.sendCHPSMessage(messageId, null, workerNumber, patientList, "kas", messageType, 6L, serviceDate, serviceDate); assertEquals(result, MessageStatus.QUEUED); } /** * Test of sendCHPSMessage method of MessageServiceImpl class. */ @Test public void testSendCHPSMessage_NullPatient() { System.out.println("sendCHPSMessage with null patientList"); String messageId = "testId6"; String workerNumber = testProps.getProperty("workerNumber", "000000000000"); Date serviceDate = new Date(); MediaType messageType = MediaType.TEXT; NameValuePair attrib = new NameValuePair("Test", "Test"); NameValuePair[] personalInfo = new NameValuePair[]{attrib}; MessageStatus result = client.sendCHPSMessage(messageId, personalInfo, workerNumber, null, "nan", messageType, 7L, serviceDate, serviceDate); assertEquals(result, MessageStatus.QUEUED); } /** * Test of sendCHPSMessage method of MessageServiceImpl class. */ @Test public void testSendCHPSMessage_NullDates() { System.out.println("sendCHPSMessage with null dates"); String messageId = "testId7"; String workerNumber = testProps.getProperty("workerNumber", "000000000000"); Date serviceDate = null; MediaType messageType = MediaType.TEXT; NameValuePair attrib = new NameValuePair("Test", "Test"); NameValuePair[] personalInfo = new NameValuePair[]{attrib}; Patient patient = new Patient(); patient.setPreferredName("Test patient"); patient.setMotechId("TS000000001"); Patient[] patientList = new Patient[]{patient}; MessageStatus result = client.sendCHPSMessage(messageId, personalInfo, workerNumber, patientList, "en", messageType, 8L, serviceDate, serviceDate); assertEquals(result, MessageStatus.PENDING); } @Test public void testProcessMessageRequests(){ System.out.println("processMessageRequests"); omiService.processMessageRequests(); } @Test public void testSendScheduledMessages(){ System.out.println("sendScheduledMessages"); smsService.sendScheduledMessages(); } @Test public void testUpdateMessageStatuses(){ System.out.println("updateMessageStatuses"); smsService.updateMessageStatuses(); } @Test public void testGetMessageResponses(){ System.out.println("getMessageResponses"); omiService.getMessageResponses(); } @Test public void testProcessMessageRetries(){ System.out.println("processMessageRetries"); omiService.processMessageRetries(); } @Test public void testProcessRequest(){ System.out.println("processRequest"); String request = "Type=GeneralOPD\nCHPSID=123ABC\nDate=02-03-2010\nSerialNo=ANC123\nSex=f\nDoB=28/05/1981\nInsured=y\nNewCase=n\nDiagnosis=35\nSecondaryDiagnosis=14\nReferral=yup\ntime=" + new Date().getTime(); String number = "555555555"; String expResult = "Errors:\nReferral=wrong format"; IncomingMessageResponse result = impService.processRequest(request, number, false); assertEquals(result.getContent(),expResult); request = "Type=GeneralOPD\nCHPSID=123ABC\nDate=02-03-2010\nSerialNo=ANC123\nSex=f\nDoB=28/05/1981\nInsured=y\nNewCase=n\nDiagnosis=35\nSecondaryDiagnosis=14\nReferral=y\ntime=" + new Date().getTime(); expResult = "An unexpected error occurred! Please try again."; result = impService.processRequest(request, number, false); System.out.println("result: " + (result == null ? "NULL" : result.getContent())); System.out.println("expected: " + expResult); assertEquals(result.getContent(),expResult); } }
package com.github.kmbulebu.nicknack.core.providers; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.XMLConfiguration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import rx.Observable; import rx.Subscriber; import rx.observables.ConnectableObservable; import com.github.kmbulebu.nicknack.core.actions.Action; import com.github.kmbulebu.nicknack.core.actions.ActionDefinition; import com.github.kmbulebu.nicknack.core.actions.ActionFailureException; import com.github.kmbulebu.nicknack.core.actions.ActionParameterException; import com.github.kmbulebu.nicknack.core.events.Event; import com.github.kmbulebu.nicknack.core.events.EventDefinition; import com.github.kmbulebu.nicknack.core.states.StateDefinition; public class ProviderServiceImpl implements ProviderService, OnEventListener, rx.Observable.OnSubscribe<Event> { private static final Logger LOG = LogManager.getLogger(); private static ProviderServiceImpl service; private ProviderLoader loader; private final Map<UUID, EventDefinition> eventDefinitions = new HashMap<UUID, EventDefinition>(); private final Map<UUID, StateDefinition> stateDefinitions = new HashMap<UUID, StateDefinition>(); private final Map<UUID, ActionDefinition> actionDefinitions = new HashMap<UUID, ActionDefinition>(); private final Map<UUID, Provider> providers = new HashMap<UUID, Provider>(); private final Map<UUID, UUID> eventDefinitionToProvider = new HashMap<UUID, UUID>(); private final Map<UUID, UUID> stateDefinitionToProvider = new HashMap<UUID, UUID>(); private final Map<UUID, UUID> actionDefinitionToProvider = new HashMap<UUID, UUID>(); private ConnectableObservable<Event> eventStream; private Subscriber<? super Event> subscriber; private final XMLConfiguration configuration; private ProviderServiceImpl(final Path providersDirectory, final XMLConfiguration configuration) { this.configuration = configuration; loader = new ProviderLoader(providersDirectory); eventStream = Observable.create(this).publish(); eventStream.connect(); // TODO Do something smart with the errors. initializeProviders(); } public static synchronized ProviderServiceImpl getInstance(final Path providersDirectory, final XMLConfiguration configuration) { if (LOG.isTraceEnabled()) { LOG.entry(configuration); } if (service == null) { service = new ProviderServiceImpl(providersDirectory, configuration); } if (LOG.isTraceEnabled()) { LOG.exit(service); } return service; } /* (non-Javadoc) * @see com.oakcity.nicknack.core.providers.ProviderService#getActionDefinitions() */ @Override public Map<UUID, ActionDefinition> getActionDefinitions() { return Collections.unmodifiableMap(actionDefinitions); } /* (non-Javadoc) * @see com.oakcity.nicknack.core.providers.ProviderService#getEventDefinitions() */ @Override public Map<UUID, EventDefinition> getEventDefinitions() { return Collections.unmodifiableMap(eventDefinitions); } @Override public Map<UUID, StateDefinition> getStateDefinitions() { return Collections.unmodifiableMap(stateDefinitions); } @Override public Map<UUID, Provider> getProviders() { return Collections.unmodifiableMap(providers); } protected List<Exception> initializeProviders() { if (LOG.isTraceEnabled()) { LOG.entry(); } Iterator<Provider> providers; try { providers = loader.loadProviders().iterator(); } catch (IOException e) { LOG.error("Could not load providers. " + e.getMessage(), e); return Collections.emptyList(); } Provider provider = null; List<Exception> errors = new ArrayList<Exception>(); if (LOG.isInfoEnabled()) { LOG.info("Loading providers."); } while (providers.hasNext()) { provider = providers.next(); errors.addAll(initializeProvider(provider)); } return errors; } protected List<Exception> initializeProvider(Provider provider) { List<Exception> errors = new ArrayList<Exception>(); try { if (LOG.isInfoEnabled()) { LOG.info("Found provider: " + provider.getName() + " v" + provider.getVersion() + " by " + provider.getAuthor()); } this.providers.put(provider.getUuid(), provider); final String configKey = "providers.uuid" + provider.getUuid().toString().replaceAll("-", ""); if (!configuration.containsKey(configKey + ".name")) { configuration.addProperty(configKey + ".name", provider.getName()); } final Configuration providerConfig = configuration.configurationAt(configKey, true); boolean disabled = providerConfig.getBoolean("disabled", false); if (disabled) { if (LOG.isInfoEnabled()) { LOG.info("Per configuration, disabling provider: " + provider.getName() + " v" + provider.getVersion() + " by " + provider.getAuthor()); } } else { provider.init(providerConfig, this); if (provider.getEventDefinitions() != null) { for (EventDefinition eventDef : provider.getEventDefinitions()) { UUID uuid = eventDef.getUUID(); if (uuid == null) { LOG.error("Provider, " + provider.getName() + " (" + provider.getUuid() + ") has an Event Definition with null UUID."); } else { eventDefinitions.put(uuid, eventDef); eventDefinitionToProvider.put(uuid, provider.getUuid()); } } } if (provider.getStateDefinitions() != null) { for (StateDefinition stateDef : provider.getStateDefinitions()) { UUID uuid = stateDef.getUUID(); if (uuid == null) { LOG.error("Provider, " + provider.getName() + " (" + provider.getUuid() + ") has an State Definition with null UUID."); } else { stateDefinitions.put(uuid, stateDef); stateDefinitionToProvider.put(uuid, provider.getUuid()); } } } if (provider.getActionDefinitions() != null) { for (ActionDefinition actionDef : provider.getActionDefinitions()) { UUID uuid = actionDef.getUUID(); if (uuid == null) { LOG.error("Provider, " + provider.getName() + " (" + provider.getUuid() + ") has an Action Definition with null UUID."); } else { actionDefinitions.put(uuid, actionDef); actionDefinitionToProvider.put(uuid, provider.getUuid()); } } } } // If disabled } catch (Exception e) { LOG.error("Failed to initialize provider, " + provider.getName() + " (" + provider.getUuid() + "):" + e.getMessage(), e); errors.add(e); } return errors; } @Override public void onEvent(Event event) { if (LOG.isTraceEnabled()) { LOG.entry(event); } if (subscriber != null) { subscriber.onNext(event); } if (LOG.isTraceEnabled()) { LOG.exit(); } } @Override public Observable<Event> getEvents() { return eventStream; } @Override public void call(Subscriber<? super Event> subscriber) { this.subscriber = subscriber; } @Override public void run(Action action) throws ActionFailureException, ActionParameterException { if (LOG.isTraceEnabled()) { LOG.entry(action); } final UUID actionDefinitionUuid = action.getAppliesToActionDefinition(); final UUID providerUuid = actionDefinitionToProvider.get(actionDefinitionUuid); final Provider provider = providers.get(providerUuid); try { provider.run(action); } catch (ActionFailureException | ActionParameterException e) { LOG.throwing(e); throw e; } catch (Exception e) { // Any unknown or unexpected exceptions are wrapped as a failure and thrown. final ActionFailureException afe = new ActionFailureException(e); LOG.throwing(afe); throw afe; } if (LOG.isTraceEnabled()) { LOG.exit(); } } @Override public Provider getProviderByActionDefinitionUuid(UUID actionDefinitionUuid) { UUID providerUuid = actionDefinitionToProvider.get(actionDefinitionUuid); if (providerUuid == null) { return null; } return providers.get(providerUuid); } @Override public Provider getProviderByEventDefinitionUuid(UUID eventDefinitionUuid) { UUID providerUuid = eventDefinitionToProvider.get(eventDefinitionUuid); if (providerUuid == null) { return null; } return providers.get(providerUuid); } @Override public Provider getProviderByStateDefinitionUuid(UUID stateDefinitionUuid) { UUID providerUuid = stateDefinitionToProvider.get(stateDefinitionUuid); if (providerUuid == null) { return null; } return providers.get(providerUuid); } @Override public List<Exception> addProvider(Provider provider) { return initializeProvider(provider); } }
package org.nuxeo.ecm.webapp.liveedit; import static org.jboss.seam.ScopeType.SESSION; import static org.jboss.seam.annotations.Install.FRAMEWORK; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.faces.context.FacesContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.Install; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.nuxeo.runtime.api.Framework; /** * This Seam component is used to represent the client configuration for LiveEdit. * On the client side, the LiveEdit plugin adertise it's feature via the Accept Header of the browser. * This information may be used to decide if LiveEdit links must be displayed or not. * * The behavior can be configured via the nuxeo.properties : * org.nuxeo.ecm.platform.liveedit.config * There are 3 possible values : * * - client : let the client choose what is live editable * => use the mime-types send by the client to define what must be live editable * - server : let the server decide * => use the mime-type registry define what types are liveEditable * - both : use client and server intersection * => in order to be liveEdititable a type must be advertised by the client and set to liveEditable in the mimetypeRegistry * * Client advertising is done in the Accept header: * Accept : application/x-nuxeo-liveedit:mimetype1;mimetype2 * * * @author Thierry Delprat */ @Scope(SESSION) @Name("liveEditClientConfig") @Install(precedence = FRAMEWORK) public class LiveEditClientConfig implements Serializable { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(LiveEditClientConfig.class); protected Boolean clientHasLiveEditInstalled=null; protected List<String> advertizedLiveEditableMimeTypes = null; protected static String liveEditConfigPolicy=null; public static final String LE_MIME_TYPE="application/x-nuxeo-liveedit"; public static final String LE_CONFIG_PROPERTY="org.nuxeo.ecm.platform.liveedit.config"; public static final String LE_CONFIG_CLIENTSIDE="client"; public static final String LE_CONFIG_SERVERSIDE="server"; public static final String LE_CONFIG_BOTHSIDES="both"; protected void detectLiveEditClientConfig() { clientHasLiveEditInstalled=false; advertizedLiveEditableMimeTypes= new ArrayList<String>(); if (getLiveEditConfigurationPolicy().equals(LE_CONFIG_SERVERSIDE)) { // in case if Server side config, consider liveEdit is installed clientHasLiveEditInstalled=true; return; } FacesContext fContext=FacesContext.getCurrentInstance(); if (fContext==null) { log.error("unable to fetch facesContext, can not detect liveEdit client config"); } else { Map<String,String> headers = fContext.getExternalContext().getRequestHeaderMap(); String accept = headers.get("Accept"); if (accept==null) return; String[] accepted = accept.split(","); for (int i=0; i<accepted.length;i++) { String acceptHeader =accepted[i]; if (acceptHeader!=null) { acceptHeader=acceptHeader.trim(); } else continue; if (acceptHeader.startsWith(LE_MIME_TYPE)) { clientHasLiveEditInstalled=true; String[] subTypes = acceptHeader.split(";"); for (int j=0;j<subTypes.length;j++) { String subMT = subTypes[j].replace("!", "/"); advertizedLiveEditableMimeTypes.add(subMT); } } } } } public boolean isLiveEditInstalled() { if (clientHasLiveEditInstalled==null) { detectLiveEditClientConfig(); } return clientHasLiveEditInstalled; } public String getLiveEditConfigurationPolicy() { if (liveEditConfigPolicy==null){ liveEditConfigPolicy=Framework.getProperty(LE_CONFIG_PROPERTY, LE_CONFIG_CLIENTSIDE); } return liveEditConfigPolicy; } public boolean isMimeTypeLiveEditable(String mimetype) { if (advertizedLiveEditableMimeTypes==null){ detectLiveEditClientConfig(); } if (advertizedLiveEditableMimeTypes.contains(mimetype)){ return true; } else { return false; } } }
package org.javarosa.core.model.instance.test; import j2meunit.framework.Test; import j2meunit.framework.TestCase; import j2meunit.framework.TestMethod; import j2meunit.framework.TestSuite; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.javarosa.core.model.IDataReference; import org.javarosa.core.model.IFormDataModel; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.model.instance.DataModelTree; import org.javarosa.core.model.instance.QuestionDataElement; import org.javarosa.core.model.instance.QuestionDataGroup; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.utils.ITreeVisitor; import org.javarosa.core.model.utils.PrototypeFactory; import org.javarosa.core.util.UnavailableExternalizerException; public class QuestionDataElementTests extends TestCase{ private final String stringElementName = "String Data Element"; StringData stringData; IntegerData integerData; IDataReference stringReference; IDataReference integerReference; QuestionDataElement stringElement; QuestionDataElement intElement; private static int NUM_TESTS = 8; /* (non-Javadoc) * @see j2meunit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); stringData = new StringData("Answer Value"); integerData = new IntegerData(4); stringReference = new IDataReference() { String reference = "stringValue"; public Object getReference() { return reference; } public void setReference(Object reference) { this.reference = (String)reference; } public boolean referenceMatches(IDataReference reference) { return this.reference.equals(reference.getReference()); } public IDataReference clone() { IDataReference newReference = null; try { newReference = (IDataReference)this.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } newReference.setReference(reference); return newReference; } public void readExternal(DataInputStream in) throws IOException, InstantiationException, IllegalAccessException, UnavailableExternalizerException {} public void writeExternal(DataOutputStream out) throws IOException {}; }; integerReference = new IDataReference() { Integer intReference = new Integer(15); public Object getReference() { return intReference; } public void setReference(Object reference) { this.intReference = (Integer)reference; } public boolean referenceMatches(IDataReference reference) { return this.intReference.equals(reference.getReference()); } public IDataReference clone() { IDataReference newReference = null; try { newReference = (IDataReference)this.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } newReference.setReference(intReference); return newReference; } public void readExternal(DataInputStream in) throws IOException, InstantiationException, IllegalAccessException, UnavailableExternalizerException {} public void writeExternal(DataOutputStream out) throws IOException {}; }; intElement = new QuestionDataElement("intElement", integerReference); intElement.setValue(integerData); stringElement = new QuestionDataElement(stringElementName, stringReference); stringElement.setValue(stringData); } public QuestionDataElementTests(String name, TestMethod rTestMethod) { super(name, rTestMethod); } public QuestionDataElementTests(String name) { super(name); } public QuestionDataElementTests() { super(); } public Test suite() { TestSuite aSuite = new TestSuite(); for (int i = 1; i <= NUM_TESTS; i++) { final int testID = i; aSuite.addTest(new QuestionDataElementTests("QuestionDataElement Test " + i, new TestMethod() { public void run (TestCase tc) { ((QuestionDataElementTests)tc).testMaster(testID); } })); } return aSuite; } public void testMaster (int testID) { //System.out.println("running " + testID); switch (testID) { case 1: testIsLeaf(); break; case 2: testGetName(); break; case 3: testSetName(); break; case 4: testGetValue(); break; case 5: testSetValue(); break; case 6: testReferenceMatch(); break; case 7: testAcceptsVisitor(); break; case 8: testSuperclassMethods(); break; } } public void testIsLeaf() { assertTrue("Question Data Element returned negative for being a leaf",stringElement.isLeaf()); } public void testGetName() { assertEquals("Question Data Element 'string' did not properly get its name", stringElement.getName(), stringElementName); } public void testSetName() { String newName = new String("New Name"); stringElement.setName(newName); assertEquals("Question Data Element 'string' did not properly set its name", stringElement.getName(), newName); } public void testGetValue() { IAnswerData data = stringElement.getValue(); assertEquals("Question Data Element did not return the correct value",data,stringData); } public void testSetValue() { stringElement.setValue(integerData); assertEquals("Question Data Element did not set value correctly",stringElement.getValue(),integerData); try { stringElement.setValue(null); } catch(Exception e) { fail("Question Data Element did not allow for its value to be set as null"); } assertEquals("Question Data Element did not return a null value correctly", stringElement.getValue(),null); } public void testReferenceMatch() { assertTrue("String Element's reference did not match the correct reference", stringElement.matchesReference(stringReference)); } private class MutableBoolean { private boolean bool; public MutableBoolean(boolean bool) { this.bool = bool; } void setValue(boolean bool) { this.bool = bool; } boolean getValue() { return bool; } } public void testAcceptsVisitor() { final MutableBoolean visitorAccepted = new MutableBoolean(false); final MutableBoolean dispatchedWrong = new MutableBoolean(false); ITreeVisitor sampleVisitor = new ITreeVisitor() { public void visit(DataModelTree tree) { } public void visit(TreeElement element) { dispatchedWrong.setValue(true); } public void visit(QuestionDataElement element) { visitorAccepted.setValue(true); } public void visit(QuestionDataGroup element) { } public void visit(IFormDataModel dataModel) { } }; stringElement.accept(sampleVisitor); assertTrue("The visitor's visit method was not called correctly by the QuestionDataElement",visitorAccepted.getValue()); assertTrue("The visitor was dispatched incorrectly by the QuestionDataElement",!dispatchedWrong.getValue()); } private void testSuperclassMethods() { //stringElement should not have a root at this point. PrototypeFactory factory = new PrototypeFactory(); stringElement.setFactory(factory); assertEquals("The QuestionDataElement 'stringElement' is not properly registering or returning factories",stringElement.getFactory(), factory); //TODO: Implement tests for the 'attribute' system. } }
package org.metaborg.spoofax.shell.output; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.metaborg.core.context.IContext; import org.metaborg.core.messages.IMessage; import org.metaborg.spoofax.core.stratego.IStrategoCommon; import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit; import org.spoofax.interpreter.terms.IStrategoTerm; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; /** * Represents a {@link ParseResult} as returned by the {@link SpoofaxCommand}. * Wraps a {@link ISpoofaxParseUnit}. */ public class ParseResult extends AbstractSpoofaxResult<ISpoofaxParseUnit> { /** * Create a {@link ParseResult}. * @param common the {@link IStrategoCommon} service * @param unit the wrapped {@link ISpoofaxParseUnit} */ @AssistedInject public ParseResult(IStrategoCommon common, @Assisted ISpoofaxParseUnit unit) { super(common, unit); } @Override public Optional<IStrategoTerm> ast() { return Optional.of(unit().ast()); } @Override public Optional<IContext> context() { return Optional.empty(); } @Override public List<IMessage> messages() { return StreamSupport.stream(unit().messages().spliterator(), false) .collect(Collectors.toList()); } @Override public StyledText styled() { if (!valid()) { return new StyledText(messages().toString()); } return toString(unit().ast()); } @Override public String sourceText() { return unit().input().text(); } @Override public boolean valid() { return unit().valid() && unit().success(); } }
package com.intellij.openapi.application; import com.intellij.ide.ApplicationInitializedListener; import com.intellij.internal.statistic.eventLog.EventLogGroup; import com.intellij.internal.statistic.eventLog.events.EventId2; import org.jetbrains.annotations.NotNull; import javax.swing.*; import static com.intellij.internal.statistic.eventLog.events.EventFields.Boolean; import static com.intellij.internal.statistic.eventLog.events.EventFields.Enum; public class ImportOldConfigsUsagesCollector { private static final EventLogGroup EVENT_GROUP = new EventLogGroup("import.old.config", 1); private static final EventId2<ImportOldConfigType, Boolean> IMPORT_DIALOG_SHOWN_EVENT = EVENT_GROUP.registerEvent("import.dialog.shown", Enum("selected", ImportOldConfigType.class), Boolean("config_folder_exists")); public static class Trigger implements ApplicationInitializedListener { @Override public void componentsInitialized() { ImportOldConfigsState state = ImportOldConfigsState.getInstance(); if (state.wasOldConfigPanelOpened()) { IMPORT_DIALOG_SHOWN_EVENT.log(state.getType(), state.doesSourceConfigFolderExist()); } } } public static class ImportOldConfigsState { private static final ImportOldConfigsState ourInstance = new ImportOldConfigsState(); public static @NotNull ImportOldConfigsState getInstance() { return ourInstance; } private volatile boolean myOldConfigPanelWasOpened = false; private volatile boolean mySourceConfigFolderExists = false; private volatile @NotNull ImportOldConfigType myType = ImportOldConfigType.NOT_INITIALIZED; public void saveImportOldConfigType(@NotNull JRadioButton previous, @NotNull JRadioButton custom, @NotNull JRadioButton doNotImport, boolean configFolderExists) { myOldConfigPanelWasOpened = true; mySourceConfigFolderExists = configFolderExists; myType = getOldImportType(previous, custom, doNotImport); } private static @NotNull ImportOldConfigType getOldImportType(@NotNull JRadioButton previous, @NotNull JRadioButton custom, @NotNull JRadioButton doNotImport) { if (previous.isSelected()) return ImportOldConfigType.FROM_PREVIOUS; if (custom.isSelected()) return ImportOldConfigType.FROM_CUSTOM; if (doNotImport.isSelected()) return ImportOldConfigType.DO_NOT_IMPORT; return ImportOldConfigType.OTHER; } public boolean wasOldConfigPanelOpened() { return myOldConfigPanelWasOpened; } public boolean doesSourceConfigFolderExist() { return mySourceConfigFolderExists; } public @NotNull ImportOldConfigType getType() { return myType; } } public enum ImportOldConfigType { FROM_PREVIOUS, FROM_CUSTOM, DO_NOT_IMPORT, OTHER, NOT_INITIALIZED } }
package org.jetbrains.plugins.groovy.lang.psi.impl; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.impl.PsiFileEx; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider.Result; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.reference.SoftReference; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder; import org.jetbrains.plugins.groovy.lang.resolve.AnnotationHint; import org.jetbrains.plugins.groovy.lang.resolve.caches.DeclarationHolder; import org.jetbrains.plugins.groovy.lang.resolve.caches.FileCacheBuilderProcessor; import org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyFileImports; import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolverProcessor; import static org.jetbrains.plugins.groovy.lang.resolve.ResolveUtilKt.*; /** * @author ilyas */ public abstract class GroovyFileBaseImpl extends PsiFileBase implements GroovyFileBase, GrControlFlowOwner { private final CachedValue<DeclarationHolder> myAnnotationsCache; private final CachedValue<DeclarationHolder> myDeclarationsCache; private final DeclarationHolder myAllCachedDeclarations; protected GroovyFileBaseImpl(FileViewProvider viewProvider, @NotNull Language language) { super(viewProvider, language); CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(viewProvider.getManager().getProject()); myAnnotationsCache = cachedValuesManager.createCachedValue(() -> Result.create( buildCache(true), this, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT ), false); myDeclarationsCache = cachedValuesManager.createCachedValue(() -> Result.create( buildCache(false), this, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT ), false); myAllCachedDeclarations = (processor, state, place) -> myAnnotationsCache.getValue().processDeclarations(processor, state, place) && myDeclarationsCache.getValue().processDeclarations(processor, state, place); } public GroovyFileBaseImpl(IFileElementType root, IFileElementType root1, FileViewProvider provider) { this(provider, root.getLanguage()); init(root, root1); } @Override @NotNull public FileType getFileType() { return GroovyFileType.GROOVY_FILE_TYPE; } public String toString() { return "Groovy script"; } @Override @NotNull public GrTypeDefinition[] getTypeDefinitions() { final StubElement<?> stub = getGreenStub(); if (stub != null) { return stub.getChildrenByType(TokenSets.TYPE_DEFINITIONS, GrTypeDefinition.ARRAY_FACTORY); } return calcTreeElement().getChildrenAsPsiElements(TokenSets.TYPE_DEFINITIONS, GrTypeDefinition.ARRAY_FACTORY); } @Override @NotNull public GrMethod[] getMethods() { final StubElement<?> stub = getGreenStub(); if (stub != null) { return stub.getChildrenByType(GroovyElementTypes.METHOD_DEFINITION, GrMethod.ARRAY_FACTORY); } return calcTreeElement().getChildrenAsPsiElements(GroovyElementTypes.METHOD_DEFINITION, GrMethod.ARRAY_FACTORY); } @Override @NotNull public GrTopStatement[] getTopStatements() { return findChildrenByClass(GrTopStatement.class); } @Override public boolean importClass(@NotNull PsiClass aClass) { return addImportForClass(aClass) != null; } @Override public void removeImport(@NotNull GrImportStatement importStatement) throws IncorrectOperationException { GroovyCodeStyleManager.getInstance(getProject()).removeImport(this, importStatement); } @Override public void removeElements(PsiElement[] elements) throws IncorrectOperationException { for (PsiElement element : elements) { if (element.isValid()) { if (element.getParent() != this) throw new IncorrectOperationException(); deleteChildRange(element, element); } } } @NotNull @Override public GrStatement[] getStatements() { return findChildrenByClass(GrStatement.class); } @Override @NotNull public GrStatement addStatementBefore(@NotNull GrStatement statement, @Nullable GrStatement anchor) throws IncorrectOperationException { final PsiElement result = addBefore(statement, anchor); if (anchor != null) { getNode().addLeaf(GroovyTokenTypes.mNLS, "\n", anchor.getNode()); } else { getNode().addLeaf(GroovyTokenTypes.mNLS, "\n", result.getNode()); } return (GrStatement)result; } @Override public void removeVariable(GrVariable variable) { PsiImplUtil.removeVariable(variable); } @Override public GrVariableDeclaration addVariableDeclarationBefore(GrVariableDeclaration declaration, GrStatement anchor) throws IncorrectOperationException { GrStatement statement = addStatementBefore(declaration, anchor); assert statement instanceof GrVariableDeclaration; return ((GrVariableDeclaration) statement); } @Override public void accept(@NotNull GroovyElementVisitor visitor) { visitor.visitFile(this); } @Override public void acceptChildren(@NotNull GroovyElementVisitor visitor) { PsiElement child = getFirstChild(); while (child != null) { if (child instanceof GroovyPsiElement) { ((GroovyPsiElement) child).accept(visitor); } child = child.getNextSibling(); } } @Override @NotNull public PsiClass[] getClasses() { return getTypeDefinitions(); } @Override public void clearCaches() { super.clearCaches(); myControlFlow = null; } private volatile SoftReference<Instruction[]> myControlFlow; @Override public Instruction[] getControlFlow() { assert isValid(); Instruction[] result = SoftReference.dereference(myControlFlow); if (result == null) { result = new ControlFlowBuilder(getProject()).buildControlFlow(this); myControlFlow = new SoftReference<>(result); } return ControlFlowBuilder.assertValidPsi(result); } @Override public boolean isTopControlFlowOwner() { return false; } @Override public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException { if (last instanceof GrTopStatement) { PsiImplUtil.deleteStatementTail(this, last); } super.deleteChildRange(first, last); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { for (PsiScopeProcessor each : GroovyResolverProcessor.allProcessors(processor)) { if (!shouldProcessMembers(each)) continue; if (!getAppropriateHolder(getAnnotationHint(processor)).processDeclarations(each, state, place)) return false; } return true; } @NotNull private DeclarationHolder getAppropriateHolder(@Nullable AnnotationHint hint) { boolean mayUseCache = useCache(); if (hint == null) { if (mayUseCache || myAnnotationsCache.hasUpToDateValue() && myDeclarationsCache.hasUpToDateValue()) { return myAllCachedDeclarations; } } else if (hint.isAnnotationResolve()) { if (mayUseCache || myAnnotationsCache.hasUpToDateValue()) { return myAnnotationsCache.getValue(); } } else { if (mayUseCache || myDeclarationsCache.hasUpToDateValue()) { return myDeclarationsCache.getValue(); } } return this::processDeclarationsNoCache; } private boolean useCache() { if (!isPhysical()) return false; if (ApplicationManager.getApplication().isDispatchThread()) return false; return getUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING) == Boolean.TRUE; } @NotNull private DeclarationHolder buildCache(boolean annotationCache) { FileCacheBuilderProcessor processor = new FileCacheBuilderProcessor(annotationCache); processDeclarationsNoCache(processor, ResolveState.initial(), this); return processor.buildCache(); } private boolean processDeclarationsNoCache(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @NotNull PsiElement place) { if (!processClassesInFile(this, processor, state)) return false; final GroovyFileImports imports = getImports(); if (!imports.processAllNamedImports(processor, state, place)) return false; if (!processClassesInPackage(this, processor, state, place)) return false; if (!imports.processAllStarImports(processor, state, place)) return false; if (!imports.processDefaultImports(processor, state, place)) return false; return true; } protected abstract GroovyFileImports getImports(); }
package com.opengamma.financial.analytics.model.horizon; import java.util.Collections; import java.util.Set; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.financial.analytics.model.fixedincome.InterestRateInstrumentDefaultPropertiesFunction; import com.opengamma.util.ArgumentChecker; public class SwapThetaDefaults extends InterestRateInstrumentDefaultPropertiesFunction { private final String _defaultNumberOfDays; public SwapThetaDefaults(final String priority, final String includeIRFutures, final String defaultNumberOfDays, final String... currencyAndCurveConfigNames) { super(priority, includeIRFutures, currencyAndCurveConfigNames); ArgumentChecker.notNull(defaultNumberOfDays, "default number of days"); _defaultNumberOfDays = defaultNumberOfDays; } @Override protected void getDefaults(final PropertyDefaults defaults) { super.getDefaults(defaults); defaults.addValuePropertyName(ValueRequirementNames.VALUE_THETA, ThetaPropertyNamesAndValues.PROPERTY_DAYS_TO_MOVE_FORWARD); } @Override protected Set<String> getDefaultValue(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue, final String propertyName) { if (ThetaPropertyNamesAndValues.PROPERTY_DAYS_TO_MOVE_FORWARD.equals(propertyName)) { return Collections.singleton(_defaultNumberOfDays); } return super.getDefaultValue(context, target, desiredValue, propertyName); } }
package com.ctrip.xpipe.redis.core.meta.impl; import com.ctrip.xpipe.endpoint.HostPort; import com.ctrip.xpipe.redis.core.entity.*; import com.ctrip.xpipe.redis.core.exception.RedisRuntimeException; import com.ctrip.xpipe.redis.core.meta.MetaClone; import com.ctrip.xpipe.redis.core.meta.MetaException; import com.ctrip.xpipe.redis.core.meta.MetaUtils; import com.ctrip.xpipe.redis.core.meta.XpipeMetaManager; import com.ctrip.xpipe.redis.core.transform.DefaultSaxParser; import com.ctrip.xpipe.redis.core.util.OrgUtil; import com.ctrip.xpipe.tuple.Pair; import com.ctrip.xpipe.utils.FileUtils; import com.ctrip.xpipe.utils.ObjectUtils; import com.ctrip.xpipe.utils.StringUtil; import com.google.common.base.Joiner; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.*; /** * @author wenchao.meng * * Jul 7, 2016 */ public class DefaultXpipeMetaManager extends AbstractMetaManager implements XpipeMetaManager{ private String fileName = null; protected final XpipeMeta xpipeMeta; private Map<HostPort, MetaDesc> inverseMap; public DefaultXpipeMetaManager(XpipeMeta xpipeMeta){ this.xpipeMeta = xpipeMeta; } private DefaultXpipeMetaManager(String fileName) { this.fileName = fileName; xpipeMeta = load(fileName); } public static XpipeMetaManager buildFromFile(String fileName){ return new DefaultXpipeMetaManager(fileName); } public static XpipeMetaManager buildFromMeta(XpipeMeta xpipeMeta){ return new DefaultXpipeMetaManager(xpipeMeta); } public XpipeMeta load(String fileName) { try { InputStream ins = FileUtils.getFileInputStream(fileName); return DefaultSaxParser.parse(ins); } catch (SAXException | IOException e) { logger.error("[load]" + fileName, e); throw new IllegalStateException("load " + fileName + " failed!", e); } } @Override public String getActiveDc(String clusterId, String shardId){ for(DcMeta dcMeta : xpipeMeta.getDcs().values()){ ClusterMeta clusterMeta = dcMeta.getClusters().get(clusterId); if(clusterMeta == null){ continue; } String activeDc = clusterMeta.getActiveDc(); if(activeDc == null){ logger.info("[getActiveDc][activeDc null]{}", clusterMeta); throw new MetaException(String.format("cluster exist but active dc == null {}", clusterMeta)); } return activeDc.trim().toLowerCase(); } throw new MetaException("clusterId " + clusterId + " not found!"); } @Override public Set<String> getBackupDcs(String clusterId, String shardId) { boolean found = false; for(DcMeta dcMeta : xpipeMeta.getDcs().values()){ ClusterMeta clusterMeta = dcMeta.getClusters().get(clusterId); if(clusterMeta == null){ continue; } found = true; if(StringUtil.isEmpty(clusterMeta.getBackupDcs())){ logger.info("[getBackupDcs][backup dcs empty]{}, {}", dcMeta.getId(), clusterMeta); continue; } Set<String> backDcs = backupDcs(clusterMeta.getBackupDcs()); backDcs.remove(clusterMeta.getActiveDc().toLowerCase().trim()); return backDcs; } if(found){ return new HashSet<>(); } throw new MetaException("clusterId " + clusterId + " not found!"); } private Set<String> backupDcs(String backupDcsDesc) { Set<String> backDcs = new HashSet<>(); if(StringUtil.isEmpty(backupDcsDesc)){ return backDcs; } for(String dc : backupDcsDesc.split("\\s*,\\s*")){ dc = dc.trim(); if(!StringUtil.isEmpty(dc)){ backDcs.add(dc.toLowerCase()); } } return backDcs; } @Override public Set<String> getDcClusters(String dc) { return new HashSet<>(getDirectDcMeta(dc).getClusters().keySet()); } @Override public ClusterMeta getClusterMeta(String dc, String clusterId) { return clone(getDirectClusterMeta(dc, clusterId)); } public ClusterMeta getDirectClusterMeta(String dc, String clusterId) { DcMeta dcMeta = getDirectDcMeta(dc); if(dcMeta == null){ return null; } return dcMeta.getClusters().get(clusterId); } protected DcMeta getDirectDcMeta(String dc) { for(Map.Entry<String, DcMeta> dentry : xpipeMeta.getDcs().entrySet()){ String dcId = dentry.getKey(); if(dcId.equalsIgnoreCase(dc)){ return dentry.getValue(); } } return null; } @Override public ShardMeta getShardMeta(String dc, String clusterId, String shardId) { return clone(getDirectShardMeta(dc, clusterId, shardId)); } protected ShardMeta getDirectShardMeta(String dc, String clusterId, String shardId) { ClusterMeta clusterMeta = getDirectClusterMeta(dc, clusterId); if(clusterMeta == null){ return null; } return clusterMeta.getShards().get(shardId); } @SuppressWarnings("unchecked") @Override public List<KeeperMeta> getKeepers(String dc, String clusterId, String shardId) { return (List<KeeperMeta>) clone((Serializable)getDirectKeepers(dc, clusterId, shardId)); } protected List<KeeperMeta> getDirectKeepers(String dc, String clusterId, String shardId) { ShardMeta shardMeta = getDirectShardMeta(dc, clusterId, shardId); if(shardMeta == null){ return null; } return shardMeta.getKeepers(); } @SuppressWarnings("unchecked") @Override public List<RedisMeta> getRedises(String dc, String clusterId, String shardId) { ShardMeta shardMeta = getShardMeta(dc, clusterId, shardId); if(shardMeta == null){ return null; } return (List<RedisMeta>) clone((Serializable)shardMeta.getRedises()); } @Override public KeeperMeta getKeeperActive(String dc, String clusterId, String shardId) { List<KeeperMeta> keepers = getDirectKeepers(dc, clusterId, shardId); if(keepers == null){ return null; } return clone(getDirectKeeperActive(keepers)); } private KeeperMeta getDirectKeeperActive(List<KeeperMeta> keepers) { for(KeeperMeta keeperMeta : keepers){ if(keeperMeta.isActive()){ return keeperMeta; } } return null; } @Override public List<KeeperMeta> getKeeperBackup(String dc, String clusterId, String shardId) { List<KeeperMeta> keepers = getKeepers(dc, clusterId, shardId); if(keepers == null){ return null; } LinkedList<KeeperMeta> result = new LinkedList<>(); for(KeeperMeta keeperMeta : keepers){ if(!keeperMeta.isActive()){ result.add(keeperMeta); } } return clone(result); } @Override public MetaDesc findMetaDesc(HostPort hostPort) { if(inverseMap != null){ return inverseMap.get(hostPort); } synchronized (this){ if(inverseMap == null){ inverseMap = InverseHostPortMapBuilder.build(xpipeMeta); } } return inverseMap.get(hostPort); } private ShardMeta cloneWithParent(DcMeta dcMeta, ClusterMeta clusterMeta, ShardMeta shardMeta) { ShardMeta result = clone(shardMeta); result.setParent(clone(clusterMeta)); result.parent().setParent(clone(dcMeta)); return result; } @Override public Pair<String, RedisMeta> getRedisMaster(String clusterId, String shardId) { for(DcMeta dcMeta : xpipeMeta.getDcs().values()){ ClusterMeta clusterMeta = dcMeta.findCluster(clusterId); if( clusterMeta == null ){ continue; } ShardMeta shardMeta = clusterMeta.findShard(shardId); if(shardMeta == null){ continue; } for(RedisMeta redisMeta : shardMeta.getRedises()){ if(redisMeta.isMaster()){ return new Pair<>(dcMeta.getId(), clone(redisMeta)); } } } return null; } @Override public boolean noneKeeperActive(String dc, String clusterId, String shardId) { ShardMeta shardMeta = getDirectShardMeta(dc, clusterId, shardId); if(shardMeta == null){ throw new RedisRuntimeException(String.format("[shard not found]dc:%s, cluster:%s, shard:%s", dc, clusterId, shardId)); } boolean changed = false; for(KeeperMeta keeperMeta : shardMeta.getKeepers()){ if(keeperMeta.isActive()){ keeperMeta.setActive(false); changed = true; } } return changed; } @Override public void setSurviveKeepers(String dcId, String clusterId, String shardId, List<KeeperMeta> surviveKeepers) { List<KeeperMeta> keepers = getDirectKeepers(dcId, clusterId, shardId); List<KeeperMeta> unfoundKeepers = new LinkedList<>(); for(KeeperMeta active : surviveKeepers){ boolean found = false; for(KeeperMeta current :keepers){ if(MetaUtils.same(active, current)){ found = true; current.setSurvive(true); break; } } if(!found){ unfoundKeepers.add(active); } } if(unfoundKeepers.size() > 0){ throw new IllegalArgumentException("unfound keeper set active:" + unfoundKeepers); } } @Override public boolean updateKeeperActive(String dc, String clusterId, String shardId, KeeperMeta activeKeeper) { if(!valid(activeKeeper)){ logger.info("[updateKeeperActive][keeper information unvalid]{}", activeKeeper); } ShardMeta shardMeta = getDirectShardMeta(dc, clusterId, shardId); if(shardMeta == null){ throw new MetaException(String.format("unfound keepers: %s %s %s", dc, clusterId, shardId)); } List<KeeperMeta> keepers = shardMeta.getKeepers(); boolean found = false; boolean changed = false; for(KeeperMeta keeperMeta : keepers){ if(keeperMeta.getIp().equals(activeKeeper.getIp()) && keeperMeta.getPort().equals(activeKeeper.getPort())){ found = true; if(!keeperMeta.isActive()){ logger.info("[updateKeeperActive][set keeper active]{}", keeperMeta); keeperMeta.setActive(true); changed = true; } }else{ if(keeperMeta.isActive()){ logger.info("[updateKeeperActive][set keeper unactive]{}", keeperMeta); keeperMeta.setActive(false); changed = true; } } } if(!found && valid(activeKeeper)){ changed = true; activeKeeper.setActive(true); activeKeeper.setParent(shardMeta); keepers.add(activeKeeper); } return changed; } private boolean valid(KeeperMeta activeKeeper) { if(activeKeeper == null || activeKeeper.getIp() == null || activeKeeper.getPort() == null){ return false; } return true; } public String getFileName() { return fileName; } @Override public List<MetaServerMeta> getMetaServers(String dc) { DcMeta dcMeta = getDirectDcMeta(dc); if( dcMeta == null ){ return null; } return clone(new LinkedList<>(dcMeta.getMetaServers())); } @Override public ZkServerMeta getZkServerMeta(String dc) { DcMeta dcMeta = getDirectDcMeta(dc); if( dcMeta == null ){ return null; } return clone(dcMeta.getZkServer()); } @Override public Set<String> getDcs() { return xpipeMeta.getDcs().keySet(); } @Override public boolean updateRedisMaster(String dc, String clusterId, String shardId, RedisMeta redisMaster) throws MetaException { String activeDc = getActiveDc(clusterId, shardId); if(!activeDc.equals(dc)){ throw new MetaException("active dc:" + activeDc + ", but given:" + dc + ", clusterID:" + clusterId); } ShardMeta shardMeta = getDirectShardMeta(dc, clusterId, shardId); if(shardMeta == null){ throw new MetaException(String.format("unfound shard %s,%s,%s", dc, clusterId, shardId)); } boolean found = false, changed = false; String newMaster = String.format("%s:%d", redisMaster.getIp(), redisMaster.getPort()); String oldRedisMaster = null; for(RedisMeta redisMeta : shardMeta.getRedises()){ if(redisMeta.getIp().equals(redisMaster.getIp()) && redisMeta.getPort().equals(redisMaster.getPort())){ found = true; if(!redisMeta.isMaster()){ logger.info("[updateRedisMaster][change redis to master]{}", redisMeta); redisMeta.setMaster(null); changed = true; }else{ logger.info("[updateRedisMaster][redis already master]{}", redisMeta); } }else{ if(redisMeta.isMaster()){ logger.info("[updateRedisMaster][change redis to slave]{}", redisMeta); //unknown oldRedisMaster = String.format("%s:%d", redisMeta.getIp(), redisMeta.getPort()); redisMeta.setMaster(getNewMasterofOldMaster(redisMeta, newMaster)); changed = true; } } } if(oldRedisMaster != null){ for(RedisMeta redisMeta : shardMeta.getRedises()){ if(oldRedisMaster.equalsIgnoreCase(redisMeta.getMaster())){ redisMeta.setMaster(newMaster); changed = true; } } for(KeeperMeta keeperMeta : shardMeta.getKeepers()){ if(oldRedisMaster.equalsIgnoreCase(keeperMeta.getMaster())){ keeperMeta.setMaster(newMaster); changed = true; } } } if(!found){ redisMaster.setParent(shardMeta); shardMeta.getRedises().add(redisMaster); changed = true; } return changed; } private String getNewMasterofOldMaster(RedisMeta oldRedisMaster, String newRedisMaster) { Integer phase = oldRedisMaster.parent().getPhase(); if(phase == null){ phase = oldRedisMaster.parent().parent().getPhase(); } if(phase == null){ phase = 1; } if(phase == 1){ return newRedisMaster; } KeeperMeta keeperActive = getDirectKeeperActive(oldRedisMaster.parent().getKeepers()); if(keeperActive == null){ throw new RedisRuntimeException(String.format("can not find active keeper:", oldRedisMaster.parent().getKeepers())); } return String.format("%s:%d", keeperActive.getIp(), keeperActive.getPort()); } @Override public boolean dcExists(String dc) { return getDirectDcMeta(dc)!= null; } @Override public KeeperContainerMeta getKeeperContainer(String dc, KeeperMeta keeperMeta) { DcMeta dcMeta = getDirectDcMeta(dc); for(KeeperContainerMeta keeperContainerMeta : dcMeta.getKeeperContainers()){ if(keeperContainerMeta.getId().equals(keeperMeta.getKeeperContainerId())){ return clone(keeperContainerMeta); } } throw new IllegalArgumentException(String.format("[getKeeperContainer][unfound keepercontainer]%s, %s", dc, keeperMeta)); } @Override public void update(DcMeta dcMeta) { xpipeMeta.addDc(clone(dcMeta)); } @Override public void update(String dcId, ClusterMeta clusterMeta) { DcMeta dcMeta = xpipeMeta.getDcs().get(dcId); dcMeta.addCluster(clone(clusterMeta)); } @Override public ClusterMeta removeCluster(String dcId, String clusterId) { DcMeta dcMeta = xpipeMeta.getDcs().get(dcId); return dcMeta.removeCluster(clusterId); } @Override public DcMeta getDcMeta(String dcId) { return clone(getDirectDcMeta(dcId)); } @Override public List<KeeperMeta> getAllSurviceKeepers(String dcId, String clusterId, String shardId) { List<KeeperMeta> keepers = getDirectKeepers(dcId, clusterId, shardId); List<KeeperMeta> result = new LinkedList<>(); for(KeeperMeta keeper : keepers){ if(keeper.isSurvive()){ result.add(MetaClone.clone(keeper)); } } return result; } @Override public boolean hasCluster(String dcId, String clusterId) { DcMeta dcMeta = getDirectDcMeta(dcId); if(dcMeta == null){ return false; } return dcMeta.getClusters().get(clusterId) != null; } @Override public boolean hasShard(String dcId, String clusterId, String shardId) { ShardMeta shardMeta = getDirectShardMeta(dcId, clusterId, shardId); if(shardMeta == null){ return false; } return true; } @Override public SentinelMeta getSentinel(String dc, String clusterId, String shardId) { DcMeta dcMeta = getDirectDcMeta(dc); if((dcMeta == null)){ throw new RedisRuntimeException("dcmeta not found:" + dc); } ShardMeta shardMeta = getDirectShardMeta(dc, clusterId, shardId); if(shardMeta == null){ throw new RedisRuntimeException(String.format("shardMeta not found:%s %s %s", dc, clusterId, shardId)); } Long sentinelId = shardMeta.getSentinelId(); SentinelMeta sentinelMeta = dcMeta.getSentinels().get(sentinelId); if(sentinelMeta == null){ return new SentinelMeta().setAddress(""); } return MetaClone.clone(sentinelMeta); } @Override public void primaryDcChanged(String dc, String clusterId, String shardId, String newPrimaryDc) { for(DcMeta dcMeta : xpipeMeta.getDcs().values()){ changePrimaryDc(dcMeta, clusterId, shardId, newPrimaryDc); } } @Override public List<RouteMeta> routes(String currentDc, String tag) { DcMeta dcMeta = getDirectDcMeta(currentDc); List<RouteMeta> routes = dcMeta.getRoutes(); List<RouteMeta> result = new LinkedList<>(); if(routes != null){ routes.forEach(routeMeta -> { if(routeMeta.tagEquals(tag) && currentDc.equalsIgnoreCase(routeMeta.getSrcDc())) { result.add(MetaClone.clone(routeMeta)); } }); } return result; } @Override public RouteMeta randomRoute(String currentDc, String tag, Integer orgId, String dstDc) { logger.info("[randomRoute]currentDc: {}, tag: {}, orgId: {}, dstDc: {}", currentDc, tag, orgId, dstDc); List<RouteMeta> routes = routes(currentDc, tag); if(routes == null || routes.isEmpty()){ return null; } logger.info("[randomRoute]routes: {}", routes); //for Same dstdc List<RouteMeta> dstDcRoutes = new LinkedList<>(); routes.forEach(routeMeta -> { if(routeMeta.getDstDc().equalsIgnoreCase(dstDc)){ dstDcRoutes.add(routeMeta); } }); if(dstDcRoutes.isEmpty()){ logger.info("[randomRoute]dst dc empty: {}", routes); return null; } //for same org id List<RouteMeta> resultsCandidates = new LinkedList<>(); dstDcRoutes.forEach(routeMeta -> { if(ObjectUtils.equals(routeMeta.getOrgId(), orgId)){ resultsCandidates.add(routeMeta); } }); if(!resultsCandidates.isEmpty()){ return random(resultsCandidates); } dstDcRoutes.forEach(routeMeta -> { if(OrgUtil.isDefaultOrg(routeMeta.getOrgId())){ resultsCandidates.add(routeMeta); } }); return random(resultsCandidates); } @Override public List<ClusterMeta> getSpecificActiveDcClusters(String currentDc, String clusterActiveDc) { DcMeta directDcMeta = getDirectDcMeta(currentDc); if(directDcMeta == null){ throw new IllegalArgumentException(String.format("can not find currentDc %s, %s", currentDc, clusterActiveDc)); } List<ClusterMeta> result = new LinkedList<>(); directDcMeta.getClusters().forEach((clusterId, clusterMeta) -> { if(clusterActiveDc.equalsIgnoreCase(clusterMeta.getActiveDc())){ result.add(clone(clusterMeta)); } }); return result; } protected <T> T random(List<T> resultsCandidates) { if(resultsCandidates.isEmpty()){ return null; } int random = new Random().nextInt(resultsCandidates.size()); logger.info("[randomRoute]random: {}, size: {}", random, resultsCandidates.size()); return resultsCandidates.get(random); } private void changePrimaryDc(DcMeta dcMeta, String clusterId, String shardId, String newPrimaryDc) { ClusterMeta clusterMeta = dcMeta.getClusters().get(clusterId); if(clusterMeta == null){ throw new RedisRuntimeException(String.format("clusterMeta not found:%s %s %s", dcMeta.getId(), clusterId, shardId)); } String currentPrimaryDc = clusterMeta.getActiveDc(); if(StringUtil.trimEquals(newPrimaryDc, currentPrimaryDc, true)){ logger.info("[changePrimaryDc][equal]{}, {}, {}", clusterId, shardId, newPrimaryDc); return; } newPrimaryDc = newPrimaryDc.trim().toLowerCase(); Set<String> allDcs = new HashSet<>(); if(currentPrimaryDc != null){ allDcs.add(currentPrimaryDc.trim().toLowerCase()); } allDcs.addAll(backupDcs(clusterMeta.getBackupDcs())); clusterMeta.setActiveDc(newPrimaryDc); allDcs.remove(newPrimaryDc); clusterMeta.setBackupDcs(Joiner.on(",").join(allDcs)); } @Override public String toString() { return xpipeMeta.toString(); } }
package org.opensingular.resources.filter; 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 javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.SecureRandom; @WebFilter(urlPatterns = "*") public class CachingFilter implements Filter { public static final String CACHE_CONTROL = "Cache-Control"; public static final String MAX_AGE_PATTERN = "max-age=%d"; public static final long THIRTY_DAYS = 86400L * 30; // 30 days in seconds public static final long TWELVE_HOURS = 86400L / 2; // 12 hours in seconds public static final SecureRandom RANDOM = new SecureRandom(SecureRandom.getSeed(4)); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader(CACHE_CONTROL, String.format(MAX_AGE_PATTERN, THIRTY_DAYS + RANDOM.longs(0, TWELVE_HOURS).findFirst().orElse(0L))); chain.doFilter(request, httpServletResponse); } @Override public void destroy() { } }
package io.opentelemetry.sdk.extension.zpages; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.sdk.trace.ReadableSpan; import io.opentelemetry.sdk.trace.data.StatusData; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; final class TracezSpanBuckets { private final LatencyBuckets latencyBuckets = new LatencyBuckets(); private final SpanBucket errors = new SpanBucket(/* isLatencyBucket= */ false); void addToBucket(ReadableSpan span) { StatusData status = span.toSpanData().getStatus(); if (status.getStatusCode() != StatusCode.ERROR) { latencyBuckets.get(LatencyBoundary.getBoundary(span.getLatencyNanos())).add(span); return; } errors.add(span); } Map<LatencyBoundary, Integer> getLatencyBoundaryToCountMap() { Map<LatencyBoundary, Integer> latencyCounts = new EnumMap<>(LatencyBoundary.class); for (LatencyBoundary bucket : LatencyBoundary.values()) { latencyCounts.put(bucket, latencyBuckets.get(bucket).size()); } return latencyCounts; } List<ReadableSpan> getOkSpans() { List<ReadableSpan> okSpans = new ArrayList<>(); latencyBuckets.addTo(okSpans); return okSpans; } List<ReadableSpan> getErrorSpans() { List<ReadableSpan> errorSpans = new ArrayList<>(); errors.addTo(errorSpans); return errorSpans; } List<ReadableSpan> getSpans() { List<ReadableSpan> spans = new ArrayList<>(); spans.addAll(getOkSpans()); spans.addAll(getErrorSpans()); return spans; } private static class LatencyBuckets { final SpanBucket zeroToTenMicros = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket tenMicrosToHundredMicros = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket hundredMicrosToOneMilli = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket oneMilliToTenMillis = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket tenMillisToHundredMillis = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket hundredMillisToOneSecond = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket oneSecondToTenSeconds = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket tenSecondsToHundredSeconds = new SpanBucket(/* isLatencyBucket= */ true); final SpanBucket hundredSecondsToMax = new SpanBucket(/* isLatencyBucket= */ true); void addTo(List<ReadableSpan> spans) { zeroToTenMicros.addTo(spans); tenMicrosToHundredMicros.addTo(spans); hundredMicrosToOneMilli.addTo(spans); oneMilliToTenMillis.addTo(spans); tenMillisToHundredMillis.addTo(spans); hundredMillisToOneSecond.addTo(spans); oneSecondToTenSeconds.addTo(spans); tenSecondsToHundredSeconds.addTo(spans); hundredSecondsToMax.addTo(spans); } SpanBucket get(LatencyBoundary boundary) { switch (boundary) { case ZERO_MICROSx10: return zeroToTenMicros; case MICROSx10_MICROSx100: return tenMicrosToHundredMicros; case MICROSx100_MILLIx1: return hundredMicrosToOneMilli; case MILLIx1_MILLIx10: return oneMilliToTenMillis; case MILLIx10_MILLIx100: return tenMillisToHundredMillis; case MILLIx100_SECONDx1: return hundredMillisToOneSecond; case SECONDx1_SECONDx10: return oneSecondToTenSeconds; case SECONDx10_SECONDx100: return tenSecondsToHundredSeconds; case SECONDx100_MAX: return hundredSecondsToMax; } // Can't happen with aligned versions, just pick an arbitrary one to compile. return hundredSecondsToMax; } } }
package org.phenotips.similarity.internal; import org.phenotips.consents.ConsentManager; import org.phenotips.data.Feature; import org.phenotips.data.Gene; import org.phenotips.data.Patient; import org.phenotips.data.PatientData; import org.phenotips.data.PatientRepository; import org.phenotips.data.permissions.AccessLevel; import org.phenotips.data.permissions.EntityAccess; import org.phenotips.data.permissions.EntityPermissionsManager; import org.phenotips.data.permissions.Owner; import org.phenotips.data.permissions.Visibility; import org.phenotips.data.similarity.PatientSimilarityView; import org.phenotips.data.similarity.PatientSimilarityViewFactory; import org.phenotips.similarity.SimilarPatientsFinder; import org.phenotips.studies.family.Family; import org.phenotips.studies.family.FamilyRepository; import org.phenotips.vocabulary.SolrCoreContainerHandler; import org.phenotips.vocabulary.VocabularyManager; import org.phenotips.vocabulary.VocabularyTerm; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.model.reference.EntityReference; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.CommonParams; import org.slf4j.Logger; /** * Implementation for {@link SimilarPatientsFinder} based on Solr indexing of existing patients. * * @version $Id$ * @since 1.0M1 */ @Component @Singleton @SuppressWarnings("checkstyle:ClassFanOutComplexity") public class SolrSimilarPatientsFinder implements SimilarPatientsFinder, Initializable { /** The number of records to fully score. */ private static final int SEED_QUERY_SIZE = 50; /** Logging helper object. */ @Inject private Logger logger; /** Provides access to patient data. */ @Inject private PatientRepository patients; /** Provides access to patients families data. */ @Inject private FamilyRepository familyRepository; /** The minimal access level needed for including a patient in the result. */ @Inject @Named("match") private AccessLevel accessLevelThreshold; /** The minimal visibility level needed for including a patient in the result. */ @Inject @Named("matchable") private Visibility visibilityLevelThreshold; /** Allows to make a secure pair of patients. */ @Inject @Named("restricted") private PatientSimilarityViewFactory factory; @Inject private VocabularyManager vocabularies; @Inject private SolrCoreContainerHandler cores; @Inject private ConsentManager consentManager; @Inject private EntityPermissionsManager permissionsManager; /** The Solr server instance used. */ private SolrClient server; @Override public void initialize() throws InitializationException { this.server = new EmbeddedSolrServer(this.cores.getContainer(), "patients"); } @Override public List<PatientSimilarityView> findSimilarPatients(Patient referencePatient) { return findSimilarPatients(referencePatient, null); } @Override public List<PatientSimilarityView> findSimilarPatients(Patient referencePatient, String requiredConsentId) { return find(referencePatient, requiredConsentId, false); } @Override public List<PatientSimilarityView> findSimilarPrototypes(Patient referencePatient) { return find(referencePatient, null, true); } @Override public long countSimilarPatients(Patient referencePatient) { SolrQuery query = generateQuery(referencePatient, false); return count(query); } private List<PatientSimilarityView> find(Patient referencePatient, String requiredConsentId, boolean prototypes) { this.logger.debug("Searching for patients similar to [{}] using access level {}", referencePatient.getId(), this.accessLevelThreshold.getName()); SolrQuery query = generateQuery(referencePatient, prototypes); if (query == null) { return Collections.emptyList(); } SolrDocumentList docs = search(query); List<PatientSimilarityView> results = new ArrayList<>(docs.size()); // re-fetching patient to force it to be instance of internal Patient, not SecurePatient Patient referenceIntPatient = this.patients.get(referencePatient.getId()); Family family = this.familyRepository.getFamilyForPatient(referenceIntPatient); Owner refOwner = this.permissionsManager.getEntityAccess(referenceIntPatient).getOwner(); EntityReference refOwnerRef = (refOwner != null) ? refOwner.getUser() : null; for (SolrDocument doc : docs) { String name = (String) doc.getFieldValue("document"); Patient matchPatient = this.patients.get(name); if (filterPatient(matchPatient, family, refOwnerRef, requiredConsentId)) { continue; } PatientSimilarityView result = this.factory.makeSimilarPatient(matchPatient, referencePatient); this.logger.debug("Found match: [{}] with score: {}, accessLevel: {}, accessCompare: {}", name, result.getScore(), result.getAccess().getName(), this.accessLevelThreshold.compareTo(result.getAccess())); if (result.getScore() > 0) { results.add(result); } } // Sort by score Collections.sort(results, new Comparator<PatientSimilarityView>() { @Override public int compare(PatientSimilarityView o1, PatientSimilarityView o2) { double score1 = o1.getScore(); double score2 = o2.getScore(); return (int) Math.signum(score2 - score1); } }); return results; } @SuppressWarnings({ "checkstyle:NPathComplexity", "checkstyle:CyclomaticComplexity", "checkstyle:ReturnCount" }) private boolean filterPatient(Patient matchPatient, Family family, EntityReference refOwner, String requiredConsentId) { EntityAccess access = this.permissionsManager.getEntityAccess(matchPatient); if (matchPatient == null) { // Leftover patient in the index, should be removed return true; } // filter out patients from the same family if (family != null && family.isMember(matchPatient)) { return true; } // filter out patients of the same owner Owner matchOwner = access.getOwner(); if (refOwner != null && matchOwner != null && refOwner.equals(matchOwner.getUser())) { return true; } // check consents, if required if (requiredConsentId != null && !this.consentManager.hasConsent(matchPatient, requiredConsentId)) { return true; } // filter out patients with access level less than defined access level threshold AccessLevel patientAccessLevel = access.getAccessLevel(); if (this.accessLevelThreshold.compareTo(patientAccessLevel) > 0) { return true; } // filter out patients with visibility level less than defined visibility level threshold Visibility patientVisibility = access.getVisibility(); if (this.visibilityLevelThreshold.compareTo(patientVisibility) > 0) { return true; } return false; } /** * Generates a Solr query that tries to match patients similar to the reference. * * @param referencePatient the reference patient * @return a query populated with terms from the patient phenotype */ private SolrQuery generateQuery(Patient referencePatient, boolean prototypes) { SolrQuery query = new SolrQuery(); StringBuilder q = new StringBuilder(); // Whitespace-delimiter terms querying the extended phenotype field Collection<String> termIds = getPresentPhenotypeTerms(referencePatient); if (!termIds.isEmpty()) { q.append(" extended_phenotype:" + getQueryFromTerms(termIds)); } PatientData<Gene> allGenes = referencePatient.getData("genes"); appendGenesToQuery(allGenes, q); // Ignore the reference patient itself (unless reference patient is a temporary in-memory only // patient, e.g. a RemoteMatchingPatient created from remote patient data obtained via remote-matching API) if (referencePatient.getDocumentReference() != null) { q.append(" -document:" + ClientUtils.escapeQueryChars(referencePatient.getDocumentReference().toString())); } q.append(prototypes ? " +" : " -").append("document:xwiki\\:data.MIM*"); query.add(CommonParams.Q, q.toString()); this.logger.debug("SOLRQUERY generated for matching patient [{}]: {}", referencePatient.getId(), query.toString()); return query; } /** * Performs a search in the Solr index, returning the matched documents. * * @param query the query prepared with {@link #generateQuery(Patient, boolean)} * @return the documents matched by the query, if any */ private SolrDocumentList search(SolrQuery query) { query.setRows(SEED_QUERY_SIZE); try { return this.server.query(query).getResults(); } catch (IOException | SolrServerException ex) { this.logger.warn("Failed to query the patients index: {}", ex.getMessage()); return null; } } /** * Performs a search in the Solr index, returning only the total number of matches found. * * @param query the query prepared with {@link #generateQuery(Patient, boolean)} * @return the total number of document matched by the query, {@code 0} if none match */ private long count(SolrQuery query) { query.setRows(0); SolrDocumentList response = search(query); if (response != null) { return response.getNumFound(); } return 0; } private Collection<String> getPresentPhenotypeTerms(Patient patient) { Collection<String> termIds = new HashSet<>(); for (Feature phenotype : patient.getFeatures()) { if (phenotype != null && phenotype.isPresent()) { String termId = phenotype.getId(); if (StringUtils.isNotBlank(termId)) { VocabularyTerm term = this.vocabularies.resolveTerm(termId); if (term != null) { for (VocabularyTerm ancestor : term.getAncestorsAndSelf()) { termIds.add(ancestor.getId()); } } } } } return termIds; } private void appendGenesToQuery(PatientData<Gene> allGenes, StringBuilder q) { Collection<String> genesToSearch = new ArrayList<>(); if (allGenes != null && allGenes.size() > 0 && allGenes.isIndexed()) { for (Gene gene : allGenes) { String geneName = gene.getId(); if (StringUtils.isBlank(geneName)) { continue; } geneName = geneName.trim(); String status = gene.getStatus(); // Treat empty status as candidate if (StringUtils.isBlank(status) || "solved".equals(status) || "candidate".equals(status)) { genesToSearch.add(geneName); } } } if (!genesToSearch.isEmpty()) { String geneQuery = getQueryFromTerms(genesToSearch); q.append(" solved_genes:" + geneQuery); q.append(" candidate_genes:" + geneQuery); } } private String getQueryFromTerms(Collection<String> terms) { if (terms == null || terms.isEmpty()) { return ""; } Collection<String> escaped = new HashSet<>(terms.size()); for (String term : terms) { escaped.add(ClientUtils.escapeQueryChars(term)); } return "(" + StringUtils.join(escaped, " ") + ")"; } }
package org.eclipse.rdf4j.spring.util; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.sparqlbuilder.rdf.Iri; import org.eclipse.rdf4j.sparqlbuilder.rdf.Rdf; /** * @since 4.0.0 * @author Florian Kleedorfer */ public class TypeMappingUtils { public static Iri toIri(IRI from) { return Rdf.iri(from.toString()); } public static List<Iri> toIri(Collection<IRI> from) { return from.stream().map(e -> Rdf.iri(e.toString())).collect(Collectors.toList()); } public static Iri[] toIriArray(Collection<IRI> from) { return toIri(from).toArray(new Iri[from.size()]); } public static IRI toIRI(String from) { return toIRIOptional(from) .orElseThrow(() -> new NullPointerException("iriString must not be null")); } public static IRI toIRIMaybe(String from) { return toIRIOptional(from).orElse(null); } public static Optional<IRI> toIRIOptional(String from) { return Optional.ofNullable(from).map(s -> SimpleValueFactory.getInstance().createIRI(s)); } public static IRI toIRI(Value from) { return SimpleValueFactory.getInstance().createIRI(from.stringValue()); } public static Boolean toBoolean(Value from) { return ((Literal) from).booleanValue(); } public static Boolean toBooleanMaybe(Value from) { return (from == null) ? null : toBoolean(from); } public static Optional<Boolean> toBooleanOptional(Value from) { return Optional.ofNullable(from).map(TypeMappingUtils::toBoolean); } public static Boolean toBoolean(String from) { Objects.requireNonNull(from); return Boolean.valueOf(from); } public static Boolean toBooleanMaybe(String from) { return (from == null) ? null : toBoolean(from); } public static Boolean toBooleanMaybe(Boolean from) { return from; } public static Optional<Boolean> toBooleanOptional(String from) { return Optional.ofNullable(from).map(TypeMappingUtils::toBoolean); } public static Optional<Boolean> toBooleanOptional(Boolean from) { return Optional.ofNullable(from); } public static Double toDouble(Value from) { return ((Literal) from).doubleValue(); } public static BigInteger toInteger(Value from) { return ((Literal) from).integerValue(); } public static Integer toInt(Value from) { return ((Literal) from).intValue(); } public static List<IRI> toIRI(Collection<String> from) { return from.stream().map(TypeMappingUtils::toIRI).collect(Collectors.toList()); } public static final String toString(Value from) { return from.toString(); } }
package ca.ualberta.CMPUT301W15T06.test; import ca.ualberta.CMPUT301W15T06.ClaimantClaimListActivity; import ca.ualberta.CMPUT301W15T06.ClaimantClaimListController; import ca.ualberta.CMPUT301W15T06.ClaimantEditClaimActivity; import ca.ualberta.CMPUT301W15T06.ClaimantItemListActivity; import ca.ualberta.CMPUT301W15T06.MainActivity; import ca.ualberta.CMPUT301W15T06.NetWorkException; import ca.ualberta.CMPUT301W15T06.User; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.Instrumentation; import android.app.Instrumentation.ActivityMonitor; import android.app.ProgressDialog; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.ViewAsserts; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.ListView; @SuppressLint("CutPasteId") public class US09_01_01_Test extends ActivityInstrumentationTestCase2<MainActivity> { Button ApproverButton; Button ClaimantButton; Button UserButton; Instrumentation instrumentation; MainActivity activity; EditText textInput; Intent intent; TextView input_name; TextView input_start; TextView input_end; ListView listView; Menu menu; View View1; EditText claimant_name; EditText claimant_starting_date; EditText claimant_ending_date; Button FinishButton; ClaimantClaimListController cclc; User u; public US09_01_01_Test() { super(MainActivity.class); } //set up protected void setUp() throws Exception { super.setUp(); instrumentation = getInstrumentation(); activity = getActivity(); setActivityInitialTouchMode(false); ApproverButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.approverButton); ClaimantButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton); UserButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.userButton); intent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class); u = new User("temp"); cclc = new ClaimantClaimListController(u); } public void testUS010101() { /* * Test for US09.01.01 Basic Flow 1,2 */ // test button exists assertNotNull(activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton)); assertNotNull(activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.approverButton)); assertNotNull(activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.userButton)); //test "Approver" button layout final View decorView = activity.getWindow().getDecorView(); ViewAsserts.assertOnScreen(decorView, ApproverButton); final ViewGroup.LayoutParams layoutParams = ApproverButton.getLayoutParams(); assertNotNull(layoutParams); assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT); assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT); Button view = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.approverButton); assertEquals("Incorrect label of the button", "Approver", view.getText()); //test "Claimant" button layout ViewAsserts.assertOnScreen(decorView, ClaimantButton); final ViewGroup.LayoutParams layoutParams1 = ClaimantButton.getLayoutParams(); assertNotNull(layoutParams1); assertEquals(layoutParams1.width, WindowManager.LayoutParams.WRAP_CONTENT); assertEquals(layoutParams1.height, WindowManager.LayoutParams.WRAP_CONTENT); Button view1 = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton); assertEquals("Incorrect label of the button", "Claimant", view1.getText()); //test "Change User" button layout ViewAsserts.assertOnScreen(decorView, ClaimantButton); final ViewGroup.LayoutParams layoutParams2 = UserButton.getLayoutParams(); assertNotNull(layoutParams1); assertEquals(layoutParams1.width, WindowManager.LayoutParams.WRAP_CONTENT); assertEquals(layoutParams1.height, WindowManager.LayoutParams.WRAP_CONTENT); Button view2 = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.userButton); assertEquals("Incorrect label of the button", "Change User", view2.getText()); ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity.class.getName(), null, false); //User click "Change User" activity.runOnUiThread(new Runnable(){ @Override public void run() { /* * Test for US 01.01.01 Basic Flow 2 */ // click button to start another activity assertTrue(UserButton.performClick()); /* * Test for US 01.01.01 Basic Flow 3 */ //test opening a dialog // access the alert dialog using the getDialog() method created in the activity AlertDialog d = (AlertDialog) activity.getDialog(); // check layout assertTrue(d.isShowing()); Button p = d.getButton(AlertDialog.BUTTON_POSITIVE); Button n = d.getButton(AlertDialog.BUTTON_NEGATIVE); final View decorView = activity.getWindow().getDecorView(); ViewAsserts.assertOnScreen(decorView, p); ViewAsserts.assertOnScreen(decorView, n); // set text EditText et = activity.getInputField(); assertNotNull(et); et.setText("NewUser"); assertTrue(p.performClick()); } }); /* * Test for US 01.01.01 Basic Flow 5 */ //click "Claimant" button and create next activity final Button button = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton); activity.runOnUiThread(new Runnable() { @Override public void run() { // click button and open next activity. button.performClick(); ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity.class.getName(), null, false); ClaimantClaimListActivity nextActivity = (ClaimantClaimListActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 10000); // next activity is opened and captured. assertNotNull(nextActivity); // view which is expected to be present on the screen // test claim list layout final View decorView1 = nextActivity.getWindow().getDecorView(); listView = (ListView) nextActivity .findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimListView); // check if it is on screen ViewAsserts.assertOnScreen(decorView1, listView); // check whether the Button object's width and height attributes // match the expected values final ViewGroup.LayoutParams layoutParams11 = listView .getLayoutParams(); /* assertNotNull(layoutParams); */ assertEquals(layoutParams11.width, WindowManager.LayoutParams.MATCH_PARENT); assertEquals(layoutParams11.height, WindowManager.LayoutParams.WRAP_CONTENT); // after claimant request to add new claim, a new claim should be added into list int count1 = u.getClaimList().size(); assertEquals(count1, 0); // Click the menu option // open third activity by options menu ActivityMonitor am = getInstrumentation().addMonitor( ClaimantEditClaimActivity.class.getName(), null, false); // Click the menu option // getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU); getInstrumentation().invokeMenuActionSync(nextActivity, ca.ualberta.CMPUT301W15T06.R.id.add_new_claim, 1); Activity a = getInstrumentation().waitForMonitorWithTimeout(am, 10000); assertNotNull(a); a.finish(); /* * Test for US09.01.01 Basic Flow 3,4 */ final ListView claimList = (ListView) nextActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimListView); // get next activity nextActivity.runOnUiThread(new Runnable() { @Override public void run() { ActivityMonitor am = getInstrumentation().addMonitor(ClaimantItemListActivity.class.getName(), null, false); // click the list open next activity. claimList.getChildAt(0).performClick(); ClaimantItemListActivity thirdActivity = (ClaimantItemListActivity) getInstrumentation().waitForMonitorWithTimeout(am, 1000); assertNotNull(thirdActivity); ListView ilv = (ListView) thirdActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.itemListView); // check if it is on screen ViewAsserts.assertOnScreen(decorView1, ilv); // Click the option menu; getInstrumentation().invokeMenuActionSync(thirdActivity,ca.ualberta.CMPUT301W15T06.R.id.edit, 1); //open the forth activity Activity forthActivity = getInstrumentation().waitForMonitorWithTimeout(am, 10000); assertNotNull(forthActivity); thirdActivity.finish(); forthActivity.finish(); } }); nextActivity.finish(); } }); activity.finish(); } }
package com.braintreepayments.api; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.VisibleForTesting; import com.braintreepayments.api.exceptions.BraintreeException; import com.braintreepayments.api.exceptions.BrowserSwitchException; import com.braintreepayments.api.exceptions.ConfigurationException; import com.braintreepayments.api.exceptions.ErrorWithResponse; import com.braintreepayments.api.interfaces.ConfigurationListener; import com.braintreepayments.api.interfaces.HttpResponseCallback; import com.braintreepayments.api.interfaces.PaymentMethodNonceCallback; import com.braintreepayments.api.models.ClientToken; import com.braintreepayments.api.models.Configuration; import com.braintreepayments.api.models.PayPalAccountBuilder; import com.braintreepayments.api.models.PayPalConfiguration; import com.braintreepayments.api.models.PayPalPaymentResource; import com.braintreepayments.api.models.PayPalRequest; import com.braintreepayments.api.models.PaymentMethodNonce; import com.braintreepayments.api.models.PostalAddress; import com.paypal.android.sdk.onetouch.core.AuthorizationRequest; import com.paypal.android.sdk.onetouch.core.BillingAgreementRequest; import com.paypal.android.sdk.onetouch.core.CheckoutRequest; import com.paypal.android.sdk.onetouch.core.PayPalOneTouchCore; import com.paypal.android.sdk.onetouch.core.Request; import com.paypal.android.sdk.onetouch.core.Result; import com.paypal.android.sdk.onetouch.core.enums.RequestTarget; import com.paypal.android.sdk.onetouch.core.sdk.PayPalScope; import com.paypal.android.sdk.onetouch.core.sdk.PendingRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.List; /** * Class containing PayPal specific logic. */ public class PayPal { public static final int PAYPAL_REQUEST_CODE = 13591; /** * PayPal Scope for Future Payments. Always enabled for the future payments flow. */ public static final String SCOPE_FUTURE_PAYMENTS = PayPalScope.FUTURE_PAYMENTS.getScopeUri(); /** * PayPal Scope for email. Always enabled for the future payments flow. */ public static final String SCOPE_EMAIL = PayPalScope.EMAIL.getScopeUri(); /** * PayPal Scope for obtaining the accounts address. Optional, can be specified in the optional * scopes when using {@link #authorizeAccount(BraintreeFragment, List)}. */ public static final String SCOPE_ADDRESS = PayPalScope.ADDRESS.getScopeUri(); protected static boolean sEnableSignatureVerification = true; private static final String SETUP_BILLING_AGREEMENT_ENDPOINT = "paypal_hermes/setup_billing_agreement"; private static final String CREATE_SINGLE_PAYMENT_ENDPOINT = "paypal_hermes/create_payment_resource"; private static final String NO_SHIPPING_KEY = "no_shipping"; private static final String ADDRESS_OVERRIDE_KEY = "address_override"; private static final String LOCALE_CODE_KEY = "locale_code"; private static final String AUTHORIZATION_FINGERPRINT_KEY = "authorization_fingerprint"; private static final String TOKENIZATION_KEY = "client_key"; private static final String RETURN_URL_KEY = "return_url"; private static final String CANCEL_URL_KEY = "cancel_url"; private static final String EXPERIENCE_PROFILE_KEY = "experience_profile"; private static final String AMOUNT_KEY = "amount"; private static final String CURRENCY_ISO_CODE_KEY = "currency_iso_code"; private static final String PAYLOAD_CLIENT_TOKEN_KEY = "client_token"; private static Request sRequest; /** * Starts the Pay With PayPal flow. This will launch the PayPal app if installed or switch to * the browser for user authorization. The Billing Agreement flow will be used if enabled, * otherwise the Future Payment flow will be used. * * @param fragment A {@link BraintreeFragment} used to process the request. */ public static void authorizeAccount(BraintreeFragment fragment) { authorizeAccount(fragment, null); } /** * Starts the Pay With PayPal flow with additional scopes. This will launch the PayPal app if * installed or switch to the browser for user authorization. The Billing Agreement flow will be * used if enabled, otherwise the Future Payment flow will be used. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param additionalScopes A {@link java.util.List} of additional scopes. Ex: {@link * #SCOPE_ADDRESS}. Acceptable scopes are defined in {@link com.braintreepayments.api.PayPal}. */ public static void authorizeAccount(final BraintreeFragment fragment, final List<String> additionalScopes) { fragment.sendAnalyticsEvent("paypal.selected"); fragment.waitForConfiguration(new ConfigurationListener() { @Override public void onConfigurationFetched(Configuration configuration) { if (!configuration.isPayPalEnabled()) { fragment.postCallback(new ConfigurationException("PayPal is not enabled")); return; } if (configuration.getPayPal().shouldUseBillingAgreement()) { requestBillingAgreement(fragment, new PayPalRequest()); return; } sRequest = getAuthorizationRequest(fragment.getApplicationContext(), fragment.getConfiguration().getPayPal(), fragment.getAuthorization().toString()); if (additionalScopes != null) { for (String scope : additionalScopes) { ((AuthorizationRequest) sRequest).withScopeValue(scope); } } startPayPal(fragment, PayPalOneTouchCore.getStartIntent(fragment.getApplicationContext(), sRequest, sEnableSignatureVerification)); } }); } /** * Starts the Billing Agreement flow for PayPal. This will launch the PayPal app if installed or * fall back to a browser switch. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param request A {@link PayPalRequest} used to customize the request. */ public static void requestBillingAgreement(BraintreeFragment fragment, PayPalRequest request) { if (request.getAmount() == null) { requestOneTimePayment(fragment, request, true); } else { fragment.postCallback(new BraintreeException( "There must be no amount specified for the Billing Agreement flow")); } } /** * Starts the Single Payment flow for PayPal. This will launch the PayPal app if installed or * fall back to a browser switch. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param request A {@link PayPalRequest} used to customize the request. An amount MUST be * specified. */ public static void requestOneTimePayment(BraintreeFragment fragment, PayPalRequest request) { if (request.getAmount() != null) { requestOneTimePayment(fragment, request, false); } else { fragment.postCallback(new BraintreeException("An amount must be specified for the Single Payment flow.")); } } /** * Starts the Checkout With PayPal flow. This will launch the PayPal app if installed or switch * to the browser for user authorization. * <p> * This requires that the merchant uses a {@link com.braintreepayments.api.models.ClientToken} * * @param fragment A {@link BraintreeFragment} used to process the request. * @param request A {@link PayPalRequest} used to customize the request. * @param isBillingAgreement A boolean. If true, this will use the Billing Agreement. Otherwise, * PayPal will perform a Single Payment. */ private static void requestOneTimePayment(final BraintreeFragment fragment, final PayPalRequest request, final boolean isBillingAgreement) { final HttpResponseCallback callback = new HttpResponseCallback() { @Override public void success(String responseBody) { final PayPalPaymentResource paypalPaymentResource; try { paypalPaymentResource = PayPalPaymentResource.fromJson(responseBody); } catch (JSONException e) { fragment.postCallback(e); return; } if (isBillingAgreement) { sRequest = getBillingAgreementRequest(paypalPaymentResource.getRedirectUrl(), fragment.getApplicationContext(), fragment.getConfiguration().getPayPal()); } else { sRequest = getCheckoutRequest(paypalPaymentResource.getRedirectUrl(), fragment.getApplicationContext(), fragment.getConfiguration().getPayPal()); } startPayPal(fragment, PayPalOneTouchCore.getStartIntent(fragment.getApplicationContext(), sRequest, sEnableSignatureVerification)); } @Override public void failure(Exception e) { fragment.postCallback(e); } }; fragment.waitForConfiguration(new ConfigurationListener() { @Override public void onConfigurationFetched(Configuration configuration) { if (!configuration.isPayPalEnabled()) { fragment.postCallback(new ConfigurationException("PayPal is not enabled")); return; } try { createPaymentResource(fragment, request, isBillingAgreement, callback); } catch (JSONException | ErrorWithResponse | BraintreeException ex) { fragment.postCallback(ex); } } }); } /** * Create a PayPalPaymentResource on behalf of the merchant. To be used in the PayPal Checkout * flows for Single Payment and Billing Agreement. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param request A {@link PayPalRequest} used to customize the request. * @param isBillingAgreement A boolean. If true, this will use the Billing Agreement. Otherwise, * PayPal will perform a Single Payment. * @param callback A callback on the http request. */ private static void createPaymentResource(BraintreeFragment fragment, PayPalRequest request, boolean isBillingAgreement, HttpResponseCallback callback) throws JSONException, ErrorWithResponse, BraintreeException { CheckoutRequest checkoutRequest = getCheckoutRequest(null, fragment.getApplicationContext(), fragment.getConfiguration().getPayPal()); String currencyCode = request.getCurrencyCode(); if (currencyCode == null) { currencyCode = fragment.getConfiguration().getPayPal().getCurrencyIsoCode(); } JSONObject experienceProfile = new JSONObject(); experienceProfile.put(NO_SHIPPING_KEY, !request.isShippingAddressRequired()); if (request.getLocaleCode() != null) { experienceProfile.put(LOCALE_CODE_KEY, request.getLocaleCode()); } JSONObject parameters = new JSONObject() .put(RETURN_URL_KEY, checkoutRequest.getSuccessUrl()) .put(CANCEL_URL_KEY, checkoutRequest.getCancelUrl()); if (fragment.getAuthorization() instanceof ClientToken) { parameters.put(AUTHORIZATION_FINGERPRINT_KEY, ((ClientToken) fragment.getAuthorization()).getAuthorizationFingerprint()); } else { parameters.put(TOKENIZATION_KEY, fragment.getAuthorization().toString()); } if (!isBillingAgreement) { parameters.put(AMOUNT_KEY, request.getAmount()) .put(CURRENCY_ISO_CODE_KEY, currencyCode); } if (request.getShippingAddressOverride() != null && !request.getShippingAddressOverride().isEmpty()) { experienceProfile.put(ADDRESS_OVERRIDE_KEY, true); PostalAddress shippingAddress = request.getShippingAddressOverride(); parameters.put(PostalAddress.LINE_1_KEY, shippingAddress.getStreetAddress()); parameters.put(PostalAddress.LINE_2_KEY, shippingAddress.getExtendedAddress()); parameters.put(PostalAddress.LOCALITY_KEY, shippingAddress.getLocality()); parameters.put(PostalAddress.REGION_KEY, shippingAddress.getRegion()); parameters.put(PostalAddress.POSTAL_CODE_UNDERSCORE_KEY, shippingAddress.getPostalCode()); parameters.put(PostalAddress.COUNTRY_CODE_UNDERSCORE_KEY, shippingAddress.getCountryCodeAlpha2()); parameters.put(PostalAddress.RECIPIENT_NAME_UNDERSCORE_KEY, shippingAddress.getRecipientName()); } else { experienceProfile.put(ADDRESS_OVERRIDE_KEY, false); } parameters.put(EXPERIENCE_PROFILE_KEY, experienceProfile); String apiUrl = isBillingAgreement ? SETUP_BILLING_AGREEMENT_ENDPOINT : CREATE_SINGLE_PAYMENT_ENDPOINT; String versionedPath = "/v1/" + apiUrl; fragment.getHttpClient().post(versionedPath, parameters.toString(), callback); } private static void startPayPal(BraintreeFragment fragment, PendingRequest pendingRequest) { if (pendingRequest.isSuccess() && pendingRequest.getRequestTarget() == RequestTarget.wallet) { sendAnalyticsForPayPal(fragment, true, RequestTarget.wallet); fragment.startActivityForResult(pendingRequest.getIntent(), PAYPAL_REQUEST_CODE); } else if (pendingRequest.isSuccess() && pendingRequest.getRequestTarget() == RequestTarget.browser) { sendAnalyticsForPayPal(fragment, true, RequestTarget.browser); Intent intent = pendingRequest.getIntent() .putExtra(BraintreeBrowserSwitchActivity.EXTRA_BROWSER_SWITCH, true); fragment.startActivity(intent); } else { sendAnalyticsForPayPal(fragment, false, null); } } private static void sendAnalyticsForPayPal(BraintreeFragment fragment, boolean success, RequestTarget target) { String eventFragment = ""; if (isCheckoutRequest()) { if (!success) { eventFragment = "paypal-single-payment.initiate.failed"; } else if (target == RequestTarget.browser) { eventFragment = "paypal-single-payment.webswitch.initiate.started"; } else if (target == RequestTarget.wallet) { eventFragment = "paypal-single-payment.appswitch.initiate.started"; } } else { if (!success) { eventFragment = "paypal-future-payments.initiate.failed"; } else if (target == RequestTarget.browser) { eventFragment = "paypal-future-payments.webswitch.initiate.started"; } else if (target == RequestTarget.wallet) { eventFragment = "paypal-future-payments.appswitch.initiate.started"; } } AnalyticsManager.sendRequest(fragment, "custom", eventFragment); } /** * The result from PayPal's request. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param data Data associated with the result. */ protected static void onActivityResult(final BraintreeFragment fragment, Intent data) { if (data != null) { boolean isAppSwitch = isAppSwitch(data); Result result = PayPalOneTouchCore.parseResponse(fragment.getApplicationContext(), sRequest, data); switch (result.getResultType()) { case Error: fragment.postCallback(new BrowserSwitchException(result.getError().getMessage())); sendAnalyticsEventForSwitchResult(fragment, isAppSwitch, "failed"); break; case Cancel: fragment.postCancelCallback(PAYPAL_REQUEST_CODE); sendAnalyticsEventForSwitchResult(fragment, isAppSwitch, "canceled"); break; case Success: onSuccess(fragment, data, result); sendAnalyticsEventForSwitchResult(fragment, isAppSwitch, "succeeded"); break; } } else { fragment.postCancelCallback(PAYPAL_REQUEST_CODE); } } private static void onSuccess(final BraintreeFragment fragment, Intent data, Result result) { TokenizationClient.tokenize(fragment, parseResponse(result, data), new PaymentMethodNonceCallback() { @Override public void success(PaymentMethodNonce paymentMethodNonce) { fragment.postCallback(paymentMethodNonce); } @Override public void failure(Exception exception) { fragment.postCallback(exception); } }); } /** * Parse the PayPal response URL using OneTouchCore. * * @param result Context that received the result. * @param intent The {@link Intent} returned in result. * @return A {@link PayPalAccountBuilder} or null if the intent is invalid. */ private static PayPalAccountBuilder parseResponse(Result result, Intent intent) { PayPalAccountBuilder paypalAccountBuilder = new PayPalAccountBuilder() .clientMetadataId(sRequest.getClientMetadataId()); if (isAppSwitch(intent)) { paypalAccountBuilder.source("paypal-app"); } else { paypalAccountBuilder.source("paypal-browser"); } JSONObject payload = result.getResponse(); // Modify payload in 'mock' mode to scope the response try { JSONObject clientJson = payload.getJSONObject("client"); JSONObject response = payload.getJSONObject("response"); if (AuthorizationRequest.ENVIRONMENT_MOCK.equalsIgnoreCase(clientJson.getString("client")) && response.getString("code") != null && !isCheckoutRequest()) { payload.put("response", new JSONObject().put("code", "fake-code:" + ((AuthorizationRequest) sRequest).getScopeString())); } } catch (JSONException ignored) {} paypalAccountBuilder.oneTouchCoreData(payload); return paypalAccountBuilder; } /** * Send analytics for PayPal app switch result. * * @param fragment A {@link BraintreeFragment} used to process the request. * @param isAppSwitch True if the request switched to the PayPal app. False if browser switch. * @param eventFragment A {@link String} describing the result. */ private static void sendAnalyticsEventForSwitchResult(BraintreeFragment fragment, boolean isAppSwitch, String eventFragment) { String authorizationType = isCheckoutRequest() ? "paypal-single-payment" : "paypal-future-payments"; String switchType = isAppSwitch ? "appswitch" : "webswitch"; String event = String.format("%s.%s.%s", authorizationType, switchType, eventFragment); AnalyticsManager.sendRequest(fragment, "custom", event); } @VisibleForTesting static CheckoutRequest getCheckoutRequest(String redirectUrl, Context context, PayPalConfiguration configuration) { CheckoutRequest request = populateRequestData(new CheckoutRequest(), context, configuration) .approvalURL(redirectUrl); if (redirectUrl!= null) { request.pairingId(Uri.parse(redirectUrl).getQueryParameter("token")); } return request; } @VisibleForTesting static BillingAgreementRequest getBillingAgreementRequest(String redirectUrl, Context context, PayPalConfiguration configuration) { BillingAgreementRequest request = populateRequestData(new BillingAgreementRequest(), context, configuration) .approvalURL(redirectUrl); if (redirectUrl != null) { request.pairingId(Uri.parse(redirectUrl).getQueryParameter("ba_token")); } return request; } @VisibleForTesting static AuthorizationRequest getAuthorizationRequest(Context context, PayPalConfiguration configuration, String tokenizationKey) { return populateRequestData(new AuthorizationRequest(context), context, configuration) .privacyUrl(configuration.getPrivacyUrl()) .userAgreementUrl(configuration.getUserAgreementUrl()) .withScopeValue(SCOPE_FUTURE_PAYMENTS) .withScopeValue(SCOPE_EMAIL) .withAdditionalPayloadAttribute(PAYLOAD_CLIENT_TOKEN_KEY, tokenizationKey); } private static <T extends Request> T populateRequestData(T request, Context context, PayPalConfiguration configuration) { String environment; switch (configuration.getEnvironment()) { case "live": environment = AuthorizationRequest.ENVIRONMENT_LIVE; break; case "offline": environment = AuthorizationRequest.ENVIRONMENT_MOCK; break; default: environment = configuration.getEnvironment(); break; } String clientId = configuration.getClientId(); if (clientId == null && AuthorizationRequest.ENVIRONMENT_MOCK.equals(environment)) { clientId = "FAKE-PAYPAL-CLIENT-ID"; } request.environment(environment); request.clientId(clientId); request.cancelUrl(context.getPackageName() + ".braintree", "cancel"); request.successUrl(context.getPackageName() + ".braintree", "success"); return request; } /** * Check if the current/last request was a CheckoutRequest */ private static boolean isCheckoutRequest() { return sRequest instanceof CheckoutRequest; } private static boolean isAppSwitch(Intent data) { return data.getData() == null; } }
package de.faustedition.reasoning; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.google.common.io.FileBackedOutputStream; import de.faustedition.VerseInterval; import de.faustedition.document.MaterialUnit; import de.faustedition.transcript.TranscribedVerseInterval; import edu.bath.transitivityutils.ImmutableRelation; import edu.bath.transitivityutils.Relation; import edu.bath.transitivityutils.Relations; import org.hibernate.SessionFactory; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.restlet.data.MediaType; import org.restlet.representation.OutputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Set; import java.util.concurrent.*; @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class InscriptionPrecedenceResource extends ServerResource { @Autowired private GraphDatabaseService graphDb; @Autowired private SessionFactory sessionFactory; @Autowired private Environment environment; @Override protected void doInit() throws ResourceException { super.doInit(); final VerseInterval verseInterval = VerseInterval.fromRequestAttibutes(getRequestAttributes()); final Multimap<String, TranscribedVerseInterval> intervalIndex = Multimaps.index(TranscribedVerseInterval.forInterval(sessionFactory.getCurrentSession(), verseInterval), new Function<TranscribedVerseInterval, String>() { @Override public String apply(@Nullable TranscribedVerseInterval input) { final Node materialUnitNode = graphDb.getNodeById(input.getTranscript().getMaterialUnitId()); return MaterialUnit.forNode(materialUnitNode).toString() + "_" + materialUnitNode.getId(); } }); inscriptions = Sets.newHashSet(); for (String sigil : Ordering.natural().immutableSortedCopy(intervalIndex.keySet())) { final Inscription inscription = new Inscription(sigil); for (TranscribedVerseInterval interval : intervalIndex.get(sigil)) { inscription.addInterval(interval.getStart(), interval.getEnd()); } Preconditions.checkState(!inscription.isEmpty()); inscriptions.add(inscription); } for (Inscription subject : inscriptions) { for (Inscription object : inscriptions) { if (InscriptionRelations.syntagmaticallyPrecedesByFirstLine(subject, object)) { syntagmaticPrecedence.relate(subject, object); } if (InscriptionRelations.exclusivelyContains(subject, object)) { exclusiveContainment.relate(subject, object); } if (InscriptionRelations.paradigmaticallyContains(subject, object)) { paradigmaticContainment.relate(subject, object); } } } } public Representation dot() { return new StringRepresentation(asDot()); } @Get("svg") public Representation svg() throws IOException, ExecutionException, InterruptedException { final ExecutorService executorService = Executors.newCachedThreadPool(); final Process tred = new ProcessBuilder(environment.getRequiredProperty("graphviz.tred.path")).start(); final Process dot = new ProcessBuilder(environment.getRequiredProperty("graphviz.dot.path"), "-Tsvg").start(); executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { InputStream dataStream = null; OutputStream tredStream = null; try { ByteStreams.copy(dataStream = new ByteArrayInputStream(asDot().getBytes(Charset.forName("UTF-8"))), tredStream = tred.getOutputStream()); } finally { Closeables.close(dataStream, false); Closeables.close(tredStream, false); } return null; } }); executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { InputStream tredStream = null; OutputStream dotStream = null; try { ByteStreams.copy(tredStream = tred.getInputStream(), dotStream = dot.getOutputStream()); } finally { Closeables.close(tredStream, false); Closeables.close(dotStream, false); } return null; } }); final Future<FileBackedOutputStream> dotFuture = executorService.submit(new Callable<FileBackedOutputStream>() { @Override public FileBackedOutputStream call() throws Exception { final FileBackedOutputStream buf = new FileBackedOutputStream(102400); InputStream dotStream = null; try { ByteStreams.copy(dotStream = dot.getInputStream(), buf); } finally { Closeables.close(dotStream, false); Closeables.close(buf, false); } return buf; } }); Preconditions.checkState(tred.waitFor() == 0); Preconditions.checkState(dot.waitFor() == 0); final FileBackedOutputStream resultBuf = dotFuture.get(); return new OutputRepresentation(MediaType.IMAGE_SVG) { @Override public void write(OutputStream outputStream) throws IOException { ByteStreams.copy(resultBuf.getSupplier(), outputStream); resultBuf.reset(); } }; } private String asDot() { final StringBuilder dot = new StringBuilder("digraph genetic_graph {\n"); for (Inscription inscription : inscriptions) { dot.append(toLabel(inscription)).append(";\n"); } dot.append(" edge ["); dot.append(" color=").append("black"); dot.append(" fontcolor=").append("black"); dot.append(" weight=").append("1"); dot.append(" ];\n"); for (Inscription i : inscriptions) { for (Inscription j : inscriptions) { if (precedence.areRelated(i, j)) { final String premise = precedence.findRelevantPremise(i, j).getName(); dot.append(toLabel(i)); dot.append(" -> "); dot.append(toLabel(j)); dot.append(" [ "); dot.append(" label=").append(premise); dot.append(" color=").append("r_syn".equals(premise) ? "grey" : "black"); dot.append(" ];\n"); } } } dot.append("}\n"); return dot.toString(); } private String toLabel(Inscription inscription) { return inscription.getName().replaceAll("[ ,:\\(\\)\\-\\.\\{\\}/]", "_"); } private Set<Inscription> inscriptions; private Relation<Inscription> syntagmaticPrecedence = Relations.newTransitiveRelation(); private Relation<Inscription> exclusiveContainment = MultimapBasedRelation.create(); private Relation<Inscription> paradigmaticContainment = MultimapBasedRelation.create(); @SuppressWarnings("unchecked") public PremiseBasedRelation<Inscription> precedence = new PremiseBasedRelation<Inscription>( new PremiseBasedRelation.Premise<Inscription>() { @Override public String getName() { return "r_econ"; } @Override public boolean applies(Inscription i, Inscription j) { return exclusiveContainment.areRelated(i, j); } }, new PremiseBasedRelation.Premise<Inscription>() { @Override public String getName() { return "r_pcon"; } @Override public boolean applies(Inscription i, Inscription j) { return paradigmaticContainment.areRelated(j, i); } }, new PremiseBasedRelation.Premise<Inscription>() { @Override public String getName() { return "r_syn"; } @Override public boolean applies(Inscription i, Inscription j) { return syntagmaticPrecedence.areRelated(i, j); } } ); /** * @param relA * @param relB is supposed to be the overriding or "stronger" relation * @return A relation result where result(i, j) if relA(i,j) && relB(j,i) */ public Relation<Inscription> contradictions(ImmutableRelation<Inscription> relA, ImmutableRelation<Inscription> relB) { Relation<Inscription> result = MultimapBasedRelation.create(); for (Inscription i : inscriptions) for (Inscription j : inscriptions) { if (relA.areRelated(i, j) && relB.areRelated(j, i)) { result.relate(i, j); } } return result; } }
package org.flymine.dataconversion; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Iterator; import java.util.HashSet; import java.util.Set; import java.io.InputStreamReader; import java.io.File; import java.io.FileWriter; import java.io.Reader; import java.io.FileReader; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.xml.full.FullParser; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemReader; import org.intermine.dataconversion.MockItemWriter; import org.intermine.dataconversion.XmlConverter; import org.intermine.metadata.Model; import org.intermine.xml.full.Item; import org.intermine.xml.full.FullRenderer; public class PsiDataTranslatorTest extends DataTranslatorTestCase { private String tgtNs = "http://www.flymine.org/model/genomic public void testTranslate() throws Exception { Collection srcItems = getSrcItems(); // print out source items XML - result of running XmlConverter on PSI XML // FileWriter writer = new FileWriter(new File("src.xml")); // writer.write(FullRenderer.render(srcItems)); // writer.close(); DataTranslator translator = new PsiDataTranslator(new MockItemReader(writeItems(srcItems)), getOwlModel(), tgtNs); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(new HashSet(getExpectedItems()), tgtIw.getItems()); } protected String getModelName() { return "genomic"; } protected Collection getExpectedItems() throws Exception { return FullParser.parse(getClass().getClassLoader().getResourceAsStream("test/PsiDataTranslatorTest_tgt.xml")); } protected Collection getSrcItems() throws Exception { Model psiModel = Model.getInstanceByName("psi"); Reader srcReader = (new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/PsiDataTranslatorTest_src.xml"))); MockItemWriter mockIw = new MockItemWriter(new HashMap()); Reader xsdReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("psi.xsd")); XmlConverter converter = new XmlConverter(psiModel, xsdReader, mockIw); converter.process(srcReader); // FileWriter fw = new FileWriter(new File("psi_tmp.xml")); // fw.write(mockIw.getItems()); // fw.flush(); // fw.close(); return mockIw.getItems(); } protected OntModel getOwlModel() { InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("genomic.n3")); OntModel ont = ModelFactory.createOntologyModel(); ont.read(reader, null, "N3"); return ont; } }
package org.flymine.dataconversion; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Iterator; import java.util.HashSet; import java.util.Set; import java.io.InputStreamReader; import java.io.File; import java.io.FileWriter; import java.io.Reader; import java.io.FileReader; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.xml.full.FullParser; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemReader; import org.intermine.dataconversion.MockItemWriter; import org.intermine.dataconversion.XmlConverter; import org.intermine.metadata.Model; import org.intermine.xml.full.FullRenderer; public class PsiDataTranslatorTest extends DataTranslatorTestCase { private String tgtNs = "http://www.flymine.org/model/genomic public void testTranslate() throws Exception { Collection srcItems = getSrcItems(); // print out source items XML - result of running XmlConverter on PSI XML // FileWriter writer = new FileWriter(new File("src.xml")); // writer.write(FullRenderer.render(srcItems)); // writer.flush(); writer.close(); DataTranslator translator = new PsiDataTranslator(new MockItemReader(writeItems(srcItems)), getOwlModel(), tgtNs); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(new HashSet(getExpectedItems()), tgtIw.getItems()); } protected String getModelName() { return "genomic"; } protected Collection getExpectedItems() throws Exception { return FullParser.parse(getClass().getClassLoader().getResourceAsStream("test/PsiDataTranslatorTest_tgt.xml")); } protected Collection getSrcItems() throws Exception { Model psiModel = Model.getInstanceByName("psi"); Reader srcReader = (new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/PsiDataTranslatorTest_src.xml"))); MockItemWriter mockIw = new MockItemWriter(new HashMap()); Reader xsdReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("psi.xsd")); XmlConverter converter = new XmlConverter(psiModel, xsdReader, mockIw); converter.process(srcReader); return mockIw.getItems(); } protected OntModel getOwlModel() { InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("genomic.n3")); OntModel ont = ModelFactory.createOntologyModel(); ont.read(reader, null, "N3"); return ont; } }
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class LoginTest { private WebDriver driver; private WebDriverWait wait; @Before public void start() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, 10); } @Test public void Test() { driver.get("http://localhost/litecart/admin/"); driver.findElement(By.name("username")).clear(); driver.findElement(By.name("username")).sendKeys("admin"); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys("admin"); driver.findElement(By.name("login")).click(); } @After public void stop() { driver.quit(); driver=null; } }
package <%=packageName%>.web.rest; import com.codahale.metrics.annotation.Timed; <% if (authenticationType == 'session') { %> import <%=packageName%>.domain.PersistentToken;<% } %> import <%=packageName%>.domain.User;<% if (authenticationType == 'session') { %> import <%=packageName%>.repository.PersistentTokenRepository;<% } %> import <%=packageName%>.repository.UserRepository; import <%=packageName%>.security.SecurityUtils; import <%=packageName%>.service.MailService; import <%=packageName%>.service.UserService; import <%=packageName%>.service.dto.UserDTO; import <%=packageName%>.web.rest.vm.KeyAndPasswordVM; import <%=packageName%>.web.rest.vm.ManagedUserVM; import <%=packageName%>.web.rest.util.HeaderUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; /** * REST controller for managing the current user's account. */ @RestController @RequestMapping("/api") public class AccountResource { private final Logger log = LoggerFactory.getLogger(AccountResource.class); @Inject private UserRepository userRepository; @Inject private UserService userService;<% if (authenticationType == 'session') { %> @Inject private PersistentTokenRepository persistentTokenRepository;<% } %> @Inject private MailService mailService; /** * POST /register : register the user. * * @param managedUserVM the managed user View Model * @param request the HTTP request * @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad Request) if the login or e-mail is already in use */ @PostMapping(path = "/register", produces={MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE}) @Timed public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM, HttpServletRequest request) { HttpHeaders textPlainHeaders = new HttpHeaders(); textPlainHeaders.setContentType(MediaType.TEXT_PLAIN); return userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()) .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> userRepository.findOneByEmail(managedUserVM.getEmail()) .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> { User user = userService.createUser(managedUserVM.getLogin(), managedUserVM.getPassword(), managedUserVM.getFirstName(), managedUserVM.getLastName(), managedUserVM.getEmail().toLowerCase(), managedUserVM.getLangKey()); String baseUrl = request.getScheme() + // "http" ": request.getServerName() + // "myhost" ":" + request.getServerPort() + request.getContextPath(); // "/myContextPath" or "" if deployed in root context mailService.sendActivationEmail(user, baseUrl); return new ResponseEntity<>(HttpStatus.CREATED); }) ); } /** * GET /activate : activate the registered user. * * @param key the activation key * @return the ResponseEntity with status 200 (OK) and the activated user in body, or status 500 (Internal Server Error) if the user couldn't be activated */ @GetMapping("/activate") @Timed public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) { return userService.activateRegistration(key) .map(user -> new ResponseEntity<String>(HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); } /** * GET /authenticate : check if the user is authenticated, and return its login. * * @param request the HTTP request * @return the login if the user is authenticated */ @GetMapping("/authenticate") @Timed public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } /** * GET /account : get the current user. * * @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server Error) if the user couldn't be returned */ @GetMapping("/account") @Timed public ResponseEntity<UserDTO> getAccount() { return Optional.ofNullable(userService.getUserWithAuthorities()) .map(user -> new ResponseEntity<>(new UserDTO(user), HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); } /** * POST /account : update the current user information. * * @param userDTO the current user information * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated */ @PostMapping(path = "/account") @Timed public ResponseEntity<String> saveAccount(@Valid @RequestBody UserDTO userDTO) { Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")).body(null); } return userRepository .findOneByLogin(SecurityUtils.getCurrentUserLogin()) .map(u -> { userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()); return new ResponseEntity<String>(HttpStatus.OK); }) .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); } /** * POST /account/change_password : changes the current user's password * * @param password the new password * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) if the new password is not strong enough */ @PostMapping(path = "/account/change_password", produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<?> changePassword(@RequestBody String password) { if (!checkPasswordLength(password)) { return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST); } userService.changePassword(password); return new ResponseEntity<>(HttpStatus.OK); }<% if (authenticationType == 'session') { %> /** * GET /account/sessions : get the current open sessions. * * @return the ResponseEntity with status 200 (OK) and the current open sessions in body, * or status 500 (Internal Server Error) if the current open sessions couldn't be retrieved */ @GetMapping("/account/sessions") @Timed public ResponseEntity<List<PersistentToken>> getCurrentSessions() { return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()) .map(user -> new ResponseEntity<>( persistentTokenRepository.findByUser(user), HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); } /** * DELETE /account/sessions?series={series} : invalidate an existing session. * * - You can only delete your own sessions, not any other user's session * - If you delete one of your existing sessions, and that you are currently logged in on that session, you will * still be able to use that session, until you quit your browser: it does not work in real time (there is * no API for that), it only removes the "remember me" cookie * - This is also true if you invalidate your current session: you will still be able to use it until you close * your browser or that the session times out. But automatic login (the "remember me" cookie) will not work * anymore. * There is an API to invalidate the current session, but there is no API to check which session uses which * cookie. * * @param series the series of an existing session * @throws UnsupportedEncodingException if the series couldnt be URL decoded */ @DeleteMapping("/account/sessions/{series}") @Timed public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException { String decodedSeries = URLDecoder.decode(series, "UTF-8"); userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> { persistentTokenRepository.findByUser(u).stream() .filter(persistentToken -> StringUtils.equals(persistentToken.getSeries(), decodedSeries)) .findAny().ifPresent(t -> persistentTokenRepository.delete(decodedSeries)); }); }<% } %> /** * POST /account/reset_password/init : Send an e-mail to reset the password of the user * * @param mail the mail of the user * @param request the HTTP request * @return the ResponseEntity with status 200 (OK) if the e-mail was sent, or status 400 (Bad Request) if the e-mail address is not registered */ @PostMapping(path = "/account/reset_password/init", produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<?> requestPasswordReset(@RequestBody String mail, HttpServletRequest request) { return userService.requestPasswordReset(mail) .map(user -> { String baseUrl = request.getScheme() + ": request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); mailService.sendPasswordResetMail(user, baseUrl); return new ResponseEntity<>("e-mail was sent", HttpStatus.OK); }).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST)); } /** * POST /account/reset_password/finish : Finish to reset the password of the user * * @param keyAndPassword the generated key and the new password * @return the ResponseEntity with status 200 (OK) if the password has been reset, * or status 400 (Bad Request) or 500 (Internal Server Error) if the password could not be reset */ @PostMapping(path = "/account/reset_password/finish", produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<String> finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST); } return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()) .map(user -> new ResponseEntity<String>(HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); } private boolean checkPasswordLength(String password) { return (!StringUtils.isEmpty(password) && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH); } }
package mil.nga.geopackage.tiles.retriever; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import org.osgeo.proj4j.ProjCoordinate; import java.io.IOException; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.io.BitmapConverter; import mil.nga.geopackage.projection.Projection; import mil.nga.geopackage.projection.ProjectionTransform; import mil.nga.geopackage.tiles.TileBoundingBoxAndroidUtils; import mil.nga.geopackage.tiles.TileBoundingBoxUtils; import mil.nga.geopackage.tiles.TileGrid; import mil.nga.geopackage.tiles.matrix.TileMatrix; import mil.nga.geopackage.tiles.matrixset.TileMatrixSet; import mil.nga.geopackage.tiles.user.TileCursor; import mil.nga.geopackage.tiles.user.TileDao; import mil.nga.geopackage.tiles.user.TileRow; /** * Tile Creator, creates a tile from a tile matrix to the desired projection * * @author osbornb * @since 1.2.10 */ public class TileCreator { /** * Compress format */ private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; /** * Tile DAO */ public final TileDao tileDao; /** * Tile width */ public final Integer width; /** * Tile height */ public final Integer height; /** * Tile Matrix Set */ public final TileMatrixSet tileMatrixSet; /** * Projection of the requests */ public final Projection requestProjection; /** * Projection of the tiles */ public final Projection tilesProjection; /** * Tile Set bounding box */ public final BoundingBox tileSetBoundingBox; /** * Flag indicating */ public final boolean sameProjection; /** * Constructor * * @param tileDao * @param width * @param height * @param tileMatrixSet * @param requestProjection * @param tilesProjection */ public TileCreator(TileDao tileDao, Integer width, Integer height, TileMatrixSet tileMatrixSet, Projection requestProjection, Projection tilesProjection) { this.tileDao = tileDao; this.width = width; this.height = height; this.tileMatrixSet = tileMatrixSet; this.requestProjection = requestProjection; this.tilesProjection = tilesProjection; tileSetBoundingBox = tileMatrixSet.getBoundingBox(); // Check if the projections have the same from meters value sameProjection = (requestProjection.getUnit().name.equals(tilesProjection.getUnit().name)); } /** * Check if the tile table contains a tile for the request bounding box * * @param requestBoundingBox request bounding box in the request projection * @return true if a tile exists */ public boolean hasTile(BoundingBox requestBoundingBox) { boolean hasTile = false; // Transform to the projection of the tiles ProjectionTransform transformRequestToTiles = requestProjection.getTransformation(tilesProjection); BoundingBox tilesBoundingBox = transformRequestToTiles.transform(requestBoundingBox); TileMatrix tileMatrix = getTileMatrix(tilesBoundingBox); TileCursor tileResults = retrieveTileResults(tilesBoundingBox, tileMatrix); if (tileResults != null) { try { hasTile = tileResults.getCount() > 0; } finally { tileResults.close(); } } return hasTile; } /** * Get the tile from the request bounding box in the request projection * * @param requestBoundingBox request bounding box in the request projection * @return tile */ public GeoPackageTile getTile(BoundingBox requestBoundingBox) { GeoPackageTile tile = null; // Transform to the projection of the tiles ProjectionTransform transformRequestToTiles = requestProjection.getTransformation(tilesProjection); BoundingBox tilesBoundingBox = transformRequestToTiles.transform(requestBoundingBox); TileMatrix tileMatrix = getTileMatrix(tilesBoundingBox); TileCursor tileResults = retrieveTileResults(tilesBoundingBox, tileMatrix); if (tileResults != null) { try { if (tileResults.getCount() > 0) { BoundingBox requestProjectedBoundingBox = transformRequestToTiles.transform(requestBoundingBox); // Determine the requested tile dimensions, or use the dimensions of a single tile matrix tile int requestedTileWidth = width != null ? width : (int) tileMatrix .getTileWidth(); int requestedTileHeight = height != null ? height : (int) tileMatrix .getTileHeight(); // Determine the size of the tile to initially draw int tileWidth = requestedTileWidth; int tileHeight = requestedTileHeight; if (!sameProjection) { tileWidth = (int) Math.round( (requestProjectedBoundingBox.getMaxLongitude() - requestProjectedBoundingBox.getMinLongitude()) / tileMatrix.getPixelXSize()); tileHeight = (int) Math.round( (requestProjectedBoundingBox.getMaxLatitude() - requestProjectedBoundingBox.getMinLatitude()) / tileMatrix.getPixelYSize()); } // Draw the resulting bitmap with the matching tiles Bitmap tileBitmap = drawTile(tileMatrix, tileResults, requestProjectedBoundingBox, tileWidth, tileHeight); // Create the tile if (tileBitmap != null) { // Project the tile if needed if (!sameProjection) { Bitmap reprojectTile = reprojectTile(tileBitmap, requestedTileWidth, requestedTileHeight, requestBoundingBox, transformRequestToTiles, tilesBoundingBox); tileBitmap.recycle(); tileBitmap = reprojectTile; } try { byte[] tileData = BitmapConverter.toBytes( tileBitmap, COMPRESS_FORMAT); tileBitmap.recycle(); tile = new GeoPackageTile(requestedTileWidth, requestedTileHeight, tileData); } catch (IOException e) { Log.e(TileCreator.class.getSimpleName(), "Failed to create tile. min lat: " + requestBoundingBox.getMinLatitude() + ", max lat: " + requestBoundingBox.getMaxLatitude() + ", min lon: " + requestBoundingBox.getMinLongitude() + ", max lon: " + requestBoundingBox.getMaxLongitude(), e); } } } } finally { tileResults.close(); } } return tile; } /** * Draw the tile from the tile results * * @param tileMatrix * @param tileResults * @param requestProjectedBoundingBox * @param tileWidth * @param tileHeight * @return tile bitmap */ private Bitmap drawTile(TileMatrix tileMatrix, TileCursor tileResults, BoundingBox requestProjectedBoundingBox, int tileWidth, int tileHeight) { // Draw the resulting bitmap with the matching tiles Bitmap tileBitmap = null; Canvas canvas = null; Paint paint = null; while (tileResults.moveToNext()) { // Get the next tile TileRow tileRow = tileResults.getRow(); Bitmap tileDataBitmap = tileRow.getTileDataBitmap(); // Get the bounding box of the tile BoundingBox tileBoundingBox = TileBoundingBoxUtils .getBoundingBox( tileSetBoundingBox, tileMatrix, tileRow.getTileColumn(), tileRow.getTileRow()); // Get the bounding box where the requested image and // tile overlap BoundingBox overlap = TileBoundingBoxUtils.overlap( requestProjectedBoundingBox, tileBoundingBox); // If the tile overlaps with the requested box if (overlap != null) { // Get the rectangle of the tile image to draw Rect src = TileBoundingBoxAndroidUtils .getRectangle(tileMatrix.getTileWidth(), tileMatrix.getTileHeight(), tileBoundingBox, overlap); // Get the rectangle of where to draw the tile in // the resulting image RectF dest = TileBoundingBoxAndroidUtils .getRoundedFloatRectangle(tileWidth, tileHeight, requestProjectedBoundingBox, overlap); // Create the bitmap first time through if (tileBitmap == null) { tileBitmap = Bitmap.createBitmap(tileWidth, tileHeight, Bitmap.Config.ARGB_8888); canvas = new Canvas(tileBitmap); paint = new Paint(Paint.ANTI_ALIAS_FLAG); } // Draw the tile to the bitmap canvas.drawBitmap(tileDataBitmap, src, dest, paint); } } return tileBitmap; } /** * Reproject the tile to the requested projection * * @param tile tile in the tile matrix projection * @param requestedTileWidth requested tile width * @param requestedTileHeight requested tile height * @param requestBoundingBox request bounding box in the request projection * @param transformRequestToTiles transformation from request to tiles * @param tilesBoundingBox request bounding box in the tile matrix projection * @return projected tile */ private Bitmap reprojectTile(Bitmap tile, int requestedTileWidth, int requestedTileHeight, BoundingBox requestBoundingBox, ProjectionTransform transformRequestToTiles, BoundingBox tilesBoundingBox) { final double requestedWidthUnitsPerPixel = (requestBoundingBox.getMaxLongitude() - requestBoundingBox.getMinLongitude()) / requestedTileWidth; final double requestedHeightUnitsPerPixel = (requestBoundingBox.getMaxLatitude() - requestBoundingBox.getMinLatitude()) / requestedTileHeight; final double tilesDistanceWidth = tilesBoundingBox.getMaxLongitude() - tilesBoundingBox.getMinLongitude(); final double tilesDistanceHeight = tilesBoundingBox.getMaxLatitude() - tilesBoundingBox.getMinLatitude(); final int width = tile.getWidth(); final int height = tile.getHeight(); // Tile pixels of the tile matrix tiles int[] pixels = new int[width * height]; tile.getPixels(pixels, 0, width, 0, 0, width, height); // Projected tile pixels to draw the reprojected tile int[] projectedPixels = new int[requestedTileWidth * requestedTileHeight]; // Retrieve each pixel in the new tile from the unprojected tile for (int y = 0; y < requestedTileHeight; y++) { for (int x = 0; x < requestedTileWidth; x++) { double longitude = requestBoundingBox.getMinLongitude() + (x * requestedWidthUnitsPerPixel); double latitude = requestBoundingBox.getMaxLatitude() - (y * requestedHeightUnitsPerPixel); ProjCoordinate fromCoord = new ProjCoordinate(longitude, latitude); ProjCoordinate toCoord = transformRequestToTiles.transform(fromCoord); double projectedLongitude = toCoord.x; double projectedLatitude = toCoord.y; int xPixel = (int) Math.round(((projectedLongitude - tilesBoundingBox.getMinLongitude()) / tilesDistanceWidth) * width); int yPixel = (int) Math.round(((tilesBoundingBox.getMaxLatitude() - projectedLatitude) / tilesDistanceHeight) * height); xPixel = Math.max(0, xPixel); xPixel = Math.min(width - 1, xPixel); yPixel = Math.max(0, yPixel); yPixel = Math.min(height - 1, yPixel); int color = pixels[(yPixel * width) + xPixel]; projectedPixels[(y * requestedTileWidth) + x] = color; } } // Draw the new tile bitmap Bitmap projectedTileBitmap = Bitmap.createBitmap(requestedTileWidth, requestedTileHeight, tile.getConfig()); projectedTileBitmap.setPixels(projectedPixels, 0, requestedTileWidth, 0, 0, requestedTileWidth, requestedTileHeight); return projectedTileBitmap; } /** * Get the tile matrix that contains the tiles for the bounding box, matches against the bounding box and zoom level * * @param projectedRequestBoundingBox bounding box projected to the tiles * @return tile matrix or null */ private TileMatrix getTileMatrix(BoundingBox projectedRequestBoundingBox) { TileMatrix tileMatrix = null; // Check if the request overlaps the tile matrix set if (TileBoundingBoxUtils.overlap(projectedRequestBoundingBox, tileSetBoundingBox) != null) { // Get the tile distance double distance = projectedRequestBoundingBox.getMaxLongitude() - projectedRequestBoundingBox.getMinLongitude(); // Get the zoom level to request based upon the tile size Long zoomLevel = tileDao.getZoomLevel(distance); // If there is a matching zoom level if (zoomLevel != null) { tileMatrix = tileDao.getTileMatrix(zoomLevel); } } return tileMatrix; } /** * Get the tile row results of tiles needed to draw the requested bounding box tile * * @param projectedRequestBoundingBox bounding box projected to the tiles * @param tileMatrix * @return tile cursor results or null */ private TileCursor retrieveTileResults(BoundingBox projectedRequestBoundingBox, TileMatrix tileMatrix) { TileCursor tileResults = null; if (tileMatrix != null) { // Get the tile grid TileGrid tileGrid = TileBoundingBoxUtils.getTileGrid( tileSetBoundingBox, tileMatrix.getMatrixWidth(), tileMatrix.getMatrixHeight(), projectedRequestBoundingBox); // Query for matching tiles in the tile grid tileResults = tileDao.queryByTileGrid(tileGrid, tileMatrix.getZoomLevel()); } return tileResults; } }
package org.jboss.windup.graph.model; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.frames.Adjacency; import com.tinkerpop.frames.Property; import com.tinkerpop.frames.modules.typedgraph.TypeValue; /** * Project dependency information. This has all of the information that would be required for a Maven dependency, but * can also be used for non-maven dependencies. Additional interfaces may extend this to provide further functionality. */ @TypeValue(ProjectDependencyModel.TYPE) public interface ProjectDependencyModel extends WindupVertexFrame { public static final String TYPE = "ProjectDependency"; public static final String PROPERTY_SCOPE = "dependencyScope"; public static final String PROPERTY_CLASSIFIER = "dependencyClassifier"; public static final String PROPERTY_TYPE = "dependencyType"; @Property(PROPERTY_SCOPE) void setScope(String scope); @Property(PROPERTY_SCOPE) String getScope(); @Property(PROPERTY_CLASSIFIER) void setClassifier(String classifier); @Property(PROPERTY_CLASSIFIER) String getClassifier(); @Property(PROPERTY_TYPE) void setType(String type); @Property(PROPERTY_TYPE) void getType(); /** * A reference to the project represented by this dependency (whether that be a project representing a binary jar, * or a project representing a different source module within the current application). */ @Adjacency(label = TYPE + ".representedProject", direction = Direction.OUT) void setProject(ProjectModel projectModel); @Adjacency(label = TYPE + ".representedProject", direction = Direction.OUT) ProjectModel getProjectModel(); }
package com.netcosports.flip; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.AnimationUtils; public class FlipCountdownView extends View{ private int roundRectRadius = 4; private int middleLineHeight = 2; public FlipCountdownView(Context context) { super(context); init(null); } public FlipCountdownView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public FlipCountdownView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private Paint mPaint; private Paint mPaintBg; private Paint mPaintGradientTop; private Paint mPaintMiddle; private Paint mPaintInnerShadow; private int numberOffset = 0; private int colorGradientTop; private boolean mEnableInnerShadow; private boolean mEnableOuterShadow; private boolean mEnableGradient; private void init(AttributeSet attrs) { Resources res = getContext().getResources(); int textColor, bgColor, innerShadowColor, middleColor, outerShadowColor; float textSize; if(attrs != null) { TypedArray a = res.obtainAttributes(attrs, R.styleable.FlipCountdownView); textColor = a.getColor(R.styleable.FlipCountdownView_flipTextColor, res.getColor(R.color.flip_countdown_text)); bgColor = a.getColor(R.styleable.FlipCountdownView_flipBackgroundColor, res.getColor(R.color.flip_countdown_background)); innerShadowColor = a.getColor(R.styleable.FlipCountdownView_flipInnerShadowColor, res.getColor(R.color.flip_inner_shadow)); outerShadowColor = a.getColor(R.styleable.FlipCountdownView_flipOuterShadowColor, res.getColor(R.color.flip_outer_shadow)); middleColor = a.getColor(R.styleable.FlipCountdownView_flipMiddleColor, res.getColor(R.color.flip_middle_divider)); textSize = a.getDimension(R.styleable.FlipCountdownView_flipTextSize, res.getDimension(R.dimen.flip_countdown_text_size)); mEnableInnerShadow = a.getBoolean(R.styleable.FlipCountdownView_flipEnableInnerShadow, res.getBoolean(R.bool.flip_enable_inner_shadow)); mEnableOuterShadow = a.getBoolean(R.styleable.FlipCountdownView_flipEnableOuterShadow, res.getBoolean(R.bool.flip_enable_outer_shadow)); mEnableGradient = a.getBoolean(R.styleable.FlipCountdownView_flipEnableGradient, res.getBoolean(R.bool.flip_enable_gradient)); a.recycle(); } else { textColor = res.getColor(R.color.flip_countdown_text); bgColor = res.getColor(R.color.flip_countdown_background); innerShadowColor = res.getColor(R.color.flip_inner_shadow); outerShadowColor = res.getColor(R.color.flip_outer_shadow); middleColor = res.getColor(R.color.flip_middle_divider); textSize = res.getDimension(R.dimen.flip_countdown_text_size); mEnableInnerShadow = res.getBoolean(R.bool.flip_enable_inner_shadow); mEnableOuterShadow = res.getBoolean(R.bool.flip_enable_outer_shadow); mEnableGradient = res.getBoolean(R.bool.flip_enable_gradient); } roundRectRadius = res.getDimensionPixelSize(R.dimen.flip_countdown_round_rect_radius); middleLineHeight = res.getDimensionPixelSize(R.dimen.flip_countdown_middle_line_height); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(textColor); mPaint.setTextSize(textSize); mPaintBg = new Paint(Paint.ANTI_ALIAS_FLAG); mPaintBg.setColor(bgColor); mPaintBg.setStyle(Paint.Style.FILL); if(mEnableOuterShadow) { mPaintBg.setShadowLayer(res.getDimension(R.dimen.flip_outer_shadow_radius), res.getDimension(R.dimen.flip_outer_shadow_dx), res.getDimension(R.dimen.flip_outer_shadow_dy), outerShadowColor); } if(mEnableInnerShadow) { mPaintInnerShadow = new Paint(Paint.ANTI_ALIAS_FLAG); mPaintInnerShadow.setColor(innerShadowColor); mPaintInnerShadow.setStyle(Paint.Style.STROKE); mPaintInnerShadow.setStrokeWidth(middleLineHeight); mPaintInnerShadow.setMaskFilter(new BlurMaskFilter(res.getDimensionPixelSize(R.dimen.flip_inner_shadow_blur_radius), BlurMaskFilter.Blur.OUTER)); } mPaintMiddle = new Paint(Paint.ANTI_ALIAS_FLAG); mPaintMiddle.setColor(middleColor); mPaintMiddle.setStrokeWidth(middleLineHeight); mPaintMiddle.setStyle(Paint.Style.STROKE); mPaintGradientTop = new Paint(Paint.ANTI_ALIAS_FLAG); colorGradientTop = res.getColor(R.color.flip_countdown_gradient); duration = res.getInteger(R.integer.flip_duration); if((mEnableOuterShadow || mEnableInnerShadow) && Build.VERSION.SDK_INT >= 11) { setLayerType(LAYER_TYPE_SOFTWARE, null); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(mEnableGradient) { mPaintGradientTop.setShader(new LinearGradient(0, getPaddingLeft(), getPaddingTop(), getMeasuredHeight() / 2, new int[]{Color.TRANSPARENT, colorGradientTop}, new float[]{0, 1}, Shader.TileMode.REPEAT )); } } private int mCurrentValue = -1; private int mValue = -1; public void setValue(int value) { if(value >= 0) { mValue = value; invalidate(); } } private float duration; public void setDuration(int duration) { this.duration = duration; } private long startAnimTimestamp = 0; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawBgRect(canvas); if(mValue >= 0) { if(mCurrentValue == -1 || mCurrentValue == mValue) { mCurrentValue = mValue; drawNumber(canvas, mValue); } else if(mCurrentValue != mValue) { //animation in progress if(startAnimTimestamp == 0) { //start animation startAnimTimestamp = AnimationUtils.currentAnimationTimeMillis(); drawNumber(canvas, mCurrentValue); ViewCompat.postInvalidateOnAnimation(this); } else { float currentPercentage = (AnimationUtils.currentAnimationTimeMillis() - startAnimTimestamp) / duration; if(currentPercentage >= 1) { //animation finished mCurrentValue = mValue; startAnimTimestamp = 0; drawNumber(canvas, mCurrentValue); } else { //draw current state drawHalfUpperNumber(canvas, mValue); float percent = 1 - 2 * currentPercentage; drawHalfUpperNumber(canvas, mCurrentValue, percent); drawHalfBottomNumber(canvas, mCurrentValue); drawHalfBottomNumber(canvas, mValue, 2 * (currentPercentage - 0.5f)); ViewCompat.postInvalidateOnAnimation(this); } } } } canvas.drawLine(getPaddingLeft(), getMeasuredHeight()/2, getMeasuredWidth() - getPaddingRight(), getMeasuredHeight()/2, mPaintMiddle); if(mEnableInnerShadow) { canvas.drawLine(getPaddingLeft(), getMeasuredHeight() / 2, getMeasuredWidth() - getPaddingRight(), getMeasuredHeight() / 2, mPaintInnerShadow); } } private Rect bounds = new Rect(); private void drawNumber(Canvas canvas, int value) { drawHalfBottomNumber(canvas, value); drawHalfUpperNumber(canvas, value); } private RectF rectF = new RectF(); private void drawHalfBottomNumber(Canvas canvas, int value) { drawHalfBottomNumber(canvas, value, 1); } private void drawHalfBottomNumber(Canvas canvas, int value, float percent) { percent = getRealPercent(percent); if(percent != 0) { String text = String.valueOf(value); mPaint.getTextBounds(text, 0, text.length(), bounds); canvas.save(); canvas.clipRect(getPaddingLeft(), getMeasuredHeight() / 2 + numberOffset /2, getMeasuredWidth() - getPaddingRight(), getMeasuredHeight() - getPaddingBottom()); canvas.scale(1, percent, 0, getMeasuredHeight() / 2); setColorFilter(percent); drawBgRect(canvas); float widthText = mPaint.measureText(text); canvas.drawText(text, (int) (getMeasuredWidth() / 2 - widthText / 2), getMeasuredHeight() / 2 + bounds.height() / 2, mPaint); canvas.restore(); } } private void setColorFilter(float percent) { if(percent != 1) { PorterDuffColorFilter filter = new PorterDuffColorFilter(addAlphaPercentToColor((int) (80 - 80 * percent), Color.BLACK), PorterDuff.Mode.DARKEN); mPaintBg.setColorFilter(filter); } else { mPaintBg.setColorFilter(null); } } public static int addAlphaPercentToColor(int alphaPercent, int color) { return Color.argb(alphaPercent * 255 / 100, Color.red(color), Color.green(color), Color.blue(color)); } private void drawHalfUpperNumber(Canvas canvas, int value) { drawHalfUpperNumber(canvas, value, 1); } private void drawHalfUpperNumber(Canvas canvas, int value, float percent) { percent = getRealPercent(percent); if(percent != 0) { String text = String.valueOf(value); mPaint.getTextBounds(text, 0, text.length(), bounds); canvas.save(); canvas.clipRect(getPaddingLeft(), getPaddingTop(), getMeasuredWidth() - getPaddingRight(), getMeasuredHeight() / 2 - numberOffset / 2); canvas.scale(1, percent, 0, getMeasuredHeight() / 2); setColorFilter(percent); drawBgRect(canvas); float widthText = mPaint.measureText(text); canvas.drawText(text, (int) (getMeasuredWidth() / 2 - widthText / 2), getMeasuredHeight() / 2 + bounds.height() / 2, mPaint); canvas.restore(); } } private void drawBgRect(Canvas canvas) { rectF.set(getPaddingLeft(), getPaddingTop(), getMeasuredWidth() - getPaddingLeft(), getMeasuredHeight() - getPaddingBottom()); canvas.drawRoundRect(rectF, roundRectRadius, roundRectRadius, mPaintBg); if(mEnableGradient) { rectF.set(getPaddingLeft(), getPaddingTop(), getMeasuredWidth() - getPaddingRight(), getMeasuredHeight() / 2); canvas.drawRoundRect(rectF, roundRectRadius, roundRectRadius, mPaintGradientTop); } } private float getRealPercent(float percent) { if(percent > 1) percent = 1; else if(percent < 0) percent = 0; return percent; } }
package org.waterforpeople.mapping.helper; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.AccessPointScoreDetailDao; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.AccessPointMappingHistory; import org.waterforpeople.mapping.domain.AccessPointScoreComputationItem; import org.waterforpeople.mapping.domain.AccessPointScoreDetail; import org.waterforpeople.mapping.domain.GeoCoordinates; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import com.beoui.geocell.GeocellManager; import com.beoui.geocell.model.Point; import com.gallatinsystems.common.util.StringUtil; import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.domain.DataChangeRecord; import com.gallatinsystems.gis.coordinate.utilities.CoordinateUtilities; import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl; import com.gallatinsystems.gis.location.GeoPlace; import com.gallatinsystems.gis.map.domain.OGRFeature; import com.gallatinsystems.standards.dao.StandardScoringDao; import com.gallatinsystems.standards.domain.StandardScoring; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.domain.Question; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; public class AccessPointHelper { private static String photo_url_root; private static final String GEO_TYPE = "GEO"; private static final String PHOTO_TYPE = "IMAGE"; private SurveyAttributeMappingDao mappingDao; static { Properties props = System.getProperties(); photo_url_root = props.getProperty("photo_url_root"); } private static Logger logger = Logger.getLogger(AccessPointHelper.class .getName()); public AccessPointHelper() { mappingDao = new SurveyAttributeMappingDao(); } public AccessPoint getAccessPoint(Long id) { BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class); return apDAO.getByKey(id); } public AccessPoint getAccessPoint(Long id, Boolean needScoreDetail) { BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class); AccessPointScoreDetailDao apddao = new AccessPointScoreDetailDao(); AccessPoint ap = apDAO.getByKey(id); List<AccessPointScoreDetail> apScoreSummaryList = apddao .listByAccessPointId(id); if (apScoreSummaryList != null && !apScoreSummaryList.isEmpty()) ap.setApScoreDetailList(apScoreSummaryList); return ap; } public void processSurveyInstance(String surveyInstanceId) { // Get the survey and QuestionAnswerStore // Get the surveyDefinition SurveyInstanceDAO sid = new SurveyInstanceDAO(); List<QuestionAnswerStore> questionAnswerList = sid .listQuestionAnswerStore(Long.parseLong(surveyInstanceId), null); Collection<AccessPoint> apList = null; if (questionAnswerList != null && questionAnswerList.size() > 0) { try { apList = parseAccessPoint(new Long(questionAnswerList.get(0) .getSurveyId()), questionAnswerList, AccessPoint.AccessPointType.WATER_POINT); } catch (Exception ex) { logger.log(Level.SEVERE, "problem parsing access point." + ex); } if (apList != null) { for (AccessPoint ap : apList) { try { saveAccessPoint(ap); } catch (Exception ex) { logger.log( Level.SEVERE, "Inside processSurveyInstance could not save AP for SurveyInstanceId: " + surveyInstanceId + ":" + ap.toString() + " ex: " + ex + " exMessage: " + ex.getMessage()); } } } } } private Collection<AccessPoint> parseAccessPoint(Long surveyId, List<QuestionAnswerStore> questionAnswerList, AccessPoint.AccessPointType accessPointType) { Collection<AccessPoint> apList = null; List<SurveyAttributeMapping> mappings = mappingDao .listMappingsBySurvey(surveyId); if (mappings != null) { apList = parseAccessPoint(surveyId, questionAnswerList, mappings); } else { logger.log(Level.SEVERE, "NO mappings for survey " + surveyId); } return apList; } /** * uses the saved mappings for the survey definition to parse values in the * questionAnswerStore into attributes of an AccessPoint object * * TODO: figure out way around known limitation of only having 1 GEO * response per survey * * @param questionAnswerList * @param mappings * @return */ private Collection<AccessPoint> parseAccessPoint(Long surveyId, List<QuestionAnswerStore> questionAnswerList, List<SurveyAttributeMapping> mappings) { HashMap<String, AccessPoint> apMap = new HashMap<String, AccessPoint>(); List<AccessPointMappingHistory> apmhList = new ArrayList<AccessPointMappingHistory>(); List<Question> questionList = new QuestionDao() .listQuestionsBySurvey(surveyId); if (questionAnswerList != null) { for (QuestionAnswerStore qas : questionAnswerList) { SurveyAttributeMapping mapping = getMappingForQuestion( mappings, qas.getQuestionID()); if (mapping != null) { List<String> types = mapping.getApTypes(); if (types == null || types.size() == 0) { // default the list to be access point if nothing is // specified (for backward compatibility) types.add(AccessPointType.WATER_POINT.toString()); } else { if (types.contains(AccessPointType.PUBLIC_INSTITUTION .toString()) && (types.contains(AccessPointType.HEALTH_POSTS .toString()) || types .contains(AccessPointType.SCHOOL .toString()))) { types.remove(AccessPointType.PUBLIC_INSTITUTION .toString()); } } for (String type : types) { AccessPointMappingHistory apmh = new AccessPointMappingHistory(); apmh.setSource(this.getClass().getName()); apmh.setSurveyId(surveyId); apmh.setSurveyInstanceId(qas.getSurveyInstanceId()); apmh.setQuestionId(Long.parseLong(qas.getQuestionID())); apmh.addAccessPointType(type); try { AccessPoint ap = apMap.get(type); if (ap == null) { ap = new AccessPoint(); ap.setPointType(AccessPointType.valueOf(type)); // if(AccessPointType.PUBLIC_INSTITUTION.toString().equals(type)){ // //get the pointType value from the survey to // properly set it apMap.put(type, ap); } ap.setCollectionDate(qas.getCollectionDate()); setAccessPointField(ap, qas, mapping, apmh); } catch (NoSuchFieldException e) { logger.log( Level.SEVERE, "Could not map field to access point: " + mapping.getAttributeName() + ". Check the surveyAttribueMapping for surveyId " + surveyId); } catch (IllegalAccessException e) { logger.log(Level.SEVERE, "Could not set field to access point: " + mapping.getAttributeName() + ". Illegal access."); } for (Question q : questionList) { if (q.getKey().getId() == Long.parseLong(qas .getQuestionID())) { apmh.setQuestionText(q.getText()); break; } } apmhList.add(apmh); } } // if (apmhList.size() > 0) { // BaseDAO<AccessPointMappingHistory> apmhDao = new // BaseDAO<AccessPointMappingHistory>( // AccessPointMappingHistory.class); // apmhDao.save(apmhList); } } return apMap.values(); } public static void setAccessPointField(AccessPoint ap, QuestionAnswerStore qas, SurveyAttributeMapping mapping, AccessPointMappingHistory apmh) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { apmh.setResponseAnswerType(qas.getType()); QuestionDao qDao = new QuestionDao(); ap.setSurveyId(qas.getSurveyId()); ap.setSurveyInstanceId(qas.getSurveyInstanceId()); Question q = qDao.getByKey(Long.parseLong(qas.getQuestionID())); if (!qas.getType().equals(q.getType().toString())) { qas.setType(q.getType().toString()); logger.log(Level.INFO, "Remapping question type value because QAS version is incorrect"); } // FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME, // STRENGTH if (GEO_TYPE.equals(q.getType().toString())) { GeoCoordinates geoC = GeoCoordinates.extractGeoCoordinate(qas .getValue()); if (geoC != null) { ap.setLatitude(geoC.getLatitude()); ap.setLongitude(geoC.getLongitude()); ap.setAltitude(geoC.getAltitude()); if (ap.getCommunityCode() == null && geoC.getCode() != null) { ap.setCommunityCode(geoC.getCode()); } apmh.setSurveyResponse(geoC.getLatitude() + "|" + geoC.getLongitude() + "|" + geoC.getAltitude()); apmh.setQuestionAnswerType("GEO"); apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude() + "|" + ap.getAltitude()); apmh.setAccessPointField("Latitude,Longitude,Altitude"); } } else { apmh.setSurveyResponse(qas.getValue()); // if it's a value or OTHER type Field f = ap.getClass() .getDeclaredField(mapping.getAttributeName()); if (!f.isAccessible()) { f.setAccessible(true); } apmh.setAccessPointField(f.getName()); // TODO: Hack. In the QAS the type is PHOTO, but we were looking for // image this is why we were getting /sdcard I think. if (PHOTO_TYPE.equals(q.getType().toString()) || qas.getType().equals("PHOTO")) { String newURL = null; String[] photoParts = qas.getValue().split("/"); if (photoParts.length > 1) { if (qas.getValue().startsWith("/sdcard")) { newURL = photo_url_root + photoParts[2]; } else if (qas.getValue().startsWith("/mnt")) { newURL = photo_url_root + photoParts[3]; }else{ //otherwise, take the last token and concatenate with the photo_url_root newURL = photo_url_root + photoParts[photoParts.length-1]; } } else if (photoParts.length == 1) { // handle the case where we only have the filename (no // paths) newURL = photo_url_root + photoParts[0]; } f.set(ap, newURL); apmh.setQuestionAnswerType("PHOTO"); apmh.setAccessPointValue(ap.getPhotoURL()); } else if (mapping.getAttributeName().equals("pointType")) { if (qas.getValue().contains("Health")) { f.set(ap, AccessPointType.HEALTH_POSTS); } else { qas.setValue(qas.getValue().replace(" ", "_")); f.set(ap, AccessPointType.valueOf(qas.getValue() .toUpperCase())); } } else { String stringVal = qas.getValue(); if (stringVal != null && stringVal.trim().length() > 0) { if (f.getType() == String.class) { f.set(ap, qas.getValue()); apmh.setQuestionAnswerType("String"); apmh.setAccessPointValue(f.get(ap).toString()); } else if (f.getType() == AccessPoint.Status.class) { String val = qas.getValue(); f.set(ap, encodeStatus(val, ap.getPointType())); apmh.setQuestionAnswerType("STATUS"); apmh.setAccessPointValue(f.get(ap).toString()); } else if (f.getType() == Double.class) { try { Double val = Double.parseDouble(stringVal.trim()); f.set(ap, val); apmh.setQuestionAnswerType("DOUBLE"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as double", e); apmh.setMappingMessage("Could not parse " + stringVal + " as double"); } } else if (f.getType() == Long.class) { try { String temp = stringVal.trim(); if (temp.contains(".")) { temp = temp.substring(0, temp.indexOf(".")); } Long val = Long.parseLong(temp); f.set(ap, val); logger.info("Setting " + f.getName() + " to " + val + " for ap: " + (ap.getKey() != null ? ap.getKey() .getId() : "UNSET")); apmh.setQuestionAnswerType("LONG"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as long", e); apmh.setMappingMessage("Could not parse " + stringVal + " as long"); } } else if (f.getType() == Boolean.class) { try { Boolean val = null; if (stringVal.toLowerCase().contains("yes")) { val = true; } else if (stringVal.toLowerCase().contains("no")) { val = false; } else { if (stringVal == null || stringVal.equals("")) { val = null; } val = Boolean.parseBoolean(stringVal.trim()); } f.set(ap, val); apmh.setQuestionAnswerType("BOOLEAN"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as boolean", e); apmh.setMappingMessage("Could not parse " + stringVal + " as boolean"); } } } } } } /** * reads value of field from AccessPoint via reflection * * @param ap * @param field * @return */ public static String getAccessPointFieldAsString(AccessPoint ap, String field) { try { Field f = ap.getClass().getDeclaredField(field); if (!f.isAccessible()) { f.setAccessible(true); } Object val = f.get(ap); if (val != null) { return val.toString(); } } catch (Exception e) { logger.log(Level.SEVERE, "Could not extract field value: " + field, e); } return null; } private SurveyAttributeMapping getMappingForQuestion( List<SurveyAttributeMapping> mappings, String questionId) { if (mappings != null) { for (SurveyAttributeMapping mapping : mappings) { if (mapping.getSurveyQuestionId().equals(questionId)) { return mapping; } } } return null; } /** * generates a unique code based on the lat/lon passed in. Current algorithm * returns the concatenation of the integer portion of 1000 times absolute * * value of lat and lon in base 36 * * @param lat * @param lon * @return */ private String generateCode(double lat, double lon) { Long code = Long.parseLong((int) ((Math.abs(lat) * 10000d)) + "" + (int) ((Math.abs(lon) * 10000d))); return Long.toString(code, 36); } /** * saves an access point and fires off a summarization message * * @param ap * @return */ public AccessPoint saveAccessPoint(AccessPoint ap) { AccessPointDao apDao = new AccessPointDao(); AccessPoint apCurrent = null; if (ap != null) { if (ap.getPointType() != null && ap.getLatitude() != null && ap.getLongitude() != null) { apCurrent = apDao.findAccessPoint(ap.getPointType(), ap.getLatitude(), ap.getLongitude(), ap.getCollectionDate()); if (apCurrent != null) { // if (!apCurrent.getKey().equals(ap.getKey())) { ap.setKey(apCurrent.getKey()); } if (ap.getAccessPointCode() == null) { ap.setAccessPointCode(generateCode(ap.getLatitude(), ap.getLongitude())); logger.log( Level.INFO, "No APCode set in ap so setting to: " + ap.getAccessPointCode()); } if (ap.getCommunityCode() == null) { if (ap.getAccessPointCode() != null) ap.setCommunityCode(ap.getAccessPointCode()); logger.log( Level.INFO, "No Community Code set in ap so setting to: " + ap.getAccessPointCode()); } if (ap.getKey() != null) { String oldValues = null; if (ap != null && ap.getKey() != null && apCurrent == null) { apCurrent = apDao.getByKey(ap.getKey()); } if (apCurrent != null) { oldValues = formChangeRecordString(apCurrent); if (apCurrent != null) { ap.setKey(apCurrent.getKey()); apCurrent = ap; logger.log(Level.INFO, "Found existing point and updating it." + apCurrent.getKey().getId()); } // TODO: Hack since the fileUrl keeps getting set to // incorrect value // Changing from apCurrent to ap ap = apDao.save(ap); String newValues = formChangeRecordString(ap); if (oldValues != null) { DataChangeRecord change = new DataChangeRecord( AccessPointStatusSummary.class.getName(), "n/a", oldValues, newValues); Queue queue = QueueFactory.getQueue("dataUpdate"); queue.add(url("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, ap.getKey().getId() + "") .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointSummaryChange") .param(DataSummarizationRequest.VALUE_KEY, change.packString())); } } } else { logger.log(Level.INFO, "Did not find existing point" + ap.toString()); if (ap.getGeocells() == null || ap.getGeocells().size() == 0) { if (ap.getLatitude() != null && ap.getLongitude() != null && ap.getLongitude() < 180 && ap.getLatitude() < 180) { try { ap.setGeocells(GeocellManager .generateGeoCell(new Point(ap .getLatitude(), ap .getLongitude()))); } catch (Exception ex) { logger.log(Level.INFO, "Could not generate GeoCell for AP: " + ap.getKey().getId() + " error: " + ex); } } } try { ap = apDao.save(ap); } catch (Exception ex) { logger.log(Level.INFO, "Could not save point"); } if (ap.getKey() != null) { Queue summQueue = QueueFactory .getQueue("dataSummarization"); summQueue.add(url("/app_worker/datasummarization") .param("objectKey", ap.getKey().getId() + "") .param("type", "AccessPoint")); } else { logger.log( Level.SEVERE, "After saving could not get key" + ap.toString()); } } } } if (ap != null) { // ap = this.scoreAccessPointDynamic(ap); return ap; } else return null; } private String formChangeRecordString(AccessPoint ap) { String changeString = null; if (ap != null) { changeString = (ap.getCountryCode() != null ? ap.getCountryCode() : "") + "|" + (ap.getCommunityCode() != null ? ap.getCommunityCode() : "") + "|" + (ap.getPointType() != null ? ap.getPointType().toString() : "") + "|" + (ap.getPointStatus() != null ? ap.getPointStatus() .toString() : "") + "|" + StringUtil.getYearString(ap.getCollectionDate()); } return changeString; } public List<AccessPoint> listAccessPoint(String cursorString) { AccessPointDao apDao = new AccessPointDao(); return apDao.list(cursorString); } public static AccessPoint.Status encodeStatus(String statusVal, AccessPoint.AccessPointType pointType) { AccessPoint.Status status = null; statusVal = statusVal.toLowerCase().trim(); if (pointType.equals(AccessPointType.WATER_POINT)) { if ("functioning but with problems".equals(statusVal) || "working but with problems".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } else if ("broken down system".equals(statusVal) || "broken down".equals(statusVal) || statusVal.contains("broken")) { status = AccessPoint.Status.BROKEN_DOWN; } else if ("no improved system".equals(statusVal) || "not a protected waterpoint".equals(statusVal)) { status = AccessPoint.Status.NO_IMPROVED_SYSTEM; } else if ("functioning and meets government standards" .equals(statusVal) || "working and protected".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("high".equalsIgnoreCase(statusVal) || "functioning".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("ok".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_OK; } else { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } } else if (pointType.equals(AccessPointType.SANITATION_POINT)) { if ("latrine full".equals(statusVal)) status = AccessPoint.Status.LATRINE_FULL; else if ("Latrine used but technical problems evident" .toLowerCase().trim().equals(statusVal)) status = AccessPoint.Status.LATRINE_USED_TECH_PROBLEMS; else if ("Latrine not being used due to structural/technical problems" .toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_NOT_USED_TECH_STRUCT_PROBLEMS; else if ("Do not Know".toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_DO_NOT_KNOW; else if ("Functional".toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_FUNCTIONAL; } else { if ("functioning but with problems".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } else if ("broken down system".equals(statusVal)) { status = AccessPoint.Status.BROKEN_DOWN; } else if ("no improved system".equals(statusVal)) status = AccessPoint.Status.NO_IMPROVED_SYSTEM; else if ("functioning and meets government standards" .equals(statusVal)) status = AccessPoint.Status.FUNCTIONING_HIGH; else if ("high".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("ok".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_OK; } else { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } } return status; } private void copyNonKeyValues(AccessPoint source, AccessPoint target) { if (source != null && target != null) { Field[] fields = AccessPoint.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { if (isCopyable(fields[i].getName())) { fields[i].setAccessible(true); fields[i].set(target, fields[i].get(source)); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't set the field: " + fields[i].getName()); } } } } private boolean isCopyable(String name) { if ("key".equals(name)) { return false; } else if ("serialVersionUID".equals(name)) { return false; } else if ("jdoFieldFlags".equals(name)) { return false; } else if ("jdoPersistenceCapableSuperclass".equals(name)) { return false; } else if ("jdoFieldTypes".equals(name)) { return false; } else if ("jdoFieldNames".equals(name)) { return false; } else if ("jdoInheritedFieldCount".equals(name)) { return false; } return true; } public AccessPoint setGeoDetails(AccessPoint point) { if (point.getLatitude() != null && point.getLongitude() != null) { GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl(); GeoPlace geoPlace = gs.manualLookup(point.getLatitude().toString(), point.getLongitude().toString(), OGRFeature.FeatureType.SUB_COUNTRY_OTHER); if (geoPlace != null) { point.setCountryCode(geoPlace.getCountryCode()); point.setSub1(geoPlace.getSub1()); point.setSub2(geoPlace.getSub2()); point.setSub3(geoPlace.getSub3()); point.setSub4(geoPlace.getSub4()); point.setSub5(geoPlace.getSub5()); point.setSub6(geoPlace.getSub6()); } else if (geoPlace == null && point.getCountryCode() == null) { GeoPlace geoPlaceCountry = gs.manualLookup(point.getLatitude() .toString(), point.getLongitude().toString(), OGRFeature.FeatureType.COUNTRY); if (geoPlaceCountry != null) { point.setCountryCode(geoPlaceCountry.getCountryCode()); } } } return point; } public AccessPoint scoreAccessPointDynamic(AccessPoint ap) { AccessPointScoreDetail apss = new AccessPointScoreDetail(); HashMap<Long, Integer> scoreBucketMap = new HashMap<Long, Integer>(); logger.log(Level.INFO, "About to compute score for: " + ap.getCommunityCode()); StandardScoringDao ssDao = new StandardScoringDao(); List<StandardScoring> ssList = ssDao.listStandardScoring(ap); ArrayList<AccessPointScoreComputationItem> apsciList = new ArrayList<AccessPointScoreComputationItem>(); if (ssList != null && !ssList.isEmpty()) { Integer score = 0; for (StandardScoring item : ssList) { if (scoreBucketMap.containsKey(item.getScoreBucketId())) { score = scoreBucketMap.get(item.getScoreBucketId()); } else { scoreBucketMap.put(item.getScoreBucketId(), 0); } try { AccessPointScoreComputationItem apsi = executeItemScore(ap, score, item); score = apsi.getScoreItem(); apsciList.add(apsi); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } scoreBucketMap.put(item.getScoreBucketId(), score); } for (Entry<Long, Integer> item : scoreBucketMap.entrySet()) { String scoreBucketName = null; for (StandardScoring ssitem : ssList) { if (ssitem.getScoreBucketId().equals(item.getKey())) { scoreBucketName = ssitem.getScoreBucket(); } } apss.setScoreBucketId(item.getKey()); apss.setScoreBucket(scoreBucketName); apss.setScore(item.getValue()); apss.setScoreComputationItems(apsciList); ap.setScore(score); ap.setScoreComputationDate(new Date()); apss.setComputationDate(ap.getScoreComputationDate()); ap.setApScoreDetail(apss); } } return ap; } private AccessPointScoreComputationItem executeItemScore(AccessPoint ap, Integer score, StandardScoring item) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String criteriaType = item.getCriteriaType(); String scoreItemMessage = null; if (item.getCriteriaType().equals("Distance")) { if (ap.getNumberOutsideAcceptableDistance() != null && ap.getNumberOutsideAcceptableDistance() == 0) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } else { scoreItemMessage = item.getNegativeMessage(); } } else { item.setEvaluateField(StringUtil .capitalizeFirstCharacterString(item.getEvaluateField())); if (criteriaType.equals("String")) { Method m = AccessPoint.class.getMethod( "get" + item.getEvaluateField(), null); String value = (String) m.invoke(ap, null); if (item.getPositiveOperator().equals("==")) { if (item.getPositiveCriteria().equals(value)) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals("!=")) { if (!item.getPositiveCriteria().equals(value)) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getNegativeOperator().equals("==")) { if (item.getNegativeCriteria().equals(value)) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals("!=")) { if (!item.getNegativeCriteria().equals(value)) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } } else if (criteriaType.equals("Boolean")) { Method m = AccessPoint.class.getMethod( "get" + item.getEvaluateField(), null); Boolean value = null; String type = m.getReturnType().toString(); if (type.equals("class java.lang.Boolean")) { value = Boolean.parseBoolean(m.invoke(ap, null).toString()); if (item.getPositiveOperator().equals("==")) { if (Boolean.parseBoolean(item.getPositiveCriteria()) == value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals("!=")) { if (Boolean.parseBoolean(item.getPositiveCriteria()) != value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } if (item.getNegativeOperator() != null && item.getNegativeOperator().equals("==")) { if (Boolean.parseBoolean(item.getNegativeCriteria()) == value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator() != null && item.getNegativeOperator().equals("!=")) { if (Boolean.parseBoolean(item.getNegativeCriteria()) != value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } } } else if (criteriaType.equals("Integer") || criteriaType.equals("Number")) { Method m = AccessPoint.class.getMethod( "get" + item.getEvaluateField(), null); Float value = null; String type = m.getReturnType().toString(); if (m.getReturnType().toString().equals("class java.lang.Long")) value = Float.parseFloat(((Long) m.invoke(ap, null)) .toString()); else if (m.getReturnType().toString() .equals("class java.lang.Integer")) value = Float.parseFloat(((Integer) m.invoke(ap, null)) .toString()); else if (m.getReturnType().toString() .equals("class java.lang.Double")) value = Float.parseFloat(((Double) m.invoke(ap, null)) .toString()); if (item.getPositiveOperator().equals("<=")) { if (Integer.parseInt(item.getPositiveCriteria()) <= value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals("<")) { if (Integer.parseInt(item.getPositiveCriteria()) < value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals("==")) { if (Integer.parseInt(item.getPositiveCriteria()) == value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals("!=")) { if (Integer.parseInt(item.getPositiveCriteria()) != value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals(">=")) { if (Integer.parseInt(item.getPositiveCriteria()) >= value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getPositiveOperator().equals(">")) { if (Integer.parseInt(item.getPositiveCriteria()) > value) { score = score + item.getPositiveScore(); scoreItemMessage = item.getPositiveMessage(); } } else if (item.getNegativeOperator().equals("<=")) { if (Integer.parseInt(item.getNegativeCriteria()) <= value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals("<")) { if (Integer.parseInt(item.getNegativeCriteria()) < value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals("==")) { if (Integer.parseInt(item.getNegativeCriteria()) == value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals("!=")) { if (Integer.parseInt(item.getNegativeCriteria()) != value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals(">=")) { if (Integer.parseInt(item.getNegativeCriteria()) >= value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } else if (item.getNegativeOperator().equals(">")) { if (Integer.parseInt(item.getNegativeCriteria()) > value) { score = score + item.getNegativeScore(); scoreItemMessage = item.getNegativeMessage(); } } } } return new AccessPointScoreComputationItem(score, scoreItemMessage); } public static AccessPoint scoreAccessPoint(AccessPoint ap) { // Is there an improved water system no=0, yes=1 // Provide enough drinking water for community everyday of year no=0, // yes=1, don't know=0, // Water system been down in 30 days: No=1,yes=0 // Are there current problems: no=1,yes=0 // meet govt quantity standards:no=0,yes=1 // Is there a tarriff or fee no=0,yes=1 AccessPointScoreDetail apss = new AccessPointScoreDetail(); logger.log(Level.INFO, "About to compute score for: " + ap.getCommunityCode()); Integer score = 0; // added other conditions to guess if it's an improved point or not // since the scoring seems like it's flawed if ((ap.isImprovedWaterPointFlag() != null && ap .isImprovedWaterPointFlag()) || (ap.getConstructionDateYear() != null && !ap .getConstructionDateYear().trim() .equalsIgnoreCase("na")) || (ap.getConstructionDateYear() != null && !ap .getConstructionDateYear().trim() .equalsIgnoreCase("n/a"))) { score++; apss.addScoreComputationItem(1, "Plus 1 for Improved Water System = true: "); if (ap.getProvideAdequateQuantity() != null && ap.getProvideAdequateQuantity().equals(true)) { score++; apss.addScoreComputationItem(1, "Plus 1 for Provide Adequate Quantity = true: "); } else { apss.addScoreComputationItem(1, "Plus 0 for Provide Adequate Quantity = false or null: "); } if (ap.getHasSystemBeenDown1DayFlag() != null && !ap.getHasSystemBeenDown1DayFlag().equals(true)) { score++; apss.addScoreComputationItem(1, "Plus 1 for Has System Been Down 1 Day Flag = false: "); } else { apss.addScoreComputationItem(1, "Plus 0 for Has System Been Down 1 Day Flag = true or null: "); } if (ap.getCurrentProblem() == null) { score++; apss.addScoreComputationItem(1, "Plus 1 for Get Current Problem = null"); } else { apss.addScoreComputationItem( 1, "Plus 0 for Get Current Problem != null value: " + ap.getCurrentProblem()); } if (ap.isCollectTariffFlag() != null && ap.isCollectTariffFlag()) { score++; apss.addScoreComputationItem(1, "Plus 1 for Collect Tariff Flag = true "); } else { apss.addScoreComputationItem(1, "Plus 0 for Collect Tariff Flag = false or null: "); } } else { apss.addScoreComputationItem(1, "Plus 0 for Improved Water System = false or null: "); } apss.setScore(score); ap.setScore(score); ap.setScoreComputationDate(new Date()); apss.setComputationDate(ap.getScoreComputationDate()); logger.log(Level.INFO, "AP Collected in 2011 so scoring: " + ap.getCommunityCode() + "/" + ap.getCollectionDate() + " score: " + score); if (score == 0) { ap.setPointStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM); apss.setStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM.toString()); } else if (score >= 1 && score <= 2) { ap.setPointStatus(AccessPoint.Status.BROKEN_DOWN); apss.setStatus(AccessPoint.Status.BROKEN_DOWN.toString()); } else if (score >= 3 && score <= 4) { ap.setPointStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS); apss.setStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS .toString()); } else if (score >= 5) { ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); apss.setStatus(AccessPoint.Status.FUNCTIONING_HIGH.toString()); } else { ap.setPointStatus(AccessPoint.Status.OTHER); apss.setStatus(AccessPoint.Status.OTHER.toString()); } ap.setApScoreDetail(apss); return ap; } public void computeDistanceRule(AccessPoint ap) { AccessPointDao apDao = new AccessPointDao(); Integer targetDistance = null; if (ap != null) { StandardScoringDao ssDao = new StandardScoringDao(); List<StandardScoring> ssList = ssDao .listLocalDistanceStandardScoringForAccessPoint(ap); if (ssList != null && !ssList.isEmpty()) { StandardScoring ssItem = ssList.get(0); if (ssItem != null && ssItem.getPositiveCriteria() != null) targetDistance = Integer.parseInt(ssItem .getPositiveCriteria()); } if (ap.getTypeTechnologyString().equals( "Gravity Fed System with Household Taps")) { // ToDo: check against tech type of HH, but need to know which // question ap.setNumberWithinAcceptableDistance(ap .getNumberWithinAcceptableDistance() + 1); } else if (ap.getPointType().equals( AccessPoint.AccessPointType.WATER_POINT) && (ap.getCommunityCode() != null)) { List<AccessPoint> apList = apDao.listAccessPointByLocation( ap.getCountryCode(), ap.getCommunityCode(), AccessPointType.HOUSEHOLD.toString(), null, "all"); if (apList != null && !apList.isEmpty()) { for (AccessPoint hh : apList) { Double distance = CoordinateUtilities.computeDistance( ap, hh); if (distance != null && distance < 500) { ap.setNumberWithinAcceptableDistance(ap .getNumberWithinAcceptableDistance() + 1); } else { ap.setNumberOutsideAcceptableDistance(ap .getNumberOutsideAcceptableDistance() + 1); } } apDao.save(ap); } } else if (ap.getPointType().equals(AccessPointType.HOUSEHOLD) && ap.getCommunityCode() != null) { List<AccessPoint> apList = apDao.listAccessPointByLocation( ap.getCountryCode(), ap.getCommunityCode(), AccessPointType.WATER_POINT.toString(), null, "all"); AccessPoint minDistanceWaterPoint = null; Double minDistance = null; for (AccessPoint wp : apList) { Double distance = CoordinateUtilities.computeDistance(ap, wp); if (distance < minDistance || minDistance == null) { minDistance = CoordinateUtilities.computeDistance(ap, wp); minDistanceWaterPoint = wp; } } if (minDistance != null && minDistance < 500) { minDistanceWaterPoint .setNumberWithinAcceptableDistance(minDistanceWaterPoint .getNumberWithinAcceptableDistance() + 1); } else { minDistanceWaterPoint .setNumberOutsideAcceptableDistance(minDistanceWaterPoint .getNumberOutsideAcceptableDistance()); } apDao.save(minDistanceWaterPoint); } } } }
package info.justaway.adapter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.greenrobot.event.EventBus; import info.justaway.BuildConfig; import info.justaway.JustawayApplication; import info.justaway.MainActivity; import info.justaway.ProfileActivity; import info.justaway.R; import info.justaway.ScaleImageActivity; import info.justaway.event.AlertDialogEvent; import info.justaway.event.GoToTopEvent; import info.justaway.model.Row; import twitter4j.DirectMessage; import twitter4j.MediaEntity; import twitter4j.Status; import twitter4j.URLEntity; import twitter4j.User; public class TwitterAdapter extends ArrayAdapter<Row> { static class ViewHolder { LinearLayout action; TextView action_icon; TextView action_by_display_name; TextView action_by_screen_name; ImageView icon; TextView display_name; TextView screen_name; TextView fontello_lock; TextView datetime_relative; TextView status; LinearLayout images; TableLayout menu_and_via; TextView do_reply; TextView do_retweet; TextView retweet_count; TextView do_fav; TextView fav_count; TextView via; TextView datetime; LinearLayout retweet; ImageView retweet_icon; TextView retweet_by; } private JustawayApplication mApplication; private Context mContext; private ArrayList<Row> mStatuses = new ArrayList<Row>(); private LayoutInflater mInflater; private int mLayout; private int mColorBlue = 0; private Boolean isMain; private static final int LIMIT = 100; private int mLimit = LIMIT; private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM'/'dd' 'HH':'mm':'ss", Locale.ENGLISH); public TwitterAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mContext = context; this.mLayout = textViewResourceId; this.mApplication = JustawayApplication.getApplication(); this.isMain = mContext instanceof MainActivity; } public void extensionAdd(Row row) { if (JustawayApplication.isMute(row)) { return; } super.add(row); this.filter(row); this.mStatuses.add(row); mLimit++; } @Override public void add(Row row) { if (JustawayApplication.isMute(row)) { return; } super.add(row); this.filter(row); this.mStatuses.add(row); this.limitation(); } @Override public void insert(Row row, int index) { if (JustawayApplication.isMute(row)) { return; } super.insert(row, index); this.filter(row); this.mStatuses.add(index, row); this.limitation(); } @Override public void remove(Row row) { super.remove(row); this.mStatuses.remove(row); } private void filter(Row row) { Status status = row.getStatus(); if (status != null && status.isRetweeted()) { Status retweet = status.getRetweetedStatus(); if (retweet != null && status.getUser().getId() == mApplication.getUserId()) { mApplication.setRtId(retweet.getId(), status.getId()); } } } @SuppressWarnings("unused") public void replaceStatus(Status status) { for (Row row : mStatuses) { if (!row.isDirectMessage() && row.getStatus().getId() == status.getId()) { row.setStatus(status); notifyDataSetChanged(); break; } } } public void removeStatus(long statusId) { for (Row row : mStatuses) { if (!row.isDirectMessage() && row.getStatus().getId() == statusId) { remove(row); break; } } } public void removeDirectMessage(long directMessageId) { for (Row row : mStatuses) { if (row.isDirectMessage() && row.getMessage().getId() == directMessageId) { remove(row); break; } } } public void limitation() { int size = this.mStatuses.size(); if (size > mLimit) { int count = size - mLimit; for (int i = 0; i < count; i++) { super.remove(this.mStatuses.remove(size - i - 1)); } } } @Override public void clear() { super.clear(); this.mStatuses.clear(); mLimit = LIMIT; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View view = convertView; if (view == null) { // null view = mInflater.inflate(this.mLayout, null); if (view == null) { return null; } holder = new ViewHolder(); holder.action = (LinearLayout) view.findViewById(R.id.action); holder.action_icon = (TextView) view.findViewById(R.id.action_icon); holder.action_by_display_name = (TextView) view.findViewById(R.id.action_by_display_name); holder.action_by_screen_name = (TextView) view.findViewById(R.id.action_by_screen_name); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.display_name = (TextView) view.findViewById(R.id.display_name); holder.screen_name = (TextView) view.findViewById(R.id.screen_name); holder.fontello_lock = (TextView) view.findViewById(R.id.fontello_lock); holder.datetime_relative = (TextView) view.findViewById(R.id.datetime_relative); holder.status = (TextView) view.findViewById(R.id.status); holder.status.setTag(12); holder.images = (LinearLayout) view.findViewById(R.id.images); holder.menu_and_via = (TableLayout) view.findViewById(R.id.menu_and_via); holder.do_reply = (TextView) view.findViewById(R.id.do_reply); holder.do_retweet = (TextView) view.findViewById(R.id.do_retweet); holder.retweet_count = (TextView) view.findViewById(R.id.retweet_count); holder.do_fav = (TextView) view.findViewById(R.id.do_fav); holder.fav_count = (TextView) view.findViewById(R.id.fav_count); holder.via = (TextView) view.findViewById(R.id.via); holder.datetime = (TextView) view.findViewById(R.id.datetime); holder.retweet = (LinearLayout) view.findViewById(R.id.retweet); holder.retweet_icon = (ImageView) view.findViewById(R.id.retweet_icon); holder.retweet_by = (TextView) view.findViewById(R.id.retweet_by); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } if (mApplication.getFontSize() != (Integer) holder.status.getTag()) { holder.status.setTag(mApplication.getFontSize()); holder.status.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize()); holder.display_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize()); holder.screen_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize() - 2); holder.datetime_relative.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize() - 2); } Row row = mStatuses.get(position); if (row.isDirectMessage()) { DirectMessage message = row.getMessage(); if (message == null) { return view; } renderMessage(holder, message); } else { Status status = row.getStatus(); if (status == null) { return view; } Status retweet = status.getRetweetedStatus(); if (row.isFavorite()) { renderStatus(holder, status, null, row.getSource()); } else if (retweet == null) { renderStatus(holder, status, null, null); } else { renderStatus(holder, retweet, status, null); } } if (isMain && position == 0) { EventBus.getDefault().post(new GoToTopEvent()); } return view; } private void renderMessage(ViewHolder holder, final DirectMessage message) { Typeface fontello = JustawayApplication.getFontello(); long userId = JustawayApplication.getApplication().getUserId(); holder.do_retweet.setVisibility(View.GONE); holder.do_fav.setVisibility(View.GONE); holder.retweet_count.setVisibility(View.GONE); holder.fav_count.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); if (message.getSender().getId() == userId) { holder.do_reply.setVisibility(View.GONE); } else { holder.do_reply.setVisibility(View.VISIBLE); holder.do_reply.setTypeface(fontello); holder.do_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mApplication.doReplyDirectMessage(message, mContext); } }); } holder.display_name.setText(message.getSender().getName()); holder.screen_name.setText("@" + message.getSender().getScreenName()); holder.status.setText("D " + message.getRecipientScreenName() + " " + message.getText()); holder.datetime .setText(getAbsoluteTime(message.getCreatedAt())); holder.datetime_relative.setText(getRelativeTime(message.getCreatedAt())); holder.via.setVisibility(View.GONE); holder.retweet.setVisibility(View.GONE); holder.images.setVisibility(View.GONE); mApplication.displayUserIcon(message.getSender(), holder.icon); holder.icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ProfileActivity.class); intent.putExtra("screenName", message.getSender().getScreenName()); mContext.startActivity(intent); } }); holder.action.setVisibility(View.GONE); holder.fontello_lock.setVisibility(View.INVISIBLE); } private void renderStatus(final ViewHolder holder, final Status status, Status retweet, User favorite) { long userId = JustawayApplication.getApplication().getUserId(); Typeface fontello = JustawayApplication.getFontello(); if (status.getFavoriteCount() > 0) { holder.fav_count.setText(String.valueOf(status.getFavoriteCount())); holder.fav_count.setVisibility(View.VISIBLE); } else { holder.fav_count.setText("0"); holder.fav_count.setVisibility(View.INVISIBLE); } if (status.getRetweetCount() > 0) { holder.retweet_count.setText(String.valueOf(status.getRetweetCount())); holder.retweet_count.setVisibility(View.VISIBLE); } else { holder.retweet_count.setText("0"); holder.retweet_count.setVisibility(View.INVISIBLE); } holder.do_reply.setTypeface(fontello); holder.do_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mApplication.doReplyAll(status, mContext); } }); holder.do_retweet.setTypeface(fontello); holder.do_retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (status.getUser().isProtected()) { JustawayApplication.showToast(R.string.toast_protected_tweet_can_not_share); return; } Long id = mApplication.getRtId(status); if (id != null) { if (id == 0) { JustawayApplication.showToast(R.string.toast_destroy_retweet_progress); } else { DialogFragment dialog = new DestroyRetweetDialogFragment(); Bundle args = new Bundle(1); args.putSerializable("status", status); dialog.setArguments(args); EventBus.getDefault().post(new AlertDialogEvent(dialog)); } } else { DialogFragment dialog = new RetweetDialogFragment(); Bundle args = new Bundle(1); args.putSerializable("status", status); dialog.setArguments(args); EventBus.getDefault().post(new AlertDialogEvent(dialog)); } } }); holder.do_fav.setTypeface(fontello); holder.do_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (holder.do_fav.getTag().equals("is_fav")) { holder.do_fav.setTag("no_fav"); holder.do_fav.setTextColor(Color.parseColor("#666666")); mApplication.doDestroyFavorite(status.getId()); } else { holder.do_fav.setTag("is_fav"); holder.do_fav.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); mApplication.doFavorite(status.getId()); } } }); if (mApplication.getRtId(status) != null) { holder.do_retweet.setTextColor(mContext.getResources().getColor(R.color.holo_green_light)); } else { holder.do_retweet.setTextColor(Color.parseColor("#666666")); } if (mApplication.isFav(status)) { holder.do_fav.setTag("is_fav"); holder.do_fav.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); } else { holder.do_fav.setTag("no_fav"); holder.do_fav.setTextColor(Color.parseColor("#666666")); } holder.display_name.setText(status.getUser().getName()); holder.screen_name.setText("@" + status.getUser().getScreenName()); holder.datetime_relative.setText(getRelativeTime(status.getCreatedAt())); holder.datetime.setText(getAbsoluteTime(status.getCreatedAt())); String via = mApplication.getClientName(status.getSource()); holder.via.setText("via " + via); holder.via.setVisibility(View.VISIBLE); /** * Justaway for Android */ if (BuildConfig.DEBUG) { if (via.equals("Justaway for Android")) { if (mColorBlue == 0) { mColorBlue = mApplication.getThemeTextColor((Activity) mContext, R.attr.holo_blue); } holder.via.setTextColor(mColorBlue); } else { holder.via.setTextColor(Color.parseColor("#666666")); } } holder.action_icon.setTypeface(fontello); // fav if (favorite != null) { holder.action_icon.setText(R.string.fontello_star); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); holder.action_by_display_name.setText(favorite.getName()); holder.action_by_screen_name.setText("@" + favorite.getScreenName()); holder.retweet.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.action.setVisibility(View.VISIBLE); } else if (retweet != null) { if (userId == status.getUser().getId()) { holder.action_icon.setText(R.string.fontello_retweet); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_green_light)); holder.action_by_display_name.setText(retweet.getUser().getName()); holder.action_by_screen_name.setText("@" + retweet.getUser().getScreenName()); holder.retweet.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.action.setVisibility(View.VISIBLE); } else { mApplication.displayRoundedImage(retweet.getUser().getProfileImageURL(), holder.retweet_icon); holder.retweet_by.setText("RT by " + retweet.getUser().getName() + " @" + retweet.getUser().getScreenName()); holder.action.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.retweet.setVisibility(View.VISIBLE); } } else { if (mApplication.isMentionForMe(status)) { holder.action_icon.setText(R.string.fontello_at); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_red_light)); holder.action_by_display_name.setText(status.getUser().getName()); holder.action_by_screen_name.setText("@" + status.getUser().getScreenName()); holder.action.setVisibility(View.VISIBLE); holder.retweet.setVisibility(View.GONE); } else { holder.action.setVisibility(View.GONE); holder.retweet.setVisibility(View.GONE); } holder.menu_and_via.setVisibility(View.VISIBLE); } if (status.getUser().isProtected()) { holder.fontello_lock.setTypeface(fontello); holder.fontello_lock.setVisibility(View.VISIBLE); } else { holder.fontello_lock.setVisibility(View.INVISIBLE); } mApplication.displayUserIcon(status.getUser(), holder.icon); holder.icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ProfileActivity.class); intent.putExtra("screenName", status.getUser().getScreenName()); mContext.startActivity(intent); } }); MediaEntity[] medias = retweet != null ? retweet.getMediaEntities() : status .getMediaEntities(); URLEntity[] urls = retweet != null ? retweet.getURLEntities() : status.getURLEntities(); ArrayList<String> imageUrls = new ArrayList<String>(); Pattern twitpic_pattern = Pattern.compile("^http://twitpic\\.com/(\\w+)$"); Pattern twipple_pattern = Pattern.compile("^http://p\\.twipple\\.jp/(\\w+)$"); Pattern instagram_pattern = Pattern.compile("^http://instagram\\.com/p/([^/]+)/$"); Pattern images_pattern = Pattern.compile("^https?://.*\\.(png|gif|jpeg|jpg)$"); Pattern youtube_pattern = Pattern.compile("^https?://(?:www\\.youtube\\.com/watch\\?.*v=|youtu\\.be/)([\\w-]+)"); Pattern niconico_pattern = Pattern.compile("^http://(?:www\\.nicovideo\\.jp/watch|nico\\.ms)/sm(\\d+)$"); String statusString = status.getText(); for (URLEntity url : urls) { Pattern p = Pattern.compile(url.getURL()); Matcher m = p.matcher(statusString); statusString = m.replaceAll(url.getExpandedURL()); Matcher twitpic_matcher = twitpic_pattern.matcher(url.getExpandedURL()); if (twitpic_matcher.find()) { imageUrls.add("http://twitpic.com/show/full/" + twitpic_matcher.group(1)); continue; } Matcher twipple_matcher = twipple_pattern.matcher(url.getExpandedURL()); if (twipple_matcher.find()) { imageUrls.add("http://p.twpl.jp/show/orig/" + twipple_matcher.group(1)); continue; } Matcher instagram_matcher = instagram_pattern.matcher(url.getExpandedURL()); if (instagram_matcher.find()) { imageUrls.add(url.getExpandedURL() + "media?size=l"); continue; } Matcher youtube_matcher = youtube_pattern.matcher(url.getExpandedURL()); if (youtube_matcher.find()) { imageUrls.add("http://i.ytimg.com/vi/" + youtube_matcher.group(1) + "/hqdefault.jpg"); continue; } Matcher niconico_matcher = niconico_pattern.matcher(url.getExpandedURL()); if (niconico_matcher.find()) { int id = Integer.valueOf(niconico_matcher.group(1)); int host = id % 4 + 1; imageUrls.add("http://tn-skr" + host + ".smilevideo.jp/smile?i=" + id + ".L"); continue; } Matcher images_matcher = images_pattern.matcher(url.getExpandedURL()); if (images_matcher.find()) { imageUrls.add(url.getExpandedURL()); } } holder.status.setText(statusString); for (MediaEntity media : medias) { imageUrls.add(media.getMediaURL()); } holder.images.removeAllViews(); if (imageUrls.size() > 0) { for (final String url : imageUrls) { ImageView image = new ImageView(mContext); image.setScaleType(ImageView.ScaleType.CENTER_CROP); holder.images.addView(image, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, 120)); mApplication.displayRoundedImage(url, image); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ScaleImageActivity.class); intent.putExtra("url", url); mContext.startActivity(intent); } }); } holder.images.setVisibility(View.VISIBLE); } else { holder.images.setVisibility(View.GONE); } } private String getRelativeTime(Date date) { int diff = (int) (((new Date()).getTime() - date.getTime()) / 1000); if (diff < 1) { return "now"; } else if (diff < 60) { return diff + "s"; } else if (diff < 3600) { return (diff / 60) + "m"; } else if (diff < 86400) { return (diff / 3600) + "h"; } else { return (diff / 86400) + "d"; } } private String getAbsoluteTime(Date date) { return DATE_FORMAT.format(date); } public static final class RetweetDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Status status = (Status) getArguments().getSerializable("status"); if (status == null) { return null; } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_retweet); builder.setMessage(status.getText()); builder.setNeutralButton(getString(R.string.button_quote), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { JustawayApplication.getApplication().doQuote(status, getActivity()); dismiss(); } } ); builder.setPositiveButton(getString(R.string.button_retweet), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { JustawayApplication.getApplication().doRetweet(status.getId()); dismiss(); } } ); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } } ); return builder.create(); } } public static final class DestroyRetweetDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Status status = (Status) getArguments().getSerializable("status"); if (status == null) { return null; } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_destroy_retweet); builder.setMessage(status.getText()); builder.setPositiveButton(getString(R.string.button_destroy_retweet), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { JustawayApplication.getApplication().doDestroyRetweet(status); dismiss(); } } ); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } } ); return builder.create(); } } }
package io.jxcore.node; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Handler; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.thaliproject.p2p.btconnectorlib.ConnectionManager; import org.thaliproject.p2p.btconnectorlib.ConnectionManager.ConnectionManagerState; import org.thaliproject.p2p.btconnectorlib.DiscoveryManager; import org.thaliproject.p2p.btconnectorlib.PeerProperties; import java.io.IOException; import java.util.HashMap; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; /** * Wraps the Android connector library functionality and provides an interface for JXcore layer * (with the help of JXcoreExtensions class). */ public class ConnectionHelper implements ConnectionManager.ConnectionManagerListener, DiscoveryManager.DiscoveryManagerListener { /** * A listener interface for relaying connection status change events to Node layer. * This interface only applies to outgoing connection attempts (i.e. when you call * ConnectionHelper.connect() */ public interface JxCoreExtensionListener { void onConnectionStatusChanged(String message, int port); } private static final String TAG = ConnectionHelper.class.getName(); private static final String SERVICE_TYPE = "Cordovap2p._tcp"; private static final String SERVICE_UUID_AS_STRING = "fa87c0d0-afac-11de-8a39-0800200c9a66"; private static final String BLUETOOTH_NAME = "Thali_Bluetooth"; private static final UUID SERVICE_UUID = UUID.fromString(SERVICE_UUID_AS_STRING); private static final long PEER_EXPIRATION_FOR_WIFI_PEER_DISCOVERY_IN_MILLISECONDS = 60000; private static final int MAXIMUM_NUMBER_OF_CONNECTIONS = 100; // TODO: Determine a way to figure out a proper value here private static final int PORT_NUMBER_IN_ERROR_CASES = -1; private final Context mContext; private final Thread.UncaughtExceptionHandler mThreadUncaughtExceptionHandler; private final CopyOnWriteArrayList<PeerProperties> mDiscoveredPeers = new CopyOnWriteArrayList<PeerProperties>(); private final CopyOnWriteArrayList<IncomingSocketThread> mIncomingSocketThreads = new CopyOnWriteArrayList<IncomingSocketThread>(); private final CopyOnWriteArrayList<OutgoingSocketThread> mOutgoingSocketThreads = new CopyOnWriteArrayList<OutgoingSocketThread>(); private final HashMap<String, JxCoreExtensionListener> mOutgoingConnectionListeners = new HashMap<String, JxCoreExtensionListener>(); private ConnectionManager mConnectionManager = null; private DiscoveryManager mDiscoveryManager = null; private int mServerPort = 0; /** * Constructor. */ public ConnectionHelper() { mContext = jxcore.activity.getBaseContext(); mThreadUncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, final Throwable ex) { final Throwable tempException = ex; new Handler(jxcore.activity.getMainLooper()).post(new Runnable() { @Override public void run() { Log.e(TAG, "Unhandled exception: " + ex.getMessage(), ex); throw new RuntimeException(tempException); } }); } }; } /** * Tries to start the connection manager and peer discovery. * @param peerName Our peer name. * @param port The local server port to use. * @return True, if started successfully. False otherwise. */ public synchronized boolean start(String peerName, int port) { stop(); mServerPort = port; mConnectionManager = new ConnectionManager(mContext, this, SERVICE_UUID, BLUETOOTH_NAME); mDiscoveryManager = new DiscoveryManager(mContext, this, SERVICE_TYPE); boolean connectionManagerStarted = mConnectionManager.start(peerName); boolean discoveryManagerStarted = false; if (connectionManagerStarted) { if (mDiscoveryManager.getDiscoveryMode() == DiscoveryManager.DiscoveryMode.WIFI) { mDiscoveryManager.setPeerExpiration(PEER_EXPIRATION_FOR_WIFI_PEER_DISCOVERY_IN_MILLISECONDS); } discoveryManagerStarted = mDiscoveryManager.start(peerName); if (discoveryManagerStarted) { Log.i(TAG, "start: OK"); } } if (!connectionManagerStarted || !discoveryManagerStarted) { Log.e(TAG, "start: Failed: Connection manager started: " + connectionManagerStarted + ", Discovery manager started: " + discoveryManagerStarted); stop(); } return (connectionManagerStarted && discoveryManagerStarted); } /** * Stops all activities and disconnects all active connections. */ public synchronized void stop() { if (mConnectionManager != null) { Log.i(TAG, "stop"); mConnectionManager.stop(); mConnectionManager = null; } if (mDiscoveryManager != null) { mDiscoveryManager.stop(); mDiscoveryManager = null; } closeAndRemoveAllOutgoingConnections(); closeAndRemoveAllIncomingConnections(); } public boolean isRunning() { return (mConnectionManager != null && mDiscoveryManager != null); } public boolean isBleAdvertisingSupported() { return (mDiscoveryManager != null && mDiscoveryManager.isBleAdvertisingSupported()); } /** * Disconnects the outgoing connection with the given peer ID. * @param peerId The ID of the peer to disconnect. * @return True, if the peer was found and disconnected. */ public synchronized boolean disconnectOutgoingConnection(final String peerId) { Log.d(TAG, "disconnectOutgoingConnection: Trying to close connection to peer with ID " + peerId); boolean success = closeAndRemoveOutgoingConnectionThread(peerId, false); if (success) { Log.i(TAG, "disconnectOutgoingConnection: Successfully disconnected (peer ID: " + peerId); } else { Log.w(TAG, "disconnectOutgoingConnection: Failed to disconnect (peer ID: " + peerId + "), either no such connection or failed to close the connection"); } return success; } /** * @return Our Bluetooth address or empty string, if not resolved. */ public String getBluetoothAddress() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); return bluetooth == null ? "" : bluetooth.getAddress(); } /** * Checks if we have an incoming connection with a peer matching the given peer ID. * @param peerId The peer ID. * @return True, if connected. False otherwise. */ public synchronized boolean hasIncomingConnection(final String peerId) { return (findSocketThread(peerId, true) != null); } /** * Checks if we have an outgoing connection with a peer matching the given peer ID. * @param peerId The peer ID. * @return True, if connected. False otherwise. */ public synchronized boolean hasOutgoingConnection(final String peerId) { return (findSocketThread(peerId, false) != null); } /** * Checks if we have either an incoming or outgoing connection with a peer matching the given ID. * @param peerId The peer ID. * @return True, if connected. False otherwise. */ public synchronized boolean hasConnection(final String peerId) { boolean hasIncoming = hasIncomingConnection(peerId); boolean hasOutgoing = hasOutgoingConnection(peerId); if (hasIncoming) { Log.d(TAG, "hasConnection: We have an incoming connection with peer with ID " + peerId); } if (hasOutgoing) { Log.d(TAG, "hasConnection: We have an outgoing connection with peer with ID " + peerId); } if (!hasIncoming && !hasOutgoing){ Log.d(TAG, "hasConnection: No connection with peer with ID " + peerId); } return (hasIncoming || hasOutgoing); } /** * Starts the connection process to a peer with the given ID. * @param peerIdToConnectTo The ID of the peer to connect to. * @param listener The listener. */ public synchronized void connect(final String peerIdToConnectTo, JxCoreExtensionListener listener) { Log.i(TAG, "connect: Trying to connect to peer with ID " + peerIdToConnectTo); if (listener == null) { Log.e(TAG, "connect: Listener is null"); throw new NullPointerException("Listener is null"); } if (isRunning()) { if (hasConnection(peerIdToConnectTo)) { Log.i(TAG, "connect: We already have a connection to peer with ID " + peerIdToConnectTo); } if (mOutgoingSocketThreads.size() < MAXIMUM_NUMBER_OF_CONNECTIONS) { PeerProperties selectedDevice = findDiscoveredPeer(peerIdToConnectTo); if (selectedDevice == null) { Log.w(TAG, "connect: The peer to connect to is not amongst the discovered peers, but trying anyway..."); selectedDevice = new PeerProperties( peerIdToConnectTo, peerIdToConnectTo, peerIdToConnectTo, "", "", ""); } if (BluetoothAdapter.checkBluetoothAddress(selectedDevice.getBluetoothAddress())) { if (mConnectionManager.connect(selectedDevice)) { Log.i(TAG, "connect: Connection process successfully started (peer ID: " + peerIdToConnectTo + ")"); mOutgoingConnectionListeners.put(peerIdToConnectTo, listener); } else { Log.e(TAG, "connect: Failed to start connecting"); listener.onConnectionStatusChanged("Failed to start connecting", PORT_NUMBER_IN_ERROR_CASES); } } else { Log.e(TAG, "connect: Invalid Bluetooth address: " + selectedDevice.getBluetoothAddress()); listener.onConnectionStatusChanged( "Invalid Bluetooth address: " + selectedDevice.getBluetoothAddress(), PORT_NUMBER_IN_ERROR_CASES); } } else { Log.e(TAG, "connect: Maximum number of peer connections (" + mOutgoingSocketThreads.size() + ") reached, please try again after disconnecting a peer"); listener.onConnectionStatusChanged("Maximum number of peer connections (" + mOutgoingSocketThreads.size() + ") reached, please try again after disconnecting a peer", PORT_NUMBER_IN_ERROR_CASES); } } else { Log.e(TAG, "connect: Not running, please call start() first"); listener.onConnectionStatusChanged("Not running, please call start() first", PORT_NUMBER_IN_ERROR_CASES); } } /** * Does nothing but logs the new state. * @param connectionManagerState The new state. */ @Override public void onConnectionManagerStateChanged(ConnectionManagerState connectionManagerState) { Log.i(TAG, "onConnectionManagerStateChanged: " + connectionManagerState.toString()); } /** * Takes ownership of the given Bluetooth socket, initializes the connection and adds it to the * list of incoming/outgoing connections. * @param bluetoothSocket The Bluetooth socket. * @param isIncoming True, if the connection is incoming. False, if it is outgoing. * @param peerProperties The peer properties. */ @Override public void onConnected(BluetoothSocket bluetoothSocket, boolean isIncoming, PeerProperties peerProperties) { Log.i(TAG, "onConnected: " + (isIncoming ? "Incoming" : "Outgoing") + " connection to peer " + peerProperties.toString()); if (bluetoothSocket == null) { Log.e(TAG, "onConnected: Bluetooth socket is null"); throw new RuntimeException("onConnected: Bluetooth socket is null"); } if (hasConnection(peerProperties.getId())) { Log.w(TAG, "onConnected: Already connected with peer " + peerProperties.toString() + ", continuing anyway..."); } // Add the peer to the list, if was not discovered before if (modifyListOfDiscoveredPeers(peerProperties, true)) { notifyPeerAvailability(peerProperties, true); } if (isIncoming) { IncomingSocketThread newIncomingSocketThread = null; try { newIncomingSocketThread = new IncomingSocketThread(bluetoothSocket, new ConnectionStatusListener() { @Override public void onDisconnected(SocketThreadBase who, String errorMessage) { Log.w(TAG, "onDisconnected: Incoming connection, peer " + who.getPeerProperties().toString() + " disconnected: " + errorMessage); closeAndRemoveIncomingConnectionThread(who.getId()); } }); } catch (IOException e) { Log.e(TAG, "onConnected: Failed to create an incoming connection thread instance: " + e.getMessage(), e); newIncomingSocketThread = null; } if (newIncomingSocketThread != null) { newIncomingSocketThread.setDefaultUncaughtExceptionHandler(mThreadUncaughtExceptionHandler); newIncomingSocketThread.setPeerProperties(peerProperties); newIncomingSocketThread.setHttpPort(mServerPort); mIncomingSocketThreads.add(newIncomingSocketThread); newIncomingSocketThread.start(); Log.i(TAG, "onConnected: Incoming socket thread, for peer " + peerProperties + ", created successfully"); } } else { // Is outgoing connection OutgoingSocketThread newOutgoingSocketThread = null; final String tempPeerId = peerProperties.getId(); final JxCoreExtensionListener listener = mOutgoingConnectionListeners.get(tempPeerId); try { newOutgoingSocketThread = new OutgoingSocketThread(bluetoothSocket, new ConnectionStatusListener() { @Override public void onListeningForIncomingConnections(int port) { Log.i(TAG, "onListeningForIncomingConnections: Outgoing connection is using port " + port + " (peer ID: " + tempPeerId + ")"); if (listener != null) { listener.onConnectionStatusChanged(null, port); } } @Override public void onDisconnected(SocketThreadBase who, String errorMessage) { Log.w(TAG, "onDisconnected: Outgoing connection, peer " + who.getPeerProperties().toString() + " disconnected: " + errorMessage); closeAndRemoveOutgoingConnectionThread(who.getPeerProperties().getId(), true); } }); } catch (IOException e) { Log.e(TAG, "onConnected: Failed to create an outgoing connection thread instance: " + e.getMessage(), e); newOutgoingSocketThread = null; if (listener != null) { listener.onConnectionStatusChanged("Failed to create an outgoing connection thread instance: " + e.getMessage(), PORT_NUMBER_IN_ERROR_CASES); mOutgoingConnectionListeners.remove(tempPeerId); } } if (newOutgoingSocketThread != null) { newOutgoingSocketThread.setDefaultUncaughtExceptionHandler(mThreadUncaughtExceptionHandler); newOutgoingSocketThread.setPeerProperties(peerProperties); mOutgoingSocketThreads.add(newOutgoingSocketThread); newOutgoingSocketThread.start(); Log.i(TAG, "onConnected: Outgoing socket thread, for peer " + peerProperties + ", created successfully"); } } Log.d(TAG, "onConnected: The total number of connections is now " + (mIncomingSocketThreads.size() + mOutgoingSocketThreads.size())); } /** * Forwards the connection failure to the correct listener. * @param peerProperties The peer properties. */ @Override public void onConnectionTimeout(PeerProperties peerProperties) { if (peerProperties != null) { final JxCoreExtensionListener listener = mOutgoingConnectionListeners.get(peerProperties.getId()); if (listener != null) { listener.onConnectionStatusChanged("Connection to peer " + peerProperties.toString() + " timed out", PORT_NUMBER_IN_ERROR_CASES); mOutgoingConnectionListeners.remove(peerProperties.getId()); // Dispose the listener } } } /** * Forwards the connection failure to the correct listener. * @param peerProperties The peer properties. */ @Override public void onConnectionFailed(PeerProperties peerProperties) { if (peerProperties != null) { final JxCoreExtensionListener listener = mOutgoingConnectionListeners.get(peerProperties.getId()); if (listener != null) { listener.onConnectionStatusChanged("Connection to peer " + peerProperties.toString() + " failed", PORT_NUMBER_IN_ERROR_CASES); mOutgoingConnectionListeners.remove(peerProperties.getId()); // Dispose the listener } } } /** * Does nothing but logs the new state. * @param discoveryManagerState The new state. */ @Override public void onDiscoveryManagerStateChanged(DiscoveryManager.DiscoveryManagerState discoveryManagerState) { Log.i(TAG, "onDiscoveryManagerStateChanged: " + discoveryManagerState.toString()); } /** * Called when a peer is discovered. Tries to add the peer to the list and notifies the listener. * @param peerProperties The peer properties. */ @Override public void onPeerDiscovered(PeerProperties peerProperties) { Log.i(TAG, "onPeerDiscovered: " + peerProperties.toString() + ", Bluetooth address: " + peerProperties.getBluetoothAddress() + ", device name: " + peerProperties.getDeviceName() + ", device address: " + peerProperties.getDeviceAddress()); if (modifyListOfDiscoveredPeers(peerProperties, true)) { notifyPeerAvailability(peerProperties, true); } } /** * Called when a peer is lost. Tries to remove the peer from the list and notifies the listener. * @param peerProperties The peer properties. */ @Override public void onPeerLost(PeerProperties peerProperties) { Log.i(TAG, "onPeerLost: " + peerProperties.toString()); if (modifyListOfDiscoveredPeers(peerProperties, false)) { notifyPeerAvailability(peerProperties, false); } } /** * Tries to find a socket thread with the given peer ID. * @param peerId The peer ID associated with the socket thread. * @param isIncoming If true, will search from incoming connections. If false, will search from outgoing connections. * @return The socket thread or null if not found. */ private synchronized SocketThreadBase findSocketThread(final String peerId, final boolean isIncoming) { if (isIncoming) { for (IncomingSocketThread incomingSocketThread : mIncomingSocketThreads) { if (incomingSocketThread != null && incomingSocketThread.getPeerProperties().getId().equalsIgnoreCase(peerId)) { return incomingSocketThread; } } } else { for (OutgoingSocketThread outgoingSocketThread : mOutgoingSocketThreads) { if (outgoingSocketThread != null && outgoingSocketThread.getPeerProperties().getId().equalsIgnoreCase(peerId)) { return outgoingSocketThread; } } } return null; } /** * Closes and removes an incoming connection thread with the given ID. * @param incomingThreadId The ID of the incoming connection thread. * @return True, if the thread was found, the connection was closed and the thread was removed from the list. */ private synchronized boolean closeAndRemoveIncomingConnectionThread(final long incomingThreadId) { boolean wasFoundClosedAndRemoved = false; for (IncomingSocketThread incomingSocketThread : mIncomingSocketThreads) { if (incomingSocketThread != null && incomingSocketThread.getId() == incomingThreadId) { Log.i(TAG, "closeAndRemoveIncomingConnectionThread: Closing and removing incoming connection thread with ID " + incomingThreadId); mIncomingSocketThreads.remove(incomingSocketThread); incomingSocketThread.close(); wasFoundClosedAndRemoved = true; break; } } Log.d(TAG, "closeAndRemoveIncomingConnectionThread: " + mIncomingSocketThreads.size() + " incoming connection(s) left"); return wasFoundClosedAndRemoved; } /** * Closes and removes an outgoing connection with the given peer ID. * @param peerId The ID of the peer to disconnect. * @param notifyError If true, will notify the Node layer about a connection error. * @return True, if the thread was found, the connection was closed and the thread was removed from the list. */ private synchronized boolean closeAndRemoveOutgoingConnectionThread( final String peerId, boolean notifyError) { boolean wasFoundAndDisconnected = false; SocketThreadBase socketThread = findSocketThread(peerId, false); if (socketThread != null) { Log.i(TAG, "closeAndRemoveOutgoingConnectionThread: Closing connection, peer ID: " + peerId); mOutgoingConnectionListeners.remove(peerId); mOutgoingSocketThreads.remove(socketThread); socketThread.close(); wasFoundAndDisconnected = true; if (notifyError) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(JXcoreExtension.EVENT_VALUE_PEER_ID, peerId); } catch (JSONException e) { Log.e(TAG, "closeAndRemoveOutgoingConnectionThread: Failed to construct a JSON object: " + e.getMessage(), e); } jxcore.CallJSMethod(JXcoreExtension.EVENT_NAME_CONNECTION_ERROR, jsonObject.toString()); } } if (!wasFoundAndDisconnected) { Log.e(TAG, "closeAndRemoveOutgoingConnectionThread: Failed to find an outgoing connection to peer with ID " + peerId); } Log.d(TAG, "closeAndRemoveOutgoingConnectionThread: " + mOutgoingSocketThreads.size() + " outgoing connection(s) left"); return wasFoundAndDisconnected; } /** * Disconnects all outgoing connections. */ private synchronized void closeAndRemoveAllOutgoingConnections() { for (OutgoingSocketThread outgoingSocketThread : mOutgoingSocketThreads) { if (outgoingSocketThread != null) { Log.d(TAG, "closeAndRemoveAllOutgoingConnections: Peer: " + outgoingSocketThread.getPeerProperties().toString()); outgoingSocketThread.close(); } } mOutgoingConnectionListeners.clear(); mOutgoingSocketThreads.clear(); } /** * Disconnects all incoming connections. * This method should only be used internally and should, in the future, made private. * For now, this method can be used for testing to emulate 'peer disconnecting' events. * @return The number of connections closed. */ public synchronized int closeAndRemoveAllIncomingConnections() { int numberOfConnectionsClosed = 0; for (IncomingSocketThread incomingSocketThread : mIncomingSocketThreads) { if (incomingSocketThread != null) { Log.d(TAG, "closeAndRemoveAllIncomingConnections: Peer: " + incomingSocketThread.getPeerProperties().toString()); incomingSocketThread.close(); numberOfConnectionsClosed++; } } mIncomingSocketThreads.clear(); return numberOfConnectionsClosed; } /** * Tries to find a peer with the given ID. * @param peerId The ID of the peer to find. * @return The properties of the found peer or null, if not found. */ private synchronized PeerProperties findDiscoveredPeer(final String peerId) { PeerProperties peerProperties = null; for (PeerProperties existingPeerProperties : mDiscoveredPeers) { if (existingPeerProperties != null && existingPeerProperties.getId().contentEquals(peerId)) { peerProperties = existingPeerProperties; break; } } return peerProperties; } /** * Adds/removes the given peer to/from the list of discovered peers. * @param peerProperties The peer properties. * @param add If true, will try to add. If false, will try to remove. * @return True, if successfully added/removed. */ private synchronized boolean modifyListOfDiscoveredPeers(PeerProperties peerProperties, boolean add) { boolean success = false; if (add) { if (findDiscoveredPeer(peerProperties.getId()) != null) { Log.w(TAG, "modifyListOfDiscoveredPeers: Peer " + peerProperties.toString() + " already in the list, will not add again"); } else { mDiscoveredPeers.add(peerProperties); success = true; } } else { // Remove PeerProperties peerPropertiesToRemove = findDiscoveredPeer(peerProperties.getId()); if (peerPropertiesToRemove != null && mDiscoveredPeers.remove(peerPropertiesToRemove)) { Log.d(TAG, "modifyListOfDiscoveredPeers: Peer " + peerProperties.toString() + " removed"); success = true; } } return success; } /** * Notifies the JXcore layer of a peer availability changed event. * @param peerProperties The peer properties. * @param isAvailable If true, the peer is available. If false, it is not available. */ private synchronized void notifyPeerAvailability(PeerProperties peerProperties, boolean isAvailable) { JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(JXcoreExtension.EVENT_VALUE_PEER_ID, peerProperties.getId()); jsonObject.put(JXcoreExtension.EVENT_VALUE_PEER_NAME, peerProperties.getName()); jsonObject.put(JXcoreExtension.EVENT_VALUE_PEER_AVAILABLE, isAvailable); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyPeerAvailability: Failed to create a JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { Log.d(TAG, "notifyPeerAvailability: Peer " + peerProperties.toString() + (isAvailable ? " is available" : " not available")); JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObject); jxcore.CallJSMethod(JXcoreExtension.EVENT_NAME_PEER_AVAILABILITY_CHANGED, jsonArray.toString()); } } }
package org.hibernate.ogm.test.utils; import static org.fest.assertions.Assertions.assertThat; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.rules.ExternalResource; /** * test case useful when one want to write a test relying on an archive (like a JPA archive) * * @author Hardy Ferentschik * @author Emmanuel Bernard <emmanuel@hibernate.org> * @author Sanne Grinovero */ public class PackagingRule extends ExternalResource { private static final ArchivePath persistencePath = ArchivePaths.create( "persistence.xml" ); protected static ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); protected static ClassLoader bundleClassLoader; protected static File targetDir; private final JavaArchive archive; private final File testPackage; public static File getTargetDir() { return targetDir; } static { // get a URL reference to something we now is part of the classpath (us) URL myUrl = originalClassLoader.getResource( PackagingRule.class.getName().replace( '.', '/' ) + ".class" ); File myPath = new File( myUrl.getFile() ); // navigate back to '/target' targetDir = myPath .getParentFile() // target/classes/org/hibernate/ogm/test/utils .getParentFile() // target/classes/org/hibernate/ejb/test .getParentFile() // target/classes/org/hibernate/ejb .getParentFile() // target/classes/org/hibernate .getParentFile() // target/classes/org .getParentFile() // target/classes/ .getParentFile(); // target File testPackagesDir = new File( targetDir, "bundles" ); try { bundleClassLoader = new URLClassLoader( new URL[] { testPackagesDir.toURL() }, originalClassLoader ); } catch ( MalformedURLException e ) { assertThat( true ).as( "Unable to build custom class loader" ).isFalse(); } targetDir = new File( targetDir, "packages" ); targetDir.mkdirs(); } public PackagingRule(String persistenceConfResource, Class<?>... entities) { archive = ShrinkWrap.create( JavaArchive.class, "jtastandalone.jar" ); archive.addClasses( entities ); archive.addAsManifestResource( persistenceConfResource, persistencePath ); testPackage = new File( PackagingRule.getTargetDir(), "jtastandalone.jar" ); archive.as( ZipExporter.class ).exportTo( testPackage, true ); } @Override public void before() throws MalformedURLException { URLClassLoader classLoader = new URLClassLoader( new URL[]{ testPackage.toURL() }, originalClassLoader ); Thread.currentThread().setContextClassLoader( classLoader ); } @Override public void after() { // reset the classloader Thread.currentThread().setContextClassLoader( originalClassLoader ); } }
package io.github.ihongs.dh.search.sorter; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.lucene.index.BinaryDocValues; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.LeafReader; import org.apache.lucene.search.FieldComparator; import org.apache.lucene.search.FieldComparatorSource; import org.apache.lucene.util.BytesRef; /** * * new SortField(FIELD_NAME, new SortInSet(DIST), DESC) * MySQL ORDER BY FIND_IN_SET(col, set) * @author hong */ public class SortInSet extends FieldComparatorSource { private final Map<String, Long> dist; public SortInSet(Collection<String> vals) { long i = 0 - vals.size(); dist = new HashMap ( ); for ( String val : vals ) { dist.put( val , i ++ ); } } @Override public String toString() { return dist.keySet().toString(); } @Override public FieldComparator<?> newComparator(String fn, int nh, int sp, boolean rv) { return new Comparator ( fn, nh, dist); } private static class Comparator extends BaseComparator { private final Map<String, Long> dist ; BinaryDocValues docs ; public Comparator(String name, int hits, Map<String, Long> dist) { super(name, hits); this.dist = dist ; } @Override protected void doSetNextReader(LeafReader r ) throws IOException { docs = DocValues.getBinary(r, name); } @Override protected long toGetCurrDvalue( int d ) { try { BytesRef br = docs.get( d ); String v = br.utf8ToString(); Long bs = dist.get( v ); if (null != bs) { return bs; } else { return 0L; } } catch (NullPointerException ex) { return 0L; } } } }
package org.mskcc.cbio.importer.internal; import org.mskcc.cbio.importer.*; import org.mskcc.cbio.importer.model.*; import org.apache.commons.logging.*; import org.apache.commons.lang.StringUtils; import org.jsoup.*; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import java.io.*; import java.util.*; public class BCRHTMLDictImporter extends ImporterBaseImpl implements Importer { private static final String DISPLAY_AND_COLUMN_NAME_HEADER = "CDE Name"; private static final String DEFINITION_HEADER = "Definition"; private static final String DISEASE_TYPE_HEADER = "Disease Type"; private static final String TUMOR_TYPES_DELIMITER = " \\| "; private static final String COLUMN_NAME_REGEX = "xmlTag: "; private static final Log LOG = LogFactory.getLog(BCRHTMLDictImporter.class); private Config config; private FileUtils fileUtils; private DatabaseUtils databaseUtils; private int displayAndColumnNameIndex; private int definitionIndex; private int tumorTypeIndex; public BCRHTMLDictImporter(Config config, FileUtils fileUtils, DatabaseUtils databaseUtils) { this.config = config; this.fileUtils = fileUtils; this.databaseUtils = databaseUtils; } @Override public void importData(String portal, Boolean initPortalDatabase, Boolean initTumorTypes, Boolean importReferenceData) throws Exception { throw new UnsupportedOperationException(); } @Override public void importCancerStudy(String cancerStudyDirectoryName, boolean skip, boolean force) throws Exception { throw new UnsupportedOperationException(); } @Override public void importReferenceData(ReferenceMetadata referenceMetadata) throws Exception { String bcrDictionaryFilename = referenceMetadata.getImporterArgs().get(0); if (!bcrDictionaryFilename.isEmpty()) { logMessage(LOG, "importReferenceData, processing Biospecimen Core Resource dictionary: " + bcrDictionaryFilename); config.importBCRClinicalAttributes(getBCRDictEntries(bcrDictionaryFilename)); } else { logMessage(LOG, "importReferenceData, missing Biospecimen Core Resource dictionary filename."); } } private List<BCRDictEntry> getBCRDictEntries(String bcrDictionaryFilename) throws Exception { Document doc = Jsoup.parse(new File(bcrDictionaryFilename), null); return getBCRDictEntriesFromTable(doc.select("table").first()); } private List<BCRDictEntry> getBCRDictEntriesFromTable(Element table) { List<BCRDictEntry> bcrs = new ArrayList<BCRDictEntry>(); setColumnIndices(table.select("thead").first()); for (Element row : table.select("tbody").first().select("tr")) { bcrs.addAll(getBCRDictEntryFromRow(row)); } if (bcrs.isEmpty()) { fatal(); } return bcrs; } private void setColumnIndices(Element htmlTableHeader) { displayAndColumnNameIndex = getColumnIndex(htmlTableHeader, DISPLAY_AND_COLUMN_NAME_HEADER); definitionIndex = getColumnIndex(htmlTableHeader, DEFINITION_HEADER); tumorTypeIndex = getColumnIndex(htmlTableHeader, DISEASE_TYPE_HEADER); if (displayAndColumnNameIndex < 0 || definitionIndex < 0 || tumorTypeIndex < 0) { fatal(); } } private int getColumnIndex(Element htmlTableHeader, String attributeName) { Elements columns = htmlTableHeader.select("th"); for (int colIndex = 0; colIndex < columns.size(); colIndex++) { Element column = columns.get(colIndex); if (column.text().contains(attributeName)) { return colIndex; } } return -1; } private List<BCRDictEntry> getBCRDictEntryFromRow(Element row) { List<BCRDictEntry> bcrs = new ArrayList<BCRDictEntry>(); // there can be multiple column attribute headers per row for (String columnName : getColumnNamesFromRow(row)) { BCRDictEntry bcr = new BCRDictEntry(); bcr.id = columnName.trim(); bcr.displayName = getDisplayNameFromRow(row); bcr.description = row.select("td").get(definitionIndex).text(); bcr.cancerStudy = ""; bcr.tumorType = getTumorTypesFromRow(row); bcrs.add(bcr); } return bcrs; } private List<String> getColumnNamesFromRow(Element row) { List<String> values = Arrays.asList(row.select("td").get(displayAndColumnNameIndex).text().split(COLUMN_NAME_REGEX)); return values.subList(1, values.size()); } private String getDisplayNameFromRow(Element row) { return row.select("td").get(displayAndColumnNameIndex).text().split(COLUMN_NAME_REGEX)[0].trim(); } private String getTumorTypesFromRow(Element row) { return StringUtils.join(row.select("td").get(tumorTypeIndex).text().split(TUMOR_TYPES_DELIMITER), ",").toLowerCase(); } private void fatal() { throw new IllegalArgumentException("BCR HTML Dictionary format has changed, aborting..."); } }
package com.inepex.ineFrame.server.auth; import java.util.UUID; import javax.servlet.http.HttpSession; import net.customware.gwt.dispatch.server.ExecutionContext; import net.customware.gwt.dispatch.shared.DispatchException; import nl.captcha.Captcha; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Provider; import com.inepex.ineFrame.server.dispatch.AbstractIneHandler; import com.inepex.ineFrame.shared.auth.AuthStatusResultBase; import com.inepex.ineFrame.shared.auth.LoginAction; import com.inepex.ineFrame.shared.exceptions.AuthenticationException; public abstract class AbstractLoginHandler<U extends AuthUser, R extends AuthStatusResultBase> extends AbstractIneHandler<LoginAction, AuthStatusResultBase>{ private static final Logger _logger = LoggerFactory .getLogger(AbstractLoginHandler.class); private final Provider<SessionScopedAuthStat> authStatProvider; private final Provider<SessionScopedCaptchaInfo> captchaInfoProvider; private final Provider<HttpSession> sessionProvider; protected AbstractLoginHandler(Provider<SessionScopedAuthStat> authStat, Provider<HttpSession> sesionProvider, Provider<SessionScopedCaptchaInfo> captchaInfoProvider) { this.authStatProvider = authStat; this.captchaInfoProvider=captchaInfoProvider; this.sessionProvider=sesionProvider; } protected void onLogin(U user){ } @Override protected AuthStatusResultBase doExecute(LoginAction action, ExecutionContext context) throws AuthenticationException, DispatchException { U user; SessionScopedCaptchaInfo captchaInfo = captchaInfoProvider.get(); synchronized (captchaInfo) { if(action.getUserName()==null || action.getPassword()==null) { captchaInfo.registerIncorrectAnswer(); return new AuthStatusResultBase(captchaInfo.needCaptcha()); } if(captchaInfo.needCaptcha()) { //incorrect request if(action.getCaptchaAnswer()==null || sessionProvider.get().getAttribute(Captcha.NAME)==null || !action.getCaptchaAnswer().equals(((Captcha)sessionProvider.get().getAttribute(Captcha.NAME)).getAnswer())) { captchaInfo.registerIncorrectAnswer(); return new AuthStatusResultBase(captchaInfo.needCaptcha()); } } user = findByUserNameAndPassword(action.getUserName(), action.getPassword()); if(user==null) { //incorrect password captchaInfo.registerIncorrectAnswer(); return new AuthStatusResultBase(captchaInfo.needCaptcha()); } else { captchaInfo.registerCorrectAnswer(); } } R result = createResultBase(); setUserToSession(user, result, action.getUserName()); // if the login was successful and the user wants to stay signed in if(result.isSuccess() && action.isNeedStaySignedIn()){ String UUIDString = UUID.randomUUID().toString(); result.setUserEmail(action.getUserName()); result.setUserUUID(UUIDString); // set the UUID for the user setUserStaySignedInUUID(result.getUserId(), UUIDString); } _logger.debug("Login successful: {}", authStatProvider.get()); return result; } public void setUserToSession(U user, R result, String email) { result.setSuccess(true); result.setDisplayName(user.getDisplayName()); result.setRoles(user.getAllowedRoles()); result.setUserId(user.getUserId()); result.setUserEmail(email); mapAdditional(user, result); onLogin(user); SessionScopedAuthStat authStat = authStatProvider.get(); synchronized (authStat) { authStat.clearState(); authStat.setUserId(user.getUserId()); authStat.setAuthStatusResultBase(result); } } protected abstract void mapAdditional(U user, R result); /** * * @return - the selected authUser or null if password or userName is incorrect */ protected abstract U findByUserNameAndPassword(String userAuthString, String password); /** * @return an empty result base object */ protected abstract R createResultBase(); @Override public Class<LoginAction> getActionType() { return LoginAction.class; } // methods for the stay signed in logic // needs to be implemented in the derived classes, because of the user handling protected abstract void setUserStaySignedInUUID(Long userId, String UUIDString); public abstract AuthUser checkSignedInUUIDForUserAndLogUserIntoIfCorrect(String userEmail, String userUUID, AuthStatusResultBase result); }
package org.om.core.impl.persistence.jcr.util; import java.math.BigDecimal; import java.util.Calendar; import javax.jcr.PropertyType; public class PropertyTypeToClass { private static final Class<?>[] TYPES; static { TYPES = new Class<?>[12]; TYPES[PropertyType.STRING] = String.class; TYPES[PropertyType.BINARY] = byte[].class; TYPES[PropertyType.LONG] = long.class; TYPES[PropertyType.DOUBLE] = double.class; TYPES[PropertyType.DATE] = Calendar.class; TYPES[PropertyType.BOOLEAN] = boolean.class; TYPES[PropertyType.NAME] = String.class; TYPES[PropertyType.DECIMAL] = BigDecimal.class; } /** * Maps a {@link PropertyType}.* type to a {@link Class} object. * * @param type * @return */ public static Class<?> getClassForType(int type) { if ((type >= TYPES.length) || (type < 0)) { throw new IllegalArgumentException("Don't know how to map type " + type + " to a class."); } return TYPES[type]; } /** * Maps a {@link Class} object to a JCR type. * * @return */ public static int getTypeForClass(Class<?> type) { if (type == String.class) { return PropertyType.STRING; } if (type == int.class || type == Integer.class || type == long.class || type == Long.class) { return PropertyType.LONG; } if (type == float.class || type == Float.class || type == double.class || type == Double.class) { return PropertyType.DOUBLE; } if (type == boolean.class || type == Boolean.class) { return PropertyType.LONG; } if (type == byte[].class) { return PropertyType.BINARY; } if (type == Calendar.class) { return PropertyType.DATE; } if (type == BigDecimal.class) { return PropertyType.DECIMAL; } throw new IllegalArgumentException("Don't know how to map class " + type.getName() + " to a JCR property type."); } }
package com.jenjinstudios.server.sql; import com.jenjinstudios.core.util.Hash; import com.jenjinstudios.server.net.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import static java.sql.ResultSet.CONCUR_UPDATABLE; import static java.sql.ResultSet.TYPE_SCROLL_SENSITIVE; /** * The SQLHandler class is responsible for connecting to and querying the SQL database associated with a given Server. * @author Caleb Brinkman */ @SuppressWarnings("SameParameterValue") public class Authenticator { private static final String SALT_COLUMN = "salt"; private static final String PASSWORD_COLUMN = "password"; /** The name of the column in the user table specifying whether the user is currently logged in. */ private static final String LOGGED_IN_COLUMN = "loggedin"; /** The connection used to communicate with the SQL database. */ protected final Connection dbConnection; /** The string used to get all information about the user. */ private final String USER_QUERY; /** * Create a new SQLHandler with the given database information, and connect to the database. */ public Authenticator(Connection dbConnection) { USER_QUERY = "SELECT * FROM jenjin_users WHERE username = ?"; this.dbConnection = dbConnection; } /** * Attempt to log the given user with the given password into the database. This method does not perform any sort * of hashing or encryption on the password. If the user is already logged in this method will return false. * <p> * This method should be overwritten by implementations, or called from super if they still wish to use the * "loggedIn" column. * @return true if the user was logged in successfully, false if the user was already logged in or the update to * the * database failed. */ public User logInUser(String username, String password) throws LoginException { User user = getUserWithValidPassword(username, password); updateLoggedinColumn(username, true); user.setLoggedIn(true); return user; } private User getUserWithValidPassword(String username, String password) throws LoginException { User user = lookUpUser(username); if (user.isLoggedIn()) throw new LoginException("User " + username + " is already logged in."); String hashedPassword = Hash.getHashedString(password, user.getSalt()); boolean passwordCorrect = hashedPassword != null && hashedPassword.equalsIgnoreCase(user.getPassword()); if (!passwordCorrect) throw new LoginException("User " + username + " provided incorrect password."); return user; } public User lookUpUser(String username) throws LoginException { boolean loggedIn; String salt; String dbPass; User user; try (ResultSet results = makeUserQuery(username)) { if (!results.next()) { throw new LoginException("User " + username + " does not exist."); } loggedIn = results.getBoolean(LOGGED_IN_COLUMN); salt = results.getString(SALT_COLUMN); dbPass = results.getString(PASSWORD_COLUMN); user = new User(); user.setUsername(username); user.setPassword(dbPass); user.setSalt(salt); user.setLoggedIn(loggedIn); } catch (SQLException e) { throw new LoginException("Unable to retrieve user " + username + " because of SQL Exception.", e); } return user; } /** * Attempt to log out the user with the given username. Note that if a user is already logged out, * this method will * have no affect. * @param username The username of the user to be logged out. * @return The user that was logged out. */ public User logOutUser(String username) throws LoginException { User user = lookUpUser(username); if (user.isLoggedIn()) { user.setLoggedIn(false); updateLoggedinColumn(username, false); } return user; } /** * Query the database for user info. * @param username The username of the user we're looking for. * @return The ResultSet returned by the query. * @throws SQLException If there is a SQL error. */ protected ResultSet makeUserQuery(String username) throws SQLException { PreparedStatement statement; synchronized (dbConnection) { statement = dbConnection.prepareStatement(USER_QUERY, TYPE_SCROLL_SENSITIVE, CONCUR_UPDATABLE); statement.setString(1, username); } return statement.executeQuery(); } /** * Update the loggedin column to reflect the supplied boolean. * @param username The user being queried. * @param status The new status of the loggedin column. * @throws com.jenjinstudios.server.sql.LoginException If there is a SQL error. */ protected void updateLoggedinColumn(String username, boolean status) throws LoginException { String newValue = status ? "1" : "0"; String updateLoggedInQuery = "UPDATE jenjin_users SET " + LOGGED_IN_COLUMN + "=" + newValue + " WHERE " + "username = ?"; synchronized (dbConnection) { try (PreparedStatement updateLoggedIn = dbConnection.prepareStatement(updateLoggedInQuery)) { updateLoggedIn.setString(1, username); updateLoggedIn.executeUpdate(); updateLoggedIn.close(); } catch (SQLException e) { throw new LoginException("Unable to update " + username + "; SQLException when updating loggedin " + "column."); } } } }
package com.foilen.smalltools.crypt.cert; import java.io.ByteArrayOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.Writer; import java.math.BigInteger; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.spongycastle.asn1.ASN1Primitive; import org.spongycastle.asn1.ASN1Set; import org.spongycastle.asn1.x500.AttributeTypeAndValue; import org.spongycastle.asn1.x500.RDN; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; import org.spongycastle.cert.X509CertificateHolder; import org.spongycastle.cert.X509v3CertificateBuilder; import org.spongycastle.cert.jcajce.JcaX509CertificateConverter; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.jce.provider.BouncyCastleProvider; import org.spongycastle.openssl.MiscPEMGenerator; import org.spongycastle.operator.ContentSigner; import org.spongycastle.operator.ContentVerifierProvider; import org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.spongycastle.operator.bc.BcRSAContentVerifierProviderBuilder; import org.spongycastle.operator.jcajce.JcaContentSignerBuilder; import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemObjectGenerator; import org.spongycastle.util.io.pem.PemReader; import org.spongycastle.util.io.pem.PemWriter; import com.foilen.smalltools.crypt.asymmetric.AsymmetricKeys; import com.foilen.smalltools.crypt.asymmetric.RSACrypt; import com.foilen.smalltools.crypt.asymmetric.RSAKeyDetails; import com.foilen.smalltools.exception.SmallToolsException; import com.foilen.smalltools.hash.HashSha1; import com.foilen.smalltools.tools.AssertTools; import com.foilen.smalltools.tools.CloseableTools; import com.foilen.smalltools.tools.DateTools; import com.foilen.smalltools.tools.FileTools; /** * To create self-signed certificates and to sign other certificates. * * <pre> * Usage: * * // Root * AsymmetricKeys rootKeys = rsaCrypt.generateKeyPair(2048); * RSACertificate rootCertificate = new RSACertificate(rootKeys); * rootCertificate.selfSign(new CertificateDetails().setCommonName("CA root")); * * // Node * AsymmetricKeys nodeKeys = rsaCrypt.generateKeyPair(2048); * RSACertificate nodeCertificate = rootCertificate.signPublicKey(nodeKeys, new CertificateDetails().setCommonName("p001.node.foilen.org")); * * // Fake Root * AsymmetricKeys fakeRootKeys = rsaCrypt.generateKeyPair(2048); * RSACertificate fakeRootCertificate = new RSACertificate(fakeRootKeys); * fakeRootCertificate.selfSign(new CertificateDetails().setCommonName("CA root")); * * // Assert certificates * Assert.assertTrue(rootCertificate.isValidSignature(rootCertificate)); * Assert.assertTrue(nodeCertificate.isValidSignature(rootCertificate)); * Assert.assertTrue(fakeRootCertificate.isValidSignature(fakeRootCertificate)); * * Assert.assertFalse(rootCertificate.isValidSignature(nodeCertificate)); * Assert.assertFalse(rootCertificate.isValidSignature(fakeRootCertificate)); * Assert.assertFalse(nodeCertificate.isValidSignature(nodeCertificate)); * Assert.assertFalse(nodeCertificate.isValidSignature(fakeRootCertificate)); * Assert.assertFalse(fakeRootCertificate.isValidSignature(rootCertificate)); * Assert.assertFalse(fakeRootCertificate.isValidSignature(nodeCertificate)); * </pre> * * <pre> * Dependencies: * compile 'com.madgag.spongycastle:prov:1.51.0.0' * compile 'com.madgag.spongycastle:pkix:1.51.0.0' * compile 'com.madgag.spongycastle:pg:1.51.0.0' * </pre> */ public class RSACertificate { static { BouncyCastleProvider provider = new BouncyCastleProvider(); if (Security.getProvider(provider.getName()) == null) { Security.addProvider(provider); } } private static String OID_COMMON_NAME = "2.5.4.3"; private static RSACrypt rsaCrypt = new RSACrypt(); /** * Load the certificate and keys (if present in the file). * * @param fileName * the full path of the file * @return the certificate */ public static RSACertificate loadPemFromFile(String fileName) { String pem = FileTools.getFileAsString(fileName); return loadPemFromString(pem); } /** * Load the certificate and keys (if present in the string). * * @param pem * the pem * @return the certificate */ public static RSACertificate loadPemFromString(String pem) { RSACertificate certificate = new RSACertificate(); PemReader pemReader = null; try { // Keys if present certificate.keysForSigning = rsaCrypt.loadKeysPemFromString(pem); // Certificate pemReader = new PemReader(new StringReader(pem)); PemObject pemObject; while ((pemObject = pemReader.readPemObject()) != null) { if ("CERTIFICATE".equals(pemObject.getType())) { certificate.certificateHolder = new X509CertificateHolder(pemObject.getContent()); } } return certificate; } catch (Exception e) { throw new SmallToolsException("Problem loading the certificate", e); } finally { CloseableTools.close(pemReader); } } private X509CertificateHolder certificateHolder; private AsymmetricKeys keysForSigning; public RSACertificate() { } public RSACertificate(AsymmetricKeys keysForSigning) { this.keysForSigning = keysForSigning; } public RSACertificate(X509CertificateHolder certificateHolder) { this.certificateHolder = certificateHolder; } public RSACertificate(X509CertificateHolder certificateHolder, AsymmetricKeys keysForSigning) { this.certificateHolder = certificateHolder; this.keysForSigning = keysForSigning; } /** * Get the Java certificate. * * @return the Java certificate */ public X509Certificate getCertificate() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); try { return new JcaX509CertificateConverter().getCertificate(certificateHolder); } catch (CertificateException e) { throw new SmallToolsException("Could not convert the certificate", e); } } public X509CertificateHolder getCertificateHolder() { return certificateHolder; } /** * Get the certificate's common name. * * @return the common name */ public String getCommonName() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); X500Name subject = certificateHolder.getSubject(); for (RDN rdn : subject.getRDNs()) { AttributeTypeAndValue first = rdn.getFirst(); if (OID_COMMON_NAME.equals(first.getType().toString())) { return first.getValue().toString(); } } return null; } /** * Get the certificate's common names. * * @return the common names */ public Set<String> getCommonNames() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); X500Name subject = certificateHolder.getSubject(); Set<String> commonNames = new HashSet<>(); for (RDN rdn : subject.getRDNs()) { ASN1Primitive primitive = rdn.toASN1Primitive(); if (primitive instanceof ASN1Set) { ASN1Set asn1Set = (ASN1Set) primitive; for (int i = 0; i < asn1Set.size(); ++i) { AttributeTypeAndValue next = AttributeTypeAndValue.getInstance(asn1Set.getObjectAt(i)); if (OID_COMMON_NAME.equals(next.getType().toString())) { commonNames.add(next.getValue().toString()); } } } } return commonNames; } /** * Get the ending date of this certificate. * * @return the ending date */ public Date getEndDate() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); return certificateHolder.getNotAfter(); } public AsymmetricKeys getKeysForSigning() { return keysForSigning; } /** * Get the starting date of this certificate. * * @return the starting date */ public Date getStartDate() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); return certificateHolder.getNotBefore(); } /** * Compute the SHA1 thumbprint. * * @return the SHA1 thumbprint */ public String getThumbprint() { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); try { return HashSha1.hashBytes(certificateHolder.getEncoded()); } catch (IOException e) { throw new SmallToolsException("Problem getting the thumbprint", e); } } /** * Check if the current time is in the certificate dates range. * * @return true if valid */ public boolean isValidDate() { return isValidDate(new Date()); } /** * Check if the specified time is in the certificate dates range. * * @param date * the time to check * @return true if valid */ public boolean isValidDate(Date date) { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); return DateTools.isAfter(date, certificateHolder.getNotBefore()) && DateTools.isBefore(date, certificateHolder.getNotAfter()); } /** * Check if the certificate was signed by the specified public key. * * @param signerPublicKey * the signer's public key * @return true if signed by it */ public boolean isValidSignature(AsymmetricKeyParameter signerPublicKey) { try { ContentVerifierProvider verifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(signerPublicKey); return certificateHolder.isSignatureValid(verifierProvider); } catch (Exception e) { throw new SmallToolsException("Problem validating the certificate", e); } } /** * Check if the certificate was signed by the specified public key. * * @param signerPublicKey * the signer's pair of keys that contains the public key * @return true if signed by it */ public boolean isValidSignature(AsymmetricKeys signerPublicKey) { try { ContentVerifierProvider verifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(signerPublicKey.getPublicKey()); return certificateHolder.isSignatureValid(verifierProvider); } catch (Exception e) { throw new SmallToolsException("Problem validating the certificate", e); } } /** * Check if the certificate was signed by the specified certificate. * * @param signerCertificate * the signer's certificate * @return true if signed by it */ public boolean isValidSignature(RSACertificate signerCertificate) { try { ContentVerifierProvider verifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(signerCertificate.certificateHolder); return certificateHolder.isSignatureValid(verifierProvider); } catch (Exception e) { throw new SmallToolsException("Problem validating the certificate", e); } } /** * Save the certificate in a PEM file. * * @param fileName * the full path to the file */ public void saveCertificatePem(String fileName) { try { saveCertificatePem(new FileWriter(fileName)); } catch (IOException e) { throw new SmallToolsException("Could not save cert", e); } } /** * Save the certificate in a PEM writer. * * @param writer * the writer. Will be closed at the end */ public void saveCertificatePem(Writer writer) { AssertTools.assertNotNull(certificateHolder, "The certificate is not set"); PemWriter pemWriter = null; try { pemWriter = new PemWriter(writer); PemObjectGenerator pemObjectGenerator = new MiscPEMGenerator(certificateHolder); pemWriter.writeObject(pemObjectGenerator); } catch (Exception e) { throw new SmallToolsException("Could not save cert", e); } finally { CloseableTools.close(pemWriter); } } /** * Save the certificate in a PEM String. * * @return the pem */ public String saveCertificatePemAsString() { ByteArrayOutputStream result = new ByteArrayOutputStream(); saveCertificatePem(new OutputStreamWriter(result)); return result.toString(); } /** * Sign the {@link #setKeysForSigning(AsymmetricKeys)} with itself and put it in certificateHolder. * * @param certificateDetails * some information to store in the certificate * @return this */ public RSACertificate selfSign(CertificateDetails certificateDetails) { AssertTools.assertNotNull(keysForSigning, "The keysForSigning is not set"); AssertTools.assertNull(certificateHolder, "The certificate already exists"); try { RSAKeyDetails keyDetails = rsaCrypt.retrieveKeyDetails(keysForSigning); PrivateKey privKey = keyDetails.getJcaPrivateKey(); PublicKey publicKey = keyDetails.getJcaPublicKey(); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider("SC").build(privKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = certificateDetails.getStartDate(); Date endDate = certificateDetails.getEndDate(); BigInteger serial = certificateDetails.getSerial(); X500Name issuer = new X500Name("CN=" + certificateDetails.getCommonName()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuer, serial, startDate, endDate, issuer, subPubKeyInfo); certificateHolder = certificateBuilder.build(sigGen); return this; } catch (Exception e) { throw new SmallToolsException("Problem signing the key", e); } } public RSACertificate setCertificateHolder(X509CertificateHolder certificateHolder) { this.certificateHolder = certificateHolder; return this; } public RSACertificate setKeysForSigning(AsymmetricKeys keysForSigning) { this.keysForSigning = keysForSigning; return this; } /** * Sign another public key. * * @param publicKeyToSign * the public key to sign * @param certificateDetails * some information to store in the certificate * @return the new certificate */ public RSACertificate signPublicKey(AsymmetricKeys publicKeyToSign, CertificateDetails certificateDetails) { try { PrivateKey privKey = rsaCrypt.retrieveKeyDetails(keysForSigning).getJcaPrivateKey(); PublicKey publicKey = rsaCrypt.retrieveKeyDetails(publicKeyToSign).getJcaPublicKey(); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider("SC").build(privKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = certificateDetails.getStartDate(); Date endDate = certificateDetails.getEndDate(); BigInteger serial = certificateDetails.getSerial(); X500Name issuer = new X500Name("CN=" + getCommonName()); X500Name subject = new X500Name("CN=" + certificateDetails.getCommonName()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuer, serial, startDate, endDate, subject, subPubKeyInfo); X509CertificateHolder newCert = certificateBuilder.build(sigGen); return new RSACertificate(newCert, publicKeyToSign); } catch (Exception e) { throw new SmallToolsException("Problem signing the key", e); } } }
package org.joyrest.routing; import org.joyrest.model.http.HttpMethod; import org.joyrest.processor.RequestProcessor; import org.joyrest.routing.entity.*; /** * Class {@link TypedControllerConfiguration} is abstract implementation of {@link ControllerConfiguration} and makes easier to create the * given route using predefined protected method. * <p/> * It can be considered as container for routes which are provided to {@link RequestProcessor} because of processing and handling incoming * requests. * * @author pbouda */ public abstract class TypedControllerConfiguration extends AbstractControllerConfiguration { protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, req, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, req, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, req, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, req, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, req, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, req, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, req, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, req, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.POST, "", action, req, null); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.POST, path, action, req, null); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, null, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, null, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.POST, "", action, req, null); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.POST, path, action, req, null); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, "", action, null, resp); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.POST, path, action, null, resp); } protected final <REQ, RESP> Route post(RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.POST, "", action, null, null); } protected final <REQ, RESP> Route post(String path, RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.POST, path, action, null, null); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, req, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, req, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, req, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, req, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, req, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, req, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, req, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, req, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.GET, "", action, req, null); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.GET, path, action, req, null); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, null, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, null, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.GET, "", action, req, null); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.GET, path, action, req, null); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, "", action, null, resp); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.GET, path, action, null, resp); } protected final <REQ, RESP> Route get(RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.GET, "", action, null, null); } protected final <REQ, RESP> Route get(String path, RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.GET, path, action, null, null); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, req, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, req, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, req, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, req, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, req, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, req, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, req, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, req, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.PUT, "", action, req, null); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.PUT, path, action, req, null); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, null, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, ResponseType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, null, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.PUT, "", action, req, null); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, RequestCollectionType<REQ> req) { return createEntityRoute(HttpMethod.PUT, path, action, req, null); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, "", action, null, resp); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action, ResponseCollectionType<RESP> resp) { return createEntityRoute(HttpMethod.PUT, path, action, null, resp); } protected final <REQ, RESP> Route put(RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.PUT, "", action, null, null); } protected final <REQ, RESP> Route put(String path, RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.PUT, path, action, null, null); } protected final <REQ, RESP> Route delete(RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.DELETE, "", action, null, null); } protected final <REQ, RESP> Route delete(String path, RouteAction<REQ, RESP> action) { return createEntityRoute(HttpMethod.DELETE, path, action, null, null); } protected final <REQ, RESP> Route delete(String path, RouteAction<REQ, RESP> action, RequestType<REQ> req) { return createEntityRoute(HttpMethod.DELETE, path, action, req, null); } }
package com.reactnativenavigation.parse; import android.app.Activity; import com.facebook.react.ReactInstanceManager; import com.reactnativenavigation.react.EventEmitter; import com.reactnativenavigation.utils.CommandListenerAdapter; import com.reactnativenavigation.utils.ImageLoader; import com.reactnativenavigation.utils.TypefaceLoader; import com.reactnativenavigation.viewcontrollers.ComponentViewController; import com.reactnativenavigation.viewcontrollers.SideMenuController; import com.reactnativenavigation.viewcontrollers.StackController; import com.reactnativenavigation.viewcontrollers.StackControllerBuilder; import com.reactnativenavigation.viewcontrollers.ViewController; import com.reactnativenavigation.viewcontrollers.bottomtabs.BottomTabsController; import com.reactnativenavigation.viewcontrollers.externalcomponent.ExternalComponentCreator; import com.reactnativenavigation.viewcontrollers.externalcomponent.ExternalComponentViewController; import com.reactnativenavigation.viewcontrollers.topbar.TopBarBackgroundViewController; import com.reactnativenavigation.viewcontrollers.topbar.TopBarController; import com.reactnativenavigation.viewcontrollers.toptabs.TopTabsController; import com.reactnativenavigation.views.ComponentViewCreator; import com.reactnativenavigation.views.titlebar.TitleBarButtonCreator; import com.reactnativenavigation.views.titlebar.TitleBarReactViewCreator; import com.reactnativenavigation.views.topbar.TopBarBackgroundViewCreator; import com.reactnativenavigation.views.toptabs.TopTabsLayoutCreator; import java.util.ArrayList; import java.util.List; import java.util.Map; public class LayoutFactory { private final Activity activity; private final ReactInstanceManager reactInstanceManager; private EventEmitter eventEmitter; private Map<String, ExternalComponentCreator> externalComponentCreators; private Options defaultOptions; private final TypefaceLoader typefaceManager; public LayoutFactory(Activity activity, final ReactInstanceManager reactInstanceManager, EventEmitter eventEmitter, Map<String, ExternalComponentCreator> externalComponentCreators, Options defaultOptions) { this.activity = activity; this.reactInstanceManager = reactInstanceManager; this.eventEmitter = eventEmitter; this.externalComponentCreators = externalComponentCreators; this.defaultOptions = defaultOptions; typefaceManager = new TypefaceLoader(activity); } public ViewController create(final LayoutNode node) { switch (node.type) { case Component: return createComponent(node); case ExternalComponent: return createExternalComponent(node); case Stack: return createStack(node); case BottomTabs: return createBottomTabs(node); case SideMenuRoot: return createSideMenuRoot(node); case SideMenuCenter: return createSideMenuContent(node); case SideMenuLeft: return createSideMenuLeft(node); case SideMenuRight: return createSideMenuRight(node); case TopTabs: return createTopTabs(node); default: throw new IllegalArgumentException("Invalid node type: " + node.type); } } private ViewController createSideMenuRoot(LayoutNode node) { SideMenuController sideMenuController = new SideMenuController(activity, node.id, parseNodeOptions(node)); for (LayoutNode child : node.children) { ViewController childController = create(child); childController.setParentController(sideMenuController); switch (child.type) { case SideMenuCenter: sideMenuController.setCenterController(childController); break; case SideMenuLeft: sideMenuController.setLeftController(childController); break; case SideMenuRight: sideMenuController.setRightController(childController); break; default: throw new IllegalArgumentException("Invalid node type in sideMenu: " + node.type); } } return sideMenuController; } private ViewController createSideMenuContent(LayoutNode node) { return create(node.children.get(0)); } private ViewController createSideMenuLeft(LayoutNode node) { return create(node.children.get(0)); } private ViewController createSideMenuRight(LayoutNode node) { return create(node.children.get(0)); } private ViewController createComponent(LayoutNode node) { String id = node.id; String name = node.data.optString("name"); return new ComponentViewController(activity, id, name, new ComponentViewCreator(reactInstanceManager), parseNodeOptions(node) ); } private ViewController createExternalComponent(LayoutNode node) { final ExternalComponent externalComponent = ExternalComponent.parse(node.data); return new ExternalComponentViewController(activity, node.id, externalComponent, externalComponentCreators.get(externalComponent.name.get()), reactInstanceManager, parseNodeOptions(node) ); } private ViewController createStack(LayoutNode node) { StackController stackController = new StackControllerBuilder(activity) .setTopBarButtonCreator(new TitleBarButtonCreator(reactInstanceManager)) .setTitleBarReactViewCreator(new TitleBarReactViewCreator(reactInstanceManager)) .setTopBarBackgroundViewController(new TopBarBackgroundViewController(activity, new TopBarBackgroundViewCreator(reactInstanceManager))) .setTopBarController(new TopBarController()) .setId(node.id) .setInitialOptions(parseNodeOptions(node)) .createStackController(); addChildrenToStack(node.children, stackController); return stackController; } private void addChildrenToStack(List<LayoutNode> children, StackController stackController) { for (LayoutNode child : children) { stackController.push(create(child), new CommandListenerAdapter()); } } private ViewController createBottomTabs(LayoutNode node) { final BottomTabsController tabsComponent = new BottomTabsController(activity, eventEmitter, new ImageLoader(), node.id, parseNodeOptions(node)); List<ViewController> tabs = new ArrayList<>(); for (int i = 0; i < node.children.size(); i++) { tabs.add(create(node.children.get(i))); } tabsComponent.setTabs(tabs); return tabsComponent; } private ViewController createTopTabs(LayoutNode node) { final List<ViewController> tabs = new ArrayList<>(); for (int i = 0; i < node.children.size(); i++) { ViewController tabController = create(node.children.get(i)); Options options = parseNodeOptions(node.children.get(i)); options.setTopTabIndex(i); tabs.add(tabController); } return new TopTabsController(activity, node.id, tabs, new TopTabsLayoutCreator(activity, tabs), parseNodeOptions(node)); } private Options parseNodeOptions(LayoutNode node) { return Options.parse(typefaceManager, node.getNavigationOptions(), defaultOptions); } }
package org.rstudio.studio.client.workbench.views.source.editors.text; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.http.client.URL; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.events.EnsureHeightHandler; import org.rstudio.core.client.events.EnsureVisibleHandler; import org.rstudio.core.client.events.HasEnsureHeightHandlers; import org.rstudio.core.client.events.HasEnsureVisibleHandlers; import org.rstudio.core.client.files.FileSystemContext; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsUtil; import org.rstudio.core.client.regex.Match; import org.rstudio.core.client.regex.Pattern; import org.rstudio.core.client.widget.*; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.ChangeFontSizeHandler; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.*; import org.rstudio.studio.client.common.debugging.BreakpointManager; import org.rstudio.studio.client.common.debugging.events.BreakpointsSavedEvent; import org.rstudio.studio.client.common.debugging.model.Breakpoint; import org.rstudio.studio.client.common.filetypes.DocumentMode; import org.rstudio.studio.client.common.filetypes.FileType; import org.rstudio.studio.client.common.filetypes.FileTypeCommands; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.SweaveFileType; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.common.rnw.RnwWeave; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.common.synctex.SynctexUtils; import org.rstudio.studio.client.common.synctex.model.SourceLocation; import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewEvent; import org.rstudio.studio.client.htmlpreview.model.HTMLPreviewParams; import org.rstudio.studio.client.notebook.CompileNotebookOptions; import org.rstudio.studio.client.notebook.CompileNotebookOptionsDialog; import org.rstudio.studio.client.notebook.CompileNotebookPrefs; import org.rstudio.studio.client.notebook.CompileNotebookResult; import org.rstudio.studio.client.rmarkdown.events.ConvertToShinyDocEvent; import org.rstudio.studio.client.rmarkdown.events.RmdOutputFormatChangedEvent; import org.rstudio.studio.client.rmarkdown.model.RMarkdownContext; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateFormat; import org.rstudio.studio.client.rmarkdown.model.RmdYamlData; import org.rstudio.studio.client.rmarkdown.model.YamlFrontMatter; import org.rstudio.studio.client.rmarkdown.ui.RmdTemplateOptionsDialog; import org.rstudio.studio.client.rsconnect.events.RSConnectActionEvent; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.shiny.events.ShinyApplicationStatusEvent; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor; import org.rstudio.studio.client.workbench.ui.FontSizeManager; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection; import org.rstudio.studio.client.workbench.views.files.events.FileChangeEvent; import org.rstudio.studio.client.workbench.views.files.events.FileChangeHandler; import org.rstudio.studio.client.workbench.views.files.model.FileChange; import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent; import org.rstudio.studio.client.workbench.views.presentation.events.SourceFileSaveCompletedEvent; import org.rstudio.studio.client.workbench.views.presentation.model.PresentationState; import org.rstudio.studio.client.workbench.views.source.SourceBuildHelper; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetCodeExecution; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay.AnchoredSelection; import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeList.ContainsFoldPredicate; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper.RmdSelectedTemplate; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceFold; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Token; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Tokenizer; import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext; import org.rstudio.studio.client.workbench.views.source.editors.text.events.*; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupRequest; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog; import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent; import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler; import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent; import org.rstudio.studio.client.workbench.views.source.events.SourceNavigationEvent; import org.rstudio.studio.client.workbench.views.source.model.*; import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsDiffEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsHistoryEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRevertFileEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsViewOnGitHubEvent; import org.rstudio.studio.client.workbench.views.vcs.common.model.GitHubViewRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Stack; public class TextEditingTarget implements EditingTarget, EditingTargetCodeExecution.CodeExtractor { interface MyCommandBinder extends CommandBinder<Commands, TextEditingTarget> { } private static final String NOTEBOOK_TITLE = "notebook_title"; private static final String NOTEBOOK_AUTHOR = "notebook_author"; private static final String NOTEBOOK_TYPE = "notebook_type"; private static final MyCommandBinder commandBinder = GWT.create(MyCommandBinder.class); public interface Display extends TextDisplay, WarningBarDisplay, HasEnsureVisibleHandlers, HasEnsureHeightHandlers { HasValue<Boolean> getSourceOnSave(); void ensureVisible(); void showFindReplace(boolean defaultForward); void findNext(); void findPrevious(); void findSelectAll(); void findFromSelection(); void replaceAndFind(); StatusBar getStatusBar(); boolean isAttached(); void adaptToExtendedFileType(String extendedType); void onShinyApplicationStateChanged(String state); void debug_dumpContents(); void debug_importDump(); void setIsShinyFormat(boolean isPresentation); void setFormatOptions(TextFileType fileType, List<String> options, List<String> values, List<String> extensions, String selected); void setFormatOptionsVisible(boolean visible); HandlerRegistration addRmdFormatChangedHandler( RmdOutputFormatChangedEvent.Handler handler); } private class SaveProgressIndicator implements ProgressIndicator { public SaveProgressIndicator(FileSystemItem file, TextFileType fileType, Command executeOnSuccess) { file_ = file; newFileType_ = fileType; executeOnSuccess_ = executeOnSuccess; } public void onProgress(String message) { } public void clearProgress() { } public void onCompleted() { // don't need to check again soon because we just saved // (without this and when file monitoring is active we'd // end up immediately checking for external edits) externalEditCheckInterval_.reset(250); if (newFileType_ != null) fileType_ = newFileType_; if (file_ != null) { ignoreDeletes_ = false; forceSaveCommandActive_ = false; commands_.reopenSourceDocWithEncoding().setEnabled(true); name_.setValue(file_.getName(), true); // Make sure tooltip gets updated, even if name hasn't changed name_.fireChangeEvent(); // If we were dirty prior to saving, clean up the debug state so // we don't continue highlighting after saving. (There are cases // in which we want to restore highlighting after the dirty state // is marked clean--i.e. when unwinding the undo stack.) if (dirtyState_.getValue()) endDebugHighlighting(); dirtyState_.markClean(); } if (newFileType_ != null) { // Make sure the icon gets updated, even if name hasn't changed name_.fireChangeEvent(); updateStatusBarLanguage(); view_.adaptToFileType(newFileType_); events_.fireEvent(new FileTypeChangedEvent()); if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { view_.getSourceOnSave().setValue(false, true); } } if (executeOnSuccess_ != null) executeOnSuccess_.execute(); } public void onError(final String message) { // in case the error occured saving a document that wasn't // in the foreground view_.ensureVisible(); // command to show the error final Command showErrorCommand = new Command() { @Override public void execute() { globalDisplay_.showErrorMessage("Error Saving File", message); } }; // check whether the file exists and isn't writeable if (file_ != null) { server_.isReadOnlyFile(file_.getPath(), new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean isReadOnly) { if (isReadOnly) { String message = "This source file is read-only " + "so changes cannot be saved"; view_.showWarningBar(message); String saveAsPath = file_.getParentPath().completePath( file_.getStem() + "-copy" + file_.getExtension()); saveNewFile( saveAsPath, null, CommandUtil.join(postSaveCommand(), new Command() { @Override public void execute() { view_.hideWarningBar(); } })); } else { showErrorCommand.execute(); } } @Override public void onError(ServerError error) { Debug.logError(error); showErrorCommand.execute(); } }); } else { showErrorCommand.execute(); } } private final FileSystemItem file_; private final TextFileType newFileType_; private final Command executeOnSuccess_; } @Inject public TextEditingTarget(Commands commands, SourceServerOperations server, EventBus events, GlobalDisplay globalDisplay, FileDialogs fileDialogs, FileTypeRegistry fileTypeRegistry, FileTypeCommands fileTypeCommands, ConsoleDispatcher consoleDispatcher, WorkbenchContext workbenchContext, Session session, Synctex synctex, FontSizeManager fontSizeManager, DocDisplay docDisplay, UIPrefs prefs, BreakpointManager breakpointManager, SourceBuildHelper sourceBuildHelper) { commands_ = commands; server_ = server; events_ = events; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileTypeRegistry_ = fileTypeRegistry; fileTypeCommands_ = fileTypeCommands; consoleDispatcher_ = consoleDispatcher; workbenchContext_ = workbenchContext; session_ = session; synctex_ = synctex; fontSizeManager_ = fontSizeManager; breakpointManager_ = breakpointManager; sourceBuildHelper_ = sourceBuildHelper; docDisplay_ = docDisplay; dirtyState_ = new DirtyState(docDisplay_, false); prefs_ = prefs; codeExecution_ = new EditingTargetCodeExecution(docDisplay_, this); compilePdfHelper_ = new TextEditingTargetCompilePdfHelper(docDisplay_); rmarkdownHelper_ = new TextEditingTargetRMarkdownHelper(); cppHelper_ = new TextEditingTargetCppHelper(server); presentationHelper_ = new TextEditingTargetPresentationHelper( docDisplay_); docDisplay_.setRnwCompletionContext(compilePdfHelper_); docDisplay_.setCppCompletionContext(cppCompletionContext_); docDisplay_.setRCompletionContext(rContext_); scopeHelper_ = new TextEditingTargetScopeHelper(docDisplay_); addRecordNavigationPositionHandler(releaseOnDismiss_, docDisplay_, events_, this); docDisplay_.addKeyDownHandler(new KeyDownHandler() { @SuppressWarnings("deprecation") public void onKeyDown(KeyDownEvent event) { NativeEvent ne = event.getNativeEvent(); int mod = KeyboardShortcut.getModifierValue(ne); if ((mod == KeyboardShortcut.META || (mod == KeyboardShortcut.CTRL && !BrowseCap.hasMetaKey())) && ne.getKeyCode() == 'F') { event.preventDefault(); event.stopPropagation(); commands_.findReplace().execute(); } else if (BrowseCap.hasMetaKey() && (mod == KeyboardShortcut.META) && (ne.getKeyCode() == 'E')) { event.preventDefault(); event.stopPropagation(); commands_.findFromSelection().execute(); } else if (mod == KeyboardShortcut.ALT && ne.getKeyCode() == 189) // hyphen { event.preventDefault(); event.stopPropagation(); if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) || (!docDisplay_.hasSelection() && docDisplay_.getCursorPosition().getColumn() == 0)) docDisplay_.insertCode("<- ", false); else docDisplay_.insertCode(" <- ", false); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_UP && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToPreviousFunction(); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_DOWN && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToNextFunction(); } else if ((ne.getKeyCode() == KeyCodes.KEY_ESCAPE) && !prefs_.useVimMode().getValue()) { event.preventDefault(); event.stopPropagation(); if (commands_.interruptR().isEnabled()) commands_.interruptR().execute(); } else if (ne.getKeyCode() == KeyCodes.KEY_M && ( (BrowseCap.hasMetaKey() && mod == (KeyboardShortcut.META + KeyboardShortcut.SHIFT)) || (!BrowseCap.hasMetaKey() && mod == (KeyboardShortcut.CTRL + KeyboardShortcut.SHIFT)))) { event.preventDefault(); event.stopPropagation(); if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) || (!docDisplay_.hasSelection() && docDisplay_.getCursorPosition().getColumn() == 0)) docDisplay_.insertCode("%>% ", false); else docDisplay_.insertCode(" %>% ", false); } else if ( prefs_.continueCommentsOnNewline().getValue() && !docDisplay_.isPopupVisible() && ne.getKeyCode() == KeyCodes.KEY_ENTER && mod == 0 && (fileType_.isC() || isCursorInRMode() || isCursorInTexMode())) { String line = docDisplay_.getCurrentLineUpToCursor(); Pattern pattern = null; if (isCursorInRMode()) pattern = Pattern.create("^(\\s* else if (isCursorInTexMode()) pattern = Pattern.create("^(\\s*%+'?\\s*)"); else if (fileType_.isC()) { // bail on attributes if (!line.matches("^\\s* pattern = Pattern.create("^(\\s* } if (pattern != null) { Match match = pattern.match(line, 0); if (match != null) { event.preventDefault(); event.stopPropagation(); docDisplay_.insertCode("\n" + match.getGroup(1)); } } } else if ( prefs_.continueCommentsOnNewline().getValue() && !docDisplay_.isPopupVisible() && ne.getKeyCode() == KeyCodes.KEY_ENTER && mod == KeyboardShortcut.SHIFT) { event.preventDefault(); event.stopPropagation(); String indent = docDisplay_.getNextLineIndent(); docDisplay_.insertCode("\n" + indent); } } }); docDisplay_.addCommandClickHandler(new CommandClickEvent.Handler() { @Override public void onCommandClick(CommandClickEvent event) { if (fileType_.canCompilePDF() && commands_.synctexSearch().isEnabled()) { // warn firefox users that this doesn't really work in Firefox if (BrowseCap.isFirefox() && !BrowseCap.isMacintosh()) SynctexUtils.maybeShowFirefoxWarning("PDF preview"); doSynctexSearch(true); } else { docDisplay_.goToFunctionDefinition(); } } }); docDisplay_.addFindRequestedHandler(new FindRequestedEvent.Handler() { @Override public void onFindRequested(FindRequestedEvent event) { view_.showFindReplace(event.getDefaultForward()); } }); events_.addHandler( ShinyApplicationStatusEvent.TYPE, new ShinyApplicationStatusEvent.Handler() { @Override public void onShinyApplicationStatus( ShinyApplicationStatusEvent event) { // If the document appears to be inside the directory // associated with the event, update the view to match the // new state. if (getPath() != null && getPath().startsWith(event.getParams().getPath())) { view_.onShinyApplicationStateChanged( event.getParams().getState()); } } }); events_.addHandler( BreakpointsSavedEvent.TYPE, new BreakpointsSavedEvent.Handler() { @Override public void onBreakpointsSaved(BreakpointsSavedEvent event) { // if this document isn't ready for breakpoints, stop now if (docUpdateSentinel_ == null) { return; } for (Breakpoint breakpoint: event.breakpoints()) { // discard the breakpoint if it's not related to the file this // editor instance is concerned with if (!breakpoint.isInFile(getPath())) { continue; } // if the breakpoint was saved successfully, enable it on the // editor surface; otherwise, just remove it. if (event.successful()) { docDisplay_.addOrUpdateBreakpoint(breakpoint); } else { // Show a warning for breakpoints that didn't get set (unless // the reason the breakpoint wasn't set was that it's being // removed) if (breakpoint.getState() != Breakpoint.STATE_REMOVING) { view_.showWarningBar("Breakpoints can only be set inside "+ "the body of a function. "); } docDisplay_.removeBreakpoint(breakpoint); } } updateBreakpointWarningBar(); } }); events_.addHandler(ConvertToShinyDocEvent.TYPE, new ConvertToShinyDocEvent.Handler() { @Override public void onConvertToShinyDoc(ConvertToShinyDocEvent event) { if (getPath() != null && getPath().equals(event.getPath())) { String yaml = getRmdFrontMatter(); if (yaml == null) return; String newYaml = rmarkdownHelper_.convertYamlToShinyDoc(yaml); applyRmdFrontMatter(newYaml); renderRmd(); } } }); } @Override public void recordCurrentNavigationPosition() { docDisplay_.recordCurrentNavigationPosition(); } @Override public void navigateToPosition(SourcePosition position, boolean recordCurrent) { docDisplay_.navigateToPosition(position, recordCurrent); } @Override public void navigateToPosition(SourcePosition position, boolean recordCurrent, boolean highlightLine) { docDisplay_.navigateToPosition(position, recordCurrent, highlightLine); } @Override public void restorePosition(SourcePosition position) { docDisplay_.restorePosition(position); } @Override public boolean isAtSourceRow(SourcePosition position) { return docDisplay_.isAtSourceRow(position); } @Override public void setCursorPosition(Position position) { docDisplay_.setCursorPosition(position); } @Override public void ensureCursorVisible() { docDisplay_.ensureCursorVisible(); } @Override public void forceLineHighlighting() { docDisplay_.setHighlightSelectedLine(true); } @Override public void highlightDebugLocation( SourcePosition startPos, SourcePosition endPos, boolean executing) { debugStartPos_ = startPos; debugEndPos_ = endPos; docDisplay_.highlightDebugLocation(startPos, endPos, executing); updateDebugWarningBar(); } @Override public void endDebugHighlighting() { docDisplay_.endDebugHighlighting(); debugStartPos_ = null; debugEndPos_ = null; updateDebugWarningBar(); } private void updateDebugWarningBar() { // show the warning bar if we're debugging and the document is dirty if (debugStartPos_ != null && dirtyState().getValue() && !isDebugWarningVisible_) { view_.showWarningBar("Debug lines may not match because the file contains unsaved changes."); isDebugWarningVisible_ = true; } // hide the warning bar if the dirty state or debug state change else if (isDebugWarningVisible_ && (debugStartPos_ == null || dirtyState().getValue() == false)) { view_.hideWarningBar(); // if we're still debugging, start highlighting the line again if (debugStartPos_ != null) { docDisplay_.highlightDebugLocation( debugStartPos_, debugEndPos_, false); } isDebugWarningVisible_ = false; } } private void jumpToPreviousFunction() { Scope jumpTo = scopeHelper_.getPreviousFunction( docDisplay_.getCursorPosition()); if (jumpTo != null) docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true); } private void jumpToNextFunction() { Scope jumpTo = scopeHelper_.getNextFunction( docDisplay_.getCursorPosition()); if (jumpTo != null) docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true); } public void initialize(SourceDocument document, FileSystemContext fileContext, FileType type, Provider<String> defaultNameProvider) { id_ = document.getId(); fileContext_ = fileContext; fileType_ = (TextFileType) type; extendedType_ = document.getExtendedType(); extendedType_ = rmarkdownHelper_.detectExtendedType(document.getContents(), extendedType_, fileType_); view_ = new TextEditingTargetWidget(commands_, prefs_, fileTypeRegistry_, docDisplay_, fileType_, extendedType_, events_, session_); docUpdateSentinel_ = new DocUpdateSentinel( server_, docDisplay_, document, globalDisplay_.getProgressIndicator("Save File"), dirtyState_, events_); // ensure that Makefile and Makebars always uses tabs name_.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { if ("Makefile".equals(event.getValue()) || "Makevars".equals(event.getValue()) || "Makevars.win".equals(event.getValue())) { docDisplay_.setUseSoftTabs(false); } } }); name_.setValue(getNameFromDocument(document, defaultNameProvider), true); docDisplay_.setCode(document.getContents(), false); final ArrayList<Fold> folds = Fold.decode(document.getFoldSpec()); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { for (Fold fold : folds) docDisplay_.addFold(fold.getRange()); } }); registerPrefs(releaseOnDismiss_, prefs_, docDisplay_, document); // Initialize sourceOnSave, and keep it in sync view_.getSourceOnSave().setValue(document.sourceOnSave(), false); view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { docUpdateSentinel_.setSourceOnSave( event.getValue(), globalDisplay_.getProgressIndicator("Error Saving Setting")); } }); if (document.isDirty()) dirtyState_.markDirty(false); else dirtyState_.markClean(); docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() { public void onValueChange(ValueChangeEvent<Void> event) { dirtyState_.markDirty(true); } }); docDisplay_.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { public boolean execute() { if (view_.isAttached()) checkForExternalEdit(); return false; } }, 500); } }); if (fileType_.isR()) { docDisplay_.addBreakpointSetHandler(new BreakpointSetEvent.Handler() { @Override public void onBreakpointSet(BreakpointSetEvent event) { if (event.isSet()) { Breakpoint breakpoint = null; // don't try to set breakpoints in unsaved code if (isNewDoc()) { view_.showWarningBar("Breakpoints cannot be set until " + "the file is saved."); return; } // don't try to set breakpoints if the R version is too old if (!session_.getSessionInfo().getHaveSrcrefAttribute()) { view_.showWarningBar("Editor breakpoints require R 2.14 " + "or newer."); return; } Position breakpointPosition = Position.create(event.getLineNumber() - 1, 1); // if we're not in function scope, set a top-level breakpoint ScopeFunction innerFunction = docDisplay_.getFunctionAtPosition(breakpointPosition); if (innerFunction == null || !innerFunction.isFunction() || StringUtil.isNullOrEmpty(innerFunction.getFunctionName())) { breakpoint = breakpointManager_.setTopLevelBreakpoint( getPath(), event.getLineNumber()); } // the scope tree will find nested functions, but in R these // are addressable only as substeps of the parent function. // keep walking up the scope tree until we've reached the top // level function. else { while (innerFunction.getParentScope() != null && innerFunction.getParentScope().isFunction()) { innerFunction = (ScopeFunction) innerFunction.getParentScope(); } String functionName = innerFunction.getFunctionName(); breakpoint = breakpointManager_.setBreakpoint( getPath(), functionName, event.getLineNumber(), dirtyState().getValue() == false); } docDisplay_.addOrUpdateBreakpoint(breakpoint); } else { breakpointManager_.removeBreakpoint(event.getBreakpointId()); } updateBreakpointWarningBar(); } }); docDisplay_.addBreakpointMoveHandler(new BreakpointMoveEvent.Handler() { @Override public void onBreakpointMove(BreakpointMoveEvent event) { breakpointManager_.moveBreakpoint(event.getBreakpointId()); } }); } // validate required components (e.g. Tex, knitr, C++ etc.) checkCompilePdfDependencies(); rmarkdownHelper_.verifyPrerequisites(view_, fileType_); syncFontSize(releaseOnDismiss_, events_, view_, fontSizeManager_); final String rTypeId = FileTypeRegistry.R.getTypeId(); releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler( new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { if (fileType_.getTypeId().equals(rTypeId)) view_.adaptToFileType(fileType_); } } )); releaseOnDismiss_.add(events_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler() { @Override public void onFileChange(FileChangeEvent event) { // screen out adds and events that aren't for our path FileChange fileChange = event.getFileChange(); if (fileChange.getType() == FileChange.ADD) return; else if (!fileChange.getFile().getPath().equals(getPath())) return; // always check for changes if this is the active editor if (commandHandlerReg_ != null) { checkForExternalEdit(); } // also check for changes on modifications if we are not dirty // note that we don't check for changes on removed files because // this will show a confirmation dialog else if (event.getFileChange().getType() == FileChange.MODIFIED && dirtyState().getValue() == false) { checkForExternalEdit(); } } })); spelling_ = new TextEditingTargetSpelling(docDisplay_, docUpdateSentinel_); // show/hide the debug toolbar when the dirty state changes. (note: // this doesn't yet handle the case where the user saves the document, // in which case we should still show some sort of warning.) dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { updateDebugWarningBar(); } } ); // find all of the debug breakpoints set in this document and replay them // onto the edit surface ArrayList<Breakpoint> breakpoints = breakpointManager_.getBreakpointsInFile(getPath()); for (Breakpoint breakpoint: breakpoints) { docDisplay_.addOrUpdateBreakpoint(breakpoint); } // for R Markdown docs, populate the popup menu with a list of available // formats if (extendedType_.equals("rmarkdown")) updateRmdFormatList(); view_.addRmdFormatChangedHandler(new RmdOutputFormatChangedEvent.Handler() { @Override public void onRmdOutputFormatChanged(RmdOutputFormatChangedEvent event) { setRmdFormat(event.getFormat()); } }); initStatusBar(); } private void updateBreakpointWarningBar() { // check to see if there are any inactive breakpoints in this file boolean hasInactiveBreakpoints = false; boolean hasDebugPendingBreakpoints = false; boolean hasPackagePendingBreakpoints = false; String pendingPackageName = ""; ArrayList<Breakpoint> breakpoints = breakpointManager_.getBreakpointsInFile(getPath()); for (Breakpoint breakpoint: breakpoints) { if (breakpoint.getState() == Breakpoint.STATE_INACTIVE) { if (breakpoint.isPendingDebugCompletion()) { hasDebugPendingBreakpoints = true; } else if (breakpoint.isPackageBreakpoint()) { hasPackagePendingBreakpoints = true; pendingPackageName = breakpoint.getPackageName(); } else { hasInactiveBreakpoints = true; } break; } } boolean showWarning = hasDebugPendingBreakpoints || hasInactiveBreakpoints || hasPackagePendingBreakpoints; if (showWarning && !isBreakpointWarningVisible_) { String message = ""; if (hasDebugPendingBreakpoints) { message = "Breakpoints will be activated when the file or " + "function is finished executing."; } else if (isPackageFile()) { message = "Breakpoints will be activated when the package is " + "built and reloaded."; } else if (hasPackagePendingBreakpoints) { message = "Breakpoints will be activated when an updated version " + "of the " + pendingPackageName + " package is loaded"; } else { message = "Breakpoints will be activated when this file is " + "sourced."; } view_.showWarningBar(message); isBreakpointWarningVisible_ = true; } else if (!showWarning && isBreakpointWarningVisible_) { hideBreakpointWarningBar(); } } private void hideBreakpointWarningBar() { if (isBreakpointWarningVisible_) { view_.hideWarningBar(); isBreakpointWarningVisible_ = false; } } private boolean isPackageFile() { // not a package file if we're not in package development mode String type = session_.getSessionInfo().getBuildToolsType(); if (!type.equals(SessionInfo.BUILD_TOOLS_PACKAGE)) { return false; } // get the directory associated with the project and see if the file is // inside that directory FileSystemItem projectDir = session_.getSessionInfo() .getActiveProjectDir(); return getPath().startsWith(projectDir.getPath() + "/R"); } private boolean isPackageDocumentationFile() { if (getPath() == null) { return false; } String type = session_.getSessionInfo().getBuildToolsType(); if (!type.equals(SessionInfo.BUILD_TOOLS_PACKAGE)) { return false; } FileSystemItem srcFile = FileSystemItem.createFile(getPath()); FileSystemItem projectDir = session_.getSessionInfo() .getActiveProjectDir(); if (srcFile.getPath().startsWith(projectDir.getPath() + "/vignettes")) return true; else if (srcFile.getParentPathString().equals(projectDir.getPath()) && srcFile.getExtension().toLowerCase().equals(".md")) return true; else return false; } private void checkCompilePdfDependencies() { compilePdfHelper_.checkCompilers(view_, fileType_); } private void initStatusBar() { statusBar_ = view_.getStatusBar(); docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { public void onCursorChanged(CursorChangedEvent event) { updateStatusBarPosition(); } }); updateStatusBarPosition(); updateStatusBarLanguage(); // build file type menu dynamically (so it can change according // to whether e.g. knitr is installed) statusBar_.getLanguage().addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent event) { // build menu with all file types - also track whether we need // to add the current type (may be the case for types which we // support but don't want to expose on the menu -- e.g. Rmd // files when knitr isn't installed) boolean addCurrentType = true; final StatusBarPopupMenu menu = new StatusBarPopupMenu(); TextFileType[] fileTypes = fileTypeCommands_.statusBarFileTypes(); for (TextFileType type : fileTypes) { menu.addItem(createMenuItemForType(type)); if (addCurrentType && type.equals(fileType_)) addCurrentType = false; } // add the current type if isn't on the menu if (addCurrentType) menu.addItem(createMenuItemForType(fileType_)); // show the menu menu.showRelativeToUpward((UIObject) statusBar_.getLanguage()); } }); statusBar_.getScope().addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { // Unlike the other status bar elements, the function outliner // needs its menu built on demand JsArray<Scope> tree = docDisplay_.getScopeTree(); final StatusBarPopupMenu menu = new StatusBarPopupMenu(); MenuItem defaultItem = null; if (fileType_.isRpres()) { String path = docUpdateSentinel_.getPath(); if (path != null) { presentationHelper_.buildSlideMenu( docUpdateSentinel_.getPath(), dirtyState_.getValue(), TextEditingTarget.this, new CommandWithArg<StatusBarPopupRequest>() { @Override public void execute(StatusBarPopupRequest request) { showStatusBarPopupMenu(request); } }); } } else { defaultItem = addFunctionsToMenu( menu, tree, "", docDisplay_.getCurrentScope(), true); showStatusBarPopupMenu(new StatusBarPopupRequest(menu, defaultItem)); } } }); } private void showStatusBarPopupMenu(StatusBarPopupRequest popupRequest) { final StatusBarPopupMenu menu = popupRequest.getMenu(); MenuItem defaultItem = popupRequest.getDefaultMenuItem(); if (defaultItem != null) { menu.selectItem(defaultItem); Scheduler.get().scheduleFinally(new RepeatingCommand() { public boolean execute() { menu.ensureSelectedIsVisible(); return false; } }); } menu.showRelativeToUpward((UIObject) statusBar_.getScope()); } private MenuItem createMenuItemForType(final TextFileType type) { SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendEscaped(type.getLabel()); MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docUpdateSentinel_.changeFileType( type.getTypeId(), new SaveProgressIndicator(null, type, null)); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { focus(); } }); } }); return menuItem; } private MenuItem addFunctionsToMenu(StatusBarPopupMenu menu, final JsArray<Scope> funcs, String indent, Scope defaultFunction, boolean includeNoFunctionsMessage) { MenuItem defaultMenuItem = null; if (funcs.length() == 0 && includeNoFunctionsMessage) { String type = fileType_.canExecuteChunks() ? "chunks" : "functions"; MenuItem noFunctions = new MenuItem("(No " + type + " defined)", false, (Command) null); noFunctions.setEnabled(false); noFunctions.getElement().addClassName("disabled"); menu.addItem(noFunctions); } for (int i = 0; i < funcs.length(); i++) { final Scope func = funcs.get(i); String childIndent = indent; if (!StringUtil.isNullOrEmpty(func.getLabel())) { SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendHtmlConstant(indent); labelBuilder.appendEscaped(func.getLabel()); final MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docDisplay_.navigateToPosition(toSourcePosition(func), true); } }); menu.addItem(menuItem); childIndent = indent + "&nbsp;&nbsp;"; if (defaultFunction != null && defaultMenuItem == null && func.getLabel().equals(defaultFunction.getLabel()) && func.getPreamble().getRow() == defaultFunction.getPreamble().getRow() && func.getPreamble().getColumn() == defaultFunction.getPreamble().getColumn()) { defaultMenuItem = menuItem; } } MenuItem childDefaultMenuItem = addFunctionsToMenu( menu, func.getChildren(), childIndent, defaultMenuItem == null ? defaultFunction : null, false); if (childDefaultMenuItem != null) defaultMenuItem = childDefaultMenuItem; } return defaultMenuItem; } private void updateStatusBarLanguage() { statusBar_.getLanguage().setValue(fileType_.getLabel()); boolean canShowScope = fileType_.canShowScopeTree(); statusBar_.setScopeVisible(canShowScope); if (canShowScope) updateCurrentScope(); } private void updateStatusBarPosition() { Position pos = docDisplay_.getCursorPosition(); statusBar_.getPosition().setValue((pos.getRow() + 1) + ":" + (pos.getColumn() + 1)); if (fileType_.canShowScopeTree()) updateCurrentScope(); } private void updateCurrentScope() { Scheduler.get().scheduleDeferred( new ScheduledCommand() { public void execute() { // special handing for presentations since we extract // the slide structure in a different manner than // the editor scope trees if (fileType_.isRpres()) { statusBar_.getScope().setValue( presentationHelper_.getCurrentSlide()); statusBar_.setScopeType(StatusBar.SCOPE_SLIDE); } else { Scope scope = docDisplay_.getCurrentScope(); String label = scope != null ? scope.getLabel() : null; statusBar_.getScope().setValue(label); if (scope != null) { boolean useChunk = scope.isChunk() || (fileType_.isRnw() && scope.isTopLevel()); if (useChunk) statusBar_.setScopeType(StatusBar.SCOPE_CHUNK); else if (scope.isNamespace()) statusBar_.setScopeType(StatusBar.SCOPE_NAMESPACE); else if (scope.isClass()) statusBar_.setScopeType(StatusBar.SCOPE_CLASS); else if (scope.isSection()) statusBar_.setScopeType(StatusBar.SCOPE_SECTION); else if (scope.isTopLevel()) statusBar_.setScopeType(StatusBar.SCOPE_TOP_LEVEL); else if (scope.isFunction()) statusBar_.setScopeType(StatusBar.SCOPE_FUNCTION); else if (scope.isLambda()) statusBar_.setScopeType(StatusBar.SCOPE_LAMBDA); else if (scope.isAnon()) statusBar_.setScopeType(StatusBar.SCOPE_ANON); } } } }); } private String getNameFromDocument(SourceDocument document, Provider<String> defaultNameProvider) { if (document.getPath() != null) return FileSystemItem.getNameFromPath(document.getPath()); String name = document.getProperties().getString("tempName"); if (!StringUtil.isNullOrEmpty(name)) return name; String defaultName = defaultNameProvider.get(); docUpdateSentinel_.setProperty("tempName", defaultName, null); return defaultName; } public long getFileSizeLimit() { return 2 * 1024 * 1024; } public long getLargeFileSize() { return 512 * 1024; } public void insertCode(String source, boolean blockMode) { docDisplay_.insertCode(source, blockMode); } public HashSet<AppCommand> getSupportedCommands() { return fileType_.getSupportedCommands(commands_); } @Override public boolean canCompilePdf() { return fileType_.canCompilePDF(); } @Override public void verifyCppPrerequisites() { // NOTE: will be a no-op for non-c/c++ file types cppHelper_.checkBuildCppDependencies(this, view_, fileType_); } public void focus() { docDisplay_.focus(); } public String getSelectedText() { if (docDisplay_.hasSelection()) return docDisplay_.getSelectionValue(); else return ""; } public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler) { return view_.addEnsureVisibleHandler(handler); } public HandlerRegistration addEnsureHeightHandler(EnsureHeightHandler handler) { return view_.addEnsureHeightHandler(handler); } public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler) { return handlers_.addHandler(CloseEvent.getType(), handler); } public void fireEvent(GwtEvent<?> event) { handlers_.fireEvent(event); } public void onActivate() { // IMPORTANT NOTE: most of this logic is duplicated in // CodeBrowserEditingTarget (no straightforward way to create a // re-usable implementation) so changes here need to be synced // If we're already hooked up for some reason, unhook. // This shouldn't happen though. if (commandHandlerReg_ != null) { Debug.log("Warning: onActivate called twice without intervening onDeactivate"); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } commandHandlerReg_ = commandBinder.bind(commands_, this); Scheduler.get().scheduleFinally(new ScheduledCommand() { public void execute() { // This has to be executed in a scheduleFinally because // Source.manageCommands gets called after this.onActivate, // and if we're going from a non-editor (like data view) to // an editor, setEnabled(true) will be called on the command // in manageCommands. commands_.reopenSourceDocWithEncoding().setEnabled( docUpdateSentinel_.getPath() != null); } }); view_.onActivate(); } public void onDeactivate() { // IMPORTANT NOTE: most of this logic is duplicated in // CodeBrowserEditingTarget (no straightforward way to create a // re-usable implementation) so changes here need to be synced externalEditCheckInvalidation_.invalidate(); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; // switching tabs is a navigation action try { docDisplay_.recordCurrentNavigationPosition(); } catch(Exception e) { Debug.log("Exception recording nav position: " + e.toString()); } } @Override public void onInitiallyLoaded() { checkForExternalEdit(); } public boolean onBeforeDismiss() { Command closeCommand = new Command() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }; if (dirtyState_.getValue()) saveWithPrompt(closeCommand, null); else closeCommand.execute(); return false; } public void save() { save(new Command() { @Override public void execute() { }}); } public void save(Command onCompleted) { saveThenExecute(null, CommandUtil.join(postSaveCommand(), onCompleted)); } public void saveWithPrompt(final Command command, final Command onCancelled) { view_.ensureVisible(); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, getName().getValue() + " - Unsaved Changes", "The document '" + getName().getValue() + "' has unsaved changes.\n\n" + "Do you want to save these changes?", true, new Operation() { public void execute() { saveThenExecute(null, command); } }, new Operation() { public void execute() { command.execute(); } }, new Operation() { public void execute() { if (onCancelled != null) onCancelled.execute(); } }, "Save", "Don't Save", true); } public void revertChanges(Command onCompleted) { docUpdateSentinel_.revert(onCompleted); } private void saveThenExecute(String encodingOverride, final Command command) { checkCompilePdfDependencies(); final String path = docUpdateSentinel_.getPath(); if (path == null) { saveNewFile(null, encodingOverride, command); return; } withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { fixupCodeBeforeSaving(); docUpdateSentinel_.save(path, null, encoding, new SaveProgressIndicator( FileSystemItem.createFile(path), null, command )); } }); } private void saveNewFile(final String suggestedPath, String encodingOverride, final Command executeOnSuccess) { withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { saveNewFileWithEncoding(suggestedPath, encoding, executeOnSuccess); } }); } private void withEncodingRequiredUnlessAscii( final String encodingOverride, final CommandWithArg<String> command) { final String encoding = StringUtil.firstNotNullOrEmpty(new String[] { encodingOverride, docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue() }); if (StringUtil.isNullOrEmpty(encoding)) { if (docUpdateSentinel_.isAscii()) { // Don't bother asking when it's just ASCII command.execute(null); } else { withChooseEncoding(session_.getSessionInfo().getSystemEncoding(), new CommandWithArg<String>() { public void execute(String newEncoding) { command.execute(newEncoding); } }); } } else { command.execute(encoding); } } private void withChooseEncoding(final String defaultEncoding, final CommandWithArg<String> command) { view_.ensureVisible();; server_.iconvlist(new SimpleRequestCallback<IconvListResult>() { @Override public void onResponseReceived(IconvListResult response) { // Stupid compiler. Use this Value shim to make the dialog available // in its own handler. final HasValue<ChooseEncodingDialog> d = new Value<ChooseEncodingDialog>(null); d.setValue(new ChooseEncodingDialog( response.getCommon(), response.getAll(), defaultEncoding, false, true, new OperationWithInput<String>() { public void execute(String newEncoding) { if (newEncoding == null) return; if (d.getValue().isSaveAsDefault()) { prefs_.defaultEncoding().setGlobalValue(newEncoding); prefs_.writeUIPrefs(); } command.execute(newEncoding); } })); d.getValue().showModal(); } }); } private void saveNewFileWithEncoding(String suggestedPath, final String encoding, final Command executeOnSuccess) { view_.ensureVisible(); FileSystemItem fsi; if (suggestedPath != null) fsi = FileSystemItem.createFile(suggestedPath); else fsi = getSaveFileDefaultDir(); fileDialogs_.saveFile( "Save File - " + getName().getValue(), fileContext_, fsi, fileType_.getDefaultExtension(), false, new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem saveItem, ProgressIndicator indicator) { if (saveItem == null) return; try { workbenchContext_.setDefaultFileDialogDir( saveItem.getParentPath()); final TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(saveItem); final Command saveCommand = new Command() { @Override public void execute() { // breakpoints are file-specific, so when saving as // a different file, clear the display of breakpoints // from the old file name if (!getPath().equals(saveItem.getPath())) { docDisplay_.removeAllBreakpoints(); } fixupCodeBeforeSaving(); docUpdateSentinel_.save( saveItem.getPath(), fileType.getTypeId(), encoding, new SaveProgressIndicator(saveItem, fileType, executeOnSuccess)); events_.fireEvent( new SourceFileSavedEvent(saveItem.getPath())); } }; // if we are switching from an R file type // to a non-R file type then confirm if (fileType_.isR() && !fileType.isR()) { globalDisplay_.showYesNoMessage( MessageDialog.WARNING, "Confirm Change File Type", "This file was created as an R script however " + "the file extension you specified will change " + "it into another file type that will no longer " + "open as an R script.\n\n" + "Are you sure you want to change the type of " + "the file so that it is no longer an R script?", new Operation() { @Override public void execute() { saveCommand.execute(); } }, false); } else { saveCommand.execute(); } } catch (Exception e) { indicator.onError(e.toString()); return; } indicator.onCompleted(); } }); } private void fixupCodeBeforeSaving() { int lineCount = docDisplay_.getRowCount(); if (lineCount < 1) return; if (prefs_.stripTrailingWhitespace().getValue() && !fileType_.isMarkdown()) { String code = docDisplay_.getCode(); Pattern pattern = Pattern.create("[ \t]+$"); String strippedCode = pattern.replaceAll(code, ""); if (!strippedCode.equals(code)) docDisplay_.setCode(strippedCode, true); } if (prefs_.autoAppendNewline().getValue() || fileType_.isPython()) { String lastLine = docDisplay_.getLine(lineCount - 1); if (lastLine.length() != 0) docDisplay_.insertCode(docDisplay_.getEnd().getEnd(), "\n"); } } private FileSystemItem getSaveFileDefaultDir() { FileSystemItem fsi = null; SessionInfo si = session_.getSessionInfo(); if (si.getBuildToolsType() == SessionInfo.BUILD_TOOLS_PACKAGE) { FileSystemItem pkg = FileSystemItem.createDir(si.getBuildTargetDir()); if (fileType_.isR()) { fsi = FileSystemItem.createDir(pkg.completePath("R")); } else if (fileType_.isC() && si.getHasPackageSrcDir()) { fsi = FileSystemItem.createDir(pkg.completePath("src")); } else if (fileType_.isRd()) { fsi = FileSystemItem.createDir(pkg.completePath("man")); } else if ((fileType_.isRnw() || fileType_.isRmd()) && si.getHasPackageVignetteDir()) { fsi = FileSystemItem.createDir(pkg.completePath("vignettes")); } } if (fsi == null) fsi = workbenchContext_.getDefaultFileDialogDir(); return fsi; } public void onDismiss() { docUpdateSentinel_.stop(); if (spelling_ != null) spelling_.onDismiss(); while (releaseOnDismiss_.size() > 0) releaseOnDismiss_.remove(0).removeHandler(); codeExecution_.detachLastExecuted(); } public ReadOnlyValue<Boolean> dirtyState() { return dirtyState_; } @Override public boolean isSaveCommandActive() { return // force active? forceSaveCommandActive_ || // standard check of dirty state (dirtyState().getValue() == true) || // empty untitled document (allow for immediate save) ((getPath() == null) && docDisplay_.getCode().isEmpty()) || // source on save is active (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()); } @Override public void forceSaveCommandActive() { forceSaveCommandActive_ = true; } public Widget asWidget() { return (Widget) view_; } public String getId() { return id_; } @Override public void adaptToExtendedFileType(String extendedType) { view_.adaptToExtendedFileType(extendedType); if (extendedType.equals("rmarkdown")) updateRmdFormatList(); extendedType_ = extendedType; } @Override public String getExtendedFileType() { return extendedType_; } public HasValue<String> getName() { return name_; } public String getTitle() { return getName().getValue(); } public String getPath() { if (docUpdateSentinel_ == null) return null; return docUpdateSentinel_.getPath(); } public String getContext() { return null; } public ImageResource getIcon() { return fileType_.getDefaultIcon(); } public String getTabTooltip() { return getPath(); } @Override public TextFileType getTextFileType() { return fileType_; } private static final String VALID_WORD_FOR_ALIGN = "[-+\\w._$@'\"]+"; private static final Pattern DELIM_PATTERN = Pattern.create("(^\\s*" + VALID_WORD_FOR_ALIGN + "\\s*)" + "(<<-|<-|=(?!=))" + "(\\s*" + VALID_WORD_FOR_ALIGN + "[,;]?\\s*$)"); private ArrayList<Pair<Integer, Integer>> getAlignmentRanges() { int selectionStart = docDisplay_.getSelectionStart().getRow(); int selectionEnd = docDisplay_.getSelectionEnd().getRow(); ArrayList<Pair<Integer, Integer>> ranges = new ArrayList<Pair<Integer, Integer>>(); for (int i = selectionStart; i <= selectionEnd; i++) { String line = docDisplay_.getLine(i); String masked = StringUtil.maskStrings(line); Match match = DELIM_PATTERN.match(masked, 0); if (match != null) { String delimiter = match.getGroup(2); int rangeStart = i; while (i++ <= selectionEnd) { line = docDisplay_.getLine(i); masked = StringUtil.maskStrings(line); // Allow empty lines, and comments, to live within the range. if (masked.matches("^\\s*$") || masked.matches("^\\s* continue; // If this line doesn't match, bail match = DELIM_PATTERN.match(masked, 0); if (match == null || !match.getGroup(2).equals(delimiter)) break; } // But don't allow comments or whitespaces to exist at the // end of a range. int rangeEnd = i - 1; line = docDisplay_.getLine(rangeEnd); while (line.matches("^\\s*$") || line.matches("^\\s* { rangeEnd line = docDisplay_.getLine(rangeEnd); } ranges.add(new Pair<Integer, Integer>(rangeStart, rangeEnd)); } } return ranges; } private void doAlignAssignment(int startRow, int endRow) { docDisplay_.setSelectionRange(Range.fromPoints( Position.create(startRow, 0), Position.create(endRow, docDisplay_.getLine(endRow).length()))); String[] splat = docDisplay_.getSelectionValue().split("\n"); ArrayList<String> starts = new ArrayList<String>(); ArrayList<String> delimiters = new ArrayList<String>(); ArrayList<String> ends = new ArrayList<String>(); for (int i = 0; i < splat.length; i++) { String line = splat[i]; String masked = StringUtil.maskStrings(splat[i]); Match match = DELIM_PATTERN.match(masked, 0); if (match == null) { starts.add(line); delimiters.add(""); ends.add(""); } else { String start = line.substring(0, match.getGroup(1).length()); start = start.replaceAll("\\s*$", ""); starts.add(start); delimiters.add(match.getGroup(2)); int endOfDelim = match.getGroup(1).length() + match.getGroup(2).length(); String end = line.substring(endOfDelim); end = end.replaceAll("^\\s*", ""); ends.add(end); } } // Transform the ends if they appear numeric-y -- we want to // right-align numbers, e.g. // x = 1, // y = 10, // z = 100 ArrayList<Integer> endPrefixes = new ArrayList<Integer>(); boolean success = true; for (int i = 0; i < ends.size(); i++) { String current = ends.get(i).replaceAll("[\\s,\\);]*", ""); try { endPrefixes.add(("" + Integer.parseInt(current)).length()); } catch (Exception e) { success = false; break; } } if (success) { int maxLength = 0; for (int i = 0; i < endPrefixes.size(); i++) maxLength = Math.max(maxLength, endPrefixes.get(i)); for (int i = 0; i < ends.size(); i++) ends.set(i, StringUtil.repeat(" ", maxLength - endPrefixes.get(i)) + ends.get(i).replaceAll("^\\s*", "")); } // Pad the 'start's with whitespace, to align the delimiter. int maxLength = 0; for (int i = 0; i < starts.size(); i++) maxLength = Math.max(maxLength, starts.get(i).replaceAll("\\s*$", "").length()); for (int i = 0; i < starts.size(); i++) starts.set(i, starts.get(i) + StringUtil.repeat(" ", maxLength - starts.get(i).length())); // Build a new selection by concatenating the (transformed) // pieces. StringBuilder newSelectionBuilder = new StringBuilder(); for (int i = 0; i < starts.size(); i++) { newSelectionBuilder.append(starts.get(i)); newSelectionBuilder.append(" " + delimiters.get(i) + " "); newSelectionBuilder.append(ends.get(i)); if (i < starts.size() - 1) newSelectionBuilder.append("\n"); } docDisplay_.replaceSelection(newSelectionBuilder.toString()); } @Handler void onReformatCode() { // Only allow if entire selection in R mode for now if (!DocumentMode.isSelectionInRMode(docDisplay_)) return; insertPrettyNewlines(); } class MutableInteger { public MutableInteger(int data) { data_ = data; } public void set(int data) { data_ = data; } public int get() { return data_; } private int data_; } private static final Pattern ENDS_WITH_NEWLINE = Pattern.create("\\n\\s*$", ""); private static final Pattern STARTS_WITH_NEWLINE = Pattern.create("^\\s*\\n", ""); class SimpleTokenCursor { public SimpleTokenCursor(ArrayList<Token> tokens) { this(tokens, 0, tokens.size()); } private SimpleTokenCursor(ArrayList<Token> tokens, int offset, int n) { complements_ = new HashMap<String, String>(); complements_.put("(", ")"); complements_.put("[", "]"); complements_.put("{", "}"); complements_.put("[[", "]]"); complements_.put(")", "("); complements_.put("]", "["); complements_.put("}", "{"); complements_.put("]]", "[["); tokens_ = tokens; offset_ = offset; n_ = n; } private SimpleTokenCursor(ArrayList<Token> tokens, int offset, int n, HashMap<String, String> complements) { tokens_ = tokens; offset_ = offset; n_ = n; complements_ = complements; } public SimpleTokenCursor clone() { return new SimpleTokenCursor( tokens_, offset_, n_, complements_); } public SimpleTokenCursor clone(int offset) { return new SimpleTokenCursor( tokens_, offset_ + offset, n_, complements_); } public boolean moveToNextToken() { if (offset_ >= n_ - 1) return false; ++offset_; return true; } public boolean moveToPreviousToken() { if (offset_ <= 0) return false; --offset_; return true; } public boolean moveToNextSignificantToken() { if (!moveToNextToken()) return false; while (isWhitespaceOrNewline()) if (!moveToNextToken()) return false; return true; } public boolean moveToPreviousSignificantToken() { if (!moveToPreviousToken()) return false; while (isWhitespaceOrNewline()) if (!moveToPreviousToken()) return false; return true; } public Token previousSignificantToken() { SimpleTokenCursor clone = clone(); if (!clone.moveToPreviousToken()) return Token.create(); while (clone.isWhitespaceOrNewline()) if (!clone.moveToPreviousToken()) return Token.create(); return clone.currentToken(); } public Token nextSignificantToken() { SimpleTokenCursor clone = clone(); if (!clone.moveToNextToken()) return Token.create(); while (clone.isWhitespaceOrNewline()) if (!clone.moveToNextToken()) return Token.create(); return clone.currentToken(); } public SimpleTokenCursor peek(int offset) { int index = offset_ + offset; if (index < 0 || index >= n_) { ArrayList<Token> dummyTokens = new ArrayList<Token>(); dummyTokens.add(Token.create("__ERROR__", "error", 0)); return new SimpleTokenCursor(dummyTokens, 0, 1, complements_); } SimpleTokenCursor clone = clone(); clone.offset_ = index; return clone; } private boolean isLeftBrace() { String value = currentValue(); return value.equals("(") || value.equals("[") || value.equals("[[") || value.equals("{"); } private boolean isRightBrace() { String value = currentValue(); return value.equals(")") || value.equals("]") || value.equals("]]") || value.equals("}"); } public boolean fwdToMatchingToken() { return fwdToMatchingToken(null); } public boolean fwdToMatchingToken(MutableInteger counter) { String lhs = this.currentValue(); if (!isLeftBrace()) return false; boolean isCounterActive = true; Stack<String> braceStack = new Stack<String>(); int stack = 0; String rhs = complements_.get(lhs); SimpleTokenCursor cursor = clone(); while (cursor.moveToNextToken()) { String value = cursor.currentValue(); if (isCounterActive && counter != null && !cursor.isComment()) { counter.set(counter.get() + value.replaceAll("\\s", "").length()); } if (cursor.isLeftBrace()) { braceStack.push(value); if (value.equals(lhs)) stack++; isCounterActive = false; } else if (cursor.isRightBrace()) { if (!braceStack.isEmpty()) braceStack.pop(); isCounterActive = braceStack.isEmpty(); if (value.equals(rhs)) { if (stack == 0) { offset_ = cursor.offset_; return true; } stack } } } return false; } public boolean bwdToMatchingToken() { String rhs = this.currentValue(); if (!isRightBrace()) return false; int stack = 0; String lhs = complements_.get(rhs); SimpleTokenCursor cursor = clone(); while (cursor.moveToPreviousToken()) { if (cursor.currentValue() == rhs) { stack++; } else if (cursor.currentValue() == lhs) { if (stack == 0) { offset_ = cursor.offset_; return true; } stack } } return false; } public void ensureNewlinePreceeds() { String value = getValue(); String prev = peek(-1).getValue(); if (ENDS_WITH_NEWLINE.test(prev) || STARTS_WITH_NEWLINE.test(value)) return; SimpleTokenCursor clone = clone(); clone.moveToPreviousToken(); clone.setValue(clone.getValue() + "\n"); } public void ensureNewlineFollows() { String value = getValue(); String next = peek(1).getValue(); if (ENDS_WITH_NEWLINE.test(value) || STARTS_WITH_NEWLINE.test(next)) return; SimpleTokenCursor clone = clone(); clone.moveToNextToken(); clone.setValue("\n" + clone.getValue()); } public void ensureSingleSpaceFollows() { setValue(getValue().replaceAll("\\s*$", "")); SimpleTokenCursor clone = clone(); clone.moveToNextToken(); clone.setValue(clone.getValue().replaceAll("^\\s*", "")); setValue(getValue() + " "); } public void ensureWhitespaceFollows() { String value = getValue(); boolean mightWantNewline = value.equals("&&") || value.equals("||") || value.equals("&") || value.equals("|") || value.equals("<-") || value.equals("<<-"); if (mightWantNewline && getCurrentLineLength() >= 70) { if (peek(1).getValue().indexOf('\n') == -1) setValue(getValue() + "\n"); } else { String newlineOrSpace = getDistanceToPreviousNewline() >= 70 ? "\n" : " "; if (!peek(1).isWhitespaceOrNewline()) setValue(currentValue() + newlineOrSpace); } } public void ensureWhitespacePreceeds() { if (!peek(-1).isWhitespaceOrNewline()) setValue(" " + getValue()); } public Token currentToken() { return tokens_.get(offset_); } public String currentValue() { return currentToken().getValue(); } public String getComplement(String value) { return complements_.get(value); } public String getValue() { return currentValue(); } public void setValue(String value) { currentToken().setValue(value); } public String valueAtOffset(int offset) { int index = offset_ + offset; if (index < 0 || index >= n_) return ""; return tokens_.get(index).getValue(); } public String currentType() { return tokens_.get(offset_).getType(); } // NOTE: see 'r_highlight_rules.js' for token type info public boolean isWhitespaceOrNewline() { Token token = currentToken(); return token.getType().equals("text") && token.getValue().matches("^[\\s\\n]*$"); } public void trimWhitespaceFwd() { SimpleTokenCursor clone = clone(); while (clone.isWhitespaceOrNewline()) { clone.setValue(""); if (!clone.moveToNextToken()) return; } } public void trimWhitespaceBwd() { SimpleTokenCursor clone = clone(); while (clone.isWhitespaceOrNewline()) { clone.setValue(""); if (!clone.moveToPreviousToken()) return; } } public boolean isComment() { return tokens_.get(offset_).getType().indexOf("comment") != -1; } public boolean hasNewline() { return tokens_.get(offset_).getValue().indexOf('\n') != -1; } public boolean isKeyword() { return tokens_.get(offset_).getType().equals("keyword"); } public boolean isControlFlowKeyword() { return tokens_.get(offset_).getValue().matches( "^\\s*(?:if|else|try|for|while|repeat|break|next|function)\\s*$"); } public boolean isOperator() { String type = tokens_.get(offset_).getType(); return type.equals("keyword.operator") || type.equals("keyword.operator.infix"); } public int getCurrentLineLength() { int length = 0; SimpleTokenCursor bwdCursor = clone(); while (bwdCursor.moveToPreviousToken()) { String value = bwdCursor.getValue(); int index = value.lastIndexOf('\n'); if (index == -1) length += value.length(); else { length += value.length() - index; break; } } SimpleTokenCursor fwdCursor = clone(); do { String value = fwdCursor.currentValue(); int index = value.indexOf('\n'); if (index == -1) length += value.length(); else { length += index; break; } } while (fwdCursor.moveToNextToken()); return length; } public int getDistanceToPreviousNewline() { int distance = 0; SimpleTokenCursor clone = clone(); while (clone.moveToPreviousToken()) { String value = clone.getValue(); int index = value.lastIndexOf('\n'); if (index == -1) distance += value.length(); else { distance += (value.length() - index); break; } } return distance; } @Override public boolean equals(Object object) { if (!(object instanceof SimpleTokenCursor)) return false; return offset_ == ((SimpleTokenCursor) object).offset_; } private final ArrayList<Token> tokens_; private int offset_; private int n_; private HashMap<String, String> complements_; } // The main driver of the new line inserter. // 'cursor': The current token cursor, unique to this block. // 'opener': The open brace ('[', '{', '(', '[['), // 'closer': The closing brace (']', '}', ')', ']]') // 'parenNestLevel': The nesting level within parentheses; e.g. '()'. // This is used to infer appropriate newline levels // for deeply nested function calls. // 'braceNestLevel': The number of braces encompassing this scope. // 'topLevel': Is this a top level cursor? void doInsertPrettyNewlines(SimpleTokenCursor cursor, String opener, String closer, int parenNestLevel, int braceNestLevel, boolean topLevel) { // Root state == top level of document; no open braces yet // encountered. boolean rootState = parenNestLevel == 0 && opener.isEmpty(); boolean newlineAfterComma = false; boolean newlineAfterBrace = false; int commaCount = 0; int equalsCount = 0; // We may override newline insertions in special cases to ensure // certain code structures remain intact, e.g. // lapply(x, function() { ... }) // We almost never want the anonymous function to lie on its own // line. boolean overrideNewlineInsertionAsFalse = false; String startValue = cursor.currentValue(); SimpleTokenCursor beforeStartCursor = cursor.clone(); beforeStartCursor.moveToPreviousSignificantToken(); String prevSignificantValue = beforeStartCursor.getValue(); // Trim whitespace following the 'opener' -- we may add it back later. if (!rootState) cursor.peek(1).trimWhitespaceFwd(); // Scan through once to figure out whether we want to insert newlines. SimpleTokenCursor clone = cursor.clone(); // Accumulate the length of the (non-whitespace) // tokens within this scope. int accumulatedLength = 0; while (clone.moveToNextToken()) { if (clone.isComment()) continue; accumulatedLength += clone.getValue().replaceAll("\\s", "").length(); if (clone.currentType().equals("text")) commaCount += StringUtil.countMatches( clone.currentValue(), ','); // If we encounter an (anonymous) function token, or an // opening brace, we prefer not inserting newlines (to preserve // structures like: // lapply(foo, function(x) { ... }) // tryCatch({ if (clone.currentValue().equals("function")) if (clone.previousSignificantToken().getValue().contains(",")) overrideNewlineInsertionAsFalse = true; if (clone.currentValue().equals("{")) { SimpleTokenCursor peek = clone.clone(); if (peek.moveToPreviousSignificantToken()) if (peek.isLeftBrace()) overrideNewlineInsertionAsFalse = true; } // If we encounter an '=', presumedly // this is for a named function call. if (clone.currentValue().equals("=")) { equalsCount++; // If there is a function token ahead of the '=', we prefer // inserting newlines after braces, so that function objects // assigned within lists (or function calls) are placed on // their own line, e.g. // foo = list( // y = function(...) { ... } if (clone.moveToNextSignificantToken()) { if (clone.currentValue().equals("function")) { newlineAfterBrace = true; newlineAfterComma = true; continue; } } } // If we encounter a '{' or '[', skip over -- we don't want to // enumerate things in 'child' scopes. if (clone.currentValue().equals("{") || clone.currentValue().equals("[")) { clone.fwdToMatchingToken(); continue; } // If we encounter a '(', we will want to accumulate the length // of tokens in that scope. This, used alongside the nesting level, // helps us infer the appropriate place to insert newlines when // within nested function calls. if (clone.currentValue().equals("(")) { if (clone.moveToPreviousSignificantToken()) { // For keywords, we prefer not accumulating -- this helps us // ensure we don't insert unnecessary newlines within // 'for', 'if', 'while' statements and the like. boolean isKeyword = clone.isKeyword(); clone.moveToNextSignificantToken(); if (isKeyword) clone.fwdToMatchingToken(); else { MutableInteger counter = new MutableInteger(0); clone.fwdToMatchingToken(counter); accumulatedLength += counter.get(); } } continue; } // If we find the associated closing paren, and we're not at the // top level, break. (The top level cursor gets to iterate over // the entire scope, sending out recursive searches as we encounter // opening parens. if (!topLevel && clone.currentValue().equals(closer)) break; } // If this is a '{', and the immediately previous token is a ')', // insert some whitespace. // TODO: Allow preferences e.g. 1TBS, always newline before brace, etc? if (startValue.equals("{")) { if (cursor.peek(-1).currentValue().equals(")")) cursor.peek(-1).setValue(") "); } // Heuristically decide if we want to insert newlines after // commas, parens. We 'score' whether we would like to insert // newlines after commas, and after braces. int commaScore = commaCount == 0 ? 0 : (commaCount - 1) * 15; // Within a function argument list, we almost always want to insert // newlines after commas, expect for very short function argument // lists. if (prevSignificantValue.equals("function")) commaScore += 20; // For scopes containing many `=`, we typically prefer inserting a // newline following a '('. int equalsScore = equalsCount == 0 ? 0 : (equalsCount - 1) * 20; /* Debug.logToConsole("Accumulated length: " + accumulatedLength); Debug.logToConsole("Root state: " + rootState); Debug.logToConsole("Paren Nest level: " + parenNestLevel); Debug.logToConsole("Brace Nest level: " + braceNestLevel); Debug.logToConsole("Comma count: " + commaCount); Debug.logToConsole("Equals count: " + equalsCount); Debug.logToConsole("Cursor value: " + cursor.currentValue()); Debug.logToConsole("Previous value: " + cursor.previousSignificantToken().getValue()); Debug.logToConsole("Comma Score: " + commaScore); Debug.logToConsole("Equals score: " + equalsScore); */ if (!rootState && startValue.equals("(")) { if (accumulatedLength + commaScore + equalsScore + parenNestLevel * 20 + braceNestLevel * docDisplay_.getTabSize() >= 80) { newlineAfterBrace = true; parenNestLevel = 0; } if (accumulatedLength + commaScore + equalsScore + braceNestLevel * docDisplay_.getTabSize() >= 60) newlineAfterComma = true; } // If the previous token is a control-flow keyword, override the // 'newlineAfterParen' behaviour. We almost always prefer e.g. // over if (cursor.moveToPreviousSignificantToken()) { if (cursor.isControlFlowKeyword()) newlineAfterBrace = false; // Special casing for tryCatch -- we prefer newlines everywhere. if (cursor.currentValue().equals("tryCatch") && accumulatedLength >= 20) { newlineAfterBrace = true; newlineAfterComma = true; } cursor.moveToNextSignificantToken(); } if (overrideNewlineInsertionAsFalse) { newlineAfterComma = false; newlineAfterBrace = false; } SimpleTokenCursor peekFwd = cursor.peek(1); // Always insert newlines following '{'. // TODO: Allow very compact single line functions? if (startValue.equals("{")) { if (cursor.peek(1).currentValue().indexOf('\n') == -1) cursor.setValue("{\n"); } // Otherwise, use the heuristics. Note that it is okay to // collect multiple braces on one line, e.g. // apple(banana(cherry(danish( // so we do not want to indiscriminately insert newlines after // all parens. else if (newlineAfterBrace) { if (!rootState && !peekFwd.isLeftBrace() && !peekFwd.isRightBrace() && peekFwd.getValue().indexOf('\n') == -1) cursor.setValue(opener + "\n"); } else if (!rootState) peekFwd.trimWhitespaceFwd(); // Now, walk through and replace tokens with appropriately white-spaced // versions. while (cursor.moveToNextToken()) { if (cursor.isComment()) continue; // Bail when we find a closing paren if (!rootState && cursor.isRightBrace()) break; // Ensure whitespace following 'if' if (cursor.currentValue().equals("if")) cursor.ensureSingleSpaceFollows(); // Ensure newlines around 'naked' else if (cursor.currentValue().equals("else")) { if (!cursor.previousSignificantToken().getValue().equals("}")) cursor.ensureNewlinePreceeds(); String nextValue = cursor.nextSignificantToken().getValue(); if (!(nextValue.equals("{") || nextValue.equals("if"))) cursor.ensureNewlineFollows(); continue; } // Ensure spaces around operators. if (cursor.isOperator()) { String value = cursor.currentValue(); // Prefer newlines after comparison operators within 'if' // statements when the enclosed selection is long if (prevSignificantValue.equals("if")) { if (accumulatedLength >= 20 && value.equals("&&") || value.equals("||") || value.equals("&") || value.equals("|")) { if (cursor.peek(1).currentValue().indexOf('\n') == -1) cursor.setValue(cursor.currentValue() + "\n"); } } else if (value.equals("$") || value.equals("@") || value.equals(":") || value.equals("::") || value.equals(":::")) { cursor.peek(-1).trimWhitespaceBwd(); cursor.peek(1).trimWhitespaceFwd(); } else { // Unary operators are tricky, especially '-'. We need to make // sure that we don't e.g. transform this: // if (- x < - y) // into // if (-x <- y) // for example. if (value.equals("-") || value.equals("+") || value.equals("!")) { // Figure out if the current token is binary or unary. SimpleTokenCursor previousCursor = cursor.clone(); previousCursor.moveToPreviousSignificantToken(); SimpleTokenCursor nextCursor = cursor.clone(); nextCursor.moveToNextSignificantToken(); boolean isBinary = (previousCursor.isRightBrace() || previousCursor.currentType().indexOf("identifier") != -1 || previousCursor.currentType().indexOf("constant") != -1) && (nextCursor.isLeftBrace() || nextCursor.currentType().indexOf("operator") == -1 || nextCursor.currentType().indexOf("constant") != -1); // Binary operators should have whitespace surrounding. if (isBinary) { cursor.ensureWhitespaceFollows(); cursor.ensureWhitespacePreceeds(); } // Unary operators should have no whitespace after the token, // but __may__ have whitespace before; e.g. if the previous // significant token is an operator. In other words, // only trim whitespace if that token is not an operator. else { cursor.peek(1).trimWhitespaceFwd(); if (previousCursor.currentType().indexOf("operator") == -1) { cursor.peek(-1).trimWhitespaceBwd(); } } } // Regular case -- ensure whitespace surrounds binary operators. else { cursor.ensureWhitespaceFollows(); cursor.ensureWhitespacePreceeds(); } } } // Ensure spaces, or newlines, after commas, if so desired. if (cursor.currentType().equals("text")) { if (newlineAfterComma && cursor.peek(1).currentValue().indexOf('\n') == -1) { cursor.setValue( cursor.currentValue().replaceAll(",(?!\\n)", ",\n")); } else if (!newlineAfterComma && !cursor.peek(1).isWhitespaceOrNewline()) { cursor.setValue(cursor.getValue().replaceAll(",[\\s\\n]*", ", ")); } // Transform semi-colons into newlines. // TODO: Too destructive? cursor.setValue(cursor.getValue().replaceAll(";+\\s*(?!\\n)", "\n")); } // If we encounter an opening paren, recurse a new token cursor within, // and step over the block. This ensures that indentation rules are // consistent within a particular scope. if (cursor.currentValue().equals("{") || cursor.currentValue().equals("(") || cursor.currentValue().equals("[") || cursor.currentValue().equals("[[")) { // If we encounter a non-paren opener, this implies that we can // reset the function nesting level. if (!startValue.equals("(")) parenNestLevel = 0; // Otherwise, if we inserted newlines after parens for this // block, reset the nest level else { if (newlineAfterBrace) parenNestLevel = 0; } // Increment the nest level for non-keyword '(' calls int incrementParenNest = startValue.equals("(") && !beforeStartCursor.isControlFlowKeyword() ? 1 : 0; // Update brace nest level int incrementBraceNest = cursor.currentValue().equals("{") ? 1 : 0; SimpleTokenCursor recursingCursor = cursor.clone(); boolean success = cursor.fwdToMatchingToken(); // Signal children scopes whether we'd prefer them to insert // newlines. TODO: less magic numbers doInsertPrettyNewlines( recursingCursor, recursingCursor.currentValue(), recursingCursor.getComplement(recursingCursor.currentValue()), parenNestLevel + incrementParenNest, braceNestLevel + incrementBraceNest, false); // If we weren't able to move the current active cursor to a // matching token, give up. This implies a different recursing // token will eventually hit the end of the token stream. if (!success) return; } } // If we ended on a ')' in e.g. // function(a, b) a // that is, a function without an opening brace, ensure // a newline following the closing paren. // Similar logic applies for e.g. // if (foo) bar if (cursor.currentValue().equals(")") && beforeStartCursor.isControlFlowKeyword() && !cursor.nextSignificantToken().getValue().equals("{")) { cursor.ensureNewlineFollows(); } // If we ended on a ')', maybe insert newline before if (cursor.currentValue().equals(closer)) { SimpleTokenCursor peek = cursor.peek(-1); if (newlineAfterBrace || cursor.currentValue().equals("}")) { if (peek.currentValue().indexOf('\n') == -1) peek.setValue(peek.currentValue() + "\n"); } // Otherwise, ensure no whitespace before the token else peek.trimWhitespaceBwd(); } } void insertPrettyNewlines() { AceEditor editor = (AceEditor) docDisplay_; if (editor != null) { String selectionText = docDisplay_.getSelectionValue(); // Tokenize the selection and walk through and replace Tokenizer tokenizer = editor.getSession().getMode().getTokenizer(); ArrayList<Token> tokens = tokenizer.tokenize(selectionText); SimpleTokenCursor cursor = new SimpleTokenCursor(tokens); // Set the initial state -- we recurse every time we encounter // an opening paren, so check for that initially. String lhs = ""; String rhs = ""; if (cursor.isLeftBrace()) { lhs = cursor.currentValue(); rhs = cursor.getComplement(lhs); } // TODO: Figure out current nesting level for the // active selection. doInsertPrettyNewlines(cursor, lhs, rhs, 0, 0, true); // Build the replacement from the modified token set StringBuilder builder = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) builder.append(tokens.get(i).getValue()); String replacement = builder.toString(); // Trim off trailing whitespace replacement = replacement.replaceAll("[ \\t]*\\n", "\n"); replacement = replacement.replaceAll("\\n+$", "\n"); docDisplay_.replaceSelection(replacement); docDisplay_.reindent(docDisplay_.getSelectionRange()); } } void alignAssignment() { InputEditorSelection initialSelection = docDisplay_.getSelection(); ArrayList<Pair<Integer, Integer>> ranges = getAlignmentRanges(); if (ranges.isEmpty()) return; for (Pair<Integer, Integer> range : ranges) doAlignAssignment(range.first, range.second); docDisplay_.setSelection( initialSelection.extendToLineStart().extendToLineEnd()); } @Handler void onCheckSpelling() { spelling_.checkSpelling(); } @Handler void onDebugDumpContents() { view_.debug_dumpContents(); } @Handler void onDebugImportDump() { view_.debug_importDump(); } @Handler void onReopenSourceDocWithEncoding() { withChooseEncoding( docUpdateSentinel_.getEncoding(), new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.reopenWithEncoding(encoding); } }); } @Handler void onSaveSourceDoc() { saveThenExecute(null, postSaveCommand()); } @Handler void onSaveSourceDocAs() { saveNewFile(docUpdateSentinel_.getPath(), null, postSaveCommand()); } @Handler void onSaveSourceDocWithEncoding() { withChooseEncoding( StringUtil.firstNotNullOrEmpty(new String[] { docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue(), session_.getSessionInfo().getSystemEncoding() }), new CommandWithArg<String>() { public void execute(String encoding) { saveThenExecute(encoding, postSaveCommand()); } }); } @Handler void onPrintSourceDoc() { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay_.print(); } }); } @Handler void onVcsFileDiff() { Command showDiffCommand = new Command() { @Override public void execute() { events_.fireEvent(new ShowVcsDiffEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } }; if (dirtyState_.getValue()) saveWithPrompt(showDiffCommand, null); else showDiffCommand.execute(); } @Handler void onVcsFileLog() { events_.fireEvent(new ShowVcsHistoryEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } @Handler void onVcsFileRevert() { events_.fireEvent(new VcsRevertFileEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } @Handler void onVcsViewOnGitHub() { fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType.View); } @Handler void onVcsBlameOnGitHub() { fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType.Blame); } private void fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType type) { FileSystemItem file = FileSystemItem.createFile(docUpdateSentinel_.getPath()); if (docDisplay_.getSelectionValue().length() > 0) { int start = docDisplay_.getSelectionStart().getRow() + 1; int end = docDisplay_.getSelectionEnd().getRow() + 1; events_.fireEvent(new VcsViewOnGitHubEvent( new GitHubViewRequest(file, type, start, end))); } else { events_.fireEvent(new VcsViewOnGitHubEvent( new GitHubViewRequest(file, type))); } } @Handler void onExtractLocalVariable() { if (!isCursorInRMode()) { showRModeWarning("Extract Variable"); return; } docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); final String refactoringName = "Extract local variable"; final String pleaseSelectCodeMessage = "Please select the code to " + "extract into a variable."; if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, initialSelection)) return; docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, code)) return; // get the first line of the selection and calculate it's indentation String firstLine = docDisplay_.getLine( docDisplay_.getSelectionStart().getRow()); final String indentation = extractIndentation(firstLine); // used to parse the code server_.detectFreeVars(code, new RefactorServerRequestCallback(refactoringName) { @Override void doExtract(JsArrayString response) { globalDisplay_.promptForText( refactoringName, "Variable Name", "", new OperationWithInput<String>() { public void execute(String input) { final String extractedCode = indentation + input.trim() + " <- " + code + "\n"; InputEditorPosition insertPosition = docDisplay_ .getSelection() .extendToLineStart() .getStart(); docDisplay_.replaceSelection( input.trim()); docDisplay_.insertCode( insertPosition, extractedCode); } } ); } } ); } private void showRModeWarning(String command) { globalDisplay_.showMessage(MessageDisplay.MSG_WARNING, "Command Not Available", "The "+ command + " command is " + "only valid for R code chunks."); return; } @Handler void onExtractFunction() { if (!isCursorInRMode()) { showRModeWarning("Extract Function"); return; } docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); final String refactoringName = "Extract Function"; final String pleaseSelectCodeMessage = "Please select the code to " + "extract into a function."; if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, initialSelection)) return; docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, code)) return; final String indentation = extractIndentation(code); server_.detectFreeVars(code, new RefactorServerRequestCallback(refactoringName) { @Override void doExtract(final JsArrayString response) { globalDisplay_.promptForText( refactoringName, "Function Name", "", new OperationWithInput<String>() { public void execute(String input) { String prefix; if (docDisplay_.getSelectionOffset(true) == 0) prefix = ""; else prefix = "\n"; String args = response != null ? response.join(", ") : ""; docDisplay_.replaceSelection( prefix + indentation + input.trim() + " <- " + "function (" + args + ") {\n" + StringUtil.indent(code, " ") + "\n" + indentation + "}"); } } ); } } ); } private boolean checkSelectionAndAlert(String refactoringName, String pleaseSelectCodeMessage, String selection) { if (isSelectionValueEmpty(selection)) { globalDisplay_.showErrorMessage(refactoringName, pleaseSelectCodeMessage); return true; } return false; } private String extractIndentation(String code) { Pattern leadingWhitespace = Pattern.create("^(\\s*)"); Match match = leadingWhitespace.match(code, 0); return match == null ? "" : match.getGroup(1); } private boolean isSelectionValueEmpty(String selection) { return selection == null || selection.trim().length() == 0; } @Handler void onJumpToMatching() { docDisplay_.jumpToMatching(); } @Handler void onCommentUncomment() { if (isCursorInTexMode()) doCommentUncomment("%"); else if (isCursorInRMode()) doCommentUncomment(" else if (fileType_.isCpp()) doCommentUncomment(" } private void doCommentUncomment(String c) { InputEditorSelection initialSelection = docDisplay_.getSelection(); String indent = ""; boolean singleLineAction = initialSelection.isEmpty() || initialSelection.getStart().getLine().equals( initialSelection.getEnd().getLine()); if (singleLineAction) { String currentLine = docDisplay_.getCurrentLine(); Match firstCharMatch = Pattern.create("([^\\s])").match(currentLine, 0); if (firstCharMatch != null) { indent = currentLine.substring(0, firstCharMatch.getIndex()); } else { indent = currentLine; } } boolean selectionCollapsed = docDisplay_.isSelectionCollapsed(); docDisplay_.fitSelectionToLines(true); String selection = docDisplay_.getSelectionValue(); // If any line's first non-whitespace character is not #, then the whole // selection should be commented. Exception: If the whole selection is // whitespace, then we comment out the whitespace. Match match = Pattern.create("^\\s*[^" + c + "\\s]").match(selection, 0); boolean uncomment = match == null && selection.trim().length() != 0; if (uncomment) { String prefix = c + "'?"; selection = selection.replaceAll("((^|\\n)\\s*)" + prefix + " ?", "$1"); } else { // Check to see if we're commenting something that looks like Roxygen Pattern pattern = Pattern.create("(^\\s*@)|(\\n\\s*@)"); boolean isRoxygen = pattern.match(selection, 0) != null; if (isRoxygen) c = c + "'"; if (singleLineAction) selection = indent + c + " " + selection.replaceAll("^\\s*", ""); else { selection = c + " " + selection.replaceAll("\\n", "\n" + c + " "); // If the selection ends at the very start of a line, we don't want // to comment out that line. This enables Shift+DownArrow to select // one line at a time. if (selection.endsWith("\n" + c + " ")) selection = selection.substring(0, selection.length() - 1 - c.length()); } } docDisplay_.replaceSelection(selection); if (selectionCollapsed) docDisplay_.collapseSelection(true); if (singleLineAction) { int offset = c.length() + 1; String line = docDisplay_.getCurrentLine(); Match matchPos = Pattern.create("([^\\s])").match(line, 0); InputEditorSelection newSelection; if (uncomment) { if (initialSelection.isEmpty()) { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(-offset, true), initialSelection.getStart().movePosition(-offset, true)); } else { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(matchPos.getIndex(), false), initialSelection.getEnd().movePosition(-offset, true)); } } else { if (initialSelection.isEmpty()) { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(offset, true), initialSelection.getStart().movePosition(offset, true)); } else { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(matchPos.getIndex() + offset, false), initialSelection.getEnd().movePosition(offset, true)); } } docDisplay_.setSelection(newSelection); } docDisplay_.focus(); } @Handler void onReindent() { docDisplay_.reindent(); docDisplay_.focus(); } @Handler void onReflowComment() { if (DocumentMode.isSelectionInRMode(docDisplay_)) doReflowComment("( else if (DocumentMode.isSelectionInCppMode(docDisplay_)) { String currentLine = docDisplay_.getLine( docDisplay_.getCursorPosition().getRow()); if (currentLine.startsWith(" *")) doReflowComment("( \\*[^/])", false); else doReflowComment("( } else if (DocumentMode.isSelectionInTexMode(docDisplay_)) doReflowComment("(%)"); } @Handler void onDebugBreakpoint() { docDisplay_.toggleBreakpointAtCursor(); } @Handler void onRsconnectDeploy() { events_.fireEvent(new RSConnectActionEvent( RSConnectActionEvent.ACTION_TYPE_DEPLOY, docUpdateSentinel_.getPath())); } @Handler void onRsconnectConfigure() { events_.fireEvent(new RSConnectActionEvent( RSConnectActionEvent.ACTION_TYPE_CONFIGURE, docUpdateSentinel_.getPath())); } @Handler void onEditRmdFormatOptions() { rmarkdownHelper_.withRMarkdownPackage( "Editing R Markdown options", false, new CommandWithArg<RMarkdownContext>() { @Override public void execute(RMarkdownContext arg) { showFrontMatterEditor(); } }); } private void showFrontMatterEditor() { final String yaml = getRmdFrontMatter(); if (yaml == null) { globalDisplay_.showErrorMessage("Edit Format Failed", "Can't find the YAML front matter for this document. Make " + "sure the front matter is enclosed by lines containing only " + "three dashes: return; } rmarkdownHelper_.convertFromYaml(yaml, new CommandWithArg<RmdYamlData>() { @Override public void execute(RmdYamlData arg) { String errCaption = "Edit Format Failed"; String errMsg = "The YAML front matter in this document could not be " + "successfully parsed. This parse error needs to be " + "resolved before format options can be edited."; if (arg == null) { globalDisplay_.showErrorMessage(errCaption, errMsg); } else if (!arg.parseSucceeded()) { // try to find where the YAML segment begins in the document // so we can show an adjusted line number for the error int numLines = docDisplay_.getRowCount(); int offsetLine = 0; String separator = RmdFrontMatter.FRONTMATTER_SEPARATOR.trim(); for (int i = 0; i < numLines; i++) { if (docDisplay_.getLine(i).equals(separator)) { offsetLine = i + 1; break; } } globalDisplay_.showErrorMessage(errCaption, errMsg + "\n\n" + arg.getOffsetParseError(offsetLine)); } else { showFrontMatterEditorDialog(yaml, arg); } } }); } private void showFrontMatterEditorDialog(String yaml, RmdYamlData data) { RmdSelectedTemplate selTemplate = rmarkdownHelper_.getTemplateFormat(yaml); if (selTemplate == null) { // we don't expect this to happen since we disable the dialog // entry point when we can't find an associated template globalDisplay_.showErrorMessage("Edit Format Failed", "Couldn't determine the format options from the YAML front " + "matter. Make sure the YAML defines a supported output " + "format in its 'output' field."); return; } RmdTemplateOptionsDialog dialog = new RmdTemplateOptionsDialog(selTemplate.template, selTemplate.format, data.getFrontMatter(), getPath() == null ? null : FileSystemItem.createFile(getPath()), selTemplate.isShiny, new OperationWithInput<RmdTemplateOptionsDialog.Result>() { @Override public void execute(RmdTemplateOptionsDialog.Result in) { // when the dialog is completed successfully, apply the new // front matter applyRmdFrontMatter(in); } }, new Operation() { @Override public void execute() { // when the dialog is cancelled, update the view's format list // (to cancel in-place changes) updateRmdFormatList(); } }); dialog.showModal(); } private String getRmdFrontMatter() { return YamlFrontMatter.getFrontMatter(docDisplay_.getCode()); } private void applyRmdFrontMatter(String yaml) { String code = docDisplay_.getCode(); String newCode = YamlFrontMatter.applyFrontMatter(code, yaml); if (!code.equals(newCode)) { docDisplay_.setCode(newCode, true); updateRmdFormatList(); } } private void applyRmdFrontMatter(RmdTemplateOptionsDialog.Result result) { rmarkdownHelper_.frontMatterToYAML(result.frontMatter, result.format, new CommandWithArg<String>() { @Override public void execute(String yaml) { applyRmdFrontMatter(yaml); } }); } private RmdSelectedTemplate getSelectedTemplate() { // try to extract the front matter and ascertain the template to which // it refers String yaml = getRmdFrontMatter(); if (yaml == null) return null; return rmarkdownHelper_.getTemplateFormat(yaml); } private void updateRmdFormatList() { RmdSelectedTemplate selTemplate = getSelectedTemplate(); if (selTemplate == null) { view_.setFormatOptionsVisible(false); return; } else if (selTemplate.isShiny) { view_.setIsShinyFormat(selTemplate.format != null && selTemplate.format.endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)); return; } // we know which template this doc is using--populate the format list // with the formats available in the template String formatUiName = ""; JsArray<RmdTemplateFormat> formats = selTemplate.template.getFormats(); List<String> formatList = new ArrayList<String>(); List<String> valueList = new ArrayList<String>(); List<String> extensionList = new ArrayList<String>(); for (int i = 0; i < formats.length(); i++) { String uiName = formats.get(i).getUiName(); formatList.add(uiName); valueList.add(formats.get(i).getName()); extensionList.add(formats.get(i).getExtension()); if (formats.get(i).getName().equals(selTemplate.format)) { formatUiName = uiName; } } view_.setFormatOptions(fileType_, formatList, valueList, extensionList, formatUiName); } private void setRmdFormat(String formatName) { RmdSelectedTemplate selTemplate = getSelectedTemplate(); if (selTemplate == null) return; // if this is the current format, we don't need to change the front matter if (selTemplate.format.equals(formatName)) { renderRmd(); return; } rmarkdownHelper_.setOutputFormat(getRmdFrontMatter(), formatName, new CommandWithArg<String>() { @Override public void execute(String yaml) { if (yaml != null) applyRmdFrontMatter(yaml); // re-knit the document renderRmd(); } }); } void doReflowComment(String commentPrefix) { doReflowComment(commentPrefix, true); } void doReflowComment(String commentPrefix, boolean multiParagraphIndent) { docDisplay_.focus(); InputEditorSelection originalSelection = docDisplay_.getSelection(); InputEditorSelection selection = originalSelection; if (selection.isEmpty()) { selection = selection.growToIncludeLines("^\\s*" + commentPrefix + ".*$"); } else { selection = selection.shrinkToNonEmptyLines(); selection = selection.extendToLineStart(); selection = selection.extendToLineEnd(); } if (selection.isEmpty()) return; reflowComments(commentPrefix, multiParagraphIndent, selection, originalSelection.isEmpty() ? originalSelection.getStart() : null); } private Position selectionToPosition(InputEditorPosition pos) { return docDisplay_.selectionToPosition(pos); } private void reflowComments(String commentPrefix, final boolean multiParagraphIndent, InputEditorSelection selection, final InputEditorPosition cursorPos) { String code = docDisplay_.getCode(selection); String[] lines = code.split("\n"); String prefix = StringUtil.getCommonPrefix(lines, true); Pattern pattern = Pattern.create("^\\s*" + commentPrefix + "+('?)\\s*"); Match match = pattern.match(prefix, 0); // Selection includes non-comments? Abort. if (match == null) return; prefix = match.getValue(); final boolean roxygen = match.hasGroup(1); int cursorRowIndex = 0; int cursorColIndex = 0; if (cursorPos != null) { cursorRowIndex = selectionToPosition(cursorPos).getRow() - selectionToPosition(selection.getStart()).getRow(); cursorColIndex = Math.max(0, cursorPos.getPosition() - prefix.length()); } final WordWrapCursorTracker wwct = new WordWrapCursorTracker( cursorRowIndex, cursorColIndex); int maxLineLength = prefs_.printMarginColumn().getValue() - prefix.length(); WordWrap wordWrap = new WordWrap(maxLineLength, false) { @Override protected boolean forceWrapBefore(String line) { String trimmed = line.trim(); if (roxygen && trimmed.startsWith("@") && !trimmed.startsWith("@@")) { // Roxygen tags always need to be at the start of a line. If // there is content immediately following the roxygen tag, then // content should be wrapped until the next roxygen tag is // encountered. indent_ = ""; if (TAG_WITH_CONTENTS.match(line, 0) != null) { indentRestOfLines_ = true; } return true; } // empty line disables indentation else if (!multiParagraphIndent && (line.trim().length() == 0)) { indent_ = ""; indentRestOfLines_ = false; } return super.forceWrapBefore(line); } @Override protected void onChunkWritten(String chunk, int insertionRow, int insertionCol, int indexInOriginalString) { if (indentRestOfLines_) { indentRestOfLines_ = false; indent_ = " "; // TODO: Use real indent from settings } wwct.onChunkWritten(chunk, insertionRow, insertionCol, indexInOriginalString); } private boolean indentRestOfLines_ = false; private Pattern TAG_WITH_CONTENTS = Pattern.create("@\\w+\\s+[^\\s]"); }; for (String line : lines) { String content = line.substring(Math.min(line.length(), prefix.length())); if (content.matches("^\\s*\\@examples\\b.*$")) wordWrap.setWrappingEnabled(false); else if (content.trim().startsWith("@")) wordWrap.setWrappingEnabled(true); wwct.onBeginInputRow(); wordWrap.appendLine(content); } String wrappedString = wordWrap.getOutput(); StringBuilder finalOutput = new StringBuilder(); for (String line : StringUtil.getLineIterator(wrappedString)) finalOutput.append(prefix).append(line).append("\n"); // Remove final \n if (finalOutput.length() > 0) finalOutput.deleteCharAt(finalOutput.length()-1); String reflowed = finalOutput.toString(); docDisplay_.setSelection(selection); if (!reflowed.equals(code)) { docDisplay_.replaceSelection(reflowed); } if (cursorPos != null) { if (wwct.getResult() != null) { int row = wwct.getResult().getY(); int col = wwct.getResult().getX(); row += selectionToPosition(selection.getStart()).getRow(); col += prefix.length(); Position pos = Position.create(row, col); docDisplay_.setSelection(docDisplay_.createSelection(pos, pos)); } else { docDisplay_.collapseSelection(false); } } } @Handler void onExecuteCodeWithoutFocus() { codeExecution_.executeSelection(false); } @Handler void onExecuteCodeWithoutMovingCursor() { if (docDisplay_.isFocused()) codeExecution_.executeSelection(true, false); else if (view_.isAttached()) view_.findSelectAll(); } @Handler void onExecuteCode() { codeExecution_.executeSelection(true); } @Override public String extractCode(DocDisplay docDisplay, Range range) { Scope sweaveChunk = null; if (fileType_.canExecuteChunks()) sweaveChunk = scopeHelper_.getCurrentSweaveChunk(range.getStart()); String code = sweaveChunk != null ? scopeHelper_.getSweaveChunkText(sweaveChunk, range) : docDisplay_.getCode(range.getStart(), range.getEnd()); return code; } @Handler void onExecuteAllCode() { sourceActiveDocument(true); } @Handler void onExecuteToCurrentLine() { docDisplay_.focus(); int row = docDisplay_.getSelectionEnd().getRow(); int col = docDisplay_.getLength(row); codeExecution_.executeRange(Range.fromPoints(Position.create(0, 0), Position.create(row, col))); } @Handler void onExecuteFromCurrentLine() { docDisplay_.focus(); int startRow = docDisplay_.getSelectionStart().getRow(); int startColumn = 0; Position start = Position.create(startRow, startColumn); codeExecution_.executeRange(Range.fromPoints(start, endPosition())); } @Handler void onExecuteCurrentFunction() { docDisplay_.focus(); // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); Scope currentFunction = docDisplay_.getCurrentFunction(); // Check if we're at the top level (i.e. not in a function), or in // an unclosed function if (currentFunction == null || currentFunction.getEnd() == null) return; Position start = currentFunction.getPreamble(); Position end = currentFunction.getEnd(); codeExecution_.executeRange(Range.fromPoints(start, end)); } @Handler void onExecuteCurrentSection() { docDisplay_.focus(); // Determine the current section. docDisplay_.getScopeTree(); Scope currentSection = docDisplay_.getCurrentSection(); if (currentSection == null) return; // Determine the start and end of the section Position start = currentSection.getBodyStart(); if (start == null) start = Position.create(0, 0); Position end = currentSection.getEnd(); if (end == null) end = endPosition(); codeExecution_.executeRange(Range.fromPoints(start, end)); } private Position endPosition() { int endRow = Math.max(0, docDisplay_.getRowCount() - 1); int endColumn = docDisplay_.getLength(endRow); return Position.create(endRow, endColumn); } @Handler void onInsertChunk() { Position pos = moveCursorToNextInsertLocation(); InsertChunkInfo insertChunkInfo = docDisplay_.getInsertChunkInfo(); if (insertChunkInfo != null) { docDisplay_.insertCode(insertChunkInfo.getValue(), false); Position cursorPosition = insertChunkInfo.getCursorPosition(); docDisplay_.setCursorPosition(Position.create( pos.getRow() + cursorPosition.getRow(), cursorPosition.getColumn())); docDisplay_.focus(); } else { assert false : "Mode did not have insertChunkInfo available"; } } @Handler void onInsertSection() { globalDisplay_.promptForText( "Insert Section", "Section label:", "", new OperationWithInput<String>() { @Override public void execute(String label) { // move cursor to next insert location Position pos = moveCursorToNextInsertLocation(); // truncate length to print margin - 5 int printMarginColumn = prefs_.printMarginColumn().getValue(); int length = printMarginColumn - 5; // truncate label to maxLength - 10 (but always allow at // least 20 chars for the label) int maxLabelLength = length - 10; maxLabelLength = Math.max(maxLabelLength, 20); if (label.length() > maxLabelLength) label = label.substring(0, maxLabelLength-1); // prefix String prefix = "# " + label + " "; // fill to maxLength (bit ensure at least 4 fill characters // so the section parser is sure to pick it up) StringBuffer sectionLabel = new StringBuffer(); sectionLabel.append("\n"); sectionLabel.append(prefix); int fillChars = length - prefix.length(); fillChars = Math.max(fillChars, 4); for (int i=0; i<fillChars; i++) sectionLabel.append("-"); sectionLabel.append("\n\n"); // insert code and move cursor docDisplay_.insertCode(sectionLabel.toString(), false); docDisplay_.setCursorPosition(Position.create(pos.getRow() + 3, 0)); docDisplay_.focus(); } }); } private Position moveCursorToNextInsertLocation() { docDisplay_.collapseSelection(true); if (!docDisplay_.moveSelectionToBlankLine()) { int lastRow = docDisplay_.getRowCount(); int lastCol = docDisplay_.getLength(lastRow); Position endPos = Position.create(lastRow, lastCol); docDisplay_.setCursorPosition(endPos); docDisplay_.insertCode("\n", false); } return docDisplay_.getCursorPosition(); } @Handler void onExecuteCurrentChunk() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); executeSweaveChunk(scopeHelper_.getCurrentSweaveChunk(), false); } @Handler void onExecuteNextChunk() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); executeSweaveChunk(scopeHelper_.getNextSweaveChunk(), true); } @Handler void onExecutePreviousChunks() { withPreservedSelection(new Command() { @Override public void execute() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); // see if there is a region of code in the current chunk to execute Range currentChunkRange = null; Scope currentScope = scopeHelper_.getCurrentSweaveChunk(); if (currentScope != null) { // get end position (always execute the current line unless // the cursor is at the beginning of it) Position endPos = docDisplay_.getCursorPosition(); if (endPos.getColumn() >0) endPos = Position.create(endPos.getRow()+1, 0); currentChunkRange = Range.fromPoints(currentScope.getBodyStart(), endPos); } // execute the previous chunks Scope[] previousScopes = scopeHelper_.getPreviousSweaveChunks(); for (Scope scope : previousScopes) executeSweaveChunk(scope, false); // execute code from the current chunk if we have it if (currentChunkRange != null) codeExecution_.executeRange(currentChunkRange); } }); } private void withPreservedSelection(Command command) { // save the selection and scroll position for restoration int scrollPosition = docDisplay_.getScrollTop(); Position start = docDisplay_.getSelectionStart(); Position end = docDisplay_.getSelectionEnd(); AnchoredSelection anchoredSelection = docDisplay_.createAnchoredSelection(start,end); // execute the command command.execute(); // restore the selection and scroll position anchoredSelection.apply(); docDisplay_.scrollToY(scrollPosition); } private void executeSweaveChunk(Scope chunk, boolean scrollNearTop) { if (chunk == null) return; Range range = scopeHelper_.getSweaveChunkInnerRange(chunk); if (scrollNearTop) { docDisplay_.navigateToPosition( SourcePosition.create(range.getStart().getRow(), range.getStart().getColumn()), true); } docDisplay_.setSelection( docDisplay_.createSelection(range.getStart(), range.getEnd())); if (!range.isEmpty()) { codeExecution_.setLastExecuted(range.getStart(), range.getEnd()); String code = scopeHelper_.getSweaveChunkText(chunk); events_.fireEvent(new SendToConsoleEvent(code, true)); docDisplay_.collapseSelection(true); } } @Handler void onJumpTo() { statusBar_.getScope().click(); } @Handler void onGoToLine() { globalDisplay_.promptForInteger( "Go to Line", "Enter line number:", null, new ProgressOperationWithInput<Integer>() { @Override public void execute(Integer line, ProgressIndicator indicator) { indicator.onCompleted(); line = Math.max(1, line); line = Math.min(docDisplay_.getRowCount(), line); docDisplay_.navigateToPosition( SourcePosition.create(line-1, 0), true); } }, null); } @Handler void onCodeCompletion() { docDisplay_.codeCompletion(); } @Handler void onGoToHelp() { docDisplay_.goToHelp(); } @Handler void onGoToFunctionDefinition() { docDisplay_.goToFunctionDefinition(); } @Handler public void onSetWorkingDirToActiveDoc() { // get path String activeDocPath = docUpdateSentinel_.getPath(); if (activeDocPath != null) { FileSystemItem wdPath = FileSystemItem.createFile(activeDocPath).getParentPath(); consoleDispatcher_.executeSetWd(wdPath, true); } else { globalDisplay_.showMessage( MessageDialog.WARNING, "Source File Not Saved", "The currently active source file is not saved so doesn't " + "have a directory to change into."); return; } } @SuppressWarnings("unused") private String stangle(String sweaveStr) { ScopeList chunks = new ScopeList(docDisplay_); chunks.selectAll(ScopeList.CHUNK); StringBuilder code = new StringBuilder(); for (Scope chunk : chunks) { String text = scopeHelper_.getSweaveChunkText(chunk); code.append(text); if (text.length() > 0 && text.charAt(text.length()-1) != '\n') code.append('\n'); } return code.toString(); } @Handler void onSourceActiveDocument() { sourceActiveDocument(false); } @Handler void onSourceActiveDocumentWithEcho() { sourceActiveDocument(true); } private void sourceActiveDocument(final boolean echo) { docDisplay_.focus(); // If the document being sourced is a Shiny file, run the app instead. if (fileType_.isR() && extendedType_.equals("shiny")) { runShinyApp(); return; } // If the document being sourced is a script then use that codepath if (fileType_.isScript()) { runScript(); return; } // If the document is previewable if (fileType_.canPreviewFromR()) { previewFromR(); return; } String code = docDisplay_.getCode(); if (code != null && code.trim().length() > 0) { // R 2.14 prints a warning when sourcing a file with no trailing \n if (!code.endsWith("\n")) code = code + "\n"; boolean sweave = fileType_.canCompilePDF() || fileType_.canKnitToHTML() || fileType_.isRpres(); RnwWeave rnwWeave = compilePdfHelper_.getActiveRnwWeave(); final boolean forceEcho = sweave && (rnwWeave != null) ? rnwWeave.forceEchoOnExec() : false; // NOTE: we always set echo to true for knitr because knitr doesn't // require print statements so if you don't echo to the console // then you don't see any of the output boolean saveWhenSourcing = fileType_.isCpp() || docDisplay_.hasBreakpoints(); if ((dirtyState_.getValue() || sweave) && !saveWhenSourcing) { server_.saveActiveDocument(code, sweave, compilePdfHelper_.getActiveRnwWeaveName(), new SimpleRequestCallback<Void>() { @Override public void onResponseReceived(Void response) { consoleDispatcher_.executeSourceCommand( "~/.active-rstudio-document", fileType_, "UTF-8", activeCodeIsAscii(), forceEcho ? true : echo, true, docDisplay_.hasBreakpoints()); } }); } else { Command sourceCommand = new Command() { @Override public void execute() { if (docDisplay_.hasBreakpoints()) { hideBreakpointWarningBar(); } consoleDispatcher_.executeSourceCommand( getPath(), fileType_, docUpdateSentinel_.getEncoding(), activeCodeIsAscii(), forceEcho ? true : echo, true, docDisplay_.hasBreakpoints()); } }; if (saveWhenSourcing && (dirtyState_.getValue() || (getPath() == null))) saveThenExecute(null, sourceCommand); else sourceCommand.execute(); } } // update pref if necessary if (prefs_.sourceWithEcho().getValue() != echo) { prefs_.sourceWithEcho().setGlobalValue(echo, true); prefs_.writeUIPrefs(); } } private void runShinyApp() { sourceBuildHelper_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { RStudioGinjector.INSTANCE.getShinyApplication() .launchShinyApplication(getPath()); } }, "Run Shiny Application"); } private void runScript() { saveThenExecute(null, new Command() { @Override public void execute() { String interpreter = fileType_.getScriptInterpreter(); server_.getScriptRunCommand( interpreter, getPath(), new SimpleRequestCallback<String>() { @Override public void onResponseReceived(String cmd) { events_.fireEvent(new SendToConsoleEvent(cmd, true)); } }); } }); } private void previewFromR() { saveThenExecute(null, new Command() { @Override public void execute() { server_.getMinimalSourcePath( getPath(), new SimpleRequestCallback<String>() { @Override public void onResponseReceived(String path) { String cmd = fileType_.createPreviewCommand(path); if (cmd != null) events_.fireEvent(new SendToConsoleEvent(cmd, true)); } }); } }); } private boolean activeCodeIsAscii() { String code = docDisplay_.getCode(); for (int i=0; i< code.length(); i++) { if (code.charAt(i) > 127) return false; } return true; } @Handler void onExecuteLastCode() { docDisplay_.focus(); codeExecution_.executeLastCode(); } @Handler void onMarkdownHelp() { events_.fireEvent(new ShowHelpEvent("help/doc/markdown_help.html")) ; } @Handler void onUsingRMarkdownHelp() { if (extendedType_.equals("rmarkdown")) globalDisplay_.openRStudioLink("using_rmarkdown"); else globalDisplay_.openRStudioLink("using_markdown"); } @Handler void onAuthoringRPresentationsHelp() { globalDisplay_.openRStudioLink("authoring_presentations"); } @Handler void onRcppHelp() { globalDisplay_.openRStudioLink("rcpp_help"); } @Handler void onDebugHelp() { globalDisplay_.openRStudioLink("visual_debugger"); } @Handler void onKnitDocument() { onPreviewHTML(); } @Handler void onPreviewHTML() { // last ditch extended type detection String extendedType = extendedType_; extendedType = rmarkdownHelper_.detectExtendedType(docDisplay_.getCode(), extendedType, fileType_); if (extendedType == "rmarkdown") renderRmd(); else if (fileType_.isRd()) previewRd(); else if (fileType_.isRpres()) previewRpresentation(); else if (fileType_.isR()) onCompileNotebook(); else previewHTML(); } void previewRpresentation() { SessionInfo sessionInfo = session_.getSessionInfo(); if (!fileTypeCommands_.getHTMLCapabiliites().isRMarkdownSupported()) { globalDisplay_.showMessage( MessageDisplay.MSG_WARNING, "Unable to Preview", "R Presentations require the knitr package " + "(version 1.2 or higher)"); return; } PresentationState state = sessionInfo.getPresentationState(); // if we are showing a tutorial then don't allow preview if (state.isTutorial()) { globalDisplay_.showMessage( MessageDisplay.MSG_WARNING, "Unable to Preview", "R Presentations cannot be previewed when a Tutorial " + "is active"); return; } // if this presentation is already showing then just activate if (state.isActive() && state.getFilePath().equals(docUpdateSentinel_.getPath())) { commands_.activatePresentation().execute(); save(); } // otherwise reload else { saveThenExecute(null, new Command() { @Override public void execute() { server_.showPresentationPane(docUpdateSentinel_.getPath(), new VoidServerRequestCallback()); } }); } } void previewRd() { saveThenExecute(null, new Command() { @Override public void execute() { String previewURL = "help/preview?file="; previewURL += URL.encodeQueryString(docUpdateSentinel_.getPath()); events_.fireEvent(new ShowHelpEvent(previewURL)) ; } }); } void renderRmd() { boolean renderSourceOnly = (docUpdateSentinel_.getPath() == null) && !isShinyDoc(); if (renderSourceOnly) { rmarkdownHelper_.renderRMarkdownSource(docDisplay_.getCode(), isShinyDoc()); } else { saveThenExecute(null, new Command() { @Override public void execute() { boolean asTempfile = isPackageDocumentationFile(); rmarkdownHelper_.renderRMarkdown( docUpdateSentinel_.getPath(), docDisplay_.getCursorPosition().getRow() + 1, null, docUpdateSentinel_.getEncoding(), asTempfile, isShinyDoc(), false); } }); } } private boolean isShinyDoc() { try { RmdSelectedTemplate template = getSelectedTemplate(); return (template != null) && template.isShiny; } catch(Exception e) { Debug.log(e.getMessage()); return false; } } void previewHTML() { // validate pre-reqs if (!rmarkdownHelper_.verifyPrerequisites(view_, fileType_)) return; doHtmlPreview(new Provider<HTMLPreviewParams>() { @Override public HTMLPreviewParams get() { return HTMLPreviewParams.create(docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), fileType_.isMarkdown(), fileType_.requiresKnit(), false); } }); } private void doHtmlPreview(final Provider<HTMLPreviewParams> pParams) { // command to show the preview window final Command showPreviewWindowCommand = new Command() { @Override public void execute() { HTMLPreviewParams params = pParams.get(); events_.fireEvent(new ShowHTMLPreviewEvent(params)); } }; // command to run the preview final Command runPreviewCommand = new Command() { @Override public void execute() { final HTMLPreviewParams params = pParams.get(); server_.previewHTML(params, new SimpleRequestCallback<Boolean>()); } }; if (pParams.get().isNotebook()) { saveThenExecute(null, new Command() { @Override public void execute() { generateNotebook(new Command() { @Override public void execute() { showPreviewWindowCommand.execute(); runPreviewCommand.execute(); } }); } }); } // if the document is new and unsaved, then resolve that and then // show the preview window -- it won't activate in web mode // due to popup activation rules but at least it will show up else if (isNewDoc()) { saveThenExecute(null, CommandUtil.join(showPreviewWindowCommand, runPreviewCommand)); } // otherwise if it's dirty then show the preview window first (to // beat the popup blockers) then save & run else if (dirtyState().getValue()) { showPreviewWindowCommand.execute(); saveThenExecute(null, runPreviewCommand); } // otherwise show the preview window then run the preview else { showPreviewWindowCommand.execute(); runPreviewCommand.execute(); } } private void generateNotebook(final Command executeOnSuccess) { // default title String defaultTitle = docUpdateSentinel_.getProperty(NOTEBOOK_TITLE); if (StringUtil.isNullOrEmpty(defaultTitle)) defaultTitle = FileSystemItem.getNameFromPath(docUpdateSentinel_.getPath()); // default author String defaultAuthor = docUpdateSentinel_.getProperty(NOTEBOOK_AUTHOR); if (StringUtil.isNullOrEmpty(defaultAuthor)) { defaultAuthor = prefs_.compileNotebookOptions().getValue().getAuthor(); if (StringUtil.isNullOrEmpty(defaultAuthor)) defaultAuthor = session_.getSessionInfo().getUserIdentity(); } // default type String defaultType = docUpdateSentinel_.getProperty(NOTEBOOK_TYPE); if (StringUtil.isNullOrEmpty(defaultType)) { defaultType = prefs_.compileNotebookOptions().getValue().getType(); if (StringUtil.isNullOrEmpty(defaultType)) defaultType = CompileNotebookOptions.TYPE_DEFAULT; } CompileNotebookOptionsDialog dialog = new CompileNotebookOptionsDialog( getId(), defaultTitle, defaultAuthor, defaultType, new OperationWithInput<CompileNotebookOptions>() { @Override public void execute(CompileNotebookOptions input) { server_.createNotebook( input, new SimpleRequestCallback<CompileNotebookResult>() { @Override public void onResponseReceived(CompileNotebookResult response) { if (response.getSucceeded()) { executeOnSuccess.execute(); } else { globalDisplay_.showErrorMessage( "Unable to Compile Notebook", response.getFailureMessage()); } } }); // save options for this document HashMap<String, String> changedProperties = new HashMap<String, String>(); changedProperties.put(NOTEBOOK_TITLE, input.getNotebookTitle()); changedProperties.put(NOTEBOOK_AUTHOR, input.getNotebookAuthor()); changedProperties.put(NOTEBOOK_TYPE, input.getNotebookType()); docUpdateSentinel_.modifyProperties(changedProperties, null); // save global prefs CompileNotebookPrefs prefs = CompileNotebookPrefs.create( input.getNotebookAuthor(), input.getNotebookType()); if (!CompileNotebookPrefs.areEqual( prefs, prefs_.compileNotebookOptions().getValue())) { prefs_.compileNotebookOptions().setGlobalValue(prefs); prefs_.writeUIPrefs(); } } } ); dialog.showModal(); } @Handler void onCompileNotebook() { if (session_.getSessionInfo().getRMarkdownPackageAvailable()) { saveThenExecute(null, new Command() { @Override public void execute() { rmarkdownHelper_.renderNotebookv2(docUpdateSentinel_); } }); } else { if (!rmarkdownHelper_.verifyPrerequisites("Compile Notebook", view_, FileTypeRegistry.RMARKDOWN)) { return; } doHtmlPreview(new Provider<HTMLPreviewParams>() { @Override public HTMLPreviewParams get() { return HTMLPreviewParams.create(docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), true, true, true); } }); } } @Handler void onCompilePDF() { String pdfPreview = prefs_.pdfPreview().getValue(); boolean showPdf = !pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_NONE); boolean useInternalPreview = pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_RSTUDIO); boolean useDesktopSynctexPreview = pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_DESKTOP_SYNCTEX) && Desktop.isDesktop(); String action = new String(); if (showPdf && !useInternalPreview && !useDesktopSynctexPreview) action = "view_external"; handlePdfCommand(action, useInternalPreview, null); } @Handler void onSynctexSearch() { doSynctexSearch(true); } private void doSynctexSearch(boolean fromClick) { SourceLocation sourceLocation = getSelectionAsSourceLocation(fromClick); if (sourceLocation == null) return; // compute the target pdf FileSystemItem editorFile = FileSystemItem.createFile( docUpdateSentinel_.getPath()); FileSystemItem targetFile = compilePdfHelper_.getTargetFile(editorFile); String pdfFile = targetFile.getParentPath().completePath(targetFile.getStem() + ".pdf"); synctex_.forwardSearch(pdfFile, sourceLocation); } private SourceLocation getSelectionAsSourceLocation(boolean fromClick) { // get doc path (bail if the document is unsaved) String file = docUpdateSentinel_.getPath(); if (file == null) return null; Position selPos = docDisplay_.getSelectionStart(); int line = selPos.getRow() + 1; int column = selPos.getColumn() + 1; return SourceLocation.create(file, line, column, fromClick); } @Handler void onFindReplace() { view_.showFindReplace(true); } @Handler void onFindNext() { view_.findNext(); } @Handler void onFindPrevious() { view_.findPrevious(); } @Handler void onFindSelectAll() { view_.findSelectAll(); } @Handler void onFindFromSelection() { view_.findFromSelection(); } @Handler void onReplaceAndFind() { view_.replaceAndFind(); } @Override public Position search(String regex) { return search(Position.create(0, 0), regex); } @Override public Position search(Position startPos, String regex) { InputEditorSelection sel = docDisplay_.search(regex, false, false, false, false, startPos, null, true); if (sel != null) return docDisplay_.selectionToPosition(sel.getStart()); else return null; } @Handler void onFold() { if (useScopeTreeFolding()) { Range range = Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); if (range.isEmpty()) { // If no selection, fold the innermost non-anonymous scope ScopeList scopeList = new ScopeList(docDisplay_); scopeList.removeAll(ScopeList.ANON_BRACE); Scope scope = scopeList.findLast(new ContainsFoldPredicate( Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()))); if (scope == null) return; docDisplay_.addFoldFromRow(scope.getFoldStart().getRow()); } else { // If selection, fold the selection docDisplay_.addFold(range); } } else { int row = docDisplay_.getSelectionStart().getRow(); docDisplay_.addFoldFromRow(row); } } @Handler void onUnfold() { if (useScopeTreeFolding()) { Range range = Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); if (range.isEmpty()) { // If no selection, unfold the closest fold on the current row Position pos = range.getStart(); AceFold startCandidate = null; AceFold endCandidate = null; for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) { if (startCandidate == null && f.getStart().getRow() == pos.getRow() && f.getStart().getColumn() >= pos.getColumn()) { startCandidate = f; } if (f.getEnd().getRow() == pos.getRow() && f.getEnd().getColumn() <= pos.getColumn()) { endCandidate = f; } } if (startCandidate == null ^ endCandidate == null) { docDisplay_.unfold(startCandidate != null ? startCandidate : endCandidate); } else if (startCandidate != null) { // Both are candidates; see which is closer int startDelta = startCandidate.getStart().getColumn() - pos.getColumn(); int endDelta = pos.getColumn() - endCandidate.getEnd().getColumn(); docDisplay_.unfold(startDelta <= endDelta? startCandidate : endCandidate); } } else { // If selection, unfold the selection docDisplay_.unfold(range); } } else { int row = docDisplay_.getSelectionStart().getRow(); docDisplay_.unfold(row); } } @Handler void onFoldAll() { if (useScopeTreeFolding()) { // Fold all except anonymous braces HashSet<Integer> rowsFolded = new HashSet<Integer>(); for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) rowsFolded.add(f.getStart().getRow()); ScopeList scopeList = new ScopeList(docDisplay_); scopeList.removeAll(ScopeList.ANON_BRACE); for (Scope scope : scopeList) { int row = scope.getFoldStart().getRow(); if (!rowsFolded.contains(row)) docDisplay_.addFoldFromRow(row); } } else { docDisplay_.foldAll(); } } @Handler void onUnfoldAll() { if (useScopeTreeFolding()) { for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) docDisplay_.unfold(f); } else { docDisplay_.unfoldAll(); } } boolean useScopeTreeFolding() { return docDisplay_.hasScopeTree() && !fileType_.isRmd(); } void handlePdfCommand(final String completedAction, final boolean useInternalPreview, final Command onBeforeCompile) { if (fileType_.isRnw() && prefs_.alwaysEnableRnwConcordance().getValue()) compilePdfHelper_.ensureRnwConcordance(); // if the document has been previously saved then we should execute // the onBeforeCompile command immediately final boolean isNewDoc = isNewDoc(); if (!isNewDoc && (onBeforeCompile != null)) onBeforeCompile.execute(); saveThenExecute(null, new Command() { public void execute() { // if this was a new doc then we still need to execute the // onBeforeCompile command if (isNewDoc && (onBeforeCompile != null)) onBeforeCompile.execute(); String path = docUpdateSentinel_.getPath(); if (path != null) { String encoding = StringUtil.notNull( docUpdateSentinel_.getEncoding()); fireCompilePdfEvent(path, encoding, completedAction, useInternalPreview); } } }); } private void fireCompilePdfEvent(String path, String encoding, String completedAction, boolean useInternalPreview) { // first validate the path to make sure it doesn't contain spaces FileSystemItem file = FileSystemItem.createFile(path); if (file.getName().indexOf(' ') != -1) { globalDisplay_.showErrorMessage( "Invalid Filename", "The file '" + file.getName() + "' cannot be compiled to " + "a PDF because TeX does not understand paths with spaces. " + "If you rename the file to remove spaces then " + "PDF compilation will work correctly."); return; } CompilePdfEvent event = new CompilePdfEvent( compilePdfHelper_.getTargetFile(file), encoding, getSelectionAsSourceLocation(false), completedAction, useInternalPreview); events_.fireEvent(event); } private Command postSaveCommand() { return new Command() { public void execute() { // fire source document saved event FileSystemItem file = FileSystemItem.createFile( docUpdateSentinel_.getPath()); events_.fireEvent(new SourceFileSaveCompletedEvent( file, docUpdateSentinel_.getContents(), docDisplay_.getCursorPosition())); // check for source on save if (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { if (fileType_.isRd()) { previewRd(); } else if (fileType_.canPreviewFromR()) { previewFromR(); } else { if (docDisplay_.hasBreakpoints()) { hideBreakpointWarningBar(); } consoleDispatcher_.executeSourceCommand( docUpdateSentinel_.getPath(), fileType_, docUpdateSentinel_.getEncoding(), activeCodeIsAscii(), false, false, docDisplay_.hasBreakpoints()); } } } }; } public void checkForExternalEdit() { if (!externalEditCheckInterval_.hasElapsed()) return; externalEditCheckInterval_.reset(); externalEditCheckInvalidation_.invalidate(); // If the doc has never been saved, don't even bother checking if (getPath() == null) return; final Invalidation.Token token = externalEditCheckInvalidation_.getInvalidationToken(); server_.checkForExternalEdit( id_, new ServerRequestCallback<CheckForExternalEditResult>() { @Override public void onResponseReceived(CheckForExternalEditResult response) { if (token.isInvalid()) return; if (response.isDeleted()) { if (ignoreDeletes_) return; globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Deleted", "The file " + StringUtil.notNull(docUpdateSentinel_.getPath()) + " has been deleted or moved. " + "Do you want to close this file now?", false, new Operation() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); ignoreDeletes_ = true; // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } else if (response.isModified()) { ignoreDeletes_ = false; // Now we know it exists // Use StringUtil.formatDate(response.getLastModified())? if (!dirtyState_.getValue()) { docUpdateSentinel_.revert(); } else { externalEditCheckInterval_.reset(); globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Changed", "The file " + name_.getValue() + " has changed " + "on disk. Do you want to reload the file from " + "disk and discard your unsaved changes?", false, new Operation() { public void execute() { docUpdateSentinel_.revert(); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); docUpdateSentinel_.ignoreExternalEdit(); // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private SourcePosition toSourcePosition(Scope func) { Position pos = func.getPreamble(); return SourcePosition.create(pos.getRow(), pos.getColumn()); } private boolean isCursorInTexMode() { if (fileType_.canCompilePDF()) { if (fileType_.isRnw()) { return SweaveFileType.TEX_LANG_MODE.equals( docDisplay_.getLanguageMode(docDisplay_.getCursorPosition())); } else { return true; } } else { return false; } } private boolean isCursorInRMode() { String mode = docDisplay_.getLanguageMode(docDisplay_.getCursorPosition()); if (mode == null) return true; if (mode.equals(TextFileType.R_LANG_MODE)) return true; return false; } private boolean isNewDoc() { return docUpdateSentinel_.getPath() == null; } private CppCompletionContext cppCompletionContext_ = new CppCompletionContext() { @Override public boolean isCompletionEnabled() { return session_.getSessionInfo().getClangAvailable() && (docUpdateSentinel_.getPath() != null); } @Override public void withUpdatedDoc(final CommandWithArg<String> onUpdated) { docUpdateSentinel_.withSavedDoc(new Command() { @Override public void execute() { onUpdated.execute(docUpdateSentinel_.getPath()); } }); } }; private RCompletionContext rContext_ = new RCompletionContext() { @Override public String getPath() { return docUpdateSentinel_.getPath(); } @Override public String getId() { return docUpdateSentinel_.getId(); } }; // these methods are public static so that other editing targets which // display source code (but don't inherit from TextEditingTarget) can share // their implementation public static interface PrefsContext { FileSystemItem getActiveFile(); } public static void registerPrefs( ArrayList<HandlerRegistration> releaseOnDismiss, UIPrefs prefs, DocDisplay docDisplay, final SourceDocument sourceDoc) { registerPrefs(releaseOnDismiss, prefs, docDisplay, new PrefsContext() { @Override public FileSystemItem getActiveFile() { String path = sourceDoc.getPath(); if (path != null) return FileSystemItem.createFile(path); else return null; } }); } public static void registerPrefs( ArrayList<HandlerRegistration> releaseOnDismiss, UIPrefs prefs, final DocDisplay docDisplay, final PrefsContext context) { releaseOnDismiss.add(prefs.highlightSelectedLine().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setHighlightSelectedLine(arg); }})); releaseOnDismiss.add(prefs.highlightSelectedWord().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setHighlightSelectedWord(arg); }})); releaseOnDismiss.add(prefs.showLineNumbers().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowLineNumbers(arg); }})); releaseOnDismiss.add(prefs.useSpacesForTab().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { // Makefile always uses tabs FileSystemItem file = context.getActiveFile(); if ((file != null) && ("Makefile".equals(file.getName()) || "Makevars".equals(file.getName()) || "Makevars.win".equals(file.getName()))) { docDisplay.setUseSoftTabs(false); } else { docDisplay.setUseSoftTabs(arg); } }})); releaseOnDismiss.add(prefs.numSpacesForTab().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.setTabSize(arg); }})); releaseOnDismiss.add(prefs.showMargin().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowPrintMargin(arg); }})); releaseOnDismiss.add(prefs.blinkingCursor().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setBlinkingCursor(arg); }})); releaseOnDismiss.add(prefs.printMarginColumn().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.setPrintMarginColumn(arg); }})); releaseOnDismiss.add(prefs.showInvisibles().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowInvisibles(arg); }})); releaseOnDismiss.add(prefs.showIndentGuides().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowIndentGuides(arg); }})); releaseOnDismiss.add(prefs.useVimMode().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setUseVimMode(arg); }})); } public static void syncFontSize( ArrayList<HandlerRegistration> releaseOnDismiss, EventBus events, final TextDisplay view, FontSizeManager fontSizeManager) { releaseOnDismiss.add(events.addHandler( ChangeFontSizeEvent.TYPE, new ChangeFontSizeHandler() { public void onChangeFontSize(ChangeFontSizeEvent event) { view.setFontSize(event.getFontSize()); } })); view.setFontSize(fontSizeManager.getSize()); } public static void onPrintSourceDoc(final DocDisplay docDisplay) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay.print(); } }); } public static void addRecordNavigationPositionHandler( ArrayList<HandlerRegistration> releaseOnDismiss, final DocDisplay docDisplay, final EventBus events, final EditingTarget target) { releaseOnDismiss.add(docDisplay.addRecordNavigationPositionHandler( new RecordNavigationPositionHandler() { @Override public void onRecordNavigationPosition( RecordNavigationPositionEvent event) { SourcePosition pos = SourcePosition.create( target.getContext(), event.getPosition().getRow(), event.getPosition().getColumn(), docDisplay.getScrollTop()); events.fireEvent(new SourceNavigationEvent( SourceNavigation.create( target.getId(), target.getPath(), pos))); } })); } private StatusBar statusBar_; private final DocDisplay docDisplay_; private final UIPrefs prefs_; private Display view_; private final Commands commands_; private SourceServerOperations server_; private EventBus events_; private final GlobalDisplay globalDisplay_; private final FileDialogs fileDialogs_; private final FileTypeRegistry fileTypeRegistry_; private final FileTypeCommands fileTypeCommands_; private final ConsoleDispatcher consoleDispatcher_; private final WorkbenchContext workbenchContext_; private final Session session_; private final Synctex synctex_; private final FontSizeManager fontSizeManager_; private final SourceBuildHelper sourceBuildHelper_; private DocUpdateSentinel docUpdateSentinel_; private Value<String> name_ = new Value<String>(null); private TextFileType fileType_; private String id_; private HandlerRegistration commandHandlerReg_; private ArrayList<HandlerRegistration> releaseOnDismiss_ = new ArrayList<HandlerRegistration>(); private final DirtyState dirtyState_; private HandlerManager handlers_ = new HandlerManager(this); private FileSystemContext fileContext_; private final TextEditingTargetCompilePdfHelper compilePdfHelper_; private final TextEditingTargetRMarkdownHelper rmarkdownHelper_; private final TextEditingTargetCppHelper cppHelper_; private final TextEditingTargetPresentationHelper presentationHelper_; private boolean ignoreDeletes_; private boolean forceSaveCommandActive_ = false; private final TextEditingTargetScopeHelper scopeHelper_; private TextEditingTargetSpelling spelling_; private BreakpointManager breakpointManager_; // Allows external edit checks to supercede one another private final Invalidation externalEditCheckInvalidation_ = new Invalidation(); // Prevents external edit checks from happening too soon after each other private final IntervalTracker externalEditCheckInterval_ = new IntervalTracker(1000, true); private final EditingTargetCodeExecution codeExecution_; private SourcePosition debugStartPos_ = null; private SourcePosition debugEndPos_ = null; private boolean isDebugWarningVisible_ = false; private boolean isBreakpointWarningVisible_ = false; private String extendedType_; private abstract class RefactorServerRequestCallback extends ServerRequestCallback<JsArrayString> { private final String refactoringName_; public RefactorServerRequestCallback(String refactoringName) { refactoringName_ = refactoringName; } @Override public void onResponseReceived(final JsArrayString response) { doExtract(response); } @Override public void onError(ServerError error) { globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, refactoringName_, "The selected code could not be " + "parsed.\n\n" + "Are you sure you want to continue?", new Operation() { public void execute() { doExtract(null); } }, false); } abstract void doExtract(final JsArrayString response); } }
package hex.tree.gbm; import hex.Distribution; import hex.DistributionFactory; import hex.ModelCategory; import hex.genmodel.utils.DistributionFamily; import hex.quantile.Quantile; import hex.quantile.QuantileModel; import hex.tree.*; import hex.tree.DTree.DecidedNode; import hex.tree.DTree.LeafNode; import hex.tree.DTree.UndecidedNode; import org.apache.log4j.Logger; import water.*; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.*; import water.util.ArrayUtils; import water.util.MathUtils; import water.util.RandomUtils; import water.util.VecUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import static hex.tree.ScoreBuildHistogram.DECIDED_ROW; import static hex.util.LinearAlgebraUtils.toEigenArray; /** Gradient Boosted Trees * * Based on "Elements of Statistical Learning, Second Edition, page 387" */ public class GBM extends SharedTree<GBMModel,GBMModel.GBMParameters,GBMModel.GBMOutput> { private static final Logger LOG = Logger.getLogger(GBM.class); @Override public ModelCategory[] can_build() { return new ModelCategory[]{ ModelCategory.Regression, ModelCategory.Binomial, ModelCategory.Multinomial, }; } // Called from an http request public GBM( GBMModel.GBMParameters parms ) { super(parms ); init(false); } public GBM( GBMModel.GBMParameters parms, Key<GBMModel> key) { super(parms, key); init(false); } public GBM(boolean startup_once) { super(new GBMModel.GBMParameters(),startup_once); } @Override protected int nModelsInParallel(int folds) { return nModelsInParallel(folds, 2); } /** Start the GBM training Job on an F/J thread. */ @Override protected GBMDriver trainModelImpl() { return new GBMDriver(); } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the learning rate and distribution family. */ @Override public void init(boolean expensive) { super.init(expensive); // Initialize response based on given distribution family. // Regression: initially predict the response mean // Binomial: just class 0 (class 1 in the exact inverse prediction) // Multinomial: Class distribution which is not a single value. // However there is this weird tension on the initial value for // classification: If you guess 0's (no class is favored over another), // then with your first GBM tree you'll typically move towards the correct // answer a little bit (assuming you have decent predictors) - and // immediately the Confusion Matrix shows good results which gradually // improve... BUT the Means Squared Error will suck for unbalanced sets, // even as the CM is good. That's because we want the predictions for the // common class to be large and positive, and the rare class to be negative // and instead they start around 0. Guessing initial zero's means the MSE // is so bad, that the R^2 metric is typically negative (usually it's // between 0 and 1). // If instead you guess the mean (reversed through the loss function), then // the zero-tree GBM model reports an MSE equal to the response variance - // and an initial R^2 of zero. More trees gradually improves the R^2 as // expected. However, all the minority classes have large guesses in the // wrong direction, and it takes a long time (lotsa trees) to correct that // - so your CM sucks for a long time. if (expensive) { if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(GBM.this); if (_parms._distribution == DistributionFamily.AUTO) { if (_nclass == 1) _parms._distribution = DistributionFamily.gaussian; if (_nclass == 2) _parms._distribution = DistributionFamily.bernoulli; if (_nclass >= 3) _parms._distribution = DistributionFamily.multinomial; } checkDistributions(); if (hasOffsetCol() && isClassifier() && (_parms._distribution == DistributionFamily.multinomial || _parms._distribution == DistributionFamily.custom)) { error("_offset_column", "Offset is not supported for "+_parms._distribution+" distribution."); } if (_parms._monotone_constraints != null && _parms._monotone_constraints.length > 0 && !supportMonotoneConstraints(_parms._distribution)) { error("_monotone_constraints", "Monotone constraints are only supported for Gaussian, Bernoulli, Tweedie and Quantile distributions, your distribution: " + _parms._distribution + "."); } if (_origTrain != null && _origTrain != _train) { List<Double> projections = new ArrayList<>(); for (int i = 0; i < _origTrain.numCols(); i++) { Vec currentCol = _origTrain.vec(i); if (currentCol.isCategorical()) { double[] actProjection = toEigenArray(currentCol); for (double v : actProjection) { projections.add(v); } } } double[] primitive_projections = new double[projections.size()]; for (int i = 0; i < projections.size(); i++) { primitive_projections[i] = projections.get(i); } _orig_projection_array = primitive_projections; } } switch( _parms._distribution) { case bernoulli: if( _nclass != 2 /*&& !couldBeBool(_response)*/) error("_distribution", H2O.technote(2, "Binomial requires the response to be a 2-class categorical")); break; case quasibinomial: if ( !_response.isNumeric() ) error("_distribution", H2O.technote(2, "Quasibinomial requires the response to be numeric.")); if ( _nclass != 2) error("_distribution", H2O.technote(2, "Quasibinomial requires the response to be binary.")); break; case modified_huber: if( _nclass != 2 /*&& !couldBeBool(_response)*/) error("_distribution", H2O.technote(2, "Modified Huber requires the response to be a 2-class categorical.")); break; case multinomial: if (!isClassifier()) error("_distribution", H2O.technote(2, "Multinomial requires an categorical response.")); break; case huber: if (isClassifier()) error("_distribution", H2O.technote(2, "Huber requires the response to be numeric.")); break; case poisson: if (isClassifier()) error("_distribution", H2O.technote(2, "Poisson requires the response to be numeric.")); break; case gamma: if (isClassifier()) error("_distribution", H2O.technote(2, "Gamma requires the response to be numeric.")); break; case tweedie: if (isClassifier()) error("_distribution", H2O.technote(2, "Tweedie requires the response to be numeric.")); break; case gaussian: if (isClassifier()) error("_distribution", H2O.technote(2, "Gaussian requires the response to be numeric.")); break; case laplace: if (isClassifier()) error("_distribution", H2O.technote(2, "Laplace requires the response to be numeric.")); break; case quantile: if (isClassifier()) error("_distribution", H2O.technote(2, "Quantile requires the response to be numeric.")); break; case custom: if(_parms._custom_distribution_func == null) error("_distribution", H2O.technote(2, "Custom requires custom function loaded.")); break; case AUTO: break; default: error("_distribution","Invalid distribution: " + _parms._distribution); } if( !(0. < _parms._learn_rate && _parms._learn_rate <= 1.0) ) error("_learn_rate", "learn_rate must be between 0 and 1"); if( !(0. < _parms._learn_rate_annealing && _parms._learn_rate_annealing <= 1.0) ) error("_learn_rate_annealing", "learn_rate_annealing must be between 0 and 1"); if( !(0. < _parms._col_sample_rate && _parms._col_sample_rate <= 1.0) ) error("_col_sample_rate", "col_sample_rate must be between 0 and 1"); if (_parms._max_abs_leafnode_pred <= 0) error("_max_abs_leafnode_pred", "max_abs_leafnode_pred must be larger than 0."); if (_parms._pred_noise_bandwidth < 0) error("_pred_noise_bandwidth", "pred_noise_bandwidth must be >= 0."); if ((_train != null) && (_parms._monotone_constraints != null)) { TreeUtils.checkMonotoneConstraints(this, _train, _parms._monotone_constraints); } } private boolean supportMonotoneConstraints(DistributionFamily distributionFamily){ switch (distributionFamily) { case gaussian: case bernoulli: case tweedie: case quantile: return true; default: return false; } } private class GBMDriver extends Driver { private transient FrameMap frameMap; private transient long _skippedCnt; // #observations that will be skipped because they have 0 weight or NA label in the training frame @Override protected Frame makeValidWorkspace() { final int nClasses = numClassTrees(); final Vec[] tmp; if (validWorkspaceCanReuseTrainWorkspace()) { tmp = new Vec[nClasses]; for (int i = 0; i < nClasses; i++) { tmp[i] = _train.vec(idx_tree(i)); assert tmp[i].isVolatile(); } } else { tmp = _valid.anyVec().makeVolatileDoubles(nClasses); } String[] tmpNames = new String[tmp.length]; for (int i = 0; i < tmpNames.length; i++) tmpNames[i] = "__P_" + i; return new Frame(tmpNames, tmp); } private boolean validWorkspaceCanReuseTrainWorkspace() { // 1. only possible for CV models if (!_parms._is_cv_model) return false; // 2. and only if training frame and validation frame are identical (except for weights) // training frame can eg. be sub/over-sampled for imbalanced problems\ // shortcut: if responses are identical => frames must be identical as well (for CV models only!!!) return _vresponse._key.equals(_response._key); } @Override protected boolean doOOBScoring() { return false; } @Override protected void initializeModelSpecifics() { frameMap = new FrameMap(GBM.this); _mtry_per_tree = Math.max(1, (int)(_parms._col_sample_rate_per_tree * _ncols)); //per-tree if (!(1 <= _mtry_per_tree && _mtry_per_tree <= _ncols)) throw new IllegalArgumentException("Computed mtry_per_tree should be in interval <1,"+_ncols+"> but it is " + _mtry_per_tree); _mtry = Math.max(1, (int)(_parms._col_sample_rate * _parms._col_sample_rate_per_tree * _ncols)); //per-split if (!(1 <= _mtry && _mtry <= _ncols)) throw new IllegalArgumentException("Computed mtry should be in interval <1,"+_ncols+"> but it is " + _mtry); // for Bernoulli, we compute the initial value with Newton-Raphson iteration, otherwise it might be NaN here DistributionFamily distr = _parms._distribution; _initialPrediction = _nclass > 2 || distr == DistributionFamily.laplace || distr == DistributionFamily.huber || distr == DistributionFamily.quantile ? 0 : getInitialValue(); if(distr == DistributionFamily.quasibinomial){ _model._output._quasibinomialDomains = new VecUtils.CollectDoubleDomain(null,2).doAll(_response).stringDomain(_response.isInt()); } if (distr == DistributionFamily.bernoulli || distr == DistributionFamily.quasibinomial) { if (hasOffsetCol()) _initialPrediction = getInitialValueBernoulliOffset(_train); } else if (distr == DistributionFamily.laplace || distr == DistributionFamily.huber) { _initialPrediction = getInitialValueQuantile(0.5); } else if (distr == DistributionFamily.quantile) { _initialPrediction = getInitialValueQuantile(_parms._quantile_alpha); } _model._output._init_f = _initialPrediction; //always write the initial value here (not just for Bernoulli) if (_model.evalAutoParamsEnabled) { _model.initActualParamValuesAfterOutputSetup(_nclass, isClassifier()); } // Set the initial prediction into the tree column 0 if (_initialPrediction != 0.0) { new FillVecWithConstant(_initialPrediction) .doAll(vec_tree(_train, 0), _parms._build_tree_one_node); // Only setting tree-column 0 } // Mark all rows that either have zero weights or the label is NA as decided // This is way we can avoid processing them when building trees final long zeroWeights = hasWeightCol() ? _weights.length() - _weights.nzCnt() : 0; if (zeroWeights > 0 || // has some zero weights or response().naCnt() > 0) { // there are NAs in the response Vec[] vecs = new Vec[]{_response}; if (hasWeightCol()) vecs = ArrayUtils.append(vecs, _weights); for (int k = 0; k < _nclass; k++) { Vec nidsVecK = vec_nids(_train, k); if (nidsVecK.min() == DECIDED_ROW) { // classes not present in the training frame are skipped assert _model._output._distribution[k] == 0; assert nidsVecK.isConst(); continue; } vecs = ArrayUtils.append(vecs, nidsVecK); } _skippedCnt = new MarkDecidedRows().doAll(vecs).markedCnt; assert _skippedCnt >= zeroWeights; assert _skippedCnt >= response().naCnt(); assert _skippedCnt <= response().naCnt() + zeroWeights; } else _skippedCnt = 0; } class MarkDecidedRows extends MRTask<MarkDecidedRows> { int markedCnt; @Override public void map(Chunk[] cs) { final int colStart; final Chunk y; final Chunk weights; if (hasWeightCol()) { y = cs[0]; weights = cs[1]; colStart = 2; } else { y = cs[0]; weights = new C0DChunk(1, cs[0]._len); colStart = 1; } for (int row = 0; row < y._len; row++) { if (weights.atd(row) == 0 || y.isNA(row)) { markedCnt++; for (int c = colStart; c < cs.length; c++) { cs[c].set(row, DECIDED_ROW); } } } } @Override public void reduce(MarkDecidedRows mrt) { markedCnt += mrt.markedCnt; } @Override protected boolean modifiesVolatileVecs() { return true; } } /** * Helper to compute the initial value for Laplace/Huber/Quantile (incl. optional offset and obs weights) * @return weighted median of response - offset */ private double getInitialValueQuantile(double quantile) { // obtain y - o Vec y = hasOffsetCol() ? new ResponseLessOffsetTask(frameMap).doAll(1, Vec.T_NUM, _train).outputFrame().anyVec() : response(); // Now compute (weighted) quantile of y - o double res; QuantileModel qm = null; Frame tempFrame = null; try { tempFrame = new Frame(Key.<Frame>make(H2O.SELF), new String[]{"y"}, new Vec[]{y}); if (hasWeightCol()) tempFrame.add("w", _weights); DKV.put(tempFrame); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = tempFrame._key; parms._probs = new double[]{quantile}; parms._weights_column = hasWeightCol() ? "w" : null; Job<QuantileModel> job1 = new Quantile(parms).trainModel(); qm = job1.get(); res = qm._output._quantiles[0][0]; } finally { if (qm!=null) qm.remove(); if (tempFrame!=null) DKV.remove(tempFrame._key); } return res; } /** * Helper to compute the initial value for Bernoulli for offset != 0 */ private double getInitialValueBernoulliOffset(Frame train) { LOG.info("Running Newton-Raphson iteration to find the initial value since offsets are specified."); double delta; int count = 0; double tol = 1e-4; //From R GBM vignette: //For speed, gbm() does only one step of the Newton-Raphson algorithm //rather than iterating to convergence. No appreciable loss of accuracy //since the next boosting iteration will simply correct for the prior iterations //inadequacy. int N = 1; //one step is enough - same as R double init = 0; //start with initial value of 0 for convergence do { double newInit = new NewtonRaphson(frameMap, DistributionFactory.getDistribution(_parms), init).doAll(train).value(); delta = Math.abs(init - newInit); init = newInit; LOG.info("Iteration " + (++count) + ": initial value: " + init); } while (count < N && delta >= tol); if (delta > tol) LOG.warn("Not fully converged."); LOG.info("Newton-Raphson iteration ran for " + count + " iteration(s). Final residual: " + delta); return init; } private static final double MIN_LOG_TRUNC = -19; private static final double MAX_LOG_TRUNC = 19; private void truncatePreds(final DTree tree, int firstLeafIndex, DistributionFamily dist) { if (firstLeafIndex==tree._len) return; ComputeMinMax minMax = new ComputeMinMax(frameMap, firstLeafIndex, tree._len).doAll(_train); if (LOG.isTraceEnabled()) { LOG.trace("Number of leaf nodes: " + minMax._mins.length); LOG.trace("Min: " + Arrays.toString(minMax._mins)); LOG.trace("Max: " + Arrays.toString(minMax._maxs)); } //loop over leaf nodes only: starting at leaf index for (int i = 0; i < tree._len - firstLeafIndex; i++) { final LeafNode node = ((LeafNode) tree.node(firstLeafIndex + i)); int nidx = node.nid(); float nodeMin = minMax._mins[nidx- firstLeafIndex]; float nodeMax = minMax._maxs[nidx- firstLeafIndex]; if (LOG.isTraceEnabled()) LOG.trace("Node: " + nidx + " min/max: " + nodeMin + "/" + nodeMax); double val = node._pred; if (dist == DistributionFamily.gamma || dist == DistributionFamily.tweedie) //only for gamma/tweedie val += nodeMax; if (val > MAX_LOG_TRUNC) { if (LOG.isDebugEnabled()) LOG.debug("Truncating large positive leaf prediction (log): " + node._pred + " to " + (MAX_LOG_TRUNC - nodeMax)); node._pred = (float) (MAX_LOG_TRUNC - nodeMax); } val = node._pred; if (dist == DistributionFamily.gamma || dist == DistributionFamily.tweedie) //only for gamma/tweedie val += nodeMin; if (val < MIN_LOG_TRUNC) { if (LOG.isDebugEnabled()) LOG.debug("Truncating large negative leaf prediction (log): " + node._pred + " to " + (MIN_LOG_TRUNC - nodeMin)); node._pred = (float) (MIN_LOG_TRUNC - nodeMin); } if (node._pred < MIN_LOG_TRUNC && node._pred > MAX_LOG_TRUNC) { LOG.warn("Terminal node prediction outside of allowed interval in log-space: " + node._pred + " (should be in " + MIN_LOG_TRUNC + "..." + MAX_LOG_TRUNC + ")."); } } } // Build the next k-trees, which is trying to correct the residual error from // the prior trees. @Override protected boolean buildNextKTrees() { // We're going to build K (nclass) trees - each focused on correcting // errors for a single class. final DTree[] ktrees = new DTree[_nclass]; // Define a "working set" of leaf splits, from here to tree._len int[] leaves = new int[_nclass]; // Get distribution Distribution distributionImpl = DistributionFactory.getDistribution(_parms); // Compute predictions and resulting residuals // ESL2, page 387, Steps 2a, 2b // fills "Work" columns for all rows (incl. OOB) with the residuals double huberDelta = Double.NaN; if (_parms._distribution == DistributionFamily.huber) { // Jerome Friedman 1999: Greedy Function Approximation: A Gradient Boosting Machine // compute absolute diff |y-(f+o)| for all rows Vec diff = new ComputeAbsDiff(frameMap).doAll(1, (byte)3 /*numeric*/, _train).outputFrame().anyVec(); // compute weighted alpha-quantile of the absolute residual -> this is the delta for the huber loss huberDelta = MathUtils.computeWeightedQuantile(_weights, diff, _parms._huber_alpha); distributionImpl.setHuberDelta(huberDelta); // now compute residuals using the gradient of the huber loss (with a globally adjusted delta) new StoreResiduals(frameMap, distributionImpl).doAll(_train, _parms._build_tree_one_node); } else { // compute predictions and residuals in one shot new ComputePredAndRes(frameMap, _nclass, _model._output._distribution, distributionImpl) .doAll(_train, _parms._build_tree_one_node); } for (int k = 0; k < _nclass; k++) { if (LOG.isTraceEnabled() && ktrees[k]!=null) { LOG.trace("Updated predictions in WORK col for class " + k + ":\n" + new Frame(new String[]{"WORK"},new Vec[]{vec_work(_train, k)}).toTwoDimTable()); } } // ESL2, page 387. Step 2b ii. // One Big Loop till the ktrees are of proper depth. // Adds a layer to the trees each pass. Constraints cs = _parms.constraints(_train); growTrees(ktrees, leaves, _rand, cs); for (int k = 0; k < _nclass; k++) { if (LOG.isTraceEnabled() && ktrees[k]!=null) { LOG.trace("Grew trees. Updated NIDs for class " + k + ":\n" + new Frame(new String[]{"NIDS"},new Vec[]{vec_nids(_train, k)}).toTwoDimTable()); } } // into the tree leaves. Includes learn_rate. GammaPass gp = new GammaPass(frameMap, ktrees, leaves, distributionImpl, _nclass); gp.doAll(_train); if (_parms._distribution == DistributionFamily.laplace) { fitBestConstantsQuantile(ktrees, leaves[0], 0.5); //special case for Laplace: compute the median for each leaf node and store that as prediction } else if (_parms._distribution == DistributionFamily.quantile) { if(cs == null) { fitBestConstantsQuantile(ktrees, leaves[0], _parms._quantile_alpha); //compute the alpha-quantile for each leaf node and store that as prediction } else { fitBestConstants(ktrees, leaves, gp, cs); // compute quantile monotone constraints using precomputed parent prediction resetQuantileConstants(ktrees, _parms._quantile_alpha, cs); } } else if (_parms._distribution == DistributionFamily.huber) { fitBestConstantsHuber(ktrees, leaves[0], huberDelta); //compute the alpha-quantile for each leaf node and store that as prediction } else { fitBestConstants(ktrees, leaves, gp, cs); } // Apply a correction for strong mispredictions (otherwise deviance can explode) if (_parms._distribution == DistributionFamily.gamma || _parms._distribution == DistributionFamily.poisson || _parms._distribution == DistributionFamily.tweedie) { assert(_nclass == 1); truncatePreds(ktrees[0], leaves[0], _parms._distribution); } if ((cs != null) && constraintCheckEnabled()) { _job.update(0, "Checking monotonicity constraints on the final model"); checkConstraints(ktrees, leaves, cs); } // ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the // new tree, in the 'tree' columns. Also, zap the NIDs for next pass. // Tree <== f(Tree) // Nids <== 0 new AddTreeContributions( frameMap, ktrees, _parms._pred_noise_bandwidth, _parms._seed, _parms._ntrees, _model._output._ntrees ).doAll(_train); // sanity check for (int k = 0; k < _nclass; k++) { assert ktrees[k] == null || vec_nids(_train, k).nzCnt() == _skippedCnt; } // Grow the model by K-trees _model._output.addKTrees(ktrees); boolean converged = effective_learning_rate() < 1e-6; if (converged) { LOG.warn("Effective learning rate dropped below 1e-6 (" + _parms._learn_rate + " * " + _parms._learn_rate_annealing + "^" + (_model._output._ntrees-1) + ") - stopping the model now."); } return converged; } /** * How may trees are actually calculated for the number of classes the model uses. * @return number of trees */ private int numClassTrees() { return _nclass == 2 ? 1 : _nclass; // Boolean Optimization (only one tree needed for 2-class problems) } /** * Grow k regression trees (k=1 for regression and binomial, k=N for classification with N classes) * @param ktrees k trees to grow (must be properly initialized) * @param leaves workspace to store the leaf node starting index (k-dimensional - one per tree) * @param rand PRNG for reproducibility */ private void growTrees(DTree[] ktrees, int[] leaves, Random rand, Constraints cs) { // Initial set of histograms. All trees; one leaf per tree (the root // leaf); all columns DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols]; // Adjust real bins for the top-levels int adj_nbins = Math.max(_parms._nbins_top_level,_parms._nbins); long rseed = rand.nextLong(); // initialize trees for (int k = 0; k < numClassTrees(); k++) { // Initially setup as-if an empty-split had just happened if (_model._output._distribution[k] != 0) { ktrees[k] = new DTree(_train, _ncols, _mtry, _mtry_per_tree, rseed, _parms); DHistogram[] hist = DHistogram.initialHist(_train, _ncols, adj_nbins, hcs[k][0], rseed, _parms, getGlobalQuantilesKeys(), cs); new UndecidedNode(ktrees[k], DTree.NO_PARENT, hist, cs); // The "root" node } } // Sample - mark the lines by putting 'OUT_OF_BAG' into nid(<klass>) vector if (_parms._sample_rate < 1 || _parms._sample_rate_per_class != null) { Sample ss[] = new Sample[_nclass]; for (int k = 0; k < _nclass; k++) if (ktrees[k] != null) ss[k] = new Sample(ktrees[k], _parms._sample_rate, _parms._sample_rate_per_class).dfork(null, new Frame(vec_nids(_train, k), _response), _parms._build_tree_one_node); for (int k = 0; k < _nclass; k++) { if (ss[k] != null) { ss[k].getResult(); if (LOG.isTraceEnabled() && ktrees[k]!=null) { LOG.trace("Sampled OOB rows. NIDS:\n" + new Frame(vec_nids(_train, k)).toTwoDimTable()); } } } } // ESL2, page 387. Step 2b ii. // One Big Loop till the ktrees are of proper depth. // Adds a layer to the trees each pass. int depth = 0; for (; depth < _parms._max_depth; depth++) { hcs = buildLayer(_train, _parms._nbins, _parms._nbins_cats, ktrees, leaves, hcs, _parms._build_tree_one_node); // If we did not make any new splits, then the tree is split-to-death if (hcs == null) break; } // Each tree bottomed-out in a DecidedNode; go 1 more level and insert // LeafNodes to hold predictions. for (int k = 0; k < _nclass; k++) { DTree tree = ktrees[k]; if (tree == null) continue; int leaf = tree.len(); leaves[k] = leaf; //record the size of the tree before splitting the bottom nodes as the starting index for the leaf node indices for (int nid = 0; nid < leaf; nid++) { if (tree.node(nid) instanceof DecidedNode) { DecidedNode dn = tree.decided(nid); if (dn._split == null) { // No decision here, no row should have this NID now if (nid == 0) // Handle the trivial non-splitting tree new LeafNode(tree, DTree.NO_PARENT, 0); continue; } for (int i = 0; i < dn._nids.length; i++) { //L/R children int cnid = dn._nids[i]; if (cnid == ScoreBuildHistogram.UNDECIDED_CHILD_NODE_ID || // Bottomed out (predictors or responses known constant) tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth (tree.node(cnid) instanceof DecidedNode && // Or not possible to split ((DecidedNode) tree.node(cnid))._split == null)) { dn._nids[i] = new LeafNode(tree, nid).nid(); // Mark a leaf here } } } } } // -- k-trees are done } // Jerome Friedman 1999: Greedy Function Approximation: A Gradient Boosting Machine private void fitBestConstantsHuber(DTree[] ktrees, int firstLeafIndex, double huberDelta) { if (firstLeafIndex == ktrees[0]._len) return; // no splits happened - nothing to do assert(_nclass==1); // get diff y-(f+o) and weights and strata (node idx) Vec diff = new ComputeDiff(frameMap).doAll(1, (byte)3 /*numeric*/, _train).outputFrame().anyVec(); Vec weights = hasWeightCol() ? _train.vecs()[idx_weight()] : null; Vec strata = vec_nids(_train,0); // compute median diff for each leaf node Quantile.StratifiedQuantilesTask sqt = new Quantile.StratifiedQuantilesTask(null, 0.5 /*median of weighted residuals*/, diff, weights, strata, QuantileModel.CombineMethod.INTERPOLATE); H2O.submitTask(sqt); sqt.join(); // subtract median(diff) from residuals for all observations of each leaf DiffMinusMedianDiff hp = new DiffMinusMedianDiff(strata, sqt._quantiles /*median residuals per leaf*/); Frame tmpFrame1 = new Frame(new String[]{"strata","diff"}, new Vec[]{strata,diff}); hp.doAll(tmpFrame1); Vec diffMinusMedianDiff = diff; // for each leaf, compute the mean of Math.signum(resMinusMedianRes) * Math.min(Math.abs(resMinusMedianRes), huberDelta), // where huberDelta is the alpha-percentile of the residual across all observations Frame tmpFrame2 = new Frame(_train.vecs()); tmpFrame2.add("resMinusMedianRes", diffMinusMedianDiff); double[] huberGamma = new HuberLeafMath(frameMap, huberDelta, strata).doAll(tmpFrame2)._huberGamma; // now assign the median per leaf + the above _huberCorrection[i] to each leaf final DTree tree = ktrees[0]; for (int i = 0; i < sqt._quantiles.length; i++) { double huber = (sqt._quantiles[i] /*median*/ + huberGamma[i]); if (Double.isNaN(sqt._quantiles[i])) continue; //no active rows for this NID double val = effective_learning_rate() * huber; assert !Double.isNaN(val) && !Double.isInfinite(val); if (val > _parms._max_abs_leafnode_pred) val = _parms._max_abs_leafnode_pred; if (val < -_parms._max_abs_leafnode_pred) val = -_parms._max_abs_leafnode_pred; ((LeafNode) tree.node(sqt._nids[i]))._pred = (float) val; if (LOG.isTraceEnabled()) { LOG.trace("Leaf " + sqt._nids[i] + " has huber value: " + huber); } } diffMinusMedianDiff.remove(); } private double effective_learning_rate() { return _parms._learn_rate * Math.pow(_parms._learn_rate_annealing, (_model._output._ntrees-1)); } private void fitBestConstantsQuantile(DTree[] ktrees, int firstLeafIndex, double quantile) { if (firstLeafIndex == ktrees[0]._len) return; // no splits happened - nothing to do assert(_nclass==1); Vec diff = new ComputeDiff(frameMap).doAll(1, (byte)3 /*numeric*/, _train).outputFrame().anyVec(); Vec weights = hasWeightCol() ? _train.vecs()[idx_weight()] : null; Vec strata = vec_nids(_train,0); // compute quantile for all leaf nodes QuantileModel.CombineMethod combine_method = QuantileModel.CombineMethod.INTERPOLATE; Quantile.StratifiedQuantilesTask sqt = new Quantile.StratifiedQuantilesTask(null, quantile, diff, weights, strata, combine_method); H2O.submitTask(sqt); sqt.join(); final DTree tree = ktrees[0]; for (int i = 0; i < sqt._quantiles.length; i++) { double leafQuantile = sqt._quantiles[i]; if (Double.isNaN(leafQuantile)) continue; //no active rows for this NID double val = effective_learning_rate() * leafQuantile; if (val > _parms._max_abs_leafnode_pred) val = _parms._max_abs_leafnode_pred; if (val < -_parms._max_abs_leafnode_pred) val = -_parms._max_abs_leafnode_pred; ((LeafNode) tree.node(sqt._nids[i]))._pred = (float) val; } } /** * This method recompute result leaf node prediction to get a more precise prediction but respecting * the column constraints in subtrees * @param ktrees array of all trained trees * @param quantile quantile alpha parameter * @param cs constraint object to get information about constraints for each column */ private void resetQuantileConstants(DTree[] ktrees, double quantile, Constraints cs) { Vec diff = new ComputeDiff(frameMap).doAll(1, (byte)3, _train).outputFrame().anyVec(); Vec weights = hasWeightCol() ? _train.vecs()[idx_weight()] : null; Vec strata = vec_nids(_train,0); // compute quantile for all leaf nodes QuantileModel.CombineMethod combine_method = QuantileModel.CombineMethod.INTERPOLATE; Quantile.StratifiedQuantilesTask sqt = new Quantile.StratifiedQuantilesTask(null, quantile, diff, weights, strata, combine_method); H2O.submitTask(sqt); sqt.join(); for (int k = 0; k < _nclass; k++) { final DTree tree = ktrees[k]; if (tree == null || tree.len() < 2) continue; float[] mins = new float[tree._len]; int[] min_ids = new int[tree._len]; float[] maxs = new float[tree._len]; int[] max_ids = new int[tree._len]; int dnSize = tree._len - tree._leaves; // calculate index where leaves starts rollupMinMaxPreds(tree, tree.root(), mins, min_ids, maxs, max_ids); for (int i = dnSize; i < tree.len(); i++) { LeafNode node = (LeafNode)tree.node(i); int quantileId = i - dnSize; double leafQuantile = sqt._quantiles[quantileId]; boolean canBeReplaced = true; DTree.Node tmpNode = tree.node(i); while(tmpNode.pid() != DTree.NO_PARENT) { DecidedNode parent = (DecidedNode) tree.node(tmpNode._pid); int constraint = cs.getColumnConstraint(parent._split._col); if (parent._split.naSplitDir() == DHistogram.NASplitDir.NAvsREST || constraint == 0) { tmpNode = parent; continue; } if (constraint > 0) { if (leafQuantile > mins[parent._nids[0]] || leafQuantile < maxs[parent._nids[1]]) { canBeReplaced = false; break; } } else if (leafQuantile < maxs[parent._nids[0]] || leafQuantile > mins[parent._nids[1]]) { canBeReplaced = false; break; } tmpNode = parent; } if(canBeReplaced){ node._pred = (float) leafQuantile; } } } } private void fitBestConstants(DTree[] ktrees, int[] leafs, GammaPass gp, Constraints cs) { final boolean useSplitPredictions = cs != null && cs.useBounds(); double m1class = (_nclass > 1 && _parms._distribution == DistributionFamily.multinomial) || (_nclass > 2 && _parms._distribution == DistributionFamily.custom) ? (double) (_nclass - 1) / _nclass : 1.0; // K-1/K for multinomial for (int k = 0; k < _nclass; k++) { final DTree tree = ktrees[k]; if (tree == null) continue; if (LOG.isTraceEnabled()) { for (int i=0;i<ktrees[k]._len-leafs[k];++i) LOG.trace(ktrees[k].node(leafs[k]+i).toString()); } for (int i = 0; i < tree._len - leafs[k]; i++) { LeafNode leafNode = (LeafNode) ktrees[k].node(leafs[k] + i); final double gamma; if (useSplitPredictions) { gamma = gp.gamma(leafNode.getSplitPrediction()); } else { gamma = gp.gamma(k, i); } double gf = effective_learning_rate() * m1class * gamma; // In the multinomial case, check for very large values (which will get exponentiated later) // Note that gss can be *zero* while rss is non-zero - happens when some rows in the same // split are perfectly predicted true, and others perfectly predicted false. if (_parms._distribution == DistributionFamily.multinomial || (_parms._distribution == DistributionFamily.custom && _nclass > 2)) { if (gf > 1e4) gf = 1e4f; // Cap prediction, will already overflow during Math.exp(gf) else if (gf < -1e4) gf = -1e4f; } if (Double.isNaN(gf)) gf=0; else if (Double.isInfinite(gf)) gf=Math.signum(gf)*1e4f; if (gf > _parms._max_abs_leafnode_pred) gf = _parms._max_abs_leafnode_pred; if (gf < -_parms._max_abs_leafnode_pred) gf = -_parms._max_abs_leafnode_pred; leafNode._pred = (float) gf; } } } private boolean constraintCheckEnabled() { return Boolean.parseBoolean(getSysProperty("gbm.monotonicity.checkEnabled", "true")); } private void checkConstraints(DTree[] ktrees, int[] leafs, Constraints cs) { for (int k = 0; k < _nclass; k++) { final DTree tree = ktrees[k]; if (tree == null) continue; float[] mins = new float[tree._len]; int[] min_ids = new int[tree._len]; float[] maxs = new float[tree._len]; int[] max_ids = new int[tree._len]; rollupMinMaxPreds(tree, tree.root(), mins, min_ids, maxs, max_ids); for (int i = 0; i < tree._len - leafs.length; i++) { DTree.Node node = tree.node(i); if (! (node instanceof DecidedNode)) continue; DecidedNode dn = ((DecidedNode) node); if (dn._split == null) continue; int constraint = cs.getColumnConstraint(dn._split._col); if (dn._split.naSplitDir() == DHistogram.NASplitDir.NAvsREST) { // NAs are not subject to constraints, we don't have to check the monotonicity on "NA vs REST" type of splits continue; } if (constraint > 0) { if (maxs[dn._nids[0]] > mins[dn._nids[1]]) { String message = "Monotonicity constraint " + constraint + " violated on column '" + _train.name(dn._split._col) + "' (max(left) > min(right)): " + maxs[dn._nids[0]] + " > " + mins[dn._nids[1]] + "\nNode: " + node + "\nLeft Node (max): " + tree.node(max_ids[dn._nids[0]]) + "\nRight Node (min): " + tree.node(min_ids[dn._nids[1]]); throw new IllegalStateException(message); } } else if (constraint < 0) { if (mins[dn._nids[0]] < maxs[dn._nids[1]]) { String message = "Monotonicity constraint " + constraint + " violated on column '" + _train.name(dn._split._col) + "' (min(left) < max(right)): " + mins[dn._nids[0]] + " < " + maxs[dn._nids[1]] + "\nNode: " + node + "\nLeft Node (min): " + tree.node(min_ids[dn._nids[0]]) + "\nRight Node (max): " + tree.node(max_ids[dn._nids[1]]); throw new IllegalStateException(message); } } } } } private void rollupMinMaxPreds(DTree tree, DTree.Node node, float[] mins, int min_ids[], float[] maxs, int[] max_ids) { if (node instanceof LeafNode) { mins[node.nid()] = ((LeafNode) node)._pred; min_ids[node.nid()] = node.nid(); maxs[node.nid()] = ((LeafNode) node)._pred; max_ids[node.nid()] = node.nid(); return; } DecidedNode dn = (DecidedNode) node; rollupMinMaxPreds(tree, tree.node(dn._nids[0]), mins, min_ids, maxs, max_ids); rollupMinMaxPreds(tree, tree.node(dn._nids[1]), mins, min_ids, maxs, max_ids); final int min_id = mins[dn._nids[0]] < mins[dn._nids[1]] ? dn._nids[0] : dn._nids[1]; mins[node.nid()] = mins[min_id]; min_ids[node.nid()] = min_ids[min_id]; final int max_id = maxs[dn._nids[0]] > maxs[dn._nids[1]] ? dn._nids[0] : dn._nids[1]; maxs[node.nid()] = maxs[max_id]; max_ids[node.nid()] = max_ids[max_id]; } @Override protected GBMModel makeModel(Key<GBMModel> modelKey, GBMModel.GBMParameters parms) { return new GBMModel(modelKey, parms, new GBMModel.GBMOutput(GBM.this)); } } private static class FillVecWithConstant extends MRTask<FillVecWithConstant> { private double init; public FillVecWithConstant(double d) { init = d; } @Override protected boolean modifiesVolatileVecs() { return true; } @Override public void map(Chunk tree) { if (tree instanceof C8DVolatileChunk) { Arrays.fill(((C8DVolatileChunk) tree).getValues(), init); } else { for (int i = 0; i < tree._len; i++) tree.set(i, init); } } } private static class ResponseLessOffsetTask extends MRTask<ResponseLessOffsetTask> { private FrameMap fm; public ResponseLessOffsetTask(FrameMap frameMap) { fm = frameMap; } @Override public void map(Chunk[] chks, NewChunk[] nc) { final Chunk resp = chks[fm.responseIndex]; final Chunk offset = chks[fm.offsetIndex]; for (int i = 0; i < chks[0]._len; ++i) nc[0].addNum(resp.atd(i) - offset.atd(i)); // y - o } } /** * Newton-Raphson fixpoint iteration to find a self-consistent initial value */ private static class NewtonRaphson extends MRTask<NewtonRaphson> { private FrameMap fm; private Distribution dist; private double _init; private double _numerator; private double _denominator; public NewtonRaphson(FrameMap frameMap, Distribution distribution, double initialValue) { assert frameMap != null && distribution != null; fm = frameMap; dist = distribution; _init = initialValue; _numerator = 0; _denominator = 0; } public double value() { return _init + _numerator / _denominator; } @Override public void map(Chunk[] chks) { Chunk ys = chks[fm.responseIndex]; Chunk offset = chks[fm.offsetIndex]; Chunk weight = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); for (int row = 0; row < ys._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (ys.isNA(row)) continue; double y = ys.atd(row); double o = offset.atd(row); double p = dist.linkInv(o + _init); _numerator += w * (y - p); _denominator += w * p * (1. - p); } } @Override public void reduce(NewtonRaphson mrt) { _numerator += mrt._numerator; _denominator += mrt._denominator; } } /** * Compute Residuals * Do this for all rows, whether OOB or not */ private static class ComputePredAndRes extends MRTask<ComputePredAndRes> { private FrameMap fm; private int nclass; private boolean[] out; private Distribution dist; public ComputePredAndRes(FrameMap frameMap, int nClasses, double[] outputDistribution, Distribution distribution) { fm = frameMap; nclass = nClasses; dist = distribution; out = new boolean[outputDistribution.length]; for (int i = 0; i < out.length; i++) out[i] = (outputDistribution[i] != 0); } @Override public void map(Chunk[] chks) { Chunk ys = chks[fm.responseIndex]; Chunk offset = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); Chunk preds = chks[fm.tree0Index]; // Prior tree sums C8DVolatileChunk wk = (C8DVolatileChunk) chks[fm.work0Index]; // Place to store residuals Chunk weights = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); double[] fs = nclass > 1 ? new double[nclass + 1] : null; for (int row = 0; row < wk._len; row++) { double weight = weights.atd(row); if (weight == 0) continue; if (ys.isNA(row)) continue; double f = preds.atd(row) + offset.atd(row); double y = ys.atd(row); if (LOG.isTraceEnabled()) LOG.trace(f + " vs " + y); //expect that the model predicts very negative values for 0 and very positive values for 1 if ((dist._family == DistributionFamily.multinomial && fs != null) || (dist._family == DistributionFamily.custom && nclass > 2)) { double sum = score1static(chks, fm.tree0Index, 0.0 /*not used for multiclass*/, fs, row, dist, nclass); if (Double.isInfinite(sum)) { // Overflow (happens for constant responses) for (int k = 0; k < nclass; k++) { wk = (C8DVolatileChunk) chks[fm.work0Index + k]; wk.getValues()[row] = ((float) dist.negHalfGradient(y, (Double.isInfinite(fs[k + 1]) ? 1.0f : 0.0f), k)); } } else { for (int k = 0; k < nclass; k++) { // Save as a probability distribution if (out[k]) { wk = (C8DVolatileChunk) chks[fm.work0Index + k]; wk.getValues()[row] = ((float) dist.negHalfGradient(y, (float) (fs[k + 1] / sum), k)); } } } } else { wk.getValues()[row] = ((float) dist.negHalfGradient(y, f)); } } } } private static class ComputeMinMax extends MRTask<ComputeMinMax> { private FrameMap fm; int firstLeafIdx; int _totalNumNodes; float[] _mins; float[] _maxs; public ComputeMinMax(FrameMap frameMap, int firstLeafIndex, int totalNumNodes) { fm = frameMap; firstLeafIdx = firstLeafIndex; _totalNumNodes = totalNumNodes; } @Override public void map(Chunk[] chks) { int len = _totalNumNodes - firstLeafIdx; // number of leaves _mins = new float[len]; _maxs = new float[len]; Arrays.fill(_mins, Float.MAX_VALUE); Arrays.fill(_maxs, -Float.MAX_VALUE); Chunk ys = chks[fm.responseIndex]; Chunk offset = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); Chunk preds = chks[fm.tree0Index]; // Prior tree sums Chunk nids = chks[fm.nids0Index]; Chunk weights = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); for (int row = 0; row < preds._len; row++) { if (ys.isNA(row)) continue; if (weights.atd(row) == 0) continue; int nid = (int) nids.at8(row); assert (nid != ScoreBuildHistogram.UNDECIDED_CHILD_NODE_ID); if (nid < 0) continue; //skip OOB and otherwise skipped rows float f = (float) (preds.atd(row) + offset.atd(row)); int idx = nid - firstLeafIdx; _mins[idx] = Math.min(_mins[idx], f); _maxs[idx] = Math.max(_maxs[idx], f); } } @Override public void reduce(ComputeMinMax mrt) { ArrayUtils.reduceMin(_mins, mrt._mins); ArrayUtils.reduceMax(_maxs, mrt._maxs); } } private static class ComputeDiff extends MRTask<ComputeDiff> { private FrameMap fm; public ComputeDiff(FrameMap frameMap) { fm = frameMap; } @Override public void map(Chunk[] chks, NewChunk[] nc) { final Chunk y = chks[fm.responseIndex]; final Chunk o = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); final Chunk f = chks[fm.tree0Index]; for (int i = 0; i < chks[0].len(); ++i) nc[0].addNum(y.atd(i) - (f.atd(i) + o.atd(i))); } } private static class ComputeAbsDiff extends MRTask<ComputeAbsDiff> { private FrameMap fm; public ComputeAbsDiff(FrameMap frameMap) { fm = frameMap; } @Override public void map(Chunk[] chks, NewChunk[] nc) { final Chunk y = chks[fm.responseIndex]; final Chunk o = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); final Chunk f = chks[fm.tree0Index]; for (int i = 0; i < chks[0].len(); ++i) nc[0].addNum(Math.abs(y.atd(i) - (f.atd(i) + o.atd(i)))); } } public static class DiffMinusMedianDiff extends MRTask<DiffMinusMedianDiff> { private final int _strataMin; private double[] _terminalMedians; public DiffMinusMedianDiff(Vec strata, double[] terminalMedians) { _strataMin = (int) strata.min(); _terminalMedians = terminalMedians; } @Override public void map(Chunk[] chks) { final Chunk strata = chks[0]; final Chunk diff = chks[1]; for (int i = 0; i < chks[0].len(); ++i) { int nid = (int) strata.atd(i); diff.set(i, diff.atd(i) - _terminalMedians[nid - _strataMin]); } } } private static final class HuberLeafMath extends MRTask<HuberLeafMath> { // INPUT final FrameMap fm; final double _huberDelta; final Vec _strata; final int _strataMin; final int _strataMax; // OUTPUT double[/*leaves*/] _huberGamma, _wcounts; public HuberLeafMath(FrameMap frameMap, double huberDelta, Vec strata) { fm = frameMap; _huberDelta = huberDelta; _strata = strata; _strataMin = (int) _strata.min(); _strataMax = (int) _strata.max(); } @Override public void map(Chunk[] cs) { if (_strata.length() == 0) { LOG.warn("No Huber math can be done since there's no strata."); _huberGamma = new double[0]; return; } final int nstrata = _strataMax - _strataMin + 1; LOG.info("Computing Huber math for (up to) " + nstrata + " different strata."); _huberGamma = new double[nstrata]; _wcounts = new double[nstrata]; Chunk weights = fm.weightIndex >= 0 ? cs[fm.weightIndex] : new C0DChunk(1, cs[0]._len); Chunk stratum = cs[fm.nids0Index]; Chunk diffMinusMedianDiff = cs[cs.length - 1]; for (int row = 0; row < cs[0]._len; ++row) { int nidx = (int) stratum.at8(row) - _strataMin; //get terminal node for this row _huberGamma[nidx] += weights.atd(row) * Math.signum(diffMinusMedianDiff.atd(row)) * Math.min(Math.abs(diffMinusMedianDiff.atd(row)), _huberDelta); _wcounts[nidx] += weights.atd(row); } } @Override public void reduce(HuberLeafMath mrt) { ArrayUtils.add(_huberGamma, mrt._huberGamma); ArrayUtils.add(_wcounts, mrt._wcounts); } @Override protected void postGlobal() { for (int i = 0; i < _huberGamma.length; ++i) _huberGamma[i] /= _wcounts[i]; } } private static class StoreResiduals extends MRTask<StoreResiduals> { private FrameMap fm; private Distribution dist; public StoreResiduals(FrameMap frameMap, Distribution distribution) { fm = frameMap; dist = distribution; } @Override protected boolean modifiesVolatileVecs() { return true; } @Override public void map(Chunk[] chks) { Chunk ys = chks[fm.responseIndex]; Chunk offset = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); Chunk preds = chks[fm.tree0Index]; // Prior tree sums C8DVolatileChunk wk = (C8DVolatileChunk) chks[fm.work0Index]; // Place to store residuals Chunk weights = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); for (int row = 0; row < wk._len; row++) { double weight = weights.atd(row); if (weight == 0) continue; if (ys.isNA(row)) continue; double f = preds.atd(row) + offset.atd(row); double y = ys.atd(row); wk.getValues()[row] = ((float) dist.negHalfGradient(y, f)); } } } /** * Set terminal node estimates (gamma) * ESL2, page 387. Step 2b iii. * Nids <== f(Nids) * For classification (bernoulli): * <pre>{@code gamma_i = sum (w_i * res_i) / sum (w_i*p_i*(1 - p_i)) where p_i = y_i - res_i}</pre> * For classification (multinomial): * <pre>{@code gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|)))}</pre> * For regression (gaussian): * <pre>{@code gamma_i = sum res_i / count(res_i)}</pre> */ private static class GammaPass extends MRTask<GammaPass> { private final FrameMap fm; private final DTree[] _trees; // Read-only, shared (except at the histograms in the Nodes) private final int[] _leafs; // Starting index of leaves (per class-tree) private final Distribution _dist; private final int _nclass; private double[/*tree/klass*/][/*tree-relative node-id*/] _num; private double[/*tree/klass*/][/*tree-relative node-id*/] _denom; public GammaPass(FrameMap frameMap, DTree[] trees, int[] leafs, Distribution distribution, int nClasses) { fm = frameMap; _leafs = leafs; _trees = trees; _dist = distribution; _nclass = nClasses; } double gamma(int tree, int nid) { return gamma(tree, nid, _num[tree][nid]); } double gamma(int tree, int nid, double num) { if (_denom[tree][nid] == 0) return 0; double g = num / _denom[tree][nid]; assert !Double.isInfinite(g) && !Double.isNaN(g); return gamma(g); } double gamma(double g) { if (_dist._family == DistributionFamily.poisson || _dist._family == DistributionFamily.gamma || _dist._family == DistributionFamily.tweedie) { return _dist.link(g); } else { return g; } } @Override protected boolean modifiesVolatileVecs() { return true; } @Override public void map(Chunk[] chks) { _denom = new double[_nclass][]; _num = new double[_nclass][]; final Chunk resp = chks[fm.responseIndex]; // Response for this frame // For all tree/klasses for (int k = 0; k < _nclass; k++) { final DTree tree = _trees[k]; final int leaf = _leafs[k]; if (tree == null) continue; // Empty class is ignored assert (tree._len - leaf >= 0); // A leaf-biased array of all active Tree leaves. final double[] denom = _denom[k] = new double[tree._len - leaf]; final double[] num = _num[k] = new double[tree._len - leaf]; final C4VolatileChunk nids = (C4VolatileChunk) chks[fm.nids0Index + k]; // Node-ids for this tree/class int[] nids_vals = nids.getValues(); final Chunk ress = chks[fm.work0Index + k]; // Residuals for this tree/class final Chunk offset = fm.offsetIndex >= 0 ? chks[fm.offsetIndex] : new C0DChunk(0, chks[0]._len); final Chunk preds = chks[fm.tree0Index + k]; final Chunk weights = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); // If we have all constant responses, then we do not split even the // root and the residuals should be zero. if (tree.root() instanceof LeafNode) continue; for (int row = 0; row < nids._len; row++) { // For all rows double w = weights.atd(row); if (w == 0) continue; double y = resp.atd(row); //response if (Double.isNaN(y)) continue; // Compute numerator and denominator of terminal node estimate (gamma) int nid = (int) nids.at8(row); // Get Node to decide from final boolean wasOOBRow = ScoreBuildHistogram.isOOBRow(nid); //same for all k if (wasOOBRow) nid = ScoreBuildHistogram.oob2Nid(nid); if (nid < 0) continue; DecidedNode dn = tree.decided(nid); // Must have a decision point if (dn._split == null) // Unable to decide? dn = tree.decided(dn.pid()); // Then take parent's decision int leafnid = dn.getChildNodeID(chks, row); // Decide down to a leafnode assert leaf <= leafnid && leafnid < tree._len : "leaf: " + leaf + " leafnid: " + leafnid + " tree._len: " + tree._len + "\ndn: " + dn; assert tree.node(leafnid) instanceof LeafNode; // Note: I can tell which leaf/region I end up in, but I do not care for // the prediction presented by the tree. For GBM, we compute the // sum-of-residuals (and sum/abs/mult residuals) for all rows in the // leaf, and get our prediction from that. nids_vals[row] = leafnid; assert !ress.isNA(row); // OOB rows get placed properly (above), but they don't affect the computed Gamma (below) // For Laplace/Quantile distribution, we need to compute the median of (y-offset-preds == y-f), will be done outside of here if (wasOOBRow || _dist._family == DistributionFamily.laplace || _dist._family == DistributionFamily.huber || _dist._family == DistributionFamily.quantile) continue; double z = ress.atd(row); // residual double f = preds.atd(row) + offset.atd(row); int idx = leafnid - leaf; num[idx] += _dist.gammaNum(w, y, z, f); denom[idx] += _dist.gammaDenom(w, y, z, f); } } } @Override public void reduce(GammaPass gp) { ArrayUtils.add(_denom, gp._denom); ArrayUtils.add(_num, gp._num); } } private static class AddTreeContributions extends MRTask<AddTreeContributions> { private FrameMap fm; private DTree[] _ktrees; private int _nclass; private double _pred_noise_bandwidth; private long _seed; private int _ntrees1; private int _ntrees2; public AddTreeContributions( FrameMap frameMap, DTree[] ktrees, double predictionNoiseBandwidth, long seed, int nTreesInp, int nTreesOut ) { fm = frameMap; _ktrees = ktrees; _nclass = ktrees.length; _pred_noise_bandwidth = predictionNoiseBandwidth; _seed = seed; _ntrees1 = nTreesInp; _ntrees2 = nTreesOut; } @Override protected boolean modifiesVolatileVecs() { return true; } @Override public void map(Chunk[] chks) { Random rand = RandomUtils.getRNG(_seed); // For all tree/klasses for (int k = 0; k < _nclass; k++) { final DTree tree = _ktrees[k]; if (tree == null) continue; final C4VolatileChunk nids = (C4VolatileChunk) chks[fm.nids0Index + k]; final int[] nids_vals = nids.getValues(); final C8DVolatileChunk ct = (C8DVolatileChunk) chks[fm.tree0Index + k]; double[] ct_vals = ct.getValues(); final Chunk y = chks[fm.responseIndex]; final Chunk weights = fm.weightIndex >= 0 ? chks[fm.weightIndex] : new C0DChunk(1, chks[0]._len); long baseseed = (0xDECAF + _seed) * (0xFAAAAAAB + k * _ntrees1 + _ntrees2); for (int row = 0; row < nids._len; row++) { int nid = nids_vals[row]; nids_vals[row] = ScoreBuildHistogram.FRESH; if (nid < 0) { if (weights.atd(row) == 0 || y.isNA(row)) nids_vals[row] = ScoreBuildHistogram.DECIDED_ROW; continue; } double factor = 1; if (_pred_noise_bandwidth != 0) { rand.setSeed(baseseed + nid); //bandwidth is a function of tree number, class and node id (but same for all rows in that node) factor += rand.nextGaussian() * _pred_noise_bandwidth; } // Prediction stored in Leaf is cut to float to be deterministic in reconstructing // <tree_klazz> fields from tree prediction ct_vals[row] = ((float) (ct.atd(row) + factor * ((LeafNode) tree.node(nid))._pred)); } } } } // Read the 'tree' columns, do model-specific math and put the results in the // fs[] array, and return the sum. Dividing any fs[] element by the sum // turns the results into a probability distribution. @Override protected double score1(Chunk[] chks, double weight, double offset, double[/*nclass*/] fs, int row) { return score1static(chks, idx_tree(0), offset, fs, row, DistributionFactory.getDistribution(_parms), _nclass); } // Read the 'tree' columns, do model-specific math and put the results in the // fs[] array, and return the sum. Dividing any fs[] element by the sum // turns the results into a probability distribution. private static double score1static(Chunk[] chks, int treeIdx, double offset, double[] fs, int row, Distribution dist, int nClasses) { double f = chks[treeIdx].atd(row) + offset; double p = dist.linkInv(f); if (dist._family == DistributionFamily.modified_huber || dist._family == DistributionFamily.bernoulli || dist._family == DistributionFamily.quasibinomial || (dist._family == DistributionFamily.custom && nClasses == 2)) { fs[2] = p; fs[1] = 1.0 - p; return 1; // f2 = 1.0 - f1; so f1+f2 = 1.0 } else if (dist._family == DistributionFamily.multinomial || (dist._family == DistributionFamily.custom && nClasses > 2)) { if (nClasses == 2) { // This optimization assumes the 2nd tree of a 2-class system is the // inverse of the first. Fill in the missing tree fs[1] = p; fs[2] = 1 / p; return fs[1] + fs[2]; } // Multinomial loss function; sum(exp(data)). Load tree data assert (offset == 0); fs[1] = f; for (int k = 1; k < nClasses; k++) fs[k + 1] = chks[treeIdx + k].atd(row); // Rescale to avoid Infinities; return sum(exp(data)) return hex.genmodel.GenModel.log_rescale(fs); } else { return fs[0] = p; } } }
package org.epistem.diagram.owl; import java.io.File; import java.io.FileOutputStream; import junit.framework.TestCase; import org.epistem.diagram.model.Diagram; import org.epistem.diagram.model.Page; import org.epistem.graffle.OmniGraffleDoc; import org.semanticweb.owlapi.io.DefaultOntologyFormat; import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat; import org.semanticweb.owlapi.io.StreamDocumentTarget; import org.semanticweb.owlapi.io.StringDocumentTarget; public class OWLEmitterTest extends TestCase { private Diagram diagram; private OWLEmitter emitter; public OWLEmitterTest( String name ) throws Exception { super( name ); } @Override protected void setUp() throws Exception { super.setUp(); File file = new File( "test-diagrams/test-owl.graffle" ); OmniGraffleDoc doc = new OmniGraffleDoc( file ); diagram = new Diagram( doc ); emitter = new OWLEmitter( diagram ); } public void testNamespaces() { assertEquals( "http: assertEquals( "http: } public void testObjectProps() { processPage( "Obj Props" ); ontologyAssertions( "Declaration(ObjectProperty(<http://www.test.com/test#obj-prop-b>))", "FunctionalObjectProperty(<http://www.test.com/test#obj-prop1>)", "ReflexiveObjectProperty(<http://www.test.com/test#obj-prop2>)", "InverseFunctionalObjectProperty(<http://www.test.com/test#obj-prop3>)", "IrreflexiveObjectProperty(<http://www.test.com/test#obj-prop4>)", "SymmetricObjectProperty(<http://www.test.com/test#obj-prop5>)", "TransitiveObjectProperty(<http://www.test.com/test#obj-prop6>)", "AsymmetricObjectProperty(<http://www.test.com/test#obj-prop7>)", "EquivalentObjectProperties(<http://www.test.com/test "InverseObjectProperties(<http://www.test.com/test "DisjointObjectProperties(<http://www.test.com/test "DisjointObjectProperties(<http://www.test.com/test "SubObjectPropertyOf(<http://www.test.com/test "ObjectPropertyDomain(<http://www.test.com/test "ObjectPropertyRange(<http://www.test.com/test "SubObjectPropertyOf(ObjectPropertyChain(<http://www.test.com/test ); } public void testDataClassExprs() { processPage( "Class Data Exprs" ); ontologyAssertions( "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test ); } public void testDataRanges() { processPage( "Data Ranges" ); ontologyAssertions( "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "Declaration(Datatype(<http://www.test.com/test#foo-bar>))", "DatatypeDefinition(<http://www.test.com/test#foo-bar> DataOneOf(\"wonka\"^^xsd:string \"3\"^^xsd:integer))", "SubClassOf(<http://www.test.com/test +"DatatypeRestriction(xsd:integer ", "xsd:maxExclusive \"66\"^^xsd:integer", "xsd:minInclusive \"45\"^^xsd:integer" ); } public void testDataProps() { processPage( "Data Props" ); ontologyAssertions( "Declaration(DataProperty(<http://www.test.com/test#data-prop-a>))", "DataPropertyDomain(<http://www.test.com/test "EquivalentDataProperties(<http://www.test.com/test "DisjointDataProperties(<http://www.test.com/test "DisjointDataProperties(<http://www.test.com/test "FunctionalDataProperty(<http://www.test.com/test#data-prop-i>)", "SubDataPropertyOf(<http://www.test.com/test "DataPropertyRange(<http://www.test.com/test#data-prop-a> xsd:nonNegativeInteger)" ); } public void testIndividuals() { processPage( "Individuals" ); ontologyAssertions( "Declaration(NamedIndividual(<http://www.test.com/test#IndividualA>))", "SameIndividual(<http://www.test.com/test "DifferentIndividuals(<http://www.test.com/test "ClassAssertion(<http://www.test.com/test "ObjectPropertyAssertion(<http://www.test.com/test "NegativeObjectPropertyAssertion(<http://www.test.com/test "ObjectPropertyAssertion(ObjectInverseOf(<http://www.test.com/test "DataPropertyAssertion(<http://www.test.com/test "NegativeDataPropertyAssertion(<http://www.test.com/test ); } public void testClassExpressions() { processPage( "Class Exprs" ); ontologyAssertions( "SubClassOf(<http://www.test.com/test "EquivalentClasses(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "EquivalentClasses(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test ); } public void testObjectCardinalityExpressions() { processPage( "Class Exprs" ); ontologyAssertions( "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test "SubClassOf(<http://www.test.com/test ); } public void testSubclassOf() { processPage( "Class Axioms" ); ontologyAssertions( "SubClassOf(<http://www.test.com/test#ClassA> owl:Thing)", "SubClassOf(<http://www.test.com/test ); } public void testEquivalentClasses() { processPage( "Class Axioms" ); ontologyAssertions( "EquivalentClasses(<http://www.test.com/test ); } public void testDisjointClasses() { processPage( "Class Axioms" ); ontologyAssertions( "DisjointClasses(<http://www.test.com/test "DisjointClasses(<http://www.test.com/test "DisjointUnion(<http://www.test.com/test ); } public void testSWRL() { processPage( "SWRL" ); ontologyAssertions( "DLSafeRule(Body(BuiltInAtom(<http://www.w3.org/2003/11/swrlb "DLSafeRule(Body(DifferentIndividualsAtom(Variable(<http://www.test.com/test "DLSafeRule(Body(BuiltInAtom(<http://www.w3.org/2003/11/swrlb "DLSafeRule(Body(SameIndividualAtom(Variable(<http://www.test.com/test ); } public void testHasKey() { processPage( "Class Axioms" ); ontologyAssertions( "HasKey(<http://www.test.com/test ); } public void testDumpOntology() { emitter.processDiagram(); System.out.println( ontologyToString() ); } //save ontology so that it can examined in Protege public void testSaveOntology() throws Exception { emitter.processDiagram(); File genDir = new File( "generated" ); genDir.mkdirs(); FileOutputStream out = new FileOutputStream( new File( genDir, "test.rdf" ) ); emitter.saveOntology( new DefaultOntologyFormat(), new StreamDocumentTarget( out ) ); out.close(); } //assert that strings are contained in ontology functional syntax private void ontologyAssertions( String...strings ) { String ontolText = ontologyToString(); for( int i = 0; i < strings.length; i++ ) { assertTrue( strings[i], ontolText.contains( strings[i] ) ); } } //get the ontology as a functional-syntax string private String ontologyToString() { StringDocumentTarget target = new StringDocumentTarget(); emitter.saveOntology( new OWLFunctionalSyntaxOntologyFormat(), target ); return target.toString(); } /** Process just one page */ private void processPage( String pageName ) { for( Page page : diagram.pages ) { if( pageName.equals( page.title ) ) { emitter.processPage( page ); } } } }
package owltools.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntologyIRIMapper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * {@link OWLOntologyIRIMapper} using the mappings from a catalog.xml file. */ public class CatalogXmlIRIMapper implements OWLOntologyIRIMapper { private static final Logger logger = Logger.getLogger(CatalogXmlIRIMapper.class); private final Map<IRI, IRI> mappings; CatalogXmlIRIMapper(Map<IRI, IRI> mappings) { this.mappings = mappings; } /** * Create an CatalogXmlIRIMapper from the given catalog.xml file. * Assume, that relative paths are relative to the catalog file location. * * @param catalogFile * @throws IOException */ public CatalogXmlIRIMapper(String catalogFile) throws IOException { this(new File(catalogFile).getAbsoluteFile()); } /** * Create an CatalogXmlIRIMapper from the given catalog.xml file. * Assume, that relative paths are relative to the catalog file location. * * @param catalogFile * @throws IOException */ public CatalogXmlIRIMapper(File catalogFile) throws IOException { this(catalogFile, catalogFile.getAbsoluteFile().getParentFile()); } /** * Create an CatalogXmlIRIMapper from the given catalog.xml file. * Use the parentFolder to resolve relative paths from the catalog file. * * @param catalogFile * @param parentFolder * @throws IOException */ public CatalogXmlIRIMapper(File catalogFile, File parentFolder) throws IOException { this(parseCatalogXml(new FileInputStream(catalogFile), parentFolder)); } /** * Create an CatalogXmlIRIMapper from the given catalog URL. * Assume, there are no relative paths in the catalog file. * * @param catalogURL * @throws IOException */ public CatalogXmlIRIMapper(URL catalogURL) throws IOException { if ("file".equals(catalogURL.getProtocol())) { try { File catalogFile = new File(catalogURL.toURI()); mappings = parseCatalogXml(new FileInputStream(catalogFile), catalogFile.getParentFile()); } catch (URISyntaxException e) { throw new IOException(e); } } else { mappings = parseCatalogXml(catalogURL.openStream(), null); } } /** * Create an CatalogXmlIRIMapper from the given catalog URL. * Use the parentFolder to resolve relative paths from the catalog file. * * @param catalogURL * @param parentFolder * @throws IOException */ public CatalogXmlIRIMapper(URL catalogURL, File parentFolder) throws IOException { this(parseCatalogXml(catalogURL.openStream(), parentFolder)); } @Override public IRI getDocumentIRI(IRI ontologyIRI) { return mappings.get(ontologyIRI); } static Map<IRI, IRI> parseCatalogXml(InputStream inputStream, final File parentFolder) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("InputStream should never be null, missing resource?"); } // use the Java built-in SAX parser SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); try { final Map<IRI, IRI> mappings = new HashMap<IRI, IRI>(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(inputStream, new DefaultHandler(){ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // only look at 'uri' tags // does not check any parent tags if ("uri".equals(qName)) { IRI original = null; IRI mapped = null; String nameString = attributes.getValue("name"); if (nameString != null) { original = IRI.create(nameString); } String mappedString = attributes.getValue("uri"); if (mappedString != null) { if (parentFolder != null && mappedString.indexOf(":") < 0) { // there is a parent folder and the mapping is not an IRI or URL File file = new File(mappedString); if (!file.isAbsolute()) { file = new File(parentFolder, mappedString); } try { file = file.getCanonicalFile(); mapped = IRI.create(file); } catch (IOException e) { logger.warn("Skipping mapping: "+nameString+" "+mappedString, e); } } else { mapped = IRI.create(mappedString); } } if (original != null && mapped != null) { mappings.put(original, mapped); } } } }); return mappings; } catch (ParserConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } finally { inputStream.close(); } } }
package com.rizki.mufrizal.spring.oauth2.custom.configuration; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @Configuration @PropertySource("classpath:application.yml") public class DataSourceConfiguration { @Autowired private Environment environment; @Bean(destroyMethod = "close") public DataSource dataSource() { HikariConfig dataSourceConfig = new HikariConfig(); dataSourceConfig.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name")); dataSourceConfig.setJdbcUrl(environment.getRequiredProperty("spring.datasource.url")); dataSourceConfig.setUsername(environment.getRequiredProperty("spring.datasource.username")); dataSourceConfig.setPassword(environment.getRequiredProperty("spring.datasource.password")); dataSourceConfig.setMaximumPoolSize(Integer.parseInt(environment.getRequiredProperty("spring.datasource.maximumPoolSize"))); dataSourceConfig.setMinimumIdle(Integer.parseInt(environment.getRequiredProperty("spring.datasource.minimumIdle"))); dataSourceConfig.setMaxLifetime(Integer.parseInt(environment.getRequiredProperty("spring.datasource.maxLifetime"))); dataSourceConfig.setConnectionTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.connectionTimeout"))); dataSourceConfig.setIdleTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.idleTimeout"))); dataSourceConfig.addDataSourceProperty("poolName", environment.getRequiredProperty("spring.datasource.poolName")); dataSourceConfig.addDataSourceProperty("cachePrepStmts", "true"); dataSourceConfig.addDataSourceProperty("prepStmtCacheSize", "250"); dataSourceConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); return new HikariDataSource(dataSourceConfig); } }
package com.welovecoding.netbeans.plugin.editorconfig.processor; import static com.welovecoding.netbeans.plugin.editorconfig.config.Settings.ENCODING_SETTING; import com.welovecoding.netbeans.plugin.editorconfig.mapper.EditorConfigPropertyMapper; import com.welovecoding.netbeans.plugin.editorconfig.model.EditorConfigConstant; import com.welovecoding.netbeans.plugin.editorconfig.processor.io.DocumentReaderWriter; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.IndentSizeOperation; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.IndentStyleOperation; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.XFinalNewLineOperation; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.XLineEndingOperation; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.XTabWidthOperation; import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.XTrimTrailingWhitespacesOperation; import com.welovecoding.netbeans.plugin.editorconfig.util.FileAccessException; import com.welovecoding.netbeans.plugin.editorconfig.util.NetBeansFileUtil; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javax.swing.text.BadLocationException; import javax.swing.text.StyledDocument; import org.editorconfig.core.EditorConfig; import org.editorconfig.core.EditorConfigException; import org.netbeans.editor.BaseDocument; import org.netbeans.modules.editor.indent.spi.CodeStylePreferences; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.text.NbDocument; import org.openide.util.Exceptions; public class EditorConfigProcessor { private static final Logger LOG = Logger.getLogger(EditorConfigProcessor.class.getSimpleName()); public static final Level OPERATION_LOG_LEVEL = Level.WARNING; private final EditorConfig ec; public EditorConfigProcessor() { ec = new EditorConfig(".editorconfig", EditorConfig.VERSION); } private HashMap<String, String> parseRulesForFile(DataObject dataObject) { String filePath = dataObject.getPrimaryFile().getPath(); LOG.log(Level.INFO, "Apply rules for: {0}", filePath); List<EditorConfig.OutPair> rules = new ArrayList<>(); HashMap<String, String> keyedRules = new HashMap<>(); try { rules = ec.getProperties(filePath); } catch (EditorConfigException ex) { LOG.log(Level.SEVERE, ex.getMessage()); } for (EditorConfig.OutPair rule : rules) { keyedRules.put(rule.getKey().toLowerCase(), rule.getVal().toLowerCase()); } return keyedRules; } public void applyRulesToFile(DataObject dataObject) throws Exception { HashMap<String, String> keyedRules = parseRulesForFile(dataObject); // Save file before appling any changes when opened in editor EditorCookie cookie = getEditorCookie(dataObject); boolean isOpenedInEditor = (cookie != null) && (cookie.getDocument() != null); FileObject fileObject = dataObject.getPrimaryFile(); StringBuilder content = new StringBuilder(fileObject.asText()); boolean fileChangeNeeded = false; boolean charsetChangeNeeded = false; boolean styleChangeNeeded = false; for (Map.Entry<String, String> rule : keyedRules.entrySet()) { final String key = rule.getKey(); final String value = rule.getValue(); LOG.log(Level.INFO, "Found rule \"{0}\" with value \"{1}\".", new Object[]{key, value}); switch (key) { case EditorConfigConstant.CHARSET: charsetChangeNeeded = doCharset(fileObject, keyedRules.get(EditorConfigConstant.CHARSET)); break; case EditorConfigConstant.END_OF_LINE: String ecLineEnding = keyedRules.get(EditorConfigConstant.END_OF_LINE); boolean changedLineEndings = doEndOfLine(dataObject, ecLineEnding); fileChangeNeeded = fileChangeNeeded || changedLineEndings; break; case EditorConfigConstant.INDENT_SIZE: //TODO this should happen in the file!! boolean indentSizeChanged = IndentSizeOperation.doIndentSize(dataObject, value); if (indentSizeChanged) { LOG.log(Level.INFO, "Action: Indent size changed"); } styleChangeNeeded = indentSizeChanged || styleChangeNeeded; break; case EditorConfigConstant.INDENT_STYLE: //TODO this happens in the file!! boolean indentStyleChanged = IndentStyleOperation.doIndentStyle(dataObject, key); if (indentStyleChanged) { LOG.log(Level.INFO, "Action: Indent style changed"); } styleChangeNeeded = indentStyleChanged || styleChangeNeeded; break; case EditorConfigConstant.INSERT_FINAL_NEWLINE: String lineEnding = keyedRules.get(EditorConfigConstant.END_OF_LINE); String javaLineEnding = EditorConfigPropertyMapper.mapLineEnding(lineEnding); boolean newLineChanged = XFinalNewLineOperation.doFinalNewLine(content, value, javaLineEnding); fileChangeNeeded = newLineChanged || fileChangeNeeded; break; case EditorConfigConstant.TAB_WIDTH: boolean tabWidthChanged = XTabWidthOperation.doTabWidth(dataObject, value); if (tabWidthChanged) { LOG.log(Level.INFO, "Action: Tab width changed"); } styleChangeNeeded = tabWidthChanged || styleChangeNeeded; break; case EditorConfigConstant.TRIM_TRAILING_WHITESPACE: boolean trimTrailingWhitespacesChanged = XTrimTrailingWhitespacesOperation.doTrimTrailingWhitespaces( content, value, EditorConfigPropertyMapper.mapLineEnding(keyedRules.get(EditorConfigConstant.END_OF_LINE))); if (trimTrailingWhitespacesChanged) { LOG.log(Level.INFO, "Action: Trailing whitespaces changed"); } fileChangeNeeded = trimTrailingWhitespacesChanged || fileChangeNeeded; break; default: LOG.log(Level.WARNING, "Unknown property: {0}", key); break; } } FileInfo info = new FileInfo(dataObject); info.setContent(content); info.setCharset(EditorConfigPropertyMapper.mapCharset(keyedRules.get(EditorConfigConstant.CHARSET))); info.setOpenedInEditor(isOpenedInEditor); info.setCookie(cookie); if (charsetChangeNeeded) { String ecCharset = keyedRules.get(EditorConfigConstant.CHARSET); String fileMark = EditorConfigPropertyMapper.getFileMark(ecCharset); Charset charset = EditorConfigPropertyMapper.mapCharset(ecCharset); info.setCharset(charset); info.setFileMark(fileMark); } if (fileChangeNeeded || charsetChangeNeeded) { flushFile(info); } if (styleChangeNeeded) { flushStyles(fileObject); } } private void flushFile(FileInfo info) { if (info.isOpenedInEditor()) { updateChangesInEditorWindow(info); } else { updateChangesInFile(info); } } private void updateChangesInFile(FileInfo info) { LOG.log(Level.INFO, "Write content (with all rules applied) to file: {0}", info.getFileObject().getPath()); WriteStringToFileTask task = new WriteStringToFileTask(info); task.run(); } private void updateChangesInEditorWindow(FileInfo info) { EditorCookie cookie = info.getCookie(); LOG.log(Level.INFO, "Update changes in Editor window for: {0}", info.getPath()); NbDocument.runAtomic(cookie.getDocument(), () -> { try { DocumentReaderWriter.writeWithEditorKit(info); } catch (FileAccessException ex) { LOG.log(Level.SEVERE, ex.getMessage()); } }); } private boolean doCharset(FileObject fileObject, String charset) { boolean hasToBeChanged = false; Charset currentCharset = NetBeansFileUtil.guessCharset(fileObject); Charset requestedCharset = EditorConfigPropertyMapper.mapCharset(charset); if (!currentCharset.equals(requestedCharset)) { LOG.log(Level.INFO, "Charset change needed from {0} to {1}", new Object[]{currentCharset.name(), requestedCharset.name()}); hasToBeChanged = true; } return hasToBeChanged; } private boolean doEndOfLine(DataObject dataObject, String ecLineEnding) { FileObject fileObject = dataObject.getPrimaryFile(); String javaLineEnding = EditorConfigPropertyMapper.mapLineEnding(ecLineEnding); boolean wasChanged = false; try { StringBuilder content = new StringBuilder(fileObject.asText()); wasChanged = XLineEndingOperation.doLineEndings(content, javaLineEnding); } catch (IOException ex) { Exceptions.printStackTrace(ex); } StyledDocument document = NbDocument.getDocument(dataObject); if (document != null && wasChanged) { if (!document.getProperty(BaseDocument.READ_LINE_SEPARATOR_PROP).equals(javaLineEnding)) { document.putProperty(BaseDocument.READ_LINE_SEPARATOR_PROP, javaLineEnding); LOG.log(Level.INFO, "Action: Changed line endings in Document."); } else { LOG.log(Level.INFO, "Action not needed: Line endings are already set to: {0}", ecLineEnding); } } return wasChanged; } private void flushStyles(FileObject fileObject) { try { Preferences codeStyle = CodeStylePreferences.get(fileObject, fileObject.getMIMEType()).getPreferences(); codeStyle.flush(); } catch (BackingStoreException ex) { LOG.log(Level.SEVERE, "Error applying code style: {0}", ex.getMessage()); } } private EditorCookie getEditorCookie(DataObject dataObject) { return dataObject.getLookup().lookup(EditorCookie.class); } }
package de.tum.in.www1.artemis.config.migration.entries; import java.util.List; import org.jasypt.exceptions.EncryptionOperationNotPossibleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import de.tum.in.www1.artemis.config.migration.MigrationEntry; import de.tum.in.www1.artemis.domain.User; import de.tum.in.www1.artemis.repository.UserRepository; import de.tum.in.www1.artemis.security.SecurityUtils; import de.tum.in.www1.artemis.service.user.LegacyPasswordService; /** * This migration separates the users into internal and external users and sets the newly created attribute isInternal in {@link User} */ @Component public class MigrationEntry20211214_184200 extends MigrationEntry { private static final Logger LOGGER = LoggerFactory.getLogger(MigrationEntry20211214_184200.class); private final UserRepository userRepository; private final LegacyPasswordService passwordService; public MigrationEntry20211214_184200(UserRepository userRepository, LegacyPasswordService passwordService) { this.userRepository = userRepository; this.passwordService = passwordService; } /** * Retrieves all users from the database and executes the processing method in batches of a 100 users to prevent database timeouts */ @Override public void execute() { SecurityUtils.setAuthorizationObject(); int listSize = 100; // false is the default value so if they were already set to true, this migration probably runs on a fresh system List<User> users = userRepository.findAllByInternal(false); LOGGER.info("Found {} users to process with `User.isInternal=false`.", users.size()); int remainder = users.size() % listSize; int listCount = (int) Math.floor(users.size() / 100f); for (int i = 0; i < listCount; i++) { List<User> sublist = users.subList(i * listSize, (i + 1) * listSize); processUsers(sublist); } if (remainder > 0) { List<User> sublist = users.subList(listCount * listSize, (listCount * listSize) + remainder); processUsers(sublist); } } /** * Sets a user internal if the password is decryptable and is not empty. Otherwise, the user is external. * If the user is external, the password will be set to an empty encrypted password as a default. Additionally, password reset fields get set to default. * * @param userList a batch of at max 100 users to be processed */ private void processUsers(List<User> userList) { userList = userList.stream().peek(user -> { // This user is either already external or a user with a default `isInternal` value String encryptedPassword = user.getPassword(); // Users without a password or with a Bcrypt password that are set to isInternal=false have to be old users => Cleanup // Keep in mind that we already don't have any proper internal users at this stage if (encryptedPassword == null || encryptedPassword.matches("^\\$2[abxy]\\$\\d{2}\\$.*$")) { user.setInternal(false); user.setPassword(passwordService.encryptPassword("")); } else { try { String decryptedPassword = passwordService.decryptPassword(user); user.setInternal(!decryptedPassword.isEmpty()); } catch (EncryptionOperationNotPossibleException e) { // Broken encryption, fall back to cleanup (see above) user.setInternal(false); user.setPassword(passwordService.encryptPassword("")); } } if (!user.isInternal()) { user.setResetDate(null); user.setResetKey(null); } }).toList(); userRepository.saveAll(userList); } /** * @return Author of the entry. Either full name or GitHub name. */ @Override public String author() { return "julian-christl"; } /** * Format YYYYMMDD_HHmmss * * @return Current time in given format */ @Override public String date() { return "20211214_184200"; } }
package jp.ikedam.jenkins.plugins.scoringloadbalancer.rules; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import antlr.ANTLRException; import hudson.Extension; import hudson.Util; import hudson.matrix.MatrixConfiguration; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Label; import hudson.model.Node; import hudson.model.Queue.Task; import hudson.model.labels.LabelExpression; import hudson.model.queue.MappingWorksheet.Mapping; import hudson.model.queue.MappingWorksheet.WorkChunk; import hudson.model.queue.SubTask; import hudson.util.FormValidation; import jp.ikedam.jenkins.plugins.scoringloadbalancer.ScoringRule; import jp.ikedam.jenkins.plugins.scoringloadbalancer.ScoringLoadBalancer.NodesScore; import jp.ikedam.jenkins.plugins.scoringloadbalancer.preferences.BuildPreference; import jp.ikedam.jenkins.plugins.scoringloadbalancer.preferences.BuildPreferenceJobProperty; import jp.ikedam.jenkins.plugins.scoringloadbalancer.preferences.BuildPreferenceNodeProperty; import jp.ikedam.jenkins.plugins.scoringloadbalancer.util.ValidationUtil; /** * Scores nodes depending on preferences of nodes and projects. */ public class NodePreferenceScoringRule extends ScoringRule { private static Logger LOGGER = Logger.getLogger(NodePreferenceScoringRule.class.getName()); private int nodesPreferenceScale; private int projectPreferenceScale; /** * @return the nodesPreferenceScale */ public int getNodesPreferenceScale() { return nodesPreferenceScale; } /** * @return the projectPreferenceScale */ public int getProjectPreferenceScale() { return projectPreferenceScale; } /** * Constructor. * * Initialized with values a user configured. * * @param nodesPreferenceScale * @param projectPreferenceScale */ @DataBoundConstructor public NodePreferenceScoringRule(int nodesPreferenceScale, int projectPreferenceScale) { this.nodesPreferenceScale = nodesPreferenceScale; this.projectPreferenceScale = projectPreferenceScale; } /** * Scores nodes depending on preferences of nodes and projects. * * @param task * @param wc * @param m * @param nodesScore * @return * @see jp.ikedam.jenkins.plugins.scoringloadbalancer.ScoringRule#updateScores(hudson.model.Queue.Task, hudson.model.queue.MappingWorksheet.WorkChunk, hudson.model.queue.MappingWorksheet.Mapping, jp.ikedam.jenkins.plugins.scoringloadbalancer.ScoringLoadBalancer.NodesScore) */ @Override public boolean updateScores(Task task, WorkChunk wc, Mapping m, NodesScore nodesScore) { // scores by preference configured in nodes. for(Node node: nodesScore.getNodes()) { List<BuildPreferenceNodeProperty> prefList = Util.filter(node.getNodeProperties(), BuildPreferenceNodeProperty.class); if(prefList == null || prefList.isEmpty()) { continue; } BuildPreferenceNodeProperty pref = prefList.get(0); nodesScore.addScore(node, pref.getPreference() * getNodesPreferenceScale()); } // scores by preference configured in projects. for(SubTask subtask: wc) { BuildPreferenceJobProperty prefs = getBuildPreferenceJobProperty(subtask); if(prefs == null || prefs.getBuildPreferenceList() == null) { continue; } for(BuildPreference pref: prefs.getBuildPreferenceList()) { try { Label l = LabelExpression.parseExpression(pref.getLabelExpression()); for(Node node: nodesScore.getNodes()) { if(!l.contains(node)) { continue; } nodesScore.addScore(node, pref.getPreference() * getProjectPreferenceScale()); } } catch(ANTLRException e) { LOGGER.log(Level.WARNING, String.format("Skipped an invalid label: %s (configured in %s)", pref.getLabelExpression(), subtask.toString()), e); } } } return true; } private BuildPreferenceJobProperty getBuildPreferenceJobProperty(SubTask subtask) { if(!(subtask instanceof Job)) { return null; } if(subtask instanceof MatrixConfiguration) { MatrixConfiguration conf = (MatrixConfiguration)subtask; return conf.getParent().getProperty(BuildPreferenceJobProperty.class); } Job<?,?> job = (Job<?,?>)subtask; return job.getProperty(BuildPreferenceJobProperty.class); } /** * Manages views for {@link NodePreferenceScoringRule} */ @Extension public static class DescriptorImpl extends Descriptor<ScoringRule> { /** * Returns the name to display. * * Displayed in System Configuration page, as a name of a scoring rule. * * @return the name to display * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return Messages.NodePreferenceScoringRule_DisplayName(); } /** * Verify the input nodesPreferenceScale. * * @param value * @return */ public FormValidation doCheckNodesPreferenceScale(@QueryParameter String value) { return ValidationUtil.doCheckInteger(value); } /** * Verify the input projectPreferenceScale. * * @param value * @return */ public FormValidation doCheckProjectPreferenceScale(@QueryParameter String value) { return ValidationUtil.doCheckInteger(value); } } }
package org.mtransit.parser.ca_lethbridge_transit_bus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.commons.CharUtils; import org.mtransit.commons.CleanUtils; import org.mtransit.commons.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.MTLog; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.mt.data.MAgency; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.mtransit.parser.StringUtils.EMPTY; public class LethbridgeTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@Nullable String[] args) { new LethbridgeTransitBusAgencyTools().start(args); } @Override public boolean defaultExcludeEnabled() { return true; } @NotNull @Override public String getAgencyName() { return "Lethbridge Transit"; } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final long RID_ENDS_WITH_A = 10_000L; private static final long RID_ENDS_WITH_B = 20_000L; private static final long RID_ENDS_WITH_C = 30_000L; private static final long RID_STARTS_WITH_N = 140_000L; private static final long RID_STARTS_WITH_S = 190_000L; @Override public long getRouteId(@NotNull GRoute gRoute) { if (CharUtils.isDigitsOnly(gRoute.getRouteShortName())) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } final Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName()); if (matcher.find()) { final long digits = Long.parseLong(matcher.group()); final String rsnLC = gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH); if (rsnLC.endsWith("a")) { return RID_ENDS_WITH_A + digits; } else if (rsnLC.endsWith("b")) { return RID_ENDS_WITH_B + digits; } else if (rsnLC.endsWith("c")) { return RID_ENDS_WITH_C + digits; } if (rsnLC.endsWith("n")) { return RID_STARTS_WITH_N + digits; } else if (rsnLC.endsWith("s")) { return RID_STARTS_WITH_S + digits; } } throw new MTLog.Fatal("Unexpected route ID for %s!", gRoute.toStringPlus()); } private static final String _SLASH_ = " / "; @NotNull @SuppressWarnings("DuplicateBranchesInSwitch") @Override public String getRouteLongName(@NotNull GRoute gRoute) { String routeLongName = gRoute.getRouteLongNameOrDefault(); if (StringUtils.isEmpty(routeLongName)) { routeLongName = gRoute.getRouteDescOrDefault(); // using route description as route long name } if (StringUtils.isEmpty(routeLongName)) { if (CharUtils.isDigitsOnly(gRoute.getRouteShortName())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 12: return "University" + _SLASH_ + "Downtown"; case 23: return "Mayor Magrath" + _SLASH_ + "Scenic"; // Counter Clockwise Loop case 24: return "Mayor Magrath" + _SLASH_ + "Scenic"; // Clockwise case 31: return "Legacy Rdg" + _SLASH_ + "Uplands"; case 32: return "Indian Battle"+_SLASH_+ "Columbia Blvd"; // Indian Battle Heights, Varsity Village case 33: return "Heritage" + _SLASH_ + "West Highlands" ; // Ridgewood, Heritage, West Highlands case 35: return "Copperwood"; // Copperwood case 36: return "Sunridge"; // Sunridge, Riverstone, Mtn Hts case 37: return "Garry Station"; // @formatter:on } } if ("20N".equalsIgnoreCase(gRoute.getRouteShortName())) { return "North Terminal"; } else if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) { return "South Enmax"; } else if ("21N".equalsIgnoreCase(gRoute.getRouteShortName())) { return "Nord-Bridge"; } else if ("21S".equalsIgnoreCase(gRoute.getRouteShortName())) { return "Henderson Lk" + _SLASH_ + "Industrial"; } else if ("22N".equalsIgnoreCase(gRoute.getRouteShortName())) { return "North Terminal"; // 22 North } else if ("22S".equalsIgnoreCase(gRoute.getRouteShortName())) { return "South Gate"; } throw new MTLog.Fatal("Unexpected route long name for %s!", gRoute); } return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_BLUE_LIGHT = "009ADE"; // BLUE LIGHT (from web site CSS) private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE_LIGHT; @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } @Nullable @Override public String getRouteColor(@NotNull GRoute gRoute) { if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) { if ("80FF00".equalsIgnoreCase(gRoute.getRouteColor())) { // too light return "81CC2B"; // darker (from PDF schedule) } } else if ("32".equalsIgnoreCase(gRoute.getRouteShortName())) { if ("73CFFF".equalsIgnoreCase(gRoute.getRouteColor())) { // too light return "76AFE3"; // darker (from PDF schedule) } } else if ("36".equalsIgnoreCase(gRoute.getRouteShortName())) { if ("80FF80".equalsIgnoreCase(gRoute.getRouteColor())) { // too light return "4DB8A4"; // darker (from PDF schedule) } } return super.getRouteColor(gRoute); } @Override public boolean directionSplitterEnabled() { return true; } @Override public boolean directionSplitterEnabled(long routeId) { //noinspection RedundantIfStatement if (routeId == 20L + RID_STARTS_WITH_N // 20N || routeId == 22L + RID_STARTS_WITH_N // 22N || routeId == 22L + RID_STARTS_WITH_S // 22S ) { return true; // OVERRIDE provided direction_id INVALID (used for "via " / trip variation) } return false; } @Override public boolean directionFinderEnabled() { return true; } private static final Pattern ENDS_WITH_LOOP = Pattern.compile("([\\s]*loop$)", Pattern.CASE_INSENSITIVE); private static final Pattern ENDS_WITH_ROUTE = Pattern.compile("([\\s]*route$)", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { tripHeadsign = ENDS_WITH_LOOP.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = ENDS_WITH_ROUTE.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = CleanUtils.fixMcXCase(tripHeadsign); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanBounds(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private String[] getIgnoredWords() { return new String[]{"ATB"}; } @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, gStopName, getIgnoredWords()); gStopName = CleanUtils.fixMcXCase(gStopName); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.cleanBounds(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public int getStopId(@NotNull GStop gStop) { if (CharUtils.isDigitsOnly(gStop.getStopCode())) { return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID } final Matcher matcher = DIGITS.matcher(gStop.getStopCode()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); if (gStop.getStopCode().startsWith("MESC")) { return 13_050_000 + digits; } } throw new MTLog.Fatal("Unexpected stop ID for %s!", gStop); } }
package net.sf.mzmine.modules.peaklistmethods.identification.dbsearch.databases; import java.io.IOException; import java.net.URL; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.mzmine.modules.peaklistmethods.identification.dbsearch.DBCompound; import net.sf.mzmine.modules.peaklistmethods.identification.dbsearch.DBGateway; import net.sf.mzmine.modules.peaklistmethods.identification.dbsearch.OnlineDatabase; import net.sf.mzmine.parameters.parametertypes.MZTolerance; import net.sf.mzmine.util.InetUtils; import net.sf.mzmine.util.Range; public class MassBankGateway implements DBGateway { // Unfortunately, we need to list all the instrument types here private static final String instrumentTypes[] = { "EI-B", "EI-EBEB", "GC-EI-TOF", "CE-ESI-TOF", "ESI-IT-MS/MS", "ESI-QqQ-MS/MS", "ESI-QqTOF-MS/MS", "LC-ESI-IT", "LC-ESI-ITFT", "LC-ESI-ITTOF", "LC-ESI-Q", "LC-ESI-QIT", "LC-ESI-QQ", "LC-ESI-QTOF", "CI-B", "FAB-B", "FAB-EB", "FAB-EBEB", "FD-B", "FI-B", "MALDI-TOF" }; private static final String massBankSearchAddress = "http: private static final String massBankEntryAddress = "http: public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults) throws IOException { Range toleranceRange = mzTolerance.getToleranceRange(mass); StringBuilder queryAddress = new StringBuilder(massBankSearchAddress); for (String inst : instrumentTypes) { queryAddress.append("&inst="); queryAddress.append(inst); } queryAddress.append("&mz="); queryAddress.append(toleranceRange.getAverage()); queryAddress.append("&tol="); queryAddress.append(toleranceRange.getSize() / 2); URL queryURL = new URL(queryAddress.toString()); // Submit the query String queryResult = InetUtils.retrieveData(queryURL); Vector<String> results = new Vector<String>(); // Find IDs in the HTML data Pattern pat = Pattern .compile("&nbsp;&nbsp;&nbsp;&nbsp;([A-Z0-9]{8})&nbsp;"); Matcher matcher = pat.matcher(queryResult); while (matcher.find()) { String MID = matcher.group(1); results.add(MID); if (results.size() == numOfResults) break; } return results.toArray(new String[0]); } /** * This method retrieves the details about the compound * */ public DBCompound getCompound(String ID) throws IOException { URL entryURL = new URL(massBankEntryAddress + ID); String massBankEntry = InetUtils.retrieveData(entryURL); String compoundName = null; String compoundFormula = null; URL structure2DURL = null; URL structure3DURL = null; URL databaseURL = entryURL; // Find compound name Pattern patName = Pattern.compile("RECORD_TITLE: (.*)"); Matcher matcherName = patName.matcher(massBankEntry); if (matcherName.find()) { compoundName = matcherName.group(1); } // Find compound formula Pattern patFormula = Pattern.compile("CH\\$FORMULA: (.*)"); Matcher matcherFormula = patFormula.matcher(massBankEntry); if (matcherFormula.find()) { compoundFormula = matcherFormula.group(1); } if (compoundName == null) { throw (new IOException( "Could not parse compound name for compound " + ID)); } DBCompound newCompound = new DBCompound(OnlineDatabase.MASSBANK, ID, compoundName, compoundFormula, databaseURL, structure2DURL, structure3DURL); return newCompound; } }
package org.jivesoftware.openfire.gateway.protocols.yahoo; import org.jivesoftware.util.Log; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.openfire.gateway.*; import org.jivesoftware.openfire.roster.RosterItem; import org.jivesoftware.openfire.user.UserNotFoundException; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.PacketError; import org.xmpp.packet.Presence; import ymsg.network.*; import java.io.IOException; import java.util.*; /** * Represents a Yahoo session. * * This is the interface with which the base transport functionality will * communicate with Yahoo. * * @author Daniel Henninger * Heavily inspired by Noah Campbell's work. */ public class YahooSession extends TransportSession { final private PseudoRosterManager pseudoRosterManager = new PseudoRosterManager(); /** * Create a Yahoo Session instance. * * @param registration Registration informationed used for logging in. * @param jid JID associated with this session. * @param transport Transport instance associated with this session * @param priority Priority of this session */ public YahooSession(Registration registration, JID jid, YahooTransport transport, Integer priority) { super(registration, jid, transport, priority); pseudoRoster = pseudoRosterManager.getPseudoRoster(registration); yahooSession = new Session(new DirectConnectionHandler( JiveGlobals.getProperty("plugin.gateway.yahoo.connecthost", "scs.msg.yahoo.com"), JiveGlobals.getIntProperty("plugin.gateway.yahoo.connectport", 5050) )); yahooSession.addSessionListener(new YahooSessionListener(this)); } /** * Our pseudo roster. * * We only really use it for nickname tracking. */ private PseudoRoster pseudoRoster; /** * How many attempts have been made so far? */ private Integer loginAttempts = 0; /** * Yahoo session */ private final Session yahooSession; /** * Stored Last Presence Type */ public PresenceType presenceType = null; /** * Stored Last Verbose Status */ public String verboseStatus = null; /** * Log in to Yahoo. * * @param presenceType Type of presence. * @param verboseStatus Long representation of status. */ public void logIn(PresenceType presenceType, String verboseStatus) { this.presenceType = presenceType; this.verboseStatus = verboseStatus; final PresenceType pType = presenceType; if (!isLoggedIn() && getLoginStatus() != TransportLoginStatus.LOGGING_IN && loginAttempts <= 3) { setLoginStatus(TransportLoginStatus.LOGGING_IN); new Thread() { public void run() { try { loginAttempts++; yahooSession.setStatus(StatusConstants.STATUS_AVAILABLE); yahooSession.login(registration.getUsername(), registration.getPassword()); setLoginStatus(TransportLoginStatus.LOGGED_IN); Presence p = new Presence(); p.setTo(getJID()); p.setFrom(getTransport().getJID()); getTransport().sendPacket(p); yahooSession.setStatus(((YahooTransport)getTransport()).convertJabStatusToYahoo(pType)); getRegistration().setLastLogin(new Date()); syncUsers(); } catch (LoginRefusedException e) { yahooSession.reset(); String reason = LocaleUtils.getLocalizedString("gateway.yahoo.loginrefused", "gateway"); switch((int)e.getStatus()) { case (int)StatusConstants.STATUS_BADUSERNAME: reason = LocaleUtils.getLocalizedString("gateway.yahoo.unknownuser", "gateway"); break; case (int)StatusConstants.STATUS_BAD: reason = LocaleUtils.getLocalizedString("gateway.yahoo.badpassword", "gateway"); break; case (int)StatusConstants.STATUS_LOCKED: AccountLockedException e2 = (AccountLockedException)e; if(e2.getWebPage() != null) { reason = LocaleUtils.getLocalizedString("gateway.yahoo.accountlockedwithurl", "gateway", Arrays.asList(e2.getWebPage().toString())); } else { reason = LocaleUtils.getLocalizedString("gateway.yahoo.accountlocked", "gateway"); } break; } Log.warn("Yahoo login failed for "+getJID()+": "+reason); getTransport().sendMessage( getJID(), getTransport().getJID(), reason, Message.Type.error ); setLoginStatus(TransportLoginStatus.LOGGED_OUT); } catch (IOException e) { Log.error("Yahoo login caused IO exception:", e); getTransport().sendMessage( getJID(), getTransport().getJID(), LocaleUtils.getLocalizedString("gateway.yahoo.unknownerror", "gateway"), Message.Type.error ); setLoginStatus(TransportLoginStatus.LOGGED_OUT); } } }.start(); } } /** * Log out of Yahoo. */ public void logOut() { setLoginStatus(TransportLoginStatus.LOGGED_OUT); loginAttempts = 0; try { yahooSession.logout(); } catch (IOException e) { Log.debug("Failed to log out from Yahoo."); } yahooSession.reset(); Presence p = new Presence(Presence.Type.unavailable); p.setTo(getJID()); p.setFrom(getTransport().getJID()); getTransport().sendPacket(p); } /** * Syncs up the yahoo roster with the jabber roster. */ public void syncUsers() { // First we need to get a good mapping of users to what groups they are in. HashMap<String,ArrayList<String>> userToGroups = new HashMap<String,ArrayList<String>>(); for (YahooGroup group : yahooSession.getGroups()) { for (Enumeration e = group.getMembers().elements(); e.hasMoreElements();) { YahooUser user = (YahooUser)e.nextElement(); ArrayList<String> groups; if (userToGroups.containsKey(user.getId())) { groups = userToGroups.get(user.getId()); } else { groups = new ArrayList<String>(); } if (!groups.contains(group.getName())) { groups.add(group.getName()); } userToGroups.put(user.getId(), groups); } } // Now we will run through the entire list of users and set up our sync group. List<TransportBuddy> legacyusers = new ArrayList<TransportBuddy>(); for (Object userObj : yahooSession.getUsers().values()) { YahooUser user = (YahooUser)userObj; PseudoRosterItem rosterItem = pseudoRoster.getItem(user.getId()); String nickname = null; if (rosterItem != null) { nickname = rosterItem.getNickname(); } if (nickname == null) { nickname = user.getId(); } if (userToGroups.containsKey(user.getId()) && !userToGroups.get(user.getId()).get(0).equals("Transport Buddies")) { legacyusers.add(new TransportBuddy(user.getId(), nickname, userToGroups.get(user.getId()).get(0))); } else { legacyusers.add(new TransportBuddy(user.getId(), nickname, null)); } } // Lets try the actual sync. try { getTransport().syncLegacyRoster(getJID(), legacyusers); } catch (UserNotFoundException e) { Log.error("Unable to sync yahoo contact list for " + getJID()); } // Ok, now lets check presence for (Object userObj : yahooSession.getUsers().values()) { YahooUser user = (YahooUser)userObj; Presence p = new Presence(); p.setTo(getJID()); p.setFrom(getTransport().convertIDToJID(user.getId())); String custommsg = user.getCustomStatusMessage(); if (custommsg != null) { p.setStatus(custommsg); } ((YahooTransport)getTransport()).setUpPresencePacket(p, user.getStatus()); getTransport().sendPacket(p); } } /** * @see org.jivesoftware.openfire.gateway.TransportSession#addContact(org.jivesoftware.openfire.roster.RosterItem) */ public void addContact(RosterItem item) { // Syncing will take are of add. String contact = getTransport().convertJIDToID(item.getJid()); lockRoster(item.getJid().toString()); syncContactGroups(contact, item.getGroups()); if (pseudoRoster.hasItem(contact)) { PseudoRosterItem rosterItem = pseudoRoster.getItem(contact); rosterItem.setNickname(item.getNickname()); } else { pseudoRoster.createItem(contact, item.getNickname(), null); } unlockRoster(item.getJid().toString()); } /** * @see org.jivesoftware.openfire.gateway.TransportSession#removeContact(org.jivesoftware.openfire.roster.RosterItem) */ public void removeContact(RosterItem item) { String contact = getTransport().convertJIDToID(item.getJid()); lockRoster(item.getJid().toString()); for (YahooGroup yahooGroup : yahooSession.getGroups()) { if (yahooGroup.getIndexOfFriend(contact) != -1) { try { yahooSession.removeFriend(contact, yahooGroup.getName()); pseudoRoster.removeItem(contact); } catch (IOException e) { Log.error("Failed to remove yahoo user."); } } } unlockRoster(item.getJid().toString()); } /** * @see org.jivesoftware.openfire.gateway.TransportSession#updateContact(org.jivesoftware.openfire.roster.RosterItem) */ public void updateContact(RosterItem item) { String contact = getTransport().convertJIDToID(item.getJid()); lockRoster(item.getJid().toString()); syncContactGroups(contact, item.getGroups()); if (pseudoRoster.hasItem(contact)) { PseudoRosterItem rosterItem = pseudoRoster.getItem(contact); rosterItem.setNickname(item.getNickname()); } else { pseudoRoster.createItem(contact, item.getNickname(), null); } unlockRoster(item.getJid().toString()); } /** * Given a legacy contact and a list of groups, makes sure that the list is in sync with * the actual group list. * * @param contact Email address of contact. * @param groups List of groups contact should be in. */ public void syncContactGroups(String contact, List<String> groups) { if (groups.size() == 0) { groups.add("Transport Buddies"); } HashMap<String,YahooGroup> yahooGroups = new HashMap<String,YahooGroup>(); // Lets create a hash of these for easier reference. for (YahooGroup yahooGroup : yahooSession.getGroups()) { yahooGroups.put(yahooGroup.getName(), yahooGroup); } // Create groups(add user to them) that do not currently exist. for (String group : groups) { if (!yahooGroups.containsKey(group)) { try { Log.debug("Yahoo: Adding contact "+contact+" to non-existent group "+group); yahooSession.addFriend(contact, group); } catch (IOException e) { Log.error("Error while syncing Yahoo groups."); } } } // Now we handle adds and removes, syncing the two lists. for (YahooGroup yahooGroup : yahooSession.getGroups()) { if (groups.contains(yahooGroup.getName())) { if (yahooGroup.getIndexOfFriend(contact) == -1) { try { Log.debug("Yahoo: Adding contact "+contact+" to existing group "+yahooGroup.getName()); yahooSession.addFriend(contact, yahooGroup.getName()); } catch (IOException e) { Log.error("Error while syncing Yahoo groups."); } } } else { if (yahooGroup.getIndexOfFriend(contact) != -1) { try { Log.debug("Yahoo: Removing contact "+contact+" from group "+yahooGroup.getName()); yahooSession.removeFriend(contact, yahooGroup.getName()); } catch (IOException e) { Log.error("Error while syncing Yahoo groups."); } } } } } /** * @see org.jivesoftware.openfire.gateway.TransportSession#sendMessage(org.xmpp.packet.JID, String) */ public void sendMessage(JID jid, String message) { try { yahooSession.sendMessage(jid.getNode(), message); } catch (IOException e) { Log.error("Failed to send message to yahoo user."); } } /** * @see org.jivesoftware.openfire.gateway.TransportSession#sendServerMessage(String) */ public void sendServerMessage(String message) { // We don't care. } /** * @see org.jivesoftware.openfire.gateway.TransportSession#sendChatState(org.xmpp.packet.JID, org.jivesoftware.openfire.gateway.ChatStateType) */ public void sendChatState(JID jid, ChatStateType chatState) { // TODO: Handle this } /** * @see org.jivesoftware.openfire.gateway.TransportSession#updateStatus(org.jivesoftware.openfire.gateway.PresenceType, String) */ public void updateStatus(PresenceType presenceType, String verboseStatus) { try { if (isLoggedIn()) { yahooSession.setStatus(((YahooTransport)getTransport()).convertJabStatusToYahoo(presenceType)); } else { // TODO: Should we consider auto-logging back in? } } catch (Exception e) { Log.error("Unable to set Yahoo Status:", e); } Presence p = new Presence(); if (presenceType == PresenceType.away) { p.setShow(Presence.Show.away); } else if (presenceType == PresenceType.xa) { p.setShow(Presence.Show.xa); } else if (presenceType == PresenceType.dnd) { p.setShow(Presence.Show.dnd); } else if (presenceType == PresenceType.chat) { p.setShow(Presence.Show.chat); } p.setTo(getJID()); p.setFrom(getTransport().getJID()); getTransport().sendPacket(p); this.presenceType = presenceType; this.verboseStatus = verboseStatus; } /** * @see org.jivesoftware.openfire.gateway.TransportSession#retrieveContactStatus(org.xmpp.packet.JID) */ public void retrieveContactStatus(JID jid) { if (isLoggedIn()) { YahooUser user = yahooSession.getUser(jid.getNode()); Presence p = new Presence(); p.setTo(getJID()); if (user != null) { // User was found so update presence accordingly p.setFrom(getTransport().convertIDToJID(user.getId())); String custommsg = user.getCustomStatusMessage(); if (custommsg != null) { p.setStatus(custommsg); } ((YahooTransport)getTransport()).setUpPresencePacket(p, user.getStatus()); } else { // User was not found so send an error presence p.setFrom(jid); p.setError(PacketError.Condition.forbidden); } getTransport().sendPacket(p); } } /** * @see org.jivesoftware.openfire.gateway.TransportSession#resendContactStatuses(org.xmpp.packet.JID) */ public void resendContactStatuses(JID jid) { for (Object userObj : yahooSession.getUsers().values()) { YahooUser user = (YahooUser)userObj; Presence p = new Presence(); p.setTo(jid); p.setFrom(getTransport().convertIDToJID(user.getId())); String custommsg = user.getCustomStatusMessage(); if (custommsg != null) { p.setStatus(custommsg); } ((YahooTransport)getTransport()).setUpPresencePacket(p, user.getStatus()); getTransport().sendPacket(p); } } }
package org.helioviewer.plugins.eveplugin.view.plot; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.helioviewer.base.math.Interval; import org.helioviewer.jhv.gui.IconBank; import org.helioviewer.jhv.gui.IconBank.JHVIcon; import org.helioviewer.jhv.gui.dialogs.observation.ObservationDialog; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.LayersModel; import org.helioviewer.plugins.eveplugin.controller.ZoomController; import org.helioviewer.plugins.eveplugin.controller.ZoomController.ZOOM; import org.helioviewer.plugins.eveplugin.controller.ZoomControllerListener; import org.helioviewer.plugins.eveplugin.events.model.EventModel; import org.helioviewer.plugins.eveplugin.model.TimeIntervalLockModel; //import org.helioviewer.plugins.eveplugin.model.PlotTimeSpace; import org.helioviewer.plugins.eveplugin.settings.EVEAPI.API_RESOLUTION_AVERAGES; import org.helioviewer.plugins.eveplugin.settings.EVESettings; import org.helioviewer.plugins.eveplugin.view.periodpicker.PeriodPicker; import org.helioviewer.plugins.eveplugin.view.periodpicker.PeriodPickerListener; import org.helioviewer.viewmodel.view.View; /** * @author Stephan Pagel * */ public class PlotsControlPanel extends JPanel implements ZoomControllerListener, ActionListener, PeriodPickerListener, LayersListener { // Definitions private static final long serialVersionUID = 1L; private Interval<Date> selectedIntervalByZoombox = null; private boolean setDefaultPeriod = true; private final ImageIcon movietimeIcon = IconBank.getIcon(JHVIcon.LAYER_MOVIE_TIME); private final ImageIcon addIcon = IconBank.getIcon(JHVIcon.ADD); private final JLabel periodLabel = new JLabel("Period:"); private final PeriodPicker periodPicker = new PeriodPicker(); private final JButton periodFromLayersButton = new JButton(movietimeIcon); private final JLabel zoomLabel = new JLabel("Clip:"); private final JComboBox zoomComboBox = new JComboBox(new DefaultComboBoxModel()); private final JLabel lockIntervalLabel = new JLabel("Lock Time Interval:"); private final JCheckBox lockIntervalCheckBox = new JCheckBox(); private final JLabel eventsLabel = new JLabel("Display events: "); private final JCheckBox eventsCheckBox = new JCheckBox(); private final String[] plots = { "Plot 1", "Plot 2" }; private final JComboBox eventsComboBox = new JComboBox(plots); private final JButton addLayerButton = new JButton("Add Layer", addIcon); private boolean selectedIndexSetByProgram = false; // Methods public PlotsControlPanel() { initVisualComponents(); ZoomController.getSingletonInstance().addZoomControllerListener(this); LayersModel.getSingletonInstance().addLayersListener(this); } private void initVisualComponents() { setLayout(new BorderLayout()); initLockIntervalCheckBox(); initEventsVisualComponents(); final JPanel periodPane = new JPanel(); periodPane.setLayout(new FlowLayout(FlowLayout.LEFT)); periodPane.add(periodLabel); periodPane.add(periodPicker); periodPane.add(periodFromLayersButton); final JPanel zoomPane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); zoomPane.add(eventsLabel); zoomPane.add(eventsCheckBox); zoomPane.add(eventsComboBox); zoomPane.add(lockIntervalLabel); zoomPane.add(lockIntervalCheckBox); zoomPane.add(zoomLabel); zoomPane.add(zoomComboBox); final JPanel groupPane = new JPanel(); groupPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); groupPane.setPreferredSize(new Dimension(200, getHeight())); groupPane.add(addLayerButton); add(periodPane, BorderLayout.LINE_START); add(zoomPane, BorderLayout.CENTER); add(groupPane, BorderLayout.LINE_END); periodPicker.addPeriodPickerListener(this); periodFromLayersButton.setToolTipText("Request data of selected movie interval"); periodFromLayersButton.setPreferredSize(new Dimension(movietimeIcon.getIconWidth() + 14, periodFromLayersButton.getPreferredSize().height)); periodFromLayersButton.addActionListener(this); setEnabledStateOfPeriodMovieButton(); zoomComboBox.addActionListener(this); addLayerButton.setToolTipText("Add a new layer"); addLayerButton.addActionListener(this); } private void initEventsVisualComponents() { eventsCheckBox.setSelected(EventModel.getSingletonInstance().isEventsVisible()); eventsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EventModel.getSingletonInstance().setEventsVisible(eventsCheckBox.isSelected()); } }); eventsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (((String) eventsComboBox.getSelectedItem()).equals("Plot 1")) { EventModel.getSingletonInstance().setPlotIdentifier(PlotsContainerPanel.PLOT_IDENTIFIER_MASTER); } else { EventModel.getSingletonInstance().setPlotIdentifier(PlotsContainerPanel.PLOT_IDENTIFIER_SLAVE); } } }); } private void initLockIntervalCheckBox() { lockIntervalCheckBox.setSelected(TimeIntervalLockModel.getInstance().isLocked()); lockIntervalCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { TimeIntervalLockModel.getInstance().setLocked(lockIntervalCheckBox.isSelected()); } }); } private void setEnabledStateOfPeriodMovieButton() { final Interval<Date> frameInterval = LayersModel.getSingletonInstance().getFrameInterval(); periodFromLayersButton.setEnabled(frameInterval.getStart() != null && frameInterval.getEnd() != null); } private void fillZoomComboBox() { final Interval<Date> interval = ZoomController.getSingletonInstance().getAvailableInterval(); final Date startDate = interval.getStart(); final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, 1); calendar.add(Calendar.HOUR, 1); final boolean years = interval.containsPointInclusive(calendar.getTime()); calendar.clear(); calendar.setTime(startDate); calendar.add(Calendar.MONTH, 3); ; final boolean months = interval.containsPointInclusive(calendar.getTime()); final DefaultComboBoxModel model = (DefaultComboBoxModel) zoomComboBox.getModel(); model.removeAllElements(); model.addElement(new ZoomComboboxItem(ZOOM.CUSTOM, 0)); model.addElement(new ZoomComboboxItem(ZOOM.All, 0)); addElementToModel(model, startDate, interval, Calendar.YEAR, 10, ZOOM.Year); addElementToModel(model, startDate, interval, Calendar.YEAR, 5, ZOOM.Year); addElementToModel(model, startDate, interval, Calendar.YEAR, 1, ZOOM.Year); addElementToModel(model, startDate, interval, Calendar.MONTH, 6, ZOOM.Month); addElementToModel(model, startDate, interval, Calendar.MONTH, 3, ZOOM.Month); addElementToModel(model, startDate, interval, Calendar.MONTH, 1, ZOOM.Month); if (!years) { addElementToModel(model, startDate, interval, Calendar.DATE, 14, ZOOM.Day); addElementToModel(model, startDate, interval, Calendar.DATE, 7, ZOOM.Day); addElementToModel(model, startDate, interval, Calendar.DATE, 1, ZOOM.Day); if (!months) { addElementToModel(model, startDate, interval, Calendar.HOUR, 12, ZOOM.Hour); addElementToModel(model, startDate, interval, Calendar.HOUR, 6, ZOOM.Hour); addElementToModel(model, startDate, interval, Calendar.HOUR, 1, ZOOM.Hour); } } } private boolean addElementToModel(final DefaultComboBoxModel model, final Date startDate, final Interval<Date> interval, final int calendarField, final int calendarValue, final ZOOM zoom) { final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(startDate); calendar.add(calendarField, calendarValue); if (interval.containsPointInclusive(calendar.getTime())) { model.addElement(new ZoomComboboxItem(zoom, calendarValue)); return true; } return false; } // Layers Listener @Override public void layerAdded(int idx) { if (setDefaultPeriod) { setDefaultPeriod = false; final Interval<Date> interval = new Interval<Date>(LayersModel.getSingletonInstance().getFirstDate(), LayersModel.getSingletonInstance().getLastDate()); ZoomController.getSingletonInstance().setAvailableInterval(interval); // PlotTimeSpace.getInstance().setSelectedMinAndMaxTime(interval.getStart(), // interval.getEnd()); } setEnabledStateOfPeriodMovieButton(); } @Override public void layerRemoved(View oldView, int oldIdx) { setEnabledStateOfPeriodMovieButton(); } @Override public void layerChanged(int idx) { } @Override public void activeLayerChanged(int idx) { } @Override public void viewportGeometryChanged() { } @Override public void timestampChanged(int idx) { } @Override public void subImageDataChanged() { } @Override public void layerDownloaded(int idx) { } // Period Picker Listener @Override public void intervalChanged(Interval<Date> interval) { setDefaultPeriod = false; final ZoomController zoomController = ZoomController.getSingletonInstance(); zoomController.setAvailableInterval(interval); zoomController.setSelectedInterval(zoomController.getAvailableInterval()); // PlotTimeSpace plotTimeSpace = PlotTimeSpace.getInstance(); // plotTimeSpace.setMinAndMaxTime(interval.getStart(), // interval.getEnd()); // plotTimeSpace.setSelectedMinAndMaxTime(plotTimeSpace.getMinTime(), // plotTimeSpace.getMaxTime()); } // Action Listener @Override public void actionPerformed(final ActionEvent e) { if (e.getSource().equals(zoomComboBox)) { final ZoomComboboxItem item = (ZoomComboboxItem) zoomComboBox.getSelectedItem(); selectedIntervalByZoombox = null; if (item != null && !selectedIndexSetByProgram) { selectedIntervalByZoombox = ZoomController.getSingletonInstance().zoomTo(item.getZoom(), item.getNumber()); } else { if (selectedIndexSetByProgram) { selectedIndexSetByProgram = false; } } } else if (e.getSource() == periodFromLayersButton) { final Interval<Date> interval = new Interval<Date>(LayersModel.getSingletonInstance().getFirstDate(), LayersModel.getSingletonInstance().getLastDate()); ZoomController.getSingletonInstance().setAvailableInterval(interval); // PlotTimeSpace.getInstance().setSelectedMinAndMaxTime(interval.getStart(), // interval.getEnd()); } else if (e.getSource().equals(addLayerButton)) { ObservationDialog.getSingletonInstance().showDialog(EVESettings.OBSERVATION_UI_NAME); } } // Zoom Controller Listener @Override public void availableIntervalChanged(final Interval<Date> newInterval) { if (newInterval.getStart() != null || newInterval.getEnd() != null) { final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(newInterval.getEnd()); calendar.add(Calendar.DATE, -1); periodPicker.setInterval(new Interval<Date>(newInterval.getStart(), calendar.getTime())); fillZoomComboBox(); } } @Override public void selectedIntervalChanged(final Interval<Date> newInterval) { if (selectedIntervalByZoombox != null && newInterval != null) { if (!selectedIntervalByZoombox.equals(newInterval)) { try { selectedIndexSetByProgram = true; zoomComboBox.setSelectedIndex(0); } catch (final IllegalArgumentException ex) { } } } } @Override public void selectedResolutionChanged(final API_RESOLUTION_AVERAGES newResolution) { } // Zoom Combobox Item private class ZoomComboboxItem { // Definitions private final ZOOM zoom; private final int number; // Methods public ZoomComboboxItem(final ZOOM zoom, final int number) { this.zoom = zoom; this.number = number; } public ZOOM getZoom() { return zoom; } public int getNumber() { return number; } @Override public String toString() { final String plural = number > 1 ? "s" : ""; switch (zoom) { case All: return "Max. interval"; case Hour: return Integer.toString(number) + " Hour" + plural; case Day: return Integer.toString(number) + " Day" + plural; case Month: return Integer.toString(number) + " Month" + plural; case Year: return Integer.toString(number) + " Year" + plural; default: break; } return "Custom"; } } }
package ca.corefacility.bioinformatics.irida.config.data; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import ca.corefacility.bioinformatics.irida.model.SequenceFile; import ca.corefacility.bioinformatics.irida.repositories.CRUDRepository; import ca.corefacility.bioinformatics.irida.repositories.filesystem.SequenceFileFilesystemRepository; import ca.corefacility.bioinformatics.irida.utils.repositories.IdentifiableTestEntityRepo; import ca.corefacility.bioinformatics.irida.utils.repositories.IdentifiableTestEntityRepoImpl; @Configuration @Profile("test") public class IridaApiTestDataSourceConfig implements DataConfig { @Bean public CRUDRepository<Long, SequenceFile> sequenceFileFilesystemRepository() { Path baseDirectory = Paths.get("/tmp", "sequence-files"); if (!Files.exists(baseDirectory)) { try { Files.createDirectories(baseDirectory); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } return new SequenceFileFilesystemRepository(baseDirectory); } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) .build(); } @Bean public SessionFactory sessionFactory() { LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder( dataSource()); builder.scanPackages( "ca.corefacility.bioinformatics.irida.model", "ca.corefacility.bioinformatics.irida.repositories.relational.auditing", "ca.corefacility.bioinformatics.irida.utils.model"); Properties properties = new Properties(); properties.put("hibernate.show_sql", false); properties.put("hibernate.hbm2ddl.auto", "create-drop"); properties .put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); builder.addProperties(properties); return builder.buildSessionFactory(); } @Bean public IdentifiableTestEntityRepo identifiedRepository() { return new IdentifiableTestEntityRepoImpl(dataSource(), sessionFactory()); } }
package whelk.triples; import java.util.*; public class Graph { /** * When enriching one graph with another, sometimes special rules need to be applied to certain predicates, in order * to maintain the domain-specific correctness of the resulting graph. * For example a Whelk document should have only one "created"-timestamp, while the graphs being merged will * typically have one each, and so the special rule RULE_PREFER_ORIGINAL should be used. */ public enum PREDICATE_RULES { RULE_AGGREGATE, // Allow multiple such predicates per subject. RULE_PREFER_ORIGINAL, // Only one such predicate per subject, prefer the original documents version to the incoming RULE_PREFER_INCOMING, // Only one such predicate per subject, prefer the incoming documents version to the original (= overwrite) }; /** * The adjacency list (map). * * Mapping node IDs (A) to lists of predicate-subject pairs (edges) that connect (A) with other nodes */ private Map<String, List<String[]>> m_edgesFromId; private int m_currentHighestBNodeID = 0; public Graph(List<String[]> triples) { m_edgesFromId = new LinkedHashMap<>(); for (String[] triple : triples) { addTriple(triple); } } /** * Add the given triple to this graph */ public void addTriple(String[] triple) { // for clarity: String subject = triple[0]; String predicate = triple[1]; String object = triple[2]; // get the edge list for this node (subject) List<String[]> edges = m_edgesFromId.get(subject); if (edges == null) { edges = new ArrayList<>(); m_edgesFromId.put(subject, edges); } // check for duplicates for (String[] edge : edges) { if (edge[0].equals(predicate) && edge[1].equals(object)) // We already have this edge! return; } // add the edge represented by this triple edges.add(new String[]{predicate, object}); } public void enrichWith(Graph otherGraph, Map<String, PREDICATE_RULES> specialRules) { Map<String, String> bNodeMapping = otherGraph.generateBNodeMapTo(this); m_currentHighestBNodeID = getCurrentHighestBNodeID(); for (String subject : otherGraph.m_edgesFromId.keySet()) { List<String[]> otherEdges = otherGraph.m_edgesFromId.get(subject); subject = getTranslatedNodeId(subject, bNodeMapping); for (String[] otherEdge: otherEdges) { String predicate = otherEdge[0]; String object = getTranslatedNodeId(otherEdge[1], bNodeMapping); // == null means the deafult, if there is no special rules for *predicate if (specialRules.get(predicate) == null || specialRules.get(predicate) == PREDICATE_RULES.RULE_PREFER_ORIGINAL) { // Add the triple only if we don't already have such a subject-predicate pair. int occurrences = subjectPredicatePairOccurrences(subject, predicate); if (occurrences == 0) addTriple(new String[]{subject, predicate, object}); } else if (specialRules.get(predicate) == PREDICATE_RULES.RULE_AGGREGATE) { addTriple(new String[]{subject, predicate, object}); } else if (specialRules.get(predicate) == PREDICATE_RULES.RULE_PREFER_INCOMING) { // delete any preexisting edges in this graph that match this subject-predicate pair. List<String[]> subjectEdges = m_edgesFromId.get(subject); Iterator<String[]> it = subjectEdges.iterator(); while (it.hasNext()) { String[] edge = it.next(); if (edge[0].equals(predicate)) it.remove(); } addTriple(new String[]{subject, predicate, object}); } } } while (eliminateNextDuplicateBnode()); eliminateDuplicateTriples(); } /** * Get all triples in this graph */ public List<String[]> getTriples() { List<String[]> triples = new ArrayList<>(); for (String subject : m_edgesFromId.keySet()) { List<String[]> edges = m_edgesFromId.get(subject); for (String[] edge: edges) { String predicate = edge[0]; String object = edge[1]; triples.add(new String[]{subject, predicate, object}); } } return triples; } public String toString() { StringBuilder result = new StringBuilder(); for ( String subject : m_edgesFromId.keySet() ) { List<String[]> edges = m_edgesFromId.get(subject); if (edges == null) continue; for (String[] edge : edges) { result.append(subject); result.append(" ["); result.append(edge[0]); result.append(" ->] "); result.append(edge[1]); result.append("\n"); } } return result.toString(); } private boolean eliminateNextDuplicateBnode() { List<String> bnodeIds = new ArrayList<>(); for (String subject : m_edgesFromId.keySet()) if (subject.startsWith("_:")) bnodeIds.add(subject); for (String id1 : bnodeIds) { for (String id2 : bnodeIds) { if (id1.equals(id2)) continue; // id1 and id2 must now be examined for subgraph-equality if (hasEquivalentEdges(id1, id2, this, new HashMap<>(), new HashMap<>())) { replaceReferences(id1, id2); m_edgesFromId.remove(id1); return true; } } } return false; } private void replaceReferences(String to, String with) { for (String subject : m_edgesFromId.keySet()) { List<String[]> edges = m_edgesFromId.get(subject); for (String[] edge : edges) { String object = edge[1]; if (object.equals(to)) edge[1] = with; } } } private void eliminateDuplicateTriples() { for (String subject : m_edgesFromId.keySet()) { List<String[]> edges = m_edgesFromId.get(subject); List<Integer> indexesToRemove = new ArrayList<>(); for (int j = 0; j < edges.size(); ++j) { for (int i = edges.size()-1; i > j; --i) { String[] edge1 = edges.get(i); String[] edge2 = edges.get(j); if (edge1[0].equals(edge2[0]) && edge1[1].equals(edge2[1]) && !indexesToRemove.contains(i)) { indexesToRemove.add(i); } } } Collections.sort(indexesToRemove); Collections.reverse(indexesToRemove); for (Integer indexToRemove : indexesToRemove) edges.remove(indexToRemove.intValue()); } } /** * Is there such an edge in this graph, that 'subject' is connected to some (arbitrary) * other node via an edge of type 'predicate' ? * Returns the number of such edges. */ private int subjectPredicatePairOccurrences(String subject, String predicate) { List<String[]> edges = m_edgesFromId.get(subject); int result = 0; if (edges != null) { for (String[] edge : edges) { if (predicate.equals(edge[0])) ++result; } } return result; } /** * Find an integer I, such that new BNodes _:b(I+N) for N=1,2,3.. can be safely (without risk of collision) added to this graph */ private int getCurrentHighestBNodeID() { int currentHighestBNodeID = 0; for (String subject : m_edgesFromId.keySet()) { try { int bnodeNumber = Integer.parseInt(subject.substring( JsonldSerializer.BLANKNODE_PREFIX.length() )); if (bnodeNumber >= currentHighestBNodeID) currentHighestBNodeID = bnodeNumber; } catch (Exception e) { /* ignore */ } } return currentHighestBNodeID; } /** * Given a node id in the graph from which bNodeMapping is derived, get the corresponding node id in this graph * (which is usually the same unless it is a blank node id). */ private String getTranslatedNodeId(String naiveNodeId, Map<String, String> bNodeMapping) { if (naiveNodeId.startsWith(JsonldSerializer.BLANKNODE_PREFIX)) { if (bNodeMapping.keySet().contains(naiveNodeId)) return bNodeMapping.get(naiveNodeId); // A blank node without mapping? Give it a new blank node id in this graph // and add the mapping, so the linked web remains intact String newBNodeId = JsonldSerializer.BLANKNODE_PREFIX + (++m_currentHighestBNodeID); bNodeMapping.put(naiveNodeId, newBNodeId); return newBNodeId; } return naiveNodeId; } /** * Generates a map where BNode ids in this graph are mapped to BNode ids in otherGraph (where the mapping can be * done with surety) */ private Map<String, String> generateBNodeMapTo(Graph otherGraph) { Map<String, String> BNodeMap = new HashMap<>(); for (String otherSubject : otherGraph.m_edgesFromId.keySet()) { if (otherSubject.startsWith(JsonldSerializer.BLANKNODE_PREFIX)) { for (String subject : m_edgesFromId.keySet()) { if (subject.startsWith(JsonldSerializer.BLANKNODE_PREFIX)) { // subject and otherSubject are both blank nodes. if (hasEquivalentEdges(subject, otherSubject, otherGraph, new HashMap<>(), new HashMap<>())) BNodeMap.put(subject, otherSubject); } } } } return BNodeMap; } /** * Does 'subject' have the equivalent edges in this graph, compared to 'otherSubject' in otherGraph ? * (are the edges of otherGraph[otherSubject] a subset of the edges of this[subject]) */ private boolean hasEquivalentEdges(String subject, String otherSubject, Graph otherGraph, Map<String, String> cycleGuard, Map<String, String> otherCycleGuard) { // Check for going in circles if ( cycleGuard.keySet().contains(subject) && otherCycleGuard.keySet().contains(otherSubject) ) { // Cycle detected in both graphs. Is the other graph in the same position it was the last time we were here? if ( cycleGuard.get(subject).equals(otherSubject) && otherCycleGuard.get(otherSubject).equals(subject) ) return true; } if (cycleGuard.keySet().contains(subject) || otherCycleGuard.keySet().contains(otherSubject)) return false; // We've been here already in one graph, but the position in the other graph was different then. cycleGuard.put(subject, otherSubject); otherCycleGuard.put(otherSubject, subject); // Normal recursive base cases List<String[]> otherEdges = otherGraph.m_edgesFromId.get(otherSubject); if (otherEdges == null) return true; // nothing more to check List<String[]> edges = m_edgesFromId.get(subject); if (edges == null) return false; // no more edges in (possibly) containing graph to compare with // Compare edges for (String[] otherEdge : otherEdges) { boolean hasEquivalentEdges = false; // Does each 'otherEdge' have an equivalent edge in this graph ? for (String[] edge : edges) { boolean edgesMatch = edge[0].equals(otherEdge[0]) && // predicate is the same and ( (edge[1].equals(otherEdge[1]) && !edge[1].startsWith(JsonldSerializer.BLANKNODE_PREFIX) ) // object is the same (and not a blank node), || // or both objects are blank nodes, and in turn have equivalent edges ( edge[1].startsWith(JsonldSerializer.BLANKNODE_PREFIX) && otherEdge[1].startsWith(JsonldSerializer.BLANKNODE_PREFIX) && hasEquivalentEdges(edge[1], otherEdge[1], otherGraph, cycleGuard, otherCycleGuard) )); if (edgesMatch) hasEquivalentEdges = true; } if (!hasEquivalentEdges) return false; } return true; } }
package org.roklib.webapps.uridispatching.parameter.value; import org.junit.Before; import org.junit.Test; import org.roklib.webapps.uridispatching.parameter.SingleIntegerURIParameter; import org.roklib.webapps.uridispatching.parameter.SingleStringURIParameter; import java.util.Optional; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; public class ConsumedParameterValuesTest { private ConsumedParameterValues values; private SingleStringURIParameter stringTextParameter; private SingleStringURIParameter stringNameParameter; private SingleIntegerURIParameter integerParameter; @Before public void setUp() { values = new ConsumedParameterValues(); stringTextParameter = new SingleStringURIParameter("text"); stringNameParameter = new SingleStringURIParameter("name"); integerParameter = new SingleIntegerURIParameter("number"); } @Test public void returns_empty_optional_for_unknown_mapper_name() { assertThat(values.getValueFor("unknown", stringTextParameter), equalTo(Optional.empty())); } @Test public void returns_empty_optional_for_unavailable_parameter() { values.setValueFor("first", stringTextParameter, "test"); assertThat(values.getValueFor("first", integerParameter), equalTo(Optional.empty())); } @Test public void getValueFor_returns_correct_value() { values.setValueFor("first", stringTextParameter, "textValue"); values.setValueFor("first", stringNameParameter, "nameValue"); values.setValueFor("second", integerParameter, 17); assertThat(values.getValueFor("first", stringTextParameter).get().getValue(), equalTo("textValue")); assertThat(values.getValueFor("first", stringNameParameter).get().getValue(), equalTo("nameValue")); assertThat(values.getValueFor("second", integerParameter).get().getValue(), equalTo(17)); } @Test(expected = NullPointerException.class) public void getValueFor_mapper_name_null_not_allowed() { values.getValueFor(null, stringTextParameter); } @Test(expected = NullPointerException.class) public void getValueFor_parameter_null_not_allowed() { values.getValueFor("first", null); } @Test(expected = NullPointerException.class) public void setValueFor_mapper_name_null_not_allowed() { values.setValueFor(null, stringTextParameter, ""); } @Test(expected = NullPointerException.class) public void setValueFor_parameter_null_not_allowed() { values.setValueFor("first", null, ""); } }
package org.synyx.urlaubsverwaltung.account.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.synyx.urlaubsverwaltung.account.domain.Account; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.testdatacreator.TestDataCreator; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Optional; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; import static java.time.Month.DECEMBER; import static java.time.Month.JANUARY; import static java.time.Month.OCTOBER; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AccountInteractionServiceImplTest { private AccountInteractionServiceImpl sut; @Mock private AccountService accountService; @Mock private VacationDaysService vacationDaysService; private Person person; @Before public void setup() { sut = new AccountInteractionServiceImpl(accountService, vacationDaysService); person = TestDataCreator.createPerson("horscht"); } @Test public void testUpdateRemainingVacationDays() { final LocalDate startDate = LocalDate.of(2012, JANUARY, 1); final LocalDate endDate = LocalDate.of(2012, DECEMBER, 31); final BigDecimal annualVacationDays = BigDecimal.valueOf(30); final Account account2012 = new Account(person, startDate, endDate, annualVacationDays, BigDecimal.valueOf(5), ZERO, null); final Account account2013 = new Account(person, startDate.withYear(2013), endDate.withYear(2013), annualVacationDays, BigDecimal.valueOf(3), ZERO, "comment1"); final Account account2014 = new Account(person, startDate.withYear(2014), endDate.withYear(2014), annualVacationDays, BigDecimal.valueOf(8), ZERO, "comment2"); when(accountService.getHolidaysAccount(2012, person)).thenReturn(Optional.of(account2012)); when(accountService.getHolidaysAccount(2013, person)).thenReturn(Optional.of(account2013)); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.of(account2014)); when(accountService.getHolidaysAccount(2015, person)).thenReturn(Optional.empty()); when(vacationDaysService.calculateTotalLeftVacationDays(account2012)).thenReturn(BigDecimal.valueOf(6)); when(vacationDaysService.calculateTotalLeftVacationDays(account2013)).thenReturn(BigDecimal.valueOf(2)); sut.updateRemainingVacationDays(2012, person); verify(vacationDaysService, never()).calculateTotalLeftVacationDays(account2014); verify(accountService, never()).save(account2012); assertThat(account2012.getRemainingVacationDays()).isEqualTo(BigDecimal.valueOf(5)); assertThat(account2013.getRemainingVacationDays()).isEqualTo(BigDecimal.valueOf(6)); assertThat(account2014.getRemainingVacationDays()).isEqualTo(BigDecimal.valueOf(2)); assertThat(account2012.getComment()).isNull(); assertThat(account2013.getComment()).isSameAs("comment1"); assertThat(account2014.getComment()).isSameAs("comment2"); } @Test public void testUpdateRemainingVacationDaysAndNotExpiringDaysAreGreaterThenRemaining() { final LocalDate startDate = LocalDate.of(2012, JANUARY, 1); final LocalDate endDate = LocalDate.of(2012, DECEMBER, 31); final BigDecimal annualVacationDays = BigDecimal.valueOf(30); final Account account2012 = new Account(person, startDate, endDate, annualVacationDays, BigDecimal.valueOf(3), ZERO, null); final Account account2013 = new Account(person, startDate.withYear(2013), endDate.withYear(2013), annualVacationDays, ZERO, TEN, "comment1"); when(accountService.getHolidaysAccount(2012, person)).thenReturn(Optional.of(account2012)); when(accountService.getHolidaysAccount(2013, person)).thenReturn(Optional.of(account2013)); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.empty()); when(vacationDaysService.calculateTotalLeftVacationDays(account2012)).thenReturn(BigDecimal.valueOf(6)); sut.updateRemainingVacationDays(2012, person); assertThat(account2013.getRemainingVacationDays()).isEqualTo(BigDecimal.valueOf(6)); } @Test public void testUpdateRemainingVacationDaysHasNoThisYearAccount() { final LocalDate startDate = LocalDate.of(2012, JANUARY, 1); final LocalDate endDate = LocalDate.of(2012, DECEMBER, 31); final BigDecimal annualVacationDays = BigDecimal.valueOf(30); final BigDecimal remainingVacationDays = BigDecimal.valueOf(5); final Account nextYearAccount = new Account(person, startDate, endDate, annualVacationDays, remainingVacationDays, ZERO, null); when(accountService.getHolidaysAccount(2013, person)).thenReturn(Optional.of(nextYearAccount)); when(accountService.getHolidaysAccount(2012, person)).thenReturn(Optional.empty()); sut.updateRemainingVacationDays(2012, person); assertThat(nextYearAccount.getRemainingVacationDays()).isEqualTo(remainingVacationDays); verify(vacationDaysService, never()).calculateTotalLeftVacationDays(any()); verify(accountService, never()).save(any()); } @Test public void ensureCreatesNewHolidaysAccountIfNotExistsYet() { int year = 2014; int nextYear = 2015; LocalDate startDate = LocalDate.of(year, JANUARY, 1); LocalDate endDate = LocalDate.of(year, OCTOBER, 31); BigDecimal leftDays = BigDecimal.ONE; Account referenceHolidaysAccount = new Account(person, startDate, endDate, BigDecimal.valueOf(30), BigDecimal.valueOf(8), BigDecimal.valueOf(4), "comment"); when(accountService.getHolidaysAccount(nextYear, person)).thenReturn(Optional.empty()); when(vacationDaysService.calculateTotalLeftVacationDays(referenceHolidaysAccount)).thenReturn(leftDays); when(accountService.save(any())).then(returnsFirstArg()); Account createdHolidaysAccount = sut.autoCreateOrUpdateNextYearsHolidaysAccount(referenceHolidaysAccount); Assert.assertNotNull("Should not be null", createdHolidaysAccount); Assert.assertEquals("Wrong person", person, createdHolidaysAccount.getPerson()); Assert.assertEquals("Wrong number of annual vacation days", referenceHolidaysAccount.getAnnualVacationDays(), createdHolidaysAccount.getAnnualVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days", leftDays, createdHolidaysAccount.getRemainingVacationDays()); Assert.assertEquals("Wrong number of not expiring remaining vacation days", ZERO, createdHolidaysAccount.getRemainingVacationDaysNotExpiring()); Assert.assertEquals("Wrong validity start date", LocalDate.of(nextYear, 1, 1), createdHolidaysAccount.getValidFrom()); Assert.assertEquals("Wrong validity end date", LocalDate.of(nextYear, 12, 31), createdHolidaysAccount.getValidTo()); verify(accountService).save(createdHolidaysAccount); verify(vacationDaysService).calculateTotalLeftVacationDays(referenceHolidaysAccount); verify(accountService, times(2)).getHolidaysAccount(nextYear, person); } @Test public void ensureUpdatesRemainingVacationDaysOfHolidaysAccountIfAlreadyExists() { int year = 2014; int nextYear = 2015; LocalDate startDate = LocalDate.of(year, JANUARY, 1); LocalDate endDate = LocalDate.of(year, OCTOBER, 31); BigDecimal leftDays = BigDecimal.valueOf(7); Account referenceAccount = new Account(person, startDate, endDate, BigDecimal.valueOf(30), BigDecimal.valueOf(8), BigDecimal.valueOf(4), "comment"); Account nextYearAccount = new Account(person, LocalDate.of(nextYear, 1, 1), LocalDate.of( nextYear, 10, 31), BigDecimal.valueOf(28), ZERO, ZERO, "comment"); when(accountService.getHolidaysAccount(nextYear, person)).thenReturn(Optional.of(nextYearAccount)); when(vacationDaysService.calculateTotalLeftVacationDays(referenceAccount)).thenReturn(leftDays); Account account = sut.autoCreateOrUpdateNextYearsHolidaysAccount(referenceAccount); Assert.assertNotNull("Should not be null", account); Assert.assertEquals("Wrong person", person, account.getPerson()); Assert.assertEquals("Wrong number of annual vacation days", nextYearAccount.getAnnualVacationDays(), account.getAnnualVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days", leftDays, account.getRemainingVacationDays()); Assert.assertEquals("Wrong number of not expiring remaining vacation days", ZERO, account.getRemainingVacationDaysNotExpiring()); Assert.assertEquals("Wrong validity start date", nextYearAccount.getValidFrom(), account.getValidFrom()); Assert.assertEquals("Wrong validity end date", nextYearAccount.getValidTo(), account.getValidTo()); verify(accountService).save(account); verify(vacationDaysService).calculateTotalLeftVacationDays(referenceAccount); verify(accountService).getHolidaysAccount(nextYear, person); } @Test public void createHolidaysAccount() { LocalDate validFrom = LocalDate.of(2014, JANUARY, 1); LocalDate validTo = LocalDate.of(2014, DECEMBER, 31); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.empty()); when(accountService.save(any())).then(returnsFirstArg()); Account expectedAccount = sut.updateOrCreateHolidaysAccount(person, validFrom, validTo, TEN, ONE, ZERO, TEN, "comment"); assertThat(expectedAccount.getPerson()).isEqualTo(person); assertThat(expectedAccount.getAnnualVacationDays()).isEqualTo(TEN); assertThat(expectedAccount.getVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getRemainingVacationDays()).isSameAs(ZERO); assertThat(expectedAccount.getRemainingVacationDaysNotExpiring()).isEqualTo(TEN); } @Test public void updateHolidaysAccount() { LocalDate validFrom = LocalDate.of(2014, JANUARY, 1); LocalDate validTo = LocalDate.of(2014, DECEMBER, 31); Account account = new Account(person, validFrom, validTo, TEN, TEN, TEN, "comment"); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.of(account)); when(accountService.save(any())).then(returnsFirstArg()); Account expectedAccount = sut.updateOrCreateHolidaysAccount(person, validFrom, validTo, ONE, ONE, ONE, ONE, "new comment"); assertThat(expectedAccount.getPerson()).isEqualTo(person); assertThat(expectedAccount.getAnnualVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getRemainingVacationDays()).isSameAs(ONE); assertThat(expectedAccount.getRemainingVacationDaysNotExpiring()).isEqualTo(ONE); } }
package org.shipkit.internal.gradle.release.tasks; import org.gradle.api.GradleException; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.shipkit.gradle.release.ReleaseNeededTask; import org.shipkit.internal.util.ArgumentValidation; import org.shipkit.internal.util.EnvVariables; public class ReleaseNeeded { private final static Logger LOG = Logging.getLogger(ReleaseNeededTask.class); //We are using environment variable instead of system property or Gradle project property here //It's easier to configure Travis CI matrix builds using env variables //For reference, see the ".travis.yml" of Mockito project private final static String SKIP_RELEASE_ENV = "SKIP_RELEASE"; private final static String SKIP_RELEASE_KEYWORD = "[ci skip-release]"; private static final String SKIP_COMPARE_PUBLICATIONS = "[ci skip-compare-publications]"; public boolean releaseNeeded(ReleaseNeededTask task) { return releaseNeeded(task, new EnvVariables()); } boolean releaseNeeded(ReleaseNeededTask task, EnvVariables envVariables) { ReleaseNeed releaseNeed = releaseNeed(task, envVariables); boolean releaseNeeded = releaseNeed.needed; String message = releaseNeed.explanation; if (!releaseNeeded && task.isExplosive()) { throw new GradleException(message); } else { LOG.lifecycle(message); } return releaseNeeded; } private ReleaseNeed releaseNeed(ReleaseNeededTask task, EnvVariables envVariables) { boolean skipEnvVariable = envVariables.getNonEmptyEnv(SKIP_RELEASE_ENV) != null; boolean commitMessageEmpty = task.getCommitMessage() == null || task.getCommitMessage().trim().isEmpty(); boolean skippedByCommitMessage = !commitMessageEmpty && task.getCommitMessage().contains(SKIP_RELEASE_KEYWORD); boolean skipComparePublications = !commitMessageEmpty && task.getCommitMessage().contains(SKIP_COMPARE_PUBLICATIONS); LOG.lifecycle(" Commit message to inspect for keywords '{}' and '{}': {}", SKIP_RELEASE_KEYWORD, SKIP_COMPARE_PUBLICATIONS, commitMessageEmpty ? "<unknown commit message>" : "\n" + task.getCommitMessage()); boolean releasableBranch = task.getBranch() != null && task.getBranch().matches(task.getReleasableBranchRegex()); LOG.lifecycle(" Current branch '{}' matches '{}': {}", task.getBranch(), task.getReleasableBranchRegex(), releasableBranch); ComparisonResults results = new ComparisonResults(task.getComparisonResults()); boolean publicationsIdentical = results.areResultsIdentical(); LOG.lifecycle(results.getDescription()); LOG.lifecycle("Release is considered _not_ needed when:\n" + " - 'SKIP_RELEASE' environment variable is present (currently: " + skipEnvVariable + ")\n" + " - commit message contains '" + SKIP_RELEASE_KEYWORD + "' (currently: " + skippedByCommitMessage + ")\n" + " - we are building a \"pull request\" (currently: " + task.isPullRequest() + ")\n" + "Release is needed when all above is false and: \n" + " - we are building on a branch that matches regex '" + task.getReleasableBranchRegex() + "' (currently: " + releasableBranch + ")\n" + " - and one of the following criteria is true:\n" + " - there are changes in the binaries when compared to previous version (currently: " + !publicationsIdentical + ")\n" + " - commit message contains '" + SKIP_COMPARE_PUBLICATIONS + "' (currently: " + skipComparePublications + ")\n" + " - 'skipComparePublications' property on task " + task.getName() + " is true (currently: " + task.isSkipComparePublications() + ")\n" ); if (releasableBranch) { if (skippedByCommitMessage) { return ReleaseNeed.of(false, " Skipping release due to skip release keyword in commit message."); } else if (skipEnvVariable) { return ReleaseNeed.of(false, " Skipping release due to skip release env variable."); } else if (task.isPullRequest()) { return ReleaseNeed.of(false, " Skipping release due to is PR."); } else if (task.isSkipComparePublications()) { return ReleaseNeed.of(true, " Releasing due to 'skipComparePublications' property on task " + task.getName() + '.'); } else if (skipComparePublications) { return ReleaseNeed.of(true, " Releasing due to '" + SKIP_COMPARE_PUBLICATIONS + "' keyword in commit message."); } else { if (publicationsIdentical) { return ReleaseNeed.of(false, " Skipping release because publications are identical."); } return ReleaseNeed.of(true, " Releasing because publication changed."); } } else { return ReleaseNeed.of(false, " Skipping release because we are not on a releasable branch."); } } private static class ReleaseNeed { private final boolean needed; private final String explanation; private ReleaseNeed(boolean needed, String explanation) { ArgumentValidation.notNull( explanation, "explanation"); this.needed = needed; this.explanation = explanation; } static ReleaseNeed of(boolean needed, String explanation) { return new ReleaseNeed(needed, explanation); } @Override public String toString() { return "ReleaseNeed{needed=" + needed + ", explanation='" + explanation + '\'' + '}'; } } }
package ch.srsx.swat.datapower.tools.ant.taskdefs; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Vector; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * This ANT task generates a DataPower configuration specific files element. * * @author <a href="mailto:pshah@schlagundrahm.ch">Pierce Shah</a> * */ public class CreateFilesConfig extends Task { private File file; private Vector<FileSet> filesets; private FileUtils fileUtils; private String env; private String domain; private String comment; private String location = "local"; private boolean useBaseDir = true; private boolean createDpConfig = false; private String dpBaseDir; private String targetdir; private String targetfile; private final String dpFileSeparator = "/"; private final String systemFileSeparator = System.getProperty("file.separator"); private final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); private final SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss"); public CreateFilesConfig() { fileUtils = FileUtils.getFileUtils(); file = null; filesets = new Vector<FileSet>(); } public void setFile(File file) { this.file = file; } public void addFileset(FileSet set) { filesets.addElement(set); } public void setEnv(String env) { this.env = env; } public void setTargetdir(String targetdir) { this.targetdir = targetdir; } public void setTargetfile(String targetfile) { this.targetfile = targetfile; } public void setLocation(String location) { this.location = location; } public void setUseBaseDir(boolean useBaseDir) { this.useBaseDir = useBaseDir; } public void setDpBaseDir(String dpBaseDir) { this.dpBaseDir = dpBaseDir; } public void setCreateDpConfig(boolean createDpConfig) { this.createDpConfig = createDpConfig; } public void setDomain(String domain) { this.domain = domain; } public void setComment(String comment) { this.comment = comment; } public void execute() throws BuildException { if ((file != null) && (filesets.size() > 0)) { throw new BuildException( "You cannot supply the 'file' attribute and filesets at the same time."); } if ((file != null) && file.exists()) { log(file + " ==> " + file.getAbsolutePath()); } else if (file != null) { log("The following file is missing: '" + file.getAbsolutePath() + "'", 0); } int sz = filesets.size(); Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // initialize files element Element filesNode = doc.createElement("files"); if (createDpConfig) { // create datapower-configuration element Element dpNode = doc.createElement("datapower-configuration"); dpNode.setAttribute("version", "3"); // create export-details element Element detailsNode = doc.createElement("export-details"); Element descNode = doc.createElement("description"); descNode.setTextContent("SWAT generated configuration"); detailsNode.appendChild(descNode); Element userNode = doc.createElement("user"); userNode.setTextContent(System.getProperty("user.name")); detailsNode.appendChild(userNode); Element domainNode = doc.createElement("domain"); domainNode.setTextContent(domain); detailsNode.appendChild(domainNode); Element commentNode = doc.createElement("comment"); commentNode.setTextContent(comment); detailsNode.appendChild(commentNode); Calendar cal = Calendar.getInstance(); Element dateNode = doc.createElement("current-date"); dateNode.setTextContent(df.format(cal.getTime())); detailsNode.appendChild(dateNode); Element timeNode = doc.createElement("current-time"); timeNode.setTextContent(tf.format(cal.getTime())); detailsNode.appendChild(timeNode); dpNode.appendChild(detailsNode); // create configuration element Element configNode = doc.createElement("configuration"); configNode.setAttribute("domain", domain); dpNode.appendChild(configNode); // append empty files node dpNode.appendChild(filesNode); // append root node to the document doc.appendChild(dpNode); } else { doc.appendChild(filesNode); } for (int i = 0; i < sz; i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); log("number of files: " + files.length); for (int j = 0; j < files.length; j++) { log("file[" + j + "] = " + files[j]); File f = new File(fs.getDir(getProject()), files[j]); String dpFileSrc = files[j].replace( systemFileSeparator, dpFileSeparator); String dpFileName = dpFileSrc; if (useBaseDir) { int pos = dpFileName.indexOf(dpFileSeparator); dpBaseDir = dpFileName.substring(0, pos); dpFileName = dpFileName.substring(pos + 1); } else { dpBaseDir = location; } if (f.exists()) { try { log("File: " + f); Element child = doc.createElement("file"); filesNode.appendChild(child); child.setAttribute("name", dpBaseDir + ":///" + dpFileName); child.setAttribute("src", dpFileSrc); child.setAttribute("location", location); child.setAttribute("hash", calculateFileHash(f)); } catch (Exception e) { log("An error occurred processing file: '" + f.getAbsolutePath() + "': " + e.toString(), 0); } } else { log("The following file is missing: '" + f.getAbsolutePath() + "'", 0); } } } /* * OutputFormat format = new OutputFormat(document); * format.setLineWidth(65); format.setIndenting(true); * format.setIndent(2); */ try { Transformer serializer = TransformerFactory.newInstance() .newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4"); File f = new File(targetdir + systemFileSeparator + targetfile); log("file: " + f); URI uri = f.toURI(); log("URI: " + uri); StreamResult sr = new StreamResult(new File(uri)); serializer.transform(new DOMSource(doc), sr); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String calculateFileHash(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] hash = null; try { hash = DigestUtils.sha(is); } finally { if (is != null) { is.close(); } } if (hash == null) { throw new BuildException("Could not calcualte SHA-1 hash for file: " + file); } return Base64.encodeBase64String(hash).trim(); } }
package edu.northwestern.bioinformatics.studycalendar.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dbunit.DatabaseUnitException; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.Column; import org.dbunit.dataset.CompositeDataSet; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.DefaultTable; import org.dbunit.dataset.DefaultTableIterator; import org.dbunit.dataset.FilteredDataSet; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.ITableIterator; import org.dbunit.dataset.ITableMetaData; import org.dbunit.dataset.filter.SequenceTableFilter; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.operation.DatabaseOperation; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author Rhett Sutphin */ public class LoaderController implements Controller { private static Log log = LogFactory.getLog(LoaderController.class); private String resourcePrefix; private DataSource dataSource; public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/plain"); Writer w = new OutputStreamWriter(response.getOutputStream()); Loader loader = createLoader(request, w); loader.load(); w.close(); return null; } private Loader createLoader(HttpServletRequest request, Writer writer) throws IOException { String commaDelim = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); List<String> names = Arrays.asList(commaDelim.split(",")); return new Loader(names, writer); } public void setResourcePrefix(String resourcePrefix) { this.resourcePrefix = resourcePrefix; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } private class Loader { private List<String> names; private Writer out; private Loader(List<String> names, Writer out) { this.names = names; this.out = out; } public void load() throws Exception { IDatabaseConnection conn = null; try { log("Opening connection"); conn = new DatabaseConnection(dataSource.getConnection()); executeLoad(conn); } catch (Exception e) { error("Load failed due to exception", e); } finally { if (conn != null) conn.close(); } } private void executeLoad(IDatabaseConnection conn) throws IOException, SQLException, DatabaseUnitException { log("Creating merged dataset from " + names); List<IDataSet> sets = new ArrayList<IDataSet>(); for (String name : names) { InputStream resource = getResourceFor(name); if (resource != null) { sets.add(new FlatXmlDataSet(resource)); } } if (sets.size() == 0) { error("No datasets found"); } else { CompositeDataSet source = new CompositeDataSet(sets.toArray(new IDataSet[sets.size()])); log("Merged dataset contains tables " + Arrays.asList(source.getTableNames())); log("Ordering tables to prevent foreign key conflicts"); SequenceTableFilter filter = new ForeignKeySequenceFilter(conn, source.getTableNames()); log(" - Filtered order is " + Arrays.asList(filter.getTableNames(source))); IDataSet dataset = new NullAsNoValueDataSet(new FilteredDataSet(filter, source)); log("Wiping all configured tables"); DatabaseOperation.DELETE_ALL.execute(conn, dataset); log("Inserting test data"); if (log.isDebugEnabled()) { for (ITableIterator it = dataset.iterator(); it.next();) { ITable table = it.getTable(); log.debug("Found " + table.getRowCount() + " row(s) for " + table.getTableMetaData().getTableName()); for (int i = 0 ; i < table.getRowCount() ; i++) { log.debug("Row " + i); for (Column column : table.getTableMetaData().getColumns()) { Object value = table.getValue(i, column.getColumnName()); log.debug(" - " + column.getColumnName() + '=' + value + " (null? " + (value == null) + ')'); } } } } DatabaseOperation.INSERT.execute(conn, dataset); conn.getConnection().commit(); log("Load complete"); } } private InputStream getResourceFor(String name) throws IOException { StringBuilder sb = new StringBuilder().append(resourcePrefix); if (sb.charAt(sb.length() - 1) != '/') sb.append('/'); String resName = sb.append(name).append(".xml").toString(); log(" - Loading dataset " + name); InputStream resource = getClass().getResourceAsStream(resName); if (resource == null) { error(" Cannot find resource " + resName + " implied by " + name); } return resource; } private void log(String message) throws IOException { log.info(message); out.write("INFO " + message + '\n'); out.flush(); } private void error(String message) throws IOException { error(message, null); } private void error(String message, Exception e) throws IOException { if (e == null) { log.error(message); } else { log.error(message, e); } out.write("ERROR " + message + '\n'); if (e != null) { out.write(" " + e.getMessage() + '\n'); for (StackTraceElement element : e.getStackTrace()) { out.write(" " + element + '\n'); } } out.flush(); } } private static class NullAsNoValueDataSet implements IDataSet { private Map<String, ITable> byName; public NullAsNoValueDataSet(IDataSet source) throws DataSetException { byName = new LinkedHashMap<String, ITable>(); for (ITableIterator it = source.iterator(); it.next();) { ITable table = it.getTable(); DefaultTable newTable = new DefaultTable(table.getTableMetaData()); newTable.addTableRows(table); for (int r = 0; r < table.getRowCount(); r++) { for (Column column : table.getTableMetaData().getColumns()) { Object value = transformValue(table.getValue(r, column.getColumnName())); newTable.setValue(r, column.getColumnName(), value); } } byName.put(newTable.getTableMetaData().getTableName(), newTable); } } private Object transformValue(Object value) { return value == null ? ITable.NO_VALUE : value; } public ITable getTable(String tableName) throws DataSetException { return byName.get(tableName); } public ITable[] getTables() throws DataSetException { return byName.values().toArray(new ITable[byName.size()]); } public String[] getTableNames() throws DataSetException { return byName.keySet().toArray(new String[byName.size()]); } public ITableMetaData getTableMetaData(String tableName) throws DataSetException { return getTable(tableName).getTableMetaData(); } public ITableIterator iterator() throws DataSetException { return new DefaultTableIterator(getTables(), false); } public ITableIterator reverseIterator() throws DataSetException { return new DefaultTableIterator(getTables(), true); } } }
package no.nordicsemi.android.dfu.internal; import android.os.Build; import android.util.Log; import com.google.gson.Gson; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import androidx.annotation.NonNull; import no.nordicsemi.android.dfu.DfuBaseService; import no.nordicsemi.android.dfu.internal.manifest.FileInfo; import no.nordicsemi.android.dfu.internal.manifest.Manifest; import no.nordicsemi.android.dfu.internal.manifest.ManifestFile; import no.nordicsemi.android.dfu.internal.manifest.SoftDeviceBootloaderFileInfo; public class ArchiveInputStream extends InputStream { private static final String TAG = "DfuArchiveInputStream"; /** * The name of the manifest file is fixed. */ private static final String MANIFEST = "manifest.json"; // Those file names are for backwards compatibility mode private static final String SOFTDEVICE_HEX = "softdevice.hex"; private static final String SOFTDEVICE_BIN = "softdevice.bin"; private static final String BOOTLOADER_HEX = "bootloader.hex"; private static final String BOOTLOADER_BIN = "bootloader.bin"; private static final String APPLICATION_HEX = "application.hex"; private static final String APPLICATION_BIN = "application.bin"; private static final String SYSTEM_INIT = "system.dat"; private static final String APPLICATION_INIT = "application.dat"; private final ZipInputStream zipInputStream; /** * Contains bytes arrays with BIN files. HEX files are converted to BIN before being * added to this map. */ private final Map<String, byte[]> entries; private final CRC32 crc32; private Manifest manifest; private byte[] applicationBytes; private byte[] softDeviceBytes; private byte[] bootloaderBytes; private byte[] softDeviceAndBootloaderBytes; private byte[] systemInitBytes; private byte[] applicationInitBytes; private byte[] currentSource; private int type; private int bytesReadFromCurrentSource; private int softDeviceSize; private int bootloaderSize; private int applicationSize; private int bytesRead; private byte[] markedSource; private int bytesReadFromMarkedSource; /** * <p> * The ArchiveInputStream read HEX or BIN files from the Zip stream. It may skip some of them, * depending on the value of the types parameter. This is useful if the DFU service wants to * send the Soft Device and Bootloader only, and then the Application in the following connection, * despite the ZIP file contains all 3 HEX/BIN files. * When types is equal to {@link DfuBaseService#TYPE_AUTO} all present files are read. * <p> * Use bit combination of the following types: * <ul> * <li>{@link DfuBaseService#TYPE_SOFT_DEVICE}</li> * <li>{@link DfuBaseService#TYPE_BOOTLOADER}</li> * <li>{@link DfuBaseService#TYPE_APPLICATION}</li> * <li>{@link DfuBaseService#TYPE_AUTO}</li> * </ul> * * @param stream the Zip Input Stream * @param mbrSize The size of the MRB segment (Master Boot Record) on the device. * The parser will cut data from addresses below that number from all HEX files. * @param types File types that are to be read from the ZIP. Use * {@link DfuBaseService#TYPE_APPLICATION} etc. * @throws java.io.IOException Thrown in case of an invalid ZIP file. */ public ArchiveInputStream(final InputStream stream, final int mbrSize, final int types) throws IOException { // Check if the file is not too big. It's hard to say what would be considered too big, but // 10 MB should be enough for any firmware package. If not, fork the library and change this. if (stream.available() > 10 * 1024 * 1024) { throw new IOException("File too large: " + stream.available() + " bytes (max 10 MB)"); } this.zipInputStream = new ZipInputStream(stream); this.crc32 = new CRC32(); this.entries = new HashMap<>(); this.bytesRead = 0; this.bytesReadFromCurrentSource = 0; try { /* * This method reads all entries from the ZIP file and puts them to entries map. * The 'manifest.json' file, if exists, is converted to the manifestData String. */ parseZip(mbrSize); /* * Let's read and parse the 'manifest.json' file. */ if (manifest != null) { boolean valid = false; // Read the application if (manifest.getApplicationInfo() != null && (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_APPLICATION) > 0)) { final FileInfo application = manifest.getApplicationInfo(); applicationBytes = entries.get(application.getBinFileName()); applicationInitBytes = entries.get(application.getDatFileName()); if (applicationBytes == null) throw new IOException("Application file " + application.getBinFileName() + " not found."); applicationSize = applicationBytes.length; currentSource = applicationBytes; valid = true; } // Read the Bootloader if (manifest.getBootloaderInfo() != null && (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_BOOTLOADER) > 0)) { if (systemInitBytes != null) throw new IOException("Manifest: softdevice and bootloader specified. Use softdevice_bootloader instead."); final FileInfo bootloader = manifest.getBootloaderInfo(); bootloaderBytes = entries.get(bootloader.getBinFileName()); systemInitBytes = entries.get(bootloader.getDatFileName()); if (bootloaderBytes == null) throw new IOException("Bootloader file " + bootloader.getBinFileName() + " not found."); bootloaderSize = bootloaderBytes.length; currentSource = bootloaderBytes; valid = true; } // Read the Soft Device if (manifest.getSoftdeviceInfo() != null && (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_SOFT_DEVICE) > 0)) { final FileInfo softdevice = manifest.getSoftdeviceInfo(); softDeviceBytes = entries.get(softdevice.getBinFileName()); systemInitBytes = entries.get(softdevice.getDatFileName()); if (softDeviceBytes == null) throw new IOException("SoftDevice file " + softdevice.getBinFileName() + " not found."); softDeviceSize = softDeviceBytes.length; currentSource = softDeviceBytes; valid = true; } // Read the combined Soft Device and Bootloader if (manifest.getSoftdeviceBootloaderInfo() != null && (types == DfuBaseService.TYPE_AUTO || ((types & DfuBaseService.TYPE_SOFT_DEVICE) > 0) && (types & DfuBaseService.TYPE_BOOTLOADER) > 0)) { if (systemInitBytes != null) throw new IOException("Manifest: The softdevice_bootloader may not be used together with softdevice or bootloader."); final SoftDeviceBootloaderFileInfo system = manifest.getSoftdeviceBootloaderInfo(); softDeviceAndBootloaderBytes = entries.get(system.getBinFileName()); systemInitBytes = entries.get(system.getDatFileName()); if (softDeviceAndBootloaderBytes == null) throw new IOException("File " + system.getBinFileName() + " not found."); softDeviceSize = system.getSoftdeviceSize(); bootloaderSize = system.getBootloaderSize(); currentSource = softDeviceAndBootloaderBytes; valid = true; } if (!valid) { throw new IOException("Manifest file must specify at least one file."); } } else { /* * Compatibility mode. The 'manifest.json' file does not exist. * * In that case the ZIP file must contain one or more of the following files: * * - application.hex/dat * + application.dat * - softdevice.hex/dat * - bootloader.hex/dat * + system.dat */ boolean valid = false; // Search for the application if (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_APPLICATION) > 0) { applicationBytes = entries.get(APPLICATION_HEX); // the entry bytes has already been converted to BIN, just the name remained. if (applicationBytes == null) applicationBytes = entries.get(APPLICATION_BIN); if (applicationBytes != null) { applicationSize = applicationBytes.length; applicationInitBytes = entries.get(APPLICATION_INIT); currentSource = applicationBytes; valid = true; } } // Search for theBootloader if (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_BOOTLOADER) > 0) { bootloaderBytes = entries.get(BOOTLOADER_HEX); // the entry bytes has already been converted to BIN, just the name remained. if (bootloaderBytes == null) bootloaderBytes = entries.get(BOOTLOADER_BIN); if (bootloaderBytes != null) { bootloaderSize = bootloaderBytes.length; systemInitBytes = entries.get(SYSTEM_INIT); currentSource = bootloaderBytes; valid = true; } } // Search for the Soft Device if (types == DfuBaseService.TYPE_AUTO || (types & DfuBaseService.TYPE_SOFT_DEVICE) > 0) { softDeviceBytes = entries.get(SOFTDEVICE_HEX); // the entry bytes has already been converted to BIN, just the name remained. if (softDeviceBytes == null) softDeviceBytes = entries.get(SOFTDEVICE_BIN); if (softDeviceBytes != null) { softDeviceSize = softDeviceBytes.length; systemInitBytes = entries.get(SYSTEM_INIT); currentSource = softDeviceBytes; valid = true; } } if (!valid) { throw new IOException("The ZIP file must contain an Application, a Soft Device and/or a Bootloader."); } } mark(0); } finally { type = getContentType(); zipInputStream.close(); } } /** * Validates the path (not the content) of the zip file to prevent path traversal issues. * * <p> When unzipping an archive, always validate the compressed files' paths and reject any path * that has a path traversal (such as ../..). Simply looking for .. characters in the compressed * file's path may not be enough to prevent path traversal issues. The code validates the name of * the entry before extracting the entry. If the name is invalid, the entire extraction is aborted. * <p> * * @param filename The path to the file. * @param intendedDir The intended directory where the zip should be. * @return The validated path to the file. * @throws java.io.IOException Thrown in case of path traversal issues. */ @SuppressWarnings("SameParameterValue") private String validateFilename(@NonNull final String filename, @NonNull final String intendedDir) throws java.io.IOException { File f = new File(filename); String canonicalPath = f.getCanonicalPath(); File iD = new File(intendedDir); String canonicalID = iD.getCanonicalPath(); if (canonicalPath.startsWith(canonicalID)) { return canonicalPath.substring(1); // remove leading "/" } else { throw new IllegalStateException("File is outside extraction target directory."); } } /** * Reads all files into byte arrays. * Here we don't know whether the ZIP file is valid. * <p> * The ZIP file is valid when contains a 'manifest.json' file and all BIN and DAT files that * are specified in the manifest. * <p> * For backwards compatibility ArchiveInputStream supports also ZIP archives without * 'manifest.json' file but than it MUST include at least one of the following files: * softdevice.bin/hex, bootloader.bin/hex, application.bin/hex. * To support the init packet such ZIP file should contain also application.dat and/or system.dat * (with the CRC16 of a SD, BL or SD+BL together). */ private void parseZip(final int mbrSize) throws IOException { final byte[] buffer = new byte[1024]; String manifestData = null; ZipEntry ze; while ((ze = zipInputStream.getNextEntry()) != null) { final String filename = validateFilename(ze.getName(), "."); if (ze.isDirectory()) { Log.w(TAG, "A directory found in the ZIP: " + filename + "!"); continue; } // Read file content to byte array final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int count; while ((count = zipInputStream.read(buffer)) != -1) { baos.write(buffer, 0, count); } byte[] source = baos.toByteArray(); // In case of HEX file convert it to BIN if (filename.toLowerCase(Locale.US).endsWith("hex")) { final HexInputStream is = new HexInputStream(source, mbrSize); source = new byte[is.available()]; is.read(source); is.close(); } // Save the file content either as a manifest data or by adding it to entries if (MANIFEST.equals(filename)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { manifestData = new String(source, StandardCharsets.UTF_8); } else { //noinspection CharsetObjectCanBeUsed manifestData = new String(source, "UTF-8"); } else entries.put(filename, source); } // Some validation if (entries.isEmpty()) { throw new FileNotFoundException("No files found in the ZIP. Check if the URI provided is " + "valid and the ZIP contains required files on root level, not in a directory."); } if (manifestData != null) { final ManifestFile manifestFile = new Gson().fromJson(manifestData, ManifestFile.class); manifest = manifestFile.getManifest(); if (manifest == null) { Log.w(TAG, "Manifest failed to be parsed. Did you add \n" + "-keep class no.nordicsemi.android.dfu.** { *; }\n" + "to your proguard rules?"); } } else { Log.w(TAG, "Manifest not found in the ZIP. It is recommended to use a distribution " + "file created with: https://github.com/NordicSemiconductor/pc-nrfutil/ (for Legacy DFU use version 0.5.x)"); } } @Override public void close() throws IOException { softDeviceBytes = null; bootloaderBytes = null; applicationBytes = null; softDeviceAndBootloaderBytes = null; softDeviceSize = bootloaderSize = applicationSize = 0; currentSource = null; bytesRead = bytesReadFromCurrentSource = 0; zipInputStream.close(); } @Override public long skip(final long n) { return 0; } @Override public int read() { final byte[] buffer = new byte[1]; if (read(buffer) == -1) { return -1; } else { return buffer[0] & 0xFF; } } @Override public int read(@NonNull final byte[] buffer) { return read(buffer, 0, buffer.length); } @Override public int read(@NonNull final byte[] buffer, final int offset, final int length) { final int size = rawRead(buffer, offset, length); if (length > size && startNextFile() != null) { return size + rawRead(buffer, offset + size, length - size); } return size; } private int rawRead(@NonNull final byte[] buffer, final int offset, final int length) { final int maxSize = currentSource.length - bytesReadFromCurrentSource; final int size = Math.min(length, maxSize); System.arraycopy(currentSource, bytesReadFromCurrentSource, buffer, offset, size); bytesReadFromCurrentSource += size; bytesRead += size; crc32.update(buffer, offset, size); return size; } @Override public boolean markSupported() { return true; } /** * Marks the current position in the stream. The parameter is ignored. * * @param readlimit this parameter is ignored, can be anything */ @Override public void mark(final int readlimit) { markedSource = currentSource; bytesReadFromMarkedSource = bytesReadFromCurrentSource; } @Override public void reset() { currentSource = markedSource; bytesRead = bytesReadFromCurrentSource = bytesReadFromMarkedSource; // Restore the CRC to the value is was on mark. crc32.reset(); if (currentSource == bootloaderBytes && softDeviceBytes != null) { crc32.update(softDeviceBytes); bytesRead += softDeviceSize; } crc32.update(currentSource, 0, bytesReadFromCurrentSource); } /** * Resets to the beginning of current stream. * If SD and BL were updated, the stream will be reset to the beginning. * If SD and BL were already sent and the current stream was changed to application, * this method will reset to the beginning of the application stream. */ public void fullReset() { // Reset stream to SoftDevice if SD and BL firmware were given separately if (softDeviceBytes != null && bootloaderBytes != null && currentSource == bootloaderBytes) { currentSource = softDeviceBytes; } // Reset the bytes count to 0 bytesReadFromCurrentSource = 0; mark(0); reset(); } /** * Returns number of bytes read until now. */ public int getBytesRead() { return bytesRead; } /** * Returns the CRC32 of the part of the firmware that was already read. * * @return the CRC */ public long getCrc32() { return crc32.getValue(); } /** * Returns the content type based on the content of the ZIP file. The content type may be * truncated using {@link #setContentType(int)}. * * @return A bit field of {@link DfuBaseService#TYPE_SOFT_DEVICE TYPE_SOFT_DEVICE}, * {@link DfuBaseService#TYPE_BOOTLOADER TYPE_BOOTLOADER} and * {@link DfuBaseService#TYPE_APPLICATION TYPE_APPLICATION} */ public int getContentType() { type = 0; // In Secure DFU the softDeviceSize and bootloaderSize may be 0 if both are in the ZIP file. // The size of each part is embedded in the Init packet. if (softDeviceAndBootloaderBytes != null) type |= DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER; // In Legacy DFU the size of each of these parts was given in the manifest file. if (softDeviceSize > 0) type |= DfuBaseService.TYPE_SOFT_DEVICE; if (bootloaderSize > 0) type |= DfuBaseService.TYPE_BOOTLOADER; if (applicationSize > 0) type |= DfuBaseService.TYPE_APPLICATION; return type; } /** * Truncates the current content type. May be used to hide some files, e.g. to send Soft Device * and Bootloader without Application or only the Application. * * @param type the new type. * @return The final type after truncating. */ public int setContentType(final int type) { this.type = type; // If the new type has Application, but there is no application fw, remove this type bit if ((type & DfuBaseService.TYPE_APPLICATION) > 0 && applicationBytes == null) this.type &= ~DfuBaseService.TYPE_APPLICATION; // If the new type has SD+BL if ((type & (DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER)) == (DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER)) { // but there is no SD, remove the softdevice type bit if (softDeviceBytes == null && softDeviceAndBootloaderBytes == null) this.type &= ~DfuBaseService.TYPE_SOFT_DEVICE; // or there is no BL, remove the bootloader type bit if (bootloaderBytes == null && softDeviceAndBootloaderBytes == null) this.type &= ~DfuBaseService.TYPE_SOFT_DEVICE; } else { // If at least one of SD or B: bit is cleared, but the SD+BL file is set, remove both bits. if (softDeviceAndBootloaderBytes != null) this.type &= ~(DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER); } if ((type & (DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER)) > 0 && softDeviceAndBootloaderBytes != null) currentSource = softDeviceAndBootloaderBytes; else if ((type & DfuBaseService.TYPE_SOFT_DEVICE) > 0) currentSource = softDeviceBytes; else if ((type & DfuBaseService.TYPE_BOOTLOADER) > 0) currentSource = bootloaderBytes; else if ((type & DfuBaseService.TYPE_APPLICATION) > 0) currentSource = applicationBytes; bytesReadFromCurrentSource = 0; mark(0); reset(); return this.type; } /** * Sets the currentSource to the new file or to <code>null</code> if the last file has been * transmitted. * * @return The new source, the same as {@link #currentSource}. */ private byte[] startNextFile() { byte[] ret; if (currentSource == softDeviceBytes && bootloaderBytes != null && (type & DfuBaseService.TYPE_BOOTLOADER) > 0) { ret = currentSource = bootloaderBytes; } else if (currentSource != applicationBytes && applicationBytes != null && (type & DfuBaseService.TYPE_APPLICATION) > 0) { ret = currentSource = applicationBytes; } else { ret = currentSource = null; } bytesReadFromCurrentSource = 0; return ret; } /** * Returns the number of bytes that has not been read yet. This value includes only * firmwares matching the content type set by the constructor or the * {@link #setContentType(int)} method. */ @Override public int available() { // In Secure DFU softdevice and bootloader sizes are not provided in the Init file // (they are encoded inside the Init file instead). The service doesn't send those sizes, // not the whole size of the firmware separately, like it was done in the Legacy DFU. // This method then is just used to log file size. // In case of SD+BL in Secure DFU: if (softDeviceAndBootloaderBytes != null && softDeviceSize == 0 && bootloaderSize == 0 && (type & (DfuBaseService.TYPE_SOFT_DEVICE | DfuBaseService.TYPE_BOOTLOADER)) > 0) return softDeviceAndBootloaderBytes.length + applicationImageSize() - bytesRead; // Otherwise: return softDeviceImageSize() + bootloaderImageSize() + applicationImageSize() - bytesRead; } /** * Returns the total size of the SoftDevice firmware. In case the firmware was given as a HEX, * this method returns the size of the BIN content of the file. * * @return The size of the SoftDevice firmware (BIN part). */ public int softDeviceImageSize() { return (type & DfuBaseService.TYPE_SOFT_DEVICE) > 0 ? softDeviceSize : 0; } /** * Returns the total size of the Bootloader firmware. In case the firmware was given as a HEX, * this method returns the size of the BIN content of the file. * * @return The size of the Bootloader firmware (BIN part). */ public int bootloaderImageSize() { return (type & DfuBaseService.TYPE_BOOTLOADER) > 0 ? bootloaderSize : 0; } /** * Returns the total size of the Application firmware. In case the firmware was given as a HEX, * this method returns the size of the BIN content of the file. * * @return The size of the Application firmware (BIN part). */ public int applicationImageSize() { return (type & DfuBaseService.TYPE_APPLICATION) > 0 ? applicationSize : 0; } /** * Returns the content of the init file for SoftDevice and/or Bootloader. When both SoftDevice * and Bootloader are present in the ZIP file (as two files using the compatibility mode * or as one file using the new Distribution packet) the system init contains validation data * for those two files combined (e.g. the CRC value). This method may return * <code>null</code> if there is no SoftDevice nor Bootloader in the ZIP or the DAT file is * not present there. * * @return The content of the init packet for SoftDevice and/or Bootloader. */ public byte[] getSystemInit() { return systemInitBytes; } /** * Returns the content of the init file for the Application or <code>null</code> if no * application file in the ZIP, or the DAT file is not provided. * * @return The content of the init packet for Application. */ public byte[] getApplicationInit() { return applicationInitBytes; } /** * This method returns true if the content of the ZIP file may be sent only using Secure DFU. * The reason may be that the ZIP contains a single bin file with SD and/or BL together with * App, which has to be sent in a single connection. * Sizes of each component are not given explicitly in the Manifest (even if they are, * they are ignored). They are hidden in the Init Packet instead. * * @return True if the content of this ZIP may only be sent using Secure DFU. */ public boolean isSecureDfuRequired() { return manifest != null && manifest.isSecureDfuRequired(); } }
package uk.co.transputersystems.occam.open_transputer; import uk.co.transputersystems.occam.ILOpFormatter; import uk.co.transputersystems.occam.il.Add; import uk.co.transputersystems.occam.il.Call; import uk.co.transputersystems.occam.metadata.Function; import uk.co.transputersystems.occam.il.*; import uk.co.transputersystems.occam.metadata.Workspace; import uk.co.transputersystems.occam.open_transputer.assembly.*; import uk.co.transputersystems.occam.open_transputer.assembly.Label; import java.io.InvalidObjectException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ASMGenerator { public List<ASMBlock> generateASM(List<ILBlock<Integer, ILOp<Integer>>> ilBlocks, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean suppressErrors) throws Exception { DependencyTree<Integer> dependencyTree = new DependencyTree<>(ilBlocks); ilBlocks = dependencyTree.flatten(); List<ASMBlock> result = new ArrayList<>(); /** * Preprocessing means going through all the IL ops, performing all the relevant stack tracking stuff * but not actually producing any ASM ops. * * Processing means going through all the IL ops and actually creating the relevant ASM ops. * * Preprocessing is required for calculating the maximum workspace size and thus at what offsets * things which overflow from the ABC register stack will go into. Also, what offsets variables * and arguments will be at and how big the workspace adjustments have to be. */ // Preprocess all blocks for (ILBlock<Integer, ILOp<Integer>> block : ilBlocks) { context.setCurrentILBlock(block); context.setCurrentASMBlock(null); for (ILOp<Integer> ilOp : block.getAll()) { try { process(ilOp, context, true); context.getCurrentFunction().updateAllWSSizesAndOffsets(); } catch (InvalidObjectException e) { System.err.println(e.toString()); System.err.flush(); if (!suppressErrors) { throw e; } } catch (Exception e) { System.err.println(e.toString()); System.err.flush(); if (!suppressErrors) { throw e; } } } } // Process all blocks for (ILBlock<Integer, ILOp<Integer>> block : ilBlocks) { ASMBlock asmBlock = new ASMBlock(); context.setCurrentILBlock(block); context.setCurrentASMBlock(asmBlock); for (ILOp<Integer> ilOp : block.getAll()) { try { process(ilOp, context, false); } catch (InvalidObjectException e) { System.err.println(e.toString()); System.err.flush(); asmBlock.addOp(new Label("ERROR! Couldn't process: " + ILOpFormatter.formatOp(ilOp, context.getCurrentILBlock()))); if (!suppressErrors) { throw e; } } catch (Exception e) { System.err.println(e.toString()); System.err.flush(); asmBlock.addOp(new Label("ERROR! Couldn't process: " + ILOpFormatter.formatOp(ilOp, context.getCurrentILBlock()))); if (!suppressErrors) { throw e; } } } result.add(asmBlock); } return result; } private void process(ILOp<Integer> ilOp, ASMGeneratorContext context, boolean preProcess) throws Exception { // Pre-op processing that occurs for every op context.checkForWorkspaceTransition(ilOp); context.updateCurrentStackBranch(ilOp.getId()); boolean prefixWithJump = false; if (ilOp.getRequiresLabel()) { if (ilOp.getRequiresPopAfterLabel()) { if (context.getEvaluationStackSize() == 0) { prefixWithJump = true; } else { context.popFromEvaluationStack(); } } } // Preprocess or process the IL op // Holds the result of processing. Should remain null for preprocessing List<ASMOp> asmOps = null; if (ilOp instanceof Add) { asmOps = processAdd((Add) ilOp, context, preProcess); } else if (ilOp instanceof After) { asmOps = processAfter((After) ilOp, context, preProcess); } else if (ilOp instanceof BitwiseAnd) { asmOps = processBitwiseAnd((BitwiseAnd) ilOp, context, preProcess); } else if (ilOp instanceof BitwiseNot) { asmOps = processBitwiseNot((BitwiseNot) ilOp, context, preProcess); } else if (ilOp instanceof BitwiseOr) { asmOps = processBitwiseOr((BitwiseOr) ilOp, context, preProcess); } else if (ilOp instanceof BitwiseXor) { asmOps = processBitwiseXor((BitwiseXor) ilOp, context, preProcess); } else if (ilOp instanceof BooleanAnd) { asmOps = processBooleanAnd((BooleanAnd) ilOp, context, preProcess); } else if (ilOp instanceof BooleanNot) { asmOps = processBooleanNot((BooleanNot) ilOp, context, preProcess); } else if (ilOp instanceof BooleanOr) { asmOps = processBooleanOr((BooleanOr) ilOp, context, preProcess); } else if (ilOp instanceof Branch) { asmOps = processBranch((Branch) ilOp, context, preProcess); } else if (ilOp instanceof BranchEqZero) { asmOps = processBranchEqZero((BranchEqZero) ilOp, context, preProcess); } else if (ilOp instanceof BranchIfFalse) { asmOps = processBranchIfFalse((BranchIfFalse) ilOp, context, preProcess); } else if (ilOp instanceof BranchIfTrue) { asmOps = processBranchIfTrue((BranchIfTrue) ilOp, context, preProcess); } else if (ilOp instanceof BranchNotEqZero) { asmOps = processBranchNotEqZero((BranchNotEqZero) ilOp, context, preProcess); } else if (ilOp instanceof Call) { asmOps = processCall((Call) ilOp, context, preProcess); } else if (ilOp instanceof CompareEqual) { asmOps = processCompareEqual((CompareEqual) ilOp, context, preProcess); } else if (ilOp instanceof CompareGreaterThan) { asmOps = processCompareGreaterThan((CompareGreaterThan) ilOp, context, preProcess); } else if (ilOp instanceof CompareGreaterThanOrEqual) { asmOps = processCompareGreaterThanOrEqual((CompareGreaterThanOrEqual) ilOp, context, preProcess); } else if (ilOp instanceof CompareLessThan) { asmOps = processCompareLessThan((CompareLessThan) ilOp, context, preProcess); } else if (ilOp instanceof CompareLessThanOrEqual) { asmOps = processCompareLessThanOrEqual((CompareLessThanOrEqual) ilOp, context, preProcess); } else if (ilOp instanceof CompareNotEqual) { asmOps = processCompareNotEqual((CompareNotEqual) ilOp, context, preProcess); } else if (ilOp instanceof DelayedTimerInput) { asmOps = processDelayedTimerInput((DelayedTimerInput) ilOp, context, preProcess); } else if (ilOp instanceof DisableChannel) { asmOps = processDisableChannel((DisableChannel) ilOp, context, preProcess); } else if (ilOp instanceof DisablePort) { asmOps = processDisablePort((DisablePort) ilOp, context, preProcess); } else if (ilOp instanceof DisableSkip) { asmOps = processDisableSkip((DisableSkip) ilOp, context, preProcess); } else if (ilOp instanceof DisableTimer) { asmOps = processDisableTimer((DisableTimer) ilOp, context, preProcess); } else if (ilOp instanceof Divide) { asmOps = processDivide((Divide) ilOp, context, preProcess); } else if (ilOp instanceof Duplicate) { asmOps = processDuplicate((Duplicate) ilOp, context, preProcess); } else if (ilOp instanceof EnableChannel) { asmOps = processEnableChannel((EnableChannel) ilOp, context, preProcess); } else if (ilOp instanceof EnablePort) { asmOps = processEnablePort((EnablePort) ilOp, context, preProcess); } else if (ilOp instanceof EnableSkip) { asmOps = processEnableSkip((EnableSkip) ilOp, context, preProcess); } else if (ilOp instanceof EnableTimer) { asmOps = processEnableTimer((EnableTimer) ilOp, context, preProcess); } else if (ilOp instanceof EndAlt) { asmOps = processEndAlt((EndAlt) ilOp, context, preProcess); } else if (ilOp instanceof EndProcess) { asmOps = processEndProcess((EndProcess) ilOp, context, preProcess); } else if (ilOp instanceof InitAlt) { asmOps = processInitAlt((InitAlt) ilOp, context, preProcess); } else if (ilOp instanceof InitChannel) { asmOps = processInitChannel((InitChannel) ilOp, context, preProcess); } else if (ilOp instanceof InitProcesses) { asmOps = processInitProcesses((InitProcesses) ilOp, context, preProcess); } else if (ilOp instanceof uk.co.transputersystems.occam.il.Label) { asmOps = processLabel((uk.co.transputersystems.occam.il.Label) ilOp, context, preProcess); } else if (ilOp instanceof LeftShift) { asmOps = processLeftShift((LeftShift) ilOp, context, preProcess); } else if (ilOp instanceof LoadArgument) { asmOps = processLoadArgument((LoadArgument) ilOp, context, preProcess); } else if (ilOp instanceof LoadChannelRef) { asmOps = processLoadChannelRef((LoadChannelRef) ilOp, context, preProcess); } else if (ilOp instanceof LoadConstant) { asmOps = processLoadConstant((LoadConstant) ilOp, context, preProcess); } else if (ilOp instanceof LoadGlobal) { asmOps = processLoadGlobal((LoadGlobal) ilOp, context, preProcess); } else if (ilOp instanceof LoadLocal) { asmOps = processLoadLocal((LoadLocal) ilOp, context, preProcess); } else if (ilOp instanceof LoadPortRef) { asmOps = processLoadPortRef((LoadPortRef) ilOp, context, preProcess); } else if (ilOp instanceof MethodEnd) { asmOps = processMethodEnd((MethodEnd) ilOp, context, preProcess); } else if (ilOp instanceof MethodStart) { asmOps = processMethodStart((MethodStart) ilOp, context, preProcess); } else if (ilOp instanceof Modulo) { asmOps = processModulo((Modulo) ilOp, context, preProcess); }else if (ilOp instanceof MostPositive) { asmOps = processMostPositive((MostPositive) ilOp, context, preProcess); }else if (ilOp instanceof MostNegative){ asmOps = processMostNegative((MostNegative) ilOp, context, preProcess); } else if (ilOp instanceof Multiply) { asmOps = processMultiply((Multiply) ilOp, context, preProcess); } else if (ilOp instanceof ReadChannel) { asmOps = processReadChannel((ReadChannel) ilOp, context, preProcess); } else if (ilOp instanceof ReadPort) { asmOps = processReadPort((ReadPort) ilOp, context, preProcess); } else if (ilOp instanceof ReadTimer) { asmOps = processReadTimer((ReadTimer) ilOp, context, preProcess); } else if (ilOp instanceof RightShift) { asmOps = processRightShift((RightShift) ilOp, context, preProcess); } else if (ilOp instanceof Skip) { asmOps = processSkip((Skip) ilOp, context, preProcess); } else if (ilOp instanceof StartProcess) { asmOps = processStartProcess((StartProcess) ilOp, context, preProcess); } else if (ilOp instanceof StoreArgument) { asmOps = processStoreArgument((StoreArgument) ilOp, context, preProcess); } else if (ilOp instanceof StoreGlobal) { asmOps = processStoreGlobal((StoreGlobal) ilOp, context, preProcess); } else if (ilOp instanceof StoreLocal) { asmOps = processStoreLocal((StoreLocal) ilOp, context, preProcess); } else if (ilOp instanceof Subtract) { asmOps = processSubtract((Subtract) ilOp, context, preProcess); } else if (ilOp instanceof UnaryMinus) { asmOps = processUnaryMinus((UnaryMinus) ilOp, context, preProcess); } else if (ilOp instanceof WaitAlt) { asmOps = processWaitAlt((WaitAlt) ilOp, context, preProcess); } else if (ilOp instanceof WriteChannel) { asmOps = processWriteChannel((WriteChannel) ilOp, context, preProcess); } else if (ilOp instanceof WritePort) { asmOps = processWritePort((WritePort) ilOp, context, preProcess); } else { throw new InvalidObjectException("Unrecognised IL op type in the ASMGenerator! IL op: " + ILOpFormatter.formatOp(ilOp, context.getCurrentILBlock())); } if (!preProcess && asmOps != null) { // Post-op processing if (context.initProcesses_ContinueOpIds.size() > 0) { if (context.initProcesses_ContinueOpIds.peek().equals(ilOp.getId())) { context.initProcesses_ContinueOpIds.pop(); asmOps.add(0, new Ajw(-(int)context.initProcesses_ProcCountOffsets.pop())); } } if (ilOp.getRequiresLabel()) { String labelStr = context.generateILOpLabel(ilOp); Label label = new Label(labelStr); if (asmOps.size() > 0) { asmOps = new ArrayList<>(asmOps); asmOps.add(0, label); } else { asmOps = new ArrayList<>(); asmOps.add(label); } if (prefixWithJump) { asmOps.add(0, new Ldc(0)); asmOps.add(1, new Cj(labelStr + "-$0")); } if (ilOp.getRequiresPopAfterLabel()) { asmOps.add(new Diff()); } } // Save the ops context.getCurrentASMBlock().addOps(asmOps); } else if (preProcess && asmOps != null) { System.out.println("Pre-processing mistake. The op's process method returned a non-null list for a preprocess call. Il op: " + ILOpFormatter.formatOp(ilOp, context.getCurrentILBlock())); } } private List<ASMOp> processCall(Call<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess Function functionToCall = context.libraryInformation.getFunction(op.functionName); // Push parent WS pointer as last argument List<ASMOp> parentWSPtrOps = preProcess ? null : new ArrayList<>(); int argsSize = functionToCall.getArguments().size(); if (functionToCall.getWorkspace().getParent() != null) { argsSize += 1; List<ASMOp> pushPtrOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); if (!preProcess) { parentWSPtrOps.add(new Ldlp(0)); parentWSPtrOps.addAll(pushPtrOps); } } int expansionSize = ASMGeneratorHelpers.getFullWorkspaceSize(context, functionToCall); expansionSize -= Math.max(argsSize - 3, 0); context.getCurrentWorkspace().growExpansionArea(expansionSize); /* int extraSpace = functionToCall.getArguments().size() >= functionToCall.getReturnTypes().size() ? 0 : functionToCall.getReturnTypes().size() - functionToCall.getArguments().size(); for (int i = 0; i < extraSpace; i++) { context.getCurrentWorkspace().allocateTemporary(); }*/ List<ASMOp> popOps = ASMGeneratorHelpers.processPops(Math.min(argsSize, 3), op, context, preProcess); for (int i = 0; i < argsSize - 3; i++) { if (preProcess) { StackItem<Integer> item = context.popFromEvaluationStack(); ASMGeneratorHelpers.setupTempStore(context, item, true); } else { context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } } for (int i = 0; i < functionToCall.getReturnTypes().size() - 3; i++) { if (preProcess) { context.pushToEvaluationStack(op.getId(), i+3); } else { context.getCurrentWorkspace().allocateTemporary(); } } List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(Math.min(functionToCall.getReturnTypes().size(), 3), op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(parentWSPtrOps); result.addAll(popOps); for (int i = argsSize; i < 3; i++) { result.add(new Ldc(0)); } int offset = context.getCurrentWorkspace().getLastTemporaryOffset(Math.max(functionToCall.getReturnTypes().size()-3,0) - Math.max(argsSize-3,0), true, Integer.MIN_VALUE); result.add(new Ajw(offset)); result.add(new uk.co.transputersystems.occam.open_transputer.assembly.Call(op.functionName + "-$0" )); offset = context.getCurrentWorkspace().getLastTemporaryOffset(0, true, Integer.MIN_VALUE); result.add(new Ajw(-offset)); result.addAll(pushOps); } // Post-op code for both process and preprocess context.getCurrentWorkspace().shrinkExpansionArea(expansionSize); return result; } private List<ASMOp> processMethodStart(MethodStart<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = Collections.singletonList(new Ajw(-context.getCurrentWorkspace().getInitSize())); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processMethodEnd(MethodEnd<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = preProcess ? null : new ArrayList<>(); int retValsToPop = context.getCurrentFunction().getReturnTypes().size(); if (retValsToPop > 3) { if (preProcess) { StackItem<Integer> item1 = context.popFromEvaluationStack(); StackItem<Integer> item2 = context.popFromEvaluationStack(); StackItem<Integer> item3 = context.popFromEvaluationStack(); for (int i = 3; i < retValsToPop; i++) { StackItem<Integer> item = context.popFromEvaluationStack(); ASMGeneratorHelpers.setupTempStore(context, item, false); } context.pushToEvaluationStack(item3); context.pushToEvaluationStack(item2); context.pushToEvaluationStack(item1); } retValsToPop = 3; } if (retValsToPop > 0) { popOps = ASMGeneratorHelpers.processPops(retValsToPop, op, context, preProcess); } int iPtrStoreLocation = context.getCurrentWorkspace().getNextTemporaryOffset(true, Integer.MIN_VALUE); context.getCurrentWorkspace().allocateTemporary(); int r2StoreLocation = Integer.MIN_VALUE; if (context.getCurrentFunction().getReturnTypes().size() >= 3) { r2StoreLocation = context.getCurrentWorkspace().getNextTemporaryOffset(true, Integer.MIN_VALUE); context.getCurrentWorkspace().allocateTemporary(); } int r1StoreLocation = Integer.MIN_VALUE; if (context.getCurrentFunction().getReturnTypes().size() >= 2) { r1StoreLocation = context.getCurrentWorkspace().getNextTemporaryOffset(true, Integer.MIN_VALUE); context.getCurrentWorkspace().allocateTemporary(); } int r0StoreLocation = Integer.MIN_VALUE; if (context.getCurrentFunction().getReturnTypes().size() >= 1) { r0StoreLocation = context.getCurrentWorkspace().getNextTemporaryOffset(true, Integer.MIN_VALUE); context.getCurrentWorkspace().allocateTemporary(); } List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); //Store r0, r1, r2 if (context.getCurrentFunction().getReturnTypes().size() >= 1) { result.add(new Stl(r0StoreLocation)); if (context.getCurrentFunction().getReturnTypes().size() >= 2) { result.add(new Stl(r1StoreLocation)); } if (context.getCurrentFunction().getReturnTypes().size() >= 3) { result.add(new Stl(r2StoreLocation)); } //Load iPtr result.add(new Ldl(context.getCurrentWorkspace().getInitSize())); //Store iPtr result.add(new Stl(iPtrStoreLocation)); //Copy rN...r3 to `size` int rNDstOffset = context.getCurrentWorkspace().getSize() - 1; if (context.getCurrentFunction().getReturnTypes().size() > 3) { int rNSrcOffset = context.getCurrentWorkspace().getLastTemporaryOffset(4 + context.getCurrentFunction().getReturnTypes().size() - 3 - 1, true, Integer.MIN_VALUE); for (int i = 0; i < context.getCurrentFunction().getReturnTypes().size()-3; i++, rNSrcOffset--, rNDstOffset--) { result.add(new Ldl(rNSrcOffset)); result.add(new Stl(rNDstOffset)); } } rNDstOffset -= 3; //Copy iPtr to `size` - ((rets - 3) downto 0) - 1 - 1 // cntToIdx result.add(new Ldl(iPtrStoreLocation)); result.add(new Stl(rNDstOffset)); //Restore r0 to r2 (size-args) if (context.getCurrentFunction().getReturnTypes().size() >= 3) { result.add(new Ldl(r2StoreLocation)); } if (context.getCurrentFunction().getReturnTypes().size() >= 2) { result.add(new Ldl(r1StoreLocation)); } result.add(new Ldl(r0StoreLocation)); //Ajw result.add(new Ajw(rNDstOffset)); } else { //Ajw result.add(new Ajw(context.getCurrentWorkspace().getSize() - 4)); } //Ret result.add(new Ret()); } // Post-op code for both process and preprocess // Remove r0, r1, r2 if (context.getCurrentFunction().getReturnTypes().size() >= 1) { context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } if (context.getCurrentFunction().getReturnTypes().size() >= 2) { context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } if (context.getCurrentFunction().getReturnTypes().size() >= 3) { context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } // Remove iPtr context.getCurrentWorkspace().removeTemporaryFromWorkspace(); retValsToPop = context.getCurrentFunction().getReturnTypes().size(); if (retValsToPop > 3) { if (preProcess) { for (int i = 3; i < retValsToPop; i++) { context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } } } return result; } private List<ASMOp> processInitProcesses(InitProcesses<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<Integer> wsIds = new ArrayList<>(op.workspaceIds); wsIds.remove(0); context.setStartingProcessesWorkspaceIds(wsIds); context.addWorkspaceTransition(op.continueILOpID, context.getCurrentWorkspace().getId()); context.getCurrentWorkspace().allocateTemporary(); context.getCurrentWorkspace().allocateTemporary(); context.initProcesses_NumProcessesToStart.push(op.numProcesses - 1); context.initProcesses_NumProcessesToEnd.push(op.numProcesses); context.initProcesses_TotalNumProcessesToEnd.push(op.numProcesses); context.initProcesses_ExpandedSizes.push(0); context.getCurrentWorkspace().allocateTemporary(); int processesCountOffset = context.getCurrentWorkspace().getLastTemporaryOffset(0, true, Integer.MIN_VALUE); context.getCurrentWorkspace().allocateTemporary(); int continuePtrOffset = context.getCurrentWorkspace().getLastTemporaryOffset(0, true, Integer.MIN_VALUE); context.initProcesses_ProcCountOffsets.push(continuePtrOffset); context.initProcesses_ContinueOpIds.push(op.continueILOpID); List<ASMOp> result; if (preProcess) { // Code for preprocess only context.getCurrentILBlock().get(op.continueILOpID).setRequiresLabel(true); result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Ldc(op.numProcesses)); result.add(new Stl(processesCountOffset)); result.add(new Ldc(context.generateILOpLabel(op.continueILOpID) + "-$1")); result.add(new Ldpi()); result.add(new Stl(continuePtrOffset)); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processStartProcess(StartProcess<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<Integer> workspaceIds = context.getStartingProcessesWorkspaceIds(); Integer newWorkspaceId = workspaceIds.remove(0); context.addWorkspaceTransition(op.firstILOpID, newWorkspaceId); int numProcessesToStart = context.initProcesses_NumProcessesToStart.pop(); numProcessesToStart if (numProcessesToStart > 0) { context.initProcesses_NumProcessesToStart.push(numProcessesToStart); } ILOp<Integer> processStartOp = context.getCurrentILBlock().get(op.firstILOpID); List<ASMOp> result; if (preProcess) { // Code for preprocess only processStartOp.setRequiresLabel(true); result = null; } else { // Code for process only Workspace targetWS = context.getCurrentFunction().getWorkspaceById(newWorkspaceId); targetWS.fixedParentOffset = context.initProcesses_ProcCountOffsets.peek(); result = new ArrayList<>(); result.add(new Ldlp(targetWS.fixedParentOffset)); result.add(new Stl(-context.getCurrentWorkspace().getExpansionAreaSize() - 1)); String processLabelStr = context.generateILOpLabel(processStartOp); result.add(new Ldc(processLabelStr + "-$2")); result.add(new Ldlp(-context.getCurrentWorkspace().getExpansionAreaSize() - targetWS.getInitSize())); result.add(new Startp()); } // Post-op code for both process and preprocess int newWorkspaceFullSize = ASMGeneratorHelpers.getFullWorkspaceSize(context, context.getCurrentFunction().getScopeByWorkspaceId(newWorkspaceId)); context.initProcesses_ExpandedSizes.push(context.initProcesses_ExpandedSizes.pop() + newWorkspaceFullSize); context.getCurrentWorkspace().growExpansionArea(newWorkspaceFullSize); return result; } private List<ASMOp> processEndProcess(EndProcess<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess int totalNumProcessesToEnd = context.initProcesses_TotalNumProcessesToEnd.peek(); int numProcessesToEnd = context.initProcesses_NumProcessesToEnd.pop(); numProcessesToEnd if (numProcessesToEnd > 0) { context.initProcesses_NumProcessesToEnd.push(numProcessesToEnd); } else { context.initProcesses_TotalNumProcessesToEnd.pop(); context.getCurrentWorkspace().getParent().removeTemporaryFromWorkspace(); context.getCurrentWorkspace().getParent().removeTemporaryFromWorkspace(); } if (numProcessesToEnd == totalNumProcessesToEnd - 1) { context.getCurrentWorkspace().shrinkExpansionArea(context.initProcesses_ExpandedSizes.pop()); context.getCurrentWorkspace().removeTemporaryFromWorkspace(); context.getCurrentWorkspace().removeTemporaryFromWorkspace(); } List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); if (numProcessesToEnd == totalNumProcessesToEnd - 1) { result.add(new Ldlp(context.initProcesses_ProcCountOffsets.peek())); } else { result.add(new Ldl(context.getCurrentWorkspace().getOffset(Integer.MIN_VALUE, true, Integer.MIN_VALUE))); } result.add(new Endp()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processSkip(Skip<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLabel(uk.co.transputersystems.occam.il.Label<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only //TODO: Handle is global result = Collections.singletonList(new uk.co.transputersystems.occam.open_transputer.assembly.Label(op.label)); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processMostPositive(MostPositive<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); Long value = null; switch(op.type) { case "BOOL": value = 1l; break; case "BYTE": value = (long)Byte.MAX_VALUE; break; case "INT": value = (long)Integer.MAX_VALUE; // TODO: Load byte size from config break; case "INT16": value = (long)Short.MAX_VALUE; break; case "INT32": value = (long)Integer.MAX_VALUE; break; case "INT64": value = Long.MAX_VALUE; break; } result.add(new Ldc(value)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processMostNegative(MostNegative<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); Long value = null; switch(op.type) { case "BOOL": value = 0l; break; case "BYTE": value = (long)Byte.MIN_VALUE; break; case "INT": value = (long)Integer.MIN_VALUE; // TODO: Load byte size from config break; case "INT16": value = (long)Short.MIN_VALUE; break; case "INT32": value = (long)Integer.MIN_VALUE; break; case "INT64": value = Long.MIN_VALUE; break; } result.add(new Ldc(value)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLoadConstant(LoadConstant<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); long value = Long.parseLong(op.value); // TODO: may throw exception result.add(new Ldc(value)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLoadArgument(LoadArgument<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processLoadArgument(-op.index, op, context, preProcess, op.loadAddress); } private List<ASMOp> processLoadLocal(LoadLocal<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processLoadLocal(op.index, op, context, preProcess, op.loadAddress); } private List<ASMOp> processLoadGlobal(LoadGlobal<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // Ldc if (!op.loadAddress) { context.pushToEvaluationStack(op.getId(), -1); context.popFromEvaluationStack(); } List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Ldc(context.generateGlobalRepresentation(op.globalName))); if (!op.loadAddress) { //TODO: Handle globals which are record types i.e. reference types //TODO: Handle globals which are > word size result.add(new Ldnl(0)); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processStoreArgument(StoreArgument<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processStoreArgument(-op.index, op, context, preProcess); } private List<ASMOp> processStoreLocal(StoreLocal<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processStoreLocal(op.index, op, context, preProcess); } private List<ASMOp> processStoreGlobal(StoreGlobal<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess context.pushToEvaluationStack(op.getId(), -1); context.popFromEvaluationStack(); List<ASMOp> popOps = ASMGeneratorHelpers.processPops(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); //TODO: Handle globals which are record types i.e. reference types //TODO: Handle globals which are > word size result.add(new Ldc(context.generateGlobalRepresentation(op.globalName))); result.addAll(popOps); result.add(new Stnl(0)); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processReadChannel(ReadChannel<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { //TODO // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(3, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new In()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processReadPort(ReadPort<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { //TODO // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(3, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new In()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processReadTimer(ReadTimer<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { //TODO // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Ldtimer()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processWriteChannel(WriteChannel<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { //TODO // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(3, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Out()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processWritePort(WritePort<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { //TODO // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(3, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Out()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processAdd(Add<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); //Sum assembly op ignores overflow check if (op.ignore_overflow) { result.add(new Sum()); } else { result.add(new uk.co.transputersystems.occam.open_transputer.assembly.Add()); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processSubtract(Subtract<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); //Diff instruction ignores overflow if (op.ignore_overflow) { result.add(new Diff()); } else { result.add(new Sub()); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processMultiply(Multiply<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); if (op.ignore_overflow) { //Prod instruction ignores overflow result.add(new Prod()); } else { //Mul doesn't ignore overflow result.add(new Mul()); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processDuplicate(Duplicate<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // Dup List<ASMOp> popOps = ASMGeneratorHelpers.processPops(1, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(2, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Dup()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBranch(Branch<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) throws Exception { // Currently we store the Id of the destination label in a separate destination field for all branch instructions // Pre-op code for both process and preprocess // Ldc if (context.getEvaluationStackSize() != 0) { throw new Exception("Stack should be empty before branching!"); } List<ASMOp> result; if (preProcess) { // Code for preprocess only ILOp<Integer> target = context.getCurrentILBlock().get(op.target); target.setRequiresLabel(true); target.setRequiresPopAfterLabel(true); result = null; } else { // Code for process only // Avoid being time sliced by using conditional jump result = new ArrayList<>(); result.add(new Ldc(0)); result.add(new Cj(context.generateILOpLabel(op.target) + "-$0")); } // Post-op code for both process and preprocess // Branch context.pushToEvaluationStack(op.getId(), -1); context.forkCurrentState(op.target); context.popFromEvaluationStack(); return result; } private List<ASMOp> processBranchEqZero(BranchEqZero<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processConditionalBranch_False(op.target, op, context, preProcess); } private List<ASMOp> processBranchNotEqZero(BranchNotEqZero<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processConditionalBranch_True(op.target, op, context, preProcess); } private List<ASMOp> processBranchIfFalse(BranchIfFalse<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processConditionalBranch_False(op.target, op, context, preProcess); } private List<ASMOp> processBranchIfTrue(BranchIfTrue<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processConditionalBranch_True(op.target, op, context, preProcess); } private List<ASMOp> processCompareGreaterThan(CompareGreaterThan<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = Collections.singletonList(new Gt()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processCompareGreaterThanOrEqual(CompareGreaterThanOrEqual<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // Rev List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); context.pushToEvaluationStack(op.getId(), -1); context.pushToEvaluationStack(op.getId(), -1); context.popFromEvaluationStack(); context.popFromEvaluationStack(); context.pushToEvaluationStack(op.getId(), -1); // Eqc context.popFromEvaluationStack(); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Rev()); result.add(new Gt()); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processCompareEqual(CompareEqual<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); // Diff context.pushToEvaluationStack(op.getId(), -1); // Eqc context.popFromEvaluationStack(); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Diff()); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processCompareNotEqual(CompareNotEqual<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); // Diff context.pushToEvaluationStack(op.getId(), -1); // Eqc context.popFromEvaluationStack(); context.pushToEvaluationStack(op.getId(), -1); // Eqc context.popFromEvaluationStack(); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Diff()); result.add(new Eqc(0)); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processCompareLessThan(CompareLessThan<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); // Rev context.pushToEvaluationStack(op.getId(), -1); context.pushToEvaluationStack(op.getId(), -1); context.popFromEvaluationStack(); context.popFromEvaluationStack(); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Rev()); result.add(new Gt()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processCompareLessThanOrEqual(CompareLessThanOrEqual<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); context.pushToEvaluationStack(op.getId(), -1); // Eqc context.popFromEvaluationStack(); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Gt()); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBooleanAnd(BooleanAnd<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // And List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Eqc(0)); result.add(new Rev()); result.add(new Eqc(0)); result.add(new Or()); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBooleanOr(BooleanOr<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // And List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Or()); result.add(new Eqc(0)); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBitwiseAnd(BitwiseAnd<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // And List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new And()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBitwiseOr(BitwiseOr<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Or()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBooleanNot(BooleanNot<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(1, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Eqc(0)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBitwiseNot(BitwiseNot<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(1, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Not()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processBitwiseXor(BitwiseXor<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Xor()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processDivide(Divide<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Div()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processUnaryMinus(UnaryMinus<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // See page 5.3.5 of Compilers Writers Guide List<ASMOp> prePushOps = null; List<ASMOp> popOps; List<ASMOp> pushOps; // Pre-op code for both process and preprocess if (op.ignore_overflow) { // Ldc prePushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); // Prod popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); } else { // Ldc prePushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); // Mul popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); } List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Ldc(-1)); result.addAll(prePushOps); result.addAll(popOps); if (op.ignore_overflow) { result.add(new Prod()); } else { result.add(new Mul()); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processModulo(Modulo<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); result.add(new Rem()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLeftShift(LeftShift<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // And List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); //TODO: Handle long data types result.add(new Shl()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processRightShift(RightShift<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess // And List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.addAll(popOps); //TODO: Handle long data types result.add(new Shr()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processAfter(After<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); //TODO: Handle byte type as (( MINUS )MINUS1) 127 result.addAll(popOps); result.add(new Diff()); result.add(new Ldc(0)); result.add(new Gt()); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processDelayedTimerInput(DelayedTimerInput<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> popOps = ASMGeneratorHelpers.processPops(2, op, context, preProcess); //TODO: Stack should be empty or all stored into memory? List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Ldtimer()); result.addAll(pushOps); result.addAll(popOps); result.add(new Sum()); result.add(new Tin()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processDisableChannel(DisableChannel<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processDisable(op.target, op.endAlt, new Disc(), op, context, preProcess); } private List<ASMOp> processDisablePort(DisablePort<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processDisable(op.target, op.endAlt, new Disc(), op, context, preProcess); } private List<ASMOp> processDisableSkip(DisableSkip<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processDisable(op.target, op.endAlt, new Diss(), op, context, preProcess); } private List<ASMOp> processDisableTimer(DisableTimer<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processDisable(op.target, op.endAlt, new Dist(), op, context, preProcess); } private List<ASMOp> processEnableChannel(EnableChannel<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processEnable(new Enbc(), op, context, preProcess); } private List<ASMOp> processEnablePort(EnablePort<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processEnable(new Enbc(), op, context, preProcess); } private List<ASMOp> processEnableSkip(EnableSkip<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processEnable(new Enbs(), op, context, preProcess); } private List<ASMOp> processEnableTimer(EnableTimer<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { return ASMGeneratorHelpers.processEnable(new Enbt(), op, context, preProcess); } private List<ASMOp> processInitAlt(InitAlt<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only //TODO: Talt? result = new ArrayList<>(); result.add(new Alt()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processWaitAlt(WaitAlt<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only //TODO: Taltwt? result = new ArrayList<>(); result.add(new Altwt()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processEndAlt(EndAlt<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); result.add(new Altend()); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processInitChannel(InitChannel<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> popOps = ASMGeneratorHelpers.processPops(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only context.addChannel(op.index, op.name, op.typeName); context.getCurrentWorkspace().allocateTemporary(); result = null; } else { // Code for process only ChannelDescriptor softChannelDescriptor = context.getChannel(op.index); result = new ArrayList<>(); result.add(new Mint()); result.addAll(pushOps); result.addAll(popOps); result.add(new Stl(softChannelDescriptor.ownerWS.getNthTemporaryOffset(softChannelDescriptor.offset, true, Integer.MIN_VALUE))); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLoadChannelRef(LoadChannelRef<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result = new ArrayList<>(); ChannelDescriptor softChannelDescriptor = context.getChannel(op.index); int fixedOffset = ASMGeneratorHelpers.climbStaticChain(result, context.getCurrentWorkspace(), softChannelDescriptor.ownerWS, context); boolean isLocal = fixedOffset == Integer.MIN_VALUE; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only //TODO: Handle channel data type //TODO: External channels? result.add(new Channel(context.getChannel(op.index).getKey())); if (isLocal) { result.add(new Ldlp(softChannelDescriptor.ownerWS.getNthTemporaryOffset(softChannelDescriptor.offset, isLocal, fixedOffset))); } else { result.add(new Ldnlp(softChannelDescriptor.ownerWS.getNthTemporaryOffset(softChannelDescriptor.offset, isLocal, fixedOffset))); } result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } private List<ASMOp> processLoadPortRef(LoadPortRef<Integer> op, ASMGeneratorContext<Integer, ILOp<Integer>> context, boolean preProcess) { // Pre-op code for both process and preprocess List<ASMOp> pushOps = ASMGeneratorHelpers.processPushes(1, op, context, preProcess); List<ASMOp> result; if (preProcess) { // Code for preprocess only result = null; } else { // Code for process only result = new ArrayList<>(); //TODO: Handle port data type result.add(new Ldc("@" + op.name)); result.addAll(pushOps); } // Post-op code for both process and preprocess return result; } }
package main.java.tools; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.security.UserGroupInformation; public class KerbTest { public static void main(String[] args) { //HTable ht = null; Table table = null; Configuration conf = HBaseConfiguration.create(); conf.addResource(new Path("/etc/hbase/conf/hbase-site.xml")); conf.set("hadoop.security.authentication", "Kerberos"); UserGroupInformation.setConfiguration(conf); Connection connection = null; Admin admin = null; TableName tablename = null; //HTableDescriptor htd = null; try { UserGroupInformation.loginUserFromKeytab("hbase-kerbed_2node@OLIVER.COM", "/etc/security/keytabs/hdfs.headless.keytab"); // hdfs.headless.keytab connection = ConnectionFactory.createConnection(conf); admin = connection.getAdmin(); tablename = TableName.valueOf("table_example"); if(!admin.isTableAvailable(tablename)) { HTableDescriptor desc = new HTableDescriptor(tablename); desc.addFamily(new HColumnDescriptor("cf1")); admin.createTable(desc); //admin.createTable(desc); } //ht = new HTable(conf, "table_example"); //htd = admin.getTableDescriptor(tablename); table = connection.getTable(tablename); } catch(Exception e) { e.printStackTrace(); } Put put = new Put(Bytes.toBytes("Value to enter")); put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("newQualifier"), Bytes.toBytes("NewValue")); try { table.put(put); } catch(Exception e) { e.printStackTrace(); } // Insert rows for RowCounter for(int i = 50000; i < 50002; i++) { String strVal = "'" + i + "'"; Put insert = new Put(Bytes.toBytes(strVal)); try { insert.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("newQualifier"), Bytes.toBytes("NewValue")); table.put(insert); } catch (Exception e) {} } /* //Put put = new Put(Bytes.toBytes("Value to enter")); Scan scan = new Scan(); scan.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("newQualifier")); ResultScanner scanner = null; try { scanner = table.getScanner(scan); } catch(Exception e) { e.printStackTrace(); } for(Result result : scanner) { System.out.println(result.getRow().toString()); } */ } }
package org.wso2.carbon.uuf.handlebars.helpers.runtime; import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Helper; import com.github.jknack.handlebars.Options; import com.google.common.collect.Multimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.uuf.core.Fragment; import org.wso2.carbon.uuf.core.Renderable; import org.wso2.carbon.uuf.core.UUFException; import java.io.IOException; import java.util.Map; import static org.wso2.carbon.uuf.handlebars.HbsRenderable.BINDING_KEY; import static org.wso2.carbon.uuf.handlebars.HbsRenderable.FRAGMENT_KEY; public class IncludeFragmentHelper implements Helper<String> { private static final Logger log = LoggerFactory.getLogger(IncludeFragmentHelper.class); @Override public CharSequence apply(String fragmentName, Options options) throws IOException { //TODO: remove duplicate, defineZone Multimap<String, Renderable> bindings = options.data(BINDING_KEY); Map<String, Fragment> fragments = options.data(FRAGMENT_KEY); Fragment fragment = fragments.get(fragmentName); if (fragment == null) { throw new UUFException("Fragment '" + fragmentName + "' does not exists."); } Map<String, Object> fragmentArgs = options.hash; Object fragmentContext; if (fragmentArgs.isEmpty()) { fragmentContext = options.context; } else { fragmentContext = fragmentArgs; } if (log.isDebugEnabled()) { log.debug("Fragment " + fragment + " is called from '" + options.fn.text() + "'."); } String content = fragment.render(fragmentContext, bindings, fragments).trim(); return new Handlebars.SafeString(content); } }
package nl.jpoint.vertx.mod.cluster.handler.servicebus; import nl.jpoint.vertx.mod.cluster.aws.AwsState; import nl.jpoint.vertx.mod.cluster.request.*; import nl.jpoint.vertx.mod.cluster.service.AwsService; import nl.jpoint.vertx.mod.cluster.service.DeployArtifactService; import nl.jpoint.vertx.mod.cluster.service.DeployConfigService; import nl.jpoint.vertx.mod.cluster.service.DeployModuleService; import nl.jpoint.vertx.mod.cluster.util.LogConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonObject; public class DeployHandler implements Handler<Message<JsonObject>> { private static final Logger LOG = LoggerFactory.getLogger(DeployHandler.class); private final AwsService awsService; private final DeployModuleService deployModuleService; private final DeployArtifactService deployArtifactService; private final DeployConfigService deployConfigService; public DeployHandler(AwsService awsService, DeployModuleService deployModuleService, DeployArtifactService deployArtifactService, DeployConfigService deployConfigService) { this.awsService = awsService; this.deployModuleService = deployModuleService; this.deployArtifactService = deployArtifactService; this.deployConfigService = deployConfigService; } @Override public void handle(Message<JsonObject> message) { JsonObject body = message.body(); String deployId = body.getString("id"); AwsState state = AwsState.valueOf(body.getString("state")); if (!body.getBoolean("success")) { awsService.failBuild(deployId); return; } LOG.info("[{} - {}]: Handle internal deploy request with state {}", LogConstants.DEPLOY_REQUEST, deployId, state); switch (state) { case STANDBY: case NOTREGISTERED: case OUTOFSERVICE: this.deployArtifacts(deployId); break; case INSERVICE: this.registerInstance(deployId); break; default: // do nothing } } private void registerInstance(String deployId) { awsService.updateAndGetRequest(DeployState.SUCCESS, deployId); } private void deployArtifacts(String deployId) { DeployRequest deployRequest = awsService.updateAndGetRequest(DeployState.DEPLOYING_CONFIGS, deployId); boolean deployOk = false; if (deployRequest.withRestart()) { deployModuleService.stopContainer(deployId); } if (deployRequest.getConfigs() != null && !deployRequest.getConfigs().isEmpty()) { for (DeployConfigRequest configRequests : deployRequest.getConfigs()) { deployOk = deployConfigService.deploy(configRequests); if (!deployOk) { awsService.failBuild(deployId); return; } } } deployRequest = awsService.updateAndGetRequest(DeployState.DEPLOYING_ARTIFACTS, deployId); if (deployRequest.getArtifacts() != null && !deployRequest.getArtifacts().isEmpty()) { for (DeployArtifactRequest artifactRequest : deployRequest.getArtifacts()) { deployOk = deployArtifactService.deploy(artifactRequest); if (!deployOk) { awsService.failBuild(deployId); return; } } } deployRequest = awsService.updateAndGetRequest(DeployState.DEPLOYING_MODULES, deployId); if (deployRequest.getModules() != null && !deployRequest.getModules().isEmpty()) { for (DeployModuleRequest moduleRequest : deployRequest.getModules()) { deployOk = deployModuleService.deploy(moduleRequest); if (!deployOk) { awsService.failBuild(deployId); return; } } } awsService.updateAndGetRequest(DeployState.WAITING_FOR_REGISTER, deployId); awsService.registerInstance(deployId); } }
package de.htwberlin.liar.game; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Random; import android.content.ContentResolver; import android.content.Context; import android.util.Log; import de.htwberlin.liar.database.LiarContract.Players; import de.htwberlin.liar.model.Player; /** * This class contains the Game logic. It most important method is the {@link #next()} method, * which let the game proceed. Not that you have to register yourself as {@link Observer} * of this class to get notified of a change after calling {@link #next()}. */ public class Game extends Observable{ private Context mContext; /**Points to add per correct answered question*/ private static final int ADD_POINTS = 10; /**Points to subtract per correct answered question*/ private static final int SUBTRACT_POINTS = 5; /**Index of the current player*/ private int currentPlayer; /**The current round*/ private int currentRound; /**The current question to answer*/ private String currentQuestion; /**The current {@link Phase}*/ private Phase phase; /**List of players for this game*/ private List<Player> players; /**List of questions for current player*/ private List<String> questionSet; /** * Enum for the Game Phases. * * <table> * <tr> * <td>NEXT_QUESTION</td> * <td>ANSWER</td> * <td>GAME_END</td> * </tr> * <tr> * <td>The Game is currently searching for the next question.</td> * <td>The game waits for an answer.</td> * <td>The game ended.</td> * </tr> * </table> */ public enum Phase { NEXT_QUESTION, ANSWER, GAME_END } /** * The constructor sets up the game. This includes all class fields. * * @param players the players of this game * @param questions the questions of this game * @param maxQuestions the max questions per player */ public Game(final List<Player> players, final List<String> questions, final int maxQuestions, final Context context) { if (players.isEmpty()) { throw new IllegalArgumentException("Player list is not allowed to be empty."); } else if (questions.size() < maxQuestions){ throw new IllegalArgumentException("The max questions must be equal or less than number of given questions."); } this.currentPlayer = 0; this.players = players; this.currentRound = 0; createQuestionSet(questions, maxQuestions); this.phase = Phase.NEXT_QUESTION; this.currentQuestion = null; mContext = context; } /** * Gets the current question * * @return the current question */ public String getQuestion(){ return currentQuestion; } /** * Gets the current player * * @return the current player */ public Player getPlayer(){ return players.get(currentPlayer); } /** * Gets the current round. The current round is <code>maxQuestions - currentQuestionSet.size()</code> * and can not be higher than the max number of questions. * * @return the current round. */ public int getRound(){ return currentRound; } /** * Gets the max number of questions. * * @return max number of questions */ public int getMaxQuestions(){ return questionSet.size(); } /** * Answers a question and returns if the answer was a lie or the truth. * * @param answer * @return */ public boolean answerQuestion(boolean answer){ boolean isTrue = answer; final Player currentPlayerObj = players.get(currentPlayer); if(isTrue){ currentPlayerObj.addPoints(ADD_POINTS); } else { currentPlayerObj.subtractPoints(SUBTRACT_POINTS); } updatePlayerInDB(currentPlayerObj); phase = Phase.NEXT_QUESTION; return isTrue; } private void updatePlayerInDB(final Player player) { final ContentResolver cr = mContext.getContentResolver(); String where = Players.PLAYER_NAME +" =? AND " + Players.PLAYER_GAME_ID + "=?"; String[] selectionArgs = {players.get(currentPlayer).getName(), players.get(currentPlayer).getGameId().toString()}; int rows = cr.update(Players.CONTENT_URI, players.get(currentPlayer).toContentValues(), where, selectionArgs); Log.d("Updated rows ",":" +rows); } public void next(){ switch (phase) { case NEXT_QUESTION: nextQuestion(); break; case GAME_END: notifyChanges(); break; case ANSWER: notifyChanges(); break; default: throw new IllegalStateException("No matching Phase found."); } } /** * Calculates the next question. If <code>getRound() + 1 > questionSet.size()</code> * the next player will be selected. If there is no more next player, * <code>currentPlayer + 1 >= players.size()</code>, the game ends.<br> * This method will always notify the {@link Observer}. */ private void nextQuestion(){ if (getRound() + 1 <= questionSet.size()) { currentQuestion = findQuestion(); phase = Phase.ANSWER; } else if (currentPlayer + 1 < players.size()) { currentRound = 0; currentPlayer++; currentQuestion = findQuestion(); phase = Phase.ANSWER; } else { phase = Phase.GAME_END; } notifyChanges(); } /** * Notify the {@link Observer} with the current {@link Phase}. */ private void notifyChanges(){ setChanged(); notifyObservers(phase); } /** * First gets the next question form the question set, * <code>questionSet.get(currentRound)</code>, and than * increases the Round by one. * * @return the next question */ private String findQuestion(){ final String question = questionSet.get(currentRound); currentRound++; return question; } /** * Creates a random question set form the List of available questions. * * @param questions the questions to chose from * @param size the size of the set to create */ private void createQuestionSet(List<String> questions, int size){ this.questionSet = new ArrayList<String>(size); Random random = new Random(); questionSet.clear(); for(int i = 0; i < size; i++){ final int index = random.nextInt(questions.size()); String question = questions.get(index); questionSet.add(question); questions.remove(question); } } }
package org.cytoscape.view.vizmap.gui.internal.view; import static org.cytoscape.view.vizmap.gui.internal.util.NotificationNames.*; import static org.cytoscape.view.vizmap.gui.internal.view.util.ViewUtil.invokeOnEDT; import static org.cytoscape.view.vizmap.gui.internal.view.util.ViewUtil.invokeOnEDTAndWait; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.function.BiConsumer; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import org.cytoscape.application.CyUserLog; import org.cytoscape.application.swing.AbstractCyAction; import org.cytoscape.application.swing.CyAction; import org.cytoscape.event.DebounceTimer; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTable; import org.cytoscape.model.events.ColumnCreatedEvent; import org.cytoscape.model.events.ColumnCreatedListener; import org.cytoscape.model.events.ColumnDeletedEvent; import org.cytoscape.model.events.ColumnDeletedListener; import org.cytoscape.model.events.ColumnNameChangedEvent; import org.cytoscape.model.events.ColumnNameChangedListener; import org.cytoscape.model.events.RowsSetEvent; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.View; import org.cytoscape.view.model.VisualLexicon; import org.cytoscape.view.model.VisualProperty; import org.cytoscape.view.model.events.UpdateNetworkPresentationEvent; import org.cytoscape.view.model.events.UpdateNetworkPresentationListener; import org.cytoscape.view.presentation.property.BasicVisualLexicon; import org.cytoscape.view.presentation.property.DefaultVisualizableVisualProperty; import org.cytoscape.view.presentation.property.table.BasicTableVisualLexicon; import org.cytoscape.view.vizmap.StyleAssociation; import org.cytoscape.view.vizmap.TableVisualMappingManager; import org.cytoscape.view.vizmap.VisualMappingFunction; import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; import org.cytoscape.view.vizmap.VisualPropertyDependency; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.view.vizmap.events.VisualMappingFunctionChangedEvent; import org.cytoscape.view.vizmap.events.VisualMappingFunctionChangedListener; import org.cytoscape.view.vizmap.gui.editor.EditorManager; import org.cytoscape.view.vizmap.gui.event.LexiconStateChangedEvent; import org.cytoscape.view.vizmap.gui.event.LexiconStateChangedListener; import org.cytoscape.view.vizmap.gui.internal.ColumnSpec; import org.cytoscape.view.vizmap.gui.internal.GraphObjectType; import org.cytoscape.view.vizmap.gui.internal.VizMapperProperty; import org.cytoscape.view.vizmap.gui.internal.action.GenerateDiscreteValuesAction; import org.cytoscape.view.vizmap.gui.internal.controller.CopyContinuousMappingCommand; import org.cytoscape.view.vizmap.gui.internal.controller.RemoveVisualMappingsCommand; import org.cytoscape.view.vizmap.gui.internal.model.AttributeSetProxy; import org.cytoscape.view.vizmap.gui.internal.model.LockedValueState; import org.cytoscape.view.vizmap.gui.internal.model.LockedValuesVO; import org.cytoscape.view.vizmap.gui.internal.model.MappingFunctionFactoryProxy; import org.cytoscape.view.vizmap.gui.internal.model.PropsProxy; import org.cytoscape.view.vizmap.gui.internal.model.VizMapperProxy; import org.cytoscape.view.vizmap.gui.internal.util.NotificationNames; import org.cytoscape.view.vizmap.gui.internal.util.ServicePropertiesUtil; import org.cytoscape.view.vizmap.gui.internal.util.ServicesUtil; import org.cytoscape.view.vizmap.gui.internal.view.ColumnStylePicker.Action; import org.cytoscape.view.vizmap.gui.internal.view.VisualPropertySheetItem.MessageType; import org.cytoscape.view.vizmap.gui.internal.view.editor.mappingeditor.ContinuousMappingEditorPanel; import org.cytoscape.view.vizmap.gui.internal.view.editor.mappingeditor.EditorValueRangeTracer; import org.cytoscape.view.vizmap.gui.util.DiscreteMappingGenerator; import org.cytoscape.view.vizmap.mappings.ContinuousMapping; import org.cytoscape.view.vizmap.mappings.DiscreteMapping; import org.cytoscape.work.ServiceProperties; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.swing.DialogTaskManager; import org.cytoscape.work.undo.AbstractCyEdit; import org.cytoscape.work.undo.UndoSupport; import org.puremvc.java.multicore.interfaces.INotification; import org.puremvc.java.multicore.patterns.mediator.Mediator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"unchecked", "serial"}) public class VizMapperMediator extends Mediator implements LexiconStateChangedListener, RowsSetListener, ColumnCreatedListener, ColumnDeletedListener, ColumnNameChangedListener, UpdateNetworkPresentationListener, VisualMappingFunctionChangedListener { public static final String NAME = "VizMapperMediator"; static final List<Class<? extends CyIdentifiable>> NETWORK_SHEET_TYPES = List.of(CyNode.class, CyEdge.class, CyNetwork.class); static final List<Class<? extends CyIdentifiable>> TABLE_SHEET_TYPES = List.of(CyColumn.class); private VizMapperProxy vmProxy; private AttributeSetProxy attrProxy; private MappingFunctionFactoryProxy mappingFactoryProxy; private PropsProxy propsProxy; private boolean ignoreVisualStyleSelectedEvents; private VisualPropertySheetItem<?> curVpSheetItem; private VizMapperProperty<?, ?, ?> curVizMapperProperty; // Remember what column was selected. private ColumnSpec selectedColumn; private BiConsumer<ColumnSpec,ColumnStylePicker.Action> columnChangeListener; // MKTODO Current network renderer private String curRendererId; private final ServicesUtil servicesUtil; private final VizMapperMainPanel vizMapperMainPanel; private final VizMapPropertyBuilder vizMapPropertyBuilder; private final Map<String, GenerateDiscreteValuesAction> mappingGenerators; private final Map<TaskFactory, JMenuItem> taskFactories; private final Map<CyAction, JMenuItem> actions; /** IDs of property sheet items that were set visible/invisible by the user */ private final Map<String, Boolean> userProps; private final Map<Class<? extends CyIdentifiable>, Set<String>> defVisibleProps; private final DebounceTimer debounceTimer = new DebounceTimer(240); private static final Logger logger = LoggerFactory.getLogger(CyUserLog.NAME); public VizMapperMediator( VizMapperMainPanel vizMapperMainPanel, ServicesUtil servicesUtil, VizMapPropertyBuilder vizMapPropertyBuilder ) { super(NAME, vizMapperMainPanel); this.vizMapperMainPanel = Objects.requireNonNull(vizMapperMainPanel, "'vizMapperMainPanel' must not be null"); this.servicesUtil = Objects.requireNonNull(servicesUtil, "'servicesUtil' must not be null"); this.vizMapPropertyBuilder = Objects.requireNonNull(vizMapPropertyBuilder, "'vizMapPropertyBuilder' must not be null"); mappingGenerators = new TreeMap<>(Collator.getInstance(Locale.getDefault())::compare); taskFactories = new HashMap<>(); actions = new HashMap<>(); userProps = new HashMap<>(); defVisibleProps = new HashMap<>(); setViewComponent(vizMapperMainPanel); } @Override public final void onRegister() { vmProxy = (VizMapperProxy) getFacade().retrieveProxy(VizMapperProxy.NAME); attrProxy = (AttributeSetProxy) getFacade().retrieveProxy(AttributeSetProxy.NAME); mappingFactoryProxy = (MappingFunctionFactoryProxy) getFacade().retrieveProxy(MappingFunctionFactoryProxy.NAME); propsProxy = (PropsProxy) getFacade().retrieveProxy(PropsProxy.NAME); updateDefaultProps(); initView(); super.onRegister(); } @Override public String[] listNotificationInterests() { return new String[]{ VISUAL_STYLE_SET_CHANGED, VISUAL_STYLE_ADDED, VISUAL_STYLE_REMOVED, CURRENT_VISUAL_STYLE_CHANGED, VISUAL_STYLE_UPDATED, CURRENT_NETWORK_VIEW_CHANGED, VISUAL_STYLE_NAME_CHANGED, TABLE_ASSOCIATED_VISUAL_STYLE_UPDATED}; } @Override public void handleNotification(INotification notification) { var id = notification.getName(); var body = notification.getBody(); switch(id) { case VISUAL_STYLE_SET_CHANGED: updateVisualStyleList((SortedSet<VisualStyle>) body, true); break; case VISUAL_STYLE_ADDED: case VISUAL_STYLE_REMOVED: updateVisualStyleList(vmProxy.getVisualStyles(), false); break; case CURRENT_VISUAL_STYLE_CHANGED: invokeOnEDTAndWait(() -> { ignoreVisualStyleSelectedEvents = true; try { selectCurrentVisualStyle((VisualStyle) body); } finally { ignoreVisualStyleSelectedEvents = false; } }); invokeOnEDT(() -> { var vs = (VisualStyle) body; updateAllVisualPropertySheets(vs, false); }); break; case VISUAL_STYLE_UPDATED: if (body != null) { var style = (VisualStyle) body; VisualStyle currNetStyle = vmProxy.getCurrentNetworkVisualStyle(); if (style.equals(currNetStyle)) { updateAllVisualPropertySheets(style, false); } else { // Check if its a column visual style associated with the current network style. var tableVMM = servicesUtil.get(TableVisualMappingManager.class); Set<VisualStyle> netStyles = tableVMM.getAssociatedNetworkVisualStyles(style); if(netStyles.contains(currNetStyle)) { updateVisualPropertySheets(style, TABLE_SHEET_TYPES, false, false); } break; } invokeOnEDT(() -> vizMapperMainPanel.getStylesPanelProvider().update(style)); } break; case CURRENT_NETWORK_VIEW_CHANGED: var view = (CyNetworkView) body; var newRendererId = view != null ? view.getRendererId() : null; if (view != null && newRendererId != null && !newRendererId.equals(curRendererId)) { updateAllVisualPropertySheets(vmProxy.getNetworkVisualStyle(view), false); curRendererId = newRendererId; } else if (view == null || vmProxy.getNetworkVisualStyle(view).equals(vizMapperMainPanel.getSelectedVisualStyle())) { // Ignore it, if the selected style is not the current one, // because it should change the selection style first and then recreate all the items, anyway. updateLockedValues(view); if (body instanceof CyNetworkView) { updateMappings(CyNode.class, view.getModel().getDefaultNodeTable()); updateMappings(CyEdge.class, view.getModel().getDefaultEdgeTable()); } updateItemsStatus(); updateColumnPickerWarnings(); } break; case VISUAL_STYLE_NAME_CHANGED: invokeOnEDT(() -> { vizMapperMainPanel.getStylesBtn().update(); vizMapperMainPanel.getStylesPanelProvider().update((VisualStyle) body); }); break; case TABLE_ASSOCIATED_VISUAL_STYLE_UPDATED: var association = (StyleAssociation) body; updateColumnAssociation(association); break; } } private VisualProperty<?> getRootVP(Class<? extends CyIdentifiable> type) { if (NETWORK_SHEET_TYPES.contains(type)) return BasicVisualLexicon.NETWORK; else return BasicTableVisualLexicon.CELL; } public CyTable getCurrentMappingTable() { var tableType = getSelectedVisualPropertySheet().getModel().getTableType(); return getCurrentMappingTable(tableType); } public CyTable getCurrentMappingTable(GraphObjectType type) { var curNet = vmProxy.getCurrentNetwork(); if (type == null) { return null; } else if (type.type() == CyNode.class) { return curNet == null ? null : curNet.getDefaultNodeTable(); } else if (type.type() == CyEdge.class) { return curNet == null ? null : curNet.getDefaultEdgeTable(); } else if (type.type() == CyNetwork.class) { return curNet == null ? null : curNet.getDefaultNetworkTable(); } return null; } // MKTODO possibly get rid of this method @Override public void handleEvent(LexiconStateChangedEvent e) { // Update Network Views var curStyle = vmProxy.getCurrentNetworkVisualStyle(); var views = vmProxy.getNetworkViewsWithStyle(curStyle); for (var view : views) { // TODO This should be done by NetworkViewMediator only, if possible curStyle.apply(view); view.updateView(); } // Update VP Sheet Items invokeOnEDT(() -> updateItemsStatus()); } @Override public void handleEvent(RowsSetEvent e) { var tbl = e.getSource(); // Update bypass buttons--check selected nodes and edges of the current view var curNetView = vmProxy.getCurrentNetworkView(); if (curNetView != null && e.containsColumn(CyNetwork.SELECTED)) { var curNet = curNetView.getModel(); // We have to get all selected elements again if (tbl.equals(curNet.getDefaultEdgeTable())) updateLockedValues(vmProxy.getSelectedEdgeViews(curNetView), CyEdge.class); else if (tbl.equals(curNet.getDefaultNodeTable())) updateLockedValues(vmProxy.getSelectedNodeViews(curNetView), CyNode.class); else if (tbl.equals(curNet.getDefaultNetworkTable())) updateLockedValues(Collections.singleton((View<CyNetwork>)curNetView), CyNetwork.class); } // Also update mappings var curNet = vmProxy.getCurrentNetwork(); if (curNet != null) { var vpSheets = new ArrayList<VisualPropertySheet>(2); if (tbl.equals(curNet.getDefaultEdgeTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyEdge.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); } else if (tbl.equals(curNet.getDefaultNodeTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyNode.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); } else if (tbl.equals(curNet.getDefaultNetworkTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyNetwork.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); // Not really needed by why not. } if (!vpSheets.isEmpty()) { var columns = e.getColumns(); for (var vpSheet : vpSheets) { if (vpSheet == null) continue; // Shouldn't happen for (var item : vpSheet.getItems()) { var mapping = item.getModel().getVisualMappingFunction(); if (mapping != null) { for (var columnName : columns) { if (mapping.getMappingColumnName().equalsIgnoreCase(columnName)) { invokeOnEDT(() -> item.updateMapping()); break; } } } } } } } } @Override public void handleEvent(ColumnDeletedEvent e) { var table = e.getSource(); onColumnChangedUpdateMappings(e.getColumnName(), table); } @Override public void handleEvent(ColumnCreatedEvent e) { var table = e.getSource(); onColumnChangedUpdateMappings(e.getColumnName(), table); } @Override public void handleEvent(ColumnNameChangedEvent e) { var table = e.getSource(); onColumnChangedUpdateMappings(e.getOldColumnName(), table); onColumnChangedUpdateMappings(e.getNewColumnName(), table); } @Override public void handleEvent(UpdateNetworkPresentationEvent e) { var view = e.getSource(); if (view.equals(vmProxy.getCurrentNetworkView())) updateLockedValues(view); } @Override public void handleEvent(VisualMappingFunctionChangedEvent e) { var vm = e.getSource(); var vp = vm.getVisualProperty(); var curStyleSet = vmProxy.getCurrentVisualStyleSet(); // If the source mapping belongs to the current visual style, update the correspondent property sheet item if (curStyleSet != null) { for(VisualStyle style : curStyleSet.getAllStyles()) { if(vm.equals(style.getVisualMappingFunction(vp))) { var vpSheet = vizMapperMainPanel.getVisualPropertySheet(vp.getTargetDataType()); if (vpSheet != null) { var vpSheetItem = vpSheet.getItem(vp); if (vpSheetItem != null) { invokeOnEDT(() -> vpSheetItem.updateMapping()); } } } } } } public VisualPropertySheetItem<?> getCurrentVisualPropertySheetItem() { return curVpSheetItem; } public VisualPropertySheet getSelectedVisualPropertySheet() { return vizMapperMainPanel.getSelectedVisualPropertySheet(); } public VizMapperProperty<?, ?, ?> getCurrentVizMapperProperty() { return curVizMapperProperty; } /** * Custom listener for adding registered VizMapper CyActions to the main menu. */ public synchronized void onCyActionRegistered(CyAction action, Map<?, ?> properties) { var serviceType = ServicePropertiesUtil.getServiceType(properties); if (serviceType != null && serviceType.startsWith("vizmapUI")) { invokeOnEDT(() -> { var menuItem = createMenuItem(action, properties); if (menuItem != null) actions.put(action, menuItem); }); } } /** * Custom listener for removing unregistered VizMapper CyActions from the main and context menus. */ public synchronized void onCyActionUnregistered(CyAction action, Map<?,?> properties) { var menuItem = actions.remove(action); if (menuItem != null) { invokeOnEDT(() -> { vizMapperMainPanel.removeOption(menuItem); vizMapperMainPanel.removeContextMenuItem(menuItem); }); } } /** * Create menu items for related registered Task Factories. */ public void onTaskFactoryRegistered(TaskFactory taskFactory, Map<?,?> properties) { // First filter the service... var serviceType = ServicePropertiesUtil.getServiceType(properties); if (serviceType == null || !serviceType.toString().startsWith("vizmapUI")) return; var title = ServicePropertiesUtil.getTitle(properties); if (title == null) { logger.error("Cannot create VizMapper menu item for: " + taskFactory + "; \"" + ServiceProperties.TITLE + "\" metadata is missing from properties: " + properties); return; } // Add new menu to the pull-down var config = new HashMap<String, String>(); config.put(ServiceProperties.TITLE, title.toString()); var action = new AbstractCyAction(config, taskFactory) { @Override public void actionPerformed(ActionEvent e) { new Thread(() -> { servicesUtil.get(DialogTaskManager.class).execute(taskFactory.createTaskIterator()); }).start(); } }; invokeOnEDT(() -> { var menuItem = createMenuItem(action, properties); if (menuItem != null) taskFactories.put(taskFactory, menuItem); }); } public void onTaskFactoryUnregistered(TaskFactory taskFactory, Map<?, ?> properties) { var menuItem = taskFactories.remove(taskFactory); if (menuItem != null) { invokeOnEDT(() -> { vizMapperMainPanel.removeOption(menuItem); vizMapperMainPanel.removeContextMenuItem(menuItem); }); } } public void onMappingGeneratorRegistered(DiscreteMappingGenerator<?> generator, Map<?, ?> properties) { var serviceType = ServicePropertiesUtil.getServiceType(properties); if (serviceType == null) { logger.error("Cannot create VizMapper context menu item for: " + generator + "; \"" + ServicePropertiesUtil.SERVICE_TYPE + "\" metadata is missing from properties: " + properties); return; } // This is a menu item for Main Command Button. var title = ServicePropertiesUtil.getTitle(properties);; if (title == null) { logger.error("Cannot create VizMapper context menu item for: " + generator + "; \"" + ServiceProperties.TITLE + "\" metadata is missing from properties: " + properties); return; } // Add new menu to the pull-down var action = new GenerateDiscreteValuesAction(title.toString(), generator, servicesUtil); vizMapperMainPanel.getContextMenu().addPopupMenuListener(action); // Concatenate the data type with the title when setting the map key, so the generators // can be sorted first by data type and then by title. mappingGenerators.put(generator.getDataType().getSimpleName() + "::" + title.toString(), action); } public void onMappingGeneratorUnregistered(DiscreteMappingGenerator<?> generator, Map<?, ?> properties) { var iter = mappingGenerators.entrySet().iterator(); while (iter.hasNext()) { var entry = iter.next(); var action = entry.getValue(); if (action.getGenerator().equals(generator)) { vizMapperMainPanel.getContextMenu().removePopupMenuListener(action); iter.remove(); break; } } } private void updateDefaultProps() { defVisibleProps.clear(); defVisibleProps.put(CyNode.class, propsProxy.getDefaultVisualProperties(CyNode.class)); defVisibleProps.put(CyEdge.class, propsProxy.getDefaultVisualProperties(CyEdge.class)); defVisibleProps.put(CyNetwork.class, propsProxy.getDefaultVisualProperties(CyNetwork.class)); defVisibleProps.put(CyColumn.class, propsProxy.getDefaultVisualProperties(CyColumn.class)); } private void initView() { servicesUtil.registerAllServices(vizMapperMainPanel, new Properties()); addViewListeners(); } private void addViewListeners() { // Switching the current Visual Style var stylesBtn = vizMapperMainPanel.getStylesBtn(); stylesBtn.addPropertyChangeListener("selectedStyle", evt -> onSelectedVisualStyleChanged(evt)); columnChangeListener = this::onColumnStylePickerAction; vizMapperMainPanel.getColumnStylePnl().addColumnSelectionListener(columnChangeListener); // vizMapperMainPanel.getColumnStylePnl().getAddButton(columnChangeListener); } private void addViewListeners(VisualPropertySheet vpSheet) { for (var vpSheetItem : vpSheet.getItems()) addViewListeners(vpSheet, vpSheetItem); } private void addViewListeners(VisualPropertySheet vpSheet, VisualPropertySheetItem<?> vpSheetItem) { if (vpSheetItem.getModel().getVisualPropertyDependency() == null) { // It's a regular VisualProperty Editor... // Default value button clicked vpSheetItem.getDefaultBtn().addActionListener(evt -> openDefaultValueEditor(evt, vpSheetItem)); // Default value button right-clicked vpSheetItem.getDefaultBtn().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybeShowContextMenu(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowContextMenu(e); } private void maybeShowContextMenu(MouseEvent e) { if (e.isPopupTrigger()) { var contextMenu = new JPopupMenu(); contextMenu.add(new JMenuItem(new AbstractAction("Reset Default Value") { @Override public void actionPerformed(ActionEvent e) { vpSheetItem.getModel().resetDefaultValue(); } })); showContextMenu(contextMenu, e); } } }); // Bypass button clicked if (vpSheetItem.getModel().isLockedValueAllowed()) { // Create context menu var bypassMenu = new JPopupMenu(); final JMenuItem removeBypassMenuItem; bypassMenu.add(new JMenuItem(new AbstractAction("Set Bypass...") { @Override public void actionPerformed(ActionEvent e) { openLockedValueEditor(e, vpSheetItem); } })); bypassMenu.add(removeBypassMenuItem = new JMenuItem(new AbstractAction("Remove Bypass") { @Override public void actionPerformed(ActionEvent e) { removeLockedValue(e, vpSheetItem); } })); // Right-clicked vpSheetItem.getBypassBtn().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybeShowContextMenu(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowContextMenu(e); } private void maybeShowContextMenu(MouseEvent e) { if (vpSheetItem.getBypassBtn().isEnabled() && e.isPopupTrigger()) { var state = vpSheetItem.getModel().getLockedValueState(); removeBypassMenuItem.setEnabled(state != LockedValueState.ENABLED_NOT_SET); showContextMenu(bypassMenu, e); } } }); // Left-clicked vpSheetItem.getBypassBtn().addActionListener(evt -> { var state = vpSheetItem.getModel().getLockedValueState(); var btn = vpSheetItem.getBypassBtn(); if (state == LockedValueState.ENABLED_NOT_SET) { // There is only one option to execute, so do it now, rather than showing the popup menu openLockedValueEditor(evt, vpSheetItem); } else { bypassMenu.show(btn, 0, btn.getHeight()); bypassMenu.requestFocusInWindow(); } }); } // Right-click var cmMouseListener = new ContextMenuMouseListener(vpSheet, vpSheetItem); vpSheetItem.addMouseListener(cmMouseListener); if (vpSheetItem.getModel().isVisualMappingAllowed()) { vpSheetItem.getPropSheetPnl().getTable().addMouseListener(cmMouseListener); vpSheetItem.getRemoveMappingBtn().addActionListener(evt -> { curVpSheetItem = vpSheetItem; removeVisualMapping(vpSheetItem); }); if(vpSheetItem.isNodeColumnColor()) { vpSheetItem.getCopyNodeColorMappingBtn().addActionListener(evt -> { curVpSheetItem = vpSheetItem; copyNodeColumnColorMappingToTable(vpSheetItem); }); } vpSheetItem.getPropSheetTbl().addPropertyChangeListener("editingVizMapperProperty", evt -> { curVpSheetItem = vpSheetItem; // Save the current editor (the one the user is interacting with) curVizMapperProperty = (VizMapperProperty<?, ?, ?>) evt.getNewValue(); var mappingTypeProperty = vizMapPropertyBuilder.getMappingTypeProperty(vpSheetItem.getPropSheetPnl()); var factory = (VisualMappingFunctionFactory) mappingTypeProperty.getValue(); attrProxy.setCurrentMappingType(factory != null ? factory.getMappingFunctionType() : null); var columnProp = vizMapPropertyBuilder.getColumnProperty(vpSheetItem.getPropSheetPnl()); var columnValue = columnProp.getValue(); mappingFactoryProxy.setCurrentColumnName(columnValue != null ? columnValue.toString() : null); mappingFactoryProxy.setCurrentTargetDataType(vpSheet.getModel().getTableType()); }); } } else { // It's a Dependency Editor... vpSheetItem.getDependencyCkb().addItemListener(evt -> onDependencySelectionChanged(evt, vpSheetItem)); } // Save sheet items that were explicitly shown/hidden by the user, // so his preferences can be respected when the current style changes vpSheetItem.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { userProps.put(vpSheetItem.getModel().getId(), Boolean.TRUE); } @Override public void componentHidden(ComponentEvent e) { userProps.put(vpSheetItem.getModel().getId(), Boolean.FALSE); } }); } protected void removeVisualMapping(VisualPropertySheetItem<?> vpSheetItem) { var model = vpSheetItem.getModel(); if(model == null) return; var vm = model.getVisualMappingFunction(); if(vm == null) return; var body = new RemoveVisualMappingsCommand.Body(model.getVisualStyle(), Set.of(vm)); sendNotification(NotificationNames.REMOVE_VISUAL_MAPPINGS, body); } protected void copyNodeColumnColorMappingToTable(VisualPropertySheetItem<?> vpSheetItem) { var model = vpSheetItem.getModel(); if(model == null) return; var sourceStyle = vmProxy.getCurrentNetworkVisualStyle(); var sourceVP = BasicVisualLexicon.NODE_FILL_COLOR; var targetStyle = model.getVisualStyle(); var targetVP = BasicTableVisualLexicon.CELL_BACKGROUND_PAINT; var body = new CopyContinuousMappingCommand.Body(sourceStyle, sourceVP, targetStyle, targetVP); sendNotification(NotificationNames.COPY_CONTINUOUS_MAPPING, body); } private void updateVisualStyleList(SortedSet<VisualStyle> styles, boolean resetDefaultVisibleItems) { attrProxy.setCurrentMappingType(null); mappingFactoryProxy.setCurrentColumnName(null); debounceTimer.debounce(() -> { var vs = vmProxy.getCurrentNetworkVisualStyle(); // var table = vmProxy.getCurrentTable(); invokeOnEDT(() -> { ignoreVisualStyleSelectedEvents = true; vizMapperMainPanel.updateVisualStyles(styles, vs); selectCurrentVisualStyle(vs); ignoreVisualStyleSelectedEvents = false; updateAllVisualPropertySheets(vs, resetDefaultVisibleItems); // if (table != null) // updateTableVisualPropertySheets(table, resetDefaultVisibleItems, false); }); }); } private void selectCurrentVisualStyle(VisualStyle vs) { invokeOnEDT(() -> { var selectedVs = vizMapperMainPanel.getSelectedVisualStyle(); // Switching styles. Need to reset the range tracer ContinuousMappingEditorPanel.setTracer(new EditorValueRangeTracer(servicesUtil)); if (vs != null && !vs.equals(selectedVs)) vizMapperMainPanel.setSelectedVisualStyle(vs); }); } private void updateAllVisualPropertySheets(VisualStyle netVS, boolean resetDefaultVisibleItems) { boolean rebuild = shouldRebuildVisualPropertySheets(netVS); var tableVMM = servicesUtil.get(TableVisualMappingManager.class); var nodeColStyles = tableVMM.getAssociatedColumnVisualStyles(netVS, CyNode.class); var edgeColStyles = tableVMM.getAssociatedColumnVisualStyles(netVS, CyEdge.class); List<ColumnSpec> columns = new ArrayList<>(); for(var entry : nodeColStyles.entrySet()) { columns.add(new ColumnSpec(GraphObjectType.node(), entry.getKey())); } for(var entry : edgeColStyles.entrySet()) { columns.add(new ColumnSpec(GraphObjectType.edge(), entry.getKey())); } columns.sort(ColumnSpec.comparingName()); if(selectedColumn == null && !columns.isEmpty()) { selectedColumn = columns.get(0); } VisualStyle colVS = null; if(selectedColumn != null) { var tableType = selectedColumn.tableType().type(); colVS = tableVMM.getAssociatedColumnVisualStyle(netVS, tableType, selectedColumn.columnName()); } updateVisualPropertySheets(netVS, NETWORK_SHEET_TYPES, resetDefaultVisibleItems, rebuild); updateVisualPropertySheets(colVS, TABLE_SHEET_TYPES, resetDefaultVisibleItems, true); vizMapperMainPanel.getColumnStylePnl().removeColumnSelectionListener(columnChangeListener); vizMapperMainPanel.updateColumns(columns, selectedColumn); vizMapperMainPanel.getColumnStylePnl().addColumnSelectionListener(columnChangeListener); } private void updateColumnPickerWarnings() { vizMapperMainPanel.updateColumnPickerWarnings(); } /** * Fires when the user clicks on a column in the ColumnStylePicker at the top of the Column tab. */ private void onColumnStylePickerAction(ColumnSpec col, ColumnStylePicker.Action action) { if(col == null || action == null) return; ContinuousMappingEditorPanel.setTracer(new EditorValueRangeTracer(servicesUtil)); // MKTODO why? var netVS = vmProxy.getCurrentNetworkVisualStyle(); var tableVMM = servicesUtil.get(TableVisualMappingManager.class); var tableType = col.tableType().type(); if(action == Action.CREATE) { selectedColumn = col; VisualStyle colVS = tableVMM.getAssociatedColumnVisualStyle(netVS, tableType, col.columnName()); if(colVS == null) { var visualStyleFactory = servicesUtil.get(VisualStyleFactory.class); colVS = visualStyleFactory.createVisualStyle(col.columnName()); tableVMM.setAssociatedVisualStyle(netVS, tableType, col.columnName(), colVS); // Fires event that calls updateColumnAssociation } } else if(action == Action.DELETE) { selectedColumn = null; tableVMM.setAssociatedVisualStyle(netVS, tableType, col.columnName(), null); // Fires event that calls updateColumnAssociation } else { // SELECT selectedColumn = col; VisualStyle colVS = tableVMM.getAssociatedColumnVisualStyle(netVS, tableType, col.columnName()); updateVisualPropertySheets(colVS, TABLE_SHEET_TYPES, false, true); } } private void updateColumnAssociation(StyleAssociation association) { var netVS = association.networkVisualStyle(); if(netVS == vmProxy.getCurrentNetworkVisualStyle()) { updateAllVisualPropertySheets(netVS, false); } } private void updateVisualPropertySheets( VisualStyle vs, List<Class<? extends CyIdentifiable>> sheetTypes, boolean resetDefaultVisibleItems, boolean rebuild ) { if (vs == null) return; if (!rebuild) { // Also check if dependencies have changed var map = new HashMap<String, VisualPropertyDependency<?>>(); var dependencies = vs.getAllVisualPropertyDependencies(); for (var dep : dependencies) { var type = dep.getParentVisualProperty().getTargetDataType(); var sheet = vizMapperMainPanel.getVisualPropertySheet(type); if (sheet == null) continue; // Shouldn't happen if (sheet.getItem(dep) == null) { // There's a new dependency! rebuild = true; break; } map.put(dep.getIdString(), dep); } if (!rebuild) { var vpSheets = vizMapperMainPanel.getVisualPropertySheets(); for (var sheet : vpSheets) { for (var item : sheet.getItems()) { var dep = item.getModel().getVisualPropertyDependency(); if (dep != null && !map.containsKey(dep.getIdString())) { // This dependency has been removed from the Visual Style! rebuild = true; break; } } } } } if (rebuild) { createVisualPropertySheets(vs, sheetTypes, resetDefaultVisibleItems); } else { // Just update the current Visual Property sheets var vpSheets = vizMapperMainPanel.getVisualPropertySheets(); for (var sheet : vpSheets) { for (var item : sheet.getItems()) { // Update values var model = item.getModel(); model.update(vmProxy.getRenderingEngine(model.getLexiconType())); if (model.getVisualPropertyDependency() != null) item.update(); // Also make sure items with mappings are visible if (model.getVisualMappingFunction() != null) item.setVisible(true); } } if (resetDefaultVisibleItems) updateVisibleItems(resetDefaultVisibleItems); } } private boolean shouldRebuildVisualPropertySheets(VisualStyle vs) { var curNetSheet = vizMapperMainPanel.getVisualPropertySheet(CyNetwork.class); var curModel = curNetSheet != null ? curNetSheet.getModel() : null; var curStyle = curModel != null ? curModel.getVisualStyle() : null; var curNetView = vmProxy.getCurrentNetworkView(); var newRendererId = curNetView != null ? curNetView.getRendererId() : ""; // If a different style or renderer, rebuild all property sheets boolean rebuild = !vs.equals(curStyle) || !newRendererId.equals(curRendererId); if (curNetView != null) curRendererId = curNetView.getRendererId(); return rebuild; } public VisualLexicon getCurrentVisualLexicon(VisualProperty<?> vp) { Class<? extends CyIdentifiable> type = vp.getTargetDataType(); var re = vmProxy.getRenderingEngine(type); if(re == null) return null; return re.getVisualLexicon(); } private void createVisualPropertySheets(VisualStyle style, List<Class<? extends CyIdentifiable>> sheetTypes, boolean resetDefaultVisibleItems) { invokeOnEDT(() -> { var selVpSheet = getSelectedVisualPropertySheet(); var selectedTargetDataType = selVpSheet != null ? selVpSheet.getModel().getLexiconType() : null; for (var lexiconType : sheetTypes) { // Create Visual Property Sheet VisualPropertySheet vpSheet; Set<VisualPropertySheetItem<?>> vpSheetItems; var lexicon = vmProxy.getCurrentLexicon(lexiconType); GraphObjectType tableType; if(lexiconType == CyColumn.class) { if(selectedColumn == null) // this shouldn't happen, being defensive tableType = GraphObjectType.node(); else tableType = selectedColumn.tableType(); } else { tableType = GraphObjectType.of(lexiconType); } var model = new VisualPropertySheetModel(lexiconType, tableType, style, lexicon); vpSheet = new VisualPropertySheet(model, servicesUtil); vizMapperMainPanel.addVisualPropertySheet(vpSheet); vpSheetItems = createVisualPropertySheetItems(lexiconType, tableType, lexicon, style); vpSheet.setItems(vpSheetItems); // Add event listeners to the new components addViewListeners(vpSheet); // Add more menu items to the Properties menu if (vpSheetItems.size() > 1) { vpSheet.getVpsMenu().add(new JSeparator()); { var mi = new JMenuItem("Show Default"); mi.addActionListener(evt -> showDefaultItems(vpSheet)); vpSheet.getVpsMenu().add(mi); } { var mi = new JMenuItem("Show All"); mi.addActionListener(evt -> setVisibleItems(vpSheet, true)); vpSheet.getVpsMenu().add(mi); } { var mi = new JMenuItem("Hide All"); mi.addActionListener(evt -> setVisibleItems(vpSheet, false)); vpSheet.getVpsMenu().add(mi); } } vpSheet.getVpsMenu().add(new JSeparator()); var mi = new JMenuItem("Make Default"); mi.addActionListener(evt -> saveDefaultVisibleItems(vpSheet)); vpSheet.getVpsMenu().add(mi); } updateVisibleItems(resetDefaultVisibleItems); updateItemsStatus(); // Update panel's width int minWidth = 200; for (var vpSheet : vizMapperMainPanel.getVisualPropertySheets()) { minWidth = Math.max(minWidth, vpSheet.getMinimumSize().width); } vizMapperMainPanel.setPreferredSize( new Dimension(vizMapperMainPanel.getPropertiesPnl().getComponent().getMinimumSize().width + 20, vizMapperMainPanel.getPreferredSize().height)); // Select the same sheet that was selected before var vpSheet = vizMapperMainPanel.getVisualPropertySheet(selectedTargetDataType); vizMapperMainPanel.setSelectedVisualPropertySheet(vpSheet); }); } @SuppressWarnings("rawtypes") private Set<VisualPropertySheetItem<?>> createVisualPropertySheetItems(Class<? extends CyIdentifiable> lexiconType, GraphObjectType tableType, VisualLexicon lexicon, VisualStyle style) { var items = new HashSet<VisualPropertySheetItem<?>>(); if (lexicon == null || style == null) return items; var vpList = lexicon.getAllDescendants(getRootVP(lexiconType)); var engine = vmProxy.getRenderingEngine(lexiconType); if(engine == null) { // This is kind of hackey. // In the case where we can't get a real rendering engine, we have to use a backup "dummy" engine. // For networks we can use the engine that vizMapperMainPanel uses to create the thumbnails in the style picker popup. // For tables we have to use the "dummy" engine provided by the vmProxy. if(lexiconType == CyNode.class || lexiconType == CyEdge.class || lexiconType == CyNetwork.class) { engine = vizMapperMainPanel.getRenderingEngine(); } else { engine = vmProxy.getDummyTableRenderingEngine(); } } for (var vp : vpList) { if (vp.getTargetDataType() != lexiconType || vp instanceof DefaultVisualizableVisualProperty) continue; if (!VizMapperProxy.isSupported(lexicon, vp)) continue; // Create model var model = new VisualPropertySheetItemModel(vp, tableType, lexiconType, style, engine, lexicon); final Set values; if (vp.getTargetDataType() == CyNode.class) { var curNetView = vmProxy.getCurrentNetworkView(); var selectedNodeViews = vmProxy.getSelectedNodeViews(curNetView); values = getDistinctLockedValues(vp, selectedNodeViews); updateVpInfoLockedState(model, values, selectedNodeViews); } else if (vp.getTargetDataType() == CyEdge.class) { var curNetView = vmProxy.getCurrentNetworkView(); var selectedEdgeViews = vmProxy.getSelectedEdgeViews(curNetView); values = getDistinctLockedValues(vp, selectedEdgeViews); updateVpInfoLockedState(model, values, selectedEdgeViews); } else if (vp.getTargetDataType() == CyNetwork.class) { var curNetView = vmProxy.getCurrentNetworkView(); var selectedNetViews = curNetView != null ? Collections.singleton((View<CyNetwork>)curNetView) : Collections.EMPTY_SET; values = getDistinctLockedValues(vp, selectedNetViews); updateVpInfoLockedState(model, values, selectedNetViews); } // Create View var sheetItem = new VisualPropertySheetItem(model, vizMapPropertyBuilder, servicesUtil); items.add(sheetItem); // Add listeners to item and model: if (model.isVisualMappingAllowed()) { sheetItem.getPropSheetPnl().addPropertySheetChangeListener(evt -> { if (evt.getPropertyName().equals("value") && evt.getSource() instanceof VizMapperProperty) updateMappingStatus(sheetItem); }); } // Set the updated values to the visual style model.addPropertyChangeListener("defaultValue", evt -> { var vs = model.getVisualStyle(); vs.setDefaultValue((VisualProperty)vp, evt.getNewValue()); }); model.addPropertyChangeListener("visualMappingFunction", evt -> { var vs = model.getVisualStyle(); if (evt.getNewValue() == null && vs.getVisualMappingFunction(vp) != null) vs.removeVisualMappingFunction(vp); else if (evt.getNewValue() != null && !evt.getNewValue().equals(vs.getVisualMappingFunction(vp))) vs.addVisualMappingFunction((VisualMappingFunction<?, ?>)evt.getNewValue()); updateMappingStatus(sheetItem); }); } // Add dependencies var dependencies = style.getAllVisualPropertyDependencies(); for (var dep : dependencies) { if (dep.getParentVisualProperty().getTargetDataType() != lexiconType) continue; if (!VizMapperProxy.isSupported(lexicon, dep)) continue; var model = new VisualPropertySheetItemModel(dep, style, tableType, lexiconType, engine, lexicon); var sheetItem = new VisualPropertySheetItem(model, vizMapPropertyBuilder, servicesUtil); items.add(sheetItem); } return items; } private void updateItemsStatus() { // Children of enabled dependencies must be disabled var disabled = new HashSet<VisualProperty<?>>(); var messages = new HashMap<VisualProperty<?>, String>(); // MKTODO what about the current column style? var style = vmProxy.getCurrentNetworkVisualStyle(); var infoMsgTemplate = "<html>To enable this visual property,<br><b>%s</b> the dependency <i><b>%s</b></i></html>"; for (var dep : style.getAllVisualPropertyDependencies()) { var parent = dep.getParentVisualProperty(); var properties = dep.getVisualProperties(); if (dep.isDependencyEnabled()) { disabled.addAll(properties); for (var vp : properties) messages.put(vp, String.format(infoMsgTemplate, "uncheck", dep.getDisplayName())); } else { disabled.add(parent); messages.put(parent, String.format(infoMsgTemplate, "check", dep.getDisplayName())); } } for (var vpSheet : vizMapperMainPanel.getVisualPropertySheets()) { var vpSheetItems = vpSheet.getItems(); for (var item : vpSheetItems) { // First check if this property item must be disabled and show an INFO message String msg = null; MessageType msgType = null; if (msgType == null && item.getModel().getVisualPropertyDependency() == null) { item.setEnabled(!disabled.contains(item.getModel().getVisualProperty())); msg = messages.get(item.getModel().getVisualProperty()); msgType = item.isEnabled() ? null : MessageType.INFO; } item.setMessage(msg, msgType); // If item is enabled, check whether or not the mapping is valid for the current network updateMappingStatus(item); } } } private void updateVisibleItems(boolean reset) { if (reset) userProps.clear(); for (var vpSheet : vizMapperMainPanel.getVisualPropertySheets()) { for (var item : vpSheet.getItems()) { // Items that are set visible by the user should still be visible when the current style changes. // Items hidden by the user will not be shown again when the current style changes, // unless it has a visual mapping: var set = defVisibleProps.get(item.getModel().getTargetDataType()); var vpId = item.getModel().getId(); // Start with the default properties, // but keep the ones previously hidden by the user invisible... boolean b = set != null && set.contains(vpId) && !Boolean.FALSE.equals(userProps.get(vpId)); // ...but always show properties that have a mapping b = b || item.getModel().getVisualMappingFunction() != null; // ...or that were set visible by the user b = b || Boolean.TRUE.equals(userProps.get(vpId)); item.setVisible(b); } } } private void setVisibleItems(VisualPropertySheet vpSheet, boolean visible) { userProps.clear(); for (var item : vpSheet.getItems()) item.setVisible(visible); } private void showDefaultItems(VisualPropertySheet vpSheet) { userProps.clear(); for (var item : vpSheet.getItems()) { var set = defVisibleProps.get(item.getModel().getTargetDataType()); var vpId = item.getModel().getId(); // Start with the default properties, of course boolean b = set != null && set.contains(vpId); // ...but still show properties that have a mapping b = b || item.getModel().getVisualMappingFunction() != null; item.setVisible(b); } } private void saveDefaultVisibleItems(VisualPropertySheet vpSheet) { var idSet = new HashSet<String>(); for (var item : vpSheet.getItems()) { if (item.isVisible()) idSet.add(item.getModel().getId()); } propsProxy.setDefaultVisualProperties(vpSheet.getModel().getLexiconType(), idSet); updateDefaultProps(); } private void updateMappings(Class<? extends CyIdentifiable> targetDataType, CyTable table) { if (table != null) { var vpSheet = vizMapperMainPanel.getVisualPropertySheet(targetDataType); if (vpSheet != null) { var columns = table.getColumns(); var colTypes = new HashMap<String, Class<?>>(); for (var col : columns) colTypes.put(col.getName().toLowerCase(), col.getType()); for (var item : vpSheet.getItems()) { var mapping = item.getModel().getVisualMappingFunction(); // Passthrough mappings don't need to be updated if (mapping instanceof DiscreteMapping || mapping instanceof ContinuousMapping) { var colType = colTypes.get(mapping.getMappingColumnName().toLowerCase()); if (colType != null && mapping.getMappingColumnType().isAssignableFrom(colType)) invokeOnEDT(() -> item.updateMapping()); } } } } } private void updateMappingStatus(VisualPropertySheetItem<?> item) { if (!item.isEnabled()) return; var lexiconType = item.getModel().getLexiconType(); var tableType = item.getModel().getTableType(); if (lexiconType != CyNetwork.class) { String msg = null; MessageType msgType = null; var table = getCurrentMappingTable(tableType); if (table != null) { var columnProp = vizMapPropertyBuilder.getColumnProperty(item.getPropSheetPnl()); var colName = (columnProp != null && columnProp.getValue() != null) ? columnProp.getValue().toString() : null; if (colName != null) { var mapping = item.getModel().getVisualMappingFunction(); var mapColType = mapping != null ? mapping.getMappingColumnType() : null; var column = table.getColumn(colName); var colType = column != null ? column.getType() : null; // Ignore "List" type if (mapColType == List.class) mapColType = String.class; if (colType == List.class) colType = String.class; if (column == null || (mapColType != null && !mapColType.isAssignableFrom(colType))) { var tableName = table != null ? tableType.type().getSimpleName().replace("Cy", "") : null; msg = "<html>Visual Mapping cannot be applied to current network:<br>" + tableName + " table does not have column <b>\"" + colName + "\"</b>" + (mapColType != null ? " (" + mapColType.getSimpleName() + ")" : "") + "</html>"; msgType = MessageType.WARNING; } } } var finalMsg = msg; var finalMsgType = msgType; invokeOnEDT(() -> item.setMessage(finalMsg, finalMsgType)); } } private void updateLockedValues(CyNetworkView currentView) { if (currentView != null) { updateLockedValues(Collections.singleton((View<CyNetwork>) currentView), CyNetwork.class); updateLockedValues(vmProxy.getSelectedNodeViews(currentView), CyNode.class); updateLockedValues(vmProxy.getSelectedEdgeViews(currentView), CyEdge.class); } else { updateLockedValues(Collections.EMPTY_SET, CyNetwork.class); } } @SuppressWarnings("rawtypes") private <S extends CyIdentifiable> void updateLockedValues(Set<View<S>> selectedViews, Class<S> targetDataType) { invokeOnEDT(() -> { var vpSheets = vizMapperMainPanel.getVisualPropertySheets(); for (var sheet : vpSheets) { var vpItems = sheet.getItems(); for (var item : vpItems) { var model = item.getModel(); if (model.getTargetDataType() != targetDataType) continue; Set values = getDistinctLockedValues(model.getVisualProperty(), selectedViews); updateVpInfoLockedState(model, values, selectedViews); } } }); } private <T, S extends CyIdentifiable> void updateVpInfoLockedState(VisualPropertySheetItemModel<T> model, Set<T> lockedValues, Set<View<S>> selectedViews) { T value = null; var state = LockedValueState.DISABLED; if (lockedValues.size() == 1) { value = lockedValues.iterator().next(); state = value == null ? LockedValueState.ENABLED_NOT_SET : LockedValueState.ENABLED_UNIQUE_VALUE; } else if (lockedValues.size() > 1) { state = LockedValueState.ENABLED_MULTIPLE_VALUES; } model.setLockedValue(value); model.setLockedValueState(state); } private <T, S extends CyIdentifiable> Set<T> getDistinctLockedValues(VisualProperty<T> vp, Set<View<S>> views) { var values = new HashSet<T>(); for (var view : views) { if (view != null) { if (view.isValueLocked(vp)) values.add(view.getVisualProperty(vp)); else values.add(null); // To indicate that there is least one view without a locked value if (values.size() > 1) // For our current purposes, two values is the max we need break; } } return values; } private JMenuItem createMenuItem(CyAction action, Map<?, ?> properties) { var title = ServicePropertiesUtil.getTitle(properties); if (title == null) title = action.getName(); if (title == null) { logger.error("Cannot create VizMapper menu item for: " + action + "; \"" + ServicePropertiesUtil.TITLE + "\" metadata is missing from properties: " + properties); return null; } var menuItem = new JMenuItem(action); menuItem.setText(title); double gravity = ServicePropertiesUtil.getGravity(properties); boolean insertSeparatorBefore = ServicePropertiesUtil.getInsertSeparatorBefore(properties); boolean insertSeparatorAfter = ServicePropertiesUtil.getInsertSeparatorAfter(properties); var menuId = ServicePropertiesUtil.getString(properties, ServicePropertiesUtil.MENU_ID, ""); if (menuId.equals(ServicePropertiesUtil.CONTEXT_MENU)) vizMapperMainPanel.addContextMenuItem(menuItem, gravity, insertSeparatorBefore, insertSeparatorAfter); else if(menuId.equals(ServicePropertiesUtil.TABLE_MAIN_MENU)) vizMapperMainPanel.addTableOption(menuItem, gravity, insertSeparatorBefore, insertSeparatorAfter); else vizMapperMainPanel.addOption(menuItem, gravity, insertSeparatorBefore, insertSeparatorAfter); return menuItem; } @SuppressWarnings("rawtypes") private void openDefaultValueEditor(ActionEvent evt, VisualPropertySheetItem vpSheetItem) { var model = vpSheetItem.getModel(); VisualProperty vp = model.getVisualProperty(); var style = vpSheetItem.getModel().getVisualStyle(); Object oldValue = style.getDefaultValue(vp); Object val = null; try { var editorMgr = servicesUtil.get(EditorManager.class); val = editorMgr.showVisualPropertyValueEditor(vizMapperMainPanel, vp, oldValue); } catch (Exception ex) { logger.error("Error opening Visual Property values editor for: " + vp, ex); } Object newValue = val; if (newValue != null && !newValue.equals(oldValue)) { style.setDefaultValue(vp, newValue); // Undo support var undo = servicesUtil.get(UndoSupport.class); undo.postEdit(new AbstractCyEdit("Set Default Value") { @Override public void undo() { style.setDefaultValue(vp, oldValue); } @Override public void redo() { style.setDefaultValue(vp, newValue); } }); } } @SuppressWarnings("rawtypes") private void openLockedValueEditor(ActionEvent evt, VisualPropertySheetItem vpSheetItem) { var model = vpSheetItem.getModel(); var vp = model.getVisualProperty(); Object curValue = model.getLockedValue(); Object newValue = null; try { var editorMgr = servicesUtil.get(EditorManager.class); newValue = editorMgr.showVisualPropertyValueEditor(vizMapperMainPanel, vp, curValue); } catch (Exception ex) { // logger.error("Error opening Visual Property values editor for: " + vp, ex); } if (newValue != null && !newValue.equals(curValue)) { var vo = new LockedValuesVO((Map)Collections.singletonMap(vp, newValue)); sendNotification(NotificationNames.SET_LOCKED_VALUES, vo); } } @SuppressWarnings("rawtypes") private void removeLockedValue(ActionEvent e, VisualPropertySheetItem<?> vpSheetItem) { var visualProperty = vpSheetItem.getModel().getVisualProperty(); var vo = new LockedValuesVO((Set)Collections.singleton(visualProperty)); sendNotification(NotificationNames.REMOVE_LOCKED_VALUES, vo); } private void onSelectedVisualStyleChanged(PropertyChangeEvent e) { if (ignoreVisualStyleSelectedEvents) return; var newStyle = (VisualStyle) e.getNewValue(); var oldStyle = vmProxy.getCurrentNetworkVisualStyle(); if (!Objects.equals(newStyle, oldStyle)) { new Thread(() -> { // Update proxy vmProxy.setCurrentNetworkVisualStyle(newStyle); // Undo support var undo = servicesUtil.get(UndoSupport.class); undo.postEdit(new AbstractCyEdit("Set Current Style") { @Override public void undo() { vmProxy.setCurrentNetworkVisualStyle(oldStyle); } @Override public void redo() { vmProxy.setCurrentNetworkVisualStyle(newStyle); } }); }).start(); } } private void onDependencySelectionChanged(ItemEvent e, VisualPropertySheetItem<?> vpSheetItem) { boolean selected = e.getStateChange() == ItemEvent.SELECTED; var dep = vpSheetItem.getModel().getVisualPropertyDependency(); dep.setDependency(selected); // Update VP Sheet Items invokeOnEDT(() -> updateItemsStatus()); } private void onColumnChangedUpdateMappings(String colName, CyTable tbl) { var curNet = vmProxy.getCurrentNetwork(); if (curNet == null) return; var vpSheets = new ArrayList<VisualPropertySheet>(2); if (tbl.equals(curNet.getDefaultEdgeTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyEdge.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); } else if (tbl.equals(curNet.getDefaultNodeTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyNode.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); } else if (tbl.equals(curNet.getDefaultNetworkTable())) { vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyNetwork.class)); vpSheets.add(vizMapperMainPanel.getVisualPropertySheet(CyColumn.class)); } if (vpSheets != null && !vpSheets.isEmpty()) { for (var vpSheet : vpSheets) { // Update mapping status of this sheet's properties, if necessary if (vpSheet == null) continue; for (var item : vpSheet.getItems()) { var mapping = item.getModel().getVisualMappingFunction(); if (mapping != null && mapping.getMappingColumnName().equalsIgnoreCase(colName)) updateMappingStatus(item); } } } } private void showContextMenu(JPopupMenu contextMenu, MouseEvent e) { invokeOnEDT(() -> { var parent = (Component) e.getSource(); contextMenu.show(parent, e.getX(), e.getY()); }); } private class ContextMenuMouseListener extends MouseAdapter { private VisualPropertySheet vpSheet; private VisualPropertySheetItem<?> vpSheetItem; ContextMenuMouseListener(VisualPropertySheet vpSheet, VisualPropertySheetItem<?> vpSheetItem) { this.vpSheet = vpSheet; this.vpSheetItem = vpSheetItem; } @Override public void mousePressed(MouseEvent e) { maybeShowContextMenu(e, vpSheet, vpSheetItem); } @Override public void mouseReleased(MouseEvent e) { maybeShowContextMenu(e, vpSheet, vpSheetItem); } @SuppressWarnings("rawtypes") private void maybeShowContextMenu(MouseEvent e, VisualPropertySheet vpSheet, VisualPropertySheetItem<?> vpSheetItem) { if (!e.isPopupTrigger()) return; // Select the right-clicked sheet item, if not selected yet if (!vpSheetItem.isSelected()) vpSheet.setSelectedItems((Set) (Collections.singleton(vpSheetItem))); var contextMenu = vizMapperMainPanel.getContextMenu(); invokeOnEDT(() -> { // Network properties don't have visual mappings var mapValueGeneratorsMenu = vizMapperMainPanel.getMapValueGeneratorsSubMenu(); var targetDataType = vpSheet.getModel().getLexiconType(); mapValueGeneratorsMenu.setVisible(targetDataType != CyNetwork.class); if (mapValueGeneratorsMenu.isVisible()) { // Add all mapping generators again, to keep a consistent order mapValueGeneratorsMenu.removeAll(); Class<?> dataType = null; // will store the previous generator's data type for (var entry : mappingGenerators.entrySet()) { if (dataType != null && dataType != entry.getValue().getGenerator().getDataType()) mapValueGeneratorsMenu.add(new JSeparator()); mapValueGeneratorsMenu.add(entry.getValue()); dataType = entry.getValue().getGenerator().getDataType(); } } showContextMenu(contextMenu, e); }); } } }
package ro.isdc.wro.extensions.processor.support.sass; import java.io.PrintWriter; import java.io.StringWriter; import java.util.LinkedHashSet; import java.util.Set; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.WroRuntimeException; /** * A Sass processor using ruby gems. * * @author Dmitry Erman * @created 12 Feb 2012 * @since 1.4.4 */ public class RubySassEngine { private static final Logger LOG = LoggerFactory.getLogger(RubySassEngine.class); private static final String RUBY_GEM_REQUIRE = "rubygems"; private static final String SASS_PLUGIN_REQUIRE = "sass/plugin"; private static final String SASS_ENGINE_REQUIRE = "sass/engine"; private static final Object GLOBAL_LOCK = new Object(); private final Set<String> requires; public RubySassEngine() { System.setProperty("org.jruby.embed.compat.version", "JRuby1.9"); System.setProperty("org.jruby.embed.compilemode", "jit"); System.setProperty("org.jruby.embed.sharing.variables", "false"); requires = new LinkedHashSet<String>(); requires.add(RUBY_GEM_REQUIRE); requires.add(SASS_PLUGIN_REQUIRE); requires.add(SASS_ENGINE_REQUIRE); } /** * Adds a ruby require to the ruby script to be run by this RubySassEngine. It's safe to add the same require twice. * * @param require * The name of the require, e.g. bourbon */ public void addRequire(final String require) { if (require != null && require.trim().length() > 0) { requires.add(require.trim()); } } /** * Transforms a sass content into css using Sass ruby engine. This method is synchronized because the engine itself is * not thread-safe. * * @param content * the Sass content to process. */ public String process(final String content) { if (StringUtils.isEmpty(content)) { return StringUtils.EMPTY; } try { synchronized(GLOBAL_LOCK) { final ScriptEngine rubyEngine = new ScriptEngineManager().getEngineByName("jruby"); return rubyEngine.eval(buildUpdateScript(content)).toString(); } } catch (final ScriptException e) { throw new WroRuntimeException(e.getMessage(), e); } } private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append(":syntax => :scss"); for (final String require : requires) { script.println(" require '" + require + "' "); } final int BACKSLASH = 0x5c; for (int i = 0; i < content.length(); i++) { final int code = content.codePointAt(i); if (code < 0x80) { // We leave only ASCII unchanged. if (code == BACKSLASH) { // escape backslash cb.append("\\"); } cb.append(content.charAt(i)); } else { // Non-ASCII String may cause invalid multibyte char (US-ASCII) error with Ruby 1.9 // because Ruby 1.9 expects you to use ASCII characters in your source code. // Instead we use Unicode code point representation which is usable with // Ruby 1.9 and later. Inspired from cb.append(String.format("\\u%04x", code)); } } final String scriptAsString = String.format("result = Sass::Engine.new(\"%s\", {%s}).render", cb.toString().replace("\"", "\\\"").replace("#", "\\#"), // escape ", # sb.toString()); LOG.debug("scriptAsString: {}", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); } }
package com.airbnb.android.airmapview; /** * AirMapView map that uses the web based Mapbox implementation. */ public class MapboxWebMapViewBuilder implements AirMapViewBuilder<WebViewMapFragment, AirMapType> { private AirMapType options; private final String accessToken; private final String mapId; /** * Constructor * * @param accessToken Mapbox Access Token * @param mapId Mapbox Map Id */ public MapboxWebMapViewBuilder(String accessToken, String mapId) { super(); this.accessToken = accessToken; this.mapId = mapId; } @Override public AirMapViewBuilder<WebViewMapFragment, AirMapType> withOptions(AirMapType options) { this.options = options; return this; } /** * Build the map fragment with the requested options * * @return The {@link WebViewMapFragment} map fragment. */ @Override public WebViewMapFragment build() { if (options == null) { options = new MapboxWebMapType(accessToken, mapId); } if (options instanceof MapboxWebMapType) { return MapboxWebViewMapFragment.newInstance(options); } throw new IllegalStateException("Unable to build MapboxWebMapViewFragment." + " options == '" + options + "'"); } }
package org.libreplan.web.planner; import static org.libreplan.business.workingday.EffortDuration.hours; import static org.libreplan.business.workingday.EffortDuration.min; import static org.libreplan.business.workingday.EffortDuration.seconds; import static org.libreplan.business.workingday.EffortDuration.zero; import static org.libreplan.web.I18nHelper._; import static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.biggerOrEqualThan; import static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.equalTo; import static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.lessOrEqualThan; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang.math.Fraction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.Days; import org.joda.time.Duration; import org.joda.time.LocalDate; import org.joda.time.Seconds; import org.libreplan.business.calendars.entities.BaseCalendar; import org.libreplan.business.common.IAdHocTransactionService; import org.libreplan.business.common.IOnTransaction; import org.libreplan.business.common.daos.IConfigurationDAO; import org.libreplan.business.common.entities.ProgressType; import org.libreplan.business.labels.entities.Label; import org.libreplan.business.orders.daos.IOrderElementDAO; import org.libreplan.business.orders.entities.Order; import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.orders.entities.OrderStatusEnum; import org.libreplan.business.planner.daos.IResourceAllocationDAO; import org.libreplan.business.planner.daos.ITaskElementDAO; import org.libreplan.business.planner.entities.Dependency; import org.libreplan.business.planner.entities.Dependency.Type; import org.libreplan.business.planner.entities.GenericResourceAllocation; import org.libreplan.business.planner.entities.ITaskPositionConstrained; import org.libreplan.business.planner.entities.PositionConstraintType; import org.libreplan.business.planner.entities.ResourceAllocation; import org.libreplan.business.planner.entities.ResourceAllocation.Direction; import org.libreplan.business.planner.entities.SpecificResourceAllocation; import org.libreplan.business.planner.entities.Task; import org.libreplan.business.planner.entities.TaskElement; import org.libreplan.business.planner.entities.TaskElement.IDatesHandler; import org.libreplan.business.planner.entities.TaskGroup; import org.libreplan.business.planner.entities.TaskPositionConstraint; import org.libreplan.business.resources.daos.ICriterionDAO; import org.libreplan.business.resources.daos.IResourcesSearcher; import org.libreplan.business.resources.entities.Criterion; import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.scenarios.entities.Scenario; import org.libreplan.business.workingday.EffortDuration; import org.libreplan.business.workingday.EffortDuration.IEffortFrom; import org.libreplan.business.workingday.IntraDayDate; import org.libreplan.business.workingday.IntraDayDate.PartialDay; import org.libreplan.web.planner.order.PlanningStateCreator.PlanningState; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.zkoss.ganttz.IDatesMapper; import org.zkoss.ganttz.adapters.DomainDependency; import org.zkoss.ganttz.adapters.IAdapterToTaskFundamentalProperties; import org.zkoss.ganttz.data.DependencyType; import org.zkoss.ganttz.data.GanttDate; import org.zkoss.ganttz.data.GanttDate.Cases; import org.zkoss.ganttz.data.GanttDate.CustomDate; import org.zkoss.ganttz.data.GanttDate.LocalDateBased; import org.zkoss.ganttz.data.ITaskFundamentalProperties; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.util.ReentranceGuard; import org.zkoss.ganttz.util.ReentranceGuard.IReentranceCases; @Component @Scope(BeanDefinition.SCOPE_SINGLETON) public class TaskElementAdapter { private static final Log LOG = LogFactory.getLog(TaskElementAdapter.class); public static List<Constraint<GanttDate>> getStartConstraintsFor( TaskElement taskElement, LocalDate orderInitDate) { if (taskElement instanceof ITaskPositionConstrained) { ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement; TaskPositionConstraint startConstraint = task .getPositionConstraint(); final PositionConstraintType constraintType = startConstraint .getConstraintType(); switch (constraintType) { case AS_SOON_AS_POSSIBLE: if (orderInitDate != null) { return Collections .singletonList(biggerOrEqualThan(toGantt(orderInitDate))); } return Collections.emptyList(); case START_IN_FIXED_DATE: return Collections .singletonList(equalTo(toGantt(startConstraint .getConstraintDate()))); case START_NOT_EARLIER_THAN: return Collections .singletonList(biggerOrEqualThan(toGantt(startConstraint .getConstraintDate()))); } } return Collections.emptyList(); } public static List<Constraint<GanttDate>> getEndConstraintsFor( TaskElement taskElement, LocalDate deadline) { if (taskElement instanceof ITaskPositionConstrained) { ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement; TaskPositionConstraint endConstraint = task.getPositionConstraint(); PositionConstraintType type = endConstraint.getConstraintType(); switch (type) { case AS_LATE_AS_POSSIBLE: if (deadline != null) { return Collections .singletonList(lessOrEqualThan(toGantt(deadline))); } case FINISH_NOT_LATER_THAN: GanttDate date = toGantt(endConstraint.getConstraintDate()); return Collections.singletonList(lessOrEqualThan(date)); } } return Collections.emptyList(); } public static GanttDate toGantt(IntraDayDate date) { return toGantt(date, null); } public static GanttDate toGantt(IntraDayDate date, EffortDuration dayCapacity) { if (date == null) { return null; } if (dayCapacity == null) { // a sensible default dayCapacity = EffortDuration.hours(8); } return new GanttDateAdapter(date, dayCapacity); } public static GanttDate toGantt(LocalDate date) { if (date == null) { return null; } return GanttDate.createFrom(date); } public static IntraDayDate toIntraDay(GanttDate date) { if (date == null) { return null; } return date.byCases(new Cases<GanttDateAdapter, IntraDayDate>( GanttDateAdapter.class) { @Override public IntraDayDate on(LocalDateBased localDate) { return IntraDayDate.startOfDay(localDate.getLocalDate()); } @Override protected IntraDayDate onCustom(GanttDateAdapter customType) { return customType.date; } }); } public IAdapterToTaskFundamentalProperties<TaskElement> createForCompany( Scenario currentScenario) { Adapter result = new Adapter(); result.useScenario(currentScenario); result.setPreventCalculateResourcesText(true); return result; } public IAdapterToTaskFundamentalProperties<TaskElement> createForOrder( Scenario currentScenario, Order order, PlanningState planningState) { Adapter result = new Adapter(planningState); result.useScenario(currentScenario); result.setInitDate(asLocalDate(order.getInitDate())); result.setDeadline(asLocalDate(order.getDeadline())); return result; } private LocalDate asLocalDate(Date date) { return date != null ? LocalDate.fromDateFields(date) : null; } @Autowired private IAdHocTransactionService transactionService; private final ReentranceGuard reentranceGuard = new ReentranceGuard(); @Autowired private IOrderElementDAO orderElementDAO; @Autowired private ITaskElementDAO taskDAO; @Autowired private ICriterionDAO criterionDAO; @Autowired private IResourceAllocationDAO resourceAllocationDAO; @Autowired private IResourcesSearcher searcher; @Autowired private IConfigurationDAO configurationDAO; static class GanttDateAdapter extends CustomDate { private static final int DAY_MILLISECONDS = (int) Days.days(1) .toStandardDuration().getMillis(); private final IntraDayDate date; private final Duration workingDayDuration; GanttDateAdapter(IntraDayDate date, EffortDuration capacityForDay) { this.date = date; this.workingDayDuration = toMilliseconds(capacityForDay); } protected int compareToCustom(CustomDate customType) { if (customType instanceof GanttDateAdapter) { GanttDateAdapter other = (GanttDateAdapter) customType; return this.date.compareTo(other.date); } throw new RuntimeException("incompatible type: " + customType); } protected int compareToLocalDate(LocalDate localDate) { return this.date.compareTo(localDate); } public IntraDayDate getDate() { return date; } @Override public Date toDayRoundedDate() { return date.toDateTimeAtStartOfDay().toDate(); } @Override public LocalDate toLocalDate() { return date.getDate(); } @Override public LocalDate asExclusiveEnd() { return date.asExclusiveEnd(); } @Override protected boolean isEqualsToCustom(CustomDate customType) { if (customType instanceof GanttDateAdapter) { GanttDateAdapter other = (GanttDateAdapter) customType; return this.date.equals(other.date); } return false; } @Override public int hashCode() { return date.hashCode(); } @Override public int toPixels(IDatesMapper datesMapper) { int pixesUntilDate = datesMapper.toPixels(this.date.getDate()); EffortDuration effortDuration = date.getEffortDuration(); Duration durationInDay = calculateDurationInDayFor(effortDuration); int pixelsInsideDay = datesMapper.toPixels(durationInDay); return pixesUntilDate + pixelsInsideDay; } private Duration calculateDurationInDayFor(EffortDuration effortDuration) { if (workingDayDuration.getStandardSeconds() == 0) { return Duration.ZERO; } Fraction fraction = fractionOfWorkingDayFor(effortDuration); try { return new Duration(fraction.multiplyBy( Fraction.getFraction(DAY_MILLISECONDS, 1)).intValue()); } catch (ArithmeticException e) { // if fraction overflows use floating point arithmetic return new Duration( (int) (fraction.doubleValue() * DAY_MILLISECONDS)); } } @SuppressWarnings("unchecked") private Fraction fractionOfWorkingDayFor(EffortDuration effortDuration) { Duration durationInDay = toMilliseconds(effortDuration); // cast to int is safe because there are not enough seconds in // day // to overflow Fraction fraction = Fraction.getFraction( (int) durationInDay.getStandardSeconds(), (int) workingDayDuration.getStandardSeconds()); return (Fraction) Collections.min(Arrays.asList(fraction, Fraction.ONE)); } private static Duration toMilliseconds(EffortDuration duration) { return Seconds.seconds(duration.getSeconds()).toStandardDuration(); } } public class Adapter implements IAdapterToTaskFundamentalProperties<TaskElement> { private Scenario scenario; private LocalDate initDate; private LocalDate deadline; private boolean preventCalculateResourcesText = false; private final PlanningState planningState; private void useScenario(Scenario scenario) { this.scenario = scenario; } private void setInitDate(LocalDate initDate) { this.initDate = initDate; } private void setDeadline(LocalDate deadline) { this.deadline = deadline; } public boolean isPreventCalculateResourcesText() { return preventCalculateResourcesText; } public void setPreventCalculateResourcesText( boolean preventCalculateResourcesText) { this.preventCalculateResourcesText = preventCalculateResourcesText; } public Adapter() { this(null); } public Adapter(PlanningState planningState) { this.planningState = planningState; } private class TaskElementWrapper implements ITaskFundamentalProperties { private final TaskElement taskElement; private final Scenario currentScenario; protected TaskElementWrapper(Scenario currentScenario, TaskElement taskElement) { Validate.notNull(currentScenario); this.currentScenario = currentScenario; this.taskElement = taskElement; } private final IUpdatablePosition position = new IUpdatablePosition() { @Override public void setEndDate(GanttDate endDate) { stepsBeforePossibleReallocation(); getDatesHandler(taskElement).moveEndTo(toIntraDay(endDate)); } @Override public void setBeginDate(final GanttDate beginDate) { stepsBeforePossibleReallocation(); getDatesHandler(taskElement).moveTo(toIntraDay(beginDate)); } @Override public void resizeTo(final GanttDate endDate) { stepsBeforePossibleReallocation(); updateTaskPositionConstraint(endDate); getDatesHandler(taskElement).resizeTo(toIntraDay(endDate)); } private void stepsBeforePossibleReallocation() { taskDAO.reattach(taskElement); } @Override public void moveTo(GanttDate newStart) { if (taskElement instanceof ITaskPositionConstrained) { ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement; if (task.getPositionConstraint() .isConstraintAppliedToStart()) { setBeginDate(newStart); task.explicityMoved(toIntraDay(newStart)); } else { GanttDate newEnd = inferEndFrom(newStart); setEndDate(newEnd); task.explicityMoved(toIntraDay(newEnd)); } } } }; @Override public void setName(String name) { taskElement.setName(name); } @Override public void setNotes(String notes) { taskElement.setNotes(notes); } @Override public String getName() { return taskElement.getName(); } @Override public String getNotes() { return taskElement.getNotes(); } @Override public GanttDate getBeginDate() { IntraDayDate start = taskElement.getIntraDayStartDate(); return toGantt(start); } private GanttDate toGantt(IntraDayDate date) { BaseCalendar calendar = taskElement.getCalendar(); if (calendar == null) { return TaskElementAdapter.toGantt(date); } return TaskElementAdapter.toGantt(date, calendar .getCapacityOn(PartialDay.wholeDay(date.getDate()))); } @Override public void doPositionModifications( final IModifications modifications) { reentranceGuard.entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { transactionService.runOnReadOnlyTransaction(asTransaction(modifications)); } IOnTransaction<Void> asTransaction( final IModifications modifications) { return new IOnTransaction<Void>() { @Override public Void execute() { if (planningState != null) { planningState .reassociateResourcesWithSession(); } modifications.doIt(position); return null; } }; } @Override public void ifAlreadyInside() { modifications.doIt(position); } }); } @Override public GanttDate getEndDate() { return toGantt(taskElement.getIntraDayEndDate()); } IDatesHandler getDatesHandler(TaskElement taskElement) { return taskElement.getDatesHandler(currentScenario, searcher); } private void updateTaskPositionConstraint(GanttDate endDate) { if (taskElement instanceof ITaskPositionConstrained) { ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement; PositionConstraintType constraintType = task .getPositionConstraint().getConstraintType(); if (constraintType .compareTo(PositionConstraintType.FINISH_NOT_LATER_THAN) == 0 || constraintType .compareTo(PositionConstraintType.AS_LATE_AS_POSSIBLE) == 0) { task.explicityMoved(toIntraDay(endDate)); } } } @Override public GanttDate getHoursAdvanceEndDate() { OrderElement orderElement = taskElement.getOrderElement(); EffortDuration assignedEffort = EffortDuration.zero(); if (orderElement.getSumChargedEffort() != null) { assignedEffort = orderElement.getSumChargedEffort() .getTotalChargedEffort(); } GanttDate result = null; if (!(taskElement instanceof TaskGroup)) { result = calculateLimitDateByHours(assignedEffort .toHoursAsDecimalWithScale(2).intValue()); } if (result == null) { EffortDuration effort = taskElement.getSumOfAssignedEffort(); if (effort.isZero()) { effort = EffortDuration.hours(orderElement.getWorkHours()); if (effort.isZero()) { return getBeginDate(); } } BigDecimal percentage = new BigDecimal(assignedEffort .divivedBy(effort).doubleValue()).setScale(2, RoundingMode.HALF_UP); result = calculateLimitDateByPercentage(percentage); } return result; } @Override public BigDecimal getHoursAdvancePercentage() { OrderElement orderElement = taskElement.getOrderElement(); if (orderElement == null) { return BigDecimal.ZERO; } EffortDuration totalChargedEffort = orderElement .getSumChargedEffort() != null ? orderElement .getSumChargedEffort().getTotalChargedEffort() : EffortDuration.zero(); EffortDuration estimatedEffort = taskElement.getSumOfAssignedEffort(); if(estimatedEffort.isZero()) { estimatedEffort = EffortDuration.hours(orderElement.getWorkHours()); if(estimatedEffort.isZero()) { return BigDecimal.ZERO; } } return new BigDecimal(totalChargedEffort.divivedBy( estimatedEffort).doubleValue()).setScale(2, RoundingMode.HALF_UP); } @Override public GanttDate getAdvanceEndDate(String progressType) { return getAdvanceEndDate(ProgressType.asEnum(progressType)); } private GanttDate getAdvanceEndDate(ProgressType progressType) { BigDecimal advancePercentage = BigDecimal.ZERO; if (taskElement.getOrderElement() != null) { advancePercentage = taskElement .getAdvancePercentage(progressType); } return getAdvanceEndDate(advancePercentage); } @Override public GanttDate getAdvanceEndDate() { return getAdvanceEndDate(getAdvancePercentage()); } private boolean isTaskRoot(TaskElement taskElement) { return taskElement instanceof TaskGroup && taskElement.getParent() == null; } private ProgressType getProgressTypeFromConfiguration() { return transactionService .runOnReadOnlyTransaction(new IOnTransaction<ProgressType>() { @Override public ProgressType execute() { return configurationDAO.getConfiguration() .getProgressType(); } }); } private GanttDate getAdvanceEndDate(BigDecimal advancePercentage) { if (advancePercentage.compareTo(BigDecimal.ONE) == 0) { return getEndDate(); } BigDecimal hours = BigDecimal.ZERO; if (taskElement instanceof TaskGroup) { //progess calculation for TaskGroups is done with //this method, which is much lighter return calculateLimitDateByPercentage(advancePercentage); } if (taskElement.getOrderElement() != null) { hours = taskElement.getSumOfAssignedEffort() .toHoursAsDecimalWithScale(2); } // Calculate date according to advanceHours or advancePercentage final Integer advanceHours = advancePercentage.multiply( hours).intValue(); GanttDate result = calculateLimitDateByHours(advanceHours); if (result == null) { result = calculateLimitDateByPercentage(advancePercentage); } return result; } private GanttDate calculateLimitDateByPercentage(BigDecimal advancePercentage) { BaseCalendar calendar = taskElement.getCalendar(); if (advancePercentage.compareTo(BigDecimal.ZERO) == 0 || calendar == null) { return getBeginDate(); } IntraDayDate start = taskElement.getIntraDayStartDate(); IntraDayDate end = taskElement.getIntraDayEndDate(); int daysBetween = start.numberOfDaysUntil(end); if (daysBetween == 0) { return calculateLimitDateWhenDaysBetweenAreZero(advancePercentage); } BigDecimal daysAdvance = advancePercentage .multiply(new BigDecimal(daysBetween)); int days = daysAdvance.intValue(); LocalDate advanceDate = taskElement.getStartAsLocalDate() .plusDays(days); EffortDuration capacity = calendar.getCapacityOn(PartialDay .wholeDay(advanceDate)); int seconds = daysAdvance.subtract(new BigDecimal(days)) .multiply(new BigDecimal(capacity.getSeconds())) .intValue(); return toGantt(IntraDayDate.create(advanceDate, EffortDuration.seconds(seconds))); } private GanttDate calculateLimitDateWhenDaysBetweenAreZero( BigDecimal advancePercentage) { IntraDayDate start = taskElement.getIntraDayStartDate(); IntraDayDate end = taskElement.getIntraDayEndDate(); final BaseCalendar calendar = taskElement.getCalendar(); Iterable<PartialDay> daysUntil = start.daysUntil(end); EffortDuration total = EffortDuration.sum(daysUntil, new IEffortFrom<PartialDay>() { @Override public EffortDuration from(PartialDay each) { return calendar.getCapacityOn(each); } }); BigDecimal totalAsSeconds = new BigDecimal(total.getSeconds()); EffortDuration advanceLeft = seconds(advancePercentage .multiply(totalAsSeconds).intValue()); for (PartialDay each : daysUntil) { if (advanceLeft.compareTo(calendar.getCapacityOn(each)) <= 0) { LocalDate dayDate = each.getStart().getDate(); if (dayDate.equals(start.getDate())) { return toGantt(IntraDayDate .create(dayDate, advanceLeft.plus(start .getEffortDuration()))); } return toGantt(IntraDayDate .create(dayDate, advanceLeft)); } advanceLeft = advanceLeft.minus(calendar .getCapacityOn(each)); } return toGantt(end); } private GanttDate calculateLimitDateByHours(Integer hours) { if (hours == null || hours == 0) { return null; } EffortDuration hoursLeft = hours(hours); IntraDayDate result = null; EffortDuration effortLastDayNotZero = zero(); Map<LocalDate, EffortDuration> daysMap = taskElement .getDurationsAssignedByDay(); if (daysMap.isEmpty()) { return null; } for (Entry<LocalDate, EffortDuration> entry : daysMap .entrySet()) { if (!entry.getValue().isZero()) { effortLastDayNotZero = entry.getValue(); } EffortDuration decrement = min(entry.getValue(), hoursLeft); hoursLeft = hoursLeft.minus(decrement); if (hoursLeft.isZero()) { result = IntraDayDate.create(entry.getKey(), decrement); break; } else { result = IntraDayDate.startOfDay(entry.getKey() .plusDays(1)); } } if (!hoursLeft.isZero() && effortLastDayNotZero.isZero()) { LOG.warn("limit not reached and no day with effort not zero"); } if (!hoursLeft.isZero() && !effortLastDayNotZero.isZero()) { while (!hoursLeft.isZero()) { hoursLeft = hoursLeft.minus(min(effortLastDayNotZero, hoursLeft)); result = result.nextDayAtStart(); } } if (result == null) { return null; } return toGantt(result); } @Override public String getTooltipText() { if (taskElement.isMilestone() || taskElement.getOrderElement() == null) { return ""; } return transactionService .runOnReadOnlyTransaction(new IOnTransaction<String>() { @Override public String execute() { orderElementDAO.reattach(taskElement .getOrderElement()); return buildTooltipText(); } }); } @Override public String getLabelsText() { if (taskElement.isMilestone() || taskElement.getOrderElement() == null) { return ""; } return transactionService .runOnReadOnlyTransaction(new IOnTransaction<String>() { @Override public String execute() { orderElementDAO.reattach(taskElement .getOrderElement()); return buildLabelsText(); } }); } @Override public String getResourcesText() { if (isPreventCalculateResourcesText() || taskElement.getOrderElement() == null) { return ""; } try { return transactionService .runOnAnotherReadOnlyTransaction(new IOnTransaction<String>() { @Override public String execute() { orderElementDAO.reattach(taskElement .getOrderElement()); return buildResourcesText(); } }); } catch (Exception e) { LOG.error("error calculating resources text", e); return ""; } } private Set<Label> getLabelsFromElementAndPredecesors( OrderElement order) { if (order != null) { if (order.getParent() == null) { return order.getLabels(); } else { HashSet<Label> labels = new HashSet<Label>( order.getLabels()); labels.addAll(getLabelsFromElementAndPredecesors(order .getParent())); return labels; } } return new HashSet<Label>(); } private String buildLabelsText() { List<String> result = new ArrayList<String>(); if (taskElement.getOrderElement() != null) { Set<Label> labels = getLabelsFromElementAndPredecesors(taskElement .getOrderElement()); for (Label label : labels) { String representation = label.getName(); if (!result.contains(representation)) { result.add(representation); } } } Collections.sort(result); return StringUtils.join(result, ", "); } private String buildResourcesText() { List<String> result = new ArrayList<String>(); for (ResourceAllocation<?> each : taskElement .getSatisfiedResourceAllocations()) { if (each instanceof SpecificResourceAllocation) { for (Resource r : each.getAssociatedResources()) { String representation = r.getName(); if (!result.contains(representation)) { result.add(representation); } } } else { String representation = extractRepresentationForGeneric((GenericResourceAllocation) each); if (!result.contains(representation)) { result.add(representation); } } } Collections.sort(result); return StringUtils.join(result, ", "); } private String extractRepresentationForGeneric( GenericResourceAllocation generic) { if (!generic.isNewObject()) { resourceAllocationDAO.reattach(generic); } Set<Criterion> criterions = generic.getCriterions(); List<String> forCriterionRepresentations = new ArrayList<String>(); if (!criterions.isEmpty()) { for (Criterion c : criterions) { criterionDAO.reattachUnmodifiedEntity(c); forCriterionRepresentations.add(c.getName()); } } else { forCriterionRepresentations.add((_("All workers"))); } return "[" + StringUtils.join(forCriterionRepresentations, ", ") + "]"; } @Override public String updateTooltipText() { return buildTooltipText(); } @Override public String updateTooltipText(String progressType) { return buildTooltipText(ProgressType.asEnum(progressType)); } @Override public BigDecimal getAdvancePercentage() { if (taskElement != null) { BigDecimal advancePercentage; if (isTaskRoot(taskElement)) { ProgressType progressType = getProgressTypeFromConfiguration(); advancePercentage = taskElement .getAdvancePercentage(progressType); } else { advancePercentage = taskElement.getAdvancePercentage(); } return advancePercentage; } return new BigDecimal(0); } private String buildTooltipText() { return buildTooltipText(asPercentage(getAdvancePercentage())); } private BigDecimal asPercentage(BigDecimal value) { return value.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.DOWN); } private String buildTooltipText(BigDecimal progressPercentage) { StringBuilder result = new StringBuilder(); result.append(_("Name: {0}", getName()) + "<br/>"); result.append(_("Progress") + ": ").append(progressPercentage) .append("% , "); result.append(_("Hours invested") + ": ") .append(getHoursAdvancePercentage().multiply( new BigDecimal(100))).append("% <br/>"); if (taskElement.getOrderElement() instanceof Order) { result.append(_("State") + ": ").append(getOrderState()); } String labels = buildLabelsText(); if (!labels.equals("")) { result.append("<div class='tooltip-labels'>" + _("Labels") + ": " + labels + "</div>"); } return result.toString(); } private String buildTooltipText(ProgressType progressType) { return buildTooltipText(asPercentage(taskElement .getAdvancePercentage(progressType))); } private String getOrderState() { String cssClass; OrderStatusEnum state = taskElement.getOrderElement() .getOrder().getState(); if (Arrays.asList(OrderStatusEnum.ACCEPTED, OrderStatusEnum.OFFERED, OrderStatusEnum.STARTED, OrderStatusEnum.SUBCONTRACTED_PENDING_ORDER).contains( state)) { if (taskElement.getAssignedStatus() == "assigned") { cssClass = "order-open-assigned"; } else { cssClass = "order-open-unassigned"; } } else { cssClass = "order-closed"; } return "<font class='" + cssClass + "'>" + state.toString() + "</font>"; } @Override public List<Constraint<GanttDate>> getStartConstraints() { return getStartConstraintsFor(this.taskElement, initDate); } @Override public List<Constraint<GanttDate>> getEndConstraints() { return getEndConstraintsFor(this.taskElement, deadline); } @Override public List<Constraint<GanttDate>> getCurrentLengthConstraint() { if (taskElement instanceof Task) { Task task = (Task) taskElement; if (task.getAllocationDirection() == Direction.FORWARD) { return Collections .singletonList(biggerOrEqualThan(getEndDate())); } } return Collections.emptyList(); } private GanttDate inferEndFrom(GanttDate newStart) { if (taskElement instanceof Task) { Task task = (Task) taskElement; return toGantt(task .calculateEndKeepingLength(toIntraDay(newStart))); } return newStart; } @Override public Date getDeadline() { LocalDate deadline = taskElement.getDeadline(); if (deadline == null) { return null; } return deadline.toDateTimeAtStartOfDay().toDate(); } @Override public void setDeadline(Date date) { if (date != null) { taskElement.setDeadline(LocalDate.fromDateFields(date)); } else { taskElement.setDeadline(null); } } @Override public GanttDate getConsolidatedline() { if (!taskElement.isLeaf() || !taskElement.hasConsolidations()) { return null; } LocalDate consolidatedline = ((Task) taskElement) .getFirstDayNotConsolidated().getDate(); return TaskElementAdapter.toGantt(consolidatedline); } @Override public boolean isSubcontracted() { return taskElement.isSubcontracted(); } @Override public boolean isLimiting() { return taskElement.isLimiting(); } @Override public boolean isLimitingAndHasDayAssignments() { return taskElement.isLimitingAndHasDayAssignments(); } public boolean hasConsolidations() { return taskElement.hasConsolidations(); } @Override public boolean canBeExplicitlyResized() { return taskElement.canBeExplicitlyResized(); } @Override public String getAssignedStatus() { return taskElement.getAssignedStatus(); } @Override public boolean isFixed() { return taskElement.isLimitingAndHasDayAssignments() || taskElement.hasConsolidations(); } @Override public boolean isManualAnyAllocation() { return taskElement.isTask() && ((Task) taskElement).isManualAnyAllocation(); } } @Override public ITaskFundamentalProperties adapt(final TaskElement taskElement) { return new TaskElementWrapper(scenario, taskElement); } @Override public List<DomainDependency<TaskElement>> getIncomingDependencies( TaskElement taskElement) { return toDomainDependencies(taskElement .getDependenciesWithThisDestination()); } @Override public List<DomainDependency<TaskElement>> getOutcomingDependencies( TaskElement taskElement) { return toDomainDependencies(taskElement .getDependenciesWithThisOrigin()); } private List<DomainDependency<TaskElement>> toDomainDependencies( Collection<? extends Dependency> dependencies) { List<DomainDependency<TaskElement>> result = new ArrayList<DomainDependency<TaskElement>>(); for (Dependency dependency : dependencies) { result.add(DomainDependency.createDependency( dependency.getOrigin(), dependency.getDestination(), toGanntType(dependency.getType()))); } return result; } private DependencyType toGanntType(Type type) { switch (type) { case END_START: return DependencyType.END_START; case START_END: return DependencyType.START_END; case START_START: return DependencyType.START_START; case END_END: return DependencyType.END_END; default: throw new RuntimeException(_("{0} not supported yet", type)); } } private Type toDomainType(DependencyType type) { switch (type) { case END_START: return Type.END_START; case START_END: return Type.START_END; case START_START: return Type.START_START; case END_END: return Type.END_END; default: throw new RuntimeException(_("{0} not supported yet", type)); } } @Override public void addDependency(DomainDependency<TaskElement> dependency) { TaskElement source = dependency.getSource(); TaskElement destination = dependency.getDestination(); Type domainType = toDomainType(dependency.getType()); Dependency.create(source, destination, domainType); } @Override public boolean canAddDependency(DomainDependency<TaskElement> dependency) { return true; } @Override public void removeDependency(DomainDependency<TaskElement> dependency) { TaskElement source = dependency.getSource(); Type type = toDomainType(dependency.getType()); source.removeDependencyWithDestination(dependency.getDestination(), type); } @Override public void doRemovalOf(TaskElement taskElement) { taskElement.detach(); TaskGroup parent = taskElement.getParent(); if (parent != null) { parent.remove(taskElement); } } } }
package org.libreplan.web.planner.tabs; import java.util.Collection; import java.util.EnumMap; import org.apache.commons.lang.Validate; import org.libreplan.web.planner.tabs.Mode.ModeTypeChangedListener; import org.zkoss.ganttz.extensions.ITab; import org.zkoss.zk.ui.Component; public class TabOnModeType implements ITab { private final Mode mode; private final EnumMap<ModeType, ITab> tabs; private boolean beingShown = false; public static WithType forMode(Mode mode) { return new WithType(mode, new EnumMap<ModeType, ITab>(ModeType.class)); } public static class WithType{ private final Mode mode; private EnumMap<ModeType, ITab> tabs; private WithType(Mode mode, EnumMap<ModeType, ITab> tabs) { this.mode = mode; this.tabs = tabs; } public WithType forType(ModeType modeType, ITab tab) { tabs.put(modeType, tab); return this; } public TabOnModeType create() { return new TabOnModeType(mode, tabs); } } public TabOnModeType(Mode mode, EnumMap<ModeType, ITab> tabs) { Validate.notNull(mode); Validate.isTrue(handleAtLeatOneCase(tabs), "must handle at least one ModeType"); this.mode = mode; this.tabs = new EnumMap<ModeType, ITab>(tabs); this.mode.addListener(new ModeTypeChangedListener() { @Override public void typeChanged(ModeType oldType, ModeType newType) { if (beingShown) { changeTab(oldType, newType); } } }); } private void changeTab(ModeType oldType, ModeType newType) { ITab previousTab = tabs.get(oldType); previousTab.hide(); ITab newTab = tabs.get(newType); newTab.show(); } private boolean handleAtLeatOneCase(EnumMap<ModeType, ITab> tabs) { for (ModeType modeType : ModeType.values()) { if (tabs.get(modeType) != null) { return true; } } return false; } private ITab getCurrentTab() { return tabs.get(mode.getType()); } @Override public void addToParent(Component parent) { Collection<ITab> values = tabs.values(); for (ITab tab : values) { tab.addToParent(parent); } } @Override public String getName() { ITab currentTab = getCurrentTab(); return currentTab == null ? "" : currentTab.getName(); } @Override public String getCssClass() { ITab currentTab = getCurrentTab(); return currentTab == null ? "hidden" : currentTab.getCssClass(); } @Override public void hide() { beingShown = false; ITab currentTab = getCurrentTab(); if (currentTab != null) { currentTab.hide(); } } @Override public void show() { ITab currentTab = getCurrentTab(); if (currentTab != null && !beingShown) { currentTab.show(); } beingShown = true; } @Override public void showWithoutAfterCreate() { ITab currentTab = getCurrentTab(); if (currentTab != null && !beingShown) { currentTab.showWithoutAfterCreate(); } beingShown = true; } }
package jade.domain; import java.io.StringReader; import java.io.StringWriter; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.Iterator; import java.util.Set; import java.util.NoSuchElementException; import java.util.Map; import java.util.HashMap; import java.util.Vector; import jade.core.*; import jade.core.behaviours.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.proto.FipaRequestResponderBehaviour; /** Standard <em>Agent Management System</em> agent. This class implements <em><b>FIPA</b></em> <em>AMS</em> agent. <b>JADE</b> applications cannot use this class directly, but interact with it through <em>ACL</em> message passing. Javadoc documentation for the file @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class ams extends Agent { private abstract class AMSBehaviour extends FipaRequestResponderBehaviour.Action implements FipaRequestResponderBehaviour.Factory { // This Action will be set by crackMessage() private AgentManagementOntology.AMSAction myAction; protected AgentManagementOntology myOntology; protected AMSBehaviour() { super(ams.this); myOntology = AgentManagementOntology.instance(); } protected void checkMandatory(AgentManagementOntology.AMSAgentDescriptor amsd) throws FIPAException { // Make sure mandatory attributes for the current AMS // action are non-null checkAttribute(AgentManagementOntology.AMSAgentDescriptor.NAME, amsd.getName()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.ADDRESS, amsd.getAddress()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.SIGNATURE, amsd.getSignature()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.APSTATE, amsd.getAPState()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.DELEGATE, amsd.getDelegateAgentName()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.FORWARD, amsd.getForwardAddress()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.OWNERSHIP, amsd.getOwnership()); } // This method throws a FIPAException if the attribute is // mandatory for the current AMS action but it is a null object // reference private void checkAttribute(String attributeName, String attributeValue) throws FIPAException { if(myOntology.isMandatoryForAMS(myAction.getName(), attributeName) && (attributeValue == null)) throw myOntology.getException(AgentManagementOntology.Exception.MISSINGATTRIBUTE + " " +attributeName); } // This method parses the message content and puts // 'FIPA-AMS-description' attribute values in instance // variables. If some error is found a FIPA exception is thrown private void crackMessage() throws FIPAException, NoSuchElementException { ACLMessage msg = getRequest(); String content = msg.getContent(); // Obtain an AMS action from message content try { myAction = AgentManagementOntology.AMSAction.fromText(new StringReader(content)); } catch(ParseException pe) { // pe.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR+ " :content"); } catch(TokenMgrError tme) { // tme.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR+ " :content"); } } // Each concrete subclass will implement this deferred method to // do action-specific work protected abstract void processAction(AgentManagementOntology.AMSAction a) throws FIPAException; public void action() { try { // Convert message from untyped keyword/value list to a Java // object throwing a FIPAException in case of errors crackMessage(); // Do real action, deferred to subclasses processAction(myAction); } catch(FIPAException fe) { // fe.printStackTrace(); sendRefuse(fe.getMessage()); } catch(NoSuchElementException nsee) { // nsee.printStackTrace(); sendRefuse(AgentManagementOntology.Exception.UNRECOGNIZEDVALUE); } } public boolean done() { return true; } public void reset() { } } // End of AMSBehaviour class // These four concrete classes serve both as a Factory and as an // Action: when seen as Factory they can spawn a new // Behaviour to process a given request, and when seen as // Action they process their request and terminate. private class AuthBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new AuthBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); String agentName = amsd.getName(); if(agentName == null) AMSDumpData(); else { AMSDumpData(); } throw myOntology.getException(AgentManagementOntology.Exception.UNWILLING); // FIXME: Not Implemented } } // End of AuthBehaviour class private class RegBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new RegBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // waiting for an 'inform' message. Recover the buffered // message from the Map and send it back. ACLMessage informCreator = (ACLMessage)pendingInforms.remove(amsd.getName()); // Write new agent data in AMS Agent Table try { AMSNewData(amsd); sendAgree(); sendInform(); // Inform agent creator that registration was successful. if(informCreator != null) { informCreator.setPerformative(ACLMessage.INFORM); informCreator.setContent("( done ( " + a.getName() + " ) )"); send(informCreator); } } catch(AgentAlreadyRegisteredException aare) { sendAgree(); sendFailure(aare.getMessage()); // Inform agent creator that registration failed. if(informCreator != null) { informCreator.setPerformative(ACLMessage.FAILURE); informCreator.setContent("( ( action " + getLocalName() + " " + a.getName() + " ) " + aare.getMessage() + ")"); send(informCreator); } } } } // End of RegBehaviour class private class DeregBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new DeregBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // Remove the agent data from Global Descriptor Table AMSRemoveData(amsd); sendAgree(); sendInform(); } } // End of DeregBehaviour class private class ModBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new ModBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // Modify agent data from Global Descriptor Table AMSChangeData(amsd); sendAgree(); sendInform(); } } // End of ModBehaviour class private class QueryPPBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new QueryPPBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { sendAgree(); StringWriter profile = new StringWriter(); theProfile.toText(profile); ACLMessage reply = getReply(); reply.setPerformative(ACLMessage.INFORM); reply.setContent(profile.toString()); send(reply); } } // End of QueryPPBehaviour class // These Behaviours handle interactions with Remote Management Agent. private class RegisterRMABehaviour extends CyclicBehaviour { private MessageTemplate subscriptionTemplate; RegisterRMABehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage("SL"); MessageTemplate mt2 = MessageTemplate.MatchOntology("jade-agent-management"); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("RMA-subscription"); mt2 = MessageTemplate.MatchType("subscribe"); subscriptionTemplate = MessageTemplate.and(mt1, mt2); subscriptionTemplate = MessageTemplate.and(subscriptionTemplate, mt12); } public void action() { // Receive 'subscribe' ACL messages. ACLMessage current = receive(subscriptionTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Get new RMA name from subscription message String newRMA = current.getSource(); // Send back the whole container list. String[] names = myPlatform.containerNames(); for(int i = 0; i < names.length; i++) { String containerName = names[i]; AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWCONTAINER); ev.setContainerName(containerName); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.removeAllDests(); RMANotification.addDest(newRMA); RMANotification.setContent(w.toString()); send(RMANotification); } // Send all agent names, along with their container name. names = myPlatform.agentNames(); for(int i = 0; i < names.length; i++) { try { String agentName = names[i]; String containerName = myPlatform.getContainerName(agentName); String agentAddress = myPlatform.getAddress(agentName); // FIXME: Need to use AMSAgDesc directly AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(agentName); amsd.setAddress(agentAddress); amsd.setAPState(Agent.AP_ACTIVE); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWAGENT); ev.setContainerName(containerName); ev.setAgentDescriptor(amsd); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); RMANotification.removeAllDests(); RMANotification.addDest(newRMA); send(RMANotification); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } // Add the new RMA to RMAs agent group. RMAs.addMember(newRMA); } else block(); } } // End of RegisterRMABehaviour class private class DeregisterRMABehaviour extends CyclicBehaviour { private MessageTemplate cancellationTemplate; DeregisterRMABehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage("SL"); MessageTemplate mt2 = MessageTemplate.MatchOntology("jade-agent-management"); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("RMA-cancellation"); mt2 = MessageTemplate.MatchType("cancel"); cancellationTemplate = MessageTemplate.and(mt1, mt2); cancellationTemplate = MessageTemplate.and(cancellationTemplate, mt12); } public void action() { // Receive 'cancel' ACL messages. ACLMessage current = receive(cancellationTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Remove this RMA to RMAs agent group. RMAs.removeMember(current.getSource()); } else block(); } } // End of DeregisterRMABehaviour class private class NotifyRMAsBehaviour extends CyclicBehaviour { private void processNewContainers() { Enumeration e = newContainersBuffer.elements(); while(e.hasMoreElements()) { String name = (String)e.nextElement(); AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWCONTAINER); ev.setContainerName(name); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); newContainersBuffer.removeElement(name); } } private void processDeadContainers() { Enumeration e = deadContainersBuffer.elements(); while(e.hasMoreElements()) { String name = (String)e.nextElement(); AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSEvent.DEADCONTAINER); ev.setContainerName(name); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); deadContainersBuffer.removeElement(name); } } private void processNewAgents() { Enumeration e = newAgentsBuffer.elements(); while(e.hasMoreElements()) { AgDesc ad = (AgDesc)e.nextElement(); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSEvent.NEWAGENT); ev.setContainerName(ad.containerName); ev.setAgentDescriptor(ad.amsd); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); newAgentsBuffer.removeElement(ad); } } private void processDeadAgents() { Enumeration e = deadAgentsBuffer.elements(); while(e.hasMoreElements()) { AgDesc ad = (AgDesc)e.nextElement(); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSEvent.DEADAGENT); ev.setContainerName(ad.containerName); ev.setAgentDescriptor(ad.amsd); // Remove Agent Descriptor from table String agentName = ad.amsd.getName(); descrTable.remove(agentName.toLowerCase()); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); deadAgentsBuffer.removeElement(ad); } } private void processMovedAgents() { Enumeration e = movedAgentsBuffer.elements(); while(e.hasMoreElements()) { MotionDesc md = (MotionDesc)e.nextElement(); AgentManagementOntology.AMSMotionEvent ev = new AgentManagementOntology.AMSMotionEvent(); ev.setKind(AgentManagementOntology.AMSEvent.MOVEDAGENT); ev.setAgentDescriptor(md.desc); ev.setSrc(md.src); ev.setDest(md.dest); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); movedAgentsBuffer.removeElement(md); } } public void action() { // Look into the event buffers with AgentPlatform and send // appropriate ACL messages to registered RMAs // Mutual exclusion with postXXX() methods synchronized(ams.this) { processNewContainers(); processDeadContainers(); processNewAgents(); processDeadAgents(); processMovedAgents(); } block(); } } // End of NotifyRMAsBehaviour class private class KillContainerBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new KillContainerBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { // Obtain container name and ask AgentPlatform to kill it AgentManagementOntology.KillContainerAction kca = (AgentManagementOntology.KillContainerAction)a; String containerName = kca.getContainerName(); myPlatform.killContainer(containerName); sendAgree(); sendInform(); } } // End of KillContainerBehaviour class private class CreateBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new CreateBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.CreateAgentAction caa = (AgentManagementOntology.CreateAgentAction)a; String className = caa.getClassName(); String containerName = caa.getProperty(AgentManagementOntology.CreateAgentAction.CONTAINER); sendAgree(); // Create a new agent AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); try { myPlatform.create(amsd.getName(), className, containerName); // An 'inform Done' message will be sent to the requester only // when the newly created agent will register itself with the // AMS. The new agent's name will be used as the key in the map. ACLMessage reply = getReply(); reply = (ACLMessage)reply.clone(); pendingInforms.put(amsd.getName(), reply); } catch(UnreachableException ue) { throw new NoCommunicationMeansException(); } } } // End of CreateBehaviour class private class KillBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new KillBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { // Kill an agent AgentManagementOntology.KillAgentAction kaa = (AgentManagementOntology.KillAgentAction)a; String agentName = kaa.getAgentName(); String password = kaa.getPassword(); try { myPlatform.kill(agentName, password); sendAgree(); sendInform(); } catch(UnreachableException ue) { throw new NoCommunicationMeansException(); } catch(NotFoundException nfe) { throw new AgentNotRegisteredException(); } } } // End of KillBehaviour class private class SniffAgentOnBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new SniffAgentOnBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.SniffAgentOnAction saoa = (AgentManagementOntology.SniffAgentOnAction)a; try { myPlatform.sniffOn(saoa.getSnifferName(), saoa.getEntireList()); sendAgree(); sendInform(); } catch(UnreachableException ue) { throw new NoCommunicationMeansException(); } } } // End of SniffAgentOnBehaviour class private class SniffAgentOffBehaviour extends AMSBehaviour { public FipaRequestResponderBehaviour.Action create() { return new SniffAgentOffBehaviour(); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.SniffAgentOffAction saoa = (AgentManagementOntology.SniffAgentOffAction)a; try { myPlatform.sniffOff(saoa.getSnifferName(), saoa.getEntireList()); sendAgree(); sendInform(); } catch(UnreachableException ue) { throw new NoCommunicationMeansException(); } } } // End of SniffAgentOffBehaviour class private static class AgDesc { public AgDesc(String s, AgentManagementOntology.AMSAgentDescriptor a) { containerName = s; amsd = a; } public String containerName; public AgentManagementOntology.AMSAgentDescriptor amsd; } private static class MotionDesc { public MotionDesc(AgentManagementOntology.AMSAgentDescriptor amsd, String s, String d) { desc = amsd; src = s; dest = d; } public AgentManagementOntology.AMSAgentDescriptor desc; public String src; public String dest; } // The AgentPlatform where information about agents is stored private AgentManager myPlatform; // The table of 'AMS-Agent-Description' data for all the agents private Map descrTable; // Maintains an association between action names and behaviours private FipaRequestResponderBehaviour dispatcher; // Behaviour to listen to incoming 'subscribe' messages from Remote // Management Agents. private RegisterRMABehaviour registerRMA; // Behaviour to broadcats AgentPlatform notifications to each // registered Remote Management Agent. private NotifyRMAsBehaviour notifyRMAs; // Behaviour to listen to incoming 'cancel' messages from Remote // Management Agents. private DeregisterRMABehaviour deregisterRMA; // Group of Remote Management Agents registered with this AMS private AgentGroup RMAs; // ACL Message to use for RMA notification private ACLMessage RMANotification = new ACLMessage(ACLMessage.INFORM); // Buffers for AgentPlatform notifications private Vector newContainersBuffer = new Vector(); private Vector deadContainersBuffer = new Vector(); private Vector newAgentsBuffer = new Vector(); private Vector deadAgentsBuffer = new Vector(); private Vector movedAgentsBuffer = new Vector(); private Map pendingInforms = new HashMap(); private AgentManagementOntology.PlatformProfile theProfile = new AgentManagementOntology.PlatformProfile(); /** This constructor creates a new <em>AMS</em> agent. Since a direct reference to an Agent Platform implementation must be passed to it, this constructor cannot be called from application code. Therefore, no other <em>AMS</em> agent can be created beyond the default one. */ public ams(AgentManager ap) { myPlatform = ap; descrTable = new HashMap(); MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchLanguage("SL0"), MessageTemplate.MatchOntology("fipa-agent-management")); dispatcher = new FipaRequestResponderBehaviour(this, mt); registerRMA = new RegisterRMABehaviour(); deregisterRMA = new DeregisterRMABehaviour(); notifyRMAs = new NotifyRMAsBehaviour(); RMAs = new AgentGroup(); RMANotification.setSource(getLocalName()); RMANotification.setLanguage("SL"); RMANotification.setOntology("jade-agent-management"); RMANotification.setReplyTo("RMA-subscription"); // Associate each AMS action name with the behaviour to execute // when the action is requested in a 'request' ACL message dispatcher.registerFactory(AgentManagementOntology.AMSAction.AUTHENTICATE, new AuthBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.REGISTERAGENT, new RegBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.DEREGISTERAGENT, new DeregBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.MODIFYAGENT, new ModBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.QUERYPLATFORMPROFILE, new QueryPPBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.CREATEAGENT, new CreateBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.KILLAGENT, new KillBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.KILLCONTAINER, new KillContainerBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.SNIFFAGENTON, new SniffAgentOnBehaviour()); dispatcher.registerFactory(AgentManagementOntology.AMSAction.SNIFFAGENTOFF, new SniffAgentOffBehaviour()); } /** This method starts the <em>AMS</em> behaviours to allow the agent to carry on its duties within <em><b>JADE</b></em> agent platform. */ protected void setup() { // Fill Agent Platform Profile with data. theProfile.setPlatformName("cselt.UniPR.JADE"); theProfile.setIiopURL(getAddress()); theProfile.setDynReg("false"); theProfile.setMobility("false"); theProfile.setOwnership("CSELT.it"); theProfile.setCertificationAuthority("None"); theProfile.setFipaVersion("fipa97-part1-v2"); // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction addBehaviour(dispatcher); // Add a Behaviour to accept incoming RMA registrations and a // Behaviour to broadcast events to registered RMAs. addBehaviour(registerRMA); addBehaviour(deregisterRMA); addBehaviour(notifyRMAs); } // This one is called in response to a 'register-agent' action private void AMSNewData(AgentManagementOntology.AMSAgentDescriptor amsd) throws FIPAException, AgentAlreadyRegisteredException { String agentName = amsd.getName(); AgentManagementOntology.AMSAgentDescriptor old = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); // FIXME: Should accept foreign agents by checking with the GADT if(old != null) { throw new AgentAlreadyRegisteredException(); } descrTable.put(agentName.toLowerCase(), amsd); } // This one is called in response to a 'modify-agent' action private void AMSChangeData(AgentManagementOntology.AMSAgentDescriptor amsd) throws FIPAException { try { String agentName = amsd.getName(); AgentManagementOntology.AMSAgentDescriptor toChange = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); if(toChange == null) throw new AgentNotRegisteredException(); String address = amsd.getAddress(); if(address != null) toChange.setAddress(address); String signature = amsd.getSignature(); if(signature != null) toChange.setSignature(signature); String delegateAgentName = amsd.getDelegateAgentName(); if(delegateAgentName != null) toChange.setDelegateAgentName(delegateAgentName); String forwardAddress = amsd.getForwardAddress(); if(forwardAddress != null) toChange.setAddress(forwardAddress); String ownership = amsd.getOwnership(); if(ownership != null) toChange.setOwnership(ownership); String APState = amsd.getAPState(); if(APState != null) { AgentManagementOntology o = AgentManagementOntology.instance(); int state = o.getAPStateByName(APState); int oldState = o.getAPStateByName(toChange.getAPState()); switch(state) { case Agent.AP_SUSPENDED: myPlatform.suspend(agentName, null); break; case Agent.AP_WAITING: myPlatform.wait(agentName, null); break; case Agent.AP_ACTIVE: if(oldState == Agent.AP_WAITING) myPlatform.wake(agentName, null); else myPlatform.activate(agentName, null); break; case Agent.AP_DELETED: myPlatform.kill(agentName, null); break; } toChange.setAPState(state); } } catch(NotFoundException nfe) { throw new AgentNotRegisteredException(); } catch(UnreachableException ue) { throw new NoCommunicationMeansException(); } } // This one is called in response to a 'deregister-agent' action private void AMSRemoveData(AgentManagementOntology.AMSAgentDescriptor amsd) throws FIPAException { String agentName = amsd.getName(); AgentManagementOntology.AMSAgentDescriptor toRemove = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); if(toRemove == null) { throw new jade.domain.UnableToDeregisterException(); } toRemove.setAPState(Agent.AP_DELETED); // This descriptor will be removed from the table after the platform notification } private void AMSDumpData() { Iterator descriptors = descrTable.values().iterator(); while(descriptors.hasNext()) { AgentManagementOntology.AMSAgentDescriptor amsd = (AgentManagementOntology.AMSAgentDescriptor)descriptors.next(); amsd.toText(new BufferedWriter(new OutputStreamWriter(System.out))); } } private void AMSDumpData(String agentName) { AgentManagementOntology.AMSAgentDescriptor amsd = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); amsd.toText(new BufferedWriter(new OutputStreamWriter(System.out))); } /** The AMS must have a special version for this method, or a deadlock will occur. */ public void registerWithAMS(String signature, int APState, String delegateAgentName, String forwardAddress, String ownership) { // Skip all fipa-request protocol and go straight to the target try { // FIXME: APState parameter is never used AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setSignature(signature); amsd.setAPState(Agent.AP_ACTIVE); amsd.setDelegateAgentName(delegateAgentName); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); AMSNewData(amsd); } // No exception should occur since this is a special case ... catch(AgentAlreadyRegisteredException aare) { aare.printStackTrace(); } catch(FIPAException fe) { fe.printStackTrace(); } } /** The AMS must have a special version for this method, or a deadlock will occur. */ public void deregisterWithAMS() throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(Agent.AP_ACTIVE); AMSRemoveData(amsd); } // Methods to be called from AgentPlatform to notify AMS of special events /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void postNewContainer(String name) { newContainersBuffer.addElement(new String(name)); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void postDeadContainer(String name) { deadContainersBuffer.addElement(new String(name)); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void postNewAgent(String containerName, String agentName) { AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(agentName); amsd.setAddress(myPlatform.getAddress(agentName)); newAgentsBuffer.addElement(new AgDesc(containerName, amsd)); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void postDeadAgent(String containerName, String agentName) { AgentManagementOntology.AMSAgentDescriptor amsd = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); deadAgentsBuffer.addElement(new AgDesc(containerName, amsd)); doWake(); } public synchronized void postMovedAgent(String agentName, String src, String dest) { AgentManagementOntology.AMSAgentDescriptor amsd = (AgentManagementOntology.AMSAgentDescriptor)descrTable.get(agentName.toLowerCase()); movedAgentsBuffer.addElement(new MotionDesc(amsd, src, dest)); doWake(); } } // End of class ams
package jade.domain; import java.io.StringReader; import java.io.StringWriter; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Map; import java.util.HashMap; import jade.core.*; import jade.core.behaviours.*; import jade.domain.FIPAAgentManagement.*; import jade.domain.JADEAgentManagement.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.lang.Codec; import jade.lang.sl.SL0Codec; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.onto.Frame; import jade.onto.basic.Action; import jade.onto.basic.BasicOntology; import jade.onto.basic.ResultPredicate; import jade.onto.basic.DonePredicate; import jade.mtp.MTPException; import jade.proto.FipaRequestResponderBehaviour; /** Standard <em>Agent Management System</em> agent. This class implements <em><b>FIPA</b></em> <em>AMS</em> agent. <b>JADE</b> applications cannot use this class directly, but interact with it through <em>ACL</em> message passing. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class ams extends Agent implements AgentManager.Listener { private abstract class AMSBehaviour extends FipaRequestResponderBehaviour.ActionHandler implements FipaRequestResponderBehaviour.Factory { protected AMSBehaviour(ACLMessage req) { super(ams.this,req); } // Each concrete subclass will implement this deferred method to // do action-specific work protected abstract void processAction(Action a) throws FIPAException; public void action() { try { ACLMessage msg = getRequest(); List l = myAgent.extractContent(msg); Action a = (Action)l.get(0); // Do real action, deferred to subclasses processAction(a); } catch(FIPAException fe) { System.out.println("FIPA Exception: " + fe.getMessage()); sendReply(ACLMessage.REFUSE,"("+fe.getMessage()+")"); } } /** Writes the <code>Done</code> predicate for the specific action into the result <code>String</code> object, encoded in SL0. */ protected String doneAction(Action a, String ontoName) throws FIPAException { try { Ontology o = lookupOntology(ontoName); DonePredicate dp = new DonePredicate(); dp.set_0(a); Frame f = o.createFrame(dp, BasicOntology.DONE); List l = new ArrayList(1); l.add(f); Codec c = lookupLanguage(SL0Codec.NAME); String result = c.encode(l, o); return result; } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Internal error in building Done predicate."); } } public boolean done() { return true; } public void reset() { } } // End of AMSBehaviour class // These four concrete classes serve both as a Factory and as an // Action: when seen as Factory they can spawn a new // Behaviour to process a given request, and when seen as // Action they process their request and terminate. private class RegBehaviour extends AMSBehaviour { public RegBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new RegBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Register r = (Register)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)r.get_0(); // waiting for an 'inform' message. Recover the buffered // message from the Map and send it back. ACLMessage informCreator = (ACLMessage)pendingInforms.remove(amsd.getName()); try { // Write new agent data in AMS Agent Table AMSRegister(amsd); //sendReply(ACLMessage.AGREE,"( true )"); sendReply(ACLMessage.INFORM, doneAction(a, getRequest().getOntology())); // Inform agent creator that registration was successful. if(informCreator != null) { informCreator.setPerformative(ACLMessage.INFORM); // informCreator.setContent("( done ( " + a.getName() + " ) )"); send(informCreator); } } catch(AlreadyRegistered are) { //sendReply(ACLMessage.AGREE, "( true )"); sendReply(ACLMessage.FAILURE,"("+are.getMessage()+")"); // Inform agent creator that registration failed. if(informCreator != null) { informCreator.setPerformative(ACLMessage.FAILURE); // informCreator.setContent("( ( action " + getLocalName() + " " + a.getName() + " ) " + aare.getMessage() + ")"); send(informCreator); } } } } // End of RegBehaviour class private class DeregBehaviour extends AMSBehaviour { public DeregBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new DeregBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Deregister d = (Deregister)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)d.get_0(); AMSDeregister(amsd); //sendReply(ACLMessage.AGREE, "( true )"); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } } // End of DeregBehaviour class private class ModBehaviour extends AMSBehaviour { public ModBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new ModBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Modify m = (Modify)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)m.get_0(); AMSModify(amsd); //sendReply(ACLMessage.AGREE, "( true)"); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } } // End of ModBehaviour class private class SrchBehaviour extends AMSBehaviour { public SrchBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SrchBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Search s = (Search)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)s.get_0(); SearchConstraints constraints = s.get_1(); List l = AMSSearch(amsd, constraints, getReply()); //sendReply(ACLMessage.AGREE,"( true)"); ACLMessage msg = getRequest().createReply(); msg.setPerformative(ACLMessage.INFORM); ResultPredicate r = new ResultPredicate(); r.set_0(a); for (int i=0; i<l.size(); i++) r.add_1(l.get(i)); l.clear(); l.add(r); fillContent(msg,l); send(msg); } } // End of SrchBehaviour class private class GetDescriptionBehaviour extends AMSBehaviour { public GetDescriptionBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new GetDescriptionBehaviour(msg); } protected void processAction(Action a) throws FIPAException { //sendReply(ACLMessage.AGREE, "( true )"); ACLMessage reply = getReply(); reply.setPerformative(ACLMessage.INFORM); List l = new ArrayList(1); l.add(theProfile); fillContent(reply, l); send(reply); } } // End of GetDescriptionBehaviour class // These Behaviours handle interactions with platform tools. private class RegisterToolBehaviour extends CyclicBehaviour { private MessageTemplate subscriptionTemplate; RegisterToolBehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage(SL0Codec.NAME); MessageTemplate mt2 = MessageTemplate.MatchOntology(JADEAgentManagementOntology.NAME); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("tool-subscription"); mt2 = MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE); subscriptionTemplate = MessageTemplate.and(mt1, mt2); subscriptionTemplate = MessageTemplate.and(subscriptionTemplate, mt12); } public void action() { // Receive 'subscribe' ACL messages. ACLMessage current = receive(subscriptionTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Get new tool name from subscription message AID newTool = current.getSender(); try { // Send back the whole container list. String[] names = myPlatform.containerNames(); for(int i = 0; i < names.length; i++) { String containerName = names[i]; // FIXME: Need to retrieve the real host from the platform InetAddress addr = null; try { addr = InetAddress.getLocalHost(); } catch(java.net.UnknownHostException jnuhe) { jnuhe.printStackTrace(); } String containerHost = addr.getHostName(); ContainerBorn cb = new ContainerBorn(); cb.setName(containerName); cb.setHost(containerHost); EventOccurred eo = new EventOccurred(); eo.setEvent(cb); List l = new ArrayList(1); l.add(eo); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillContent(toolNotification, l); send(toolNotification); } // Send all agent names, along with their container name. AID[] agents = myPlatform.agentNames(); for(int i = 0; i < agents.length; i++) { AID agentName = agents[i]; String containerName = myPlatform.getContainerName(agentName); AgentBorn ab = new AgentBorn(); ab.setContainer(containerName); ab.setAgent(agentName); EventOccurred eo = new EventOccurred(); eo.setEvent(ab); List l = new ArrayList(1); l.add(eo); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillContent(toolNotification, l); send(toolNotification); } // Add the new tool to tools list. tools.add(newTool); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(FIPAException fe) { fe.printStackTrace(); } } else block(); } } // End of RegisterToolBehaviour class private class DeregisterToolBehaviour extends CyclicBehaviour { private MessageTemplate cancellationTemplate; DeregisterToolBehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage(SL0Codec.NAME); MessageTemplate mt2 = MessageTemplate.MatchOntology(JADEAgentManagementOntology.NAME); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("tool-cancellation"); mt2 = MessageTemplate.MatchPerformative(ACLMessage.CANCEL); cancellationTemplate = MessageTemplate.and(mt1, mt2); cancellationTemplate = MessageTemplate.and(cancellationTemplate, mt12); } public void action() { // Receive 'cancel' ACL messages. ACLMessage current = receive(cancellationTemplate); if(current != null) { // FIXME: Should parse the content // Remove this tool to tools agent group. tools.remove(current.getSender()); } else block(); } } // End of DeregisterToolBehaviour class private class NotifyToolsBehaviour extends CyclicBehaviour { public void action() { synchronized(ams.this) { // Mutual exclusion with handleXXX() methods // Look into the event buffer Iterator it = eventQueue.iterator(); EventOccurred eo = new EventOccurred(); while(it.hasNext()) { // Write the event into the notification message AMSEvent ev = (AMSEvent)it.next(); List l = new ArrayList(1); eo.setEvent(ev); l.add(eo); try { fillContent(toolNotification, l); } catch(FIPAException fe) { fe.printStackTrace(); } // Put all tools in the receiver list toolNotification.clearAllReceiver(); Iterator toolIt = tools.iterator(); while(toolIt.hasNext()) { AID tool = (AID)toolIt.next(); toolNotification.addReceiver(tool); } send(toolNotification); it.remove(); } } block(); } } // End of NotifyToolsBehaviour class private class KillContainerBehaviour extends AMSBehaviour { public KillContainerBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new KillContainerBehaviour(msg); } protected void processAction(Action a) throws FIPAException { KillContainer kc = (KillContainer)a.get_1(); String containerName = kc.getName(); myPlatform.killContainer(containerName); //sendReply(ACLMessage.AGREE, " (true)"); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } } // End of KillContainerBehaviour class private class CreateBehaviour extends AMSBehaviour { public CreateBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new CreateBehaviour(msg); } protected void processAction(Action a) throws FIPAException { CreateAgent ca = (CreateAgent)a.get_1(); String agentName = ca.getAgentName(); String className = ca.getClassName(); String containerName = ca.getContainerName(); Iterator arg = ca.getAllArguments(); //return an iterator of all arguments //create the array of string ArrayList listArg = new ArrayList(); while(arg.hasNext()) listArg.add(arg.next().toString()); String[] arguments = new String[listArg.size()]; for(int n = 0; n< listArg.size(); n++) arguments[n] = (String)listArg.get(n); //sendReply(ACLMessage.AGREE, "(true)"); try { myPlatform.create(agentName, className, arguments, containerName); // An 'inform Done' message will be sent to the requester only // when the newly created agent will register itself with the // AMS. The new agent's name will be used as the key in the map. ACLMessage reply = getReply(); reply = (ACLMessage)reply.clone(); pendingInforms.put(agentName, reply); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } } } // End of CreateBehaviour class private class KillBehaviour extends AMSBehaviour { public KillBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new KillBehaviour(msg); } protected void processAction(Action a) throws FIPAException { // Kill an agent KillAgent ka = (KillAgent)a.get_1(); AID agentID = ka.getAgent(); String password = ka.getPassword(); try { myPlatform.kill(agentID, password); //sendReply(ACLMessage.AGREE, "( true )"); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of KillBehaviour class private class SniffAgentOnBehaviour extends AMSBehaviour { public SniffAgentOnBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SniffAgentOnBehaviour(msg); } protected void processAction(Action a) throws FIPAException { SniffOn so = (SniffOn)a.get_1(); try { myPlatform.sniffOn(so.getSniffer(), so.getCloneOfSniffedAgents()); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } } } // End of SniffAgentOnBehaviour class private class SniffAgentOffBehaviour extends AMSBehaviour { public SniffAgentOffBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SniffAgentOffBehaviour(msg); } protected void processAction(Action a) throws FIPAException { SniffOff so = (SniffOff)a.get_1(); try { myPlatform.sniffOff(so.getSniffer(), so.getCloneOfSniffedAgents()); sendReply(ACLMessage.INFORM,doneAction(a, getRequest().getOntology())); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } } } // End of SniffAgentOffBehaviour class private class InstallMTPBehaviour extends AMSBehaviour { public InstallMTPBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new InstallMTPBehaviour(msg); } protected void processAction(Action a) throws FIPAException { InstallMTP imtp = (InstallMTP)a.get_1(); try { myPlatform.installMTP(imtp.getAddress(), imtp.getContainer(), imtp.getClassName()); sendReply(ACLMessage.INFORM, doneAction(a, getRequest().getOntology())); } catch(NotFoundException nfe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", nfe.getMessage()); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError(ue.getMessage()); } catch(MTPException mtpe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", mtpe.getMessage()); } } } // End of InstallMTPBehaviour class private class UninstallMTPBehaviour extends AMSBehaviour { public UninstallMTPBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new UninstallMTPBehaviour(msg); } protected void processAction(Action a) throws FIPAException { UninstallMTP umtp = (UninstallMTP)a.get_1(); try { myPlatform.uninstallMTP(umtp.getAddress(), umtp.getContainer()); sendReply(ACLMessage.INFORM, doneAction(a, getRequest().getOntology())); } catch(NotFoundException nfe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", nfe.getMessage()); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError(ue.getMessage()); } catch(MTPException mtpe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", mtpe.getMessage()); } } } // End of UninstallMTPBehaviour class // The AgentPlatform where information about agents is stored /** @serial */ private AgentManager myPlatform; // Maintains an association between action names and behaviours to // handle 'fipa-agent-management' actions /** @serial */ private FipaRequestResponderBehaviour dispatcher; // Maintains an association between action names and behaviours to // handle 'jade-agent-management' actions /** @serial */ private FipaRequestResponderBehaviour extensionsDispatcher; // Contains a main Behaviour and some utilities to handle JADE mobility /** @serial */ private MobilityManager mobilityMgr; // Behaviour to listen to incoming 'subscribe' messages from tools. /** @serial */ private RegisterToolBehaviour registerTool; // Behaviour to broadcats AgentPlatform notifications to each // registered tool. /** @serial */ private NotifyToolsBehaviour notifyTools; // Behaviour to listen to incoming 'cancel' messages from tools. /** @serial */ private DeregisterToolBehaviour deregisterTool; // Group of tools registered with this AMS /** @serial */ private List tools; // ACL Message to use for tool notification /** @serial */ private ACLMessage toolNotification = new ACLMessage(ACLMessage.INFORM); // Buffer for AgentPlatform notifications /** @serial */ private List eventQueue = new ArrayList(10); /** @serial */ private Map pendingInforms = new HashMap(); /** @serial */ private APDescription theProfile = new APDescription(); /** This constructor creates a new <em>AMS</em> agent. Since a direct reference to an Agent Platform implementation must be passed to it, this constructor cannot be called from application code. Therefore, no other <em>AMS</em> agent can be created beyond the default one. */ public ams(AgentManager ap) { myPlatform = ap; myPlatform.addListener(this); // Fill Agent Platform Profile with data. theProfile.setName("JADE"); theProfile.setDynamic(new Boolean(false)); theProfile.setMobility(new Boolean(false)); APTransportDescription mtps = new APTransportDescription(); theProfile.setTransportProfile(mtps); MessageTemplate mtFIPA = MessageTemplate.and(MessageTemplate.MatchLanguage(SL0Codec.NAME), MessageTemplate.MatchOntology(FIPAAgentManagementOntology.NAME)); dispatcher = new FipaRequestResponderBehaviour(this, mtFIPA); MessageTemplate mtJADE = MessageTemplate.and(MessageTemplate.MatchLanguage(SL0Codec.NAME), MessageTemplate.MatchOntology(JADEAgentManagementOntology.NAME)); extensionsDispatcher = new FipaRequestResponderBehaviour(this, mtJADE); mobilityMgr = new MobilityManager(this); registerTool = new RegisterToolBehaviour(); deregisterTool = new DeregisterToolBehaviour(); notifyTools = new NotifyToolsBehaviour(); tools = new ArrayList(); toolNotification.setSender(new AID()); toolNotification.setLanguage(SL0Codec.NAME); toolNotification.setOntology("jade-agent-management"); toolNotification.setInReplyTo("tool-subscription"); // Associate each AMS action name with the behaviour to execute // when the action is requested in a 'request' ACL message dispatcher.registerFactory(FIPAAgentManagementOntology.REGISTER, new RegBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.DEREGISTER, new DeregBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.MODIFY, new ModBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.SEARCH, new SrchBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.GETDESCRIPTION, new GetDescriptionBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.CREATEAGENT, new CreateBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.KILLAGENT, new KillBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.KILLCONTAINER, new KillContainerBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.SNIFFON, new SniffAgentOnBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.SNIFFOFF, new SniffAgentOffBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.INSTALLMTP, new InstallMTPBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.UNINSTALLMTP, new UninstallMTPBehaviour(null)); } /** This method starts the <em>AMS</em> behaviours to allow the agent to carry on its duties within <em><b>JADE</b></em> agent platform. */ protected void setup() { // Register the supported ontologies registerOntology(FIPAAgentManagementOntology.NAME, FIPAAgentManagementOntology.instance()); registerOntology(JADEAgentManagementOntology.NAME, JADEAgentManagementOntology.instance()); registerOntology(MobilityOntology.NAME, MobilityOntology.instance()); // register the supported languages registerLanguage(SL0Codec.NAME, new SL0Codec()); // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction with 'fipa-agent-management' ontology. addBehaviour(dispatcher); // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction with 'jade-agent-management' ontology. addBehaviour(extensionsDispatcher); // Add a main behaviour to manage mobility related messages addBehaviour(mobilityMgr.getMain()); // Add a Behaviour to accept incoming tool registrations and a // Behaviour to broadcast events to registered tools. addBehaviour(registerTool); addBehaviour(deregisterTool); addBehaviour(notifyTools); } /** * checks that all the mandatory slots for a register/modify/deregister action * are present. * @param actionName is the name of the action (one of * <code>FIPAAgentManagementOntology.REGISTER</code>, * <code>FIPAAgentManagementOntology.MODIFY</code>, * <code>FIPAAgentManagementOntology.DEREGISTER</code>) * @param amsd is the AMSAgentDescription to be checked for * @throws MissingParameter if one of the mandatory slots is missing **/ private void checkMandatorySlots(String actionName, AMSAgentDescription amsd) throws MissingParameter { try { AID name = amsd.getName(); if ((name == null)||(name.getName().length() == 0)) throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "name"); } catch (Exception e) { e.printStackTrace(); throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "name"); } if (!actionName.equalsIgnoreCase(FIPAAgentManagementOntology.DEREGISTER)) try { String state = amsd.getState(); if((state == null)||(state.length() == 0)) throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "state"); } catch (Exception e) { e.printStackTrace(); throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "state"); } } /** @serial */ private KB agentDescriptions = new KBAbstractImpl() { protected boolean match(Object template, Object fact) { try { AMSAgentDescription templateDesc = (AMSAgentDescription)template; AMSAgentDescription factDesc = (AMSAgentDescription)fact; String o1 = templateDesc.getOwnership(); if(o1 != null) { String o2 = factDesc.getOwnership(); if((o2 == null) || (!o1.equalsIgnoreCase(o2))) return false; } String s1 = templateDesc.getState(); if(s1 != null) { String s2 = factDesc.getState(); if((s2 == null) || (!s1.equalsIgnoreCase(s2))) return false; } AID id1 = templateDesc.getName(); if(id1 != null) { AID id2 = factDesc.getName(); if((id2 == null) || (!matchAID(id1, id2))) return false; } return true; } catch(ClassCastException cce) { return false; } } }; /** it is called also by Agent.java **/ public void AMSRegister(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.REGISTER, amsd); String[] addresses = myPlatform.platformAddresses(); AID id = amsd.getName(); for(int i = 0; i < addresses.length; i++) id.addAddresses(addresses[i]); Object old = agentDescriptions.register(amsd.getName(), amsd); if(old != null) throw new AlreadyRegistered(); } /** it is called also by Agent.java **/ public void AMSDeregister(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.DEREGISTER, amsd); Object old = agentDescriptions.deregister(amsd.getName()); if(old == null) throw new NotRegistered(); } private void AMSModify(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.MODIFY, amsd); Object old = agentDescriptions.deregister(amsd.getName()); if(old == null) throw new NotRegistered(); agentDescriptions.register(amsd.getName(), amsd); } private List AMSSearch(AMSAgentDescription amsd, SearchConstraints constraints, ACLMessage reply) throws FIPAException { // Search has no mandatory slots return agentDescriptions.search(amsd); } // This one is called in response to a 'move-agent' action void AMSMoveAgent(AID agentID, Location where) throws FIPAException { try { myPlatform.move(agentID, where, ""); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } // This one is called in response to a 'clone-agent' action void AMSCloneAgent(AID agentID, Location where, String newName) throws FIPAException { try { myPlatform.copy(agentID, where, newName, ""); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } // This one is called in response to a 'where-is-agent' action MobilityOntology.Location AMSWhereIsAgent(AID agentID) throws FIPAException { try { String containerName = myPlatform.getContainerName(agentID); return mobilityMgr.getLocation(containerName); } catch(NotFoundException nfe) { nfe.printStackTrace(); throw new NotRegistered(); } } // This one is called in response to a 'query-platform-locations' action Iterator AMSGetPlatformLocations() { return mobilityMgr.getLocations(); } // Methods to be called from AgentPlatform to notify AMS of special events /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void handleNewContainer(String name, InetAddress addr) { // Add a new location to the locations list MobilityOntology.Location loc = new MobilityOntology.Location(name,getHap()); mobilityMgr.addLocation(name, loc); // Fire a 'container is born' event ContainerBorn cb = new ContainerBorn(); cb.setName(name); cb.setHost(addr.getHostName()); eventQueue.add(cb); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void handleDeadContainer(String name) { // Remove the location from the location list mobilityMgr.removeLocation(name); // Fire a 'container is dead' event ContainerDead cd = new ContainerDead(); cd.setName(name); eventQueue.add(cd); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void handleNewAgent(String containerName, AID agentID) { AgentBorn ab = new AgentBorn(); ab.setAgent(agentID); ab.setContainer(containerName); eventQueue.add(ab); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void handleDeadAgent(String containerName, AID agentID) { // Deregister the agent, if it's still there. try { AMSAgentDescription amsd = new AMSAgentDescription(); amsd.setName(agentID); List l = AMSSearch(amsd, null, null); if(!l.isEmpty()) AMSDeregister(amsd); } catch(FIPAException fe) { fe.printStackTrace(); } AgentDead ad = new AgentDead(); ad.setAgent(agentID); ad.setContainer(containerName); eventQueue.add(ad); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void handleMovedAgent(String fromContainer, String toContainer, AID agentID) { AgentMoved am = new AgentMoved(); am.setFrom(fromContainer); am.setTo(toContainer); am.setAgent(agentID); eventQueue.add(am); doWake(); } public void handleNewAddress(String address) { // Add the new address to the platform profile APTransportDescription mtps = theProfile.getTransportProfile(); MTPDescription desc = new MTPDescription(); int colonPos = address.indexOf(':'); if(colonPos != -1) desc.setMtpName(address.substring(0, colonPos)); desc.addAddresses(address); mtps.addAvailableMtps(desc); // Retrieve all agent descriptors AMSAgentDescription amsd = new AMSAgentDescription(); List l = agentDescriptions.search(amsd); // Add the new address to all the agent descriptors Iterator it = l.iterator(); while(it.hasNext()) { AMSAgentDescription ad = (AMSAgentDescription)it.next(); AID name = ad.getName(); name.addAddresses(address); } } public void handleDeadAddress(String address) { // Remove the dead address from the platform profile APTransportDescription mtps = theProfile.getTransportProfile(); Iterator it = mtps.getAllAvailableMtps(); while(it.hasNext()) { MTPDescription desc = (MTPDescription)it.next(); Iterator addresses = desc.getAllAddresses(); while(addresses.hasNext()) { // Remove all MTPs that have the 'address' String in their // address list. String nextAddr = (String)addresses.next(); if(nextAddr.equalsIgnoreCase(address)) it.remove(); } } // Remove the dead address from all the registered agents AID[] agents = myPlatform.agentNames(); AMSAgentDescription amsd = new AMSAgentDescription(); for(int i = 0; i < agents.length; i++) { amsd.setName(agents[i]); List l = agentDescriptions.search(amsd); AMSAgentDescription desc = (AMSAgentDescription)l.get(0); AID name = desc.getName(); name.removeAddresses(address); } } } // End of class ams
package com.github.dreamhead.moco.matcher; import com.github.dreamhead.moco.MocoConfig; import com.github.dreamhead.moco.MocoException; import com.github.dreamhead.moco.Request; import com.github.dreamhead.moco.RequestMatcher; import com.github.dreamhead.moco.extractor.ContentRequestExtractor; import com.github.dreamhead.moco.extractor.XmlExtractorHelper; import com.github.dreamhead.moco.resource.Resource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import static com.google.common.base.Strings.isNullOrEmpty; public abstract class XmlRequestMatcher extends AbstractRequestMatcher { protected abstract boolean doMatch(final Document actual, final Document expected); protected abstract RequestMatcher newAppliedMatcher(final Resource applied); private final XmlExtractorHelper helper = new XmlExtractorHelper(); private final ContentRequestExtractor extractor; private final Resource resource; public XmlRequestMatcher(final Resource resource) { this.extractor = new ContentRequestExtractor(); this.resource = resource; } @Override public final boolean match(final Request request) { Optional<Document> requestDocument = extractDocument(request, extractor); return requestDocument.filter(actual -> tryToMatch(request, actual)).isPresent(); } private boolean tryToMatch(final Request request, final Document actual) { try { Document expected = getExpectedDocument(request, this.resource); return doMatch(actual, expected); } catch (SAXException e) { return false; } } @Override public final RequestMatcher doApply(final MocoConfig config) { if (config.isFor(resource.id())) { return newAppliedMatcher(resource.apply(config)); } return this; } private Document getExpectedDocument(final Request request, final Resource resource) throws SAXException { InputStream stream = resource.readFor(request).toInputStream(); return extractDocument(new InputSource(stream)); } private Optional<Document> extractDocument(final Request request, final ContentRequestExtractor extractor) { Optional<InputSource> inputSourceOptional = helper.extractAsInputSource(request, extractor); return inputSourceOptional.map(this::extractDocument); } private void trimChild(final Node node, final Node child) { if (child instanceof Text) { if (isNullOrEmpty(child.getNodeValue().trim())) { node.removeChild(child); } return; } if (child instanceof Element) { trimNode(child); } } // Whitespace will be kept by DOM parser. private void trimNode(final Node node) { NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i trimChild(node, children.item(i)); } } private DocumentBuilder documentBuilder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); try { return dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new MocoException(e); } } private Document extractDocument(final InputSource inputSource) { try { DocumentBuilder builder = documentBuilder(); Document document = builder.parse(inputSource); document.normalizeDocument(); trimNode(document); return document; } catch (IOException | SAXException e) { throw new MocoException(e); } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.Area; import java.awt.geom.Path2D; import java.awt.geom.RoundRectangle2D; import java.util.Objects; import java.util.Optional; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(1, 2)); DefaultListModel<String> model = new DefaultListModel<>(); model.addElement("ABC DEF GHI JKL MNO PQR STU VWX YZ"); model.addElement("111"); model.addElement("111222"); model.addElement("111222333"); model.addElement("1234567890 abc def ghi jkl mno pqr stu vwx yz"); model.addElement("bbb1"); model.addElement("bbb12"); model.addElement("1234567890-+*/=ABC DEF GHI JKL MNO PQR STU VWX YZ"); model.addElement("bbb123"); JList<String> list1 = new JList<String>(model) { @Override public JToolTip createToolTip() { JToolTip tip = new BalloonToolTip(); tip.setComponent(this); return tip; } @Override public void updateUI() { super.updateUI(); setCellRenderer(new TooltipListCellRenderer<>()); } }; JList<String> list2 = new JList<String>(model) { @Override public void updateUI() { super.updateUI(); setCellRenderer(new TooltipListCellRenderer<>()); } }; add(makeTitledPanel("BalloonToolTip", list1)); add(makeTitledPanel("Default JToolTip", list2)); setPreferredSize(new Dimension(320, 240)); } private static Component makeTitledPanel(String title, Component c) { JScrollPane scroll = new JScrollPane(c); scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(scroll); return p; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TooltipListCellRenderer<E> implements ListCellRenderer<E> { private final ListCellRenderer<? super E> renderer = new DefaultListCellRenderer(); @Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) { JLabel l = (JLabel) renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); // Insets i = l.getInsets(); // Container c = SwingUtilities.getAncestorOfClass(JViewport.class, list); // Rectangle rect = c.getBounds(); Class<JViewport> clz = JViewport.class; Rectangle rect = Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, list)) .filter(clz::isInstance).map(clz::cast) // .map(JViewport::getBounds) .map(v -> SwingUtilities.calculateInnerArea(v, null)) .orElseGet(Rectangle::new); // rect.width -= i.left + i.right; FontMetrics fm = l.getFontMetrics(l.getFont()); String str = Objects.toString(value, ""); l.setToolTipText(fm.stringWidth(str) > rect.width ? str : null); return l; } } class BalloonToolTip extends JToolTip { private transient HierarchyListener listener; @Override public void updateUI() { removeHierarchyListener(listener); super.updateUI(); listener = e -> { Component c = e.getComponent(); if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) { // if (w instanceof JWindow) { // System.out.println("Popup$HeavyWeightWindow"); // w.setBackground(new Color(0x0, true)); Optional.ofNullable(SwingUtilities.getRoot(c)) .filter(JWindow.class::isInstance).map(JWindow.class::cast) .ifPresent(w -> w.setBackground(new Color(0x0, true))); } }; addHierarchyListener(listener); setOpaque(false); setBorder(BorderFactory.createEmptyBorder(8, 5, 0, 5)); } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.height = 28; return d; } @Override protected void paintComponent(Graphics g) { Shape s = makeBalloonShape(); Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(getBackground()); g2.fill(s); g2.setColor(getForeground()); g2.draw(s); g2.dispose(); super.paintComponent(g); } private Shape makeBalloonShape() { Insets i = getInsets(); float w = getWidth() - 1f; float h = getHeight() - 1f; float v = i.top * .5f; Path2D triangle = new Path2D.Float(); triangle.moveTo(i.left + v + v, 0f); triangle.lineTo(i.left + v, v); triangle.lineTo(i.left + v + v + v, v); Area area = new Area(new RoundRectangle2D.Float(0f, v, w, h - i.bottom - v, i.top, i.top)); area.add(new Area(triangle)); return area; } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package org.usfirst.frc4946; import edu.wpi.first.wpilibj.SimpleRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class BetaRobot extends SimpleRobot { /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { int a = 0; } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { } }
package am.matcher.dissimilar; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import am.Utility; import am.app.Core; import am.app.lexicon.LexiconBuilderParameters; import am.app.mappingEngine.AbstractMatcher; import am.app.mappingEngine.AbstractMatcherParametersPanel; import am.app.mappingEngine.Alignment; import am.app.mappingEngine.DefaultMatcherParameters; import am.app.mappingEngine.Mapping; import am.app.mappingEngine.MatcherFactory; import am.app.mappingEngine.ReferenceEvaluationData; import am.app.mappingEngine.StringUtil.NormalizerParameter; import am.app.mappingEngine.StringUtil.StringMetrics; import am.app.mappingEngine.qualityEvaluation.QualityMetricRegistry; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher; import am.app.ontology.Ontology; import am.app.ontology.ontologyParser.OntoTreeBuilder; import am.app.ontology.ontologyParser.OntologyDefinition; import am.app.ontology.profiling.OntologyProfiler; import am.app.ontology.profiling.ProfilerRegistry; import am.app.ontology.profiling.manual.ManualOntologyProfiler; import am.app.ontology.profiling.manual.ManualProfilerMatchingParameters; import am.matcher.Combination.CombinationMatcher; import am.matcher.Combination.CombinationParameters; import am.matcher.IterativeInstanceStructuralMatcher.IterativeInstanceStructuralMatcher; import am.matcher.IterativeInstanceStructuralMatcher.IterativeInstanceStructuralParameters; import am.matcher.LexicalSynonymMatcher.LexicalSynonymMatcher; import am.matcher.LexicalSynonymMatcher.LexicalSynonymMatcherParameters; import am.matcher.bsm.BaseSimilarityMatcher; import am.matcher.bsm.BaseSimilarityParameters; import am.matcher.multiWords.MultiWordsMatcher; import am.matcher.multiWords.MultiWordsParameters; import am.matcher.parametricStringMatcher.ParametricStringMatcher; import am.matcher.parametricStringMatcher.ParametricStringParameters; import am.userInterface.MatchingProgressDisplay; import com.hp.hpl.jena.rdf.model.Property; import am.matcher.intraInterCoupling.IntraInterCouplingMatcher; import am.matcher.intraInterCoupling.IntraInterCouplingParameters; import org.apache.log4j.Logger; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters; import am.app.mappingEngine.referenceAlignment.ReferenceEvaluator; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import am.matcher.iic2.iic2; import am.matcher.iic2.iic2Parameters; /** * The matching algorithm for OAEI 2011. * * New features included in this year's matching algorithm: * * */ public class DissimilarMatcher extends AbstractMatcher { private static final long serialVersionUID = -2258529392257305644L; private static String ONTOLOGY_BASE_PATH = "ontologies/benchmarks/"; // Change ONLY IF REQUIRED //private static String ONTOLOGY_BASE_PATH = "ontologies/conference/"; private static String SOURCE_ONTOLOGY = "101"; // Change this for TESTING private static String TARGET_ONTOLOGY = ""; // Change this for TESTING private static Logger log = Logger.getLogger(DissimilarMatcher.class); //This should be false in batch mode & using learning matcher / true for alignment evaluation public DissimilarMatcher(){ super(); needsParam = false; setName("Dissimilar Matcher"); setCategory(MatcherCategory.HYBRID); } public static void main(String[] args) throws Exception { DissimilarMatcher dm = new DissimilarMatcher(); File folder = new File("ontologies/benchmarks/"); File[] listOfFiles = folder.listFiles(); //File folder = new File("ontologies/conference_alignment/"); //File[] listOfFiles = folder.listFiles();// folder.listFiles(); for (File file : listOfFiles) { if (file.isDirectory()) //(file.isFile()) { //String[] tmp_str=file.getName().split("-"); //String tmp_src=tmp_str[0]+".owl"; //String tmp_trg=tmp_str[1].substring(0, tmp_str[1].lastIndexOf('.'))+".owl"; TARGET_ONTOLOGY=file.getName(); System.out.println(TARGET_ONTOLOGY); Ontology source = OntoTreeBuilder.loadOWLOntology(ONTOLOGY_BASE_PATH + SOURCE_ONTOLOGY + "/onto.rdf"); Ontology target = OntoTreeBuilder.loadOWLOntology(ONTOLOGY_BASE_PATH + TARGET_ONTOLOGY + "/onto.rdf"); // Ontology source = OntoTreeBuilder.loadOWLOntology(ONTOLOGY_BASE_PATH // + tmp_src); // Ontology target = OntoTreeBuilder.loadOWLOntology(ONTOLOGY_BASE_PATH // + tmp_trg); source.setDescription(SOURCE_ONTOLOGY); OntologyDefinition def1=new OntologyDefinition(true, source.getURI(), null, null); OntologyDefinition def2=new OntologyDefinition(true, target.getURI(), null, null); def1.largeOntologyMode=false; source.setDefinition(def1); def2.largeOntologyMode=false; target.setDefinition(def2); ManualOntologyProfiler mop=new ManualOntologyProfiler(source, target); dm.setSourceOntology(source); dm.setTargetOntology(target); DissimilarMatcherParameters param = new DissimilarMatcherParameters(); param.threshold = 0.6; param.maxSourceAlign = 1; param.maxTargetAlign = 1; dm.setName(TARGET_ONTOLOGY); dm.setParam(param); try { dm.match(); } catch (Exception e) { log.error("Caught exception when running MyMatcher.", e); } dm.getAlignment(); // run the reference alignment evaluation and output it to the log4j // logger dm.referenceEvaluation(ONTOLOGY_BASE_PATH + TARGET_ONTOLOGY + "/refalign.rdf"); //dm.referenceEvaluation("ontologies/conference_alignment/"+TARGET_ONTOLOGY.substring(0,TARGET_ONTOLOGY.lastIndexOf("."))+".rdf"); } } } private void save_to_file(StringBuilder content, String fileName) { File file_ref = new File("ontologies/refalign/iic_iism/"+fileName+".txt"); // if file doesnt exists, then create it try { if (!file_ref.exists()) { file_ref.createNewFile(); } FileWriter fw = new FileWriter(file_ref.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content.toString()); bw.close(); fw.close(); } catch(IOException e) { e.printStackTrace(); } } private void referenceEvaluation(String pathToReferenceAlignment) throws Exception { // Run the reference alignment matcher to get the list of mappings in // the reference alignment file ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();//(ReferenceAlignmentMatcher) MatcherFactory // .getMatcherInstance(MatchersRegistry.ImportAlignment); // these parameters are equivalent to the ones in the graphical // interface ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters(); parameters.fileName = pathToReferenceAlignment; parameters.format = ReferenceAlignmentMatcher.OAEI; parameters.onlyEquivalence = false; parameters.skipClasses = false; parameters.skipProperties = false; refMatcher.setSourceOntology(this.getSourceOntology()); refMatcher.setTargetOntology(this.getTargetOntology()); // When working with sub-superclass relations the cardinality is always // ANY to ANY if (!parameters.onlyEquivalence) { parameters.maxSourceAlign = AbstractMatcher.ANY_INT; parameters.maxTargetAlign = AbstractMatcher.ANY_INT; } refMatcher.setParam(parameters); // load the reference alignment refMatcher.match(); Alignment<Mapping> referenceSet; if (refMatcher.areClassesAligned() && refMatcher.arePropertiesAligned()) { referenceSet = refMatcher.getAlignment(); // class + properties } else if (refMatcher.areClassesAligned()) { referenceSet = refMatcher.getClassAlignmentSet(); } else if (refMatcher.arePropertiesAligned()) { referenceSet = refMatcher.getPropertyAlignmentSet(); } else { // empty set? -- this should not happen referenceSet = new Alignment<Mapping>(Ontology.ID_NONE, Ontology.ID_NONE); } // the alignment which we will evaluate Alignment<Mapping> myAlignment; if (refMatcher.areClassesAligned() && refMatcher.arePropertiesAligned()) { myAlignment = getAlignment(); } else if (refMatcher.areClassesAligned()) { myAlignment = getClassAlignmentSet(); } else if (refMatcher.arePropertiesAligned()) { myAlignment = getPropertyAlignmentSet(); } else { myAlignment = new Alignment<Mapping>(Ontology.ID_NONE, Ontology.ID_NONE); // empty } // use the ReferenceEvaluator to actually compute the metrics ReferenceEvaluationData rd = ReferenceEvaluator.compare(myAlignment, referenceSet); // optional setRefEvaluation(rd); // output the report StringBuilder report = new StringBuilder(); report.append("Reference Evaluation Complete\n\n").append(getName()) .append("\n\n").append(rd.getReport()).append("\n"); //log.info(report); // use system out if you don't see the log4j output System.out.println(report); save_to_file(report, TARGET_ONTOLOGY); } @Override public String getDescriptionString() { return "The method adopted in the OAEI 2011 competition. This algorithm chooses a matcher configuration automatically."; } public enum SubMatcherID { BSM, PSM, VMM, LSM, MM, IISM, GFM, LWC1, LWC2, LWC3 } private Map<SubMatcherID, AbstractMatcher> matchersByID = new HashMap<SubMatcherID, AbstractMatcher>(); @Override public void match() throws Exception { matchStart(); for( MatchingProgressDisplay mpd : progressDisplays ) mpd.ignoreComplete(true); AbstractMatcher finalResult = null; finalResult = runGeneralPurpose(); for( MatchingProgressDisplay mpd : progressDisplays ) mpd.ignoreComplete(false); if( finalResult != null ) { finalResult.select(); classesMatrix = finalResult.getClassesMatrix(); propertiesMatrix = finalResult.getPropertiesMatrix(); classesAlignmentSet = finalResult.getClassAlignmentSet(); propertiesAlignmentSet = finalResult.getPropertyAlignmentSet(); finalResult = null; } matchEnd(); //System.out.println("Classes alignments found: "+classesAlignmentSet.size()); //System.out.println("Properties alignments found: "+propertiesAlignmentSet.size()); } private AbstractMatcher runGeneralPurpose() throws Exception { // Build the lexicons. LexiconBuilderParameters lexParam = new LexiconBuilderParameters(); lexParam.sourceOntology = sourceOntology; lexParam.targetOntology = targetOntology; lexParam.sourceUseLocalname = true; lexParam.targetUseLocalname = true; lexParam.sourceUseSCSLexicon = false; lexParam.targetUseSCSLexicon = false; lexParam.detectStandardProperties(); Core.getLexiconStore().buildAll(lexParam); List<AbstractMatcher> lwcInputMatchers = new ArrayList<AbstractMatcher>(); final DefaultMatcherParameters param = getParam(); // Ontology profiling ProfilerRegistry entry = ProfilerRegistry.ManualProfiler; OntologyProfiler profiler = null; Constructor<? extends OntologyProfiler> constructor = null; constructor = entry.getProfilerClass().getConstructor(Ontology.class, Ontology.class); //profiler = constructor.newInstance(Core.getInstance().getSourceOntology(), Core.getInstance().getTargetOntology()); profiler = constructor.newInstance(sourceOntology, targetOntology); if(profiler!=null) { profiler.setName(entry); Core.getInstance().setOntologyProfiler(profiler); } ManualOntologyProfiler manualProfiler = (ManualOntologyProfiler) profiler; //MetricsOntologyProfiler metricProfiler=(MetricsOntologyProfiler) profiler; ManualProfilerMatchingParameters profilingMatchingParams = new ManualProfilerMatchingParameters(); profilingMatchingParams.matchSourceClassLocalname = true; profilingMatchingParams.matchSourcePropertyLocalname = true; profilingMatchingParams.matchTargetClassLocalname = true; profilingMatchingParams.matchTargetPropertyLocalname = true; profilingMatchingParams.sourceClassAnnotations = new ArrayList<Property>(); for( Property currentProperty : manualProfiler.getSourceClassAnnotations() ) { if( currentProperty.getLocalName().toLowerCase().contains("label") ) { profilingMatchingParams.sourceClassAnnotations.add(currentProperty); } } profilingMatchingParams.sourcePropertyAnnotations = new ArrayList<Property>(); for( Property currentProperty : manualProfiler.getSourcePropertyAnnotations() ) { if( currentProperty.getLocalName().toLowerCase().contains("label") ) { profilingMatchingParams.sourcePropertyAnnotations.add(currentProperty); } } profilingMatchingParams.targetClassAnnotations = new ArrayList<Property>(); for( Property currentProperty : manualProfiler.getTargetClassAnnotations() ) { if( currentProperty.getLocalName().toLowerCase().contains("label") ) { profilingMatchingParams.targetClassAnnotations.add(currentProperty); } } profilingMatchingParams.targetPropertyAnnotations = new ArrayList<Property>(); for( Property currentProperty : manualProfiler.getTargetPropertyAnnotations() ) { if( currentProperty.getLocalName().toLowerCase().contains("label") ) { profilingMatchingParams.targetPropertyAnnotations.add(currentProperty); } } manualProfiler.setMatchTimeParams(profilingMatchingParams); // BSM if( !isCancelled() ) { //AbstractMatcher psm = MatcherFactory.getMatcherInstance(BaseSimilarityMatcher.class); AbstractMatcher bsm = new BaseSimilarityMatcher(); BaseSimilarityParameters bsmParam = new BaseSimilarityParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); bsmParam.useDictionary = false; setupSubMatcher(bsm, bsmParam); runSubMatcher(bsm, "BSM 1/6"); lwcInputMatchers.add(bsm); } // PSM if( !isCancelled() ) { //AbstractMatcher psm = MatcherFactory.getMatcherInstance(ParametricStringMatcher.class); AbstractMatcher psm = new ParametricStringMatcher(); ParametricStringParameters psmParam = new ParametricStringParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); psmParam.localWeight = 0.33; psmParam.labelWeight = 0.34d; psmParam.commentWeight = 0.33d; psmParam.seeAlsoWeight = 0.00d; psmParam.isDefinedByWeight = 0.00d; psmParam.useLexicons = false; psmParam.useBestLexSimilarity = false; psmParam.measure = StringMetrics.AMSUB_AND_EDIT; psmParam.normParameter = new NormalizerParameter(); psmParam.normParameter.setForOAEI2009(); psmParam.redistributeWeights = true; setupSubMatcher(psm, psmParam); runSubMatcher(psm, "PSM 2/6"); lwcInputMatchers.add(psm); //psm.getClassesMatrix().get(i, j) } // VMM if( !isCancelled() ) { //AbstractMatcher vmm = MatcherFactory.getMatcherInstance(MultiWordsMatcher.class); AbstractMatcher vmm=new MultiWordsMatcher(); MultiWordsParameters vmmParam = new MultiWordsParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); vmmParam.measure = MultiWordsParameters.TFIDF; //only on concepts right now because it should be weighted differently vmmParam.considerInstances = true; vmmParam.considerNeighbors = false; vmmParam.considerConcept = true; vmmParam.considerClasses = false; vmmParam.considerProperties = false; vmmParam.ignoreLocalNames = true; vmmParam.useLexiconSynonyms = true; // May change later. setupSubMatcher(vmm, vmmParam); runSubMatcher(vmm, "VMM 3/6"); lwcInputMatchers.add(vmm); } // LSM if( !isCancelled() ) { //AbstractMatcher lsm = MatcherFactory.getMatcherInstance(LexicalSynonymMatcher.class); AbstractMatcher lsm = new LexicalSynonymMatcher(); LexicalSynonymMatcherParameters lsmParam = new LexicalSynonymMatcherParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); lsmParam.useSynonymTerms = false; setupSubMatcher(lsm, lsmParam); runSubMatcher(lsm, "LSM 4/6"); lwcInputMatchers.add(lsm); } lwcInputMatchers.get(0).getClassesMatrix(); //printMatrix(lwcInputMatchers,0, "first"); /* // IIC2 if( !isCancelled() ) { //AbstractMatcher lsm = MatcherFactory.getMatcherInstance(LexicalSynonymMatcher.class); AbstractMatcher iic2 = new iic2(); iic2Parameters iicParam = new iic2Parameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); //iicParam.useSynonymTerms = false; iic2.setInputMatchers(lwcInputMatchers); setupSubMatcher(iic2, iicParam); runSubMatcher(iic2, "IIC2 4/6"); //lwcInputMatchers.add(iic2); } lwcInputMatchers.get(0).getClassesMatrix(); */ //printMatrix(lwcInputMatchers,0, "second"); AbstractMatcher lastLayer=new CombinationMatcher(); boolean lwc_combination=false; if (lwc_combination) { // LWC AbstractMatcher lwc = null; if( !isCancelled() ) { //lwc = MatcherFactory.getMatcherInstance(CombinationMatcher.class); lwc=new CombinationMatcher(); lwc.setInputMatchers(lwcInputMatchers); CombinationParameters lwcParam = new CombinationParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); lwcParam.combinationType = CombinationParameters.AVERAGECOMB; lwcParam.qualityEvaluation = true; lwcParam.manualWeighted = false; lwcParam.quality = QualityMetricRegistry.LOCAL_CONFIDENCE; setupSubMatcher(lwc, lwcParam); runSubMatcher(lwc, "LWC 6/6"); //return lwc; lastLayer=lwc; } } else { //IIC AbstractMatcher iic = null; if( !isCancelled() ) { //iic = MatcherFactory.getMatcherInstance(IntraInterCouplingMatcher.class); iic=new IntraInterCouplingMatcher(); iic.setInputMatchers(lwcInputMatchers); IntraInterCouplingParameters iicParam = new IntraInterCouplingParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); iicParam.combinationType = IntraInterCouplingParameters.AVERAGECOMB; iicParam.qualityEvaluation = true; iicParam.manualWeighted = false; iicParam.metricType=IntraInterCouplingParameters.BOTH_COUPLING; iicParam.quality = QualityMetricRegistry.LOCAL_CONFIDENCE; setupSubMatcher(iic, iicParam); runSubMatcher(iic, "IIC 6/6"); //return iic; lastLayer=iic; } } //IISM if( !isCancelled() ) { //AbstractMatcher iism = MatcherFactory.getMatcherInstance(IterativeInstanceStructuralMatcher.class); AbstractMatcher iism=new IterativeInstanceStructuralMatcher(); iism.addInputMatcher(lastLayer); IterativeInstanceStructuralParameters iismParam = new IterativeInstanceStructuralParameters(param.threshold, param.maxSourceAlign, param.maxTargetAlign); iismParam.allBoost(); iismParam.setConsiderIndividuals(true); iismParam.setPropertyUsageThreshold(0.6); iismParam.setPropertyValuesThreshold(0.5); iismParam.setRangeDomainThreshold(0.89); iismParam.setSuperclassThreshold(0.6); iismParam.setUsePropertyUsage(true); iismParam.setUsePropertyValues(true); iismParam.setUseRangeDomain(true); iismParam.setUseSuperclasses(true); setupSubMatcher(iism, iismParam); runSubMatcher(iism, "IISM 6/6"); return iism; } return null; } private void setupSubMatcher( AbstractMatcher m, DefaultMatcherParameters p ) { setupSubMatcher(m, p, true); } private void setupSubMatcher( AbstractMatcher m, DefaultMatcherParameters p, boolean progressDelay ) { m.setParameters(p); m.setSourceOntology(sourceOntology); m.setTargetOntology(targetOntology); for( MatchingProgressDisplay mpd : progressDisplays ) m.addProgressDisplay(mpd); m.setUseProgressDelay(progressDelay); m.setPerformSelection(true); } private void runSubMatcher(AbstractMatcher m, String label) throws Exception { long startime = 0, endtime = 0, time = 0; long measure = 1000000; //DissimilarMatcherParameters p = (DissimilarMatcherParameters) param; if( Core.DEBUG ) System.out.println("Running " + m.getRegistryEntry().getMatcherShortName() ); startime = System.nanoTime()/measure; for( MatchingProgressDisplay mpd : progressDisplays ) mpd.setProgressLabel(label); //m.setProgressDisplay(getProgressDisplay()); m.match(); //m.setProgressDisplay(null); if( m.isCancelled() ) { cancel(true); } // the user canceled the matching process endtime = System.nanoTime()/measure; time = (endtime-startime); if( Core.DEBUG ) System.out.println(m.getRegistryEntry().getMatcherShortName() + " completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); /* if(p.showIntermediateMatchers && !m.isCancelled()) { MatchingTask mt = new MatchingTask(m, m.getParam(), new MwbmSelection(), new DefaultSelectionParameters()); Core.getInstance().addMatchingTask(mt); }*/ } @Override public AbstractMatcherParametersPanel getParametersPanel() { if(parametersPanel == null){ parametersPanel = new DissimilarMatcherParametersPanel(); } return parametersPanel; } public AbstractMatcher getSubMatcherByID(SubMatcherID id) { return matchersByID.get(id); } }
package com.reactnativenavigation.e2e.androide2e; import android.support.test.uiautomator.By; import org.junit.Test; public class TopLevelApiTest extends BaseTest { @Test public void switchToTabBasedApp_PassPropsFunction() throws Exception { launchTheApp(); assertMainShown(); elementByText("SWITCH TO TAB BASED APP").click(); assertExists(By.text("This is tab 1")); assertExists(By.text("Hello from a function!")); } @Test public void switchToTabsWithSideMenu() throws Exception { launchTheApp(); assertMainShown(); elementByText("SWITCH TO APP WITH SIDE MENUS").click(); assertExists(By.textStartsWith("This is a side menu center screen tab 1")); swipeRightOpenSideMenu(); assertExists(By.text("This is a left side menu screen")); } @Test public void screenLifecycle() throws Exception { launchTheApp(); assertMainShown(); elementByText("PUSH LIFECYCLE SCREEN").click(); assertExists(By.text("onStart")); elementByText("PUSH TO TEST ONSTOP").click(); assertExists(By.text("onStop")); } @Test public void unmountIsCalledOnPop() throws Exception { launchTheApp(); assertMainShown(); elementByText("PUSH LIFECYCLE SCREEN").click(); elementByText("onStart"); device().pressBack(); assertExists(By.text("componentWillUnmount")); } }
package org.geotools.geopkg; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.logging.Level; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.geotools.TestData; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultTransaction; import org.geotools.data.Transaction; import org.geotools.data.memory.MemoryFeatureCollection; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureReader; import org.geotools.data.simple.SimpleFeatureWriter; import org.geotools.factory.CommonFactoryFinder; import org.geotools.factory.Hints; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.Geometries; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.sql.SqlUtil; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.PropertyDescriptor; import org.opengis.filter.FilterFactory; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.PrecisionModel; public class GeoPackageTest { GeoPackage geopkg; @BeforeClass public static void setUpOnce() { Hints.putSystemDefault(Hints.COMPARISON_TOLERANCE, 1e-9); } @Before public void setUp() throws Exception { geopkg = new GeoPackage(File.createTempFile("geopkg", "db", new File("target"))); geopkg.init(); } @After public void tearDown() throws Exception { geopkg.close(); //for debugging, copy the current geopackage file to a well known file File f = new File("target", "geopkg.db"); if (f.exists()) { f.delete(); } FileUtils.copyFile(geopkg.getFile(), f); } @Test public void testInit() throws Exception { assertTableExists("gpkg_contents"); assertTableExists("gpkg_geometry_columns"); assertTableExists("gpkg_spatial_ref_sys"); assertDefaultSpatialReferencesExist(); assertApplicationId(); } void assertDefaultSpatialReferencesExist() throws Exception { Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_id = -1"); assertEquals(rs.getInt(1), -1); rs = st.executeQuery("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_id = 0"); assertEquals(rs.getInt(1), 0); rs = st.executeQuery("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_id = 4326"); assertEquals(rs.getInt(1), 4326); } catch(Exception e) { fail(e.getMessage()); } finally { st.close(); cx.close(); } } void assertApplicationId() throws Exception { Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery("PRAGMA application_id;"); assertEquals(rs.getInt(1), 0x47503130); } catch(Exception e) { fail(e.getMessage()); } finally { st.close(); cx.close(); } } void assertTableExists(String table) throws Exception { Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); try { st.execute(String.format("SELECT count(*) FROM %s;", table)); } catch(Exception e) { fail(e.getMessage()); } finally { st.close(); cx.close(); } } void assertLastChangedDateString(Calendar startTime, Calendar endTime) throws Exception { final TimeZone tz = TimeZone.getTimeZone("GMT"); // get the date now for comparison final Calendar c = Calendar.getInstance(tz); // this is what should be used for the date string format in the DB final String dateFomratString = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; final SimpleDateFormat sdf = new SimpleDateFormat(dateFomratString); sdf.setTimeZone(tz); try (Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); ResultSet rs = st.executeQuery(String.format("SELECT last_change FROM %s;", GeoPackage.GEOPACKAGE_CONTENTS))){ if (rs.next()) { final String dateString = rs.getString(1); // parse the date with the expected format string Date parsedDate = sdf.parse(dateString); // assert the parsed time is between the start and end time c.setTime(parsedDate); assertTrue("Start time should be less than or equal to last_change time", startTime.compareTo(c) <= 0); assertTrue("End time should be greater than or equal to last_change time", endTime.compareTo(c) >= 0); } } } boolean doesEntryExists(String table, Entry entry) throws Exception { boolean exists = false; Connection cx = geopkg.getDataSource().getConnection(); try { String sql = String.format("SELECT * FROM %s WHERE table_name = ?", table); SqlUtil.PreparedStatementBuilder psb = SqlUtil.prepare(cx, sql).set(entry.getTableName()); PreparedStatement ps = psb.log(Level.FINE).statement(); try { ResultSet rs = ps.executeQuery(); try { while(rs.next()) { exists = true; } } finally { rs.close(); } } finally { ps.close(); } } catch(Exception e) { fail(e.getMessage()); } finally { cx.close(); } return exists; } @Test public void testSRS() throws Exception { Entry entry = new Entry(); entry.setTableName("points"); entry.setDataType(Entry.DataType.Feature); entry.setIdentifier("points"); entry.setBounds(new ReferencedEnvelope(-180,180,-90,90, CRS.decode("EPSG:2000"))); entry.setSrid(2000); geopkg.addGeoPackageContentsEntry(entry); Connection cx = geopkg.getDataSource().getConnection(); try { String sql = String.format("SELECT srs_name FROM %s WHERE srs_id = ?", GeoPackage.SPATIAL_REF_SYS); SqlUtil.PreparedStatementBuilder psb = SqlUtil.prepare(cx, sql).set(2000); PreparedStatement ps = psb.log(Level.FINE).statement(); try { ResultSet rs = ps.executeQuery(); try { assertTrue(rs.next()); assertEquals("epsg:2000", rs.getString(1)); } finally { rs.close(); } } finally { ps.close(); } } catch(Exception e) { fail(e.getMessage()); } finally { cx.close(); } } @Test public void testDeleteGeoPackageContentsEntry() throws Exception { Entry entry = new Entry(); entry.setTableName("points"); entry.setDataType(Entry.DataType.Feature); entry.setIdentifier("points"); entry.setBounds(new ReferencedEnvelope(-180,180,-90,90, CRS.decode("EPSG:4326"))); entry.setSrid(4326); geopkg.addGeoPackageContentsEntry(entry); assertTrue(doesEntryExists(GeoPackage.GEOPACKAGE_CONTENTS, entry)); geopkg.deleteGeoPackageContentsEntry(entry); assertFalse(doesEntryExists(GeoPackage.GEOPACKAGE_CONTENTS, entry)); } @Test public void testDeleteGeometryColumnsEntry() throws Exception { FeatureEntry entry = new FeatureEntry(); entry.setTableName("points"); entry.setDataType(Entry.DataType.Feature); entry.setIdentifier("points"); entry.setBounds(new ReferencedEnvelope(-180,180,-90,90, CRS.decode("EPSG:4326"))); entry.setSrid(4326); entry.setGeometryColumn("geom"); entry.setGeometryType(Geometries.POINT); geopkg.addGeometryColumnsEntry(entry); assertTrue(doesEntryExists(GeoPackage.GEOMETRY_COLUMNS, entry)); geopkg.deleteGeometryColumnsEntry(entry); assertFalse(doesEntryExists(GeoPackage.GEOMETRY_COLUMNS, entry)); } @Test public void testCreateFeatureEntry() throws Exception { ShapefileDataStore shp = new ShapefileDataStore(setUpShapefile()); FeatureEntry entry = new FeatureEntry(); geopkg.add(entry, shp.getFeatureSource(), null); assertTableExists("bugsites"); //check metadata contents assertFeatureEntry(entry); SimpleFeatureReader re = Features.simple(shp.getFeatureReader()); SimpleFeatureReader ra = geopkg.reader(entry, null, null); while(re.hasNext()) { assertTrue(ra.hasNext()); assertSimilar(re.next(), ra.next()); } re.close(); ra.close(); } @Test public void test3DGeometry() throws Exception { //create feature with 3d geometry Point geom = new GeometryFactory(new PrecisionModel(), 4326).createPoint(new Coordinate(5,3,8)); SimpleFeatureTypeBuilder tBuilder = new SimpleFeatureTypeBuilder(); tBuilder.setName( "mytype" ); tBuilder.add( "name", String.class); tBuilder.add( "geom", Geometry.class, 4326); SimpleFeatureType type = tBuilder.buildFeatureType(); SimpleFeatureBuilder fBuilder = new SimpleFeatureBuilder(type); MemoryFeatureCollection featCollection = new MemoryFeatureCollection(type); fBuilder.add("testfeature"); fBuilder.add(geom); featCollection.add(fBuilder.buildFeature("fid-0001")); FeatureEntry entry = new FeatureEntry(); //important, store in database that there is a z entry.setZ(true); geopkg.add(entry, featCollection); assertTableExists("mytype"); //check metadata contents assertFeatureEntry(entry); //read feature and verify dimension SimpleFeatureReader ra = geopkg.reader(entry, null, null); assertTrue(ra.hasNext()); SimpleFeature f = ra.next(); Point readGeom = (Point) f.getAttribute("geom"); assertEquals(3, readGeom.getCoordinateSequence().getDimension()); assertEquals(geom.getCoordinate().z, readGeom.getCoordinate().z, 0.0001); ra.close(); } @Test public void testFunctions() throws Exception { ShapefileDataStore shp = new ShapefileDataStore(setUpShapefile()); SimpleFeatureReader re = Features.simple(shp.getFeatureReader()); FeatureEntry entry = new FeatureEntry(); geopkg.add(entry, shp.getFeatureSource(), null); Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); try { while(re.hasNext()) { SimpleFeature f = re.next(); ResultSet rs = st.executeQuery((String.format( "SELECT ST_MinX(the_geom), ST_MinY(the_geom), ST_MaxX(the_geom), ST_MaxY(the_geom), ST_IsEmpty(the_geom) FROM bugsites WHERE ID=" + f.getProperty("ID").getValue()))); assertEquals(rs.getDouble(1), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMinX(), 0.0001 ); assertEquals(rs.getDouble(2), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMinY(), 0.0001 ); assertEquals(rs.getDouble(3), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMaxX(), 0.0001 ); assertEquals(rs.getDouble(4), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMaxY(), 0.0001 ); assertEquals(rs.getDouble(5)==1, ((Geometry) f.getDefaultGeometry()).isEmpty() ); rs.close(); } } catch(Exception e) { fail(e.getMessage()); } finally { st.close(); cx.close(); re.close(); } } @Test public void testFunctionsNoEnvelope() throws Exception { ShapefileDataStore shp = new ShapefileDataStore(setUpShapefile()); SimpleFeatureReader re = Features.simple(shp.getFeatureReader()); FeatureEntry entry = new FeatureEntry(); geopkg.getWriterConfiguration().setWriteEnvelope(false); geopkg.add(entry, shp.getFeatureSource(), null); Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); try { while(re.hasNext()) { SimpleFeature f = re.next(); ResultSet rs = st.executeQuery((String.format( "SELECT ST_MinX(the_geom), ST_MinY(the_geom), ST_MaxX(the_geom), ST_MaxY(the_geom), ST_IsEmpty(the_geom) FROM bugsites WHERE ID=" + f.getProperty("ID").getValue()))); assertEquals(rs.getDouble(1), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMinX(), 0.0001 ); assertEquals(rs.getDouble(2), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMinY(), 0.0001 ); assertEquals(rs.getDouble(3), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMaxX(), 0.0001 ); assertEquals(rs.getDouble(4), ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal().getMaxY(), 0.0001 ); assertEquals(rs.getDouble(5)==1, ((Geometry) f.getDefaultGeometry()).isEmpty() ); rs.close(); } } catch(Exception e) { fail(e.getMessage()); } finally { st.close(); cx.close(); re.close(); } } @Test public void testSpatialIndexWriting() throws Exception { ShapefileDataStore shp = new ShapefileDataStore(setUpShapefile()); SimpleFeatureCollection coll = shp.getFeatureSource().getFeatures(); FeatureEntry entry = new FeatureEntry(); entry.setBounds(coll.getBounds()); geopkg.create(entry, shp.getSchema()); //write some features before and some after try(SimpleFeatureIterator it = coll.features()) { //some features try(Transaction tx = new DefaultTransaction(); SimpleFeatureWriter w = geopkg.writer(entry, true, null, tx)) { for (int i = 0; i < 3; i++) { SimpleFeature f = it.next(); SimpleFeature g = w.next(); for (PropertyDescriptor pd : coll.getSchema().getDescriptors()) { String name = pd.getName().getLocalPart(); g.setAttribute(name, f.getAttribute(name)); } w.write(); } tx.commit(); } //create spatial index geopkg.createSpatialIndex(entry); //the rest of features try(Transaction tx = new DefaultTransaction(); SimpleFeatureWriter w = geopkg.writer(entry, true, null, tx)) { while(it.hasNext()) { SimpleFeature f = it.next(); SimpleFeature g = w.next(); for (PropertyDescriptor pd : coll.getSchema().getDescriptors()) { String name = pd.getName().getLocalPart(); g.setAttribute(name, f.getAttribute(name)); } w.write(); } tx.commit(); } } //test if the index was properly created try(Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement()) { ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM rtree_bugsites_the_geom"); rs.next(); assertEquals(rs.getInt(1), coll.size()); } } @Test public void testSpatialIndexReading() throws Exception { FilterFactory ff = CommonFactoryFinder.getFilterFactory(); ShapefileDataStore shp = new ShapefileDataStore(setUpShapefile()); FeatureEntry entry = new FeatureEntry(); geopkg.add(entry, shp.getFeatureSource(), null); assertFalse(geopkg.hasSpatialIndex(entry)); geopkg.createSpatialIndex(entry); assertTrue(geopkg.hasSpatialIndex(entry)); Set ids = geopkg.searchSpatialIndex(entry, 590230.0, 4915038.0, 590234.0, 4915040.0); try(SimpleFeatureReader sfr = geopkg.reader(entry, ff.id(ids), null)) { assertTrue(sfr.hasNext()); assertEquals("bugsites.1", sfr.next().getID().toString()); assertFalse(sfr.hasNext()); } } @Test public void testCreateTileEntry() throws Exception { TileEntry e = new TileEntry(); e.setTableName("foo"); e.setBounds(new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84)); e.getTileMatricies().add(new TileMatrix(0, 1, 1, 256, 256, 0.1, 0.1)); e.getTileMatricies().add(new TileMatrix(1, 2, 2, 256, 256, 0.1, 0.1)); geopkg.create(e); assertTileEntry(e); List<Tile> tiles = new ArrayList(); tiles.add(new Tile(0,0,0,new byte[]{0})); tiles.add(new Tile(1,0,0,new byte[]{1})); tiles.add(new Tile(1,0,1,new byte[]{2})); tiles.add(new Tile(1,1,0,new byte[]{3})); tiles.add(new Tile(1,1,1,new byte[]{4})); for (Tile t : tiles) { geopkg.add(e, t); } try(TileReader r = geopkg.reader(e, null, null, null, null, null, null)) { assertTiles(tiles, r); } } @Test public void testListEntries() throws Exception { // grab the start and end time to ensure the last_change time range final TimeZone tz = TimeZone.getTimeZone("GMT"); final Calendar startTime = Calendar.getInstance(tz); testCreateFeatureEntry(); testCreateTileEntry(); final Calendar endTime = Calendar.getInstance(tz); List<FeatureEntry> lf = geopkg.features(); assertEquals(1, lf.size()); assertEquals("bugsites", lf.get(0).getTableName()); // make sure Date format String is fine assertLastChangedDateString(startTime, endTime); List<TileEntry> lt = geopkg.tiles(); assertEquals(1, lt.size()); TileEntry te = lt.get(0); assertEquals("foo", te.getTableName()); assertEquals(2, te.getTileMatricies().size()); } void assertTiles(List<Tile> tiles, TileReader r) throws IOException { for (Tile t : tiles) { assertTrue(r.hasNext()); Tile a = r.next(); assertEquals(t, a); } assertFalse(r.hasNext()); r.close(); } void assertContentEntry(Entry entry) throws Exception { Connection cx = geopkg.getDataSource().getConnection(); try { PreparedStatement ps = cx.prepareStatement("SELECT * FROM gpkg_contents WHERE table_name = ?"); ps.setString(1, entry.getTableName()); ResultSet rs = ps.executeQuery(); assertTrue(rs.next()); assertEquals(entry.getIdentifier(), rs.getString("identifier")); assertEquals(entry.getDescription(), rs.getString("description")); assertEquals(entry.getSrid().intValue(), rs.getInt("srs_id")); assertEquals(entry.getBounds().getMinX(), rs.getDouble("min_x"), 0.1); assertEquals(entry.getBounds().getMinY(), rs.getDouble("min_y"), 0.1); assertEquals(entry.getBounds().getMaxX(), rs.getDouble("max_x"), 0.1); assertEquals(entry.getBounds().getMaxY(), rs.getDouble("max_y"), 0.1); rs.close(); ps.close(); } finally { cx.close(); } } void assertFeatureEntry(FeatureEntry entry) throws Exception { assertContentEntry(entry); Connection cx = geopkg.getDataSource().getConnection(); try { PreparedStatement ps = cx.prepareStatement("SELECT * FROM gpkg_geometry_columns WHERE table_name = ?"); ps.setString(1, entry.getTableName()); ResultSet rs = ps.executeQuery(); assertTrue(rs.next()); assertEquals(entry.getGeometryColumn(), rs.getString("column_name")); assertEquals(entry.getGeometryType(), Geometries.getForName(rs.getString("geometry_type_name"))); assertEquals(entry.getSrid().intValue(), rs.getInt("srs_id")); assertEquals(entry.isZ(), rs.getBoolean("z")); assertEquals(entry.isM(), rs.getBoolean("m")); rs.close(); ps.close(); } finally { cx.close(); } } void assertTileEntry(TileEntry entry) throws Exception { assertContentEntry(entry); Connection cx = geopkg.getDataSource().getConnection(); try { PreparedStatement ps = cx.prepareStatement( "SELECT count(*) from gpkg_tile_matrix WHERE table_name = ?"); ps.setString(1, entry.getTableName()); ResultSet rs = ps.executeQuery(); rs.next(); assertEquals(rs.getInt(1), entry.getTileMatricies().size()); rs.close(); ps.close(); ps = cx.prepareStatement( "SELECT * from gpkg_tile_matrix_set WHERE table_name = ?"); ps.setString(1, entry.getTableName()); rs = ps.executeQuery(); rs.next(); assertEquals(rs.getInt(2), entry.getSrid().intValue()); assertEquals(rs.getDouble(3), entry.getBounds().getMinX(), 0.01); assertEquals(rs.getDouble(4), entry.getBounds().getMinY(), 0.01); assertEquals(rs.getDouble(5), entry.getBounds().getMaxX(), 0.01); assertEquals(rs.getDouble(6), entry.getBounds().getMaxY(), 0.01); assertFalse(rs.next()); rs.close(); ps.close(); //index ps = cx.prepareStatement( "SELECT * from sqlite_master WHERE type='index' and name = ?"); ps.setString(1, entry.getTableName() + "_zyx_idx"); rs = ps.executeQuery(); rs.close(); ps.close(); } finally { cx.close(); } } void assertSimilar(SimpleFeature expected, SimpleFeature actual) { assertNotNull(actual); assertTrue(((Geometry)expected.getDefaultGeometry()).equals( ((Geometry)actual.getDefaultGeometry()))); for (AttributeDescriptor d : expected.getType().getAttributeDescriptors()) { Object e = expected.getAttribute(d.getLocalName()); Object a = actual.getAttribute(d.getLocalName()); if (e instanceof Number) { assertEquals(((Number) e).intValue(), ((Number)a).intValue()); } else { assertEquals(e, a); } } } URL setUpShapefile() throws Exception { File d = File.createTempFile("bugsites", "shp", new File("target")); d.delete(); d.mkdirs(); String[] exts = new String[]{"shp", "shx", "dbf", "prj"}; for (String ext : exts) { if("prj".equals(ext)) { String wkt = CRS.decode("EPSG:26713", true).toWKT(); FileUtils.writeStringToFile(new File(d, "bugsites.prj"), wkt); } else { FileUtils.copyURLToFile(TestData.url("shapes/bugsites." + ext), new File(d, "bugsites." + ext)); } } return DataUtilities.fileToURL(new File(d, "bugsites.shp")); } URL setUpGeoTiff() throws IOException { File d = File.createTempFile("world", "tiff", new File("target")); d.delete(); d.mkdirs(); FileUtils.copyURLToFile(TestData.url("geotiff/world.tiff"), new File(d, "world.tiff")); return DataUtilities.fileToURL(new File(d, "world.tiff")); } URL setUpPNG() throws IOException { File d = File.createTempFile("Pk50095", "png", new File("target")); d.delete(); d.mkdirs(); FileUtils.copyURLToFile(TestData.url(this, "Pk50095.png"), new File(d, "Pk50095.png")); FileUtils.copyURLToFile(TestData.url(this, "Pk50095.pgw"), new File(d, "Pk50095.pgw")); return DataUtilities.fileToURL(new File(d, "Pk50095.png")); } }
/** * Provides ensemble methods. Ensemble methods is a general term used for a type * of meta-learner that combines the results of one or more learning algorithms * together to create an "ensemble" of learned objects. * * @author Justin Basilico * @since 2.0 */ @gov.sandia.cognition.annotation.Documentation package gov.sandia.cognition.learning.algorithm.ensemble;
package ca.firstvoices.nuxeo.enrichers; import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON; import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE; import ca.firstvoices.services.UnpublishedChangesService; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.CoreInstance; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.io.marshallers.json.enrichers.AbstractJsonEnricher; import org.nuxeo.ecm.core.io.registry.reflect.Setup; import org.nuxeo.ecm.core.schema.DocumentType; import org.nuxeo.runtime.api.Framework; @Setup(mode = SINGLETON, priority = REFERENCE) public class UnpublishedChangesEnricher extends AbstractJsonEnricher<DocumentModel> { public static final String NAME = "unpublished_changes"; private static final Log log = LogFactory.getLog(UnpublishedChangesEnricher.class); protected UnpublishedChangesService service = Framework .getService(UnpublishedChangesService.class); public UnpublishedChangesEnricher() { super(NAME); } // Method that will be called when the enricher is asked for @Override public void write(JsonGenerator jg, DocumentModel doc) throws IOException { // We use the Jackson library to generate Json ObjectNode unpublishedChangesJsonObject = constructUnpublishedChangesJSON(doc); jg.writeFieldName(NAME); jg.writeObject(unpublishedChangesJsonObject); } private ObjectNode constructUnpublishedChangesJSON(DocumentModel doc) throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); return CoreInstance.doPrivileged(doc.getCoreSession(), session -> { // JSON object to be returned ObjectNode jsonObj = mapper.createObjectNode(); log.debug("Constructing unpublished changes for doc: " + doc.getId()); // If the document is the correct type then check for unpublished changes using the service. if (checkType(doc)) { boolean unpublishedChanges = service.checkUnpublishedChanges(session, doc); jsonObj.put("unpublished_changes_exist", unpublishedChanges); } return jsonObj; }); } // Helper method to check that the new document is one of the types below private boolean checkType(DocumentModel inputDoc) { DocumentType currentType = inputDoc.getDocumentType(); String[] types = { "FVAlphabet", "FVAudio", "FVBook", "FVBookEntry", "FVBooks", "FVCategories", "FVCategory", "FVCharacter", "FVContributor", "FVContributors", "FVDialect", "FVDictionary", "FVGallery", "FVLanguage", "FVLanguageFamily", "FVLink", "FVLinks", "FVPhrase", "FVPicture", "FVPortal", "FVResources", "FVVideo", "FVWord", }; return Arrays.stream(types).parallel().anyMatch(currentType.toString()::contains); } }
package com.navigation.reactnative; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.transition.Transition; import android.transition.TransitionInflater; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactRootView; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import java.util.HashSet; public class SceneActivity extends Activity implements DefaultHardwareBackBtnHandler { private ReactRootView mReactRootView; public static final String CRUMB = "Navigation.CRUMB"; public static final String APP_KEY = "Navigation.APP_KEY"; public static final String SHARED_ELEMENTS = "Navigation.SHARED_ELEMENTS"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReactRootView = new ReactRootView(this); Bundle props = new Bundle(); props.putInt("crumb", getIntent().getIntExtra(CRUMB, 0)); String appKey = getIntent().getStringExtra(APP_KEY); HashSet<String> sharedElements = (HashSet<String>) getIntent().getSerializableExtra(SHARED_ELEMENTS); mReactRootView.startReactApplication(getReactNativeHost().getReactInstanceManager(), appKey, props); setContentView(mReactRootView); if (sharedElements != null ) { SharedElementTransitioner transitioner = new SharedElementTransitioner(this, sharedElements); mReactRootView.getRootView().setTag(R.id.sharedElementTransitioner, transitioner); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) this.postponeEnterTransition(); final Activity activity = this; mReactRootView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() { @Override public void onChildViewAdded(View view, View view1) { mReactRootView.setOnHierarchyChangeListener(null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Transition transition = TransitionInflater.from(activity).inflateTransition(R.transition.move); getWindow().setSharedElementEnterTransition(transition); activity.startPostponedEnterTransition(); } } @Override public void onChildViewRemoved(View view, View view1) { } }); } private ReactNativeHost getReactNativeHost() { return ((ReactApplication) getApplication()).getReactNativeHost(); } @Override protected void onPause() { super.onPause(); if (getReactNativeHost().hasInstance()) { getReactNativeHost().getReactInstanceManager().onHostPause(this); } } @Override protected void onResume() { super.onResume(); if (getReactNativeHost().hasInstance()) { getReactNativeHost().getReactInstanceManager().onHostResume(this, this); } } @Override protected void onDestroy() { super.onDestroy(); if (mReactRootView != null) { mReactRootView.unmountReactApplication(); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && getReactNativeHost().hasInstance()) { getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); return true; } return super.onKeyUp(keyCode, event); } @Override public void onBackPressed() { if (getReactNativeHost().hasInstance()) { getReactNativeHost().getReactInstanceManager().onBackPressed(); } else { super.onBackPressed(); } } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } }
package com.navigation.reactnative; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.facebook.react.ReactActivity; import com.facebook.react.bridge.GuardedRunnable; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.uimanager.JSTouchDispatcher; import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.views.view.ReactViewGroup; import java.util.HashSet; public class SceneActivity extends ReactActivity implements DefaultHardwareBackBtnHandler { public static final String CRUMB = "Navigation.CRUMB"; public static final String SHARED_ELEMENTS = "Navigation.SHARED_ELEMENTS"; private SceneRootViewGroup rootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int crumb = getIntent().getIntExtra(CRUMB, 0); rootView = new SceneRootViewGroup(getReactNativeHost().getReactInstanceManager().getCurrentReactContext()); if (crumb < NavigationStackView.sceneItems.size()) { View view = NavigationStackView.sceneItems.get(crumb).view; if (view.getParent() != null) ((ViewGroup) view.getParent()).removeView(view); rootView.addView(view); } setContentView(rootView); @SuppressWarnings("unchecked") HashSet<String> sharedElements = (HashSet<String>) getIntent().getSerializableExtra(SHARED_ELEMENTS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sharedElements != null ) { this.postponeEnterTransition(); SharedElementTransitioner transitioner = new SharedElementTransitioner(this, sharedElements); findViewById(android.R.id.content).getRootView().setTag(R.id.sharedElementTransitioner, transitioner); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); int crumb = intent.getIntExtra(CRUMB, 0); if (rootView.getChildCount() > 0) rootView.removeViewAt(0); View view = NavigationStackView.sceneItems.get(crumb).view; if (view.getParent() != null) ((ViewGroup) view.getParent()).removeView(view); rootView.addView(view); } static class SceneRootViewGroup extends ReactViewGroup implements RootView { private boolean hasAdjustedSize = false; private int viewWidth; private int viewHeight; private final JSTouchDispatcher mJSTouchDispatcher = new JSTouchDispatcher(this); public SceneRootViewGroup(Context context) { super(context); } @Override protected void onSizeChanged(final int w, final int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); viewWidth = w; viewHeight = h; updateFirstChildView(); } private void updateFirstChildView() { if (getChildCount() > 0) { hasAdjustedSize = false; final int viewTag = getChildAt(0).getId(); ReactContext reactContext = getReactContext(); reactContext.runOnNativeModulesQueueThread( new GuardedRunnable(reactContext) { @Override public void runGuarded() { (getReactContext()).getNativeModule(UIManagerModule.class) .updateNodeSize(viewTag, viewWidth, viewHeight); } }); } else { hasAdjustedSize = true; } } @Override public void addView(View child, int index, LayoutParams params) { super.addView(child, index, params); if (hasAdjustedSize) { updateFirstChildView(); } } @Override public void handleException(Throwable t) { getReactContext().handleException(new RuntimeException(t)); } private ReactContext getReactContext() { return (ReactContext) getContext(); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher()); return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher()); super.onTouchEvent(event); return true; } @Override public void onChildStartedNativeGesture(MotionEvent androidEvent) { mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, getEventDispatcher()); } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { } private EventDispatcher getEventDispatcher() { ReactContext reactContext = getReactContext(); return reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); } } public static class Crumb1 extends SceneActivity {} public static class Crumb2 extends SceneActivity {} public static class Crumb3 extends SceneActivity {} public static class Crumb4 extends SceneActivity {} public static class Crumb5 extends SceneActivity {} public static class Crumb6 extends SceneActivity {} public static class Crumb7 extends SceneActivity {} public static class Crumb8 extends SceneActivity {} public static class Crumb9 extends SceneActivity {} public static class Crumb10 extends SceneActivity {} public static class Crumb11 extends SceneActivity {} public static class Crumb12 extends SceneActivity {} public static class Crumb13 extends SceneActivity {} public static class Crumb14 extends SceneActivity {} public static class Crumb15 extends SceneActivity {} public static class Crumb16 extends SceneActivity {} public static class Crumb17 extends SceneActivity {} public static class Crumb18 extends SceneActivity {} public static class Crumb19 extends SceneActivity {} public static class Crumb20 extends SceneActivity {} public static Class getActivity(int crumb) { try { return Class.forName("com.navigation.reactnative.SceneActivity$Crumb" + crumb); } catch (ClassNotFoundException e) { return SceneActivity.class; } } }
package org.osmdroid.samplefragments; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import org.osmdroid.R; import org.osmdroid.tileprovider.cachemanager.CacheManager; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.views.MapView; public class SampleCacheDownloaderCustomUI extends BaseSampleFragment implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, TextWatcher, CacheManager.CacheManagerCallback { @Override public String getSampleTitle() { return "Cache Manager with custom UI"; } ProgressDialog progressBar; Button btnCache, executeJob; SeekBar zoom_min; SeekBar zoom_max; EditText cache_north, cache_south, cache_east, cache_west; TextView cache_estimate; CacheManager mgr; AlertDialog downloadPrompt = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.sample_cachemgr, container, false); mMapView = (MapView) root.findViewById(R.id.mapview); btnCache = (Button) root.findViewById(R.id.btnCache); btnCache.setOnClickListener(this); mgr = new CacheManager(mMapView); return root; } @Override public void addOverlays() { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.executeJob: updateEstimate(true); break; case R.id.btnCache: showCacheManagerDialog(); break; } } private void showCacheManagerDialog() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle(R.string.cache_manager); //.setMessage(R.string.cache_manager_description); // set dialog message alertDialogBuilder.setItems(new CharSequence[]{ getResources().getString(R.string.cache_current_size), getResources().getString(R.string.cache_download), getResources().getString(R.string.cancel) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: showCurrentCacheInfo(); break; case 1: downloadJobAlert(); default: dialog.dismiss(); break; } } } ); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); //mgr.possibleTilesInArea(mMapView.getBoundingBox(), 0, 18); // mgr. } private void downloadJobAlert() { //prompt for input params AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view = View.inflate(getActivity(), R.layout.sample_cachemgr_input, null); BoundingBoxE6 boundingBox = mMapView.getBoundingBox(); zoom_max = (SeekBar) view.findViewById(R.id.slider_zoom_max); zoom_max.setMax(mMapView.getMaxZoomLevel()); zoom_max.setOnSeekBarChangeListener(SampleCacheDownloaderCustomUI.this); zoom_min = (SeekBar) view.findViewById(R.id.slider_zoom_min); zoom_min.setMax(mMapView.getMaxZoomLevel()); zoom_min.setProgress(mMapView.getMinZoomLevel()); zoom_min.setOnSeekBarChangeListener(SampleCacheDownloaderCustomUI.this); cache_east = (EditText) view.findViewById(R.id.cache_east); cache_east.setText(boundingBox.getLonEastE6() / 1E6 + ""); cache_north = (EditText) view.findViewById(R.id.cache_north); cache_north.setText(boundingBox.getLatNorthE6() / 1E6 + ""); cache_south = (EditText) view.findViewById(R.id.cache_south); cache_south.setText(boundingBox.getLatSouthE6() / 1E6 + ""); cache_west = (EditText) view.findViewById(R.id.cache_west); cache_west.setText(boundingBox.getLonWestE6() / 1E6 + ""); cache_estimate = (TextView) view.findViewById(R.id.cache_estimate); //change listeners for both validation and to trigger the download estimation cache_east.addTextChangedListener((TextWatcher) this); cache_north.addTextChangedListener((TextWatcher) this); cache_south.addTextChangedListener((TextWatcher) this); cache_west.addTextChangedListener((TextWatcher) this); executeJob = (Button) view.findViewById(R.id.executeJob); executeJob.setOnClickListener(this); builder.setView(view); builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cache_east = null; cache_south = null; cache_estimate = null; cache_north = null; cache_west = null; executeJob = null; zoom_min = null; zoom_max = null; } }); downloadPrompt = builder.create(); downloadPrompt.show(); } /** * if true, start the job * if false, just update the dialog box */ private void updateEstimate(boolean startJob) { try { if (cache_east != null && cache_west != null && cache_north != null && cache_south != null && zoom_max != null && zoom_min != null) { double n = Double.parseDouble(cache_north.getText().toString()); double s = Double.parseDouble(cache_south.getText().toString()); double e = Double.parseDouble(cache_east.getText().toString()); double w = Double.parseDouble(cache_west.getText().toString()); int zoommin = zoom_min.getProgress(); int zoommax = zoom_max.getProgress(); //nesw BoundingBoxE6 bb = new BoundingBoxE6(n, e, s, w); int tilecount = mgr.possibleTilesInArea(bb, zoommin, zoommax); cache_estimate.setText(tilecount + " tiles"); if (startJob) { if (downloadPrompt != null) { downloadPrompt.dismiss(); downloadPrompt = null; } // prepare for a progress bar dialog ( do this first! ) progressBar = new ProgressDialog(SampleCacheDownloaderCustomUI.this.getActivity()); progressBar.setCancelable(true); progressBar.setMessage("Downloading ..."); progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressBar.setProgress(0); //this triggers the download mgr.downloadAreaAsyncNoUI(getActivity(), bb, zoommin, zoommax, SampleCacheDownloaderCustomUI.this); } } } catch (Exception ex) { ex.printStackTrace(); } } private void showCurrentCacheInfo() { Toast.makeText(getActivity(), "Calculating...", Toast.LENGTH_SHORT).show(); new Thread(new Runnable() { @Override public void run() { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle(R.string.cache_manager) .setMessage("Cache Capacity (bytes): " + mgr.cacheCapacity() + "\n" + "Cache Usage (bytes): " + mgr.currentCacheUsage()); // set dialog message alertDialogBuilder.setItems(new CharSequence[]{ getResources().getString(R.string.cancel) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } } ); getActivity().runOnUiThread(new Runnable() { @Override public void run() { // show it // create alert dialog final AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }); } }).start(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateEstimate(false); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateEstimate(false); } @Override public void afterTextChanged(Editable s) { } //cache manager callback @Override public void onTaskComplete() { progressBar.dismiss(); progressBar = null; Toast.makeText(getActivity(), "Download complete!", Toast.LENGTH_LONG).show(); } //cache manager callback @Override public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax) { if (progressBar != null) { progressBar.setProgress(progress); } } //cache manager callback @Override public void downloadStarted() { if (progressBar != null) { progressBar.show(); } } //cache manager callback @Override public void setPossibleTilesInArea(int total) { if (progressBar != null) { progressBar.setMax(total); } } }
package it.rainbowbreeze.picama.logic.twitter; import android.content.Context; import java.util.Set; import java.util.TreeSet; import it.rainbowbreeze.libs.data.RainbowAppPrefsManager; import it.rainbowbreeze.picama.common.ILogFacility; import it.rainbowbreeze.picama.logic.IPictureScraperConfig; public class TwitterScraperConfig implements IPictureScraperConfig { private static final String LOG_TAG = TwitterScraperConfig.class.getSimpleName(); private final TwitterPrefsManager mTwitterPrefsManager; public TwitterScraperConfig(Context appContext, ILogFacility logFacility) { mTwitterPrefsManager = new TwitterPrefsManager(appContext, logFacility); mTwitterPrefsManager.setDefaultValues(false); } public Set<String> getUserNames() { return mTwitterPrefsManager.getTwitterUserNames(); } public void setUserNames(Set<String> userNames) { mTwitterPrefsManager.setTwitterUserNames(userNames); } private class TwitterPrefsManager extends RainbowAppPrefsManager { private static final String PREF_FILENAME = "TwitterPrefs"; public TwitterPrefsManager(Context appContext, ILogFacility logFacility) { super(appContext, PREF_FILENAME, 0, logFacility); } @Override protected void setDefaultValuesInternal() { Set<String> userNames = new TreeSet<>(); userNames.add("EarthBeauties"); //userNames.add("_Paisajes_"); userNames.add("HighFromAbove"); userNames.add("HistoryInPics"); userNames.add("LuoghiDalMondo"); userNames.add("FotoFavolose"); userNames.add("planetepics"); setTwitterUserNames(userNames); } private static final String PREF_TWITTERUSERNAMES = "pref_twitterUserNames"; public Set<String> getTwitterUserNames() { Set<String> result = mAppPreferences.getStringSet(PREF_TWITTERUSERNAMES, null); return null == result ? new TreeSet<String>() : result; } public TwitterPrefsManager setTwitterUserNames(Set<String> newValue) { openSharedEditor(); mSharedEditor.putStringSet(PREF_TWITTERUSERNAMES, newValue); saveIfNeeded(); return this; } } }
//package org.RDKit; import org.junit.*; import static org.junit.Assert.*; import org.RDKit.*; public class WrapperTests { private ROMol mol1; @Before public void setUp() { String smiles="c1ccccc1"; mol1 = RDKFuncs.MolFromSmiles(smiles); } @Test public void testBasics() { assertTrue(mol1.getNumAtoms()==6); assertTrue(mol1.getNumBonds()==6); } @Test public void testAtoms() { assertTrue(mol1.getAtomWithIdx(0).getAtomicNum()==6); assertFalse(mol1.hasAtomBookmark(1)); mol1.setAtomBookmark(mol1.getAtomWithIdx(0),1); assertTrue(mol1.hasAtomBookmark(1)); } @Test public void testBonds() { assertTrue(mol1.getBondWithIdx(0).getBondType()==Bond.BondType.AROMATIC); } @Test public void testSmilesWrite() { String smi=RDKFuncs.MolToSmiles(mol1); assertEquals(smi,"c1ccccc1",smi); } @Test public void testReactionBasics() { ChemicalReaction rxn; rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn.getNumReactantTemplates()==2); assertTrue(rxn.getNumProductTemplates()==1); ROMol r1,r2; r1=RDKFuncs.MolFromSmiles("CC(=O)O"); r2=RDKFuncs.MolFromSmiles("ClCN"); assertTrue(r1.getNumAtoms()==4); assertTrue(r2.getNumAtoms()==3); ROMol_Vect rs= new ROMol_Vect(2); rs.set(0,r1); rs.set(1,r2); ROMol_Vect_Vect ps; ps=rxn.runReactants(rs); assertFalse(ps.isEmpty()); assertTrue(ps.size()==1); assertFalse(ps.get(0).isEmpty()); assertTrue(ps.get(0).size()==1); assertTrue(r1.getNumAtoms()==4); assertTrue(r2.getNumAtoms()==3); assertTrue(ps.get(0).get(0).getNumAtoms()==6); } @Test public void testSubstruct1() { ROMol p; Match_Vect mv; p = RDKFuncs.MolFromSmarts("c"); assertTrue(mol1.hasSubstructMatch(p)); mv=mol1.getSubstructMatch(p); assertTrue(mv.size()==1); assertTrue(mv.get(0).getFirst()==0); assertTrue(mv.get(0).getSecond()==0); } @Test public void testSubstruct2() { ROMol p; Match_Vect mv; p = RDKFuncs.MolFromSmarts("C"); assertFalse(mol1.hasSubstructMatch(p)); mv=mol1.getSubstructMatch(p); assertTrue(mv.size()==0); } @Test public void testSubstruct3() { ROMol p; Match_Vect mv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)CC"); p = RDKFuncs.MolFromSmarts("CN"); mv=m2.getSubstructMatch(p); assertTrue(mv.size()==2); assertTrue(mv.get(0).getFirst()==0); assertTrue(mv.get(0).getSecond()==1); assertTrue(mv.get(1).getFirst()==1); assertTrue(mv.get(1).getSecond()==0); } @Test public void testSubstruct4() { ROMol p; Match_Vect_Vect mvv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)CC"); p = RDKFuncs.MolFromSmarts("CN"); mvv=m2.getSubstructMatches(p); assertTrue(mvv.size()==1); assertTrue(mvv.get(0).size()==2); assertTrue(mvv.get(0).get(0).getFirst()==0); assertTrue(mvv.get(0).get(0).getSecond()==1); assertTrue(mvv.get(0).get(1).getFirst()==1); assertTrue(mvv.get(0).get(1).getSecond()==0); } @Test public void testSubstruct5() { ROMol p; Match_Vect_Vect mvv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)NCC"); p = RDKFuncs.MolFromSmarts("[$(C=O)]N"); mvv=m2.getSubstructMatches(p); assertTrue(mvv.size()==2); assertTrue(mvv.get(0).size()==2); assertTrue(mvv.get(0).get(0).getFirst()==0); assertTrue(mvv.get(0).get(0).getSecond()==1); assertTrue(mvv.get(0).get(1).getFirst()==1); assertTrue(mvv.get(0).get(1).getSecond()==0); assertTrue(mvv.get(1).size()==2); assertTrue(mvv.get(1).get(0).getFirst()==0); assertTrue(mvv.get(1).get(0).getSecond()==1); assertTrue(mvv.get(1).get(1).getFirst()==1); assertTrue(mvv.get(1).get(1).getSecond()==3); } @Test public void testFingerprints1() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); ExplicitBitVect fp1,fp2; fp1=RDKFuncs.RDKFingerprintMol(m1); fp2=RDKFuncs.RDKFingerprintMol(m1); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)==1.0); fp2=RDKFuncs.RDKFingerprintMol(m2); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)<1.0); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)>0.0); } @Test public void testFingerprints2() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); SparseIntVectu32 fp1,fp2; fp1=RDKFuncs.MorganFingerprintMol(m1,2); fp2=RDKFuncs.MorganFingerprintMol(m1,2); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)==1.0); fp2=RDKFuncs.MorganFingerprintMol(m2,2); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)<1.0); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)>0.0); UInt_Pair_Vect v1=fp1.getNonzero(); assertTrue(v1.size()>0); UInt_Pair_Vect v2=fp2.getNonzero(); assertTrue(v2.size()>0); assertTrue(v2.size()>v1.size()); } @Test public void testFingerprints3() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); SparseIntVecti32 fp1,fp2; fp1=RDKFuncs.getAtomPairFingerprint(m1,2,6); fp2=RDKFuncs.getAtomPairFingerprint(m1,2,6); assertTrue(RDKFuncs.DiceSimilaritySIVi32(fp1,fp2)==1.0); fp2=RDKFuncs.getAtomPairFingerprint(m2,2,6); assertEquals(RDKFuncs.DiceSimilaritySIVi32(fp1,fp2),0.66667,.0001); } @Test public void testFingerprints4() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); SparseIntVecti64 fp1,fp2; fp1=RDKFuncs.getTopologicalTorsionFingerprint(m1); fp2=RDKFuncs.getTopologicalTorsionFingerprint(m1); assertTrue(RDKFuncs.DiceSimilaritySIVi64(fp1,fp2)==1.0); fp2=RDKFuncs.getTopologicalTorsionFingerprint(m2); assertEquals(RDKFuncs.DiceSimilaritySIVi64(fp1,fp2),0.3333,.0001); } @Test public void testErrorHandling() { ROMol m1; m1 = RDKFuncs.MolFromSmiles("C1CC"); assertTrue(m1==null); m1 = RDKFuncs.MolFromSmiles("c1cc1"); assertTrue(m1==null); System.err.println("ok!"); ChemicalReaction rxn=RDKFuncs.ReactionFromSmarts("OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn==null); } @Test public void testPickling() { Char_Vect pkl=RDKFuncs.MolToBinary(mol1); ROMol m1 = RDKFuncs.MolFromBinary(pkl); assertTrue(m1.getNumAtoms()==6); assertTrue(m1.getNumBonds()==6); } @Test public void testReactionPickling() { ChemicalReaction rxn; rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn.getNumReactantTemplates()==2); assertTrue(rxn.getNumProductTemplates()==1); Char_Vect pkl=RDKFuncs.RxnToBinary(rxn); ChemicalReaction rxn2=RDKFuncs.RxnFromBinary(pkl); assertTrue(rxn2.getNumReactantTemplates()==2); assertTrue(rxn2.getNumProductTemplates()==1); } @Test public void testReactionToSmarts() { ChemicalReaction rxn; rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn.getNumReactantTemplates()==2); assertTrue(rxn.getNumProductTemplates()==1); String sma=RDKFuncs.ReactionToSmarts(rxn); ChemicalReaction rxn2; rxn2=RDKFuncs.ReactionFromSmarts(sma); assertTrue(rxn2.getNumReactantTemplates()==2); assertTrue(rxn2.getNumProductTemplates()==1); } /*@Test*/ public void testMemory() { for(int i=0;i<1000000;i++){ ROMol m1; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); if((i%1000)==0){ System.err.println("done: "+i); } m1.delete(); } } /*@Test*/ public void testMemory2() { ChemicalReaction rxn; rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn.getNumReactantTemplates()==2); assertTrue(rxn.getNumProductTemplates()==1); ROMol r1,r2; r1=RDKFuncs.MolFromSmiles("CC(=O)O"); r2=RDKFuncs.MolFromSmiles("ClCN"); assertTrue(r1.getNumAtoms()==4); assertTrue(r2.getNumAtoms()==3); for(int i=0;i<1000000;i++){ ROMol_Vect rs= new ROMol_Vect(2); rs.set(0,r1); rs.set(1,r2); ROMol_Vect_Vect ps; ps=rxn.runReactants(rs); if((i%1000)==0){ System.err.println("done: "+i); } ps.delete(); } } /*@Test*/ public void testMemory3() { ROMol m1; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1C2CCC(C(=O)OCCC)CC2"); for(int i=0;i<1000000;i++){ /*SparseIntVecti64 fp1; fp1=RDKFuncs.getTopologicalTorsionFingerprint(m1);*/ SparseIntVectu32 fp1; fp1=RDKFuncs.MorganFingerprintMol(m1,2); if((i%1000)==0){ System.err.println("done: "+i); } fp1.delete(); } } static { try { System.loadLibrary("RDKFuncs"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. Make sure that libRDKFuncs.so is somewhere in your LD_LIBRARY_PATH.\n" + e); System.exit(1); } } public static void main(String args[]) { org.junit.runner.JUnitCore.main("WrapperTests"); } }
public class Amount{ private int cents; private int dollars; public Amount(int dollars, int cents){ this.dollars = dollars; this.cents = cents; } public Amount negate(){ return new Amount(-cents, -dollars); } //@ requires a != null; public Amount subtract(Amount a){ return this.add(a.negate()); } public Amount add(Amount a){ int new_dollars = dollars + a.dollars; int new_cents = cents + a.cents; if (new_cents < -100) { new_cents = new_cents + 100; new_dollars = new_dollars - 1; } if (new_cents > 100) { new_cents = new_cents - 100; new_dollars = new_dollars - 1; } if (new_cents < 0 && new_dollars > 0) { new_cents = new_cents + 100; new_dollars = new_dollars - 1; } if (new_cents >= 0 && new_dollars <= 0) { new_cents = new_cents - 100; new_dollars = new_dollars + 1; } return new Amount(new_dollars,new_cents); } public boolean equal(Amount a) { if (a==null) return false; else return (dollars == a.dollars && cents == a.cents); } }
package com.minggo.plutoandroidexample.common; import android.app.Application; import com.minggo.pluto.Pluto; import com.minggo.pluto.Pluto.DBConfig; public class PlutoApplication extends Application { @Override public void onCreate() { super.onCreate(); bindPluto(); } private void bindPluto(){ Pluto.initPluto(this); Pluto.APP_CACHE_FILE = "com.pluto.example"; Pluto.LOG_SHOW = true; Pluto.URL_DOMAIN = "https://m8en.com"; DBConfig.NAME = "com.pluto.example.db"; DBConfig.VERSION = 1; } }
package com.opcoach.training.rental.ui.views; import java.util.ArrayList; import java.util.Collection; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.RTFTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.URLTransfer; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import com.opcoach.training.rental.RentalAgency; import com.opcoach.training.rental.core.RentalCoreActivator; import com.opcoach.training.rental.ui.RentalUIActivator; public class RentalAgencyView extends ViewPart implements IPropertyChangeListener { public static final String VIEW_ID = "com.opcoach.rental.ui.rentalagencyview"; private TreeViewer agencyViewer; private AgencyLabelProvider labelProvider; public RentalAgencyView() { // TODO Auto-generated constructor stub } @Override public void createPartControl(Composite parent) { agencyViewer = new TreeViewer(parent); agencyViewer.setContentProvider(new AgencyContentProvider()); labelProvider = new AgencyLabelProvider(); agencyViewer.setLabelProvider(labelProvider); Collection<RentalAgency> agencies = new ArrayList<RentalAgency>(); agencies.add(RentalCoreActivator.getAgency()); agencyViewer.setInput(agencies); // Association de la vue sur un contexte d'aide PlatformUI.getWorkbench().getHelpSystem().setHelp(agencyViewer.getControl(), "com.opcoach.training.rental.ui.rentalContext"); // Autorise le popup sur le treeviewer MenuManager menuManager = new MenuManager(); Menu menu = menuManager.createContextMenu(agencyViewer.getControl()); agencyViewer.getControl().setMenu(menu); getSite().registerContextMenu(menuManager, agencyViewer); // L'arbre est draggable DragSource ds = new DragSource(agencyViewer.getControl(), DND.DROP_COPY); Transfer[] ts = new Transfer[] { TextTransfer.getInstance(), RTFTransfer.getInstance(), URLTransfer.getInstance() }; ds.setTransfer(ts); ds.addDragListener(new AgencyTreeDragSourceListener(agencyViewer)); getSite().setSelectionProvider(agencyViewer); } @Override public void init(IViewSite site) throws PartInitException { super.init(site); // On s'enregistre en tant que pref listener sur le preference store... RentalUIActivator.getDefault().getPreferenceStore().addPropertyChangeListener(this); } @Override public void dispose() { RentalUIActivator.getDefault().getPreferenceStore().removePropertyChangeListener(this); super.dispose(); } @Override public void propertyChange(PropertyChangeEvent event) { labelProvider.initPalette(); agencyViewer.refresh(); } @Override public void setFocus() { // TODO Auto-generated method stub } }
package im.actor.core.modules.internal; import java.util.HashMap; import im.actor.core.api.ApiOutPeer; import im.actor.core.api.ApiPeerType; import im.actor.core.api.rpc.RequestCallInProgress; import im.actor.core.api.rpc.RequestDoCall; import im.actor.core.api.rpc.RequestEndCall; import im.actor.core.api.rpc.RequestSendCallSignal; import im.actor.core.api.rpc.RequestSubscribeToCalls; import im.actor.core.api.rpc.ResponseDoCall; import im.actor.core.api.updates.UpdateIncomingCall; import im.actor.core.entity.Peer; import im.actor.core.entity.User; import im.actor.core.modules.AbsModule; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.events.IncomingCall; import im.actor.core.modules.internal.calls.CallActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.ActorSystem; import im.actor.runtime.actors.Props; public class CallsModule extends AbsModule { public CallsModule(ModuleContext context) { super(context); } public static final int CALL_TIMEOUT = 5000; public boolean callsEnabled = true; HashMap<Long, ActorRef> calls = new HashMap<Long, ActorRef>(); public void run() { if (callsEnabled) { request(new RequestSubscribeToCalls()); } } public Command<ResponseDoCall> makeCall(final int uid, final CallCallback callCallback) { return new Command<ResponseDoCall>() { @Override public void start(final CommandCallback<ResponseDoCall> callback) { User u = users().getValue(uid); request(new RequestDoCall(new ApiOutPeer(ApiPeerType.PRIVATE, u.getUid(), u.getAccessHash()), CALL_TIMEOUT), new RpcCallback<ResponseDoCall>() { @Override public void onResult(final ResponseDoCall response) { callback.onResult(response); calls.put(response.getCallId(), ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(response.getCallId(), callCallback, context()); } }), "actor/call")); } @Override public void onError(RpcException e) { callback.onError(e); } }); } }; } public void callInProgress(long callId) { request(new RequestCallInProgress(callId, CALL_TIMEOUT)); } public void answerCall(final long callId, final CallCallback callback) { calls.put(callId, ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(callId, callback, context()); } }), "actor/call")); } //do end call public void endCall(long callId) { request(new RequestEndCall(callId)); ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.EndCall()); } } public void onIncomingCall(long callId, int uid) { if (!calls.keySet().contains(callId)) { context().getEvents().post(new IncomingCall(callId, uid)); } } //on end call update public void onEndCall(long callId) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.EndCall()); } } //after end call update processed by CallActor public void onCallEnded(long callId) { calls.remove(callId); } public void onCallInProgress(long callId, int timeout) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.CallInProgress(timeout)); } } public void sendSignal(long callId, byte[] data) { request(new RequestSendCallSignal(callId, data)); } public void onSignal(long callId, byte[] data) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.Signal(data)); } } public interface CallCallback { void onCallEnd(); void onSignal(byte[] data); } }
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.AnnotationREST; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.AnnotationRequest; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {AnnotationREST.class}) @WebAppConfiguration public class AnnotationControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); private static final int NUMBER_OF_GENERIC_DOCS = 3; private static final String ASSIGNED_BY_PARAM = "assignedBy"; private static final String PAGE_PARAM = "page"; private static final String LIMIT_PARAM = "limit"; private static final String TAXON_ID_PARAM = "taxon"; private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ"; private static final List<String> VALID_ASSIGNED_BY_PARMS = Arrays.asList("ASPGD", "ASPGD,Agbase", "ASPGD_,Agbase", "ASPGD,Agbase_", "ASPGD,Agbase", "BHF-UCL,Agbase", "Roslin_Institute,BHF-UCL,Agbase"); private static final List<String> INVALID_ASSIGNED_BY_PARMS = Arrays.asList("_ASPGD", "ASPGD,_Agbase", "5555,Agbase", "ASPGD,5555,", "4444,5555,"); private MockMvc mockMvc; private List<AnnotationDocument> genericDocs; private static final String RESOURCE_URL = "/QuickGO/services/annotation"; @Autowired protected WebApplicationContext webApplicationContext; @Autowired protected AnnotationRepository repository; @Before public void setup() { repository.deleteAll(); mockMvc = MockMvcBuilders. webAppContextSetup(webApplicationContext) .build(); genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS); repository.save(genericDocs); } //ASSIGNED BY @Test public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy)); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(1)) .andExpect(jsonPath("$.results[0].geneProductId").value(geneProductId)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy1 + "," + assignedBy2)); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(2)) .andExpect(jsonPath("$.results[*].geneProductId", contains(geneProductId1, geneProductId2))) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(ASSIGNED_BY_PARAM, assignedBy1) .param(ASSIGNED_BY_PARAM, assignedBy2)); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(2)) .andExpect(jsonPath("$.results[*].geneProductId", contains(geneProductId1, geneProductId2))) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY)); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(0)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + "," + assignedBy)); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(1)) .andExpect(jsonPath("$.results[0].geneProductId").value(geneProductId)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void invalidAssignedByThrowsAnError() throws Exception { String invalidAssignedBy = "_ASPGD"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, invalidAssignedBy)); response.andDo(print()) .andExpect(status().isBadRequest()); } //TAXON ID @Test public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception { String geneProductId = "P99999"; int taxonId = 2; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "2")); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(1)) .andExpect(jsonPath("$.results[0].geneProductId").value(geneProductId)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception { String geneProductId1 = "P99999"; int taxonId1 = 2; AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1); repository.save(document1); String geneProductId2 = "P99998"; int taxonId2 = 3; AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM, String.valueOf(taxonId1)) .param(TAXON_ID_PARAM, String.valueOf(taxonId2))); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(2)) .andExpect(jsonPath("$.results.[*].geneProductId", contains(geneProductId1, geneProductId2))) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void invalidTaxIdThrowsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "-2")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void retrievesSecondPageOfAllEntriesRequest() throws Exception { int totalEntries = 60; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, "2")); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(totalEntries)) .andExpect(jsonPath("$.results", hasSize(AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE))); } @Test public void pageRequestEqualToAvailablePagesReturns200() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "1")); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(NUMBER_OF_GENERIC_DOCS)) .andExpect(jsonPath("$.results.*").exists()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "0")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanAvailablePagesReturns400() throws Exception { repository.deleteAll(); int existingPages = 4; createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, String.valueOf(existingPages + 1))); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageExceedsMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "101")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageWithinMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(LIMIT_PARAM, "100")); expectResultsInfoExists(response) .andExpect(jsonPath("$.numberOfHits").value(NUMBER_OF_GENERIC_DOCS)) .andExpect(jsonPath("$.results.*").exists()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void limitForPageThrowsErrorWhenNegative() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "-20")); response.andDo(print()) .andExpect(status().isBadRequest()); } private ResultActions expectResultsInfoExists(ResultActions result) throws Exception { return expectFieldsInResults(result) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.pageInfo").exists()) .andExpect(jsonPath("$.pageInfo.resultsPerPage").exists()) .andExpect(jsonPath("$.pageInfo.total").exists()) .andExpect(jsonPath("$.pageInfo.current").exists()); } private ResultActions expectFieldsInResults(ResultActions result) throws Exception { int index = 0; for (int i = 0; i > genericDocs.size(); i++) { expectFields(result, "$.results[" + index++ + "]."); } return result; } private void expectFields(ResultActions result, String path) throws Exception { result .andExpect(jsonPath(path + "id").exists()) .andExpect(jsonPath(path + "geneProductId").exists()) .andExpect(jsonPath(path + "qualifier").exists()) .andExpect(jsonPath(path + "goId").exists()) .andExpect(jsonPath(path + "goEvidence").exists()) .andExpect(jsonPath(path + "ecoId").exists()) .andExpect(jsonPath(path + "reference").exists()) .andExpect(jsonPath(path + "withFrom").exists()) .andExpect(jsonPath(path + "taxonId").exists()) .andExpect(jsonPath(path + "assignedBy").exists()) .andExpect(jsonPath(path + "extensions").exists()); } private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.assignedBy = assignedBy; return doc; } private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.taxonId = taxonId; return doc; } private List<AnnotationDocument> createGenericDocs(int n) { return IntStream.range(0, n) .mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect (Collectors.toList()); } private String createId(int idNum) { return String.format("A0A%03d", idNum); } }