answer
stringlengths
17
10.2M
package io.sigpipe.sing.dataset; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; import io.sigpipe.sing.dataset.feature.Feature; /** * Handles quantization of {@link Feature} values. In other words, a Quantizer * instance takes in high-resolution data and outputs low-resolution values that * represent subdivisions ("buckets" or "tick marks") in the feature space. Each * bucket handles Features for a particular range of values. * <p> * For example, imagine a Quantizer instance set up for values ranging from 0 to * 100, with a step size of 2 (note that each of these values are integers). * Inputting values of 24.6f or 25.9999f would return bucket 24, while 99.9d * would return 98, and 1 would return 0. * <p> * Note that the outputs returned by the Quantizer.quantize() method are not * meant to be 'closest' to their original values; rather, the output values are * simply identifiers for the particular bucket in question. * * @author malensek */ public class Quantizer { private NavigableSet<Feature> ticks = new TreeSet<>(); /** * Constructs a Quantizer with a predefined list of Tick marks. For * incremental construction of a Quantizer instance, see * {@link QuantizerBuilder}. * * @param ticks collection of tick marks to be used during quantization */ public Quantizer(Feature... ticks) { for (Feature tick : ticks) { addTick(tick); } } /** * Constructs a Quantizer with a predefined collection of Tick marks. For * incremental construction of a Quantizer instance, see * {@link QuantizerBuilder}. * * @param ticks collection of tick marks to be used during quantization */ public Quantizer(Collection<Feature> ticks) { for (Feature tick : ticks) { addTick(tick); } } /** * Constructs a Quantizer with start and end points, as well as an * intermediate step size that is used to populate tick marks uniformly * between. Primitive types may be used to parameterize this constructor, * but note that each parameter must be of the same type to avoid ambiguity * during quantization. * * @param start The beginning of the feature range * @param end The end of the feature range * @param step Step size to use for populating intermediate tick marks */ public Quantizer(Object start, Object end, Object step) { this( Feature.fromPrimitiveType(start), Feature.fromPrimitiveType(end), Feature.fromPrimitiveType(step)); } /** * Constructs a Quantizer with start and end points, as well as an * intermediate step size that is used to populate tick marks uniformly * between. Note that each of these features must be of the same * {@link FeatureType} to avoid ambiguity during quantization. * * @param start The beginning of the feature range * @param end The end of the feature range * @param step Step size to use for populating intermediate tick marks */ public Quantizer(Feature start, Feature end, Feature step) { if (start.sameType(end) == false || start.sameType(step) == false) { throw new IllegalArgumentException( "All feature types must be the same"); } Feature tick = new Feature(start); while (tick.less(end)) { addTick(tick); tick = tick.add(step); } } /** * Adds a new tick mark value to this Quantizer. * * @param tick the new tick mark to add */ private void addTick(Feature tick) { ticks.add(tick); } /** * Retrieves the number of tick mark subdivisions in this Quantizer. * * @return number of tick marks */ public int numTicks() { return ticks.size(); } /** * Quantizes a given Feature based on this Quantizer's tick mark * configuration. When quantizing a Feature, a bucket will be retrieved that * represents the Feature in question in the tick mark range. Note that the * bucket returned is not necessarily closest in value to the Feature, but * simply represents its range of values. * * @param feature The Feature to quantize * @return A quantized representation of the Feature */ public Feature quantize(Feature feature) { Feature result = ticks.floor(feature); if (result == null) { return ticks.first(); } return result; } /** * Retrieves the next tick mark value after the given Feature. In other * words, this method will return the bucket after the given Feature's * bucket. If there is no next tick mark (the specified Feature's bucket is * at the end of the range) then this method returns null. * * @param feature Feature to use to locate the next tick mark bucket in the * range. * @return Next tick mark, or null if the end of the range has been reached. */ public Feature nextTick(Feature feature) { return ticks.higher(feature); } /** * Retrieves the tick mark value preceding the given Feature. In other * words, this method will return the bucket before the given Feature's * bucket. If there is no previous tick mark (the specified Feature's bucket * is at the beginning of the range) then this method returns null. * * @param feature Feature to use to locate the previous tick mark bucket in * the range. * @return Next tick mark, or null if the end of the range has been reached. */ public Feature prevTick(Feature feature) { return ticks.lower(feature); } @Override public String toString() { String output = ""; for (Feature f : ticks) { output += f.getString() + System.lineSeparator(); } return output; } /** * Builder that allows incremental creation of a {@link Quantizer}. */ public static class QuantizerBuilder { List<Feature> ticks = new ArrayList<>(); public void addTick(Feature tick) { this.ticks.add(tick); } public void addTicks(Feature... ticks) { for (Feature tick : ticks) { addTick(tick); } } public void removeTick(Feature tick) { this.ticks.remove(tick); } public List<Feature> getTicks() { return new ArrayList<Feature>(ticks); } public Quantizer build() { Quantizer q = new Quantizer(); for (Feature tick : ticks) { q.addTick(tick); } return q; } } }
// @@author A0130195M package jfdi.logic.commands; import jfdi.logic.events.SearchDoneEvent; import jfdi.logic.interfaces.Command; import jfdi.storage.apis.TaskAttributes; import opennlp.tools.stemmer.PorterStemmer; import org.apache.commons.lang3.tuple.ImmutableTriple; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collectors; /** * @author Liu Xinan */ public class SearchCommand extends Command { private static final PorterStemmer stemmer = new PorterStemmer(); private HashSet<String> keywords; private ArrayList<TaskAttributes> results; private SearchCommand(Builder builder) { this.keywords = builder.keywords; } public HashSet<String> getKeywords() { return keywords; } public ArrayList<TaskAttributes> getResults() { return results; } public static class Builder { HashSet<String> keywords = new HashSet<>(); public Builder addKeyword(String keyword) { this.keywords.add(keyword); return this; } public Builder addKeywords(Collection<String> keywords) { this.keywords.addAll(keywords); return this; } public SearchCommand build() { return new SearchCommand(this); } } @Override public void execute() { results = taskDb.getAll().stream() .map(this::constructCandidate) .filter(this::isValidCandidate) .sorted(this::candidateCompareTo) .map(ImmutableTriple::getRight) .collect(Collectors.toCollection(ArrayList::new)); eventBus.post(new SearchDoneEvent(results, keywords)); } private ImmutableTriple<Long, Integer, TaskAttributes> constructCandidate(TaskAttributes task) { String[] parts = task.getDescription().split("\\s+"); int wordCount = parts.length; long rank = Arrays.stream(parts) .map(stemmer::stem) .filter(this::isKeyword) .count(); return new ImmutableTriple<Long, Integer, TaskAttributes>(rank, wordCount, task); } private boolean isValidCandidate(ImmutableTriple<Long, Integer, TaskAttributes> candidate) { return candidate.getLeft() > 0; } private boolean isKeyword(String word) { return keywords.stream() .map(stemmer::stem) .reduce( false, (isMatched, keyword) -> isMatched || word.equalsIgnoreCase(keyword), (isPreviouslyMatched, isNowMatched) -> isPreviouslyMatched || isNowMatched ); } private int candidateCompareTo(ImmutableTriple<Long, Integer, TaskAttributes> left, ImmutableTriple<Long, Integer, TaskAttributes> right) { if (left.getLeft() > right.getLeft()) { return -1; } else if (left.getLeft() < right.getLeft()) { return 1; } else { return left.getMiddle() - right.getMiddle(); } } @Override public void undo() { assert false; } }
package jp.toastkid.slideshow.slide; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import com.jfoenix.controls.JFXProgressBar; import javafx.animation.Interpolator; import javafx.animation.TranslateTransition; import javafx.embed.swing.SwingFXUtils; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.SnapshotParameters; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.image.WritableImage; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Screen; import javafx.util.Duration; /** * Slide implementation. * * @author Toast kid */ public class Slide extends VBox { /** Slide duration. */ private static final Duration TRANSITION_DURATION = Duration.seconds(0.3d); /** Title label's font. */ private static final Font TITLE_MAIN_FONT = new Font(200); /** Header text font. */ private static final Font HEAD_FONT = new Font(150); /** Title label. */ private final Label title; /** For scrollable overflow content. */ private final ScrollPane scroll; /** Contents. */ private final VBox contents; /** * Factory of Slide. * * @author Toast kid */ public static class Builder { private boolean isFront; private String bgImage; private String title; private List<Node> contents; public Builder title(final String title) { this.title = title; return this; } public Builder isFront(final boolean isFront) { this.isFront = isFront; return this; } public Builder addQuotedLines(final String... lines) { Stream.of(lines).map(line -> isFront ? LineFactory.centeredText(line) : LineFactory.normal(line)) .forEach(line -> { line.getStyleClass().add("blockquote"); addContent(line); }); return this; } public Builder addLines(final String... lines) { Stream.of(lines).map(line -> isFront ? LineFactory.centeredText(line) : LineFactory.normal(line)) .forEach(this::addContent); return this; } public Builder withContents(final Node... lines) { Stream.of(lines).forEach(this::addContent); return this; } public Builder background(final String image) { this.bgImage = image; return this; } private void addContent(final Node node) { if (this.contents == null) { this.contents = new ArrayList<>(); } this.contents.add(node); } /** * Return has title in this slide. * @return */ public boolean hasTitle() { return title != null && title.length() != 0; } /** * Return this has background image. * @return */ public boolean hasBgImage() { return bgImage != null && bgImage.length() != 0; } public Slide build() { return new Slide(this); } } /** * Constructor. */ private Slide(final Builder b) { this.scroll = new ScrollPane(); scroll.setHbarPolicy(ScrollBarPolicy.NEVER); scroll.setVbarPolicy(ScrollBarPolicy.NEVER); scroll.setFitToWidth(true); title = new Label(b.title); initTitle(b.isFront); contents = new VBox(); contents.getChildren().addAll(LineFactory.centering(title)); Optional.ofNullable(b.contents).ifPresent(contents.getChildren()::addAll); this.setVisible(false); Optional.ofNullable(b.bgImage).ifPresent(this::setBgImage); if (b.isFront) { HorizontalMarginSetter.invoke(contents); this.getChildren().add(contents); this.setAlignment(Pos.CENTER); } else { scroll.setContent(contents); HorizontalMarginSetter.invoke(scroll); this.getChildren().add(scroll); this.heightProperty().addListener(e -> contents.setPrefHeight(this.getHeight())); } } /** * Init title. */ private void initTitle(final boolean isTitle) { title.setFont(isTitle ? TITLE_MAIN_FONT : HEAD_FONT); title.setWrapText(true); title.getStyleClass().add("title"); title.setMinHeight(Region.USE_PREF_SIZE); } /** * Set background image. * @param n Node * @param image url */ private void setBgImage(final String image) { setStyle( "-fx-background-image: url('" + image + "'); " + "-fx-background-position: center center;" + "-fx-background-size: stretch;" ); } /** * Set indicator. * @param index * @param maxPages */ public void setIndicator(final int index, final int maxPages) { final double progress = (double) index / (double) maxPages; final JFXProgressBar jfxProgressBar = new JFXProgressBar(progress); jfxProgressBar.setPrefWidth(Screen.getPrimary().getBounds().getWidth()); final VBox barBox = new VBox(jfxProgressBar); barBox.setAlignment(Pos.BOTTOM_CENTER); this.getChildren().add(barBox); } /** * Generate image. * @param width image's width * @param height image's height * @return BufferedImage */ public BufferedImage generateImage(final int width, final int height) { final WritableImage image = new WritableImage(width, height); this.snapshot(new SnapshotParameters(), image); return SwingFXUtils.fromFXImage(image, null); } /** * Animate slide to next. */ public void leftIn() { final TranslateTransition back = new TranslateTransition(TRANSITION_DURATION, this); back.setFromX(-2000); back.setToX(0); back.setInterpolator(Interpolator.LINEAR); back.setCycleCount(1); back.play(); } /** * Animate slide to next. */ public void rightIn() { final TranslateTransition next = new TranslateTransition(TRANSITION_DURATION, this); next.setFromX(2000); next.setToX(0); next.setInterpolator(Interpolator.LINEAR); next.setCycleCount(1); next.play(); } /** * Scroll up. */ public void scrollUp() { scroll.setVvalue(scroll.getVvalue() - 0.20d); } /** * Scroll down. */ public void scrollDown() { scroll.setVvalue(scroll.getVvalue() + 0.20d); } /** * Return this slide's content. * @return */ public Pane getContent() { return this.contents; } /** * Return this slide's title. * @return title or empty. */ public String getTitle() { return title != null ? title.getText() : ""; } }
package org.phenotips.data.internal; import org.phenotips.data.Feature; import org.phenotips.data.Patient; import org.phenotips.data.PatientScorer; import org.phenotips.data.PatientSpecificity; import org.xwiki.cache.Cache; import org.xwiki.cache.CacheException; import org.xwiki.cache.CacheManager; import org.xwiki.cache.config.CacheConfiguration; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.component.util.ReflectionUtils; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.test.mockito.MockitoComponentMockingRule; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.Date; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.internal.matchers.CapturingMatcher; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MonarchPatientScorerTest { private ConfigurationSource configuration; @Mock private Patient patient; @Mock private CloseableHttpClient client; @Mock private CloseableHttpResponse response; @Mock private HttpEntity responseEntity; @Mock private Cache<PatientSpecificity> cache; private Set<Feature> features = new LinkedHashSet<>(); @Rule public final MockitoComponentMockingRule<PatientScorer> mocker = new MockitoComponentMockingRule<PatientScorer>(MonarchPatientScorer.class); @Before public void setup() throws CacheException, ComponentLookupException { MockitoAnnotations.initMocks(this); CacheManager cm = this.mocker.getInstance(CacheManager.class); when(cm.<PatientSpecificity>createNewCache(any(CacheConfiguration.class))).thenReturn(this.cache); this.configuration = this.mocker.getInstance(ConfigurationSource.class, "xwikiproperties"); when(this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL", "http://monarchinitiative.org/score")) .thenReturn("http://monarchinitiative.org/score"); Feature feature = mock(Feature.class); when(feature.getId()).thenReturn("HP:1"); when(feature.isPresent()).thenReturn(true); this.features.add(feature); feature = mock(Feature.class); when(feature.getId()).thenReturn("HP:2"); when(feature.isPresent()).thenReturn(false); this.features.add(feature); feature = mock(Feature.class); when(feature.getName()).thenReturn("custom"); this.features.add(feature); ReflectionUtils.setFieldValue(this.mocker.getComponentUnderTest(), "client", this.client); } @Test public void getScoreWithNoFeaturesReturns0() throws ComponentLookupException { Mockito.doReturn(Collections.emptySet()).when(this.patient).getFeatures(); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(0.0, score, 0.0); } @Test public void getScoreSearchesRemotely() throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException { Mockito.doReturn(this.features).when(this.patient).getFeatures(); URI expectedURI = new URIBuilder("http://monarchinitiative.org/score").addParameter("annotation_profile", "{\"features\":[{\"id\":\"HP:1\"},{\"id\":\"HP:2\",\"isPresent\":false}]}").build(); CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>(); when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response); when(this.response.getEntity()).thenReturn(this.responseEntity); when(this.responseEntity.getContent()).thenReturn(IOUtils.toInputStream("{\"scaled_score\":2}")); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI()); Assert.assertEquals(2.0, score, 0.0); } @Test public void getScoreUsesCache() throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException { Mockito.doReturn(this.features).when(this.patient).getFeatures(); PatientSpecificity spec = mock(PatientSpecificity.class); when(this.cache.get("HP:1-HP:2")).thenReturn(spec); when(spec.getScore()).thenReturn(2.0); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(2.0, score, 0.0); Mockito.verifyZeroInteractions(this.client); } @Test public void getScoreWithNoResponseReturnsNegative1() throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException { Mockito.doReturn(this.features).when(this.patient).getFeatures(); URI expectedURI = new URIBuilder("http://monarchinitiative.org/score").addParameter("annotation_profile", "{\"features\":[{\"id\":\"HP:1\"},{\"id\":\"HP:2\",\"isPresent\":false}]}").build(); CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>(); when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response); when(this.response.getEntity()).thenReturn(this.responseEntity); when(this.responseEntity.getContent()).thenReturn(IOUtils.toInputStream("")); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI()); Assert.assertEquals(-1.0, score, 0.0); } @Test public void getScoreWithExceptionReturnsNegative1() throws Exception { Mockito.doReturn(this.features).when(this.patient).getFeatures(); when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException()); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(-1.0, score, 0.0); Mockito.verify(this.cache, Mockito.never()).set(any(String.class), any(PatientSpecificity.class)); } @Test public void getSpecificityWithNoFeaturesReturns0() throws ComponentLookupException { Mockito.doReturn(Collections.emptySet()).when(this.patient).getFeatures(); CapturingMatcher<PatientSpecificity> specCapture = new CapturingMatcher<>(); Mockito.doNothing().when(this.cache).set(Matchers.eq(""), Matchers.argThat(specCapture)); Date d1 = new Date(); this.mocker.getComponentUnderTest().getSpecificity(this.patient); Date d2 = new Date(); PatientSpecificity spec = specCapture.getLastValue(); Assert.assertEquals(0.0, spec.getScore(), 0.0); Assert.assertEquals("monarchinitiative.org", spec.getComputingMethod()); Assert.assertFalse(d1.after(spec.getComputationDate())); Assert.assertFalse(d2.before(spec.getComputationDate())); } @Test public void getSpecificitySearchesRemotely() throws Exception { Mockito.doReturn(this.features).when(this.patient).getFeatures(); URI expectedURI = new URIBuilder("http://monarchinitiative.org/score").addParameter("annotation_profile", "{\"features\":[{\"id\":\"HP:1\"},{\"id\":\"HP:2\",\"isPresent\":false}]}").build(); CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>(); when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response); when(this.response.getEntity()).thenReturn(this.responseEntity); when(this.responseEntity.getContent()).thenReturn(IOUtils.toInputStream("{\"scaled_score\":2}")); CapturingMatcher<PatientSpecificity> specCapture = new CapturingMatcher<>(); Mockito.doNothing().when(this.cache).set(Matchers.eq("HP:1-HP:2"), Matchers.argThat(specCapture)); Date d1 = new Date(); this.mocker.getComponentUnderTest().getSpecificity(this.patient); Date d2 = new Date(); PatientSpecificity spec = specCapture.getLastValue(); Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI()); Assert.assertEquals(2.0, spec.getScore(), 0.0); Assert.assertEquals("monarchinitiative.org", spec.getComputingMethod()); Assert.assertFalse(d1.after(spec.getComputationDate())); Assert.assertFalse(d2.before(spec.getComputationDate())); } @Test public void getSpecificityUsesCache() throws Exception { Mockito.doReturn(this.features).when(this.patient).getFeatures(); PatientSpecificity spec = mock(PatientSpecificity.class); when(this.cache.get("HP:1-HP:2")).thenReturn(spec); Assert.assertSame(spec, this.mocker.getComponentUnderTest().getSpecificity(this.patient)); Mockito.verifyZeroInteractions(this.client); } @Test public void getSpecificityWithNoResponseReturnsNull() throws Exception { Mockito.doReturn(this.features).when(this.patient).getFeatures(); when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response); when(this.response.getEntity()).thenReturn(this.responseEntity); when(this.responseEntity.getContent()).thenReturn(IOUtils.toInputStream("")); Assert.assertNull(this.mocker.getComponentUnderTest().getSpecificity(this.patient)); } @Test(expected = InitializationException.class) public void initializationFailsWhenCreatingCacheFails() throws ComponentLookupException, CacheException, InitializationException { CacheManager cm = this.mocker.getInstance(CacheManager.class); when(cm.<PatientSpecificity>createNewCache(any(CacheConfiguration.class))).thenThrow( new CacheException("failed")); ((org.xwiki.component.phase.Initializable) this.mocker.getComponentUnderTest()).initialize(); } @Test public void checkURLConfigurable() throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException, InitializationException { when(this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL", "http://monarchinitiative.org/score")) .thenReturn("http://proxy/score"); Mockito.doReturn(this.features).when(this.patient).getFeatures(); URI expectedURI = new URIBuilder("http://proxy/score").addParameter("annotation_profile", "{\"features\":[{\"id\":\"HP:1\"},{\"id\":\"HP:2\",\"isPresent\":false}]}").build(); CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>(); when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response); when(this.response.getEntity()).thenReturn(this.responseEntity); when(this.responseEntity.getContent()).thenReturn(IOUtils.toInputStream("{\"scaled_score\":2}")); // Since the component was already initialized in setUp() with the default URL, re-initialize it // with the new configuration mock ((Initializable) this.mocker.getComponentUnderTest()).initialize(); double score = this.mocker.getComponentUnderTest().getScore(this.patient); Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI()); Assert.assertEquals(2.0, score, 0.0);; } }
package logbook.internal.gui; import java.io.IOException; import java.nio.file.Path; import java.text.MessageFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextInputDialog; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import logbook.bean.AppCondition; import logbook.bean.DeckPort; import logbook.bean.Ship; import logbook.bean.ShipCollection; import logbook.bean.ShipMst; import logbook.internal.Items; import logbook.internal.SeaArea; import logbook.internal.Ships; import lombok.val; public class FleetTabPane extends ScrollPane { private DeckPort port; private List<Ship> shipList; private int portHashCode; private int shipsHashCode; /** Tab() */ private String tabCssClass; private double branchCoefficient = 1; @FXML private Label message; @FXML private VBox ships; @FXML private ImageView airSuperiorityImg; @FXML private Label airSuperiority; @FXML private ImageView touchPlaneStartProbabilityImg; @FXML private Label touchPlaneStartProbability; @FXML private ImageView decision33Img; @FXML private Label decision33; @FXML private Button branchCoefficientButton; @FXML private ImageView lvsumImg; @FXML private Label lvsum; @FXML private Label cond; /** * * * @param port */ public FleetTabPane(DeckPort port) { this.port = port; try { FXMLLoader loader = InternalFXMLLoader.load("logbook/gui/fleet_tab.fxml"); loader.setRoot(this); loader.setController(this); loader.load(); } catch (IOException e) { LoggerHolder.LOG.error("FXML", e); } } @FXML void initialize() { this.update(); this.setIcon(); } /** * * * @param event ActionEvent */ @FXML void changeBranchCoefficient(ActionEvent event) { TextInputDialog dialog = new TextInputDialog(Double.toString(this.branchCoefficient)); dialog.getDialogPane().getStylesheets().add("logbook/gui/application.css"); dialog.initOwner(this.getScene().getWindow()); dialog.setTitle(""); dialog.setHeaderText(" )\n" + SeaArea. + " H,I : 1.0\n" + SeaArea.AL + " G : 4.0\n" + SeaArea. + " E,F : 4.0\n" + SeaArea.MS + " F,H : 3.0\n" + SeaArea. + " H : 3.0"); val result = dialog.showAndWait(); if (result.isPresent()) { String value = result.get(); if (!value.isEmpty()) { try { this.branchCoefficient = Double.parseDouble(value); this.setDecision33(); } catch (NumberFormatException e) { } } } } /** * * * @param port */ public void update(DeckPort port) { this.port = port; this.update(); } public void update() { Map<Integer, Ship> shipMap = ShipCollection.get() .getShipMap(); this.shipList = this.port.getShip() .stream() .map(shipMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); if (this.portHashCode != this.port.hashCode() || this.shipsHashCode != this.shipList.hashCode()) { this.updateShips(); } this.portHashCode = this.port.hashCode(); this.shipsHashCode = this.shipList.hashCode(); } /** * CSS * * @return CSS */ public String tabCssClass() { return this.tabCssClass; } private void updateShips() { this.message.setText(this.port.getName()); this.airSuperiority .setText(Integer.toString(this.shipList.stream() .mapToInt(Ships::airSuperiority) .sum())); this.touchPlaneStartProbability .setText((int) Math.floor(Ships.touchPlaneStartProbability(this.shipList) * 100) + "%"); this.setDecision33(); this.lvsum.setText(Integer.toString(this.shipList.stream().mapToInt(Ship::getLv).sum())); ObservableList<Node> childs = this.ships.getChildren(); childs.clear(); this.shipList.stream() .map(FleetTabShipPane::new) .forEach(childs::add); if (this.shipList.stream().anyMatch(Ships::isBadlyDamage)) { this.tabCssClass = "alert"; } else if (this.shipList.stream().anyMatch(Ships::isHalfDamage)) { this.tabCssClass = "warn"; } else if (this.shipList.stream() .anyMatch(ship -> !ship.getFuel().equals(Ships.shipMst(ship).map(ShipMst::getFuelMax).orElse(0)) || !ship.getBull().equals(Ships.shipMst(ship).map(ShipMst::getBullMax).orElse(0)))) { this.tabCssClass = "shortage"; } else if (this.port.getId() > 1 && this.port.getMission().get(0) == 0L) { this.tabCssClass = "empty"; } else { this.tabCssClass = null; } int minCond = this.shipList.stream() .mapToInt(Ship::getCond) .min() .orElse(49); if (minCond < 49) { long cut = AppCondition.get().getCondUpdateTime(); long end = cut + (-Math.floorDiv(49 - minCond, -3) * 180); ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault()); long nowepoch = now.toEpochSecond(); if (end > nowepoch) { ZonedDateTime disp = ZonedDateTime.ofInstant(Instant.ofEpochSecond(end), ZoneId.systemDefault()); DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm"); this.cond.setText(format.format(disp)); } else { this.cond.setText(""); } } else { this.cond.setText(""); } } private void setDecision33() { this.decision33.setText(MessageFormat.format("{0,number, Ships.decision33(this.shipList, this.branchCoefficient))); this.branchCoefficientButton.setText(":" + this.branchCoefficient); } private void setIcon() { Path path; path = Items.itemImageByType(6); if (path != null) { this.airSuperiorityImg.setImage(new Image(path.toUri().toString())); } path = Items.itemImageByType(10); if (path != null) { this.touchPlaneStartProbabilityImg.setImage(new Image(path.toUri().toString())); } path = Items.itemImageByType(9); if (path != null) { this.decision33Img.setImage(new Image(path.toUri().toString())); } path = Items.itemImageByType(28); if (path != null) { this.lvsumImg.setImage(new Image(path.toUri().toString())); } } private static class LoggerHolder { private static final Logger LOG = LogManager.getLogger(FleetTabPane.class); } }
/* * (e-mail:zhongxunking@163.com) */ /* * : * @author 2019-09-14 19:18 */ package org.antframework.configcenter.web.controller.manage; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.antframework.common.util.facade.AbstractResult; import org.antframework.common.util.facade.EmptyResult; import org.antframework.common.util.facade.FacadeUtils; import org.antframework.configcenter.biz.util.Branches; import org.antframework.configcenter.biz.util.Properties; import org.antframework.configcenter.biz.util.PropertyValues; import org.antframework.configcenter.biz.util.Releases; import org.antframework.configcenter.facade.api.BranchService; import org.antframework.configcenter.facade.info.BranchInfo; import org.antframework.configcenter.facade.info.PropertyChange; import org.antframework.configcenter.facade.info.PropertyDifference; import org.antframework.configcenter.facade.info.ReleaseInfo; import org.antframework.configcenter.facade.order.*; import org.antframework.configcenter.facade.result.FindBranchResult; import org.antframework.configcenter.facade.result.FindBranchesResult; import org.antframework.configcenter.facade.result.MergeBranchResult; import org.antframework.configcenter.facade.vo.BranchConstants; import org.antframework.configcenter.facade.vo.Property; import org.antframework.configcenter.web.common.ManagerApps; import org.antframework.configcenter.web.common.OperatePrivileges; import org.antframework.manager.facade.enums.ManagerType; import org.antframework.manager.web.CurrentManagerAssert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; /** * controller */ @RestController @RequestMapping("/manage/branch") @AllArgsConstructor public class BranchController { private final BranchService branchService; /** * * * @param appId id * @param profileId id * @param branchId id * @param releaseVersion */ @RequestMapping("/addBranch") public EmptyResult addBranch(String appId, String profileId, String branchId, Long releaseVersion) { ManagerApps.assertAdminOrHaveApp(appId); AddBranchOrder order = new AddBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); order.setReleaseVersion(releaseVersion); EmptyResult result = branchService.addBranch(order); if (result.isSuccess()) { PropertyValues.revertPropertyValues(appId, profileId, branchId, releaseVersion); } return result; } /** * * * @param appId id * @param profileId id * @param branchId id * @param propertyChange * @param memo */ @RequestMapping("/releaseBranch") public ReleaseBranchResult releaseBranch(String appId, String profileId, String branchId, PropertyChange propertyChange, String memo) { ManagerApps.assertAdminOrHaveApp(appId); if (CurrentManagerAssert.current().getType() != ManagerType.ADMIN) { Set<String> keys = propertyChange.getAddedOrModifiedProperties().stream().map(Property::getKey).collect(Collectors.toSet()); keys.addAll(propertyChange.getDeletedKeys()); OperatePrivileges.assertAdminOrOnlyReadWrite(appId, keys); } ReleaseBranchOrder order = new ReleaseBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); order.setPropertyChange(propertyChange); order.setMemo(memo); ReleaseBranchResult result = branchService.releaseBranch(order); if (result.isSuccess()) { // value PropertyValues.changePropertyValues( appId, profileId, branchId, propertyChange); if (CurrentManagerAssert.current().getType() != ManagerType.ADMIN) { maskRelease(result.getBranch().getRelease()); } } return result; } /** * * * @param appId id * @param profileId id * @param branchId id * @param targetReleaseVersion */ @RequestMapping("/revertBranch") public EmptyResult revertBranch(String appId, String profileId, String branchId, Long targetReleaseVersion) { ManagerApps.assertAdminOrHaveApp(appId); if (CurrentManagerAssert.current().getType() != ManagerType.ADMIN && Objects.equals(branchId, BranchConstants.DEFAULT_BRANCH_ID)) { Set<String> keys = new HashSet<>(); Set<Property> startProperties = Branches.findBranch(appId, profileId, branchId).getRelease().getProperties(); Set<Property> endProperties = Releases.findRelease(appId, profileId, targetReleaseVersion).getProperties(); PropertyDifference difference = Properties.compare(endProperties, startProperties); keys.addAll(difference.getAddedKeys()); keys.addAll(difference.getModifiedValueKeys()); keys.addAll(difference.getModifiedScopeKeys()); keys.addAll(difference.getDeletedKeys()); OperatePrivileges.assertAdminOrOnlyReadWrite(appId, keys); } RevertBranchOrder order = new RevertBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); order.setTargetReleaseVersion(targetReleaseVersion); EmptyResult result = branchService.revertBranch(order); if (result.isSuccess()) { PropertyValues.revertPropertyValues( appId, profileId, branchId, targetReleaseVersion); } return result; } /** * * * @param appId id * @param profileId id * @param branchId id * @param sourceBranchId id */ @RequestMapping("/mergeBranch") public MergeBranchResult mergeBranch(String appId, String profileId, String branchId, String sourceBranchId) { ManagerApps.assertAdminOrHaveApp(appId); if (CurrentManagerAssert.current().getType() != ManagerType.ADMIN && Objects.equals(branchId, BranchConstants.DEFAULT_BRANCH_ID)) { Set<String> keys = new HashSet<>(); ComputeBranchMergenceResult computeBranchMergenceResult = computeBranchMergence( appId, profileId, branchId, sourceBranchId); FacadeUtils.assertSuccess(computeBranchMergenceResult); keys.addAll(computeBranchMergenceResult.getDifference().getAddedKeys()); keys.addAll(computeBranchMergenceResult.getDifference().getModifiedValueKeys()); keys.addAll(computeBranchMergenceResult.getDifference().getModifiedScopeKeys()); keys.addAll(computeBranchMergenceResult.getDifference().getDeletedKeys()); OperatePrivileges.assertAdminOrOnlyReadWrite(appId, keys); } MergeBranchOrder order = new MergeBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); order.setSourceBranchId(sourceBranchId); MergeBranchResult result = branchService.mergeBranch(order); if (result.isSuccess()) { // value PropertyValues.changePropertyValues( appId, profileId, branchId, result.getPropertyChange()); if (CurrentManagerAssert.current().getType() != ManagerType.ADMIN) { Set<Property> properties = result.getPropertyChange().getAddedOrModifiedProperties(); Set<Property> maskedProperties = OperatePrivileges.maskProperties(appId, properties); properties.clear(); properties.addAll(maskedProperties); } } return result; } /** * * * @param appId id * @param profileId id * @param branchId id * @param sourceBranchId id */ @RequestMapping("/computeBranchMergence") public ComputeBranchMergenceResult computeBranchMergence(String appId, String profileId, String branchId, String sourceBranchId) { ManagerApps.assertAdminOrHaveApp(appId); PropertyChange propertyChange = Branches.computeBranchMergence(appId, profileId, branchId, sourceBranchId); Set<Property> oldProperties = Branches.findBranch(appId, profileId, branchId).getRelease().getProperties(); Set<Property> changedProperties = new HashSet<>(); PropertyDifference difference = Properties.compare(propertyChange.getAddedOrModifiedProperties(), oldProperties); difference.getDeletedKeys().clear(); propertyChange.getAddedOrModifiedProperties().stream() .filter(property -> difference.getAddedKeys().contains(property.getKey()) || difference.getModifiedValueKeys().contains(property.getKey()) || difference.getModifiedScopeKeys().contains(property.getKey())) .forEach(changedProperties::add); oldProperties.stream() .filter(property -> propertyChange.getDeletedKeys().contains(property.getKey())) .forEach(property -> { difference.addDeletedKeys(property.getKey()); changedProperties.add(property); }); ComputeBranchMergenceResult result = FacadeUtils.buildSuccess(ComputeBranchMergenceResult.class); if (CurrentManagerAssert.current().getType() == ManagerType.ADMIN) { result.setChangedProperties(changedProperties); } else { result.setChangedProperties(OperatePrivileges.maskProperties(appId, changedProperties)); } result.setDifference(difference); return result; } /** * * * @param appId id * @param profileId id * @param branchId id */ @RequestMapping("/deleteBranch") public EmptyResult deleteBranch(String appId, String profileId, String branchId) { ManagerApps.assertAdminOrHaveApp(appId); if (Objects.equals(branchId, BranchConstants.DEFAULT_BRANCH_ID)) { CurrentManagerAssert.admin(); } DeleteBranchOrder order = new DeleteBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); return branchService.deleteBranch(order); } /** * * * @param appId id * @param profileId id * @param branchId id */ @RequestMapping("/findBranch") public FindBranchResult findBranch(String appId, String profileId, String branchId) { ManagerApps.assertAdminOrHaveApp(appId); FindBranchOrder order = new FindBranchOrder(); order.setAppId(appId); order.setProfileId(profileId); order.setBranchId(branchId); FindBranchResult result = branchService.findBranch(order); if (result.isSuccess() && CurrentManagerAssert.current().getType() != ManagerType.ADMIN) { maskRelease(result.getBranch().getRelease()); } return result; } /** * * * @param appId id * @param profileId id */ @RequestMapping("/findBranches") public FindBranchesResult findBranches(String appId, String profileId) { ManagerApps.assertAdminOrHaveApp(appId); FindBranchesOrder order = new FindBranchesOrder(); order.setAppId(appId); order.setProfileId(profileId); FindBranchesResult result = branchService.findBranches(order); if (result.isSuccess() && CurrentManagerAssert.current().getType() != ManagerType.ADMIN) { result.getBranches().stream().map(BranchInfo::getRelease).forEach(this::maskRelease); } return result; } private void maskRelease(ReleaseInfo release) { Set<Property> maskedProperties = OperatePrivileges.maskProperties(release.getAppId(), release.getProperties()); release.setProperties(maskedProperties); } /** * result */ @Getter @Setter public static class ComputeBranchMergenceResult extends AbstractResult { private Set<Property> changedProperties; private PropertyDifference difference; } }
package mcjty.intwheel.gui; import mcjty.intwheel.InteractionWheel; import mcjty.intwheel.api.IWheelAction; import mcjty.intwheel.api.WheelActionElement; import mcjty.intwheel.playerdata.PlayerProperties; import mcjty.intwheel.playerdata.PlayerWheelConfiguration; import mcjty.intwheel.varia.RenderHelper; import mcjty.lib.tools.MinecraftTools; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class GuiWheelConfig extends GuiScreen { private static final int WIDTH = 256; private static final int HEIGHT = 204; public static final int MARGIN = 4; public static final int SIZE = 30; private int guiLeft; private int guiTop; private static final ResourceLocation background = new ResourceLocation(InteractionWheel.MODID, "textures/gui/wheel_config.png"); public GuiWheelConfig() { } @Override public void initGui() { super.initGui(); guiLeft = (this.width - WIDTH) / 2; guiTop = (this.height - HEIGHT) / 2; } @Override protected void keyTyped(char typedChar, int keyCode) throws IOException { super.keyTyped(typedChar, keyCode); int mouseX = Mouse.getEventX() * this.width / this.mc.displayWidth; int mouseY = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; int cx = mouseX - guiLeft; int cy = mouseY - guiTop; String id = getSelectedActionID(cx, cy); if (id != null) { if (keyCode == Keyboard.KEY_LEFT) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int idx = actions.indexOf(id); if (idx > 0) { String idprev = actions.get(idx - 1); actions.set(idx - 1, id); actions.set(idx, idprev); config.setOrderActions(actions); config.sendToServer(); } } else if (keyCode == Keyboard.KEY_RIGHT) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int idx = actions.indexOf(id); if (idx < actions.size()-1) { String idnext = actions.get(idx+1); actions.set(idx+1, id); actions.set(idx, idnext); config.setOrderActions(actions); config.sendToServer(); } } else if (keyCode == Keyboard.KEY_HOME) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int idx = actions.indexOf(id); if (idx > 0) { String idnext = actions.get(0); actions.set(0, id); actions.set(idx, idnext); config.setOrderActions(actions); config.sendToServer(); } } else if (keyCode == Keyboard.KEY_END) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int idx = actions.indexOf(id); if (idx < actions.size()-1) { String idnext = actions.get(actions.size()-1); actions.set(actions.size()-1, id); actions.set(idx, idnext); config.setOrderActions(actions); config.sendToServer(); } } else if ((typedChar >= 'a' && typedChar <= 'z') || keyCode == Keyboard.KEY_DELETE || keyCode == Keyboard.KEY_BACK) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); if (keyCode == Keyboard.KEY_DELETE || keyCode == Keyboard.KEY_BACK) { config.getHotkeys().remove(id); } else { config.getHotkeys().put(id, keyCode); } config.sendToServer(); } } } @Override public boolean doesGuiPauseGame() { return true; } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); int cx = mouseX - guiLeft; int cy = mouseY - guiTop; List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int selected = getSelectedAction(cx, cy); if (selected >= 0 && selected < actions.size()) { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); String id = actions.get(selected); IWheelAction action = InteractionWheel.registry.get(id); if (action != null) { Boolean enabled = config.isEnabled(id); if (enabled == null) { enabled = action.isDefaultEnabled(); } if (enabled) { config.disable(id); } else { config.enable(id); } config.sendToServer(); } } } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); GlStateManager.enableBlend(); mc.getTextureManager().bindTexture(background); drawTexturedModalRect(guiLeft, guiTop, 0, 0, WIDTH, HEIGHT); drawIcons(); int cx = mouseX - guiLeft; int cy = mouseY - guiTop; String id = getSelectedActionID(cx, cy); if (id != null) { drawTooltip(id); } } private void renderTooltipText(String desc, int dy) { // int width = mc.fontRendererObj.getStringWidth(desc); int x = guiLeft + 5;//(WIDTH - width) / 2; int y = guiTop + 157 + 1 + dy; RenderHelper.renderText(mc, x, y, desc); } private void drawTooltip(String id) { IWheelAction action = InteractionWheel.registry.get(id); if (action != null) { WheelActionElement element = action.createElement(); String desc = element.getDescription(); // String sneakDesc = element.getSneakDescription(); // if (extended && sneakDesc != null) { // desc = sneakDesc; renderTooltipText(desc, 0); renderTooltipText(TextFormatting.YELLOW + "Click to enable/disable this action", 10); renderTooltipText(TextFormatting.YELLOW + "Press 'a' to 'z' to assign hotkey ('del' to remove hotkey)", 20); renderTooltipText(TextFormatting.YELLOW + "Arrows and home/end to order actions", 30); } } private void drawIcons() { PlayerWheelConfiguration config = PlayerProperties.getWheelConfig(MinecraftTools.getPlayer(mc)); Map<String, Integer> hotkeys = config.getHotkeys(); List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int ox = 0; int oy = 0; for (String id : actions) { IWheelAction action = InteractionWheel.registry.get(id); WheelActionElement element = action.createElement(); mc.getTextureManager().bindTexture(new ResourceLocation(element.getTexture())); int txtw = element.getTxtw(); int txth = element.getTxth(); Boolean enabled = config.isEnabled(action.getId()); if (enabled == null) { enabled = action.isDefaultEnabled(); } int u = enabled ? element.getUhigh() : element.getUlow(); int v = enabled ? element.getVhigh() : element.getVlow(); RenderHelper.drawTexturedModalRect(guiLeft + ox * SIZE + MARGIN, guiTop + oy * SIZE + MARGIN, u, v, 31, 31, txtw, txth); if (hotkeys.containsKey(id)) { String keyName = Keyboard.getKeyName(hotkeys.get(id)); RenderHelper.renderText(mc, guiLeft + ox * SIZE + MARGIN +1, guiTop + oy * SIZE + MARGIN +1, keyName); } ox++; if (ox >= 8) { ox = 0; oy++; } } } private int getSelectedAction(int cx, int cy) { if (cx < MARGIN || cy < MARGIN) { return -1; } if (cx > WIDTH || cy > WIDTH) { return -1; } int totw = 8; int i = (cx - MARGIN) / SIZE + totw * ((cy - MARGIN) / SIZE); return i; } private String getSelectedActionID(int cx, int cy) { List<String> actions = InteractionWheel.interactionWheelImp.getSortedActions(MinecraftTools.getPlayer(mc)); int selected = getSelectedAction(cx, cy); if (selected >= 0 && selected < actions.size()) { return actions.get(selected); } return null; } }
package org.apereo.cas.authentication.principal; import org.apereo.cas.util.EncodingUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Encapsulates a Response to send back for a particular service. * * @author Scott Battaglia * @author Arnaud Lesueur * @since 3.1 */ public class DefaultResponse implements Response { /** * Log instance. */ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultResponse.class); /** * Pattern to detect unprintable ASCII characters. */ private static final Pattern NON_PRINTABLE = Pattern.compile("[\\x00-\\x1F\\x7F]+"); private static final int CONST_REDIRECT_RESPONSE_MULTIPLIER = 40; private static final int CONST_REDIRECT_RESPONSE_BUFFER = 100; private static final long serialVersionUID = -8251042088720603062L; private ResponseType responseType; private String url; private Map<String, String> attributes; /** * Instantiates a new response. * * @param responseType the response type * @param url the url * @param attributes the attributes */ protected DefaultResponse(final ResponseType responseType, final String url, final Map<String, String> attributes) { this.responseType = responseType; this.url = url; this.attributes = attributes; } /** * Gets the post response. * * @param url the url * @param attributes the attributes * @return the post response */ public static Response getPostResponse(final String url, final Map<String, String> attributes) { return new DefaultResponse(ResponseType.POST, url, attributes); } /** * Gets header response. * * @param url the url * @param attributes the attributes * @return the header response */ public static Response getHeaderResponse(final String url, final Map<String, String> attributes) { return new DefaultResponse(ResponseType.HEADER, url, attributes); } /** * Gets the redirect response. * * @param url the url * @param parameters the parameters * @return the redirect response */ public static Response getRedirectResponse(final String url, final Map<String, String> parameters) { final StringBuilder builder = new StringBuilder(parameters.size() * CONST_REDIRECT_RESPONSE_MULTIPLIER + CONST_REDIRECT_RESPONSE_BUFFER); final String sanitizedUrl = sanitizeUrl(url); LOGGER.debug("Sanitized URL for redirect response is [{}]", sanitizedUrl); final String[] fragmentSplit = sanitizedUrl.split(" builder.append(fragmentSplit[0]); final String params = parameters.entrySet() .stream() .filter(entry -> entry.getValue() != null).map(entry -> { String param; try { param = String.join("=", entry.getKey(), EncodingUtils.urlEncode(entry.getValue())); } catch (final RuntimeException e) { param = String.join("=", entry.getKey(), entry.getValue()); } return param; }) .collect(Collectors.joining("&")); if (!(params == null || params.isEmpty())) { builder.append(url.contains("?") ? "&" : "?"); builder.append(params); } if (fragmentSplit.length > 1) { builder.append(' builder.append(fragmentSplit[1]); } final String urlRedirect = builder.toString(); LOGGER.debug("Final redirect response is [{}]", urlRedirect); return new DefaultResponse(ResponseType.REDIRECT, urlRedirect, parameters); } @Override public Map<String, String> getAttributes() { return this.attributes; } @Override public Response.ResponseType getResponseType() { return this.responseType; } @Override public String getUrl() { return this.url; } /** * Sanitize a URL provided by a relying party by normalizing non-printable * ASCII character sequences into spaces. This functionality protects * against CRLF attacks and other similar attacks using invisible characters * that could be abused to trick user agents. * * @param url URL to sanitize. * @return Sanitized URL string. */ private static String sanitizeUrl(final String url) { final Matcher m = NON_PRINTABLE.matcher(url); final StringBuffer sb = new StringBuffer(url.length()); boolean hasNonPrintable = false; while (m.find()) { m.appendReplacement(sb, " "); hasNonPrintable = true; } m.appendTail(sb); if (hasNonPrintable) { LOGGER.warn("The following redirect URL has been sanitized and may be sign of attack:\n[{}]", url); } return sb.toString(); } }
// G l y p h M e n u // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.glyph.ui; import omr.glyph.Glyph; import omr.glyph.Shape; import omr.selection.Selection; import omr.util.Dumper; import java.awt.event.*; import java.util.List; import javax.swing.*; import java.util.ArrayList; /** * Class <code>GlyphMenu</code> defines the popup menu which is linked to * the current selection of either one or several glyphs * * @author Herv&eacute; Bitteur * @version $Id$ */ public class GlyphMenu { // Current selection of glyphs private final Selection glyphSetSelection; // Concrete popup menu private final JPopupMenu popup; private final GlyphPane pane; private final ShapeFocus focus; private final ConfirmAction confirmAction = new ConfirmAction(); private final JMenuItem confirmItem; private final DumpAction dumpAction = new DumpAction(); private final JMenuItem dumpItem; private final DeassignAction deassignAction = new DeassignAction(); private final JMenuItem deassignItem; private final SimilarAction similarAction = new SimilarAction(); private final JMenuItem similarItem; private final JMenu assignMenu; private final JMenu compoundMenu; private final JMenuItem latestAssign; // GlyphMenu // /** * Create the popup menu * * @param pane the top companion * @param focus the current shape focus * @param glyphSetSelection the currently selected glyphs */ public GlyphMenu (final GlyphPane pane, ShapeFocus focus, Selection glyphSetSelection) { popup = new JPopupMenu(); this.pane = pane; this.focus = focus; this.glyphSetSelection = glyphSetSelection; // Confirm current guess confirmItem = popup.add(confirmAction); confirmItem.setToolTipText("Confirm current guess"); popup.addSeparator(); // Deassign selected glyph(s) deassignItem = popup.add(deassignAction); deassignItem.setToolTipText("Deassign selected glyph(s)"); // Manually assign a shape assignMenu = new JMenu("Force to"); // Direct link to latest shape assigned latestAssign = new JMenuItem("no shape", null); latestAssign.setToolTipText("Assign latest shape"); latestAssign.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); Shape shape = Shape.valueOf(source.getText()); pane.assignShape(shape, /* asGuessed => */ false, /* compound => */ false); } }); assignMenu.add(latestAssign); assignMenu.addSeparator(); Shape.addShapeItems (assignMenu, new ActionListener() { public void actionPerformed (ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); Shape shape = Shape.valueOf(source.getText()); pane.assignShape(shape, /* asGuessed => */ false, /* compound => */ false); } }); assignMenu.setToolTipText("Manually force an assignment"); popup.add(assignMenu); popup.addSeparator(); // Build a compound compoundMenu = new JMenu("Build compound"); Shape.addShapeItems (compoundMenu, new ActionListener() { public void actionPerformed (ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); Shape shape = Shape.valueOf(source.getText()); pane.assignShape(shape, /* asGuessed => */ false, /* compound => */ true); } }); compoundMenu.setToolTipText("Manually build a compound"); popup.add(compoundMenu); popup.addSeparator(); // Dump current glyph dumpItem = popup.add(dumpAction); dumpItem.setToolTipText("Dump this glyph"); popup.addSeparator(); // Display all glyphs of the same shape similarItem = popup.add(similarAction); similarItem.setToolTipText("Display all similar glyphs"); } // getPopup // /** * Report the concrete popup menu * * @return the popup menu */ public JPopupMenu getPopup() { return popup; } // updateForGlyph // /** * Update the popup menu when one glyph is selected as current * * @param glyph the current glyph */ public void updateForGlyph (Glyph glyph) { // No compound for a single glyph compoundMenu.setEnabled(false); // Confirm or Assign if (glyph.getShape() == null) { if (glyph.getGuess() == null) { confirmAction.setEnabled(false); confirmItem.setIcon(null); confirmItem.setText("Confirm"); confirmItem.setToolTipText("No guess for this glyph"); } else { confirmAction.setTargetShape(glyph.getGuess()); confirmAction.setEnabled(true); confirmItem.setIcon(glyph.getGuess().getIcon()); if (focus.getCurrent() == glyph.getGuess()) { confirmItem.setText("Confirm " + glyph.getGuess()); confirmItem.setToolTipText("Confirm this glyph is a " + glyph.getGuess()); } else { confirmItem.setText("Assign " + glyph.getGuess()); confirmItem.setToolTipText("Assign this glyph as a " + glyph.getGuess()); } } } else { if (focus.getCurrent() == null) { confirmAction.setEnabled(false); confirmItem.setIcon(null); confirmItem.setText("Confirm"); confirmItem.setToolTipText("No focus defined"); } else { confirmAction.setTargetShape(glyph.getGuess()); if (glyph.getGuess() != null) { confirmItem.setIcon(glyph.getGuess().getIcon()); } if (focus.getCurrent() == glyph.getGuess()) { confirmAction.setEnabled(true); confirmItem.setText("Confirm " + glyph.getGuess()); confirmItem.setToolTipText("Confirm this glyph is a " + glyph.getGuess()); } else { confirmAction.setEnabled(true); confirmItem.setText("Force " + glyph.getGuess()); confirmItem.setToolTipText("Force this glyph as a " + glyph.getGuess()); } } } assignMenu.setText("Force assignment to"); updateLatestAssign(); // Dump dumpItem.setText("Dump glyph"); // Deassign deassignAction.setEnabled(glyph.isKnown()); if (glyph.getShape() == Shape.COMBINING_STEM) { deassignItem.setText("Cancel this stem"); deassignItem.setToolTipText("Remove this selected stem"); } else { deassignItem.setText("Deassign"); deassignItem.setToolTipText("Deassign selected glyph"); } // Show similar if (glyph.getShape() == null) { if (glyph.getGuess() == null) { similarAction.setEnabled(false); similarItem.setText("Show similar"); } else { similarAction.setEnabled(true); similarItem.setText("Show similar " + glyph.getGuess() + "'s"); } } else { similarAction.setEnabled(true); similarItem.setText("Show similar " + glyph.getShape() + "'s"); } } // updateForGlyphs // /** * Update the popup menu when there are several glyphs selected (more * than one) * * @param glyphs the collection of current glyphs */ public void updateForGlyphs (List<Glyph> glyphs) { // Check that some candidate glyphs are consistent with current // focus int consistentNb = 0; if (focus.getCurrent() != null) { for (Glyph glyph : glyphs) { if (!glyph.isKnown() && (glyph.getGuess() == focus.getCurrent())) { consistentNb++; } } } if (consistentNb > 0) { confirmAction.setEnabled(true); confirmAction.setTargetShape(focus.getCurrent()); confirmItem.setText("Confirm " + consistentNb + " " + focus.getCurrent()); confirmItem.setToolTipText("Confirm " + consistentNb + " glyphs as " + focus.getCurrent()); } else { confirmAction.setEnabled(false); confirmItem.setText("No candidate"); confirmItem.setToolTipText ("No glyph consistent with current focus on " + focus.getCurrent()); } // Assign assignMenu.setText("Assign each of these " + glyphs.size() + " glyphs as"); updateLatestAssign(); // Compound if (glyphs.size() > 1) { compoundMenu.setEnabled(true); compoundMenu.setText("Build one " + glyphs.size() + "-glyph Compound as"); } else { compoundMenu.setEnabled(false); compoundMenu.setText("No compound"); } // Dump dumpItem.setText("Dump " + glyphs.size() + " glyphs"); // Deassign, check what is to be deassigned int knownNb = 0; int stemNb = 0; for (Glyph glyph : (List<Glyph>) glyphSetSelection.getEntity()) { if (glyph.isKnown()) { knownNb++; if (glyph.getShape() == Shape.COMBINING_STEM) { stemNb++; } } } if (knownNb > 0) { deassignAction.setEnabled(true); deassignItem.setText("Deassign " + knownNb + " glyphs" + ((stemNb > 0) ? " w/ " + stemNb + " stems": "")); deassignItem.setToolTipText("Deassign selected glyphs"); } else { deassignAction.setEnabled(false); deassignItem.setText("Deassign"); deassignItem.setToolTipText("No glyphs to deassign"); } } // updateLatestAssign // private void updateLatestAssign() { if (pane.getLatestShapeAssigned() != null) { latestAssign.setEnabled(true); latestAssign.setText(pane.getLatestShapeAssigned().toString()); } else { latestAssign.setEnabled(false); latestAssign.setText("no shape"); } } // ConfirmAction // private class ConfirmAction extends AbstractAction { // Shape that could be assigned or confirmed private Shape targetShape; public ConfirmAction () { super("Confirm Guess"); } public void setTargetShape (Shape targetShape) { this.targetShape = targetShape; } public void actionPerformed (ActionEvent e) { pane.assignShape(targetShape, /* asGuessed => */ true, /* compound => */ false); } } // DeassignAction // private class DeassignAction extends AbstractAction { public DeassignAction () { super("Deassign"); } public void actionPerformed (ActionEvent e) { // First phase, putting the stems apart List<Glyph> stems = new ArrayList<Glyph>(); for (Glyph glyph : (List<Glyph>) glyphSetSelection.getEntity()) { if (glyph.getShape() == Shape.COMBINING_STEM) { stems.add(glyph); } else { if (glyph.isKnown()) { pane.setShape(glyph, null, /* UpdateUI => */ true); } } } // Second phase dedicated to stems, if any if (stems.size() > 0) { pane.cancelStems(stems); } focus.colorizeAllGlyphs(); // TBI } } // DumpAction // private class DumpAction extends AbstractAction { public DumpAction () { super("Dump Glyph"); } public void actionPerformed (ActionEvent e) { for (Glyph glyph : (List<Glyph>) glyphSetSelection.getEntity()) { Dumper.dump(glyph); } } } // SimilarAction // private class SimilarAction extends AbstractAction { public SimilarAction () { super("Show Similars"); } public void actionPerformed (ActionEvent e) { List<Glyph> glyphs = (List<Glyph>) glyphSetSelection.getEntity(); if (glyphs.size() == 1) { Glyph glyph = glyphs.get(0); if (glyph.getShape() != null) { focus.setCurrent(glyph.getShape()); } else { focus.setCurrent(glyph.getGuess()); } } } } }
package com.telefonica.euro_iaas.paasmanager.manager.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import com.telefonica.euro_iaas.commons.dao.AlreadyExistsEntityException; import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException; import com.telefonica.euro_iaas.commons.dao.InvalidEntityException; import com.telefonica.euro_iaas.paasmanager.dao.EnvironmentInstanceDao; import com.telefonica.euro_iaas.paasmanager.dao.TierInstanceDao; import com.telefonica.euro_iaas.paasmanager.exception.InfrastructureException; import com.telefonica.euro_iaas.paasmanager.exception.InvalidEnvironmentRequestException; import com.telefonica.euro_iaas.paasmanager.exception.InvalidOVFException; import com.telefonica.euro_iaas.paasmanager.exception.InvalidProductInstanceRequestException; import com.telefonica.euro_iaas.paasmanager.exception.InvalidVappException; import com.telefonica.euro_iaas.paasmanager.exception.NotUniqueResultException; import com.telefonica.euro_iaas.paasmanager.exception.ProductInstallatorException; import com.telefonica.euro_iaas.paasmanager.installator.ProductInstallator; import com.telefonica.euro_iaas.paasmanager.manager.EnvironmentInstanceManager; import com.telefonica.euro_iaas.paasmanager.manager.EnvironmentManager; import com.telefonica.euro_iaas.paasmanager.manager.InfrastructureManager; import com.telefonica.euro_iaas.paasmanager.manager.ProductInstanceManager; import com.telefonica.euro_iaas.paasmanager.manager.ProductReleaseManager; import com.telefonica.euro_iaas.paasmanager.manager.TierInstanceManager; import com.telefonica.euro_iaas.paasmanager.manager.TierManager; import com.telefonica.euro_iaas.paasmanager.model.Attribute; import com.telefonica.euro_iaas.paasmanager.model.ClaudiaData; import com.telefonica.euro_iaas.paasmanager.model.Environment; import com.telefonica.euro_iaas.paasmanager.model.EnvironmentInstance; import com.telefonica.euro_iaas.paasmanager.model.InstallableInstance.Status; import com.telefonica.euro_iaas.paasmanager.model.ProductInstance; import com.telefonica.euro_iaas.paasmanager.model.ProductRelease; import com.telefonica.euro_iaas.paasmanager.model.Tier; import com.telefonica.euro_iaas.paasmanager.model.TierInstance; import com.telefonica.euro_iaas.paasmanager.model.searchcriteria.EnvironmentInstanceSearchCriteria; import com.telefonica.euro_iaas.paasmanager.util.EnvironmentUtils; import com.telefonica.euro_iaas.paasmanager.util.SystemPropertiesProvider; import com.telefonica.euro_iaas.sdc.model.dto.ChefClient; public class EnvironmentInstanceManagerImpl implements EnvironmentInstanceManager { private EnvironmentInstanceDao environmentInstanceDao; private TierInstanceDao tierInstanceDao; private SystemPropertiesProvider systemPropertiesProvider; private ProductInstanceManager productInstanceManager; private EnvironmentManager environmentManager; private InfrastructureManager infrastructureManager; private TierInstanceManager tierInstanceManager; private TierManager tierManager; private ProductReleaseManager productReleaseManager; private EnvironmentUtils environmentUtils; private ProductInstallator productInstallator; /** The log. */ private static Logger log = Logger.getLogger(EnvironmentInstanceManagerImpl.class); /** Max lenght of an OVF */ private static final Integer tam_max = 90000; /* * (non-Javadoc) * @see com.telefonica.euro_iaas.paasmanager.manager.EnvironmentInstanceManager #findByCriteria * (com.telefonica.euro_iaas.paasmanager.model.searchcriteria. EnvironmentInstanceSearchCriteria) */ public List<EnvironmentInstance> findByCriteria(EnvironmentInstanceSearchCriteria criteria) { return environmentInstanceDao.findByCriteria(criteria); } /* * (non-Javadoc) * @see com.telefonica.euro_iaas.paasmanager.manager.EnvironmentInstanceManager #findAll() */ public List<EnvironmentInstance> findAll() { return environmentInstanceDao.findAll(); } public EnvironmentInstance create(ClaudiaData claudiaData, EnvironmentInstance environmentInstance) throws AlreadyExistsEntityException, InvalidEntityException, EntityNotFoundException, InvalidVappException, InvalidOVFException, InfrastructureException, ProductInstallatorException { Environment environment = insertEnvironemntInDatabase(claudiaData, environmentInstance.getEnvironment()); if (environmentInstance.getEnvironment().getOvf() != null) environment.setOvf(environmentInstance.getEnvironment().getOvf()); // environmentInstance.setVdc(claudiaData.getVdc()); environmentInstance.setName(environmentInstance.getVdc() + "-" + environment.getName()); //with this set we loose the productRelease Attributes environmentInstance.setEnvironment(environment); environmentInstance.setStatus(Status.INIT); environmentInstance = insertEnvironenttInstanceInDatabase(environmentInstance); log.info("Creating the infrastructure"); environmentInstance.setStatus(Status.DEPLOYING); environmentInstanceDao.update(environmentInstance); try { environmentInstance = infrastructureManager.createInfrasctuctureEnvironmentInstance(environmentInstance, environment.getTiers(), claudiaData); } catch (InvalidVappException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new InvalidVappException(e); } catch (InvalidOVFException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new InvalidOVFException(e); } catch (InfrastructureException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new InfrastructureException(e); } // environment = environmentUtils.resolveMacros(environmentInstance); // environmentManager.update(environment); environmentInstance.setStatus(Status.INSTALLING); environmentInstanceDao.update(environmentInstance); log.info("Installing software"); boolean bScalableEnvironment; try { bScalableEnvironment = installSoftwareInEnvironmentInstance(claudiaData, environmentInstance); } catch (ProductInstallatorException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new ProductInstallatorException(e); } catch (InvalidProductInstanceRequestException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new ProductInstallatorException(e); } catch (NotUniqueResultException e) { environmentInstance.setStatus(Status.ERROR); environmentInstanceDao.update(environmentInstance); throw new ProductInstallatorException(e); } environmentInstance.setStatus(Status.INSTALLED); environmentInstanceDao.update(environmentInstance); infrastructureManager.StartStopScalability(claudiaData, bScalableEnvironment); environmentInstance.setStatus(Status.INSTALLED); environmentInstanceDao.update(environmentInstance); log.info("Enviroment Instance installed correctly"); // EnvironmentInstance environmentInstanceDB = // insertEnvironmentInstanceDB( claudiaData, environmentInstance); return environmentInstance; } public boolean installSoftwareInEnvironmentInstance(ClaudiaData claudiaData, EnvironmentInstance environmentInstance) throws ProductInstallatorException, InvalidProductInstanceRequestException, NotUniqueResultException, InfrastructureException, InvalidEntityException, EntityNotFoundException { // TierInstance by TierInstance let's check if we have to install // software boolean bScalableEnvironment = false; for (TierInstance tierInstance : environmentInstance.getTierInstances()) { log.info("Install software in tierInstance " + tierInstance.getName() + " from tier " + tierInstance.getTier().getName()); // check if the tier is scalable boolean state = checkScalability(tierInstance.getTier()); if (!bScalableEnvironment) { bScalableEnvironment = (state) ? true : false; } tierInstance.setStatus(Status.INSTALLING); tierInstanceDao.update(tierInstance); String newOVF = " "; Tier tier = tierManager.loadTierWithProductReleaseAndMetadata (tierInstance.getTier().getName(), tierInstance.getTier().getEnviromentName(), tierInstance.getTier().getVdc()); if ((tier.getProductReleases() != null) && !(tier.getProductReleases().isEmpty() )) { for (ProductRelease productRelease : tier.getProductReleases()) { productRelease = productReleaseManager.load(productRelease.getName()); log.info("Install software " + productRelease.getProduct() + " " + productRelease.getVersion()); try { ProductInstance productInstance = productInstanceManager.install(tierInstance, claudiaData, environmentInstance.getEnvironment().getName(), productRelease, productRelease.getAttributes()); log.info("Adding product instance " + productInstance.getName()); tierInstance.setStatus(Status.INSTALLED); tierInstance.addProductInstance(productInstance); } catch (ProductInstallatorException pie) { String message = " Error installing product " + productRelease.getName() + " " + pie.getMessage(); tierInstance.setStatus(Status.ERROR); tierInstanceDao.update(tierInstance); log.error(message); throw new ProductInstallatorException(message, pie); } } if (state && tierInstance.getNumberReplica() == 1) { log.info("Setup scalabiliy "); String image_Name; // claudiaData.setFqn(tierInstance.getVM().getFqn()); image_Name = infrastructureManager.ImageScalability(claudiaData, tierInstance); log.info("Generating image " + image_Name); log.info("Updating OVF "); newOVF = environmentUtils.updateVmOvf(tierInstance.getOvf(), image_Name); tierInstance.setOvf(newOVF); // tierInstance.setOvf(newOVF); } if (state && tierInstance.getNumberReplica() > 1) { log.info("Updating OVF replica more than 1 "); if (!newOVF.equals(" ")) tierInstance.setOvf(newOVF); } tierInstance.setStatus(Status.INSTALLED); tierInstanceDao.update(tierInstance); } } return bScalableEnvironment; } private boolean checkScalability(Tier tier) { boolean state; if (tier.getMaximumNumberInstances() > tier.getMinimumNumberInstances()) { state = true; } else { state = false; } return state; } public EnvironmentInstance load(String vdc, String name) throws EntityNotFoundException { EnvironmentInstance instance = null; try { instance = environmentInstanceDao.load(name); } catch (Exception e) { throw new EntityNotFoundException(EnvironmentInstance.class, "vdc", vdc); } if (!instance.getVdc().equals(vdc)) { throw new EntityNotFoundException(EnvironmentInstance.class, "vdc", vdc); } return instance; } public EnvironmentInstance loadForDelete(String vdc, String name) throws EntityNotFoundException { EnvironmentInstance instance = null; try { instance = environmentInstanceDao.loadForDelete(name); } catch (EntityNotFoundException e) { instance = environmentInstanceDao.load(name); instance.setTierInstances(null); } return instance; } public EnvironmentInstance update(EnvironmentInstance envInst) throws InvalidEntityException { try { return environmentInstanceDao.update(envInst); } catch (InvalidEntityException e) { // TODO Auto-generated catch block log.error("It is not possible to update the environment " + envInst.getName() + " : " + e.getMessage()); throw new InvalidEntityException(EnvironmentInstance.class, e); } } /* * (non-Javadoc) * @see com.telefonica.euro_iaas.paasmanager.manager.EnvironmentInstanceManager * #destroy(com.telefonica.euro_iaas.paasmanager.model.EnvironmentInstance) */ public void destroy(ClaudiaData claudiaData, EnvironmentInstance envInstance) throws InvalidEntityException { log.info("Destroying enviornment isntance " + envInstance.getBlueprintName() + " with environment " + envInstance.getEnvironment().getName() + " vdc " + envInstance.getVdc()); try { // Borrado de nodos en el chefServer envInstance.setStatus(Status.UNINSTALLING); envInstance = environmentInstanceDao.update(envInstance); for (int i = 0; i < envInstance.getTierInstances().size(); i++) { TierInstance tierInstance = envInstance.getTierInstances().get(i); log.info("Deleting node " + tierInstance.getVM().getHostname()); tierInstance.setStatus(Status.UNINSTALLING); tierInstanceDao.update(tierInstance); try { ChefClient chefClient = productInstallator.loadNode(tierInstance.getVdc(), tierInstance.getVM() .getHostname()); productInstallator.deleteNode(tierInstance.getVdc(), chefClient.getName()); tierInstance.setStatus(Status.UNINSTALLED); tierInstanceDao.update(tierInstance); } catch (EntityNotFoundException enfe) { String errorMsg = "The ChefClient " + tierInstance.getVM().getHostname() + " is not at ChefServer"; log.error(errorMsg); } catch (Exception e) { String errorMsg = "Error deleting node from Node Manager : " + tierInstance.getVM().getFqn() + "" + e.getMessage(); log.error(errorMsg); throw new InvalidEntityException(EnvironmentInstance.class, e); } envInstance.setStatus(Status.UNINSTALLED); envInstance = environmentInstanceDao.update(envInstance); // Borrado de VMs try { log.info("Deleting Virtual Machines for environmetn instance " + envInstance.getBlueprintName()); envInstance.setStatus(Status.UNDEPLOYING); envInstance = environmentInstanceDao.update(envInstance); infrastructureManager.deleteEnvironment(claudiaData, envInstance); } catch (InfrastructureException e) { log.error("It is not possible to delete the environment " + envInstance.getName() + " : " + e.getMessage()); throw new InvalidEntityException(EnvironmentInstance.class, e); } catch (EntityNotFoundException e) { log.error("It is not possible to delete the environment " + envInstance.getName() + " : " + e.getMessage()); throw new InvalidEntityException(EnvironmentInstance.class, e); } envInstance.setStatus(Status.UNDEPLOYED); } // Borrado del registro en BBDD paasmanager log.info("Deleting the environment instance " + envInstance.getBlueprintName() + " in the database "); List<TierInstance> tierInstances = envInstance.getTierInstances(); if (tierInstances != null) { envInstance.setTierInstances(null); try { envInstance = environmentInstanceDao.update(envInstance); } catch (InvalidEntityException e) { log.error(e.getMessage()); throw new InvalidEntityException(EnvironmentInstance.class, e); } for (TierInstance tierInstance : tierInstances) { tierInstanceManager.remove(tierInstance); } } } catch (NullPointerException ne) { log.info("Environment Instance " + envInstance.getBlueprintName() + " does not have any TierInstances associated"); } finally { environmentInstanceDao.remove(envInstance); log.info("Environment Instance " + envInstance.getBlueprintName() + " DESTROYED"); } } // PRVATE METHODS private Environment insertEnvironemntInDatabase(ClaudiaData claudiaData, Environment env) throws InvalidEntityException, EntityNotFoundException { log.info("Insert Environment from User into the database"); Environment environment = null; if (env.getVdc() == null) { env.setVdc(claudiaData.getVdc()); } if (env.getOrg() == null) { env.setOrg(claudiaData.getOrg()); } if (systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM).equals("FIWARE")) { try { environment = environmentManager.load(env.getName(), env.getVdc()); if (environment.getOvf() == null && env.getOvf() != null) { environment.setOvf(env.getOvf()); environment = environmentManager.update(environment); } Set<Tier> tiers = new HashSet(); for (Tier tier : env.getTiers()) { Tier tierDB = tierManager.load(tier.getName(), env.getVdc(), env.getName()); tierDB = updateTierDB(tierDB, tier); tierDB = tierManager.update(tierDB); List<ProductRelease> pReleases = new ArrayList<ProductRelease> (); List<ProductRelease> productReleases = tier.getProductReleases(); for (ProductRelease pRelease : productReleases){ ProductRelease pReleaseDB = productReleaseManager.load(pRelease.getProduct() + "-" + pRelease.getVersion()); pReleaseDB = updateProductReleaseDB(pReleaseDB, pRelease); pReleaseDB = productReleaseManager.update(pReleaseDB); pReleases.add(pReleaseDB); } tierDB.setProductReleases(null); tierDB.setProductReleases(pReleases); tiers.add(tierDB); } environment.setTiers(null); environment.setTiers(tiers); return environment; } catch (EntityNotFoundException e1) { throw new EntityNotFoundException(Environment.class, "The environment should have been already created", e1); } } try { environment = environmentManager.load(env.getName(), env.getVdc()); if (environment.getOvf() == null && env.getOvf() != null) { environment.setOvf(env.getOvf()); environment = environmentManager.update(environment); } return environment; } catch (EntityNotFoundException e1) { try { environment = environmentManager.create(claudiaData, env); } catch (InvalidEnvironmentRequestException e) { // TODO Auto-generated catch block String errorMessage = " Error to create the environment . " + environment.getName() + ". " + "Desc: " + e.getMessage(); log.error(errorMessage); throw new InvalidEntityException(Environment.class, e); } catch (Exception e) { // TODO Auto-generated catch block String errorMessage = " Error to create the environment . " + environment.getName() + ". " + "Desc: " + e.getMessage(); log.error(errorMessage); throw new InvalidEntityException(Environment.class, e); } } return environment; } private EnvironmentInstance insertEnvironenttInstanceInDatabase(EnvironmentInstance environmentInstance) throws InvalidEntityException { try { environmentInstance = environmentInstanceDao.create(environmentInstance); } catch (InvalidEntityException e) { String errorMessage = " Invalid environmentInstance objetc . Desc: " + e.getMessage(); log.error(errorMessage); throw new InvalidEntityException(EnvironmentInstance.class, e); } catch (AlreadyExistsEntityException e) { String errorMessage = " Already exists environmentInstance objetc . " + environmentInstance.getName() + ". " + "Desc: " + e.getMessage(); log.error(errorMessage); throw new InvalidEntityException(EnvironmentInstance.class, e); } return environmentInstance; } private Tier updateTierDB(Tier tierDB, Tier tier){ if (tier.getName() != null) tierDB.setName(tier.getName()); if (tier.getRegion() != null) tierDB.setRegion(tier.getRegion()); if (tier.getFlavour() != null) tierDB.setFlavour(tier.getFlavour()); if (tier.getImage() != null) tierDB.setImage(tier.getImage()); if (tier.getIcono() != null) tierDB.setIcono(tier.getIcono()); if (tier.getKeypair() != null) tierDB.setKeypair(tier.getKeypair()); if (tier.getNetworks() != null || (!tier.getNetworks().isEmpty())) { tierDB.setNetworks(null); tierDB.setNetworks(tier.getNetworks()); } return tierDB; } private ProductRelease updateProductReleaseDB(ProductRelease productReleaseDB, ProductRelease productRelease) { if (productRelease.getDescription() != null){ productReleaseDB.setName(productRelease.getDescription()); } if (productRelease.getTierName() != null){ productReleaseDB.setTierName(productRelease.getTierName()); } if (productRelease.getAttributes() != null){ List<ProductRelease> productReleases = new ArrayList<ProductRelease> (); productReleaseDB.setAttributes(null); for (Attribute attr : productRelease.getAttributes()) { productReleaseDB.addAttribute(attr); } productReleases.add(productReleaseDB); } return productReleaseDB; } /** * @param tierInstanceDao * the tierInstanceDao to set */ public void setTierInstanceDao(TierInstanceDao tierInstanceDao) { this.tierInstanceDao = tierInstanceDao; } /** * @param environmentInstanceDao * the environmentInstanceDao to set */ public void setEnvironmentInstanceDao(EnvironmentInstanceDao environmentInstanceDao) { this.environmentInstanceDao = environmentInstanceDao; } /** * @param productInstanceManager * the productInstanceManager to set */ public void setProductInstanceManager(ProductInstanceManager productInstanceManager) { this.productInstanceManager = productInstanceManager; } /** * @param tierInstanceManager * the tierInstanceManager to set */ public void setTierInstanceManager(TierInstanceManager tierInstanceManager) { this.tierInstanceManager = tierInstanceManager; } /** * @param environmentManager * the environmentManager to set */ public void setEnvironmentManager(EnvironmentManager environmentManager) { this.environmentManager = environmentManager; } /** * @param infrastructureManager * the infrastructureManager to set */ public void setInfrastructureManager(InfrastructureManager infrastructureManager) { this.infrastructureManager = infrastructureManager; } /** * @param environmentUtils * the environmentUtils to set */ public void setEnvironmentUtils(EnvironmentUtils environmentUtils) { this.environmentUtils = environmentUtils; } /** * @param productInstallator * the productInstallator to set */ public void setProductInstallator(ProductInstallator productInstallator) { this.productInstallator = productInstallator; } public void setSystemPropertiesProvider(SystemPropertiesProvider systemPropertiesProvider) { this.systemPropertiesProvider = systemPropertiesProvider; } public void setTierManager(TierManager tierManager) { this.tierManager = tierManager; } public void setProductReleaseManager (ProductReleaseManager productReleaseManager) { this.productReleaseManager=productReleaseManager; } }
package net.ihiroky.niotty.util; /** * Provides utility methods for checking arguments of a method. */ public final class Arguments { private Arguments() { throw new AssertionError(); } /** * Checks if the value is not null. * @param value the value to check * @param name the name of the variable * @param <T> the type of the value * @return the value * @throws NullPointerException if the value is null */ public static <T> T requireNonNull(T value, String name) { if (value == null) { throw (name != null) ? new NullPointerException("The " + name + " must not be null.") : new NullPointerException(); } return value; } public static int requirePositive(int value, String name) { if (value <= 0) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be positive.") : new IllegalArgumentException(); } return value; } public static long requirePositive(long value, String name) { if (value <= 0L) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be positive.") : new IllegalArgumentException(); } return value; } public static int requirePositiveOrZero(int value, String name) { if (value < 0) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be positive or zero.") : new IllegalArgumentException(); } return value; } public static long requirePositiveOrZero(long value, String name) { if (value < 0L) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be positive or zero.") : new IllegalArgumentException(); } return value; } /** * Checks if the int value is in the specified range. * * @param value the value to check * @param name the name of the variable * @param min the minimum value of the range * @param max the maximum value of the range * @return the value */ public static int requireInRange(int value, String name, int min, int max) { if (value < min || value > max) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be in [" + min + ", " + max + "].") : new IllegalArgumentException(); } return value; } /** * Checks if the long value is in the specified range. * * @param value the value to check * @param name the name of the variable * @param min the minimum value of the range * @param max the maximum value of the range * @return the value */ public static long requireInRange(long value, String name, long min, long max) { if (value < min || value > max) { throw (name != null) ? new IllegalArgumentException("The " + name + " must be in [" + min + ", " + max + "].") : new IllegalArgumentException(); } return value; } }
package net.imagej.ops.math; import java.util.Random; import net.imagej.ops.AbstractNamespace; import net.imagej.ops.MathOps; import net.imagej.ops.OpMethod; import net.imglib2.IterableInterval; import net.imglib2.IterableRealInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.basictypeaccess.array.ByteArray; import net.imglib2.img.basictypeaccess.array.DoubleArray; import net.imglib2.img.planar.PlanarImg; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.real.DoubleType; /** * The math namespace contains arithmetic operations. * * @author Curtis Rueden */ public class MathNamespace extends AbstractNamespace { // -- Math namespace ops -- @OpMethod(op = net.imagej.ops.MathOps.Abs.class) public Object abs(final Object... args) { return ops().run(net.imagej.ops.MathOps.Abs.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAbs.class) public int abs(final int a) { final int result = (Integer) ops() .run(net.imagej.ops.math.PrimitiveMath.IntegerAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAbs.class) public long abs(final long a) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAbs.class) public float abs(final float a) { final float result = (Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAbs.class) public double abs(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAbs.class) public <I extends RealType<I>, O extends RealType<O>> O abs(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAbs.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Add.class) public Object add(final Object... args) { return ops().run(net.imagej.ops.MathOps.Add.class, args); } @OpMethod(ops = { net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayByteImageP.class, net.imagej.ops.arithmetic.add.AddConstantToArrayByteImage.class }) public ArrayImg<ByteType, ByteArray> add( final ArrayImg<ByteType, ByteArray> image, final byte value) { @SuppressWarnings("unchecked") final ArrayImg<ByteType, ByteArray> result = (ArrayImg<ByteType, ByteArray>) ops().run(MathOps.Add.NAME, image, value); return result; } @OpMethod( ops = { net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayDoubleImageP.class, net.imagej.ops.arithmetic.add.AddConstantToArrayDoubleImage.class }) public ArrayImg<DoubleType, DoubleArray> add( final ArrayImg<DoubleType, DoubleArray> image, final double value) { @SuppressWarnings("unchecked") final ArrayImg<DoubleType, DoubleArray> result = (ArrayImg<DoubleType, DoubleArray>) ops().run(MathOps.Add.NAME, image, value); return result; } @OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.AddOp.class) public Object add(final Object result, final Object a, final Object b) { final Object result_op = ops().run(net.imagej.ops.onthefly.ArithmeticOp.AddOp.class, result, a, b); return result_op; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAdd.class) public int add(final int a, final int b) { final int result = (Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAdd.class) public long add(final long a, final long b) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAdd.class) public float add(final float a, final float b) { final float result = (Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAdd.class) public double add(final double a, final double b) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAdd.class) public <I extends RealType<I>, O extends RealType<O>> RealType<O> add( final RealType<O> out, final RealType<I> in, final double constant) { @SuppressWarnings("unchecked") final RealType<O> result = (RealType<O>) ops().run(net.imagej.ops.arithmetic.real.RealAdd.class, out, in, constant); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class) public <T extends NumericType<T>> IterableInterval<T> add( final IterableInterval<T> a, final RandomAccessibleInterval<T> b) { @SuppressWarnings("unchecked") final IterableInterval<T> result = (IterableInterval<T>) ops() .run( net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class, a, b); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class) public PlanarImg<DoubleType, DoubleArray> add( final PlanarImg<DoubleType, DoubleArray> image, final double value) { @SuppressWarnings("unchecked") final PlanarImg<DoubleType, DoubleArray> result = (PlanarImg<DoubleType, DoubleArray>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class, image, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class) public <T extends NumericType<T>> IterableRealInterval<T> add( final IterableRealInterval<T> image, final T value) { @SuppressWarnings("unchecked") final IterableRealInterval<T> result = (IterableRealInterval<T>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class, image, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class) public <T extends NumericType<T>> T add(final T in, final T value) { @SuppressWarnings("unchecked") final T result = (T) ops() .run(net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, in, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class) public <T extends NumericType<T>> T add(final T out, final T in, final T value) { @SuppressWarnings("unchecked") final T result = (T) ops().run( net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, out, in, value); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class) public <T extends NumericType<T>> RandomAccessibleInterval<T> add( final RandomAccessibleInterval<T> out, final IterableInterval<T> in, final T value) { @SuppressWarnings("unchecked") final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class, out, in, value); return result; } @OpMethod(op = net.imagej.ops.MathOps.AddNoise.class) public Object addnoise(final Object... args) { return ops().run(net.imagej.ops.MathOps.AddNoise.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAddNoise.class) public <I extends RealType<I>, O extends RealType<O>> O addnoise(final O out, final I in, final double rangeMin, final double rangeMax, final double rangeStdDev, final Random rng) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAddNoise.class, out, in, rangeMin, rangeMax, rangeStdDev, rng); return result; } @OpMethod(op = net.imagej.ops.MathOps.And.class) public Object and(final Object... args) { return ops().run(net.imagej.ops.MathOps.And.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAnd.class) public int and(final int a, final int b) { final int result = (Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAnd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAnd.class) public long and(final long a, final long b) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAnd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAndConstant.class) public <I extends RealType<I>, O extends RealType<O>> O and(final O out, final I in, final long constant) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAndConstant.class, out, in, constant); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccos.class) public Object arccos(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccos.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArccos.class) public double arccos(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArccos.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccos.class) public <I extends RealType<I>, O extends RealType<O>> O arccos(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccos.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccosh.class) public Object arccosh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccosh.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccosh.class) public <I extends RealType<I>, O extends RealType<O>> O arccosh(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccosh.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccot.class) public Object arccot(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccot.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccot.class) public <I extends RealType<I>, O extends RealType<O>> O arccot(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccot.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccoth.class) public Object arccoth(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccoth.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccoth.class) public <I extends RealType<I>, O extends RealType<O>> O arccoth(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccoth.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccsc.class) public Object arccsc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccsc.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccsc.class) public <I extends RealType<I>, O extends RealType<O>> O arccsc(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccsc.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccsch.class) public Object arccsch(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccsch.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccsch.class) public <I extends RealType<I>, O extends RealType<O>> O arccsch(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccsch.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arcsec.class) public Object arcsec(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsec.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsec.class) public <I extends RealType<I>, O extends RealType<O>> O arcsec(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArcsec.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arcsech.class) public Object arcsech(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsech.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsech.class) public <I extends RealType<I>, O extends RealType<O>> O arcsech(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArcsech.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arcsin.class) public Object arcsin(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsin.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArcsin.class) public double arcsin(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArcsin.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsin.class) public <I extends RealType<I>, O extends RealType<O>> O arcsin(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArcsin.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arcsinh.class) public Object arcsinh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsinh.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsinh.class) public <I extends RealType<I>, O extends RealType<O>> O arcsinh(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArcsinh.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arctan.class) public Object arctan(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arctan.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArctan.class) public double arctan(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArctan.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArctan.class) public <I extends RealType<I>, O extends RealType<O>> O arctan(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArctan.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arctanh.class) public Object arctanh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arctanh.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArctanh.class) public <I extends RealType<I>, O extends RealType<O>> O arctanh(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArctanh.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Ceil.class) public Object ceil(final Object... args) { return ops().run(net.imagej.ops.MathOps.Ceil.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCeil.class) public double ceil(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCeil.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCeil.class) public <I extends RealType<I>, O extends RealType<O>> O ceil(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCeil.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Complement.class) public Object complement(final Object... args) { return ops().run(net.imagej.ops.MathOps.Complement.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerComplement.class) public int complement(final int a) { final int result = (Integer) ops().run( net.imagej.ops.math.PrimitiveMath.IntegerComplement.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongComplement.class) public long complement(final long a) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongComplement.class, a); return result; } @OpMethod(op = net.imagej.ops.MathOps.Copy.class) public Object copy(final Object... args) { return ops().run(net.imagej.ops.MathOps.Copy.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCopy.class) public <I extends RealType<I>, O extends RealType<O>> O copy(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCopy.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Cos.class) public Object cos(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cos.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCos.class) public double cos(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCos.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCos.class) public <I extends RealType<I>, O extends RealType<O>> O cos(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCos.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Cosh.class) public Object cosh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cosh.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCosh.class) public double cosh(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCosh.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCosh.class) public <I extends RealType<I>, O extends RealType<O>> O cosh(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCosh.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Cot.class) public Object cot(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cot.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCot.class) public <I extends RealType<I>, O extends RealType<O>> O cot(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCot.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Coth.class) public Object coth(final Object... args) { return ops().run(net.imagej.ops.MathOps.Coth.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCoth.class) public <I extends RealType<I>, O extends RealType<O>> O coth(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCoth.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Csc.class) public Object csc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Csc.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCsc.class) public <I extends RealType<I>, O extends RealType<O>> O csc(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCsc.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Csch.class) public Object csch(final Object... args) { return ops().run(net.imagej.ops.MathOps.Csch.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCsch.class) public <I extends RealType<I>, O extends RealType<O>> O csch(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCsch.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.CubeRoot.class) public Object cuberoot(final Object... args) { return ops().run(net.imagej.ops.MathOps.CubeRoot.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCubeRoot.class) public double cuberoot(final double a) { final double result = (Double) ops().run( net.imagej.ops.math.PrimitiveMath.DoubleCubeRoot.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealCubeRoot.class) public <I extends RealType<I>, O extends RealType<O>> O cuberoot(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealCubeRoot.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Divide.class) public Object divide(final Object... args) { return ops().run(net.imagej.ops.MathOps.Divide.class, args); } @OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.DivideOp.class) public Object divide(final Object result, final Object a, final Object b) { final Object result_op = ops().run(net.imagej.ops.onthefly.ArithmeticOp.DivideOp.class, result, a, b); return result_op; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerDivide.class) public int divide(final int a, final int b) { final int result = (Integer) ops().run( net.imagej.ops.math.PrimitiveMath.IntegerDivide.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongDivide.class) public long divide(final long a, final long b) { final long result = (Long) ops() .run(net.imagej.ops.math.PrimitiveMath.LongDivide.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatDivide.class) public float divide(final float a, final float b) { final float result = (Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatDivide.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleDivide.class) public double divide(final double a, final double b) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleDivide.class, a, b); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealDivide.class) public <I extends RealType<I>, O extends RealType<O>> O divide(final O out, final I in, final double constant, final double dbzVal) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealDivide.class, out, in, constant, dbzVal); return result; } @OpMethod(op = net.imagej.ops.MathOps.Exp.class) public Object exp(final Object... args) { return ops().run(net.imagej.ops.MathOps.Exp.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleExp.class) public double exp(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleExp.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealExp.class) public <I extends RealType<I>, O extends RealType<O>> O exp(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealExp.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.ExpMinusOne.class) public Object expminusone(final Object... args) { return ops().run(net.imagej.ops.MathOps.ExpMinusOne.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealExpMinusOne.class) public <I extends RealType<I>, O extends RealType<O>> O expminusone( final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealExpMinusOne.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Floor.class) public Object floor(final Object... args) { return ops().run(net.imagej.ops.MathOps.Floor.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleFloor.class) public double floor(final double a) { final double result = (Double) ops() .run(net.imagej.ops.math.PrimitiveMath.DoubleFloor.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealFloor.class) public <I extends RealType<I>, O extends RealType<O>> O floor(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealFloor.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Gamma.class) public Object gamma(final Object... args) { return ops().run(net.imagej.ops.MathOps.Gamma.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealGammaConstant.class) public <I extends RealType<I>, O extends RealType<O>> O gamma(final O out, final I in, final double constant) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealGammaConstant.class, out, in, constant); return result; } @OpMethod(op = net.imagej.ops.MathOps.GaussianRandom.class) public Object gaussianrandom(final Object... args) { return ops().run(net.imagej.ops.MathOps.GaussianRandom.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Invert.class) public Object invert(final Object... args) { return ops().run(net.imagej.ops.MathOps.Invert.class, args); } @OpMethod(op = net.imagej.ops.MathOps.LeftShift.class) public Object leftshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.LeftShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log.class) public Object log(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log2.class) public Object log2(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log2.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log10.class) public Object log10(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log10.class, args); } @OpMethod(op = net.imagej.ops.MathOps.LogOnePlusX.class) public Object logoneplusx(final Object... args) { return ops().run(net.imagej.ops.MathOps.LogOnePlusX.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Max.class) public Object max(final Object... args) { return ops().run(net.imagej.ops.MathOps.Max.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Min.class) public Object min(final Object... args) { return ops().run(net.imagej.ops.MathOps.Min.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Multiply.class) public Object multiply(final Object... args) { return ops().run(net.imagej.ops.MathOps.Multiply.class, args); } @OpMethod(op = net.imagej.ops.MathOps.NearestInt.class) public Object nearestint(final Object... args) { return ops().run(net.imagej.ops.MathOps.NearestInt.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Negate.class) public Object negate(final Object... args) { return ops().run(net.imagej.ops.MathOps.Negate.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Or.class) public Object or(final Object... args) { return ops().run(net.imagej.ops.MathOps.Or.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Power.class) public Object power(final Object... args) { return ops().run(net.imagej.ops.MathOps.Power.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Reciprocal.class) public Object reciprocal(final Object... args) { return ops().run(net.imagej.ops.MathOps.Reciprocal.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Remainder.class) public Object remainder(final Object... args) { return ops().run(net.imagej.ops.MathOps.Remainder.class, args); } @OpMethod(op = net.imagej.ops.MathOps.RightShift.class) public Object rightshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.RightShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Round.class) public Object round(final Object... args) { return ops().run(net.imagej.ops.MathOps.Round.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sec.class) public Object sec(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sec.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sech.class) public Object sech(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sech.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Signum.class) public Object signum(final Object... args) { return ops().run(net.imagej.ops.MathOps.Signum.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sin.class) public Object sin(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sin.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sinc.class) public Object sinc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sinc.class, args); } @OpMethod(op = net.imagej.ops.MathOps.SincPi.class) public Object sincpi(final Object... args) { return ops().run(net.imagej.ops.MathOps.SincPi.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sinh.class) public Object sinh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sinh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sqr.class) public Object sqr(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sqr.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sqrt.class) public Object sqrt(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sqrt.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Step.class) public Object step(final Object... args) { return ops().run(net.imagej.ops.MathOps.Step.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Subtract.class) public Object subtract(final Object... args) { return ops().run(net.imagej.ops.MathOps.Subtract.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Tan.class) public Object tan(final Object... args) { return ops().run(net.imagej.ops.MathOps.Tan.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Tanh.class) public Object tanh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Tanh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Ulp.class) public Object ulp(final Object... args) { return ops().run(net.imagej.ops.MathOps.Ulp.class, args); } @OpMethod(op = net.imagej.ops.MathOps.UniformRandom.class) public Object uniformrandom(final Object... args) { return ops().run(net.imagej.ops.MathOps.UniformRandom.class, args); } @OpMethod(op = net.imagej.ops.MathOps.UnsignedRightShift.class) public Object unsignedrightshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.UnsignedRightShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Xor.class) public Object xor(final Object... args) { return ops().run(net.imagej.ops.MathOps.Xor.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Zero.class) public Object zero(final Object... args) { return ops().run(net.imagej.ops.MathOps.Zero.class, args); } // -- Named methods -- @Override public String getName() { return "math"; } }
package com.linkedin.datahub.graphql.types.dataplatform; import com.linkedin.common.urn.DataPlatformUrn; import com.linkedin.datahub.graphql.QueryContext; import com.linkedin.datahub.graphql.types.EntityType; import com.linkedin.datahub.graphql.generated.DataPlatform; import com.linkedin.datahub.graphql.types.dataplatform.mappers.DataPlatformMapper; import com.linkedin.dataplatform.client.DataPlatforms; import graphql.execution.DataFetcherResult; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class DataPlatformType implements EntityType<DataPlatform> { private final DataPlatforms _dataPlatformsClient; private Map<String, DataPlatform> _urnToPlatform; public DataPlatformType(final DataPlatforms dataPlatformsClient) { _dataPlatformsClient = dataPlatformsClient; } @Override public Class<DataPlatform> objectClass() { return DataPlatform.class; } @Override public List<DataFetcherResult<DataPlatform>> batchLoad(final List<String> urns, final QueryContext context) { try { if (_urnToPlatform == null) { _urnToPlatform = _dataPlatformsClient.getAllPlatforms().stream() .map(DataPlatformMapper::map) .collect(Collectors.toMap(DataPlatform::getUrn, platform -> platform)); } return urns.stream() .map(key -> _urnToPlatform.containsKey(key) ? _urnToPlatform.get(key) : getUnknownDataPlatform(key)) .map(dataPlatform -> DataFetcherResult.<DataPlatform>newResult().data(dataPlatform).build()) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException("Failed to batch load DataPlatforms", e); } } @Override public com.linkedin.datahub.graphql.generated.EntityType type() { return com.linkedin.datahub.graphql.generated.EntityType.DATA_PLATFORM; } private DataPlatform getUnknownDataPlatform(final String urnStr) { try { final com.linkedin.dataPlatforms.DataPlatform platform = new com.linkedin.dataPlatforms.DataPlatform() .setName(DataPlatformUrn.createFromString(urnStr).getPlatformNameEntity()); return DataPlatformMapper.map(platform); } catch (URISyntaxException e) { throw new RuntimeException(String.format("Invalid DataPlatformUrn %s provided", urnStr), e); } } }
package biz.integsys.autopatch; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.util.Log; public class AudioMonitor { private final AudioRecord audioRecord; private Thread monitorThread; private final float[] recordBuffer = new float[44100]; private final double[] re = new double[32768]; private double[] im = new double[32768]; private final double[] zero = new double[32768]; private final FFT fft = new FFT(32768); private boolean enable; public AudioMonitor() { audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_FLOAT, 44100); int state = audioRecord.getState(); Log.d("AudioMonitor", "state: " + state); for (int i=0; i < im.length; i++) zero[i]=0; //do i actually need to do this? } public void start() { enable = true; audioRecord.startRecording(); monitorThread = new Thread(new Runnable() { public void run() { do { int read = audioRecord.read(recordBuffer, 0, 44100, AudioRecord.READ_BLOCKING); Log.d("AudioMonitor", "read " + read + " floats."); im = zero.clone(); //memset, I hope? for (int i=0; i < 32768; i++) re[i] = recordBuffer[i]; fft.fft(re, im); //Log.d("AudioMonitor", "FFT done."); } while (enable); for (int i=0; i < 32768; i++) { if ((Math.abs(im[i]) > 1000) || (Math.abs(re[i]) > 1000)) Log.v("AudioMonitor", "i="+i+" x="+ im[i]+" y="+ re[i]); audioRecord.stop(); } } }); monitorThread.start(); } public void stop() { //monitorThread.interrupt(); enable = false; } }
package net.sf.jabref.groups; import java.util.Map; import java.util.regex.Pattern; import javax.swing.undo.AbstractUndoableEdit; import net.sf.jabref.*; import net.sf.jabref.undo.NamedCompound; import net.sf.jabref.undo.UndoableFieldChange; import net.sf.jabref.util.QuotedStringTokenizer; /** * @author jzieren */ public class KeywordGroup extends AbstractGroup implements SearchRule { public static final String ID = "KeywordGroup:"; private final String m_searchField; private final String m_searchExpression; private final boolean m_caseSensitive; private final boolean m_regExp; private Pattern m_pattern = null; /** * Creates a KeywordGroup with the specified properties. */ public KeywordGroup(String name, String searchField, String searchExpression, boolean caseSensitive, boolean regExp, int context) throws IllegalArgumentException { super(name, context); m_searchField = searchField; m_searchExpression = searchExpression; m_caseSensitive = caseSensitive; m_regExp = regExp; if (m_regExp) compilePattern(); } protected void compilePattern() throws IllegalArgumentException { m_pattern = m_caseSensitive ? Pattern.compile("\\b"+m_searchExpression+"\\b") : Pattern.compile("\\b"+m_searchExpression+"\\b", Pattern.CASE_INSENSITIVE); } /** * Parses s and recreates the KeywordGroup from it. * * @param s * The String representation obtained from * KeywordGroup.toString() */ public static AbstractGroup fromString(String s, BibtexDatabase db, int version) throws Exception { if (!s.startsWith(ID)) throw new Exception( "Internal error: KeywordGroup cannot be created from \"" + s + "\". " + "Please report this on www.sf.net/projects/jabref"); QuotedStringTokenizer tok = new QuotedStringTokenizer(s.substring(ID .length()), SEPARATOR, QUOTE_CHAR); switch (version) { case 0: { String name = tok.nextToken(); String field = tok.nextToken(); String expression = tok.nextToken(); // assume caseSensitive=false and regExp=true for old groups return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), false, true, AbstractGroup.INDEPENDENT); } case 1: case 2: { String name = tok.nextToken(); String field = tok.nextToken(); String expression = tok.nextToken(); boolean caseSensitive = Integer.parseInt(tok.nextToken()) == 1; boolean regExp = Integer.parseInt(tok.nextToken()) == 1; return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), caseSensitive, regExp, AbstractGroup.INDEPENDENT); } case 3: { String name = tok.nextToken(); int context = Integer.parseInt(tok.nextToken()); String field = tok.nextToken(); String expression = tok.nextToken(); boolean caseSensitive = Integer.parseInt(tok.nextToken()) == 1; boolean regExp = Integer.parseInt(tok.nextToken()) == 1; return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), caseSensitive, regExp, context); } default: throw new UnsupportedVersionException("KeywordGroup", version); } } /** * @see net.sf.jabref.groups.AbstractGroup#getSearchRule() */ public SearchRule getSearchRule() { return this; } /** * Returns a String representation of this object that can be used to * reconstruct it. */ public String toString() { return ID + Util.quote(m_name, SEPARATOR, QUOTE_CHAR) + SEPARATOR + m_context + SEPARATOR + Util.quote(m_searchField, SEPARATOR, QUOTE_CHAR) + SEPARATOR + Util.quote(m_searchExpression, SEPARATOR, QUOTE_CHAR) + SEPARATOR + (m_caseSensitive ? "1" : "0") + SEPARATOR + (m_regExp ? "1" : "0") + SEPARATOR; } public boolean supportsAdd() { return !m_regExp; } public boolean supportsRemove() { return !m_regExp; } public AbstractUndoableEdit add(BibtexEntry[] entries) { if (!supportsAdd()) return null; if ((entries != null) && (entries.length > 0)) { NamedCompound ce = new NamedCompound( Globals.lang("add entries to group")); boolean modified = false; for (BibtexEntry entry : entries) { if (applyRule(null, entry) == 0) { String oldContent = entry .getField(m_searchField), pre = Globals.prefs.get("groupKeywordSeparator"); String newContent = (oldContent == null ? "" : oldContent + pre) + m_searchExpression; entry.setField(m_searchField, newContent); // Store undo information. ce.addEdit(new UndoableFieldChange(entry, m_searchField, oldContent, newContent)); modified = true; } } if (modified) ce.end(); return modified ? ce : null; } return null; } public AbstractUndoableEdit remove(BibtexEntry[] entries) { if (!supportsRemove()) return null; if ((entries != null) && (entries.length > 0)) { NamedCompound ce = new NamedCompound(Globals.lang("remove from group")); boolean modified = false; for (BibtexEntry entry : entries) { if (applyRule(null, entry) > 0) { String oldContent = entry .getField(m_searchField); removeMatches(entry); // Store undo information. ce.addEdit(new UndoableFieldChange(entry, m_searchField, oldContent, entry .getField(m_searchField) )); modified = true; } } if (modified) ce.end(); return modified ? ce : null; } return null; } public boolean equals(Object o) { if (!(o instanceof KeywordGroup)) return false; KeywordGroup other = (KeywordGroup) o; return m_name.equals(other.m_name) && m_searchField.equals(other.m_searchField) && m_searchExpression.equals(other.m_searchExpression) && m_caseSensitive == other.m_caseSensitive && m_regExp == other.m_regExp && getHierarchicalContext() == other.getHierarchicalContext(); } /* * (non-Javadoc) * * @see net.sf.jabref.groups.AbstractGroup#contains(java.util.Map, * net.sf.jabref.BibtexEntry) */ public boolean contains(Map<String, String> searchOptions, BibtexEntry entry) { return contains(entry); } public boolean contains(BibtexEntry entry) { String content = entry.getField(m_searchField); if (content == null) return false; if (m_regExp) return m_pattern.matcher(content).find(); if (m_caseSensitive) return containsWord(m_searchExpression, content); return containsWord(m_searchExpression.toLowerCase(), content.toLowerCase()); } /** * Look for the given non-regexp string in another string, but check whether a * match concerns a complete word, not part of a word. * @param word The word to look for. * @param text The string to look in. * @return true if the word was found, false otherwise. */ private static boolean containsWord(String word, String text) { int piv = 0; while (piv < text.length()) { int ind = text.indexOf(word, piv); if (ind < 0) return false; // Found a match. See if it is a complete word: if (((ind == 0) || !Character.isLetterOrDigit(text.charAt(ind-1))) && ((ind+word.length() == text.length()) || !Character.isLetterOrDigit(text.charAt(ind+word.length())))) { return true; } else piv = ind+1; } return false; } /** * Removes matches of searchString in the entry's field. This is only * possible if the search expression is not a regExp. */ private void removeMatches(BibtexEntry entry) { String content = entry.getField(m_searchField); if (content == null) return; // nothing to modify StringBuffer sbOrig = new StringBuffer(content); StringBuffer sbLower = new StringBuffer(content.toLowerCase()); StringBuffer haystack = m_caseSensitive ? sbOrig : sbLower; String needle = m_caseSensitive ? m_searchExpression : m_searchExpression.toLowerCase(); int i, j, k; final String separator = Globals.prefs.get("groupKeywordSeparator"); while ((i = haystack.indexOf(needle)) >= 0) { sbOrig.replace(i, i + needle.length(), ""); sbLower.replace(i, i + needle.length(), ""); // reduce spaces at i to 1 j = i; k = i; while (j - 1 >= 0 && separator.indexOf(haystack.charAt(j - 1)) >= 0) --j; while (k < haystack.length() && separator.indexOf(haystack.charAt(k)) >= 0) ++k; sbOrig.replace(j, k, j >= 0 && k < sbOrig.length() ? separator : ""); sbLower.replace(j, k, j >= 0 && k < sbOrig.length() ? separator : ""); } String result = sbOrig.toString().trim(); entry.setField(m_searchField, (result.length() > 0 ? result : null)); } public int applyRule(Map<String, String> searchOptions, BibtexEntry entry) { return contains(searchOptions, entry) ? 1 : 0; } public boolean validateSearchStrings(Map<String, String> searchStrings) { return true; } public AbstractGroup deepCopy() { try { return new KeywordGroup(m_name, m_searchField, m_searchExpression, m_caseSensitive, m_regExp, m_context); } catch (Throwable t) { // this should never happen, because the constructor obviously // succeeded in creating _this_ instance! System.err.println("Internal error: Exception " + t + " in KeywordGroup.deepCopy(). " + "Please report this on www.sf.net/projects/jabref"); return null; } } public boolean isCaseSensitive() { return m_caseSensitive; } public boolean isRegExp() { return m_regExp; } public String getSearchExpression() { return m_searchExpression; } public String getSearchField() { return m_searchField; } public boolean isDynamic() { return true; } public String getDescription() { return getDescriptionForPreview(m_searchField, m_searchExpression, m_caseSensitive, m_regExp); } public static String getDescriptionForPreview(String field, String expr, boolean caseSensitive, boolean regExp) { return (regExp ? Globals.lang( "This group contains entries whose <b>%0</b> field contains the regular expression <b>%1</b>", field, Util.quoteForHTML(expr)) : Globals.lang( "This group contains entries whose <b>%0</b> field contains the keyword <b>%1</b>", field, Util.quoteForHTML(expr))) + " (" + (caseSensitive ? Globals.lang("case sensitive") : Globals.lang("case insensitive")) + "). " + (regExp ? Globals.lang("Entries cannot be manually assigned to or removed from this group.") : Globals.lang( "Additionally, entries whose <b>%0</b> field does not contain " + "<b>%1</b> can be assigned manually to this group by selecting them " + "then using either drag and drop or the context menu. " + "This process adds the term <b>%1</b> to " + "each entry's <b>%0</b> field. " + "Entries can be removed manually from this group by selecting them " + "then using the context menu. " + "This process removes the term <b>%1</b> from " + "each entry's <b>%0</b> field.", field, Util.quoteForHTML(expr))); } public String getShortDescription() { StringBuffer sb = new StringBuffer(); sb.append("<b>"); if (Globals.prefs.getBoolean("groupShowDynamic")) sb.append("<i>").append(Util.quoteForHTML(getName())).append("</i>"); else sb.append(Util.quoteForHTML(getName())); sb.append("</b> - "); sb.append(Globals.lang("dynamic group")); sb.append("<b>"); sb.append(m_searchField); sb.append("</b>"); sb.append(Globals.lang("contains")); sb.append(" <b>"); sb.append(Util.quoteForHTML(m_searchExpression)); sb.append("</b>)"); switch (getHierarchicalContext()) { case AbstractGroup.INCLUDING: sb.append(", ").append(Globals.lang("includes subgroups")); break; case AbstractGroup.REFINING: sb.append(", ").append(Globals.lang("refines supergroup")); break; default: break; } return sb.toString(); } public String getTypeId() { return ID; } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.dataprep.transformation.service; import static java.nio.charset.StandardCharsets.UTF_8; import static org.talend.daikon.exception.ExceptionContext.build; import static org.talend.dataprep.exception.error.PreparationErrorCodes.UNABLE_TO_READ_PREPARATION; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.talend.daikon.exception.ExceptionContext; import org.talend.dataprep.api.filter.FilterService; import org.talend.dataprep.api.preparation.Action; import org.talend.dataprep.api.preparation.Preparation; import org.talend.dataprep.api.preparation.PreparationMessage; import org.talend.dataprep.api.preparation.Step; import org.talend.dataprep.cache.ContentCache; import org.talend.dataprep.command.preparation.PreparationDetailsGet; import org.talend.dataprep.command.preparation.PreparationGetActions; import org.talend.dataprep.exception.TDPException; import org.talend.dataprep.exception.error.TransformationErrorCodes; import org.talend.dataprep.format.export.ExportFormat; import org.talend.dataprep.lock.LockFactory; import org.talend.dataprep.security.SecurityProxy; import org.talend.dataprep.transformation.api.transformer.TransformerFactory; import org.talend.dataprep.transformation.format.FormatRegistrationService; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class BaseExportStrategy { private static final Logger LOGGER = LoggerFactory.getLogger(BaseExportStrategy.class); @Autowired protected ApplicationContext applicationContext; @Autowired protected ObjectMapper mapper; @Autowired protected ContentCache contentCache; @Autowired protected FilterService filterService; /** The format registration service. */ @Autowired protected FormatRegistrationService formatRegistrationService; /** The transformer factory. */ @Autowired protected TransformerFactory factory; /** The lock factory. */ @Autowired protected LockFactory lockFactory; /** The security proxy to use to get the dataset despite the roles/ownership. */ @Autowired protected SecurityProxy securityProxy; /** * Return the format that matches the given name or throw an error if the format is unknown. * * @param formatName the format name. * @return the format that matches the given name. */ protected ExportFormat getFormat(String formatName) { final ExportFormat format = formatRegistrationService.getByName(formatName.toUpperCase()); if (format == null) { LOGGER.error("Export format {} not supported", formatName); throw new TDPException(TransformationErrorCodes.OUTPUT_TYPE_NOT_SUPPORTED); } return format; } /** * Return the real step id in case of "head" or empty * @param preparation The preparation * @param stepId The step id */ protected String getCleanStepId(final Preparation preparation, final String stepId) { if (StringUtils.equals("head", stepId) || StringUtils.isEmpty(stepId)) { return preparation.getSteps().get(preparation.getSteps().size() - 1).id(); } return stepId; } /** * Returns the actions for the preparation with <code>preparationId</code> at given <code>stepId</code>. * * @param preparationId The preparation id, if <code>null</code> or blank, returns <code>{actions: []}</code> * @param stepId A step id that must exist in given preparation id. * @return The actions that can be parsed by ActionParser. * @see org.talend.dataprep.transformation.api.action.ActionParser */ protected String getActions(String preparationId, String stepId) { String actions; if (StringUtils.isBlank(preparationId) || StringUtils.isBlank(stepId)) { actions = "{\"actions\": []}"; } else { final PreparationGetActions getActionsCommand = applicationContext.getBean(PreparationGetActions.class, preparationId, stepId); try { actions = "{\"actions\": " + IOUtils.toString(getActionsCommand.execute(), UTF_8) + '}'; } catch (IOException e) { final ExceptionContext context = ExceptionContext.build().put("id", preparationId).put("version", stepId); throw new TDPException(UNABLE_TO_READ_PREPARATION, e, context); } } return actions; } /** * Returns the actions for the preparation with <code>preparationId</code> between <code>startStepId</code> and * <code>endStepId</code>. * * @param preparationId The preparation id, if <code>null</code> or blank, returns <code>{actions: []}</code> * @param startStepId A step id that must exist in given preparation id. * @param endStepId A step id that must exist in given preparation id. * @return The actions that can be parsed by ActionParser. * @see org.talend.dataprep.transformation.api.action.ActionParser */ protected String getActions(String preparationId, String startStepId, String endStepId) { if (Step.ROOT_STEP.id().equals(startStepId)) { return getActions(preparationId, endStepId); } String actions; if (StringUtils.isBlank(preparationId)) { actions = "{\"actions\": []}"; } else { try { final PreparationGetActions startStepActions = applicationContext.getBean(PreparationGetActions.class, preparationId, startStepId); final PreparationGetActions endStepActions = applicationContext.getBean(PreparationGetActions.class, preparationId, endStepId); final StringWriter actionsAsString = new StringWriter(); final Action[] startActions = mapper.readValue(startStepActions.execute(), Action[].class); final Action[] endActions = mapper.readValue(endStepActions.execute(), Action[].class); if (endActions.length > startActions.length) { final Action[] filteredActions = (Action[]) ArrayUtils.subarray(endActions, startActions.length, endActions.length); LOGGER.debug("Reduced actions list from {} to {} action(s)", endActions.length, filteredActions.length); mapper.writeValue(actionsAsString, filteredActions); } else { LOGGER.debug("Unable to reduce list of actions (has {})", endActions.length); mapper.writeValue(actionsAsString, endActions); } return "{\"actions\": " + actionsAsString + '}'; } catch (IOException e) { final ExceptionContext context = ExceptionContext.build().put("id", preparationId).put("version", endStepId); throw new TDPException(UNABLE_TO_READ_PREPARATION, e, context); } } return actions; } /** * @param preparationId the wanted preparation id. * @return the preparation out of its id. */ protected PreparationMessage getPreparation(String preparationId) { return getPreparation(preparationId, null); } /** * @param preparationId the wanted preparation id. * @param stepId the preparation step (might be different from head's to navigate through versions). * @return the preparation out of its id. */ protected PreparationMessage getPreparation(String preparationId, String stepId) { if ("origin".equals(stepId)) { stepId = Step.ROOT_STEP.id(); } final PreparationDetailsGet preparationDetailsGet = applicationContext.getBean(PreparationDetailsGet.class, preparationId, stepId); try (InputStream details = preparationDetailsGet.execute()) { return mapper.readerFor(PreparationMessage.class).readValue(details); } catch (Exception e) { LOGGER.error("Unable to read preparation {}", preparationId, e); throw new TDPException(UNABLE_TO_READ_PREPARATION, e, build().put("id", preparationId)); } } }
package net.spy.memcached.auth; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.spy.memcached.KeyUtil; import net.spy.memcached.MemcachedConnection; import net.spy.memcached.MemcachedNode; import net.spy.memcached.OperationFactory; import net.spy.memcached.compat.SpyThread; import net.spy.memcached.compat.log.Level; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; /** * A thread that does SASL authentication. */ public class AuthThread extends SpyThread { /** * If a SASL step takes longer than this period in milliseconds, a warning * will be issued instead of a debug message. */ public static final int AUTH_ROUNDTRIP_THRESHOLD = 250; /** * If the total AUTH steps take longer than this period in milliseconds, a * warning will be issued instead of a debug message. */ public static final int AUTH_TOTAL_THRESHOLD = 1000; public static final String MECH_SEPARATOR = " "; private final MemcachedConnection conn; private final AuthDescriptor authDescriptor; private final OperationFactory opFact; private final MemcachedNode node; public AuthThread(MemcachedConnection c, OperationFactory o, AuthDescriptor a, MemcachedNode n) { conn = c; opFact = o; authDescriptor = a; node = n; start(); } protected String[] listSupportedSASLMechanisms(AtomicBoolean done) { final CountDownLatch listMechsLatch = new CountDownLatch(1); final AtomicReference<String> supportedMechs = new AtomicReference<String>(); Operation listMechsOp = opFact.saslMechs(new OperationCallback() { @Override public void receivedStatus(OperationStatus status) { if(status.isSuccess()) { supportedMechs.set(status.getMessage()); getLogger().debug("Received SASL supported mechs: " + status.getMessage()); } } @Override public void complete() { listMechsLatch.countDown(); } }); conn.insertOperation(node, listMechsOp); try { if (!conn.isShutDown()) { listMechsLatch.await(); } else { done.set(true); // Connection is shutting down, tear.down. } } catch(InterruptedException ex) { // we can be interrupted if we were in the // process of auth'ing and the connection is // lost or dropped due to bad auth Thread.currentThread().interrupt(); if (listMechsOp != null) { listMechsOp.cancel(); } done.set(true); // If we were interrupted, tear down. } String supported = supportedMechs.get(); if (supported == null || supported.isEmpty()) { throw new IllegalStateException("Got empty SASL auth mech list."); } return supported.split(MECH_SEPARATOR); } @Override public void run() { final AtomicBoolean done = new AtomicBoolean(); long totalStart = System.nanoTime(); String[] supportedMechs; long mechsStart = System.nanoTime(); if (authDescriptor.getMechs() == null || authDescriptor.getMechs().length == 0) { supportedMechs = listSupportedSASLMechanisms(done); } else { supportedMechs = authDescriptor.getMechs(); } long mechsDiff = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - mechsStart); String msg = String.format("SASL List Mechanisms took %dms on %s", mechsDiff, node.toString()); Level level = mechsDiff >= AUTH_ROUNDTRIP_THRESHOLD ? Level.WARN : Level.DEBUG; getLogger().log(level, msg); OperationStatus priorStatus = null; while (!done.get()) { long stepStart = System.nanoTime(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<OperationStatus> foundStatus = new AtomicReference<OperationStatus>(); final OperationCallback cb = new OperationCallback() { @Override public void receivedStatus(OperationStatus val) { // If the status we found was null, we're done. if (val.getMessage().length() == 0) { done.set(true); node.authComplete(); getLogger().info("Authenticated to " + node.getSocketAddress()); } else { foundStatus.set(val); } } @Override public void complete() { latch.countDown(); } }; // Get the prior status to create the correct operation. final Operation op = buildOperation(priorStatus, cb, supportedMechs); conn.insertOperation(node, op); try { if (!conn.isShutDown()) { latch.await(); } else { done.set(true); // Connection is shutting down, tear.down. } Thread.sleep(100); } catch (InterruptedException e) { // we can be interrupted if we were in the // process of auth'ing and the connection is // lost or dropped due to bad auth Thread.currentThread().interrupt(); if (op != null) { op.cancel(); } done.set(true); // If we were interrupted, tear down. } finally { long stepDiff = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - stepStart); msg = String.format("SASL Step took %dms on %s", stepDiff, node.toString()); level = mechsDiff >= AUTH_ROUNDTRIP_THRESHOLD ? Level.WARN : Level.DEBUG; getLogger().log(level, msg); } // Get the new status to inspect it. priorStatus = foundStatus.get(); if (priorStatus != null) { if (!priorStatus.isSuccess()) { getLogger().warn( "Authentication failed to " + node.getSocketAddress()); } } } long totalDiff = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - totalStart); msg = String.format("SASL Auth took %dms on %s", totalDiff, node.toString()); level = mechsDiff >= AUTH_TOTAL_THRESHOLD ? Level.WARN : Level.DEBUG; getLogger().log(level, msg); } private Operation buildOperation(OperationStatus st, OperationCallback cb, final String [] supportedMechs) { if (st == null) { return opFact.saslAuth(supportedMechs, node.getSocketAddress().toString(), null, authDescriptor.getCallback(), cb); } else { return opFact.saslStep(supportedMechs, KeyUtil.getKeyBytes( st.getMessage()), node.getSocketAddress().toString(), null, authDescriptor.getCallback(), cb); } } }
package pl.edu.icm.coansys.classification.documents.jobs; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.Random; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.log4j.Level; import org.apache.log4j.Logger; import pl.edu.icm.coansys.classification.documents.auxil.StringListIntListWritable; import pl.edu.icm.coansys.disambiguation.auxil.LoggingInDisambiguation; import pl.edu.icm.coansys.disambiguation.auxil.TextArrayWritable; import pl.edu.icm.coansys.disambiguation.features.FeatureInfo; /** * * @author pdendek * @version 1.0 * @since 2012-08-07 */ public class TfidfReducer extends Reducer<Text, StringListIntListWritable, TextArrayWritable, DoubleWritable> { private static Logger logger = Logger.getLogger(LoggingInDisambiguation.class); protected String reducerId = new Date().getTime() + "_" + new Random().nextFloat(); private int docs_num=1; @Override public void setup(Context context) throws IOException, InterruptedException { logger.setLevel(Level.DEBUG); Configuration conf = context.getConfiguration(); docs_num = Integer.parseInt(conf.get("DOCS_NUM")); } @Override /** * (IN) accepts key-value pairs containing K:word, V: docId + number of word occurrences in the document + no. of all words in doc * (OUT) emit key-value pairs containing K:docId + word, V: tfidf */ public void reduce(Text key, Iterable<StringListIntListWritable> values, Context context) { int docsWithTerm = 0; for (Iterator it = values.iterator(); it.hasNext();) { docsWithTerm++; } double idf = Math.log(docs_num/(double)docsWithTerm); for(final StringListIntListWritable v : values){ double tf = (double)(v.getIntList().get(0))/(double)(v.getIntList().get(1)); try { context.write(new TextArrayWritable(new Text[]{new Text(v.getStringList().get(0)), key}), new DoubleWritable(tf*idf)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.annimon.hotarufx.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import javafx.stage.FileChooser; import javafx.stage.Stage; import lombok.val; public class FileManager implements DocumentManager { private static final String FILE_OPEN_TITLE = "Select file to open"; private static final String FILE_SAVE_TITLE = "Save file"; private final FileChooser fileChooser; private File currentFile; private DocumentListener listener; public FileManager() { fileChooser = new FileChooser(); fileChooser.getExtensionFilters().setAll( new FileChooser.ExtensionFilter("Supported Files", "*.hfx") ); } @Override public Optional<String> name() { return Optional.ofNullable(currentFile) .map(File::getName); } @Override public void newDocument() { currentFile = null; } @Override public boolean open(Stage stage, Consumer<String> contentConsumer) { fileChooser.setTitle(FILE_OPEN_TITLE); if (currentFile != null) { fileChooser.setInitialDirectory(currentFile.getParentFile()); } currentFile = fileChooser.showOpenDialog(stage); if (currentFile == null) { return false; } if (!currentFile.exists() || !currentFile.isFile()) { return false; } val content = readFile(currentFile); if (content.isEmpty()) { return false; } contentConsumer.accept(content); return true; } @Override public boolean save(Stage stage, Supplier<String> contentSupplier) { if (currentFile == null) { return saveAs(stage, contentSupplier); } return writeFile(currentFile, contentSupplier); } @Override public boolean saveAs(Stage stage, Supplier<String> contentSupplier) { fileChooser.setTitle(FILE_SAVE_TITLE); if (currentFile != null) { fileChooser.setInitialDirectory(currentFile.getParentFile()); fileChooser.setInitialFileName(currentFile.getName()); } else { fileChooser.setInitialFileName("animation.hfx"); } val newFile = fileChooser.showSaveDialog(stage); if (newFile == null) { return false; } currentFile = newFile; return writeFile(currentFile, contentSupplier); } @Override public void addDocumentListener(DocumentListener listener) { this.listener = listener; } private String readFile(File file) { try (InputStream is = new FileInputStream(file)) { return IOStream.readContent(is); } catch (IOException ioe) { if (listener != null) { listener.logError("Unable to open file " + file.getName()); } return ""; } } private boolean writeFile(File file, Supplier<String> contentSupplier) { try (OutputStream os = new FileOutputStream(file); Writer writer = new OutputStreamWriter(os, "UTF-8")) { writer.write(contentSupplier.get()); writer.flush(); return true; } catch (IOException ioe) { if (listener != null) { listener.logError("Unable to save file " + file.getName()); } return false; } } }
package be.billington.rob; import be.billington.rob.bitbucket.BitbucketCredentials; import be.billington.rob.github.GithubCredentials; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.core.ConsoleAppender; import okio.*; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import ch.qos.logback.classic.Logger; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class MainSWT { public static final String CONFIG_KEY = "key"; public static final String CONFIG_SECRET = "secret"; public static final String CONFIG_TOKEN = "token"; private Shell shell; private Text txtOwner, txtRepo, txtApi, txtPrefix, txtBranch, txtConsole, txtFilePath, txtFromDate, txtToDate; private Logger logger; private File configFile; private Map<String, String> config = new HashMap<>(); public MainSWT(Display display) { LoggerContext context = new LoggerContext(); logger = context.getLogger(MainSWT.class); shell = new Shell(display); shell.setText("Rob"); initConfig(); initUI(); initLogger(context); shell.setSize(1024, 768); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } private void initLogger(LoggerContext context){ ConsoleAppender consoleAppender = new ConsoleAppender<>(); UIAppender uiAppender = new UIAppender(txtConsole); PatternLayoutEncoder pa = new PatternLayoutEncoder(); pa.setPattern("%r %5p %c [%t] - %m%n"); pa.setContext(context); pa.start(); uiAppender.setEncoder(pa); uiAppender.setContext(context); uiAppender.start(); consoleAppender.setEncoder(pa); consoleAppender.setContext(context); consoleAppender.start(); logger.addAppender(uiAppender); //logger.addAppender(consoleAppender); } private void initConfig(){ configFile = new File("./rob.conf"); try { if (!readConfig()){ createConfig(); } } catch (IOException e) { logger.error("IOException: " + e.getMessage(), e); } } private void writeConfig() throws IOException { Sink sink = Okio.sink(configFile); BufferedSink bufferedSink = Okio.buffer(sink); this.config.forEach((k, v) -> { try { bufferedSink.writeUtf8(k + "=" + v + "\n"); } catch (IOException e) { logger.error("IOException: " + e.getMessage(), e); } }); bufferedSink.close(); sink.close(); } private boolean readConfig() throws IOException { if (!configFile.exists()){ return false; } boolean simpleCheckatLeastOneLine = false; Source source = Okio.source(configFile); BufferedSource bufferedSource = Okio.buffer(source); String line = bufferedSource.readUtf8Line(); while (line != null){ if (line.contains("=")) { String[] values = line.split("="); if (values.length > 1) { this.config.put(values[0], values[1]); } } line = bufferedSource.readUtf8Line(); simpleCheckatLeastOneLine = true; } bufferedSource.close(); source.close(); return simpleCheckatLeastOneLine; } private void createConfig() { ConfigDialog configDialog = new ConfigDialog(shell, config); config = configDialog.open(); try { writeConfig(); } catch (IOException e) { logger.error("IOException: " + e.getMessage(), e); } } public void initUI() { shell.setLayout(new FillLayout()); //1st column Composite container = new Composite(shell, SWT.PUSH); GridLayout layout = new GridLayout(2, false); layout.marginRight = 5; layout.marginLeft = 10; container.setLayout(layout); Label lblRepo = new Label(container, SWT.NONE); lblRepo.setText("Repository name:"); txtRepo = new Text(container, SWT.BORDER); txtRepo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtRepo.setText("wecycle-android-recyclemanager"); Label lblOwner = new Label(container, SWT.NONE); GridData gd_lblNewLabel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel.horizontalIndent = 1; lblOwner.setLayoutData(gd_lblNewLabel); lblOwner.setText("Owner:"); txtOwner = new Text(container, SWT.BORDER); txtOwner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtOwner.setText("afrogleap"); Label lblApi = new Label(container, SWT.NONE); lblApi.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblApi.setText("API:"); txtApi = new Text(container, SWT.BORDER); txtApi.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtApi.setText("bitbucket"); Label lblPrefix = new Label(container, SWT.NONE); lblPrefix.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblPrefix.setText("Jira Prefix:"); txtPrefix = new Text(container, SWT.BORDER); txtPrefix.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtPrefix.setText("WEC"); Label lblBranch = new Label(container, SWT.NONE); lblBranch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblBranch.setText("Branch:"); txtBranch = new Text(container, SWT.BORDER); txtBranch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtBranch.setText("development"); Label lblFilePath = new Label(container, SWT.NONE); lblFilePath.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblFilePath.setText("File Path:"); txtFilePath = new Text(container, SWT.BORDER); txtFilePath.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtFilePath.setText("./target/changelog.txt"); Label lblFromDate = new Label(container, SWT.NONE); lblFromDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblFromDate.setText("From date:"); txtFromDate = new Text(container, SWT.BORDER); txtFromDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtFromDate.setText(""); Label lblToDate = new Label(container, SWT.NONE); lblToDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblToDate.setText("To date:"); txtToDate = new Text(container, SWT.BORDER); txtToDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtToDate.setText(""); Button generate = new Button(container, SWT.PUSH); generate.setText("Generate"); generate.setBounds(50, 50, 80, 30); generate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new RobThread(logger, txtApi.getText(), txtOwner.getText(), txtRepo.getText(), txtPrefix.getText(), txtBranch.getText(), txtFilePath.getText(), txtFromDate.getText(), txtToDate.getText(), config).start(); } }); Button output = new Button(container, SWT.PUSH); output.setText("Output"); output.setBounds(50, 50, 80, 30); output.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { loadGeneratedFile(); } }); Button settings = new Button(container, SWT.PUSH); settings.setText("Settings"); settings.setBounds(50, 50, 80, 30); settings.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { createConfig(); } }); Button quit = new Button(container, SWT.PUSH); quit.setText("Quit"); quit.setBounds(50, 50, 80, 30); quit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.getDisplay().dispose(); System.exit(0); } }); //2nd column Composite rightContainer = new Composite(shell, SWT.PUSH); rightContainer.setLayout(new FillLayout()); txtConsole = new Text(rightContainer, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); txtConsole.setEditable(false); } private void loadGeneratedFile() { try { Source source = Okio.source(new File(txtFilePath.getText())); BufferedSource bufferedSource = Okio.buffer(source); String content = bufferedSource.readUtf8(); txtConsole.setText(content); bufferedSource.close(); source.close(); } catch (IOException e) { logger.error("IOException: " + e.getMessage(), e); } } public void center(Shell shell) { Rectangle bds = shell.getDisplay().getBounds(); Point p = shell.getSize(); int nLeft = (bds.width - p.x) / 2; int nTop = (bds.height - p.y) / 2; shell.setBounds(nLeft, nTop, p.x, p.y); } public static void main(String[] args) { Display display = new Display(); new MainSWT(display); display.dispose(); } }
package com.google.android.apps.common.testing.ui.espresso.tests; import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData; import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView; import static com.google.android.apps.common.testing.ui.espresso.Espresso.pressBack; import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click; import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.closeSoftKeyboard; import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText; import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches; import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId; import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import com.google.android.apps.common.testing.ui.testapp.R; import com.google.android.apps.common.testing.ui.testapp.SimpleActivity; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; /** * Highlights basic * {@link com.google.android.apps.common.testing.ui.espresso.Espresso#onView(org.hamcrest.Matcher)} * functionality. */ @LargeTest public class BasicTest extends ActivityInstrumentationTestCase2<SimpleActivity> { @SuppressWarnings("deprecation") public BasicTest() { // This constructor was deprecated - but we want to support lower API levels. super("com.google.android.apps.common.testing.ui.testapp", SimpleActivity.class); } @Override public void setUp() throws Exception { super.setUp(); // Espresso will not launch our activity for us, we must launch it via getActivity(). getActivity(); } public void testSimpleClickAndCheckText() { onView(withId(R.id.button_simple)) .perform(click()); onView(withId(R.id.text_simple)) .check(matches(withText("Hello Espresso!"))); } public void testTypingAndPressBack() { // Close soft keyboard after type to avoid issues on devices with soft keyboard. onView(withId(R.id.sendtext_simple)) .perform(typeText("Have a cup of Espresso."), closeSoftKeyboard()); onView(withId(R.id.send_simple)) .perform(click()); // Clicking launches a new activity that shows the text entered above. You don't need to do // anything special to handle the activity transitions. Espresso takes care of waiting for the // new activity to be resumed and its view hierarchy to be laid out. onView(withId(R.id.display_data)) .check(matches(withText(("Have a cup of Espresso.")))); // Going back to the previous activity - lets make sure our text was perserved. pressBack(); onView(withId(R.id.sendtext_simple)) .check(matches(withText(containsString("Espresso")))); } @SuppressWarnings("unchecked") public void testClickOnSpinnerItemAmericano(){ // Open the spinner. onView(withId(R.id.spinner_simple)) .perform(click()); // Spinner creates a List View with its contents - this can be very long and the element not // contributed to the ViewHierarchy - by using onData we force our desired element into the // view hierarchy. onData(allOf(is(instanceOf(String.class)), is("Americano"))) .perform(click()); onView(withId(R.id.spinnertext_simple)) .check(matches(withText(containsString("Americano")))); } }
package nl.topicus.mssql2monetdb; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.math.BigDecimal; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class CopyTool { static Logger log = Logger.getLogger(CopyTool.class); public static final int DEFAULT_BATCH_SIZE = 10000; private Properties config; private Connection mssqlConn; private Connection monetDbConn; private Map<String, CopyTable> tablesToCopy = new HashMap<String, CopyTable>(); private int batchSize = DEFAULT_BATCH_SIZE; public static String prepareMonetDbIdentifier (String ident) { // MonetDB only supports lowercase identifiers ident = ident.toLowerCase(); // MonetDB doesn't support any special characters so replace with underscore ident = ident.replaceAll("[^a-zA-Z0-9]+","_"); return ident; } public static String quoteMonetDbValue (String value) { return "'" + value.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'"; } public static String quoteMonetDbIdentifier (String ident) { // prepare identifier ident = prepareMonetDbIdentifier(ident); // make sure identifier is actually quoted ident = "\"" + ident + "\""; return ident; } public CopyTool (Properties config) { this.config = config; this.validateConfig(); this.findTablesToCopy(); } public int getBatchSize () { return this.batchSize; } public void run () { if (tablesToCopy.size() > 0) { this.openConnections(); for(CopyTable table : tablesToCopy.values()) { try { copyTable(table); } catch (SQLException e) { log.error("Unable to copy data from table '" + table.getFromName() + "'", e); } } this.closeConnections(); } log.info("Finished!"); } protected void copyTable(CopyTable table) throws SQLException { log.info("Starting with copy of table " + table.getFromName() + "..."); // select data from MS SQL Server Statement selectStmt = mssqlConn.createStatement(); // get number of rows in table ResultSet resultSet = selectStmt.executeQuery("SELECT COUNT(*) FROM [" + table.getFromName() + "]"); resultSet.next(); long rowCount = resultSet.getLong(1); log.info("Found " + rowCount + " rows in table " + table.getFromName()); resultSet.close(); // get all data from table resultSet = selectStmt.executeQuery("SELECT * FROM [" + table.getFromName() + "]"); // get meta data (column info and such) ResultSetMetaData metaData = resultSet.getMetaData(); // check table in monetdb checkTableInMonetDb(table, metaData); // do truncate? if (table.truncate()) { truncateTable(table); } // copy data try { copyData(table, resultSet, metaData, rowCount); } catch (BatchUpdateException e) { log.error("Copying data failed", e); // print full chain of exceptions SQLException nextException = e.getNextException(); while(nextException != null) { nextException.printStackTrace(); nextException = nextException.getNextException(); } } // close everything again resultSet.close(); selectStmt.close(); log.info("Finished copy of table " + table.getFromName()); } protected void checkTableInMonetDb (CopyTable table, ResultSetMetaData metaData) throws SQLException { // check if table exists Statement q = monetDbConn.createStatement(); boolean tableExists = true; try { q.executeQuery("SELECT * FROM " + table.getToTableSql() + " LIMIT 1"); } catch (SQLException e) { if (e.getMessage().indexOf("no such table") > -1) { // ok, so does not exist tableExists = false; } else { throw e; } } // can't auto create? if (tableExists == false && table.create() == false) { throw new SQLException("Table " + table.getToTableSql() + " does not exist in MonetDB database and auto-create is set to false"); } // need to drop? if (tableExists && table.drop()) { log.info("Dropping table " + table.getToTableSql() + " in MonetDB database..."); q.executeUpdate("DROP TABLE " + table.getToTableSql()); tableExists = false; log.info("Table dropped"); } if (tableExists) { // verify table is as expected this.verifyExistingTable(table, metaData); } else { // build SQL query to create table log.info("Creating table " + table.getToTableSql() + " on MonetDB server..."); StringBuilder createSql = new StringBuilder("CREATE TABLE " + table.getToTableSql() + " ("); for(int i=1; i <= metaData.getColumnCount(); i++) { createSql.append(createColumnSql(i, metaData)); createSql.append(","); } createSql.deleteCharAt(createSql.length()-1); createSql.append(")"); // execute CREATE TABLE SQL query q.execute(createSql.toString()); log.info("Table created"); } } protected void verifyExistingTable(CopyTable table, ResultSetMetaData metaData) throws SQLException { log.info("Verifying existing table " + table.getToTableSql() + " in MonetDB matches table schema in MS SQL..."); // do a select on the table in MonetDB to get its metadata Statement q = monetDbConn.createStatement(); ResultSet res = q.executeQuery("SELECT * FROM " + table.getToTableSql() + " LIMIT 1"); ResultSetMetaData monetDbMetaData = res.getMetaData(); // create a mapping of MonetDB columns and related column indexes HashMap<String, Integer> colMapping = new HashMap<String, Integer>(); for(int i=1; i <= monetDbMetaData.getColumnCount(); i++) { String colName = monetDbMetaData.getColumnName(i); colMapping.put(prepareMonetDbIdentifier(colName), i); } // loop through columns of MS SQL and verify with columns in MonetDB for(int i=1; i <= metaData.getColumnCount(); i++) { String colName = prepareMonetDbIdentifier(metaData.getColumnName(i)); // col name exists in MonetDB? if (colMapping.containsKey(colName)) { // verify type // TODO: actually verify type } else { // create column in MonetDB log.info("Column " + colName + " is missing in MonetDB table"); log.info("Adding column " + colName + " in table " + table.getToTableSql() + " in MonetDB..."); String sql = "ALTER TABLE " + table.getToTableSql() + " ADD COLUMN " + createColumnSql(i, metaData); Statement createColumn = monetDbConn.createStatement(); createColumn.execute(sql); log.info("Column added"); } } // close objects res.close(); q.close(); log.info("Table verified"); } protected String createColumnSql(int colIndex, ResultSetMetaData metaData) throws SQLException { StringBuilder createSql = new StringBuilder(); createSql.append(quoteMonetDbIdentifier(metaData.getColumnName(colIndex).toLowerCase())); createSql.append(" "); HashMap<Integer, String> sqlTypes = new HashMap<Integer, String>(); sqlTypes.put(Types.BIGINT, "bigint"); sqlTypes.put(Types.BLOB, "blob"); sqlTypes.put(Types.BOOLEAN, "boolean"); sqlTypes.put(Types.CHAR, "char"); sqlTypes.put(Types.CLOB, "clob"); sqlTypes.put(Types.DATE, "date"); sqlTypes.put(Types.DECIMAL, "decimal"); sqlTypes.put(Types.DOUBLE, "double"); sqlTypes.put(Types.FLOAT, "float"); sqlTypes.put(Types.INTEGER, "int"); sqlTypes.put(Types.NCHAR, "char"); sqlTypes.put(Types.NCLOB, "clob"); sqlTypes.put(Types.NUMERIC, "numeric"); sqlTypes.put(Types.NVARCHAR, "varchar"); sqlTypes.put(Types.REAL,"real"); sqlTypes.put(Types.SMALLINT, "smallint"); sqlTypes.put(Types.TIME,"time"); sqlTypes.put(Types.TIMESTAMP, "timestamp"); sqlTypes.put(Types.TINYINT, "tinyint"); sqlTypes.put(Types.VARCHAR, "varchar"); int colType = metaData.getColumnType(colIndex); String colTypeName = null; if (sqlTypes.containsKey(colType)) { colTypeName = sqlTypes.get(colType); } if (colTypeName == null) { throw new SQLException("Unknown SQL type " + colType + " (" + metaData.getColumnTypeName(colIndex) + ")"); } int precision = metaData.getPrecision(colIndex); int scale = metaData.getScale(colIndex); // fix for numeric/decimal columns with no actual decimals (i.e. numeric(19,0)) if ((colTypeName.equals("decimal") || colTypeName.equals("numeric")) && scale == 0) { if (precision <= 2) { colTypeName = "tinyint"; } else if (precision <= 4) { colTypeName = "smallint"; } else if (precision <= 9) { colTypeName = "int"; } else { colTypeName = "bigint"; } }; createSql.append(colTypeName); // some types required additional info if (colTypeName.equals("char") || colTypeName.equals("character") || colTypeName.equals("varchar") || colTypeName.equals("character varying")) { createSql.append(" (" + metaData.getColumnDisplaySize(colIndex) + ")"); } else if (colTypeName.equals("decimal") || colTypeName.equals("numeric")) { // MonetDB doesn't support a precision higher than 18 if (precision > 18) precision = 18; createSql.append(" (" + precision + ", " + scale + ")"); } else if (colTypeName.equals("double")) { createSql.append("[" + metaData.getPrecision(colIndex) + "]"); } createSql.append(" "); if (metaData.isAutoIncrement(colIndex)) { createSql.append("auto_increment "); } if (metaData.isNullable(colIndex) == ResultSetMetaData.columnNoNulls) { createSql.append("NOT NULL "); } return createSql.toString(); } protected void truncateTable(CopyTable table) throws SQLException { log.info("Truncating table " + table.getToTableSql() + " on MonetDB server..."); Statement truncateStmt = monetDbConn.createStatement(); truncateStmt.execute("DELETE FROM " + table.getToTableSql()); log.info("Table truncated"); } protected void copyData(CopyTable table, ResultSet resultSet, ResultSetMetaData metaData, long rowCount) throws SQLException { log.info("Copying data to table " + table.getToTableSql() + "..."); // build insert SQL StringBuilder insertSql = new StringBuilder("INSERT INTO "); insertSql.append(table.getToTableSql()); insertSql.append(" ("); String[] colNames = new String[metaData.getColumnCount()]; String[] values = new String[metaData.getColumnCount()]; for(int i=1; i <= metaData.getColumnCount(); i++) { String colName = metaData.getColumnName(i).toLowerCase(); colNames[i-1] = quoteMonetDbIdentifier(colName); } insertSql.append(StringUtils.join(colNames, ",")); insertSql.append(")"); insertSql.append(" VALUES ("); Statement insertStmt = monetDbConn.createStatement(); DecimalFormat formatPerc = new DecimalFormat(" monetDbConn.setAutoCommit(false); int batchCount = 0; long insertCount = 0; while(resultSet.next()) { for(int i=1; i <= metaData.getColumnCount(); i++) { Object value = resultSet.getObject(i); if (value == null) { values[i-1] = "NULL"; } else if (value instanceof Number) { values[i-1] = value.toString(); // empty value is unacceptable here, replace with NULL if (StringUtils.isEmpty(values[i-1])) { values[i-1] = "NULL"; } } else if (value instanceof String) { values[i-1] = quoteMonetDbValue((String)value); } else { throw new SQLException("Unknown value type: " + value.getClass().getName()); } } StringBuilder insertRecordSql = new StringBuilder(insertSql); insertRecordSql.append(StringUtils.join(values, ",")); insertRecordSql.append(")"); insertStmt.addBatch(insertRecordSql.toString()); batchCount++; if (batchCount % this.getBatchSize() == 0) { log.info("Inserting next batch of " + this.getBatchSize() + " records..."); insertStmt.executeBatch(); monetDbConn.commit(); insertStmt.clearBatch(); insertCount = insertCount + batchCount; batchCount = 0; log.info("Batch inserted"); float perc = ((float)insertCount / (float)rowCount) * 100; log.info("Progress: " + insertCount + " out of " + rowCount + " (" + formatPerc.format(perc) + "%)"); } } if (batchCount > 0) { log.info("Inserting final batch of " + batchCount + " records..."); insertStmt.executeBatch(); monetDbConn.commit(); insertStmt.clearBatch(); insertCount = insertCount + batchCount; log.info("Batch inserted"); float perc = ((float)insertCount / (float)rowCount) * 100; log.info("Progress: " + insertCount + " out of " + rowCount + " (" + formatPerc.format(perc) + "%)"); } monetDbConn.setAutoCommit(true); log.info("Finished copying data"); } protected void validateConfig () { boolean isMissing = false; for (CONFIG_KEYS key : CONFIG_KEYS.values()) { String value = config.getProperty(key.toString()); if (key.isRequired() && StringUtils.isEmpty(value)) { isMissing = true; log.error("Missing config property: " + key); } } if (isMissing) { log.fatal("Missing essential config properties"); System.exit(1); } // check if batch size has been specified String batchSizeStr = config.getProperty(CONFIG_KEYS.BATCH_SIZE.toString()); if (StringUtils.isEmpty(batchSizeStr) == false) { try { this.batchSize = Integer.parseInt(batchSizeStr); } catch (NumberFormatException e) { // don't care, just ignore } } } protected void findTablesToCopy () { for (Entry<Object, Object> entry : config.entrySet()) { String propName = entry.getKey().toString().toLowerCase(); String propValue = entry.getValue().toString(); boolean boolValue = (propValue.equalsIgnoreCase("true") || propValue.equalsIgnoreCase("yes")); String[] split = propName.split("\\."); if (split.length != 3) continue; if (split[0].equals("table") == false) continue; String id = split[1]; String key = split[2].toLowerCase(); if (tablesToCopy.containsKey(id) == false) { tablesToCopy.put(id, new CopyTable()); } CopyTable table = tablesToCopy.get(id); if (key.equals("from")) { table.setFromName(propValue); } else if (key.equals("to")) { table.setToName(propValue.toLowerCase()); } else if (key.equals("create")) { table.setCreate(boolValue); } else if (key.equals("truncate")) { table.setTruncate(boolValue); } else if (key.equals("schema")) { table.setSchema(propValue); } else if (key.equals("drop")) { table.setDrop(boolValue); } } // verify each specified has a from and to name Iterator<Entry<String, CopyTable>> iter = tablesToCopy.entrySet().iterator(); while(iter.hasNext()) { Entry<String, CopyTable> entry = iter.next(); String id = entry.getKey(); CopyTable table = entry.getValue(); if (StringUtils.isEmpty(table.getFromName())) { log.error("Configuration for '" + id + "' is missing name of from table"); iter.remove(); continue; } if (StringUtils.isEmpty(table.getToName())) { log.warn("Configuration for '" + id + "' is missing name of to table. Using name of from table (" + table.getFromName() + ")"); table.setToName(table.getFromName()); } } if (tablesToCopy.size() == 0) { log.error("Configuration has specified NO tables to copy!"); } else { log.info("The following tables will be copied: "); for(CopyTable table : tablesToCopy.values()) { log.info("* " + table.getFromName() + " -> " + table.getToName()); } } } protected void openConnections () { // make sure JDBC drivers are loaded try { Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); } catch (ClassNotFoundException e) { log.fatal("Unable to load MonetDB JDBC driver"); System.exit(1); } try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch (ClassNotFoundException e) { log.fatal("Unable to load MS SQL jTDS JDBC driver"); System.exit(1); } try { if (mssqlConn == null || mssqlConn.isClosed()) { Properties connProps = new Properties(); String user = config.getProperty(CONFIG_KEYS.MSSQL_USER.toString()); String password = config.getProperty(CONFIG_KEYS.MSSQL_PASSWORD.toString()); if (StringUtils.isEmpty(user) == false && StringUtils.isEmpty(password) == false) { connProps.setProperty("user", user); connProps.setProperty("password", password); } String url = "jdbc:jtds:sqlserver: config.getProperty(CONFIG_KEYS.MSSQL_SERVER.toString()) + "/" + config.getProperty(CONFIG_KEYS.MSSQL_DATABASE.toString()); log.info("Using connection URL for MS SQL Server: " + url); mssqlConn = DriverManager.getConnection(url, connProps); log.info("Opened connection to MS SQL Server"); } } catch (SQLException e) { log.fatal("Unable to open connection to MS SQL server", e); System.exit(1); } try { if (monetDbConn == null || monetDbConn.isClosed()) { Properties connProps = new Properties(); String user = config.getProperty(CONFIG_KEYS.MONETDB_USER.toString()); String password = config.getProperty(CONFIG_KEYS.MONETDB_PASSWORD.toString()); if (StringUtils.isEmpty(user) == false && StringUtils.isEmpty(password) == false) { connProps.setProperty("user", user); connProps.setProperty("password", password); } String url = "jdbc:monetdb: config.getProperty(CONFIG_KEYS.MONETDB_SERVER.toString()) + "/" + config.getProperty(CONFIG_KEYS.MONETDB_DATABASE.toString()); log.info("Using connection URL for MonetDB Server: " + url); monetDbConn = DriverManager.getConnection(url, connProps); log.info("Opened connection to MonetDB Server"); } } catch (SQLException e) { log.fatal("Unable to open connection to MonetDB server", e); closeConnections(); System.exit(1); } } protected void closeConnections () { log.info("Closing database connections..."); try { if (mssqlConn != null && mssqlConn.isClosed() == false) { mssqlConn.close(); log.info("Closed connection to MS SQL server"); } } catch (SQLException e) { // don't care about this exception log.warn("Unable to close connection to MS SQL server", e); } try { if (monetDbConn != null && monetDbConn.isClosed() == false) { monetDbConn.close(); log.info("Closed connection to MonetDB server"); } } catch (SQLException e) { // don't care about this exception log.warn("Unable to close connection to MonetDB server", e); } } /** * @param args */ public static void main(String[] args) { log.info("Started MSSQL2MonetDB copy tool"); PropertyConfigurator.configure("log4j.properties"); Options options = new Options(); OptionBuilder.hasArg(true); OptionBuilder.isRequired(true); OptionBuilder.withDescription("Specify the configuration properties file"); OptionBuilder.withLongOpt("config"); options.addOption(OptionBuilder.create("c")); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse( options, args); } catch (ParseException e) { System.err.println("ERROR: " + e.getMessage()); System.out.println(""); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("mssql2monetdb", options); System.exit(1); } File configFile = new File(cmd.getOptionValue("config")); log.info("Using config file: " + configFile.getAbsolutePath()); if (configFile.exists() == false || configFile.canRead() == false) { } Properties config = new Properties(); try { config.load(new FileInputStream(configFile)); } catch (Exception e) { System.err.println("ERROR: unable to read config file"); e.printStackTrace(); System.exit(1); } // run tool (new CopyTool(config)).run(); } }
package com.apps.darkstorm.swrpg; import android.content.Context; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.apps.darkstorm.swrpg.load.DriveLoadMinions; import com.apps.darkstorm.swrpg.load.LoadMinions; import com.apps.darkstorm.swrpg.sw.Minion; import com.apps.darkstorm.swrpg.ui.cards.MinionCard; import java.util.ArrayList; public class MinionList extends Fragment { private OnMinionListInteractionListener mListener; Handler topHandle; Handler handle; ArrayList<Minion> minions = new ArrayList<>(); public MinionList() {} public static MinionList newInstance(Handler topHandle) { MinionList fragment = new MinionList(); fragment.topHandle = topHandle; return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View top = inflater.inflate(R.layout.general_list, container, false); final SwipeRefreshLayout refresh = (SwipeRefreshLayout)top.findViewById(R.id.swipe_refresh); refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loadMinions(); } }); final LinearLayout linLay = (LinearLayout)top.findViewById(R.id.main_lay); handle = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { if(msg.arg1==20){ refresh.setRefreshing(true); }else if(msg.arg1==-20){ refresh.setRefreshing(false); }else if(msg.arg1==5){ Snackbar.make(top,R.string.cloud_fail,Snackbar.LENGTH_LONG).show(); } if (msg.obj instanceof ArrayList){ ArrayList<Minion> chars = (ArrayList<Minion>)msg.obj; if(!chars.equals(minions)||linLay.getChildCount()!=chars.size()) { linLay.removeAllViews(); minions = chars; for(Minion chara:chars){ if(getActivity()!=null linLay.addView(MinionCard.getCard(getActivity(),linLay,chara,handle)); } } } if (msg.obj instanceof Minion){ if (msg.arg1==-1){ int ind = minions.indexOf(msg.obj); Minion min = (Minion)msg.obj; min.delete(getActivity()); if(ind != -1){ linLay.removeViewAt(ind); minions.remove(ind); } }else{ Message out = topHandle.obtainMessage(); out.arg1 = msg.arg1; out.obj = msg.obj; topHandle.sendMessage(out); } } } }; return top; } public void loadMinions(){ AsyncTask<Void,Void,Void> async = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Message dal = handle.obtainMessage(); dal.arg1 = 20; handle.sendMessage(dal); if(ContextCompat.checkSelfPermission(MinionList.this.getContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ while(((SWrpg)getActivity().getApplication()).askingPerm){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } if(ContextCompat.checkSelfPermission(MinionList.this.getContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){ if(((SWrpg)getActivity().getApplication()).prefs.getBoolean(getString(R.string.google_drive_key),false)){ int timeout = 0; while((((SWrpg)getActivity().getApplication()).gac == null || !((SWrpg)getActivity().getApplication()).gac.isConnected())&& timeout< 50){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } timeout++; } if(timeout != 50) { DriveLoadMinions dlc = new DriveLoadMinions(getActivity()); if (dlc.minions != null) { dlc.saveLocal(getActivity()); } }else{ Message out = handle.obtainMessage(); out.arg1 = 5; handle.sendMessage(out); } } LoadMinions lc = new LoadMinions(getActivity()); Message out = handle.obtainMessage(); out.obj = lc.minions; handle.sendMessage(out); } Message out = handle.obtainMessage(); out.arg1 = -20; handle.sendMessage(out); return null; } }; async.execute(); } public void onResume(){ super.onResume(); loadMinions(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnMinionListInteractionListener) { mListener = (OnMinionListInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnMinionListInteractionListener { } }
package no.stelar7.api.l4j8.impl; import no.stelar7.api.l4j8.basic.calling.*; import no.stelar7.api.l4j8.basic.constants.api.*; import no.stelar7.api.l4j8.basic.constants.types.*; import no.stelar7.api.l4j8.pojo.match.*; import javax.annotation.Nullable; import java.util.*; @SuppressWarnings("unchecked") public final class MatchAPI { private static final MatchAPI INSTANCE = new MatchAPI(); public static MatchAPI getInstance() { return MatchAPI.INSTANCE; } private MatchAPI() { // Hide public constructor } /** * Returns a list of the accounts games * <p> * A number of optional parameters are provided for filtering. * It is up to the caller to ensure that the combination of filter parameters provided is valid for the requested account, otherwise, no matches may be returned. * If beginIndex is specified, but not endIndex, then endIndex defaults to beginIndex+50. * If endIndex is specified, but not beginIndex, then beginIndex defaults to 0. * If both are specified, then endIndex must be greater than beginIndex. * The maximum range allowed is 50, otherwise a 400 error code is returned. * If beginTime is specified, but not endTime, then these parameters are ignored. * If endTime is specified, but not beginTime, then beginTime defaults to the start of the account's match history. * If both are specified, then endTime should be greater than beginTime. * The maximum time range allowed is one week, otherwise a 400 error code is returned. * * @param server the platform the account is on * @param accountId the account to check * @param beginTime optional filter the games started after this time * @param endTime optional filter for games started before this time * @param beginIndex optional filter for skipping the first x games * @param endIndex optional filter for skipping only showing x games * @param rankedQueue optional filter for selecting the queue * @param season optional filter for selecting the season * @param championId optional filter for selecting the champion played * @return MatchList */ public List<MatchReference> getMatchList(Platform server, long accountId, @Nullable Long beginTime, @Nullable Long endTime, @Nullable Integer beginIndex, @Nullable Integer endIndex, @Nullable Set<GameQueueType> rankedQueue, @Nullable Set<SeasonType> season, @Nullable List<Integer> championId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.ACCOUNT_ID_PLACEHOLDER, String.valueOf(accountId)) .withEndpoint(URLEndpoint.V3_MATCHLIST) .withPlatform(server); if (beginIndex != null) { builder.withURLData(Constants.BEGININDEX_PLACEHOLDER_DATA, beginIndex.toString()); } if (endIndex != null) { if ((beginIndex != null ? beginIndex : 0) + 50 - endIndex < 0) { throw new IllegalArgumentException("begin-endindex out of range! (difference between beginIndex and endIndex is more than 50)"); } builder.withURLData(Constants.ENDINDEX_PLACEHOLDER_DATA, endIndex.toString()); } if (beginTime != null) { builder.withURLData(Constants.BEGINTIME_PLACEHOLDER_DATA, beginTime.toString()); } if (endTime != null) { if ((beginTime != null ? beginTime : 0) + 604800000 - endTime < 0) { throw new IllegalArgumentException("begin-endtime out of range! (difference between beginTime and endTime is more than one week)"); } builder.withURLData(Constants.ENDTIME_PLACEHOLDER_DATA, endTime.toString()); } if (rankedQueue != null) { rankedQueue.forEach(queue -> builder.withURLDataAsSet(Constants.QUEUE_PLACEHOLDER_DATA, String.valueOf(queue.getValue()))); } if (season != null) { season.forEach(sea -> builder.withURLDataAsSet(Constants.SEASON_PLACEHOLDER_DATA, String.valueOf(sea.getValue()))); } if (championId != null) { championId.forEach(id -> builder.withURLDataAsSet(Constants.CHAMPION_PLACEHOLDER_DATA, String.valueOf(id))); } /* Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_MATCHLIST, server, accountId, beginTime, endTime, beginIndex, endIndex, rankedQueue, season, championId); if (chl.isPresent()) { return (List<MatchReference>) chl.get(); }*/ MatchList list = (MatchList) builder.build(); if (list == null) { return Collections.emptyList(); } // DataCall.getCacheProvider().store(URLEndpoint.V3_MATCHLIST, list.getMatches()); return list.getMatches(); } /** * A list of the accounts most recent games (includes normal games) * * @param server the platform the account is on ATM * @param accountId the account to check * @return MatchList */ public List<MatchReference> getRecentMatches(Platform server, long accountId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.ACCOUNT_ID_PLACEHOLDER, String.valueOf(accountId)) .withEndpoint(URLEndpoint.V3_MATCHLIST_RECENT) .withPlatform(server); /* Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_MATCHLIST_RECENT, server, accountId); if (chl.isPresent()) { return (List<MatchReference>) chl.get(); } */ MatchList list = (MatchList) builder.build(); if (list == null) { return Collections.emptyList(); } // DataCall.getCacheProvider().store(URLEndpoint.V3_MATCHLIST_RECENT, list.getMatches()); return list.getMatches(); } /** * Returns the match data from a match id * * @param server the platform the match was played on * @param matchId the id to check * @return Match */ public Match getMatch(Platform server, long matchId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.MATCH_ID_PLACEHOLDER, String.valueOf(matchId)) .withEndpoint(URLEndpoint.V3_MATCH) .withPlatform(server); Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_MATCH, server, matchId); if (chl.isPresent()) { return (Match) chl.get(); } Match match = (Match) builder.build(); DataCall.getCacheProvider().store(URLEndpoint.V3_MATCH, match); return match; } /** * Returns the timeline relating to a match. * Not avaliable for matches older than a year * * @param server the platform to find the match on * @param matchId the matchId to find timeline for * @return MatchTimeline if avaliable */ public MatchTimeline getTimeline(Platform server, long matchId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.MATCH_ID_PLACEHOLDER, String.valueOf(matchId)) .withEndpoint(URLEndpoint.V3_TIMELINE) .withPlatform(server); Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_TIMELINE, server, matchId); if (chl.isPresent()) { return (MatchTimeline) chl.get(); } MatchTimeline timeline = (MatchTimeline) builder.build(); DataCall.getCacheProvider().store(URLEndpoint.V3_TIMELINE, timeline); return timeline; } }
package com.dpanayotov.gameoflife.life; import java.util.Arrays; import java.util.Random; public class Grid { public int[][] cells = new int[Constants.GRID_WIDTH][Constants.GRID_HEIGHT]; public Grid(boolean populate) { if (populate) { populate(); } else { for (int[] row : cells) { Arrays.fill(row, 0); } } } public Grid(Grid grid) { cells = new int[grid.cells.length][]; for(int i=0;i<grid.cells.length;i++){ cells[i] = Arrays.copyOf(grid.cells[i], grid.cells[i].length); } } public int getNeighboursCount(int x, int y) { int total = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { total += cells[(Constants.GRID_WIDTH + (x + i)) % Constants.GRID_WIDTH] [(Constants.GRID_HEIGHT + (y + j)) % Constants.GRID_HEIGHT]; //mod is used for the edge warp } } total -= cells[x][y]; return total; } public void populate() { Random random = new Random(92484829894l); for (int i = 0; i < Constants.GRID_WIDTH; i++) { for (int j = 0; j < Constants.GRID_HEIGHT; j++) { cells[i][j] = random.nextInt(2); } } } public void mirrorPopulate() { Random random = new Random(92484829894l); for (int i = 0; i < Constants.GRID_WIDTH/2+1; i++) { for (int j = 0; j < Constants.GRID_HEIGHT; j++) { cells[i][j] = random.nextInt(2); cells[Constants.GRID_WIDTH - i - 1][j] = cells[i][j]; } } } }
package org.agmip.ui.quadui; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Scanner; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.agmip.dome.DomeUtil; import org.agmip.dome.Engine; import org.agmip.translators.csv.DomeInput; import org.agmip.util.MapUtil; import org.apache.pivot.util.concurrent.Task; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplyDomeTask extends Task<HashMap> { private static Logger log = LoggerFactory.getLogger(ApplyDomeTask.class); private HashMap<String, HashMap<String, Object>> ovlDomes = new HashMap<String, HashMap<String, Object>>(); private HashMap<String, HashMap<String, Object>> stgDomes = new HashMap<String, HashMap<String, Object>>(); private HashMap<String, Object> linkDomes = new HashMap<String, Object>(); private HashMap<String, String> ovlLinks = new HashMap<String, String>(); private HashMap<String, String> stgLinks = new HashMap<String, String>(); private LinkedHashMap<String, String> orgOvlLinks = new LinkedHashMap<String, String>(); private LinkedHashMap<String, String> orgStgLinks = new LinkedHashMap<String, String>(); // private HashMap<String, ArrayList<String>> wthLinks = new HashMap<String, ArrayList<String>>(); // private HashMap<String, ArrayList<String>> soilLinks = new HashMap<String, ArrayList<String>>(); private HashMap source; private String mode; private boolean autoApply; public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m, boolean autoApply) { this.source = m; this.mode = mode; this.autoApply = autoApply; // Setup the domes here. loadDomeLinkFile(linkFile); log.debug("link csv: {}", ovlLinks); if (mode.equals("strategy")) { loadDomeFile(strategyFile, stgDomes); } loadDomeFile(fieldFile, ovlDomes); } private void loadDomeLinkFile(String fileName) { String fileNameTest = fileName.toUpperCase(); log.debug("Loading LINK file: {}", fileName); linkDomes = null; try { // if (fileNameTest.endsWith(".ZIP")) { // log.debug("Entering Zip file handling"); // ZipFile z = null; // try { // z = new ZipFile(fileName); // Enumeration entries = z.entries(); // while (entries.hasMoreElements()) { // // Do we handle nested zips? Not yet. // ZipEntry entry = (ZipEntry) entries.nextElement(); // File zipFileName = new File(entry.getName()); // if (zipFileName.getName().toLowerCase().endsWith(".csv") && ! zipFileName.getName().startsWith(".")) { // log.debug("Processing file: {}", zipFileName.getName()); // DomeInput translator = new DomeInput(); // translator.readCSV(z.getInputStream(entry)); // HashMap<String, Object> link = translator.getDome(); // log.debug("link info: {}", link.toString()); // if (!link.isEmpty()) { // if (link.containsKey("link_overlay")) { // // Combine csv link // if (link.containsKey("link_stragty")) { // // Combine csv link // z.close(); // } catch (Exception ex) { // log.error("Error processing DOME file: {}", ex.getMessage()); // HashMap<String, Object> d = new HashMap<String, Object>(); // d.put("errors", ex.getMessage()); // } else if (fileNameTest.endsWith(".CSV")) { log.debug("Entering single CSV file DOME handling"); DomeInput translator = new DomeInput(); linkDomes = (HashMap<String, Object>) translator.readFile(fileName); } else if (fileNameTest.endsWith(".ACEB")) { log.debug("Entering single ACEB file DOME handling"); ObjectMapper mapper = new ObjectMapper(); String json = new Scanner(new GZIPInputStream(new FileInputStream(fileName)), "UTF-8").useDelimiter("\\A").next(); linkDomes = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {}); linkDomes = (HashMap) linkDomes.values().iterator().next(); } if (linkDomes != null) { log.debug("link info: {}", linkDomes.toString()); try { if (!linkDomes.isEmpty()) { if (linkDomes.containsKey("link_overlay")) { ovlLinks = (HashMap<String, String>) linkDomes.get("link_overlay"); } if (linkDomes.containsKey("link_stragty")) { stgLinks = (HashMap<String, String>) linkDomes.get("link_stragty"); } } } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } private String getLinkIds(String domeType, HashMap entry) { String exname = MapUtil.getValueOr(entry, "exname", ""); String wst_id = MapUtil.getValueOr(entry, "wst_id", ""); String soil_id = MapUtil.getValueOr(entry, "soil_id", ""); String linkIdsExp = getLinkIds(domeType, "EXNAME", exname); String linkIdsWst = getLinkIds(domeType, "WST_ID", wst_id); String linkIdsSoil = getLinkIds(domeType, "SOIL_ID", soil_id); String ret = ""; if (!linkIdsExp.equals("")) { ret += linkIdsExp + "|"; } if (!linkIdsWst.equals("")) { ret += linkIdsWst + "|"; } if (!linkIdsSoil.equals("")) { ret += linkIdsSoil; } if (ret.endsWith("|")) { ret = ret.substring(0, ret.length() - 1); } return ret; } private String getLinkIds(String domeType, String idType, String id) { HashMap<String, String> links; if (domeType.equals("strategy")) { links = stgLinks; } else if (domeType.equals("overlay")) { links = ovlLinks; } else { return ""; } if (links.isEmpty() || id.equals("")) { return ""; } String linkIds = ""; ArrayList<String> altLinkIds = new ArrayList(); altLinkIds.add(idType + "_ALL"); if (id.matches("[^_]+_\\d+$") && domeType.equals("strategy")) { altLinkIds.add(idType + "_" + id.replaceAll("_\\d+$", "")); } else if (id.matches(".+_\\d+__\\d+$") && domeType.equals("overlay")) { altLinkIds.add(idType + "_" + id.replaceAll("__\\d+$", "")); altLinkIds.add(idType + "_" + id.replaceAll("_\\d+__\\d+$", "")); } altLinkIds.add(idType + "_" + id); for (String linkId : altLinkIds) { if (links.containsKey(linkId)) { linkIds += links.get(linkId) + "|"; } } if (linkIds.endsWith("|")) { linkIds = linkIds.substring(0, linkIds.length() - 1); } return linkIds; } private void setOriLinkIds(HashMap entry, String domeIds, String domeType) { HashMap<String, String> links; if (domeType.equals("strategy")) { links = orgStgLinks; } else if (domeType.equals("overlay")) { links = orgOvlLinks; } else { return; } String exname = MapUtil.getValueOr(entry, "exname", ""); if (exname.matches(".+_\\d+__\\d+$") && "Y".equals(MapUtil.getValueOr(entry, "seasonal_dome_applied", ""))) { exname = exname.replaceAll("__\\d+$", ""); } if (!exname.equals("")) { links.put("EXNAME_" + exname, domeIds); } else { String soil_id = MapUtil.getValueOr(entry, "soil_id", ""); String wst_id = MapUtil.getValueOr(entry, "wst_id", ""); if (!soil_id.equals("")) { links.put("SOIL_ID_" + soil_id, domeIds); } else if (!wst_id.equals("")) { links.put("WST_ID_" + wst_id, domeIds); } } } private void loadDomeFile(String fileName, HashMap<String, HashMap<String, Object>> domes) { String fileNameTest = fileName.toUpperCase(); log.info("Loading DOME file: {}", fileName); if (fileNameTest.endsWith(".ZIP")) { log.debug("Entering Zip file handling"); ZipFile z = null; try { z = new ZipFile(fileName); Enumeration entries = z.entries(); while (entries.hasMoreElements()) { // Do we handle nested zips? Not yet. ZipEntry entry = (ZipEntry) entries.nextElement(); File zipFileName = new File(entry.getName()); if (zipFileName.getName().toLowerCase().endsWith(".csv") && !zipFileName.getName().startsWith(".")) { log.debug("Processing file: {}", zipFileName.getName()); DomeInput translator = new DomeInput(); translator.readCSV(z.getInputStream(entry)); HashMap<String, Object> dome = translator.getDome(); log.debug("dome info: {}", dome.toString()); String domeName = DomeUtil.generateDomeName(dome); if (!domeName.equals(" domes.put(domeName, new HashMap<String, Object>(dome)); } } } z.close(); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } else if (fileNameTest.endsWith(".CSV")) { log.debug("Entering single CSV file DOME handling"); try { DomeInput translator = new DomeInput(); HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName); String domeName = DomeUtil.generateDomeName(dome); log.debug("Dome name: {}", domeName); log.debug("Dome layout: {}", dome.toString()); domes.put(domeName, dome); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } else if (fileNameTest.endsWith(".ACEB")) { log.debug("Entering single ACEB file DOME handling"); try { ObjectMapper mapper = new ObjectMapper(); String json = new Scanner(new GZIPInputStream(new FileInputStream(fileName)), "UTF-8").useDelimiter("\\A").next(); HashMap<String, HashMap<String, Object>> tmp = mapper.readValue(json, new TypeReference<HashMap<String, HashMap<String, Object>>>() {}); // domes.putAll(tmp); for (HashMap dome : tmp.values()) { String domeName = DomeUtil.generateDomeName(dome); if (!domeName.equals(" domes.put(domeName, new HashMap<String, Object>(dome)); } } log.debug("Domes layout: {}", domes.toString()); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } } @Override public HashMap<String, Object> execute() { // First extract all the domes and put them in a HashMap by DOME_NAME // The read the DOME_NAME field of the CSV file // Split the DOME_NAME, and then apply sequentially to the HashMap. // PLEASE NOTE: This can be a massive undertaking if the source map // is really large. Need to find optimization points. HashMap<String, Object> output = new HashMap<String, Object>(); //HashMap<String, ArrayList<HashMap<String, String>>> dome; // Load the dome if (ovlDomes.isEmpty() && stgDomes.isEmpty()) { log.info("No DOME to apply."); HashMap<String, Object> d = new HashMap<String, Object>(); //d.put("domeinfo", new HashMap<String, String>()); d.put("domeoutput", source); return d; } if (autoApply) { HashMap<String, Object> d = new HashMap<String, Object>(); if (ovlDomes.size() > 1) { log.error("Auto-Apply feature only allows one field overlay file per run"); d.put("errors", "Auto-Apply feature only allows one field overlay file per run"); return d; } else if (stgDomes.size() > 1) { log.error("Auto-Apply feature only allows one seasonal strategy file per run"); d.put("errors", "Auto-Apply feature only allows one seasonal strategy file per run"); return d; } } // Flatten the data and apply the dome. Engine domeEngine; ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source); boolean noExpMode = false; if (flattenedData.isEmpty()) { log.info("No experiment data detected, will try Weather and Soil data only mode"); noExpMode = true; flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils")); flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers")); // flatSoilAndWthData(flattenedData, "soil"); // flatSoilAndWthData(flattenedData, "weather"); if (flattenedData.isEmpty()) { HashMap<String, Object> d = new HashMap<String, Object>(); log.error("No data found from input file, no DOME will be applied for data set {}", source.toString()); d.put("errors", "Loaded raw data is invalid, please check input files"); return d; } } if (mode.equals("strategy")) { log.debug("Domes: {}", stgDomes.toString()); log.debug("Entering Strategy mode!"); if (!noExpMode) { updateWthReferences(updateExpReferences(true)); flattenedData = MapUtil.flatPack(source); } // int cnt = 0; // for (HashMap<String, Object> entry : MapUtil.getRawPackageContents(source, "experiments")) { // log.debug("Exp at {}: {}, {}", // cnt, // entry.get("wst_id"), // entry.get("clim_id"), // ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"), // ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id") // cnt++; String stgDomeName = ""; if (autoApply) { for (String domeName : stgDomes.keySet()) { stgDomeName = domeName; } log.info("Auto apply seasonal strategy: {}", stgDomeName); } Engine generatorEngine; ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>(); for (HashMap<String, Object> entry : flattenedData) { if (autoApply) { entry.put("seasonal_strategy", stgDomeName); } String domeName = getLinkIds("strategy", entry); if (domeName.equals("")) { domeName = MapUtil.getValueOr(entry, "seasonal_strategy", ""); } else { entry.put("seasonal_strategy", domeName); log.debug("Apply seasonal strategy domes from link csv: {}", domeName); } setOriLinkIds(entry, domeName, "strategy"); String tmp[] = domeName.split("[|]"); String strategyName; if (tmp.length > 1) { log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied"); for (int i = 1; i < tmp.length; i++) { setFailedDomeId(entry, "seasonal_dome_failed", tmp[i]); } } strategyName = tmp[0]; log.info("Apply DOME {} for {}", strategyName, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>")))); log.debug("Looking for ss: {}", strategyName); if (!strategyName.equals("")) { if (stgDomes.containsKey(strategyName)) { log.debug("Found strategyName"); entry.put("dome_applied", "Y"); entry.put("seasonal_dome_applied", "Y"); generatorEngine = new Engine(stgDomes.get(strategyName), true); if (!noExpMode) { // Check if there is no weather or soil data matched with experiment if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) { log.warn("No scenario weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) { log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } } ArrayList<HashMap<String, Object>> newEntries = generatorEngine.applyStg(flatSoilAndWthData(entry, noExpMode)); log.debug("New Entries to add: {}", newEntries.size()); strategyResults.addAll(newEntries); } else { log.error("Cannot find strategy: {}", strategyName); setFailedDomeId(entry, "seasonal_dome_failed", strategyName); } } } log.debug("=== FINISHED GENERATION ==="); log.debug("Generated count: {}", strategyResults.size()); ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments"); exp.clear(); exp.addAll(strategyResults); flattenedData = MapUtil.flatPack(source); if (noExpMode) { flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils")); flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers")); } } if (!noExpMode) { if (mode.equals("strategy")) { updateExpReferences(false); } else { updateWthReferences(updateExpReferences(false)); } flattenedData = MapUtil.flatPack(source); } String ovlDomeName = ""; if (autoApply) { for (String domeName : ovlDomes.keySet()) { ovlDomeName = domeName; } log.info("Auto apply field overlay: {}", ovlDomeName); } int cnt = 0; for (HashMap<String, Object> entry : flattenedData) { log.debug("Exp at {}: {}, {}, {}", cnt, entry.get("wst_id"), ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"), ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id")); cnt++; if (autoApply) { entry.put("field_overlay", ovlDomeName); } String domeName = getLinkIds("overlay", entry); if (domeName.equals("")) { domeName = MapUtil.getValueOr(entry, "field_overlay", ""); } else { entry.put("field_overlay", domeName); log.debug("Apply field overlay domes from link csv: {}", domeName); } setOriLinkIds(entry, domeName, "overlay"); if (!domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = tmp.length; for (int i = 0; i < tmpLength; i++) { String tmpDomeId = tmp[i].toUpperCase(); log.info("Apply DOME {} for {}", tmpDomeId, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>")))); log.debug("Looking for dome_name: {}", tmpDomeId); if (ovlDomes.containsKey(tmpDomeId)) { domeEngine = new Engine(ovlDomes.get(tmpDomeId)); entry.put("dome_applied", "Y"); entry.put("field_dome_applied", "Y"); domeEngine.apply(flatSoilAndWthData(entry, noExpMode)); ArrayList<String> strategyList = domeEngine.getGenerators(); if (!strategyList.isEmpty()) { log.warn("The following DOME commands in the field overlay file are ignored : {}", strategyList.toString()); } if (!noExpMode && !mode.equals("strategy")) { // Check if there is no weather or soil data matched with experiment if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) { log.warn("No baseline weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) { log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } } } else { log.error("Cannot find overlay: {}", tmpDomeId); setFailedDomeId(entry, "field_dome_failed", tmpDomeId); } } } } if (noExpMode) { output.put("domeoutput", source); } else { output.put("domeoutput", MapUtil.bundle(flattenedData)); } if (linkDomes != null && !linkDomes.isEmpty()) { output.put("linkDomes", linkDomes); } else { linkDomes = new HashMap<String, Object>(); linkDomes.put("link_overlay", orgOvlLinks); linkDomes.put("link_stragty", orgStgLinks); output.put("linkDomes", linkDomes); } if (ovlDomes != null && !ovlDomes.isEmpty()) { output.put("ovlDomes", ovlDomes); } if (stgDomes != null && !stgDomes.isEmpty()) { output.put("stgDomes", stgDomes); } return output; } // private void flatSoilAndWthData(ArrayList<HashMap<String, Object>> flattenedData, String key) { // ArrayList<HashMap<String, Object>> arr = MapUtil.getRawPackageContents(source, key + "s"); // for (HashMap<String, Object> data : arr) { // HashMap<String, Object> tmp = new HashMap<String, Object>(); // tmp.put(key, data); // flattenedData.add(tmp); private HashMap<String, Object> flatSoilAndWthData(HashMap<String, Object> data, boolean noExpFlg) { if (!noExpFlg) { return data; } HashMap<String, Object> ret; if (data.containsKey("dailyWeather")) { ret = new HashMap<String, Object>(); ret.put("weather", data); } else if (data.containsKey("soilLayer")) { ret = new HashMap<String, Object>(); ret.put("soil", data); } else { ret = data; } return ret; } private void setFailedDomeId(HashMap data, String failKey, String failId) { String failIds; if ((failIds = (String) data.get(failKey)) != null) { data.put(failKey, failId); } else { data.put(failKey, failIds + "|" + failId); } } private boolean updateExpReferences(boolean isStgDome) { ArrayList<HashMap<String, Object>> expArr = MapUtil.getRawPackageContents(source, "experiments"); boolean isClimIDchanged = false; HashMap<String, HashMap<String, Object>> domes; String linkid; String domeKey; int maxDomeNum; if (isStgDome) { domes = stgDomes; linkid = "strategy"; domeKey = "seasonal_strategy"; maxDomeNum = 1; } else { domes = ovlDomes; linkid = "field"; domeKey = "field_overlay"; maxDomeNum = Integer.MAX_VALUE; } // Pre-scan the seasnal DOME to update reference variables String autoDomeName = ""; if (autoApply) { for (String domeName : domes.keySet()) { autoDomeName = domeName; } } for (HashMap<String, Object> exp : expArr) { String domeName = getLinkIds(linkid, exp); if (domeName.equals("")) { if (autoApply) { domeName = autoDomeName; } else { domeName = MapUtil.getValueOr(exp, domeKey, ""); } } if (!domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = Math.min(tmp.length, maxDomeNum); for (int i = 0; i < tmpLength; i++) { String tmpDomeId = tmp[i].toUpperCase(); log.debug("Looking for dome_name: {}", tmpDomeId); if (domes.containsKey(tmpDomeId)) { log.debug("Found DOME {}", tmpDomeId); Engine domeEngine = new Engine(domes.get(tmpDomeId)); isClimIDchanged = domeEngine.updateWSRef(exp, isStgDome, mode.equals("strategy")); // Check if the wst_id is switch to 8-bit long version String wst_id = MapUtil.getValueOr(exp, "wst_id", ""); if (isStgDome && wst_id.length() < 8) { exp.put("wst_id", wst_id + "0XXX"); exp.put("clim_id", "0XXX"); isClimIDchanged = true; } log.debug("New exp linkage: {}", exp); } } } } return isClimIDchanged; } private void updateWthReferences(boolean isClimIDchanged) { ArrayList<HashMap<String, Object>> wthArr = MapUtil.getRawPackageContents(source, "weathers"); boolean isStrategy = mode.equals("strategy"); HashMap<String, HashMap> unfixedWths = new HashMap(); HashSet<String> fixedWths = new HashSet(); for (HashMap<String, Object> wth : wthArr) { String wst_id = MapUtil.getValueOr(wth, "wst_id", ""); String clim_id = MapUtil.getValueOr(wth, "clim_id", ""); if (clim_id.equals("")) { if (wst_id.length() == 8) { clim_id = wst_id.substring(4, 8); } else { clim_id = "0XXX"; } } // If user assign CLIM_ID in the DOME, or find non-baseline data in the overlay mode, then switch WST_ID to 8-bit version if (isStrategy || isClimIDchanged || !clim_id.startsWith("0")) { if (wst_id.length() < 8) { wth.put("wst_id", wst_id + clim_id); } } else { // Temporally switch all the WST_ID to 8-bit in the data set if (wst_id.length() < 8) { wth.put("wst_id", wst_id + clim_id); } else { wst_id = wst_id.substring(0, 4); } // Check if there is multiple baseline record for one site if (unfixedWths.containsKey(wst_id)) { log.warn("There is multiple baseline weather data for site [{}], please choose a particular baseline via field overlay DOME", wst_id); unfixedWths.remove(wst_id); fixedWths.add(wst_id); } else { if (!fixedWths.contains(wst_id)) { unfixedWths.put(wst_id, wth); } } } } // If no CLIM_ID provided in the overlay mode, then switch the baseline WST_ID to 4-bit. if (!isStrategy && !unfixedWths.isEmpty()) { for (String wst_id : unfixedWths.keySet()) { unfixedWths.get(wst_id).put("wst_id", wst_id); } } } }
package com.gabmus.co2photoeditor; import android.util.Log; import android.view.View; import java.util.logging.Filter; public class FXHandler { public FXData[] FXList = { new FXData("B&W", R.drawable.demo_icon, 0, new int[0], new String[0]), new FXData("Sepia", R.drawable.demo_icon, 0, new int[0], new String[0]), new FXData("Negative", R.drawable.demo_icon, 0, new int[0], new String[0]), new FXData("Color Correction", R.drawable.demo_icon, 3, new int [] {0,0,0}, new String[] {"Brightness", "Contrast", "Saturation"}), new FXData("Tone Mapping 1", R.drawable.demo_icon, 2, new int [] {0,0}, new String[] {"Exposure", "Vignetting"}), new FXData("CRT", R.drawable.demo_icon, 1, new int [] {0}, new String[] {"Line Width"}), new FXData("VHS Noise", R.drawable.demo_icon, 5, new int [] {0,0,0,0,0}, new String [] {"Amount", "Size", "Luminance", "Color", "Randomizer Seed"}), new FXData("Film Grain", R.drawable.demo_icon, 4, new int [] {0,0,0,0}, new String [] {"Strength", "Dark Noise Power", "Random Noise Strength", "Randomizer Seed"}) }; public FXHandler() { } public void SelectFX(int fxID) { //Sliders not shown by default, so make them invisible MainActivity.makeAllSlidersDisappear(); //Enable the toggle, since no fx is selected by default, thus it's disabled MainActivity.fxToggle.setEnabled(true); //FX is active? if yes, let the toggle show it if (FXList[fxID].fxActive) MainActivity.fxToggle.setChecked(true); else MainActivity.fxToggle.setChecked(false); //DONE: Enable sliders needed for each kind of effect, give them the correct label if (FXList[fxID].parCount > 0) { MainActivity.sst1.setVisibility(View.VISIBLE); MainActivity.sk1.setProgress(FXList[fxID].parValues[0]); MainActivity.slb1.setText(FXList[fxID].parNames[0]); if (FXList[fxID].parCount > 1) { MainActivity.sst2.setVisibility(View.VISIBLE); MainActivity.sk2.setProgress(FXList[fxID].parValues[1]); MainActivity.slb2.setText(FXList[fxID].parNames[1]); if (FXList[fxID].parCount > 2) { MainActivity.sst3.setVisibility(View.VISIBLE); MainActivity.sk3.setProgress(FXList[fxID].parValues[2]); MainActivity.slb3.setText(FXList[fxID].parNames[2]); if (FXList[fxID].parCount > 3) { MainActivity.sst4.setVisibility(View.VISIBLE); MainActivity.sk4.setProgress(FXList[fxID].parValues[3]); MainActivity.slb4.setText(FXList[fxID].parNames[3]); if (FXList[fxID].parCount > 4) { MainActivity.sst5.setVisibility(View.VISIBLE); MainActivity.sk5.setProgress(FXList[fxID].parValues[4]); MainActivity.slb5.setText(FXList[fxID].parNames[4]); } } } } } } public String[] getFXnames() { String[] toRet = new String[FXList.length]; for (int i=0; i< toRet.length; i++) { toRet[i]=FXList[i].name; } return toRet; } public int[] getFXicons() { int[] toRet = new int[FXList.length]; for (int i=0; i< toRet.length; i++) { toRet[i]=FXList[i].icon; } return toRet; } public void enableFX(int index, FilterSurfaceView mFsv, boolean active) { switch (index) { case 0: mFsv.renderer.PARAMS_EnableBlackAndWhite = active; break; case 1: // Sepia mFsv.renderer.PARAMS_EnableSepia = active; break; case 2: // Negative mFsv.renderer.PARAMS_EnableNegative = active; break; case 3: //color correction //mFsv.renderer.PARAMS_EnableColorCorrection = active; break; case 4: // Tone mapping 1 mFsv.renderer.PARAMS_EnableToneMapping = active; break; case 5: //CRT mFsv.renderer.PARAMS_EnableCathodeRayTube = active; break; case 6: //VHS Noise, ex Film Grain mFsv.renderer.PARAMS_EnableFilmGrain = active; break; case 7: //Proper Film Grain mFsv.renderer.PARAMS_EnableProperFilmGrain = active; break; default: Log.e("CO2 Photo Editor", "enableFX: index out of range"); break; } } public void tuneFX(int FXIndex, int valIndex, int tuningValue, FilterSurfaceView mFsv) { float finalValue=0.0f; switch (FXIndex) { case 3: //color correction switch (valIndex) { case 1: //edit brightness break; case 2: //edit contrast break; case 3: //edit saturation break; default: Log.e("CO2 Photo Editor", "tuneFX: colorCorrection: index out of range (>3)"); break; } break; case 4: //tone mapping switch (valIndex) { case 1: //edit exposure finalValue = (tuningValue/100f)*2f; mFsv.renderer.PARAMS_ToneMappingExposure = finalValue; break; case 2: //edit vignetting finalValue = (tuningValue/100f)*3f; mFsv.renderer.PARAMS_ToneMappingVignetting = finalValue; break; } break; case 5: //crt switch (valIndex) { case 1: //edit line width finalValue = (tuningValue/100f)*4; int tmpValue=(int)finalValue; mFsv.renderer.PARAMS_CathodeRayTubeLineWidth = tmpValue; break; } break; //"Grain Amount", "Grain Size", "Luminance Amount", "Color Amount" case 6: //VHS Noise, ex Film Grain switch (valIndex) { case 1: //Grain amount finalValue = (tuningValue/100f)*1f; mFsv.renderer.PARAMS_FilmGrainAmount = finalValue; break; case 2: //grain size finalValue = ((tuningValue/100f)*3f)+1; mFsv.renderer.PARAMS_FilmGrainParticleSize = finalValue; break; case 3: //luminance amount finalValue = ((tuningValue/100f)*3f); mFsv.renderer.PARAMS_FilmGrainLuminance = finalValue; break; case 4: //color amount finalValue = (tuningValue/100f)*10f; mFsv.renderer.PARAMS_FilmGrainColorAmount = finalValue; break; case 5: //randomizer seed //this has a certain amount of randomicity mFsv.renderer.setPARAMS_FilmGrainSeed(tuningValue); break; } break; case 7: switch (valIndex) { case 1: //Strength finalValue = (tuningValue / 100f) * 1f; mFsv.renderer.PARAMS_ProperFilmGrainStrength = finalValue; break; case 2: //Dark Noise Power finalValue = ((tuningValue / 100f) * 3f) + 1; mFsv.renderer.PARAMS_ProperFilmGrainAccentuateDarkNoisePower = finalValue; break; case 3: //Random noise strength finalValue = ((tuningValue / 100f) * 3f); mFsv.renderer.PARAMS_ProperFilmGrainRandomNoiseStrength = finalValue; break; case 4: //randomizer seed mFsv.renderer.PARAMS_ProperFilmGrainRandomValue=tuningValue; break; } break; //other cases default: Log.e("CO2 Photo Editor", "tuneFX: index out of range"); break; } } }
package org.altbeacon.beacon; import android.annotation.TargetApi; import android.bluetooth.BluetoothDevice; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BeaconParser { private static final String TAG = "BeaconParser"; private static final Pattern I_PATTERN = Pattern.compile("i\\:(\\d+)\\-(\\d+)(l?)"); private static final Pattern M_PATTERN = Pattern.compile("m\\:(\\d+)-(\\d+)\\=([0-9A-F-a-f]+)"); private static final Pattern D_PATTERN = Pattern.compile("d\\:(\\d+)\\-(\\d+)([bl]?)"); private static final Pattern P_PATTERN = Pattern.compile("p\\:(\\d+)\\-(\\d+)"); private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; private Long mMatchingBeaconTypeCode; protected List<Integer> mIdentifierStartOffsets; protected List<Integer> mIdentifierEndOffsets; protected List<Boolean> mIdentifierLittleEndianFlags; protected List<Integer> mDataStartOffsets; protected List<Integer> mDataEndOffsets; protected List<Boolean> mDataLittleEndianFlags; protected Integer mMatchingBeaconTypeCodeStartOffset; protected Integer mMatchingBeaconTypeCodeEndOffset; protected Integer mPowerStartOffset; protected Integer mPowerEndOffset; /** * Makes a new BeaconParser. Should normally be immediately followed by a call to #setLayout */ public BeaconParser() { mIdentifierStartOffsets = new ArrayList<Integer>(); mIdentifierEndOffsets = new ArrayList<Integer>(); mDataStartOffsets = new ArrayList<Integer>(); mDataEndOffsets = new ArrayList<Integer>(); mDataLittleEndianFlags = new ArrayList<Boolean>(); mIdentifierLittleEndianFlags = new ArrayList<Boolean>(); } /** * <p>Defines a beacon field parsing algorithm based on a string designating the zero-indexed * offsets to bytes within a BLE advertisement.</p> * * <p>If you want to see examples of how other folks have set up BeaconParsers for different * kinds of beacons, try doing a Google search for "getBeaconParsers" (include the quotes in * the search.)</p> * * <p>Four prefixes are allowed in the string:</p> * * <pre> * m - matching byte sequence for this beacon type to parse (exactly one required) * i - identifier (at least one required, multiple allowed) * p - power calibration field (exactly one required) * d - data field (optional, multiple allowed) * </pre> * * <p>Each prefix is followed by a colon, then an inclusive decimal byte offset for the field from * the beginning of the advertisement. In the case of the m prefix, an = sign follows the byte * offset, followed by a big endian hex representation of the bytes that must be matched for * this beacon type. When multiple i or d entries exist in the string, they will be added in * order of definition to the identifier or data array for the beacon when parsing the beacon * advertisement. Terms are separated by commas.</p> * * <p>All offsets from the start of the advertisement are relative to the first byte of the * two byte manufacturer code. The manufacturer code is therefore always at position 0-1</p> * * <p>All data field and identifier expressions may be optionally suffixed with the letter l, which * indicates the field should be parsed as little endian. If not present, the field will be presumed * to be big endian. * * <p>If the expression cannot be parsed, a <code>BeaconLayoutException</code> is thrown.</p> * * <p>Example of a parser string for AltBeacon:</p> * * </pre> * "m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25" * </pre> * * <p>This signifies that the beacon type will be decoded when an advertisement is found with * 0xbeac in bytes 2-3, and a three-part identifier will be pulled out of bytes 4-19, bytes * 20-21 and bytes 22-23, respectively. A signed power calibration value will be pulled out of * byte 24, and a data field will be pulled out of byte 25.</p> * * Note: bytes 0-1 of the BLE manufacturer advertisements are the two byte manufacturer code. * Generally you should not match on these two bytes when using a BeaconParser, because it will * limit your parser to matching only a transmitter made by a specific manufacturer. Software * and operating systems that scan for beacons typically ignore these two bytes, allowing beacon * manufacturers to use their own company code assigned by Bluetooth SIG. The default parser * implementation will already pull out this company code and store it in the * beacon.mManufacturer field. Matcher expressions should therefore start with "m2-3:" followed * by the multi-byte hex value that signifies the beacon type. * * @param beaconLayout * @return the BeaconParser instance */ public BeaconParser setBeaconLayout(String beaconLayout) { String[] terms = beaconLayout.split(","); for (String term : terms) { boolean found = false; Matcher matcher = I_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); Boolean littleEndian = matcher.group(3).equals("l"); mIdentifierLittleEndianFlags.add(littleEndian); mIdentifierStartOffsets.add(startOffset); mIdentifierEndOffsets.add(endOffset); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } } matcher = D_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); Boolean littleEndian = matcher.group(3).equals("l"); mDataLittleEndianFlags.add(littleEndian); mDataStartOffsets.add(startOffset); mDataEndOffsets.add(endOffset); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } } matcher = P_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); mPowerStartOffset=startOffset; mPowerEndOffset=endOffset; } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer power byte offset in term: " + term); } } matcher = M_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); mMatchingBeaconTypeCodeStartOffset = startOffset; mMatchingBeaconTypeCodeEndOffset = endOffset; } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } String hexString = matcher.group(3); try { mMatchingBeaconTypeCode = Long.decode("0x"+hexString); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse beacon type code: "+hexString+" in term: " + term); } } if (!found) { BeaconManager.logDebug(TAG, "cannot parse term "+term); throw new BeaconLayoutException("Cannot parse beacon layout term: " + term); } } if (mPowerStartOffset == null || mPowerEndOffset == null) { throw new BeaconLayoutException("You must supply a power byte offset with a prefix of 'p'"); } if (mMatchingBeaconTypeCodeStartOffset == null || mMatchingBeaconTypeCodeEndOffset == null) { throw new BeaconLayoutException("You must supply a matching beacon type expression with a prefix of 'm'"); } if (mIdentifierStartOffsets.size() == 0 || mIdentifierEndOffsets.size() == 0) { throw new BeaconLayoutException("You must supply at least one identifier offset withh a prefix of 'i'"); } return this; } /** * @see #mMatchingBeaconTypeCode * @return */ public Long getMatchingBeaconTypeCode() { return mMatchingBeaconTypeCode; } /** * Construct a Beacon from a Bluetooth LE packet collected by Android's Bluetooth APIs, * including the raw bluetooth device info * * @param scanData The actual packet bytes * @param rssi The measured signal strength of the packet * @param device The bluetooth device that was detected * @return An instance of a <code>Beacon</code> */ @TargetApi(5) public Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device) { return fromScanData(scanData, rssi, device, new Beacon()); } @TargetApi(5) protected Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device, Beacon beacon) { int startByte = 2; boolean patternFound = false; byte[] typeCodeBytes = longToByteArray(getMatchingBeaconTypeCode(), mMatchingBeaconTypeCodeEndOffset-mMatchingBeaconTypeCodeStartOffset+1); while (startByte <= 5) { if (byteArraysMatch(scanData, startByte+mMatchingBeaconTypeCodeStartOffset, typeCodeBytes, 0)) { patternFound = true; break; } startByte++; } if (patternFound == false) { // This is not an beacon BeaconManager.logDebug(TAG, "This is not a matching Beacon advertisement. (Was expecting "+byteArrayToString(typeCodeBytes)+". The bytes I see are: "+bytesToHex(scanData)); return null; } else { BeaconManager.logDebug(TAG, "This is a recognized beacon advertisement -- "+String.format("%04x", getMatchingBeaconTypeCode())+" seen"); } ArrayList<Identifier> identifiers = new ArrayList<Identifier>(); for (int i = 0; i < mIdentifierEndOffsets.size(); i++) { String idString = byteArrayToFormattedString(scanData, mIdentifierStartOffsets.get(i)+startByte, mIdentifierEndOffsets.get(i)+startByte, mIdentifierLittleEndianFlags.get(i)); identifiers.add(Identifier.parse(idString)); } ArrayList<Long> dataFields = new ArrayList<Long>(); for (int i = 0; i < mDataEndOffsets.size(); i++) { String dataString = byteArrayToFormattedString(scanData, mDataStartOffsets.get(i)+startByte, mDataEndOffsets.get(i)+startByte, mDataLittleEndianFlags.get(i)); dataFields.add(Long.parseLong(dataString)); BeaconManager.logDebug(TAG, "parsing found data field "+i); // TODO: error handling needed here on the parse } int txPower = 0; String powerString = byteArrayToFormattedString(scanData, mPowerStartOffset+startByte, mPowerEndOffset+startByte, false); txPower = Integer.parseInt(powerString); // make sure it is a signed integer if (txPower > 127) { txPower -= 256; } // TODO: error handling needed on the parse int beaconTypeCode = 0; String beaconTypeString = byteArrayToFormattedString(scanData, mMatchingBeaconTypeCodeStartOffset+startByte, mMatchingBeaconTypeCodeEndOffset+startByte, false); beaconTypeCode = Integer.parseInt(beaconTypeString); // TODO: error handling needed on the parse int manufacturer = 0; String manufacturerString = byteArrayToFormattedString(scanData, startByte, startByte+1, true); manufacturer = Integer.parseInt(manufacturerString); String macAddress = null; String name = null; if (device != null) { macAddress = device.getAddress(); name = device.getName(); } beacon.mIdentifiers = identifiers; beacon.mDataFields = dataFields; beacon.mTxPower = txPower; beacon.mRssi = rssi; beacon.mBeaconTypeCode = beaconTypeCode; beacon.mBluetoothAddress = macAddress; beacon.mBluetoothName= name; beacon.mManufacturer = manufacturer; return beacon; } /** * Get BLE advertisement bytes for a Beacon * @param beacon the beacon containing the data to be transmitted * @return the byte array of the advertisement */ public byte[] getBeaconAdvertisementData(Beacon beacon) { byte[] advertisingBytes; advertisingBytes = new byte[26]; long beaconTypeCode = this.getMatchingBeaconTypeCode(); advertisingBytes[0] = (byte) (beacon.getManufacturer() & 0xff); // little endian, position fixed advertisingBytes[1] = (byte) ((beacon.getManufacturer() >> 8) & 0xff); // set type code for (int index = this.mMatchingBeaconTypeCodeStartOffset; index <= this.mMatchingBeaconTypeCodeEndOffset; index++) { byte value = (byte) (this.getMatchingBeaconTypeCode() >> (8*(this.mMatchingBeaconTypeCodeEndOffset-index)) & 0xff); advertisingBytes[index] = value; } // set identifiers for (int identifierNum = 0; identifierNum < this.mIdentifierStartOffsets.size(); identifierNum++) { byte[] identifierBytes = beacon.getIdentifier(identifierNum).toByteArrayOfSpecifiedEndianness(this.mIdentifierLittleEndianFlags.get(identifierNum)); for (int index = this.mIdentifierStartOffsets.get(identifierNum); index <= this.mIdentifierEndOffsets.get(identifierNum); index ++) { advertisingBytes[index] = (byte) identifierBytes[this.mIdentifierEndOffsets.get(identifierNum)-index]; } } // set power for (int index = this.mPowerStartOffset; index <= this.mPowerEndOffset; index ++) { advertisingBytes[index] = (byte) (beacon.getTxPower() >> (8*(index - this.mPowerStartOffset)) & 0xff); } // set data fields for (int dataFieldNum = 0; dataFieldNum < this.mDataStartOffsets.size(); dataFieldNum++) { long dataField = beacon.getDataFields().get(dataFieldNum); for (int index = this.mDataStartOffsets.get(dataFieldNum); index <= this.mDataEndOffsets.get(dataFieldNum); index ++) { int endianCorrectedIndex = index; if (this.mDataLittleEndianFlags.get(dataFieldNum)) { endianCorrectedIndex = this.mDataEndOffsets.get(dataFieldNum) - index; } advertisingBytes[endianCorrectedIndex] = (byte) (dataField >> (8*(index - this.mDataStartOffsets.get(dataFieldNum))) & 0xff); } } return advertisingBytes; } public BeaconParser setMatchingBeaconTypeCode(Long typeCode) { mMatchingBeaconTypeCode = typeCode; return this; } protected static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; int v; for ( int j = 0; j < bytes.length; j++ ) { v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } public static class BeaconLayoutException extends RuntimeException { public BeaconLayoutException(String s) { } } protected byte[] longToByteArray(long longValue, int length) { byte[] array = new byte[length]; for (int i = 0; i < length; i++){ //long mask = (long) Math.pow(256.0,1.0*(length-i))-1; long mask = 0xffl << (length-i-1)*8; long shift = (length-i-1)*8; long value = ((longValue & mask) >> shift); //BeaconManager.logDebug(TAG, "masked value is "+String.format("%08x",longValue & mask)); //BeaconManager.logDebug(TAG, "masked value shifted is "+String.format("%08x",(longValue & mask) >> shift)); //BeaconManager.logDebug(TAG, "for long "+String.format("%08x",longValue)+" at position: "+i+" of "+length+" mask: "+String.format("%08x",mask)+" shift: "+shift+" the value is "+String.format("%02x",value)); array[i] = (byte) value; } return array; } private boolean byteArraysMatch(byte[] array1, int offset1, byte[] array2, int offset2) { int minSize = array1.length > array2.length ? array2.length : array1.length; for (int i = 0; i < minSize; i++) { if (array1[i+offset1] != array2[i+offset2]) { return false; } } return true; } private String byteArrayToString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02x", bytes[i])); sb.append(" "); } return sb.toString().trim(); } private String byteArrayToFormattedString(byte[] byteBuffer, int startIndex, int endIndex, Boolean littleEndian) { byte[] bytes = new byte[endIndex-startIndex+1]; if (littleEndian) { for (int i = 0; i <= endIndex-startIndex; i++) { bytes[i] = byteBuffer[startIndex+bytes.length-1-i]; } } else { for (int i = 0; i <= endIndex-startIndex; i++) { bytes[i] = byteBuffer[startIndex+i]; } } int length = endIndex-startIndex +1; // We treat a 1-4 byte number as decimal string if (length < 5) { Long number = 0l; BeaconManager.logDebug(TAG, "Byte array is size "+bytes.length); for (int i = 0; i < bytes.length; i++) { BeaconManager.logDebug(TAG, "index is "+i); long byteValue = (long) (bytes[bytes.length - i-1] & 0xff); long positionValue = (long) Math.pow(256.0,i*1.0); long calculatedValue = (long) (byteValue * positionValue); BeaconManager.logDebug(TAG, "calculatedValue for position "+i+" with positionValue "+positionValue+" and byteValue "+byteValue+" is "+calculatedValue); number += calculatedValue; } return number.toString(); } // We treat a 7+ byte number as a hex string String hexString = bytesToHex(bytes); // And if it is a 12 byte number we add dashes to it to make it look like a standard UUID if (bytes.length == 16) { StringBuilder sb = new StringBuilder(); sb.append(hexString.substring(0,8)); sb.append("-"); sb.append(hexString.substring(8,12)); sb.append("-"); sb.append(hexString.substring(12,16)); sb.append("-"); sb.append(hexString.substring(16,20)); sb.append("-"); sb.append(hexString.substring(20,32)); return sb.toString(); } return "0x"+hexString; } }
package com.guerinet.materialtabs; import android.content.Context; import android.graphics.Typeface; import android.os.Build; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * To be used with ViewPager to provide a tab indicator component which give constant feedback as to * the user's scroll progress. * <p> * To use the component, simply add it to your view hierarchy. Then in your * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for. * <p> * The colors can be customized in two ways. The first and simplest is to provide an array of colors * via {@link #setSelectedIndicatorColors(int...)}. The * alternative is via the {@link TabColorizer} interface which provides you complete control over * which color is used for any individual position. * <p> * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)}, * providing the layout ID of your custom layout. */ public class TabLayout extends HorizontalScrollView { /** * Allows complete control over the colors drawn in the tab layout. Set with * {@link #setCustomTabColorizer(TabColorizer)}. */ public interface TabColorizer { /** * @return return the color of the indicator used when {@code position} is selected. */ int getIndicatorColor(int position); } private static final int TITLE_OFFSET_DIPS = 24; private static final int TAB_VIEW_PADDING_DIPS = 16; private static final int TAB_VIEW_TEXT_SIZE_SP = 12; /** * Keeps track of the current tab open to avoid calling methods when a user clicks on an * already open tab */ private int mCurrentPosition = -1; /* ICON VIEWS */ /** * True if the custom tab has an icon, false otherwise */ private boolean mHasIcon = false; /** * True if the custom tab should use the default selector, false otherwise */ private boolean mDefaultSelector; /** * The Id of the ImageView for the icon */ private int mTabViewIconId; /** * The array of Ids to use for the icon drawables */ private int[] mIconIds; private int mTitleOffset; private int mTabViewLayoutId; private int mTabViewTextViewId; private boolean mDistributeEvenly; private ViewPager mViewPager; private SparseArray<String> mContentDescriptions = new SparseArray<>(); private ViewPager.OnPageChangeListener mViewPagerPageChangeListener; private final TabStrip mTabStrip; public TabLayout(Context context) { this(context, null); } public TabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TabLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Disable the Scroll Bar setHorizontalScrollBarEnabled(false); // Make sure that the Tab Strips fills this View setFillViewport(true); mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density); mTabStrip = new TabStrip(context); addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } /** * Set the custom {@link TabColorizer} to be used. * * If you only require simple custmisation then you can use * {@link #setSelectedIndicatorColors(int...)} to achieve * similar effects. */ public void setCustomTabColorizer(TabColorizer tabColorizer) { mTabStrip.setCustomTabColorizer(tabColorizer); } public void setDistributeEvenly(boolean distributeEvenly) { mDistributeEvenly = distributeEvenly; } /** * Sets the colors to be used for indicating the selected tab. These colors are treated as a * circular array. Providing one color will mean that all tabs are indicated with the same color. */ public void setSelectedIndicatorColors(int... colors) { mTabStrip.setSelectedIndicatorColors(colors); } /** * Set the {@link ViewPager.OnPageChangeListener}. When using {@link TabLayout} you are * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so * that the layout can update it's scroll position correctly. * * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener) */ public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mViewPagerPageChangeListener = listener; } /** * Set the custom layout to be inflated for the tab views. * * @param layoutResId Layout id to be inflated * @param textViewId id of the {@link TextView} in the inflated view */ public void setCustomTabView(int layoutResId, int textViewId) { mTabViewLayoutId = layoutResId; mTabViewTextViewId = textViewId; } /** * Sets the custom layout view that has an icon * * @param layoutResId To Layout Id to be inflated * @param textViewId Id of the {@link TextView} in the inflated view * @param imageViewId Id of the {@link android.widget.ImageView} in the inflated view * @param iconIds The list of icon Ids to use for the icon * @param defaultSelector True if we should use the default selector as the background, false * otherwise. Note: This will override any set background */ public void setCustomTabView(int layoutResId, int textViewId, int imageViewId, int[] iconIds, boolean defaultSelector){ setCustomTabView(layoutResId, textViewId); mDefaultSelector = defaultSelector; mHasIcon = true; mTabViewIconId = imageViewId; mIconIds = iconIds; } /** * Sets the associated view pager. Note that the assumption here is that the pager content * (number of tabs and tab titles) does not change after this call has been made. */ public void setViewPager(ViewPager viewPager) { mTabStrip.removeAllViews(); mViewPager = viewPager; if (viewPager != null) { viewPager.setOnPageChangeListener(new InternalViewPagerListener()); populateTabStrip(); } } /** * Create a default view to be used for tabs. This is called if a custom tab view is not set via * {@link #setCustomTabView(int, int)}. */ protected TextView createDefaultTabView(Context context) { TextView textView = new TextView(context); textView.setGravity(Gravity.CENTER); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); textView.setBackgroundResource(outValue.resourceId); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ textView.setAllCaps(true); } int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density); textView.setPadding(padding, padding, padding, padding); return textView; } private void populateTabStrip() { final PagerAdapter adapter = mViewPager.getAdapter(); final View.OnClickListener tabClickListener = new TabViewPagerClickListener(); for (int i = 0; i < adapter.getCount(); i++) { View tabView = null; TextView tabTitleView = null; if (mTabViewLayoutId != 0) { // If there is a custom tab view layout id set, try and inflate it tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); //Set up the icon if needed if(mHasIcon){ ImageView iconView = (ImageView)tabView.findViewById(mTabViewIconId); iconView.setImageResource(mIconIds[i]); } //Set the default selector if needed if(mDefaultSelector){ TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(R.attr.selectableItemBackground, outValue, true); tabView.setBackgroundResource(outValue.resourceId); } } if (tabView == null) { tabView = createDefaultTabView(getContext()); } if (tabTitleView == null && TextView.class.isInstance(tabView)) { tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(adapter.getPageTitle(i)); tabView.setOnClickListener(tabClickListener); String desc = mContentDescriptions.get(i, null); if (desc != null) { tabView.setContentDescription(desc); } mTabStrip.addView(tabView); if (i == mViewPager.getCurrentItem()) { tabView.setSelected(true); mCurrentPosition = i; } } } public void setContentDescription(int i, String desc) { mContentDescriptions.put(i, desc); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mViewPager != null) { scrollToTab(mViewPager.getCurrentItem(), 0); } } private void scrollToTab(int tabIndex, int positionOffset) { final int tabStripChildCount = mTabStrip.getChildCount(); if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) { return; } View selectedChild = mTabStrip.getChildAt(tabIndex); if (selectedChild != null) { int targetScrollX = selectedChild.getLeft() + positionOffset; if (tabIndex > 0 || positionOffset > 0) { // If we're not at the first child and are mid-scroll, make sure we obey the offset targetScrollX -= mTitleOffset; } scrollTo(targetScrollX, 0); } } private class InternalViewPagerListener implements ViewPager.OnPageChangeListener { private int mScrollState; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int tabStripChildCount = mTabStrip.getChildCount(); if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) { return; } mTabStrip.onViewPagerPageChanged(position, positionOffset); View selectedTitle = mTabStrip.getChildAt(position); int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0; scrollToTab(position, extraOffset); if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mTabStrip.onViewPagerPageChanged(position, 0f); scrollToTab(position, 0); } for (int i = 0; i < mTabStrip.getChildCount(); i++) { mTabStrip.getChildAt(i).setSelected(position == i); } if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageSelected(position); } } } private class TabViewPagerClickListener implements View.OnClickListener { @Override public void onClick(View v) { for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)){ //If this tab is already open, do nothing if(i == mCurrentPosition){ return; } //Set the new position mCurrentPosition = i; mViewPager.setCurrentItem(i); return; } } } } /** * Clears the tabs */ public void clear(){ mTabStrip.removeAllViews(); } /** * @param position The position of the desired tab * @return The tab view */ public View getTabView(int position){ //Make sure that the position is within bounds if(position < 0 || position >= mTabStrip.getChildCount()){ return null; } return mTabStrip.getChildAt(position); } /** * Sets the color of the indicator when a tab is selected * * @param color The indicator color */ public void setIndicatorColor(int color){ mTabStrip.setSelectedIndicatorColors(color); } /* NON-VIEWPAGER TABS */ /** * Adds the tabs based on a list of Strings to use as tab titles * * @param callback The {@link Callback} to call when a tab is clicked * @param initialTab The initial tab to show * @param titles The titles for the tabs */ public void addTabs(Callback callback, int initialTab, List<String> titles){ //Create a new listener based on the given callback TabClickListener listener = new TabClickListener(callback); View firsTab = null; //Go through the titles for(int i = 0; i < titles.size(); i ++){ String title = titles.get(i); View tabView; TextView tabTitleView = null; //If there is a custom tab view layout id set, try and inflate it if(mTabViewLayoutId != 0){ tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); //Set up the icon if needed if(mHasIcon){ ImageView iconView = (ImageView)tabView.findViewById(mTabViewIconId); iconView.setImageResource(mIconIds[i]); } //Set the default selector if needed if(mDefaultSelector){ TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(R.attr.selectableItemBackground, outValue, true); tabView.setBackgroundResource(outValue.resourceId); } } else { tabView = createDefaultTabView(getContext()); } if(tabTitleView == null && TextView.class.isInstance(tabView)){ tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(title); tabView.setOnClickListener(listener); mTabStrip.addView(tabView); if(i == initialTab){ firsTab = tabView; } } if(firsTab != null){ //Click on the first tab if there is one firsTab.performClick(); //Set the current position mCurrentPosition = initialTab; } } /** * Adds the tabs based on the given titles * * @param callback The {@link Callback} to use when a tab is selected * @param initialTab The initial tab selected * @param titles The variable list of titles */ public void addTabs(Callback callback, int initialTab, String... titles){ List<String> tabTitles = new ArrayList<>(); Collections.addAll(tabTitles, titles); addTabs(callback, initialTab, tabTitles); } /** * Adds the tabs based on a list of Strings to use as tab titles. * Assumes that the first tab is the selected one but will not call the callback * * @param callback The {@link Callback} to call when a tab is clicked * @param titles The titles for the tabs */ public void addTabs(Callback callback, List<String> titles){ addTabs(callback, -1, titles); } /** * Adds the tabs based on the given titles. * Assumes that the first tab is the selected one but will not call the callback * * @param callback The {@link Callback} to call when a tab is clicked * @param titles The variable list of titles */ public void addTabs(Callback callback, String... titles){ addTabs(callback, -1, titles); } /** * The OnClickListener used when we are using tabs without a ViewPager */ private class TabClickListener implements OnClickListener{ /** * The callback to call when a tab is selected */ private Callback mCallback; /** * The ViewPagerListener instance to update the UI */ private InternalViewPagerListener listener; /** * Default Constructor * * @param callback The callback */ public TabClickListener(Callback callback){ //Create a new InternalViewPagerListener to update the UI this.listener = new InternalViewPagerListener(); this.mCallback = callback; } @Override public void onClick(View v){ for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)){ //If this tab is already open, do nothing if(i == mCurrentPosition){ return; } //Set the new position mCurrentPosition = i; //Call the appropriate listeners/callbacks mCallback.onTabSelected(i); listener.onPageSelected(i); return; } } } } /** * Callback to implement when a tab is clicked on */ public static abstract class Callback { /** * Called when a tab is selected * * @param position The tab position */ public abstract void onTabSelected(int position); } }
package com.guerinet.materialtabs; import android.content.Context; import android.graphics.Typeface; import android.os.Build; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * To be used with ViewPager to provide a tab indicator component which give constant feedback as to * the user's scroll progress. * <p> * To use the component, simply add it to your view hierarchy. Then in your * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for. * <p> * The colors can be customized in two ways. The first and simplest is to provide an array of colors * via {@link #setSelectedIndicatorColors(int...)}. The * alternative is via the {@link TabColorizer} interface which provides you complete control over * which color is used for any individual position. * <p> * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)}, * providing the layout ID of your custom layout. */ public class TabLayout extends HorizontalScrollView { /** * Allows complete control over the colors drawn in the tab layout. Set with * {@link #setCustomTabColorizer(TabColorizer)}. */ public interface TabColorizer { /** * @return return the color of the indicator used when {@code position} is selected. */ int getIndicatorColor(int position); } private static final int TITLE_OFFSET_DIPS = 24; private static final int TAB_VIEW_PADDING_DIPS = 16; private static final int TAB_VIEW_TEXT_SIZE_SP = 12; /** * Keeps track of the current tab open to avoid calling methods when a user clicks on an * already open tab */ private int mCurrentPosition = -1; /* ICON VIEWS */ /** * True if the custom tab has an icon, false otherwise */ private boolean mHasIcon = false; /** * The Id of the ImageView for the icon */ private int mTabViewIconId; /** * The array of Ids to use for the icon drawables */ private int[] mIconIds; private int mTitleOffset; private int mTabViewLayoutId; private int mTabViewTextViewId; private boolean mDistributeEvenly; private ViewPager mViewPager; private SparseArray<String> mContentDescriptions = new SparseArray<>(); private ViewPager.OnPageChangeListener mViewPagerPageChangeListener; private final TabStrip mTabStrip; public TabLayout(Context context) { this(context, null); } public TabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TabLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Disable the Scroll Bar setHorizontalScrollBarEnabled(false); // Make sure that the Tab Strips fills this View setFillViewport(true); mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density); mTabStrip = new TabStrip(context); addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } /** * Set the custom {@link TabColorizer} to be used. * * If you only require simple custmisation then you can use * {@link #setSelectedIndicatorColors(int...)} to achieve * similar effects. */ public void setCustomTabColorizer(TabColorizer tabColorizer) { mTabStrip.setCustomTabColorizer(tabColorizer); } public void setDistributeEvenly(boolean distributeEvenly) { mDistributeEvenly = distributeEvenly; } /** * Sets the colors to be used for indicating the selected tab. These colors are treated as a * circular array. Providing one color will mean that all tabs are indicated with the same color. */ public void setSelectedIndicatorColors(int... colors) { mTabStrip.setSelectedIndicatorColors(colors); } /** * Set the {@link ViewPager.OnPageChangeListener}. When using {@link TabLayout} you are * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so * that the layout can update it's scroll position correctly. * * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener) */ public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mViewPagerPageChangeListener = listener; } /** * Set the custom layout to be inflated for the tab views. * * @param layoutResId Layout id to be inflated * @param textViewId id of the {@link TextView} in the inflated view */ public void setCustomTabView(int layoutResId, int textViewId) { mTabViewLayoutId = layoutResId; mTabViewTextViewId = textViewId; } /** * Sets the custom layout view that has an icon * * @param layoutResId To Layout Id to be inflated * @param textViewId Id of the {@link TextView} in the inflated view * @param imageViewId Id of the {@link android.widget.ImageView} in the inflated view * @param iconIds The list of icon Ids to use for the icon */ public void setCustomTabView(int layoutResId, int textViewId, int imageViewId, int[] iconIds){ setCustomTabView(layoutResId, textViewId); mHasIcon = true; mTabViewIconId = imageViewId; mIconIds = iconIds; } /** * Sets the associated view pager. Note that the assumption here is that the pager content * (number of tabs and tab titles) does not change after this call has been made. */ public void setViewPager(ViewPager viewPager) { mTabStrip.removeAllViews(); mViewPager = viewPager; if (viewPager != null) { viewPager.setOnPageChangeListener(new InternalViewPagerListener()); populateTabStrip(); } } /** * Create a default view to be used for tabs. This is called if a custom tab view is not set via * {@link #setCustomTabView(int, int)}. */ protected TextView createDefaultTabView(Context context) { TextView textView = new TextView(context); textView.setGravity(Gravity.CENTER); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); textView.setBackgroundResource(outValue.resourceId); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ textView.setAllCaps(true); } int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density); textView.setPadding(padding, padding, padding, padding); return textView; } private void populateTabStrip() { final PagerAdapter adapter = mViewPager.getAdapter(); final View.OnClickListener tabClickListener = new TabViewPagerClickListener(); for (int i = 0; i < adapter.getCount(); i++) { View tabView = null; TextView tabTitleView = null; if (mTabViewLayoutId != 0) { // If there is a custom tab view layout id set, try and inflate it tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); //Set up the icon if needed if(mHasIcon){ ImageView iconView = (ImageView)tabView.findViewById(mTabViewIconId); iconView.setImageResource(mIconIds[i]); } } if (tabView == null) { tabView = createDefaultTabView(getContext()); } if (tabTitleView == null && TextView.class.isInstance(tabView)) { tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(adapter.getPageTitle(i)); tabView.setOnClickListener(tabClickListener); String desc = mContentDescriptions.get(i, null); if (desc != null) { tabView.setContentDescription(desc); } mTabStrip.addView(tabView); if (i == mViewPager.getCurrentItem()) { tabView.setSelected(true); mCurrentPosition = i; } } } public void setContentDescription(int i, String desc) { mContentDescriptions.put(i, desc); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mViewPager != null) { scrollToTab(mViewPager.getCurrentItem(), 0); } } private void scrollToTab(int tabIndex, int positionOffset) { final int tabStripChildCount = mTabStrip.getChildCount(); if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) { return; } View selectedChild = mTabStrip.getChildAt(tabIndex); if (selectedChild != null) { int targetScrollX = selectedChild.getLeft() + positionOffset; if (tabIndex > 0 || positionOffset > 0) { // If we're not at the first child and are mid-scroll, make sure we obey the offset targetScrollX -= mTitleOffset; } scrollTo(targetScrollX, 0); } } private class InternalViewPagerListener implements ViewPager.OnPageChangeListener { private int mScrollState; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int tabStripChildCount = mTabStrip.getChildCount(); if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) { return; } mTabStrip.onViewPagerPageChanged(position, positionOffset); View selectedTitle = mTabStrip.getChildAt(position); int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0; scrollToTab(position, extraOffset); if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mTabStrip.onViewPagerPageChanged(position, 0f); scrollToTab(position, 0); } for (int i = 0; i < mTabStrip.getChildCount(); i++) { mTabStrip.getChildAt(i).setSelected(position == i); } if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageSelected(position); } } } private class TabViewPagerClickListener implements View.OnClickListener { @Override public void onClick(View v) { for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)){ //If this tab is already open, do nothing if(i == mCurrentPosition){ return; } //Set the new position mCurrentPosition = i; mViewPager.setCurrentItem(i); return; } } } } /** * Clears the tabs */ public void clear(){ mTabStrip.removeAllViews(); } /** * @param position The position of the desired tab * @return The tab view */ public View getTabView(int position){ //Make sure that the position is within bounds if(position < 0 || position >= mTabStrip.getChildCount()){ return null; } return mTabStrip.getChildAt(position); } /** * Sets the color of the indicator when a tab is selected * * @param color The indicator color */ public void setIndicatorColor(int color){ mTabStrip.setSelectedIndicatorColors(color); } /* NON-VIEWPAGER TABS */ /** * Adds the tabs based on a list of Strings to use as tab titles * * @param callback The {@link Callback} to call when a tab is clicked * @param initialTab The initial tab to show * @param titles The titles for the tabs */ public void addTabs(Callback callback, int initialTab, List<String> titles){ //Create a new listener based on the given callback TabClickListener listener = new TabClickListener(callback); View firsTab = null; //Go through the titles for(int i = 0; i < titles.size(); i ++){ String title = titles.get(i); View tabView; TextView tabTitleView = null; //If there is a custom tab view layout id set, try and inflate it if(mTabViewLayoutId != 0){ tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); //Set up the icon if needed if(mHasIcon){ ImageView iconView = (ImageView)tabView.findViewById(mTabViewIconId); iconView.setImageResource(mIconIds[i]); } } else { tabView = createDefaultTabView(getContext()); } if(tabTitleView == null && TextView.class.isInstance(tabView)){ tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(title); tabView.setOnClickListener(listener); mTabStrip.addView(tabView); if(i == initialTab){ firsTab = tabView; } } if(firsTab != null){ //Click on the first tab if there is one firsTab.performClick(); //Set the current position mCurrentPosition = initialTab; } } /** * Adds the tabs based on the given titles * * @param callback The {@link Callback} to use when a tab is selected * @param initialTab The initial tab selected * @param titles The variable list of titles */ public void addTabs(Callback callback, int initialTab, String... titles){ List<String> tabTitles = new ArrayList<>(); Collections.addAll(tabTitles, titles); addTabs(callback, initialTab, tabTitles); } /** * Adds the tabs based on a list of Strings to use as tab titles. * Assumes that the first tab is the selected one but will not call the callback * * @param callback The {@link Callback} to call when a tab is clicked * @param titles The titles for the tabs */ public void addTabs(Callback callback, List<String> titles){ addTabs(callback, -1, titles); } /** * Adds the tabs based on the given titles. * Assumes that the first tab is the selected one but will not call the callback * * @param callback The {@link Callback} to call when a tab is clicked * @param titles The variable list of titles */ public void addTabs(Callback callback, String... titles){ addTabs(callback, -1, titles); } /** * The OnClickListener used when we are using tabs without a ViewPager */ private class TabClickListener implements OnClickListener{ /** * The callback to call when a tab is selected */ private Callback mCallback; /** * The ViewPagerListener instance to update the UI */ private InternalViewPagerListener listener; /** * Default Constructor * * @param callback The callback */ public TabClickListener(Callback callback){ //Create a new InternalViewPagerListener to update the UI this.listener = new InternalViewPagerListener(); this.mCallback = callback; } @Override public void onClick(View v){ for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)){ //If this tab is already open, do nothing if(i == mCurrentPosition){ return; } //Set the new position mCurrentPosition = i; //Call the appropriate listeners/callbacks mCallback.onTabSelected(i); listener.onPageSelected(i); return; } } } } /** * Callback to implement when a tab is clicked on */ public static abstract class Callback { /** * Called when a tab is selected * * @param position The tab position */ public abstract void onTabSelected(int position); } }
package bits.math3d; import java.util.Random; /** * @author decamp */ public final class Arr { public static float[] wrap( float... vals ) { return vals; } public static double[] wrap( double... vals ) { return vals; } public static float[] toFloats( double... vals ) { float[] ret = new float[ vals.length ]; for( int i = 0; i < vals.length; i++ ) { ret[i] = (float)vals[i]; } return ret; } public static double[] toDoubles( float... vals ) { double[] ret = new double[ vals.length ]; for( int i = 0; i < vals.length; i++ ) { ret[i] = vals[i]; } return ret; } public static void put( float[] src, float[] dst ) { System.arraycopy( src, 0, dst, 0, src.length ); } public static void put( double[] src, double[] dst ) { System.arraycopy( src, 0, dst, 0, src.length ); } public static void put( float[] src, int srcOff, float[] dst, int dstOff, int len ) { System.arraycopy( src, srcOff, dst, dstOff, len ); } public static void put( double[] src, int srcOff, double[] dst, int dstOff, int len ) { System.arraycopy( src, srcOff, dst, dstOff, len ); } public static void put( float[] src, double[] dst ) { for( int i = 0; i < src.length; i++ ) { dst[i] = src[i]; } } public static void put( float[] src, int srcOff, double[] dst, int dstOff, int len ) { for( int i = 0; i < len; i++ ) { dst[i+dstOff] = src[i+srcOff]; } } public static void put( double[] src, float[] dst ) { for( int i = 0; i < src.length; i++ ) { dst[i] = (float)src[i]; } } public static void put( double[] src, int srcOff, float[] dst, int dstOff, int len ) { for( int i = 0; i < len; i++ ) { dst[i+dstOff] = (float)src[i+srcOff]; } } public static void mult( float sa, float[] a ) { mult( sa, a, 0, a.length ); } public static void mult( double sa, double[] a ) { mult( sa, a, 0, a.length ); } public static void mult( float sa, float[] a, int off, int len ) { for( int i = off; i < off + len; i++ ) { a[i] *= sa; } } public static void mult( double sa, double[] a, int off, int len ) { for( int i = off; i < off + len; i++ ) { a[i] *= sa; } } public static void mult( float[] a, float[] b, float[] out ) { mult( a, 0, b, 0, a.length, out, 0 ); } public static void mult( double[] a, double[] b, double[] out ) { mult( a, 0, b, 0, a.length, out, 0 ); } public static void mult( float[] a, int aOff, float[] b, int bOff, int len, float[] out, int outOff ) { for( int i = 0; i < len; i++ ) { out[outOff+i] = a[aOff+i] * b[bOff+i]; } } public static void mult( double[] a, int aOff, double[] b, int bOff, int len, double[] out, int outOff ) { for( int i = 0; i < len; i++ ) { out[outOff+i] = a[aOff+i] * b[bOff+i]; } } public static void add( float ta, float[] a ) { add( ta, a, 0, a.length ); } public static void add( double ta, double[] a ) { add( ta, a, 0, a.length ); } public static void add( float ta, float[] a, int off, int len ) { for( int i = off; i < off + len; i++ ) { a[i] += ta; } } public static void add( double ta, double[] a, int off, int len ) { for( int i = off; i < off + len; i++ ) { a[i] += ta; } } public static void add( float[] a, float[] b, float[] out ) { add( a, 0, b, 0, a.length, out, 0 ); } public static void add( double[] a, double[] b, double[] out ) { add( a, 0, b, 0, a.length, out, 0 ); } public static void add( float[] a, int aOff, float[] b, int bOff, int len, float[] out, int outOff ) { for( int i = 0; i < len; i++ ) { out[outOff+i] = a[aOff+i] + b[bOff+i]; } } public static void add( double[] a, int aOff, double[] b, int bOff, int len, double[] out, int outOff ) { for( int i = 0; i < len; i++ ) { out[outOff+i] = a[aOff+i] + b[bOff+i]; } } public static float dot( float[] a, float[] b ) { return dot( a, 0, b, 0, a.length ); } public static double dot( double[] a, double[] b ) { return dot( a, 0, b, 0, a.length ); } public static float dot( float[] a, int aOff, float[] b, int bOff, int len ) { float sum = 0f; for( int i = 0; i < len; i++ ) { sum += a[aOff+i] * b[bOff+i]; } return sum; } public static double dot( double[] a, int aOff, double[] b, int bOff, int len ) { double sum = 0f; for( int i = 0; i < len; i++ ) { sum += a[aOff+i] * b[bOff+i]; } return sum; } public static void multAdd( float[] a, float scale, float add ) { multAdd( a, 0, a.length, scale, add ); } public static void multAdd( double[] a, double scale, double add ) { multAdd( a, 0, a.length, scale, add ); } public static void multAdd( float[] a, int off, int len, float scale, float add ) { for( int i = off; i < off + len; i++ ) { a[i] = a[i] * scale + add; } } public static void multAdd( double[] a, int off, int len, double scale, double add ) { for( int i = off; i < off + len; i++ ) { a[i] = a[i] * scale + add; } } public static void multAdd( float sa, float[] a, float sb, float[] b, float[] out ) { multAdd( sa, a, 0, sb, b, 0, a.length, out, 0 ); } public static void multAdd( double sa, double[] a, double sb, double[] b, double[] out ) { multAdd( sa, a, 0, sb, b, 0, a.length, out, 0 ); } public static void multAdd( float sa, float[] a, int offA, float sb, float[] b, int offB, int len, float[] out, int offOut ) { for( int i = 0; i < len; i++ ) { out[offOut+i] = sa * a[offA+i] + sb * b[offB+i]; } } public static void multAdd( double sa, double[] a, int offA, double sb, double[] b, int offB, int len, double[] out, int offOut ) { for( int i = 0; i < len; i++ ) { out[offOut+i] = sa * a[offA+i] + sb * b[offB+i]; } } public static void lerp( float[] a, float[] b, float p, float[] out ) { lerp( a, 0, b, 0, a.length, p, out, 0 ); } public static void lerp( double[] a, double[] b, double p, double[] out ) { lerp( a, 0, b, 0, a.length, p, out, 0 ); } public static void lerp( float[] a, int aOff, float[] b, int bOff, int len, float p, float[] out, int outOff ) { final float q = 1.0f - p; for( int i = 0; i < len; i++ ) { out[outOff+i] = q * a[aOff+i] + p * b[bOff+i]; } } public static void lerp( double[] a, int aOff, double[] b, int bOff, int len, double p, double[] out, int outOff ) { final double q = 1.0 - p; for( int i = 0; i < len; i++ ) { out[outOff+i] = q * a[aOff+i] + p * b[bOff+i]; } } public static float len( float... arr ) { return (float)Math.sqrt( lenSquared( arr, 0, arr.length ) ); } public static double len( double... arr ) { return Math.sqrt( lenSquared( arr, 0, arr.length ) ); } public static float len( float[] arr, int off, int len ) { return (float)Math.sqrt( lenSquared( arr, off, len ) ); } public static double len( double[] arr, int off, int len ) { return Math.sqrt( lenSquared( arr, off, len ) ); } public static float lenSquared( float... arr ) { return lenSquared( arr, 0, arr.length ); } public static double lenSquared( double... arr ) { return lenSquared( arr, 0, arr.length ); } public static float lenSquared( float[] arr, int off, int len ) { float sum = 0; for( int i = off; i < off + len; i++ ) { sum += arr[i] * arr[i]; } return sum; } public static double lenSquared( double[] arr, int off, int len ) { double sum = 0; for( int i = off; i < off + len; i++ ) { sum += arr[i] * arr[i]; } return sum; } public static void normalize( float[] arr ) { normalize( arr, 0, arr.length, 1f ); } public static void normalize( double[] arr ) { normalize( arr, 0, arr.length, 1.0 ); } public static void normalize( float[] a, int off, int len, float normLength ) { normLength /= len( a, off, len ); for( int i = 0; i < len; i++ ) { a[i+off] *= normLength; } } public static void normalize( double[] a, int off, int len, double normLength ) { normLength /= len( a, off, len ); for( int i = 0; i < len; i++ ) { a[i+off] *= normLength; } } public static float sum( float... arr ) { return sum( arr, 0, arr.length ); } public static double sum( double... arr ) { return sum( arr, 0, arr.length ); } public static float sum( float[] arr, int off, int len ) { float ret = 0.0f; for( int i = off; i < off + len; i++ ) { ret += arr[i]; } return ret; } public static double sum( double[] arr, int off, int len ) { double ret = 0.0f; for( int i = off; i < off + len; i++ ) { ret += arr[i]; } return ret; } public static float mean( float... arr ) { return mean( arr, 0, arr.length ); } public static double mean( double... arr ) { return mean( arr, 0, arr.length ); } public static float mean( float[] arr, int off, int len ) { float sum = 0.0f; for( int i = off; i < off + len; i++ ) { sum += arr[i]; } return sum / len; } public static double mean( double[] arr, int off, int len ) { double sum = 0.0f; for( int i = off; i < off + len; i++ ) { sum += arr[i]; } return sum / len; } public static float variance( float... arr ) { return variance( arr, 0, arr.length ); } public static double variance( double... arr ) { return variance( arr, 0, arr.length ); } public static float variance( float[] arr, int off, int len ) { return variance( arr, off, len, mean( arr, off, len ) ); } public static double variance( double[] arr, int off, int len ) { return variance( arr, off, len, mean( arr, off, len ) ); } public static float variance( float[] arr, int off, int len, float mean ) { float sum = 0.0f; for( int i = off; i < off + len; i++ ) { float v = arr[i] - mean; sum += v * v; } return sum / len; } public static double variance( double[] arr, int off, int len, double mean ) { double sum = 0.0f; for( int i = off; i < off + len; i++ ) { double v = arr[i] - mean; sum += v * v; } return sum / len; } public static float min( float... arr ) { return min( arr, 0, arr.length ); } public static double min( double... arr ) { return min( arr, 0, arr.length ); } public static float min( float[] arr, int off, int len ) { if( len <= 0.0 ) { return Float.NaN; } float ret = arr[off]; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] < ret ) { ret = arr[i]; } } return ret; } public static double min( double[] arr, int off, int len ) { if( len <= 0.0 ) { return Double.NaN; } double ret = arr[off]; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] < ret ) { ret = arr[i]; } } return ret; } public static float max( float... arr ) { return max( arr, 0, arr.length ); } public static double max( double... arr ) { return max( arr, 0, arr.length ); } public static float max( float[] arr, int off, int len ) { if( len <= 0.0 ) { return Float.NaN; } float ret = arr[off]; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] > ret ) { ret = arr[i]; } } return ret; } public static double max( double[] arr, int off, int len ) { if( len <= 0.0 ) { return Double.NaN; } double ret = arr[off]; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] > ret ) { ret = arr[i]; } } return ret; } public static float[] range( float... arr ) { return range( arr, 0, arr.length ); } public static double[] range( double... arr ) { return range( arr, 0, arr.length ); } public static float[] range( float[] arr, int off, int len ) { float[] ret = new float[2]; range( arr, off, len, ret ); return ret; } public static double[] range( double[] arr, int off, int len ) { double[] ret = new double[2]; range( arr, off, len, ret ); return ret; } public static void range( float[] arr, float[] out2x1 ) { range( arr, 0, arr.length, out2x1 ); } public static void range( double[] arr, double[] out2x1 ) { range( arr, 0, arr.length, out2x1 ); } public static void range( float[] arr, int off, int len, float[] out2x1 ) { if( len <= 0 ) { out2x1[0] = Float.NaN; out2x1[1] = Float.NaN; return; } float min = arr[off]; float max = min; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] < min ) { min = arr[i]; } if( arr[i] > max ) { max = arr[i]; } } out2x1[0] = min; out2x1[1] = max; } public static void range( double[] arr, int off, int len, double[] out2x1 ) { if( len <= 0 ) { out2x1[0] = Double.NaN; out2x1[1] = Double.NaN; return; } double min = arr[off]; double max = min; for( int i = off + 1; i < off + len; i++ ) { if( arr[i] < min ) { min = arr[i]; } if( arr[i] > max ) { max = arr[i]; } } out2x1[0] = min; out2x1[1] = max; } public static void fitRange( float[] arr, int off, int len, float min, float max ) { float[] range = range( arr, off, len ); fitRange( arr, off, len, range[0], range[1], min, max ); } public static void fitRange( double[] arr, int off, int len, double min, double max ) { double[] range = range( arr, off, len ); fitRange( arr, off, len, range[0], range[1], min, max ); } public static void fitRange( float[] arr, int off, int len, float inMin, float inMax, float outMin, float outMax ) { float scale = ( outMax - outMin) / ( inMax - inMin); if( Float.isNaN( scale ) ) { scale = 0.0f; } float add = outMin - inMin * scale; for( int i = off; i < off + len; i++ ) { arr[i] = arr[i] * scale + add; } } public static void fitRange( double[] arr, int off, int len, double inMin, double inMax, double outMin, double outMax ) { double scale = ( outMax - outMin) / ( inMax - inMin ); if( Double.isNaN( scale ) ) { scale = 0.0f; } double add = outMin - inMin * scale; for( int i = off; i < off + len; i++ ) { arr[i] = arr[i] * scale + add; } } public static void clamp( float[] arr, int off, int len, float min, float max ) { for( int i = off; i < off + len; i++ ) { if( arr[i] < min ) { arr[i] = min; } else if( arr[i] > max ) { arr[i] = max; } } } public static void clamp( double[] arr, int off, int len, double min, double max ) { for( int i = off; i < off + len; i++ ) { if( arr[i] < min ) { arr[i] = min; } else if( arr[i] > max ) { arr[i] = max; } } } public static void clampMin( float[] arr, float min ) { clampMin( arr, 0, arr.length, min ); } public static void clampMin( double[] arr, double min ) { clampMin( arr, 0, arr.length, min ); } public static void clampMin( float[] arr, int off, int len, float min ) { for( int i = off; i < off + len; i++ ) { if( arr[i] < min ) { arr[i] = min; } } } public static void clampMin( double[] arr, int off, int len, double min ) { for( int i = off; i < off + len; i++ ) { if( arr[i] < min ) { arr[i] = min; } } } public static void clampMax( float[] arr, float max ) { clampMax( arr, 0, arr.length, max ); } public static void clampMax( double[] arr, double max ) { clampMax( arr, 0, arr.length, max ); } public static void clampMax( float[] arr, int off, int len, float max ) { for( int i = off; i < off + len; i++ ) { if( arr[i] > max ) { arr[i] = max; } } } public static void clampMax( double[] arr, int off, int len, double max ) { for( int i = off; i < off + len; i++ ) { if( arr[i] > max ) { arr[i] = max; } } } public static void pow( float[] arr, float exp ) { pow( arr, 0, arr.length, exp ); } public static void pow( double[] arr, double exp ) { pow( arr, 0, arr.length, exp ); } public static void pow( float[] arr, int off, int len, float exp ) { for( int i = off; i < off + len; i++ ) { arr[i] = (float)Math.pow( arr[i], exp ); } } public static void pow( double[] arr, int off, int len, double exp ) { for( int i = off; i < off + len; i++ ) { arr[i] = Math.pow( arr[i], exp ); } } public static void exp( float[] arr, float base ) { exp( arr, 0, arr.length, base ); } public static void exp( double[] arr, double base ) { exp( arr, 0, arr.length, base ); } public static void exp( float[] arr, int off, int len, float base ) { double s = 1.0 / Math.exp( base ); for( int i = off; i < off + len; i++ ) { arr[i] = (float)( Math.exp( base ) * s ); } } public static void exp( double[] arr, int off, int len, double base ) { double s = 1.0 / Math.exp( base ); for( int i = off; i < off + len; i++ ) { arr[i] = ( Math.exp( base ) * s ); } } public static void shuffle( Object[] arr, Random rand ) { shuffle( arr, 0, arr.length, rand ); } public static void shuffle( Object[] arr, int off, int len, Random rand ) { for( int i = 0; i < len-1; i++ ) { int j = rand.nextInt( len - i ); Object temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } private Arr() {} /** * @deprecated Use transform range */ public static void normalize( double[] arr, int off, int len, double min, double max ) { double[] range = range( arr, off, len ); normalize( arr, off, len, range[0], range[1], min, max ); } /** * @deprecated Use transform range */ public static void normalize( double[] arr, int off, int len, double inMin, double inMax, double outMin, double outMax ) { double scale = ( outMax - outMin) / ( inMax - inMin ); if( Double.isNaN( scale ) ) { scale = 0.0f; } double add = outMin - inMin * scale; for( int i = off; i < off + len; i++ ) { arr[i] = arr[i] * scale + add; } } /** * @deprecated Use transformRange */ public static void normalize( float[] arr, int off, int len, float min, float max ) { float[] range = range( arr, off, len ); normalize( arr, off, len, range[0], range[1], min, max ); } /** * @deprecated Use transformRange */ public static void normalize( float[] arr, int off, int len, float inMin, float inMax, float outMin, float outMax ) { float scale = ( outMax - outMin) / ( inMax - inMin); if( Float.isNaN( scale ) ) { scale = 0.0f; } float add = outMin - inMin * scale; for( int i = off; i < off + len; i++ ) { arr[i] = arr[i] * scale + add; } } /** * @deprecated */ public static void mult( float[] arr, float scale ) { mult( arr, 0, arr.length, scale ); } /** * @deprecated */ public static void mult( double[] arr, double scale ) { mult( arr, 0, arr.length, scale ); } /** * @deprecated */ public static void mult( float[] arr, int off, int len, float scale ) { for( int i = off; i < off + len; i++ ) { arr[i] *= scale; } } /** * @deprecated */ public static void mult( double[] arr, int off, int len, double scale ) { for( int i = off; i < off + len; i++ ) { arr[i] *= scale; } } /** * @deprecated */ public static void add( float[] a, float ta ) { add( a, 0, a.length, ta ); } /** * @deprecated */ public static void add( float[] arr, int off, int len, float amount ) { for( int i = off; i < off + len; i++ ) { arr[i] += amount; } } /** * @deprecated */ public static void add( double[] arr, double amount ) { add( arr, 0, arr.length, amount ); } /** * @deprecated */ public static void add( double[] arr, int off, int len, double amount ) { for( int i = off; i < off + len; i++ ) { arr[i] += amount; } } /** * @deprecated Use normalize( float[], int, int, float ) */ public static void normalize( float length, float[] a, int off, int len ) { length /= len( a, off, len ); for( int i = 0; i < len; i++ ) { a[i+off] *= length; } } /** * @deprecated Use normalize( double[], int, int, double ) */ public static void normalize( double length, double[] a, int off, int len ) { length /= len( a, off, len ); for( int i = 0; i < len; i++ ) { a[i+off] *= length; } } }
package com.samourai.wallet; import android.animation.ObjectAnimator; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; //import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.*; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TypefaceUtil; import com.samourai.wallet.util.WebUtil; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.json.JSONException; import org.spongycastle.util.encoders.Hex; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private ProgressDialog progress = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private int refreshed = 0; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); refreshTx(notifTx, fetch); if(BalanceActivity.this != null) { try { HD_WalletFactory.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2 || (SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0 && SamouraiWallet.getInstance().getShowTotalBalance()) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.receive2Samourai) .setCancelable(false) .setPositiveButton(R.string.generate_receive_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } else { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { doExplorerView(tx.getHash()); } } }); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); refreshTx(false, true); } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onPause() { super.onPause(); // LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); ibQuickSend.collapse(); } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { doSweep(); } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(strResult), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(MainNetParams.get(), strResult); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(MainNetParams.get()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { doSweep(pvr); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { doSweep(privKeyReader); } else { ; } } } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { HD_WalletFactory.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doSweep() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep(final PrivKeyReader privKeyReader) { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { if(privKeyReader == null || privKeyReader.getKey() == null || !privKeyReader.getKey().hasPrivKey()) { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); return; } String address = privKeyReader.getKey().toAddress(MainNetParams.get()).toString(); UTXO utxo = APIFactory.getInstance(BalanceActivity.this).getUnspentOutputsForSweep(address); if(utxo != null) { long total_value = 0L; final List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint outpoint : outpoints) { total_value += outpoint.getValue().longValue(); } final BigInteger fee = FeeUtil.getInstance().estimatedFee(outpoints.size(), 1); final long amount = total_value - fee.longValue(); // Log.d("BalanceActivity", "Total value:" + total_value); // Log.d("BalanceActivity", "Amount:" + amount); // Log.d("BalanceActivity", "Fee:" + fee.toString()); String message = "Sweep " + Coin.valueOf(amount).toPlainString() + " from " + address + " (fee:" + Coin.valueOf(fee.longValue()).toPlainString() + ")?"; AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { final ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait_sending)); progress.show(); String receive_address = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(receive_address, BigInteger.valueOf(amount)); org.bitcoinj.core.Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outpoints, receivers, fee); tx = SendFactory.getInstance(BalanceActivity.this).signTransactionForSweep(tx, privKeyReader); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); // Log.d("BalanceActivity", hexTx); try { String response = WebUtil.getInstance(null).postURL(WebUtil.BLOCKCHAIN_DOMAIN + "pushtx", "tx=" + hexTx); Log.d("BalanceActivity", "pushTx:" + response); if(response.contains("Transaction Submitted")) { Toast.makeText(BalanceActivity.this, R.string.tx_sent, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show(); } } catch(Exception e) { Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.dismiss(); } } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { ; } }); AlertDialog alert = builder.create(); alert.show(); } else { Toast.makeText(BalanceActivity.this, R.string.cannot_find_unspents, Toast.LENGTH_SHORT).show(); } } catch(Exception e) { Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show(); } Looper.loop(); } }).start(); } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { HD_WalletFactory.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(HD_WalletFactory.getInstance(BalanceActivity.this).get().toJSON(BalanceActivity.this).toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", encrypted); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, encrypted); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean fetch) { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); // TBD: check on lookahead/lookbehind for all incoming payment codes if(fetch || txs.size() == 0) { APIFactory.getInstance(BalanceActivity.this).initWallet(); } try { int acc = 0; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); } else { acc = SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1; txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr()); } } else { txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr()); } if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc)); } if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc)); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } finally { ; } handler.post(new Runnable() { public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); } }); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); if(notifTx) { // check for incoming payment code notification tx try { PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode(); APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString()); // Log.i("BalanceFragment", "payment code:" + pcode.toString()); // Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString()); } catch (AddressFormatException afe) { afe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } // check on outgoing payment code notification tx List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed(); // Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size()); for(Pair<String,String> pair : outgoingUnconfirmed) { // Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft()); // Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight()); int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight()); if(confirmations > 0) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM); } if(confirmations == -1) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT); } } Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } Looper.loop(); } }).start(); } private void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat(" df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } private String getBTCDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } }
package org.broad.igv.sashimi; import org.broad.igv.event.IGVEventBus; import org.broad.igv.event.IGVEventObserver; import org.broad.igv.event.ViewChange; import org.broad.igv.feature.IExon; import org.broad.igv.prefs.Constants; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.sam.*; import org.broad.igv.track.*; import org.broad.igv.ui.IGV; import org.broad.igv.ui.color.ColorPalette; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.panel.*; import org.broad.igv.ui.util.IGVMouseInputAdapter; import org.broad.igv.ui.util.UIUtilities; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.*; import java.awt.geom.Rectangle2D; import java.io.File; import java.util.List; import java.util.*; public class SashimiPlot extends JFrame implements IGVEventObserver { private List<SpliceJunctionTrack> spliceJunctionTracks; private ReferenceFrame referenceFrame; private IGVEventBus eventBus; /** * The minimum allowed origin of the frame. We set scrolling * limits based on initialization */ private final double minOrigin; /** * The maximum allow end of the frame. We set scrolling * limits based on initialization */ private final double maxEnd; private static final List<Color> plotColors; static { ColorPalette palette = ColorUtilities.getDefaultPalette(); plotColors = Arrays.asList(palette.getColors()); } public SashimiPlot(ReferenceFrame iframe, Collection<? extends AlignmentTrack> alignmentTracks, FeatureTrack geneTrack) { // setContentPane(new SashimiContentPane()); getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); int minJunctionCoverage = PreferencesManager.getPreferences().getAsInt(Constants.SAM_JUNCTION_MIN_COVERAGE); this.eventBus = new IGVEventBus(); this.referenceFrame = new ReferenceFrame(iframe, eventBus); minOrigin = this.referenceFrame.getOrigin(); maxEnd = this.referenceFrame.getEnd(); int height = IGV.hasInstance() ? IGV.getInstance().getMainFrame().getHeight() : 800; setSize(referenceFrame.getWidthInPixels(), height); JPanel sashimiPanel = new JPanel(); BoxLayout boxLayout = new BoxLayout(sashimiPanel, BoxLayout.Y_AXIS); sashimiPanel.setLayout(boxLayout); //Add control elements to the top sashimiPanel.add(generateControlPanel(this.referenceFrame)); spliceJunctionTracks = new ArrayList<>(alignmentTracks.size()); int colorInd = 0; eventBus.subscribe(ViewChange.class, this); for (AlignmentTrack alignmentTrack : alignmentTracks) { //AlignmentDataManager oldDataManager = alignmentTrack.getDataManager(); AlignmentDataManager dataManager = alignmentTrack.getDataManager(); SpliceJunctionTrack spliceJunctionTrack = new SpliceJunctionTrack(alignmentTrack.getResourceLocator(), alignmentTrack.getName(), dataManager, alignmentTrack, SpliceJunctionTrack.StrandOption.COMBINE); // Override expand/collpase setting -- expanded sashimi plots make no sense spliceJunctionTrack.setDisplayMode(Track.DisplayMode.COLLAPSED); spliceJunctionTrack.setRendererClass(SashimiJunctionRenderer.class); Color color = plotColors.get(colorInd); colorInd = (colorInd + 1) % plotColors.size(); spliceJunctionTrack.setColor(color); TrackComponent<SpliceJunctionTrack> trackComponent = new TrackComponent<SpliceJunctionTrack>(referenceFrame, spliceJunctionTrack); trackComponent.originalFrame = iframe; initSpliceJunctionComponent(trackComponent, dataManager, dataManager.getCoverageTrack(), minJunctionCoverage); sashimiPanel.add(trackComponent); spliceJunctionTracks.add(spliceJunctionTrack); spliceJunctionTrack.load(iframe); // <= Must "load" tracks with frame of alignment track (actually just fetches from cache) } Axis axis = createAxis(referenceFrame); sashimiPanel.add(axis); SelectableFeatureTrack geneTrackClone = new SelectableFeatureTrack(geneTrack); TrackComponent<SelectableFeatureTrack> geneComponent = new TrackComponent<SelectableFeatureTrack>(referenceFrame, geneTrackClone); initGeneComponent(referenceFrame.getWidthInPixels(), geneComponent, geneTrackClone); JScrollPane scrollableGenePane = new JScrollPane(geneComponent); scrollableGenePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollableGenePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sashimiPanel, scrollableGenePane); splitPane.setDividerLocation(2 * height / 3); getContentPane().add(splitPane); validate(); } private Component generateControlPanel(ReferenceFrame frame) { JPanel controlPanel = new JPanel(); ZoomSliderPanel zoomSliderPanel = new ZoomSliderPanel(frame); zoomSliderPanel.setMinZoomLevel(frame.getZoom()); zoomSliderPanel.addMouseListener(new IGVMouseInputAdapter() { @Override public void igvMouseClicked(MouseEvent e) { SashimiPlot.this.repaint(); } }); Dimension controlSize = new Dimension(200, 30); controlPanel.add(zoomSliderPanel); setFixedSize(zoomSliderPanel, controlSize); Dimension panelSize = controlSize; setFixedSize(controlPanel, panelSize); BoxLayout layout = new BoxLayout(controlPanel, BoxLayout.X_AXIS); controlPanel.setLayout(layout); return controlPanel; } private static void setFixedSize(Component component, Dimension dimension) { component.setPreferredSize(dimension); component.setMinimumSize(dimension); component.setMaximumSize(dimension); } private Axis createAxis(ReferenceFrame frame) { Axis axis = new Axis(frame); Dimension maxDim = new Dimension(Integer.MAX_VALUE, 25); axis.setMaximumSize(maxDim); Dimension prefDim = new Dimension(maxDim); prefDim.setSize(frame.getWidthInPixels(), prefDim.height); axis.setPreferredSize(prefDim); return axis; } private void initGeneComponent(int prefWidth, TrackComponent<SelectableFeatureTrack> geneComponent, FeatureTrack geneTrack) { geneTrack.setDisplayMode(Track.DisplayMode.SQUISHED); geneTrack.clearPackedFeatures(); RenderContext context = new RenderContext(geneComponent, null, referenceFrame, null); geneTrack.load(context.getReferenceFrame()); GeneTrackMouseAdapter ad2 = new GeneTrackMouseAdapter(geneComponent); geneComponent.addMouseListener(ad2); geneComponent.addMouseMotionListener(ad2); } private void initSpliceJunctionComponent(TrackComponent<SpliceJunctionTrack> trackComponent, AlignmentDataManager dataManager, CoverageTrack coverageTrack, int minJunctionCoverage) { JunctionTrackMouseAdapter ad1 = new JunctionTrackMouseAdapter(trackComponent); trackComponent.addMouseListener(ad1); trackComponent.addMouseMotionListener(ad1); getRenderer(trackComponent.track).setDataManager(dataManager); getRenderer(trackComponent.track).setCoverageTrack(coverageTrack); getRenderer(trackComponent.track).getCoverageTrack().rescale(trackComponent.originalFrame); dataManager.setMinJunctionCoverage(minJunctionCoverage); getRenderer(trackComponent.track).setBackground(getBackground()); } private SashimiJunctionRenderer getRenderer(SpliceJunctionTrack spliceJunctionTrack) { return (SashimiJunctionRenderer) spliceJunctionTrack.getRenderer(); } @Override public void receiveEvent(Object event) { repaint(); } /** * Should consider using this elsewhere. Single component * which contains a single track */ private static class TrackComponent<T extends Track> extends JComponent { private T track; private ReferenceFrame frame; private String toolTipText = null; public ReferenceFrame originalFrame; public TrackComponent(ReferenceFrame frame, T track) { this.frame = frame; this.track = track; } public void updateToolTipText(TrackClickEvent tce) { toolTipText = track.getValueStringAt(tce.getFrame().getChrName(), tce.getChromosomePosition(), tce.getMouseEvent().getX(), tce.getMouseEvent().getY(), tce.getFrame()); toolTipText = "<html>" + toolTipText; setToolTipText(toolTipText); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Rectangle bounds = getBounds(); RenderContext context = new RenderContext(this, (Graphics2D) g, frame, bounds); track.render(context, bounds); } @Override public Dimension getPreferredSize() { return new Dimension(Integer.MAX_VALUE, track.getHeight()); } } /** * Set the minimum junction coverage, per trac,k and is not persistent * <p/> * Our "Set Max Junction Coverage Range" just changes the view scaling, it doesn't * filter anything, which is different behavior than the minimum. This might be confusing. * * @param trackComponent * @param newMinJunctionCoverage */ private void setMinJunctionCoverage(TrackComponent<SpliceJunctionTrack> trackComponent, int newMinJunctionCoverage) { AlignmentDataManager dataManager = getRenderer(trackComponent.track).getDataManager(); dataManager.setMinJunctionCoverage(newMinJunctionCoverage); trackComponent.track.clear(); trackComponent.repaint(); } /** * Set the max coverage depth, which is a graphical scaling parameter for determining how * thick the junction arcs will be * * @param trackComponent * @param newMaxDepth */ private void setMaxCoverageDepth(TrackComponent<SpliceJunctionTrack> trackComponent, int newMaxDepth) { getRenderer(trackComponent.track).setMaxDepth(newMaxDepth); repaint(); } private class JunctionTrackMouseAdapter extends TrackComponentMouseAdapter<SpliceJunctionTrack> { JunctionTrackMouseAdapter(TrackComponent<SpliceJunctionTrack> trackComponent) { super(trackComponent); } @Override protected void handleDataClick(MouseEvent e) { //Show data of some sort? } @Override protected IGVPopupMenu getPopupMenu(MouseEvent e) { IGVPopupMenu menu = new IGVPopupMenu(); final JCheckBoxMenuItem showCoverageData = new JCheckBoxMenuItem("Show Exon Coverage Data"); showCoverageData.setSelected(PreferencesManager.getPreferences().getAsBoolean(Constants.SASHIMI_SHOW_COVERAGE)); showCoverageData.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PreferencesManager.getPreferences().put(Constants.SASHIMI_SHOW_COVERAGE, showCoverageData.isSelected()); SashimiPlot.this.repaint(); } }); CoverageTrack covTrack = getRenderer(this.trackComponent.track).getCoverageTrack(); covTrack.setWindowFunction(WindowFunction.max); JMenuItem setCoverageDataRange = CoverageTrack.addDataRangeItem(SashimiPlot.this, null, Arrays.asList(covTrack)); setCoverageDataRange.setText("Set Exon Coverage Max"); JMenuItem maxJunctionCoverageRange = new JMenuItem("Set Junction Coverage Max"); maxJunctionCoverageRange.setToolTipText("The thickness of each line will be proportional to the coverage, up until this value"); maxJunctionCoverageRange.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String input = JOptionPane.showInputDialog("Set Max Junction Coverage", getRenderer(trackComponent.track).getMaxDepth()); if (input == null || input.length() == 0) return; try { int newMaxDepth = Integer.parseInt(input); setMaxCoverageDepth(JunctionTrackMouseAdapter.this.trackComponent, newMaxDepth); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(SashimiPlot.this, input + " is not an integer"); } } }); JMenuItem minJunctionCoverage = new JMenuItem("Set Junction Coverage Min"); minJunctionCoverage.setToolTipText("Junctions below this threshold will be removed from view"); minJunctionCoverage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AlignmentDataManager dataManager = getRenderer(trackComponent.track).getDataManager(); SpliceJunctionHelper.LoadOptions loadOptions = dataManager.getSpliceJunctionLoadOptions(); String input = JOptionPane.showInputDialog("Set Minimum Junction Coverage", loadOptions.minJunctionCoverage); if (input == null || input.length() == 0) return; try { int newMinJunctionCoverage = Integer.parseInt(input); setMinJunctionCoverage(JunctionTrackMouseAdapter.this.trackComponent, newMinJunctionCoverage); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(SashimiPlot.this, input + " is not an integer"); } } }); JMenuItem colorItem = new JMenuItem("Set Color"); colorItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color color = UIUtilities.showColorChooserDialog( "Select Track Color", trackComponent.track.getColor()); SashimiPlot.this.toFront(); if (color == null) return; trackComponent.track.setColor(color); trackComponent.repaint(); } }); ButtonGroup shapeGroup = new ButtonGroup(); JRadioButtonMenuItem textShape = getJunctionCoverageRadioButton("Text", SashimiJunctionRenderer.ShapeType.TEXT); textShape.setToolTipText("Show junction coverage as text"); shapeGroup.add(textShape); JRadioButtonMenuItem circleShape = getJunctionCoverageRadioButton("Circle", SashimiJunctionRenderer.ShapeType.CIRCLE); circleShape.setToolTipText("Show junction coverage as a circle"); shapeGroup.add(circleShape); JRadioButtonMenuItem ellipseShape = getJunctionCoverageRadioButton("Ellipse", SashimiJunctionRenderer.ShapeType.ELLIPSE); ellipseShape.setToolTipText("Show junction coverage as an ellipse"); shapeGroup.add(ellipseShape); JRadioButtonMenuItem noShape = getJunctionCoverageRadioButton("None", SashimiJunctionRenderer.ShapeType.NONE); ellipseShape.setToolTipText("Show junction coverage as an ellipse"); shapeGroup.add(ellipseShape); ButtonGroup strandGroup = new ButtonGroup(); JRadioButtonMenuItem combineStrands = getStrandRadioButton("Combine Strands", SpliceJunctionTrack.StrandOption.COMBINE); combineStrands.setToolTipText("Combine junctions from both strands -- best for non-strand preserving libraries."); strandGroup.add(combineStrands); // JRadioButtonMenuItem bothStrands = getStrandRadioButton("Both Strands", SpliceJunctionTrack.StrandOption.BOTH); // strandGroup.add(bothStrands); // menu.add(bothStrands); JRadioButtonMenuItem plusStrand = getStrandRadioButton("Forward Strand", SpliceJunctionTrack.StrandOption.FORWARD); plusStrand.setToolTipText("Show only junctions on the forward read strand (of first-in-pair for paired reads)"); strandGroup.add(plusStrand); JRadioButtonMenuItem minusStrand = getStrandRadioButton("Reverse Strand", SpliceJunctionTrack.StrandOption.REVERSE); plusStrand.setToolTipText("Show only junctions on the reverse read strand (of first-in-pair for paired reads)"); strandGroup.add(minusStrand); JMenuItem savePngImageItem = new JMenuItem("Save PNG Image..."); savePngImageItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File defaultFile = new File("Sashimi.png"); IGV.getInstance().createSnapshot(SashimiPlot.this.getContentPane(), defaultFile); } }); JMenuItem saveSvgImageItem = new JMenuItem("Save SVG Image..."); saveSvgImageItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File defaultFile = new File("Sashimi.svg"); IGV.getInstance().createSnapshot(SashimiPlot.this.getContentPane(), defaultFile); } }); // Coverage ranges -- these apply to current plot only menu.add(new JLabel("Junction Coverage Display")); menu.add(setCoverageDataRange); menu.add(minJunctionCoverage); menu.add(maxJunctionCoverageRange); menu.add(colorItem); // Coverage data -- applies to all plots menu.add(showCoverageData); // Shape options -- all plots menu.addSeparator(); menu.add(textShape); menu.add(circleShape); // menu.add(ellipseShape); menu.add(noShape); // Strand options -- applies to all plots menu.addSeparator(); menu.add(combineStrands); menu.add(plusStrand); menu.add(minusStrand); menu.addSeparator(); menu.add(savePngImageItem); menu.add(saveSvgImageItem); return menu; } private JRadioButtonMenuItem getJunctionCoverageRadioButton(String label, final SashimiJunctionRenderer.ShapeType shapeType) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(label); item.setSelected(SashimiJunctionRenderer.getShapeType() == shapeType); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SashimiJunctionRenderer.setShapeType(shapeType); SashimiPlot.this.repaint(); } }); return item; } private JRadioButtonMenuItem getStrandRadioButton(String label, final SpliceJunctionTrack.StrandOption option) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(label); item.setSelected(SpliceJunctionTrack.getStrandOption() == option); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SpliceJunctionTrack.setStrandOption(option); for (SpliceJunctionTrack t : spliceJunctionTracks) { t.clear(); } repaint(); } }); return item; } } private class GeneTrackMouseAdapter extends TrackComponentMouseAdapter<SelectableFeatureTrack> { GeneTrackMouseAdapter(TrackComponent<SelectableFeatureTrack> trackComponent) { super(trackComponent); } @Override protected void handleDataClick(MouseEvent e) { trackComponent.track.handleDataClick(createTrackClickEvent(e)); Set<IExon> selectedExon = trackComponent.track.getSelectedExons(); for (SpliceJunctionTrack spliceTrack : spliceJunctionTracks) { getRenderer(spliceTrack).setSelectedExons(selectedExon); } repaint(); } @Override public void mouseMoved(MouseEvent e) { trackComponent.updateToolTipText(createTrackClickEvent(e)); } @Override protected IGVPopupMenu getPopupMenu(MouseEvent e) { IGVPopupMenu menu = new IGVPopupMenu(); TrackMenuUtils.addDisplayModeItems(Arrays.asList(trackComponent.track), menu); menu.addPopupMenuListener(new RepaintPopupMenuListener(trackComponent)); return menu; } } private abstract class TrackComponentMouseAdapter<T extends Track> extends IGVMouseInputAdapter { protected TrackComponent<T> trackComponent; protected PanTool currentTool; TrackComponentMouseAdapter(TrackComponent<T> trackComponent) { this.trackComponent = trackComponent; currentTool = new PanTool(null); currentTool.setReferenceFrame(this.trackComponent.frame); } @Override public void mouseDragged(MouseEvent e) { if (currentTool.getLastMousePoint() == null) { //This shouldn't happen, but does occasionally return; } double diff = e.getX() - currentTool.getLastMousePoint().getX(); // diff > 0 means moving mouse to the right, which drags the frame towards the negative direction boolean hitBounds = SashimiPlot.this.referenceFrame.getOrigin() <= minOrigin && diff > 0; hitBounds |= SashimiPlot.this.referenceFrame.getEnd() >= maxEnd && diff < 0; if (!hitBounds) { currentTool.mouseDragged(e); repaint(); } } @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if (e.isPopupTrigger()) { doPopupMenu(e); } else { currentTool.mouseReleased(e); } } @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); if (e.isPopupTrigger()) { doPopupMenu(e); } else { currentTool.mousePressed(e); super.mousePressed(e); } } protected void doPopupMenu(MouseEvent e) { IGVPopupMenu menu = getPopupMenu(e); if (menu != null) menu.show(trackComponent, e.getX(), e.getY()); } protected TrackClickEvent createTrackClickEvent(MouseEvent e) { return new TrackClickEvent(e, trackComponent.frame); } @Override public void igvMouseClicked(MouseEvent e) { if (e.isPopupTrigger()) { doPopupMenu(e); return; } currentTool.mouseClicked(e); handleDataClick(e); } /** * Essentially left click * * @param e */ protected abstract void handleDataClick(MouseEvent e); /** * Essentially right click * * @param e * @return */ protected abstract IGVPopupMenu getPopupMenu(MouseEvent e); } /** * Show SashimiPlot window, or change settings of {@code currentWindow} */ public static void openSashimiPlot() { FeatureTrack geneTrack = null; List<FeatureTrack> nonJunctionTracks = new ArrayList(IGV.getInstance().getFeatureTracks()); Iterator iter = nonJunctionTracks.iterator(); while (iter.hasNext()) { if (iter.next() instanceof SpliceJunctionTrack) iter.remove(); } if (nonJunctionTracks.size() == 1) { geneTrack = nonJunctionTracks.get(0); } else { FeatureTrackSelectionDialog dlg = new FeatureTrackSelectionDialog(IGV.getInstance().getMainFrame(), nonJunctionTracks); dlg.setTitle("Select Gene Track"); dlg.setVisible(true); if (dlg.getIsCancelled()) { return; } geneTrack = dlg.getSelectedTrack(); } Collection<AlignmentTrack> alignmentTracks = new ArrayList<AlignmentTrack>(); for (Track track : IGV.getInstance().getAllTracks()) { if (track instanceof AlignmentTrack) { alignmentTracks.add((AlignmentTrack) track); } } if (alignmentTracks.size() > 1) { TrackSelectionDialog<AlignmentTrack> alDlg = new TrackSelectionDialog<AlignmentTrack>(IGV.getInstance().getMainFrame(), TrackSelectionDialog.SelectionMode.MULTIPLE, alignmentTracks); alDlg.setTitle("Select Alignment Tracks"); alDlg.setVisible(true); if (alDlg.getIsCancelled()) return; alignmentTracks = alDlg.getSelectedTracks(); } SashimiPlot sashimiPlot = new SashimiPlot(FrameManager.getDefaultFrame(), alignmentTracks, geneTrack); //sashimiPlot.setShapeType(shapeType); sashimiPlot.setVisible(true); } private static class RepaintPopupMenuListener implements PopupMenuListener { Component component; RepaintPopupMenuListener(Component component) { this.component = component; } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { component.repaint(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { UIUtilities.invokeOnEventThread(() -> { component.revalidate(); component.repaint(); }); } @Override public void popupMenuCanceled(PopupMenuEvent e) { component.repaint(); } } private static class Axis extends JComponent { private ReferenceFrame frame; Axis(ReferenceFrame frame) { this.frame = frame; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Rectangle visibleRect = getVisibleRect(); RenderContext context = new RenderContext(this, (Graphics2D) g, frame, visibleRect); drawGenomicAxis(context, visibleRect); } /** * Draw axis displaying genomic coordinates * * @param context * @param trackRectangle */ private void drawGenomicAxis(RenderContext context, Rectangle trackRectangle) { int numTicks = 4; int ticHeight = 5; double pixelPadding = trackRectangle.getWidth() / 20; int yLoc = ticHeight + 1; double origin = context.getOrigin(); double locScale = context.getScale(); //Pixel start/end positions of ruler double startPix = trackRectangle.getX() + pixelPadding; double endPix = trackRectangle.getMaxX() - pixelPadding; double ticIntervalPix = (endPix - startPix) / (numTicks - 1); double ticIntervalCoord = locScale * ticIntervalPix; int startCoord = (int) (origin + (locScale * startPix)); Graphics2D g2D = context.getGraphic2DForColor(Color.black); g2D.drawLine((int) startPix, yLoc, (int) endPix, yLoc); for (int tic = 0; tic < numTicks; tic++) { int xLoc = (int) (startPix + tic * ticIntervalPix); g2D.drawLine(xLoc, yLoc, xLoc, yLoc - ticHeight); int ticCoord = (int) (startCoord + tic * ticIntervalCoord); String text = "" + ticCoord; Rectangle2D textBounds = g2D.getFontMetrics().getStringBounds(text, g2D); g2D.drawString(text, (int) (xLoc - textBounds.getWidth() / 2), (int) (yLoc + textBounds.getHeight())); } } } }
package bluebot; import bluebot.commands.fun.*; import bluebot.commands.fun.quickreactions.IDGFCommand; import bluebot.commands.fun.quickreactions.KappaCommand; import bluebot.commands.fun.quickreactions.NopeCommand; import bluebot.commands.fun.quickreactions.WatCommand; import bluebot.commands.misc.*; import bluebot.commands.moderation.*; import bluebot.commands.owner.AnnouncementCommand; import bluebot.commands.owner.SetGameCommand; import bluebot.commands.owner.SetOnlineStateCommand; import bluebot.commands.owner.ShutDownCommand; import bluebot.commands.utility.*; import bluebot.utils.*; import bluebot.utils.listeners.*; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import net.dv8tion.jda.*; import net.dv8tion.jda.entities.Guild; import javax.security.auth.login.LoginException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * @file MainBot.java * @author Blue * @version 0.45 (I forgot some ...) * @brief The main class of BlueBot */ public class MainBot { private static JDA jda; private static String botOwner; private static LocalDateTime startTime = LocalDateTime.now(); public static final CommandParser parser = new CommandParser(); public static Map<String, Command> commands = new TreeMap<String, Command>(); private static Map<String, String> streamerList = new HashMap<>(); private static Map<String, String> autoRoleList = new HashMap<>(); private static Map<String, ArrayList<String>> badWords = new HashMap<>(); private static Map<String, String> prefixes = new HashMap<>(); private static Map<Guild, MyUrlPlayer> urlPlayersMap = new HashMap<>(); private static Map<String, String> bannedServers = new HashMap<>(); //server, reason for ban private static ArrayList<String> twitchDisabled = new ArrayList<>(); private static ArrayList<String> cleverBotDisabled = new ArrayList<>(); private static ArrayList<String> bwDisabled = new ArrayList<>(); private static ArrayList<String> userEventDisabled = new ArrayList<>(); private static Map<String, String> twitchChannel = new HashMap<>(); private static Map<String, String> userEventChannel = new HashMap<>(); private static Map<String, String> musicChannel = new HashMap<>(); public static Map<String, String> getBannedServers() { return bannedServers; } public static Map<Guild, MyUrlPlayer> getUrlPlayersMap() { return urlPlayersMap; } public static String getBotOwner() { return botOwner; } public static ArrayList<String> getTwitchDisabled() { return twitchDisabled; } public static ArrayList<String> getCleverBotDisabled() { return cleverBotDisabled; } public static ArrayList<String> getBwDisabled() { return bwDisabled; } public static ArrayList<String> getUserEventDisabled() { return userEventDisabled; } public static Map<String, String> getTwitchChannel() { return twitchChannel; } public static Map<String, String> getUserEventChannel() { return userEventChannel; } public static Map<String, String> getMusicChannel() { return musicChannel; } private static String basePrefix = "!"; public static void handleCommand(CommandParser.CommandContainer cmdContainer) { if(commands.containsKey(cmdContainer.invoke)) { boolean safe = commands.get(cmdContainer.invoke).called(cmdContainer.args, cmdContainer.event); if(safe) { commands.get(cmdContainer.invoke).action(cmdContainer.args, cmdContainer.event); commands.get(cmdContainer.invoke).executed(safe, cmdContainer.event); } else { commands.get(cmdContainer.invoke).executed(safe, cmdContainer.event); } } } public MainBot() { try { //jda instanciation //default method as provided in the API LoadingProperties config = new LoadingProperties(); SaveThread saveThread = new SaveThread(); //userEventDisabled.add("281978005088370688"); jda = new JDABuilder().setBotToken(config.getBotToken()) .addListener(new TwitchListener()) //.addListener(new CleverbotListener()) .addListener(new BadWordsListener()) .addListener(new UserJoinLeaveListener()) .addListener(new BotKickedListener()) .addListener(new BannedServersListener()) .addListener(new MessageReceivedListener()) .setBulkDeleteSplittingEnabled(false).buildBlocking(); botOwner = config.getBotOwner(); jda.getAccountManager().setGame(config.getBotActivity()); System.out.println("Current activity " + jda.getSelfInfo().getCurrentGame()); //Loading the previous state of the bot(before shutdown) Gson gson = new Gson(); streamerList = gson.fromJson(config.getStreamerList(), new TypeToken<Map<String, String>>(){}.getType()); autoRoleList = gson.fromJson(config.getAutoRoleList(), new TypeToken<Map<String, String>>(){}.getType()); badWords = gson.fromJson(config.getBadWords(), new TypeToken<Map<String, ArrayList<String>>>(){}.getType()); prefixes = gson.fromJson(config.getPrefixes(), new TypeToken<Map<String, String>>(){}.getType()); twitchDisabled = gson.fromJson(config.getTwitchDisabled(), new TypeToken<ArrayList<String>>(){}.getType()); cleverBotDisabled = gson.fromJson(config.getCleverBotDisabled(), new TypeToken<ArrayList<String>>(){}.getType()); bwDisabled = gson.fromJson(config.getBwDisabled(), new TypeToken<ArrayList<String>>(){}.getType()); userEventDisabled = gson.fromJson(config.getUserEventDisabled(), new TypeToken<ArrayList<String>>(){}.getType()); twitchChannel = gson.fromJson(config.getTwitchChannel(), new TypeToken<Map<String, String>>(){}.getType()); userEventChannel = gson.fromJson(config.getUserEventChannel(), new TypeToken<Map<String, String>>(){}.getType()); musicChannel = gson.fromJson(config.getMusicChannel(), new TypeToken<Map<String, String>>(){}.getType()); saveThread.run(); System.out.println("Connected servers : " + jda.getGuilds().size()); System.out.println("Concerned users : " + jda.getUsers().size()); } catch (InterruptedException e) { System.out.println("Error, please check your internet connection"); return; } catch (LoginException e) { System.out.println("No internet connection or invalid or missing token. Please edit config.blue and try again."); return; } //Banned servers bannedServers.put("304031909648793602", "spamming w/ bots to crash small bots"); //bannedServers.put("281978005088370688", "BlueBot TestServer"); //Activated bot commands commands.put("ping", new PingCommand()); commands.put("sayhi", new SayHiCommand()); commands.put("say", new SayCommand()); commands.put("rate", new RateCommand()); commands.put("clear", new ClearCommand()); commands.put("whoareyou", new WhoAreYouCommand()); commands.put("help", new HelpCommand()); commands.put("nope", new NopeCommand()); commands.put("ymjoke", new YoMommaJokeCommand()); commands.put("wat", new WatCommand()); commands.put("gif", new GifCommand()); commands.put("c&h", new CyanideHapinessCommand()); commands.put("setprefix", new SetPrefixCommand()); commands.put("sound", new PlaySoundCommand()); commands.put("tracktwitch", new TrackTwitchCommand()); commands.put("untrack", new UntrackCommand()); commands.put("setautorole", new SetAutoRoleCommand()); commands.put("cat", new CatCommand()); commands.put("idgf", new IDGFCommand()); commands.put("bw", new BadWordCommand()); commands.put("info", new InfoCommand()); commands.put("steam", new SteamStatusCommand()); commands.put("kappa", new KappaCommand()); commands.put("enable", new EnableListenerCommand()); commands.put("disable", new DisableListenerCommand()); commands.put("channel", new SpecificChannelCommand()); commands.put("invite", new InviteCommand()); commands.put("call", new CallCommand()); //commands.put("prune", new PruneCommand()); //Owner commands commands.put("setgame", new SetGameCommand()); commands.put("setos", new SetOnlineStateCommand()); commands.put("shutdown", new ShutDownCommand()); commands.put("announce", new AnnouncementCommand()); } public static JDA getJda() { return jda; } public static Map<String, String> getStreamerList() {return streamerList;} public static Map<String, String> getAutoRoleList() {return autoRoleList;} public static LocalDateTime getStartTime() {return startTime;} public static Map<String, ArrayList<String>> getBadWords() {return badWords;} public static String getBasePrefix() {return basePrefix;} public static Map<String, String> getPrefixes() { return prefixes; } }
package com.samourai.wallet; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.DumpedPrivateKey; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.PoW; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.*; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.hf.HardForkUtil; import com.samourai.wallet.hf.ReplayProtectionActivity; import com.samourai.wallet.hf.ReplayProtectionWarningActivity; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.SweepUtil; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.TypefaceUtil; import org.bitcoinj.core.Coin; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.core.Transaction; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.DecoderException; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import info.guardianproject.netcipher.proxy.OrbotHelper; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private LinearLayout layoutAlert = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private RefreshTask refreshTask = null; private PoWTask powTask = null; private RBFTask rbfTask = null; private CPFPTask cpfpTask = null; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; final String blkHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } if(intent.hasExtra("hash")) { blkHash = intent.getStringExtra("hash"); } else { blkHash = null; } BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); refreshTx(notifTx, fetch, false, false); if(BalanceActivity.this != null) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if(powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) { powTask = new PoWTask(); powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash); } } }); } } } }; protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("BalanceActivity", "torStatusReceiver onReceive()"); if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) { boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON)); Log.i("BalanceActivity", "status:" + enabled); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if(SamouraiWallet.getInstance().isTestNet()) { setTitle(getText(R.string.app_name) + ":" + "TestNet"); } LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); if(hdw != null) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2 || (SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0 && SamouraiWallet.getInstance().getShowTotalBalance()) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.receive2Samourai) .setCancelable(false) .setPositiveButton(R.string.generate_receive_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } else { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); final Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String message = getString(R.string.options_unconfirmed_tx); // RBF if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(rbfTask == null || rbfTask.getStatus().equals(AsyncTask.Status.FINISHED)) { rbfTask = new RBFTask(); rbfTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP receive else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP spend else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } else { doExplorerView(tx.getHash()); return; } } } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(false, true, true, false); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); // TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS)); boolean notifTx = false; boolean fetch = false; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("notifTx")) { notifTx = extras.getBoolean("notifTx"); } if(extras != null && extras.containsKey("uri")) { fetch = extras.getBoolean("fetch"); } refreshTx(notifTx, fetch, false, true); // user checks mnemonic & passphrase if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CREDS_CHECK, 0L) == 0L) { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(BalanceActivity.this.getText(R.string.recovery_checkup_message)) .setCancelable(false) .setPositiveButton(R.string.next, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); try { final String seed = HD_WalletFactory.getInstance(BalanceActivity.this).get().getMnemonic(); final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String message = BalanceActivity.this.getText(R.string.mnemonic) + ":<br><br><b>" + seed + "</b><br><br>" + BalanceActivity.this.getText(R.string.passphrase) + ":<br><br><b>" + passphrase + "</b>"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(Html.fromHtml(message)) .setCancelable(false) .setPositiveButton(R.string.recovery_checkup_finish, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.CREDS_CHECK, System.currentTimeMillis() / 1000L); dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(IOException | MnemonicException.MnemonicLengthException e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); if(!isFinishing()) { dlg.show(); } } } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); } AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onPause() { super.onPause(); // LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); ibQuickSend.collapse(); } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); unregisterReceiver(torStatusReceiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { menu.findItem(R.id.action_tor).setVisible(false); } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on); } else { menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off); } menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { doSweep(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_tor) { if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { ; } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { item.setIcon(R.drawable.tor_off); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); } else { OrbotHelper.requestStartTor(BalanceActivity.this); item.setIcon(R.drawable.tor_on); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true); } return true; } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class); startActivity(intent); } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(false) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader); } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true); if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, obj.toString()); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean fetch, final boolean dragged, final boolean launch) { if(refreshTask == null || refreshTask.getStatus().equals(AsyncTask.Status.FINISHED)) { refreshTask = new RefreshTask(dragged, launch); refreshTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, notifTx ? "1" : "0", fetch ? "1" : "0"); } } private void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat(" df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } private String getBTCDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) { sel = 0; } CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } private class RefreshTask extends AsyncTask<String, Void, String> { private String strProgressTitle = null; private String strProgressMessage = null; private ProgressDialog progress = null; private Handler handler = null; private boolean dragged = false; private boolean launch = false; public RefreshTask(boolean dragged, boolean launch) { super(); Log.d("BalanceActivity", "RefreshTask, dragged==" + dragged); handler = new Handler(); this.dragged = dragged; this.launch = launch; } @Override protected void onPreExecute() { Log.d("BalanceActivity", "RefreshTask.preExecute()"); if(progress != null && progress.isShowing()) { progress.dismiss(); } if(!dragged) { strProgressTitle = BalanceActivity.this.getText(R.string.app_name).toString(); strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx_pre).toString(); progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(true); progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); progress.show(); } } @Override protected String doInBackground(String... params) { Log.d("BalanceActivity", "doInBackground()"); final boolean notifTx = params[0].equals("1") ? true : false; final boolean fetch = params[1].equals("1") ? true : false; // TBD: check on lookahead/lookbehind for all incoming payment codes if(fetch || txs.size() == 0) { Log.d("BalanceActivity", "initWallet()"); APIFactory.getInstance(BalanceActivity.this).initWallet(); } try { int acc = 0; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); } else { acc = SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1; txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr()); } } else { txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr()); } if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc)); } if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc)); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } finally { ; } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx).toString(); publishProgress(); } handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); } }); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); if(notifTx) { // check for incoming payment code notification tx try { PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode(); Log.i("BalanceFragment", "payment code:" + pcode.toString()); Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString()); APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString()); } catch (AddressFormatException afe) { afe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } strProgressMessage = BalanceActivity.this.getText(R.string.refresh_incoming_notif_tx).toString(); publishProgress(); // check on outgoing payment code notification tx List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed(); // Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size()); for(Pair<String,String> pair : outgoingUnconfirmed) { // Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft()); // Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight()); int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight()); if(confirmations > 0) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM); } if(confirmations == -1) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT); } } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_outgoing_notif_tx).toString(); publishProgress(); } Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } if(!dragged) { if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.GUID_V, 0) < 4) { Log.i("BalanceActivity", "guid_v < 4"); try { String _guid = AccessFactory.getInstance(BalanceActivity.this).createGUID(); String _hash = AccessFactory.getInstance(BalanceActivity.this).getHash(_guid, new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getPIN()), AESUtil.DefaultPBKDF2Iterations); PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(_guid + AccessFactory.getInstance().getPIN())); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH, _hash); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH2, _hash); Log.i("BalanceActivity", "guid_v == 4"); } catch(MnemonicException.MnemonicLengthException | IOException | JSONException | DecryptionException e) { ; } } else if(!launch) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(Exception e) { } } else { ; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!dragged) { if(progress != null && progress.isShowing()) { progress.dismiss(); } } // bccForkThread(); } @Override protected void onProgressUpdate(Void... values) { if(!dragged) { progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); } } } private class PoWTask extends AsyncTask<String, Void, String> { private boolean isOK = true; private String strBlockHash = null; @Override protected String doInBackground(String... params) { strBlockHash = params[0]; JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash); if(nodeObj != null && nodeObj.has("hash")) { PoW pow = new PoW(strBlockHash); String hash = pow.calcHash(nodeObj); if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) { JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash); if(headerObj != null && headerObj.has("")) { if(!pow.check(headerObj, nodeObj, hash)) { isOK = false; } } } else { isOK = false; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!isOK) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } } @Override protected void onPreExecute() { ; } } private class CPFPTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(); } @Override protected String doInBackground(String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(txObj.has("inputs") && txObj.has("outputs")) { final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFee(inputs.length(), outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; UTXO utxo = null; for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String addr = obj.getString("address"); Log.d("BalanceActivity", "checking address:" + addr); if(utxo == null) { utxo = getUTXO(addr); } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); if(utxo != null) { Log.d("BalanceActivity", "utxo found"); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); selectedUTXO.add(utxo); int selected = utxo.getOutpoints().size(); long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "remaining fee:" + remainingFee); int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0); Log.d("BalanceActivity", "receive index:" + receiveIdx); final String ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); Log.d("BalanceActivity", "receive address:" + ownReceiveAddr); long totalAmount = utxo.getValue(); Log.d("BalanceActivity", "amount before fee:" + totalAmount); BigInteger cpfpFee = FeeUtil.getInstance().estimatedFee(selected, 1); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); if(totalAmount < (cpfpFee.longValue() + remainingFee)) { Log.d("BalanceActivity", "selecting additional utxo"); Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { totalAmount += _utxo.getValue(); selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); cpfpFee = FeeUtil.getInstance().estimatedFee(selected, 1); if(totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { break; } } if(totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); FeeUtil.getInstance().setSuggestedFee(suggestedFee); return "KO"; } } cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee)); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } long _totalAmount = 0L; for(MyTransactionOutPoint outpoint : outPoints) { _totalAmount += outpoint.getValue().longValue(); } Log.d("BalanceActivity", "checked total amount:" + _totalAmount); assert(_totalAmount == totalAmount); long amount = totalAmount - cpfpFee.longValue(); Log.d("BalanceActivity", "amount after fee:" + amount); if(amount < SamouraiWallet.bDust.longValue()) { Log.d("BalanceActivity", "dust output"); Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(ownReceiveAddr, BigInteger.valueOf(amount)); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show(); FeeUtil.getInstance().setSuggestedFee(suggestedFee); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); // reset receive index upon tx fail int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { // reset receive index upon tx fail int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { dialog.dismiss(); } } }); if(!isFinishing()) { dlg.show(); } } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show(); } }); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } }); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private UTXO getUTXO(String address) { UTXO ret = null; int idx = -1; for(int i = 0; i < utxos.size(); i++) { UTXO utxo = utxos.get(i); Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress()); if(utxo.getOutpoints().get(0).getAddress().equals(address)) { ret = utxo; idx = i; break; } } if(ret != null) { utxos.remove(idx); return ret; } return null; } } private class RBFTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; private RBFSpend rbf = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(); } @Override protected String doInBackground(final String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); rbf = RBFUtil.getInstance().get(params[0]); Log.d("BalanceActivity", "rbf:" + ((rbf == null) ? "null" : "not null")); final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx())); Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx()); Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size()); Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size()); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(tx != null && txObj.has("inputs") && txObj.has("outputs")) { try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFee(tx.getInputs().size(), tx.getOutputs().size()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; long total_change = 0L; List<String> selfAddresses = new ArrayList<String>(); for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String _addr = obj.getString("address"); selfAddresses.add(_addr); if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { total_change += obj.getLong("value"); } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "total change:" + total_change); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); Log.d("BalanceActivity", "remaining fee:" + remainingFee); List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>(); txOutputs.addAll(tx.getOutputs()); long remainder = remainingFee; if(total_change > remainder) { for(TransactionOutput output : txOutputs) { if(rbf.getChangeAddrs().contains(output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) { output.setValue(Coin.valueOf(output.getValue().longValue() - remainder)); remainder = 0L; break; } else { remainder -= output.getValue().longValue(); output.setValue(Coin.valueOf(0L)); // output will be discarded later } } } } // original inputs are not modified List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>(); List<TransactionInput> txInputs = tx.getInputs(); for(TransactionInput input : txInputs) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString()); } if(remainder > 0L) { List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long selectedAmount = 0L; int selected = 0; long _remainingFee = remainder; Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { Log.d("BalanceActivity", "utxo value:" + _utxo.getValue()); // do not select utxo that are change outputs in current rbf tx boolean isChange = false; boolean isSelf = false; for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { if(rbf.containsChangeAddr(outpoint.getAddress())) { Log.d("BalanceActivity", "is change:" + outpoint.getAddress()); Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue()); isChange = true; break; } if(selfAddresses.contains(outpoint.getAddress())) { Log.d("BalanceActivity", "is self:" + outpoint.getAddress()); Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue()); isSelf = true; break; } } if(isChange || isSelf) { continue; } selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); Log.d("BalanceActivity", "selected utxo:" + selected); selectedAmount += _utxo.getValue(); Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue()); _remainingFee = FeeUtil.getInstance().estimatedFee(inputs.length() + selected, outputs.length() == 1 ? 2 : outputs.length()).longValue(); Log.d("BalanceActivity", "_remaining fee:" + _remainingFee); if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) { break; } } long extraChange = 0L; if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); return "KO"; } else { extraChange = selectedAmount - _remainingFee; Log.d("BalanceActivity", "extra change:" + extraChange); } boolean addedChangeOutput = false; // parent tx didn't have change output if(outputs.length() == 1 && extraChange > 0L) { try { int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx(); String change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString(); Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address)); TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram()); txOutputs.add(output); addedChangeOutput = true; } catch(MnemonicException.MnemonicLengthException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } } // parent tx had change output else { for(TransactionOutput output : txOutputs) { Log.d("BalanceActivity", "checking for change:" + output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(rbf.containsChangeAddr(output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { Log.d("BalanceActivity", "before extra:" + output.getValue().longValue()); output.setValue(Coin.valueOf(extraChange + output.getValue().longValue())); Log.d("BalanceActivity", "after extra:" + output.getValue().longValue()); addedChangeOutput = true; break; } } } // sanity check if(extraChange > 0L && !addedChangeOutput) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } // update keyBag w/ any new paths final HashMap<String,String> keyBag = rbf.getKeyBag(); for(UTXO _utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString()); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress()); if(path != null) { rbf.addKey(outpoint.toString(), path); } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress()); int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress()); rbf.addKey(outpoint.toString(), pcode + "/" + idx); } } } rbf.setKeyBag(keyBag); } // BIP69 sort of outputs/inputs final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams()); List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>(); _txOutputs.addAll(txOutputs); Collections.sort(_txOutputs, new SendFactory.BIP69OutputComparator()); for(TransactionOutput to : _txOutputs) { // zero value outputs discarded here if(to.getValue().longValue() > 0L) { _tx.addOutput(to); } } List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>(); __inputs.addAll(_inputs); Collections.sort(__inputs, new SendFactory.BIP69InputComparator()); for(TransactionInput input : __inputs) { _tx.addInput(input); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Transaction __tx = signTx(_tx); final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = __tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); if(__tx != null) { boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show(); RBFSpend _rbf = rbf; // includes updated 'keyBag' _rbf.setSerializedTx(hexTx); _rbf.setHash(strTxHash); _rbf.setPrevHash(params[0]); RBFUtil.getInstance().add(_rbf); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); } } catch(final DecoderException de) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private Transaction signTx(Transaction tx) { HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>(); HashMap<String,String> keys = rbf.getKeyBag(); for(String outpoint : keys.keySet()) { ECKey ecKey = null; String[] s = keys.get(outpoint).split("/"); if(s.length == 3) { HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); String strPrivKey = hd_address.getPrivateKeyString(); DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey); ecKey = pk.getKey(); } else if(s.length == 2) { try { PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1])); ecKey = address.getReceiveECKey(); } catch(Exception e) { ; } } else { ; } Log.i("BalanceActivity", "outpoint:" + outpoint); Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(ecKey != null) { keyBag.put(outpoint, ecKey); } else { throw new RuntimeException("ECKey error: cannot process private key"); // Log.i("ECKey error", "cannot process private key"); } } List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { ECKey ecKey = keyBag.get(inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()))); Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram())); TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false); tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey)); } return tx; } } private void bccForkThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); boolean isFork = false; int cf = -1; boolean dismissed = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BCC_DISMISSED, false); if(!dismissed) { long latestBlockHeight = APIFactory.getInstance(BalanceActivity.this).getLatestBlockHeight(); long distance = 0L; String strForkStatus = HardForkUtil.getInstance(BalanceActivity.this).forkStatus(); try { JSONObject forkObj = new JSONObject(strForkStatus); if(forkObj != null && forkObj.has("forks") && forkObj.getJSONObject("forks").has("abc")) { JSONObject abcObj = forkObj.getJSONObject("forks").getJSONObject("abc"); if(abcObj.has("height")) { long height = abcObj.getLong("height"); distance = latestBlockHeight - height; boolean laterThanFork = true; List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(); for(UTXO utxo : utxos) { List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint outpoint : outpoints) { if(outpoint.getConfirmations() >= distance) { laterThanFork = false; break; } } if(!laterThanFork) { break; } } if(laterThanFork) { dismissed = true; PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.BCC_DISMISSED, true); } } } } catch(JSONException je) { ; } } if(!dismissed && HardForkUtil.getInstance(BalanceActivity.this).isBitcoinABCForkActivateTime()) { String status = HardForkUtil.getInstance(BalanceActivity.this).forkStatus(); Log.d("BalanceActivity", status); try { JSONObject statusObj = new JSONObject(status); if(statusObj.has("forks") && statusObj.getJSONObject("forks").has("abc") && statusObj.has("clients") && statusObj.getJSONObject("clients").has("abc") && statusObj.getJSONObject("clients").getJSONObject("abc").has("replay") && statusObj.getJSONObject("clients").getJSONObject("abc").getBoolean("replay") == true) { isFork = true; String strTxHash = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BCC_REPLAY1, ""); if(strTxHash != null && strTxHash.length() > 0) { Log.d("BalanceActivity", "rbf replay hash:" + strTxHash); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(strTxHash); final int latestBlockHeight = (int)APIFactory.getInstance(BalanceActivity.this).getLatestBlockHeight(); Log.d("BalanceActivity", "txObj:" + txObj.toString()); try { if(txObj != null && txObj.has("block")) { JSONObject blockObj = txObj.getJSONObject("block"); if(blockObj.has("height") && blockObj.getInt("height") > 0) { int blockHeight = blockObj.getInt("height"); cf = (latestBlockHeight - blockHeight) + 1; Log.d("BalanceActivity", "confirmations (block):" + cf); if(cf >= 6) { isFork = false; } } } else if(txObj != null && txObj.has("txid")) { cf = 0; Log.d("BalanceActivity", "confirmations (hash):" + cf); } else { ; } } catch(JSONException je) { ; } } } } catch(JSONException je) { ; } } final int COLOR_ORANGE = 0xfffb8c00; final int COLOR_GREEN = 0xff4caf50; final boolean bccReplayed = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BCC_REPLAYED, false); if(cf >= 0 && cf < 6) { handler.post(new Runnable() { public void run() { layoutAlert = (LinearLayout)findViewById(R.id.alert); layoutAlert.setBackgroundColor(COLOR_ORANGE); TextView tvLeftTop = (TextView)layoutAlert.findViewById(R.id.left_top); TextView tvLeftBottom = (TextView)layoutAlert.findViewById(R.id.left_bottom); TextView tvRight = (TextView)layoutAlert.findViewById(R.id.right); tvLeftTop.setText(getText(R.string.replay_chain_split)); tvLeftBottom.setText(getText(R.string.replay_in_progress)); tvRight.setText(getText(R.string.replay_info)); layoutAlert.setVisibility(View.VISIBLE); layoutAlert.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(BalanceActivity.this, ReplayProtectionActivity.class); startActivity(intent); return false; } }); } }); } else if(cf >= 6 && !bccReplayed) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.BCC_REPLAYED, true); handler.post(new Runnable() { public void run() { layoutAlert = (LinearLayout)findViewById(R.id.alert); layoutAlert.setBackgroundColor(COLOR_GREEN); TextView tvLeftTop = (TextView)layoutAlert.findViewById(R.id.left_top); TextView tvLeftBottom = (TextView)layoutAlert.findViewById(R.id.left_bottom); TextView tvRight = (TextView)layoutAlert.findViewById(R.id.right); tvLeftTop.setText(getText(R.string.replay_chain_split)); tvLeftBottom.setText(getText(R.string.replay_protected)); tvRight.setText(getText(R.string.ok)); layoutAlert.setVisibility(View.VISIBLE); } }); } else if(bccReplayed) { handler.post(new Runnable() { public void run() { layoutAlert = (LinearLayout)findViewById(R.id.alert); layoutAlert.setVisibility(View.GONE); } }); } else if(isFork) { handler.post(new Runnable() { public void run() { layoutAlert = (LinearLayout)findViewById(R.id.alert); TextView tvLeftTop = (TextView)layoutAlert.findViewById(R.id.left_top); TextView tvLeftBottom = (TextView)layoutAlert.findViewById(R.id.left_bottom); TextView tvRight = (TextView)layoutAlert.findViewById(R.id.right); tvLeftTop.setText(getText(R.string.replay_chain_split)); tvLeftBottom.setText(getText(R.string.replay_enable)); tvRight.setText(getText(R.string.replay_info)); layoutAlert.setVisibility(View.VISIBLE); layoutAlert.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(BalanceActivity.this, ReplayProtectionWarningActivity.class); startActivity(intent); return false; } }); } }); } else { handler.post(new Runnable() { public void run() { layoutAlert = (LinearLayout)findViewById(R.id.alert); layoutAlert.setVisibility(View.GONE); } }); } Looper.loop(); } }).start(); } }
package org.cg.common.avro; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.URL; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.avro.ipc.HttpTransceiver; import org.apache.avro.ipc.NettyTransceiver; import org.apache.avro.ipc.Transceiver; import org.apache.avro.ipc.specific.SpecificRequestor; import org.apache.flume.EventDeliveryException; import org.apache.flume.FlumeException; import org.apache.flume.api.RpcClientConfigurationConstants; import org.apache.flume.api.RpcClientFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.compression.ZlibDecoder; import org.jboss.netty.handler.codec.compression.ZlibEncoder; import org.jboss.netty.handler.ssl.SslHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author yanlinwang * */ public class EventIpcClient<E> { protected int batchSize = 1000; protected long connectTimeout = TimeUnit.MILLISECONDS.convert(20, TimeUnit.SECONDS); protected long requestTimeout = TimeUnit.MILLISECONDS.convert(20, TimeUnit.SECONDS); protected ExecutorService callTimeoutPool; protected final ReentrantLock stateLock = new ReentrantLock(); protected URL targetUrl = null; /** * Guarded by {@code stateLock} */ protected ConnState connState; protected InetSocketAddress address; protected boolean enableSsl; protected boolean trustAllCerts; protected String truststore; protected String truststorePassword; protected String truststoreType; protected boolean isHttp = true; protected Transceiver transceiver; protected Class<E> exClass; protected E avroClient; protected static final Logger logger = LoggerFactory .getLogger(EventIpcClient.class); protected boolean enableDeflateCompression; protected int compressionLevel; /** * This constructor is intended to be called from {@link RpcClientFactory}. * A call to this constructor should be followed by call to configure(). */ public EventIpcClient(Class<E> exClass) { this.exClass = exClass; } public E getAvroClient() { return avroClient; } /** * This method should only be invoked by the build function * * @throws FlumeException */ private void connect() throws FlumeException { connect(connectTimeout, TimeUnit.MILLISECONDS); } /** * Internal only, for now * * @param timeout * @param tu * @throws FlumeException */ private void connect(long timeout, TimeUnit tu) throws FlumeException { callTimeoutPool = Executors .newCachedThreadPool(new TransceiverThreadFactory( "Flume Avro RPC Client Call Invoker")); NioClientSocketChannelFactory socketChannelFactory = null; try { if (targetUrl == null) { targetUrl = new URL("http://" + address.getHostName() + ":" + address.getPort()); } if (isHttp) { transceiver = new HttpTransceiver(targetUrl); } else { if (enableDeflateCompression || enableSsl) { socketChannelFactory = new SSLCompressionChannelFactory( Executors .newCachedThreadPool(new TransceiverThreadFactory( "Avro " + NettyTransceiver.class .getSimpleName() + " Boss")), Executors .newCachedThreadPool(new TransceiverThreadFactory( "Avro " + NettyTransceiver.class .getSimpleName() + " I/O Worker")), enableDeflateCompression, enableSsl, trustAllCerts, compressionLevel, truststore, truststorePassword, truststoreType); } else { socketChannelFactory = new NioClientSocketChannelFactory( Executors .newCachedThreadPool(new TransceiverThreadFactory( "Avro " + NettyTransceiver.class .getSimpleName() + " Boss")), Executors .newCachedThreadPool(new TransceiverThreadFactory( "Avro " + NettyTransceiver.class .getSimpleName() + " I/O Worker"))); } transceiver = new NettyTransceiver(this.address, socketChannelFactory, tu.toMillis(timeout)); } avroClient = SpecificRequestor.getClient(this.exClass, transceiver); } catch (Throwable t) { if (callTimeoutPool != null) { callTimeoutPool.shutdownNow(); } if (socketChannelFactory != null) { socketChannelFactory.releaseExternalResources(); } if (t instanceof IOException) { throw new FlumeException(this + ": RPC connection error", t); } else if (t instanceof FlumeException) { throw (FlumeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new FlumeException(this + ": Unexpected exception", t); } } setState(ConnState.READY); } public void close() throws FlumeException { if (callTimeoutPool != null) { callTimeoutPool.shutdown(); try { if (!callTimeoutPool.awaitTermination(requestTimeout, TimeUnit.MILLISECONDS)) { callTimeoutPool.shutdownNow(); if (!callTimeoutPool.awaitTermination(requestTimeout, TimeUnit.MILLISECONDS)) { logger.warn(this + ": Unable to cleanly shut down call timeout " + "pool"); } } } catch (InterruptedException ex) { logger.warn(this + ": Interrupted during close", ex); // re-cancel if current thread also interrupted callTimeoutPool.shutdownNow(); // preserve interrupt status Thread.currentThread().interrupt(); } callTimeoutPool = null; } try { transceiver.close(); } catch (IOException ex) { throw new FlumeException(this + ": Error closing transceiver.", ex); } finally { setState(ConnState.DEAD); } } @Override public String toString() { return "NettyAvroRpcClient { host: " + address.getHostName() + ", port: " + address.getPort() + " }"; } private void setState(ConnState newState) { stateLock.lock(); try { if (connState == ConnState.DEAD && connState != newState) { throw new IllegalStateException( "Cannot transition from CLOSED state."); } connState = newState; } finally { stateLock.unlock(); } } /** * If the connection state != READY, throws {@link EventDeliveryException}. */ public void assertReady() throws EventDeliveryException { stateLock.lock(); try { ConnState curState = connState; if (curState != ConnState.READY) { throw new EventDeliveryException( "RPC failed, client in an invalid " + "state: " + curState); } } finally { stateLock.unlock(); } } /** * Helper function to convert a map of String to a map of CharSequence. */ private static Map<CharSequence, CharSequence> toCharSeqMap( Map<String, String> stringMap) { Map<CharSequence, CharSequence> charSeqMap = new HashMap<CharSequence, CharSequence>(); for (Map.Entry<String, String> entry : stringMap.entrySet()) { charSeqMap.put(entry.getKey(), entry.getValue()); } return charSeqMap; } public boolean isActive() { stateLock.lock(); try { return (connState == ConnState.READY); } finally { stateLock.unlock(); } } private static enum ConnState { INIT, READY, DEAD } /** * <p> * Configure the actual client using the properties. <tt>properties</tt> * should have at least 2 params: * <p> * <tt>hosts</tt> = <i>alias_for_host</i> * </p> * <p> * <tt>alias_for_host</tt> = <i>hostname:port</i>. * </p> * Only the first host is added, rest are discarded.</p> * <p> * Optionally it can also have a * <p> * <tt>batch-size</tt> = <i>batchSize</i> * * @param properties * The properties to instantiate the client with. * @return */ public synchronized void configure(Properties properties) throws FlumeException { stateLock.lock(); try { if (connState == ConnState.READY || connState == ConnState.DEAD) { throw new FlumeException("This client was already configured, " + "cannot reconfigure."); } } finally { stateLock.unlock(); } // batch size String strBatchSize = properties .getProperty(RpcClientConfigurationConstants.CONFIG_BATCH_SIZE); logger.debug("Batch size string = " + strBatchSize); batchSize = RpcClientConfigurationConstants.DEFAULT_BATCH_SIZE; if (strBatchSize != null && !strBatchSize.isEmpty()) { try { int parsedBatch = Integer.parseInt(strBatchSize); if (parsedBatch < 1) { logger.warn( "Invalid value for batchSize: {}; Using default value.", parsedBatch); } else { batchSize = parsedBatch; } } catch (NumberFormatException e) { logger.warn("Batchsize is not valid for RpcClient: " + strBatchSize + ". Default value assigned.", e); } } // host and port String hostNames = properties .getProperty(RpcClientConfigurationConstants.CONFIG_HOSTS); String[] hosts = null; if (hostNames != null && !hostNames.isEmpty()) { hosts = hostNames.split("\\s+"); } else { throw new FlumeException("Hosts list is invalid: " + hostNames); } if (hosts.length > 1) { logger.warn("More than one hosts are specified for the default client. " + "Only the first host will be used and others ignored. Specified: " + hostNames + "; to be used: " + hosts[0]); } String host = properties .getProperty(RpcClientConfigurationConstants.CONFIG_HOSTS_PREFIX + hosts[0]); if (host == null || host.isEmpty()) { throw new FlumeException("Host not found: " + hosts[0]); } String[] hostAndPort = host.split(":"); if (hostAndPort.length != 2) { throw new FlumeException("Invalid hostname: " + hosts[0]); } Integer port = null; try { port = Integer.parseInt(hostAndPort[1]); } catch (NumberFormatException e) { throw new FlumeException("Invalid Port: " + hostAndPort[1], e); } this.address = new InetSocketAddress(hostAndPort[0], port); // connect timeout connectTimeout = RpcClientConfigurationConstants.DEFAULT_CONNECT_TIMEOUT_MILLIS; String strConnTimeout = properties .getProperty(RpcClientConfigurationConstants.CONFIG_CONNECT_TIMEOUT); if (strConnTimeout != null && strConnTimeout.trim().length() > 0) { try { connectTimeout = Long.parseLong(strConnTimeout); if (connectTimeout < 1000) { logger.warn("Connection timeout specified less than 1s. " + "Using default value instead."); connectTimeout = RpcClientConfigurationConstants.DEFAULT_CONNECT_TIMEOUT_MILLIS; } } catch (NumberFormatException ex) { logger.error("Invalid connect timeout specified: " + strConnTimeout); } } // request timeout requestTimeout = RpcClientConfigurationConstants.DEFAULT_REQUEST_TIMEOUT_MILLIS; String strReqTimeout = properties .getProperty(RpcClientConfigurationConstants.CONFIG_REQUEST_TIMEOUT); if (strReqTimeout != null && strReqTimeout.trim().length() > 0) { try { requestTimeout = Long.parseLong(strReqTimeout); if (requestTimeout < 1000) { logger.warn("Request timeout specified less than 1s. " + "Using default value instead."); requestTimeout = RpcClientConfigurationConstants.DEFAULT_REQUEST_TIMEOUT_MILLIS; } } catch (NumberFormatException ex) { logger.error("Invalid request timeout specified: " + strReqTimeout); } } String enableCompressionStr = properties .getProperty(RpcClientConfigurationConstants.CONFIG_COMPRESSION_TYPE); if (enableCompressionStr != null && enableCompressionStr.equalsIgnoreCase("deflate")) { this.enableDeflateCompression = true; String compressionLvlStr = properties .getProperty(RpcClientConfigurationConstants.CONFIG_COMPRESSION_LEVEL); compressionLevel = RpcClientConfigurationConstants.DEFAULT_COMPRESSION_LEVEL; if (compressionLvlStr != null) { try { compressionLevel = Integer.parseInt(compressionLvlStr); } catch (NumberFormatException ex) { logger.error("Invalid compression level: " + compressionLvlStr); } } } enableSsl = Boolean.parseBoolean(properties .getProperty(RpcClientConfigurationConstants.CONFIG_SSL)); trustAllCerts = Boolean .parseBoolean(properties .getProperty(RpcClientConfigurationConstants.CONFIG_TRUST_ALL_CERTS)); truststore = properties .getProperty(RpcClientConfigurationConstants.CONFIG_TRUSTSTORE); truststorePassword = properties .getProperty(RpcClientConfigurationConstants.CONFIG_TRUSTSTORE_PASSWORD); truststoreType = properties.getProperty( RpcClientConfigurationConstants.CONFIG_TRUSTSTORE_TYPE, "JKS"); this.connect(); } /** * A thread factor implementation modeled after the implementation of * NettyTransceiver.NettyTransceiverThreadFactory class which is a private * static class. The only difference between that and this implementation is * that this implementation marks all the threads daemon which allows the * termination of the VM when the non-daemon threads are done. */ private static class TransceiverThreadFactory implements ThreadFactory { private final AtomicInteger threadId = new AtomicInteger(0); private final String prefix; public TransceiverThreadFactory(String prefix) { this.prefix = prefix; } public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName(prefix + " " + threadId.incrementAndGet()); return thread; } } /** * Factory of SSL-enabled client channels Copied from Avro's * org.apache.avro.ipc.TestNettyServerWithSSL test */ private static class SSLCompressionChannelFactory extends NioClientSocketChannelFactory { private boolean enableCompression; private int compressionLevel; private boolean enableSsl; private boolean trustAllCerts; private String truststore; private String truststorePassword; private String truststoreType; public SSLCompressionChannelFactory(Executor bossExecutor, Executor workerExecutor, boolean enableCompression, boolean enableSsl, boolean trustAllCerts, int compressionLevel, String truststore, String truststorePassword, String truststoreType) { super(bossExecutor, workerExecutor); this.enableCompression = enableCompression; this.enableSsl = enableSsl; this.compressionLevel = compressionLevel; this.trustAllCerts = trustAllCerts; this.truststore = truststore; this.truststorePassword = truststorePassword; this.truststoreType = truststoreType; } @Override public SocketChannel newChannel(ChannelPipeline pipeline) { TrustManager[] managers; try { if (enableCompression) { ZlibEncoder encoder = new ZlibEncoder(compressionLevel); pipeline.addFirst("deflater", encoder); pipeline.addFirst("inflater", new ZlibDecoder()); } if (enableSsl) { if (trustAllCerts) { logger.warn("No truststore configured, setting TrustManager to accept" + " all server certificates"); managers = new TrustManager[] { new PermissiveTrustManager() }; } else { KeyStore keystore = null; if (truststore != null) { if (truststorePassword == null) { throw new NullPointerException( "truststore password is null"); } InputStream truststoreStream = new FileInputStream( truststore); keystore = KeyStore.getInstance(truststoreType); keystore.load(truststoreStream, truststorePassword.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory .getInstance("SunX509"); // null keystore is OK, with SunX509 it defaults to // system CA Certs // see // http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager tmf.init(keystore); managers = tmf.getTrustManagers(); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, managers, null); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); // addFirst() will make SSL handling the first stage of // decoding // and the last stage of encoding this must be added after // adding compression handling above pipeline.addFirst("ssl", new SslHandler(sslEngine)); } return super.newChannel(pipeline); } catch (Exception ex) { logger.error("Cannot create SSL channel", ex); throw new RuntimeException("Cannot create SSL channel", ex); } } } /** * Permissive trust manager accepting any certificate */ private static class PermissiveTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] certs, String s) { // nothing } public void checkServerTrusted(X509Certificate[] certs, String s) { // nothing } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }
package com.samourai.wallet; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.LocalBroadcastManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.service.WebSocketHandler; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.uri.BitcoinURI; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public class ReceiveActivity extends Activity { private static Display display = null; private static int imgWidth = 0; private ImageView ivQR = null; private TextView tvAddress = null; private LinearLayout addressLayout = null; private EditText edAmountBTC = null; private EditText edAmountFiat = null; private TextWatcher textWatcherBTC = null; private TextWatcher textWatcherFiat = null; private Switch swSegwit = null; private CheckBox cbBech32 = null; private String defaultSeparator = null; private String strFiat = null; private double btc_fx = 286.0; private TextView tvFiatSymbol = null; private String addr = null; private String addr44 = null; private String addr49 = null; private String addr84 = null; private boolean canRefresh44 = false; private boolean canRefresh49 = false; private boolean canRefresh84 = false; private Menu _menu = null; public static final String ACTION_INTENT = "com.samourai.wallet.ReceiveFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { Bundle extras = intent.getExtras(); if(extras != null && extras.containsKey("received_on")) { String in_addr = extras.getString("received_on"); if(in_addr.equals(addr) || in_addr.equals(addr44) || in_addr.equals(addr49)) { ReceiveActivity.this.runOnUiThread(new Runnable() { @Override public void run() { ReceiveActivity.this.finish(); } }); } } } } }; public ReceiveActivity() { ; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receive); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ReceiveActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); display = (ReceiveActivity.this).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); imgWidth = Math.max(size.x - 460, 150); swSegwit = (Switch)findViewById(R.id.segwit); swSegwit.setChecked(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true)); swSegwit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked && cbBech32.isChecked()) { addr = addr84; cbBech32.setVisibility(View.VISIBLE); } else if(isChecked && !cbBech32.isChecked()) { addr = addr49; cbBech32.setVisibility(View.VISIBLE); } else { addr = addr44; cbBech32.setVisibility(View.GONE); } displayQRCode(); } }); cbBech32 = (CheckBox)findViewById(R.id.bech32); cbBech32.setVisibility(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true ? View.VISIBLE : View.GONE); cbBech32.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { addr = addr84; } else { addr = addr49; } displayQRCode(); } }); addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString(); addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); if(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true && cbBech32.isChecked()) { addr = addr84; } else if(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true && !cbBech32.isChecked()) { addr = addr49; } else { addr = addr44; } addressLayout = (LinearLayout)findViewById(R.id.receive_address_layout); addressLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { new AlertDialog.Builder(ReceiveActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.receive_address_to_clipboard) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ReceiveActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Receive address", addr); clipboard.setPrimaryClip(clip); Toast.makeText(ReceiveActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); return false; } }); tvAddress = (TextView)findViewById(R.id.receive_address); ivQR = (ImageView)findViewById(R.id.qr); ivQR.setMaxWidth(imgWidth); ivQR.setOnTouchListener(new OnSwipeTouchListener(ReceiveActivity.this) { @Override public void onSwipeLeft() { if(swSegwit.isChecked() && cbBech32.isChecked() && canRefresh84) { addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString(); addr = addr84; canRefresh84 = false; _menu.findItem(R.id.action_refresh).setVisible(false); displayQRCode(); } else if(swSegwit.isChecked() && !cbBech32.isChecked() && canRefresh49) { addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); addr = addr49; canRefresh49 = false; _menu.findItem(R.id.action_refresh).setVisible(false); displayQRCode(); } else if(!swSegwit.isChecked() && canRefresh44) { addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); addr = addr44; canRefresh44 = false; _menu.findItem(R.id.action_refresh).setVisible(false); displayQRCode(); } else { ; } } }); DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); DecimalFormatSymbols symbols=format.getDecimalFormatSymbols(); defaultSeparator = Character.toString(symbols.getDecimalSeparator()); strFiat = PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); btc_fx = ExchangeRateFactory.getInstance(ReceiveActivity.this).getAvgPrice(strFiat); tvFiatSymbol = (TextView)findViewById(R.id.fiatSymbol); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); edAmountBTC = (EditText)findViewById(R.id.amountBTC); edAmountFiat = (EditText)findViewById(R.id.amountFiat); textWatcherBTC = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountBTC.removeTextChangedListener(this); edAmountFiat.removeTextChangedListener(textWatcherFiat); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(max_len + 1); btcFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { edAmountBTC.setText(s1.substring(0, s1.length() - 1)); edAmountBTC.setSelection(edAmountBTC.getText().length()); s = edAmountBTC.getEditableText(); } } } } catch (NumberFormatException nfe) { ; } catch(ParseException pe) { ; } if(d > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(ReceiveActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } edAmountFiat.addTextChangedListener(textWatcherFiat); edAmountBTC.addTextChangedListener(this); displayQRCode(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountBTC.addTextChangedListener(textWatcherBTC); textWatcherFiat = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountFiat.removeTextChangedListener(this); edAmountBTC.removeTextChangedListener(textWatcherBTC); int max_len = 2; NumberFormat fiatFormat = NumberFormat.getInstance(Locale.US); fiatFormat.setMaximumFractionDigits(max_len + 1); fiatFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue(); String s1 = fiatFormat.format(d); if(s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if(dec.length() > 0) { dec = dec.substring(1); if(dec.length() > max_len) { edAmountFiat.setText(s1.substring(0, s1.length() - 1)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } } } } catch(NumberFormatException nfe) { ; } catch(ParseException pe) { ; } if((d / btc_fx) > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(ReceiveActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx)); edAmountBTC.setSelection(edAmountBTC.getText().length()); } edAmountBTC.addTextChangedListener(textWatcherBTC); edAmountFiat.addTextChangedListener(this); displayQRCode(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountFiat.addTextChangedListener(textWatcherFiat); displayQRCode(); } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(ReceiveActivity.this).registerReceiver(receiver, filter); AppUtil.getInstance(ReceiveActivity.this).checkTimeOut(); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(ReceiveActivity.this).unregisterReceiver(receiver); } @Override public void onDestroy() { ReceiveActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.findItem(R.id.action_settings).setVisible(false); menu.findItem(R.id.action_sweep).setVisible(false); menu.findItem(R.id.action_backup).setVisible(false); menu.findItem(R.id.action_scan_qr).setVisible(false); menu.findItem(R.id.action_utxo).setVisible(false); menu.findItem(R.id.action_tor).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); menu.findItem(R.id.action_batch).setVisible(false); _menu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_share_receive) { new AlertDialog.Builder(ReceiveActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.receive_address_to_share) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strFileName = AppUtil.getInstance(ReceiveActivity.this).getReceiveQRFilename(); File file = new File(strFileName); if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { Toast.makeText(ReceiveActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } file.setReadable(true, false); FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch(FileNotFoundException fnfe) { ; } android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ReceiveActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Receive address", addr); clipboard.setPrimaryClip(clip); if(file != null && fos != null) { Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); try { fos.close(); } catch(IOException ioe) { ; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); startActivity(Intent.createChooser(intent, ReceiveActivity.this.getText(R.string.send_payment_code))); } } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } else if (id == R.id.action_refresh) { if(swSegwit.isChecked() && cbBech32.isChecked() && canRefresh84) { addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString(); addr = addr84; canRefresh84 = false; item.setVisible(false); displayQRCode(); } else if(swSegwit.isChecked() && !cbBech32.isChecked() && canRefresh49) { addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); addr = addr49; canRefresh49 = false; item.setVisible(false); displayQRCode(); } else if(!swSegwit.isChecked() && canRefresh44) { addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); addr = addr44; canRefresh44 = false; item.setVisible(false); displayQRCode(); } else { ; } } else if (id == R.id.action_support) { doSupport(); } else { ; } return super.onOptionsItemSelected(item); } private void doSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/7-receiving-bitcoin")); startActivity(intent); } private void displayQRCode() { String _addr = null; if(swSegwit.isChecked() && cbBech32.isChecked()) { _addr = addr.toUpperCase(); } else { _addr = addr; } try { double amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString()).doubleValue(); long lamount = (long)(amount * 1e8); if(lamount != 0L) { if(swSegwit.isChecked() && cbBech32.isChecked()) { ivQR.setImageBitmap(generateQRCode(BitcoinURI.convertToBitcoinURI(SamouraiWallet.getInstance().getCurrentNetworkParams(), _addr, Coin.valueOf(lamount), null, null))); } else { ivQR.setImageBitmap(generateQRCode(BitcoinURI.convertToBitcoinURI(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), _addr), Coin.valueOf(lamount), null, null))); } } else { ivQR.setImageBitmap(generateQRCode(_addr)); } } catch(NumberFormatException nfe) { ivQR.setImageBitmap(generateQRCode(_addr)); } catch(ParseException pe) { ivQR.setImageBitmap(generateQRCode(_addr)); } tvAddress.setText(addr); checkPrevUse(); new Thread(new Runnable() { @Override public void run() { if(AppUtil.getInstance(ReceiveActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(ReceiveActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(ReceiveActivity.this.getApplicationContext(), WebSocketService.class)); } }).start(); } private Bitmap generateQRCode(String uri) { Bitmap bitmap = null; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(uri, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth); try { bitmap = qrCodeEncoder.encodeAsBitmap(); } catch (WriterException e) { e.printStackTrace(); } return bitmap; } private void checkPrevUse() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final JSONObject jsonObject = APIFactory.getInstance(ReceiveActivity.this).getAddressInfo(addr); handler.post(new Runnable() { @Override public void run() { try { if(jsonObject != null && jsonObject.has("addresses") && jsonObject.getJSONArray("addresses").length() > 0) { JSONArray addrs = jsonObject.getJSONArray("addresses"); JSONObject _addr = addrs.getJSONObject(0); if(_addr.has("n_tx") && _addr.getLong("n_tx") > 0L) { Toast.makeText(ReceiveActivity.this, R.string.address_used_previously, Toast.LENGTH_SHORT).show(); if(swSegwit.isChecked() && cbBech32.isChecked()) { canRefresh84 = true; } else if(swSegwit.isChecked() && !cbBech32.isChecked()) { canRefresh49 = true; } else { canRefresh44 = true; } if(_menu != null) { _menu.findItem(R.id.action_refresh).setVisible(true); } } else { if(swSegwit.isChecked() && cbBech32.isChecked()) { canRefresh84 = false; } else if(swSegwit.isChecked() && !cbBech32.isChecked()) { canRefresh49 = false; } else { canRefresh44 = false; } if(_menu != null) { _menu.findItem(R.id.action_refresh).setVisible(false); } } } } catch (Exception e) { if(swSegwit.isChecked() && cbBech32.isChecked()) { canRefresh84 = false; } else if(swSegwit.isChecked() && !cbBech32.isChecked()) { canRefresh49 = false; } else { canRefresh44 = false; } if(_menu != null) { _menu.findItem(R.id.action_refresh).setVisible(false); } e.printStackTrace(); } } }); } catch (Exception e) { if(swSegwit.isChecked() && cbBech32.isChecked()) { canRefresh84 = false; } else if(swSegwit.isChecked() && !cbBech32.isChecked()) { canRefresh49 = false; } else { canRefresh44 = false; } if(_menu != null) { _menu.findItem(R.id.action_refresh).setVisible(false); } e.printStackTrace(); } } }).start(); } public String getDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } }
package me.cvhc.equationsolver; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PointF; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.androidplot.xy.BoundaryMode; import com.androidplot.xy.LineAndPointFormatter; import com.androidplot.xy.XYPlot; import com.androidplot.xy.XYSeries; import com.androidplot.xy.XYStepMode; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.HashMap; public class PlotActivity extends AppCompatActivity implements OnTouchListener { private DecimalInputView textUpperBound, textLowerBound; private XYPlot plot; private CheckBox checkXLogScale; private HashMap<Character, String> anotherSide; private SharedPreferences sharedPreferences; private FunctionWrapper mainSeries = null; private double minX, maxX; private double defaultMinX, defaultMaxX; private double maxAbsY; private int nZero = 0; private static double SCALE_YAXIS = 1.12; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_plot); // load preferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); int prefPlot = sharedPreferences.getInt("pref_plot_samples", 200); // initialize View objects Button buttonApply = (Button)findViewById(R.id.buttonApply); Button buttonReset = (Button)findViewById(R.id.buttonReset); textLowerBound = (DecimalInputView)findViewById(R.id.textLowerBound); textUpperBound = (DecimalInputView)findViewById(R.id.textUpperBound); checkXLogScale = (CheckBox)findViewById(R.id.checkXLogScale); plot = (XYPlot)findViewById(R.id.plot); assert buttonApply != null; assert buttonReset != null; assert textLowerBound != null; assert textUpperBound != null; assert checkXLogScale != null; assert plot != null; // read data from Intent object Intent intent = getIntent(); final ExpressionCalculator eval = new ExpressionCalculator(); anotherSide = (HashMap<Character, String>)intent.getSerializableExtra("EXPRESSION"); for (Character c: anotherSide.keySet()) { eval.setVariable(c, anotherSide.get(c)); } double[] threshold = intent.getDoubleArrayExtra("THRESHOLD"); if (threshold.length == 2) { // Bisection mode java.util.Arrays.sort(threshold); defaultMinX = minX = threshold[0]; defaultMaxX = maxX = threshold[1]; } else { // find an appropriate range double[] range = findBingoRange(threshold[0], eval); java.util.Arrays.sort(range); defaultMinX = minX = range[0]; defaultMaxX = maxX = range[1]; } // auto enable Log scale if (minX > 0 && maxX > 0 && Math.log10(maxX / minX) > 6) { checkXLogScale.setChecked(true); } DecimalInputView.OnValueChangedListener valueChangedListener = new DecimalInputView.OnValueChangedListener() { @Override public void onValueChanged(Number val) { double[] tmp = { textLowerBound.getValue(), textUpperBound.getValue() }; java.util.Arrays.sort(tmp); minX = checkXLogScale.isChecked() ? logScale(tmp[0]) : tmp[0]; maxX = checkXLogScale.isChecked() ? logScale(tmp[1]) : tmp[1]; resetY(); updatePlotBound(); } }; textLowerBound.setDialogTitle(getString(R.string.lower_bound_of_roi)); textLowerBound.setDefaultValue(minX); textLowerBound.setOnValueChangedListener(valueChangedListener); textUpperBound.setDialogTitle(getString(R.string.upper_bound_of_roi)); textUpperBound.setDefaultValue(maxX); textUpperBound.setOnValueChangedListener(valueChangedListener); // listeners buttonApply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String warning = null; if (nZero == 0) { warning = "Probably no zero point in select range."; } else if (nZero > 1) { warning = "It seems there are multiple zero points in select range."; } if (warning != null) { new AlertDialog.Builder(PlotActivity.this) .setTitle(android.R.string.dialog_alert_title) .setMessage(warning) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); submitSelectRange(); } }) .setNegativeButton(android.R.string.no, null) .setIconAttribute(android.R.attr.alertDialogIcon) .show(); } else { submitSelectRange(); } } }); buttonReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { minX = checkXLogScale.isChecked() ? logScale(defaultMinX) : defaultMinX; maxX = checkXLogScale.isChecked() ? logScale(defaultMaxX) : defaultMaxX; if (minX >= maxX || !isNormal(minX) || !isNormal(maxX)) { minX = checkXLogScale.isChecked() ? logScale(1e-14) : 0.0; maxX = checkXLogScale.isChecked() ? 0.0 : 1.0; } resetY(); updatePlotBound(); } }); abstract class CustomFormat extends NumberFormat { @Override abstract public StringBuffer format(double v, StringBuffer b, FieldPosition f); @Override public StringBuffer format(long v, StringBuffer b, FieldPosition f) { return null; } @Override public Number parse(String s, ParsePosition p) { return null; } } checkXLogScale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { minX = logScale(minX); maxX = logScale(maxX); if (!isNormal(minX) || !isNormal(maxX)) { minX = logScale(Math.pow(10, -14.0)); maxX = 0.0; } } else { minX = logScaleRecover(minX); maxX = logScaleRecover(maxX); } mainSeries.resetCache(); resetY(); updatePlotBound(); } }); // plot UI settings plot.setOnTouchListener(this); plot.setDomainStep(XYStepMode.SUBDIVIDE, 5); plot.setDomainValueFormat(new CustomFormat() { @Override public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) { double output = checkXLogScale.isChecked() ? logScaleRecover(value) : value; return new StringBuffer(String.format("%6.4g", output)); } }); plot.setRangeStep(XYStepMode.SUBDIVIDE, 7); plot.setRangeValueFormat(new CustomFormat() { @Override public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) { return new StringBuffer(String.format("%6.4g", value)); } }); plot.getLegendWidget().setVisible(false); plot.getTitleWidget().setVisible(false); plot.centerOnRangeOrigin(0.0); mainSeries = new FunctionWrapper(new FunctionWrapper.MathFunction() { @Override public double call(double x) { if (checkXLogScale.isChecked()) { x = logScaleRecover(x); } eval.setVariable('x', x); ExpressionCalculator.OptionUnion op = eval.evaluate(' '); return op.getValue(); } }, prefPlot); plot.addSeries(new XYSeries() { final static int DIVIDE = 8; @Override public int size() { return DIVIDE + 1; } @Override public Number getX(int index) { return minX + (maxX - minX) / DIVIDE * index; } @Override public Number getY(int index) { return 0.0; } @Override public String getTitle() { return null; } }, new LineAndPointFormatter(Color.rgb(255, 0, 0), null, null, null)); resetY(); plot.addSeries(mainSeries, new LineAndPointFormatter(Color.rgb(50, 0, 0), null, null, null)); updatePlotBound(); } private double[] findBingoRange(double fromX, final ExpressionCalculator eval) { FunctionWrapper.MathFunction func = new FunctionWrapper.MathFunction() { @Override public double call(double x) { eval.setVariable('x', x); ExpressionCalculator.OptionUnion op = eval.evaluate(' '); return op.getValue(); } }; double x1 = fromX, y1 = func.call(fromX); double[] result = new double[]{0, fromX}; long round = 0; while (isNormal(x1) && round < 100) { double x2 = x1, y2 = Double.NaN; double inc = Math.ulp(x1); round ++; while (isNormal(x2)) { x2 += inc; inc *= 10.0; if (y1 != (y2 = func.call(x2))) { break; } } double x_inter = (x2*y1 - x1*y2) / (y1-y2); double y_inter = func.call(x_inter); if (!isNormal(x_inter)) { break; } else if (Math.signum(y1) * Math.signum(y_inter) == -1) { result[0] = x1; result[1] = x_inter; break; } x1 = x_inter; y1 = y_inter; } return result; } private void submitSelectRange() { double realMinX = getRealMinX(); double realMaxX = getRealMaxX(); final ExpressionCalculator eval = new ExpressionCalculator(); for (Character c: anotherSide.keySet()) { eval.setVariable(c, anotherSide.get(c)); } SolveTask task = new SolveTask(this, realMinX, realMaxX); // Don't use AsyncTask.get() to retrieve result, it will block main UI task.setOnResultListener(new SolveTask.OnResultListener() { @Override public void onResult(Double result) { if (result != null) { Intent resultData = new Intent(); resultData.putExtra("LAST_RESULT", result); PlotActivity.this.setResult(Activity.RESULT_OK, resultData); } } }); task.execute(new FunctionWrapper.MathFunction() { @Override public double call(double x) { eval.setVariable('x', x); return eval.evaluate(' ').getValue(); } }); } private void updatePlotBound() { double realMinX = getRealMinX(); double realMaxX = getRealMaxX(); textLowerBound.setValue(realMinX); textUpperBound.setValue(realMaxX); mainSeries.setBound(minX, maxX); plot.setDomainBoundaries(minX, maxX, BoundaryMode.FIXED); nZero = mainSeries.getNZero(); plot.setRangeBoundaries(-maxAbsY, maxAbsY, BoundaryMode.FIXED); int color_id = R.color.colorPermission; if (mainSeries.isAllInvalid() || nZero != 1) { color_id = R.color.colorProhibition; } int color = ContextCompat.getColor(plot.getContext(), color_id); plot.getGraphWidget().getGridBackgroundPaint().setColor(color); plot.redraw(); } private static final int NONE = 0; private static final int ONE_FINGER_DRAG = 1; private static final int TWO_FINGERS_DRAG = 2; private int mode = NONE; private PointF firstFinger; private double distBetweenFingers; @Override public boolean onTouch(View arg0, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // Start gesture firstFinger = new PointF(event.getX(), event.getY()); mode = ONE_FINGER_DRAG; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_POINTER_DOWN: // second finger distBetweenFingers = spacing(event); // the distance check is done to avoid false alarms if (distBetweenFingers > 5f) { mode = TWO_FINGERS_DRAG; } break; case MotionEvent.ACTION_MOVE: if (mode == ONE_FINGER_DRAG) { PointF oldFirstFinger = firstFinger; firstFinger = new PointF(event.getX(), event.getY()); scroll(oldFirstFinger.x - firstFinger.x); } else if (mode == TWO_FINGERS_DRAG) { double oldDist = distBetweenFingers; distBetweenFingers = spacing(event); if (onDirectionX(event)) { zoom(oldDist / distBetweenFingers); } else { maxAbsY *= oldDist / distBetweenFingers; } } updatePlotBound(); break; } return true; } private void resetY() { mainSeries.setBound(minX, maxX); if (mainSeries.isAllInvalid()) { maxAbsY = 1.0; } else { maxAbsY = Math.max(Math.abs(mainSeries.getMaxY()), Math.abs(mainSeries.getMinY())); maxAbsY *= SCALE_YAXIS; } } private void zoom(double scale) { double domainSpan = maxX - minX; double domainMidPoint = maxX - domainSpan / 2.0f; double offset = domainSpan * scale / 2.0f; double min = domainMidPoint - offset; double max = domainMidPoint + offset; min = Math.min(min, mainSeries.getX(mainSeries.size() - 1).doubleValue()); max = Math.max(max, mainSeries.getX(0).doubleValue()); double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min; double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max; if (min < max && isNormal(realMinX) && isNormal(realMaxX)) { minX = min; maxX = max; } } private void scroll(double pan) { double domainSpan = maxX - minX; double step = domainSpan / plot.getWidth(); double offset = pan * step; double min = minX + offset; double max = maxX + offset; double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min; double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max; if (min < max && isNormal(realMinX) && isNormal(realMaxX)) { minX = min; maxX = max; } } private double spacing(MotionEvent event) { double x = event.getX(0) - event.getX(1); double y = event.getY(0) - event.getY(1); return Math.hypot(x, y); } private boolean onDirectionX(MotionEvent event) { double x = event.getX(0) - event.getX(1); double y = event.getY(0) - event.getY(1); return Math.abs(y) < Math.abs(x); } private static double logScale(double val) { return Math.log(val); } private static double logScaleRecover(double val) { return Math.exp(val); } private double getRealMinX() { return checkXLogScale.isChecked() ? logScaleRecover(minX) : minX; } private double getRealMaxX() { return checkXLogScale.isChecked() ? logScaleRecover(maxX) : maxX; } private boolean isNormal(double n) { return !(Double.isInfinite(n) || Double.isNaN(n)); } }
package org.copinf.cc.model; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; /** * Provides a base class for board representation. */ public abstract class AbstractBoard { /** * Gets a square at specified coordinates. * @param coordinates the square's location * @return the square */ public abstract Square getSquare(final Coordinates coordinates); /** * Gets a pawn at specified coordinates. * @param coordinates the pawn's location * @return the pawn */ public Pawn getPawn(final Coordinates coordinates) { final Square square = getSquare(coordinates); if (square == null) { throw new RuntimeException("Square at " + coordinates + " is outside of the board."); } return square.getPawn(); } /** * Sets a pawn at specified coordinates. * @param pawn the pawn * @param coordinates the pawn's location */ public void setPawn(final Pawn pawn, final Coordinates coordinates) { getSquare(coordinates).setPawn(pawn); } /** * Moves a pawn from a square to another square, referenced by their coordinates. * This method does not perform any checks on the movement validity. * @param orig the origin coordinates * @param dest the destination coordinates */ public void move(final Movement movement) { getSquare(movement.getDestination()).setPawn(getSquare(movement.getOrigin()).popPawn()); } /** * Checks if a movement is valid. A movement is represented by a list of coordinates representing * the sequence of jumps performed. This method returns false if at any point in the coordinates * list a movement is invalid. It returns true if the whole movement is valid. * @param path list of movements * @param player player performing the movements * @return true if the whole movement is valid. * @throws NullPointerException if the parameters are null or if the Coordinates list contains a * null */ public boolean checkMove(final Movement path, final Player player) { if (path.size() < 2) { return false; } Coordinates orig = path.getOrigin(); final Pawn pawn = getPawn(orig); if (pawn == null || pawn.getOwner() != player) { return false; } Coordinates dest = path.getDestination(); if (path.size() == 2) { if (orig.isAdjacentTo(dest)) { return getSquare(dest).isFree(); } Coordinates middle = orig.getMiddleCoordinates(dest); return middle != null && !getSquare(middle).isFree() && getSquare(dest).isFree(); } Coordinates middle; for (final Iterator<Coordinates> it = path.subList(1, path.size()).iterator(); it.hasNext();) { dest = it.next(); if (orig.isAdjacentTo(dest)) { return false; } middle = orig.getMiddleCoordinates(dest); if (middle == null || getSquare(middle).isFree()) { return false; } orig = dest; } return true; } /** * Gets this board width. * @return board width */ public abstract int getWidth(); /** * Gets this board height. * @return board height */ public abstract int getHeight(); /** * Gets the list of BoardZone of this board. * @return list of BoardZone */ public abstract List<BoardZone> getZones(); /** * Gets the set of Coordinates pointing to the Squares of this board. * @return set of Coordinates */ public abstract Set<Coordinates> coordinates(); /** * Assigns to each player a zone on the board, taking in account the teams. * @param teams the set of teams. * @param numberOfZones the number of zones per player */ public abstract void dispatchZones(final Set<Team> teams, final int numberOfZones); /** * Gets the possible number of players on the board. * @return an ascending sorted set of the possible player numbers. */ public abstract SortedSet<Integer> getPossiblePlayerNumbers(); /** * Gets the possible number of zones per player. * @param playerNumber The number of players. * @return an ascending sorted set of the possible zones numbers per player. */ public abstract SortedSet<Integer> getPossibleZoneNumbers(final int playerNumber); }
package me.devsaki.hentoid.util; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import timber.log.Timber; public final class Preferences { private static final int VERSION = 4; private static SharedPreferences sharedPreferences; public static void init(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); int savedVersion = sharedPreferences.getInt(Key.PREFS_VERSION_KEY, VERSION); if (savedVersion != VERSION) { Timber.d("Shared Prefs Key Mismatch! Clearing Prefs!"); sharedPreferences.edit() .clear() .apply(); } } public static boolean isFirstRunProcessComplete() { return sharedPreferences.getBoolean(Key.PREF_WELCOME_DONE, false); } public static void setIsFirstRunProcessComplete(boolean isFirstRunProcessComplete) { sharedPreferences.edit() .putBoolean(Key.PREF_WELCOME_DONE, isFirstRunProcessComplete) .apply(); } public static boolean isAnalyticsDisabled() { return sharedPreferences.getBoolean(Key.PREF_ANALYTICS_TRACKING, false); } public static boolean isFirstRun() { return sharedPreferences.getBoolean(Key.PREF_FIRST_RUN, Default.PREF_FIRST_RUN_DEFAULT); } public static void setIsFirstRun(boolean isFirstRun) { sharedPreferences.edit() .putBoolean(Key.PREF_FIRST_RUN, isFirstRun) .apply(); } public static int getContentSortOrder() { return sharedPreferences.getInt(Key.PREF_ORDER_CONTENT_LISTS, Default.PREF_ORDER_CONTENT_DEFAULT); } public static void setContentSortOrder(int sortOrder) { sharedPreferences.edit() .putInt(Key.PREF_ORDER_CONTENT_LISTS, sortOrder) .apply(); } public static int getContentPageQuantity() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_QUANTITY_PER_PAGE_LISTS, Default.PREF_QUANTITY_PER_PAGE_DEFAULT + "")); } public static String getAppLockPin() { return sharedPreferences.getString(Key.PREF_APP_LOCK, ""); } public static void setAppLockPin(String pin) { sharedPreferences.edit() .putString(Key.PREF_APP_LOCK, pin) .apply(); } public static boolean getAppLockVibrate() { return sharedPreferences.getBoolean(Key.PREF_APP_LOCK_VIBRATE, Default.PREF_APP_LOCK_VIBRATE_DEFAULT); } public static boolean getEndlessScroll() { return sharedPreferences.getBoolean(Key.PREF_ENDLESS_SCROLL, Default.PREF_ENDLESS_SCROLL_DEFAULT); } public static boolean getRecentVisibility() { return sharedPreferences.getBoolean(Key.PREF_HIDE_RECENT, Default.PREF_HIDE_RECENT_DEFAULT); } public static String getSdStorageUri() { return sharedPreferences.getString(Key.PREF_SD_STORAGE_URI, null); } public static void setSdStorageUri(String uri) { sharedPreferences.edit() .putString(Key.PREF_SD_STORAGE_URI, uri) .apply(); } public static int getFolderNameFormat() { return Integer.parseInt( sharedPreferences.getString(Key.PREF_FOLDER_NAMING_CONTENT_LISTS, Default.PREF_FOLDER_NAMING_CONTENT_DEFAULT + "")); } public static String getRootFolderName() { return sharedPreferences.getString(Key.PREF_SETTINGS_FOLDER, ""); } public static boolean setRootFolderName(String rootFolderName) { return sharedPreferences.edit() .putString(Key.PREF_SETTINGS_FOLDER, rootFolderName) .commit(); } public static int getContentReadAction() { return Integer.parseInt( sharedPreferences.getString(Key.PREF_READ_CONTENT_LISTS, Default.PREF_READ_CONTENT_ACTION + "")); } public static boolean getMobileUpdate() { return sharedPreferences.getBoolean(Key.PREF_CHECK_UPDATES_LISTS, Default.PREF_CHECK_UPDATES_DEFAULT); } public static int getWebViewInitialZoom() { return Integer.parseInt( sharedPreferences.getString( Key.PREF_WEBVIEW_INITIAL_ZOOM_LISTS, Default.PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT + "")); } public static boolean getWebViewOverview() { return sharedPreferences.getBoolean( Key.PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS, Default.PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT); } public static final class Key { public static final String PREF_APP_LOCK = "pref_app_lock"; public static final String PREF_HIDE_RECENT = "pref_hide_recent"; public static final String PREF_ADD_NO_MEDIA_FILE = "pref_add_no_media_file"; public static final String PREF_CHECK_UPDATE_MANUAL = "pref_check_updates_manual"; public static final String PREF_ANALYTICS_TRACKING = "pref_analytics_tracking"; static final String PREF_WELCOME_DONE = "pref_welcome_done"; static final String PREFS_VERSION_KEY = "prefs_version"; static final String PREF_QUANTITY_PER_PAGE_LISTS = "pref_quantity_per_page_lists"; static final String PREF_ORDER_CONTENT_LISTS = "pref_order_content_lists"; static final String PREF_FIRST_RUN = "pref_first_run"; static final String PREF_APP_LOCK_VIBRATE = "pref_app_lock_vibrate"; static final String PREF_ENDLESS_SCROLL = "pref_endless_scroll"; static final String PREF_SD_STORAGE_URI = "pref_sd_storage_uri"; static final String PREF_FOLDER_NAMING_CONTENT_LISTS = "pref_folder_naming_content_lists"; static final String PREF_SETTINGS_FOLDER = "folder"; static final String PREF_READ_CONTENT_LISTS = "pref_read_content_lists"; static final String PREF_CHECK_UPDATES_LISTS = "pref_check_updates_lists"; static final String PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS = "pref_webview_override_overview_lists"; static final String PREF_WEBVIEW_INITIAL_ZOOM_LISTS = "pref_webview_initial_zoom_lists"; } public static final class Default { public static final int PREF_QUANTITY_PER_PAGE_DEFAULT = 20; public static final int PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT = 20; static final int PREF_ORDER_CONTENT_DEFAULT = Constant.PREF_ORDER_CONTENT_ALPHABETIC; static final boolean PREF_FIRST_RUN_DEFAULT = true; static final boolean PREF_APP_LOCK_VIBRATE_DEFAULT = true; static final boolean PREF_ENDLESS_SCROLL_DEFAULT = true; static final boolean PREF_HIDE_RECENT_DEFAULT = true; static final int PREF_FOLDER_NAMING_CONTENT_DEFAULT = Constant.PREF_FOLDER_NAMING_CONTENT_ID; static final int PREF_READ_CONTENT_ACTION = Constant.PREF_READ_CONTENT_DEFAULT; static final boolean PREF_CHECK_UPDATES_DEFAULT = true; static final boolean PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT = false; } public static final class Constant { public static final int PREF_ORDER_CONTENT_ALPHABETIC = 0; public static final int PREF_ORDER_CONTENT_BY_DATE = 1; static final int PREF_FOLDER_NAMING_CONTENT_ID = 0; static final int PREF_FOLDER_NAMING_CONTENT_TITLE_ID = 1; static final int PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID = 2; static final int PREF_READ_CONTENT_DEFAULT = 0; static final int PREF_READ_CONTENT_PERFECT_VIEWER = 1; } }
package org.ict4h.forms.data; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import java.io.StringReader; public class EnketoResult { private String transform; public EnketoResult(String transform) { this.transform = transform; } public String getForm() throws DocumentException { if (!hasResult()) return ""; org.dom4j.Document document = new SAXReader().read(new StringReader(transform)); return document.getRootElement().element("form").asXML(); } public String getModel() throws DocumentException { if (!hasResult()) return ""; org.dom4j.Document document = new SAXReader().read(new StringReader(transform)); return document.getRootElement().element("model").asXML(); } private boolean hasResult() { return transform != null && !transform.isEmpty(); } }
package org.sil.bloom.reader; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.WebView; import android.widget.ImageView; import android.widget.Toast; import com.segment.analytics.Analytics; import com.segment.analytics.Properties; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReaderActivity extends BaseActivity { private static final String TAG = "ReaderActivity"; private static final String sAssetsStylesheetLink = "<link rel=\"stylesheet\" href=\"file:///android_asset/book support files/assets.css\" type=\"text/css\"></link>"; private static final String sAssetsBloomPlayerScript = "<script type=\"text/javascript\" src=\"file:///android_asset/book support files/bloomPagePlayer.js\"></script>"; private static final Pattern sLayoutPattern = Pattern.compile("\\S+([P|p]ortrait|[L|l]andscape)\\b"); private static final Pattern sHeadElementEndPattern = Pattern.compile("</head"); private static final Pattern sMainLanguage = Pattern.compile("<div data-book=\"contentLanguage1\"[^>]*>\\s*(\\S*)"); // Matches a div with class bloom-page, that is, the start of the main content of one page. // (We're looking for the start of a div tag, then before finding the end wedge, we find // class<maybe space>=<maybe space><some sort of quote> and then bloom-page before we find // another quote. // Bizarre mismatches are possible...like finding the other sort of quote inside the class // value, or finding class='bloom-page' inside the value of some other attribute. But I think // it's good enough.) private static final Pattern sPagePattern = Pattern.compile("<div\\s+[^>]*class\\s*=\\s*['\"][^'\"]*bloom-page"); // For searching in a page string to see whether it's a back-matter page. Looks for bloom-backmatter // in a class attribute in the first opening tag. private static final Pattern sBackPagePattern = Pattern.compile("[^>]*class\\s*=\\s*['\"][^'\"]*bloom-backMatter"); // Matches a page div with the class numberedPage...that string must occur in a class attribute before the // close of the div element. private static final Pattern sNumberedPagePattern = Pattern.compile("[^>]*?class\\s*=\\s*['\"][^'\"]*numberedPage"); private static final Pattern sBackgroundAudio = Pattern.compile("[^>]*?data-backgroundaudio\\s*=\\s*['\"]([^'\"]*)?['\"]"); private static final Pattern sBackgroundVolume = Pattern.compile("[^>]*?data-backgroundaudiovolume\\s*=\\s*['\"]([^'\"]*)?['\"]"); private static final Pattern sClassAttrPattern = Pattern.compile("class\\s*=\\s*(['\"])(.*?)\\1"); private static final Pattern sContentLangDiv = Pattern.compile("<div [^>]*?data-book=\"contentLanguage1\"[^>]*?>\\s*(\\S+)"); private static final Pattern sBodyPattern = Pattern.compile("<body [^>]*?>"); private static final Pattern sAutoAdvance = Pattern.compile("data-bfautoadvance\\s*?=\\s*?\"[^\"]*?\\bbloomReader\\b.*?\""); private ViewPager mPager; private BookPagerAdapter mAdapter; private String mBookName ="?"; private int mAudioPagesPlayed = 0; private int mNonAudioPagesShown = 0; private int mLastNumberedPageIndex = -1; private int mNumberedPageCount = 0; private boolean mLastNumberedPageRead = false; private boolean mAutoAdvance = false; // automatically advance to next page at end of narration private boolean mPlayMusic = true; // play background music if present private int mOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; private boolean mPlayAnimation = true; // play animations (pan and zoom) if present. private String mContentLang1 = "unknown"; private String mBodyTag; int mFirstQuestionPage; int mCountQuestionPages; ScaledWebView mCurrentView; String[] mBackgroundAudioFiles; float[] mBackgroundAudioVolumes; // Keeps track of whether we switched pages while audio paused. If so, we don't resume // the audio of the previously visible page, but start this page from the beginning. boolean mSwitchedPagesWhilePaused = false; // These variables support a minimum time on each page before we automatically switch to // the next (if the audio on this page is short or non-existent). private long mTimeLastPageSwitch; private Timer mNextPageTimer; private boolean mIsMultiMediaBook; private boolean mRTLBook; private String mBrandingProjectName; private String mFailedToLoadBookMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); setContentView(R.layout.activity_reader); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); mBrandingProjectName = getIntent().getStringExtra("brandingProjectName"); new Loader().execute(); } @Override protected void onPause() { if (isFinishing()) { ReportPagesRead(); } super.onPause(); WebAppInterface.stopAllAudio(); } @Override protected void onResume(){ super.onResume(); hideSystemUI(); } // Enable "sticky immersive" mode. private void hideSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( // We don't want the System to grab swipes from the edge View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } // Shows the system bars by removing all the flags // except the ones that make the content appear under the system bars. // This would be the time to make other controls available too. private void showSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN ); } private boolean isSystemUIShowing() { View decorView = getWindow().getDecorView(); return (decorView.getSystemUiVisibility() & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0; } private void ReportPagesRead() { try { // let's differentiate between pages read and audio book pages read: (BL-5082) Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("audioPages", mAudioPagesPlayed); p.putValue("nonAudioPages", mNonAudioPagesShown); p.putValue("totalNumberedPages", mNumberedPageCount); p.putValue("lastNumberedPageRead", mLastNumberedPageRead); p.putValue("questionCount", mAdapter.mQuiz.numberOfQuestions()); p.putValue("contentLang", mContentLang1); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("Pages Read", p); } catch (Exception e) { Log.e(TAG, "Pages Read", e); // I doubt this message will help the user, and will probably just be confusing when it // comes up because a book failed to open in the first place. // BloomReaderApplication.VerboseToast("Error reporting Pages Read"); } } // class to run loadBook in the background (so the UI thread is available to animate the progress bar) private class Loader extends AsyncTask<Void, Integer, String> { @Override protected String doInBackground(Void... v) { final String path = getIntent().getStringExtra("bookPath"); BloomFileReader fileReader = new BloomFileReader(getApplicationContext(), path); String bookDirectory; try { final File bookHtmlFile = fileReader.getHtmlFile(); bookDirectory = bookHtmlFile.getParent(); String html = IOUtilities.FileToString(bookHtmlFile); mIsMultiMediaBook = isMultiMediaBook(html); WebAppInterface.resetAll(); // Break the html into everything before the first page, a sequence of pages, // and the bit after the last. Note: assumes there is nothing but the </body> after // the last page, that is, that pages are the direct children of <body> and // nothing follows the last page. final Matcher matcher = sPagePattern.matcher(html); String startFrame = ""; String endFrame = ""; ArrayList<String> pages = new ArrayList<String>(); // if we don't find even one start of page, we have no pages, and don't need startFrame, endFrame, etc. if (matcher.find()) { int firstPageIndex = matcher.start(); startFrame = html.substring(0, firstPageIndex); Matcher match = sContentLangDiv.matcher(startFrame); if (match.find()) { mContentLang1 = match.group(1); } startFrame = addAssetsStylesheetLink(startFrame); int startPage = firstPageIndex; while (matcher.find()) { final String pageContent = html.substring(startPage, matcher.start()); AddPage(pages, pageContent); startPage = matcher.start(); } mFirstQuestionPage = pages.size(); for (; mFirstQuestionPage > 0; mFirstQuestionPage String pageContent = pages.get(mFirstQuestionPage-1); if (!sBackPagePattern.matcher(pageContent).find()) { break; } } int endBody = html.indexOf("</body>", startPage); AddPage(pages, html.substring(startPage, endBody)); // We can leave out the bloom player JS altogether if not needed. endFrame = (mIsMultiMediaBook ? sAssetsBloomPlayerScript : "") + html.substring(endBody, html.length()); } boolean hasEnterpriseBranding = mBrandingProjectName != null && !mBrandingProjectName.toLowerCase(Locale.ENGLISH).equals("default"); Quiz quiz = new Quiz(); if (hasEnterpriseBranding) { String primaryLanguage = getPrimaryLanguage(html); quiz = Quiz.readQuizFromFile(fileReader, primaryLanguage); mCountQuestionPages = quiz.numberOfQuestions(); for (int i = 0; i < mCountQuestionPages; i++) { // insert all these pages just before the final 'end' page. pages.add(mFirstQuestionPage, "Q"); } } mBackgroundAudioFiles = new String[pages.size()]; mBackgroundAudioVolumes = new float[pages.size()]; String currentBackgroundAudio = ""; float currentVolume = 1.0f; for (int i = 0; i < pages.size(); i++) { if (pages.get(i) == "Q") { mBackgroundAudioFiles[i] = ""; currentBackgroundAudio = ""; continue; } Matcher bgMatcher =sBackgroundAudio.matcher(pages.get(i)); if (bgMatcher.find()) { currentBackgroundAudio = bgMatcher.group(1); if (currentBackgroundAudio == null) // may never happen? currentBackgroundAudio = ""; // Getting a new background file implies full volume unless specified. currentVolume = 1.0f; } Matcher bgvMatcher =sBackgroundVolume.matcher(pages.get(i)); if (bgvMatcher.find()) { try { currentVolume = Float.parseFloat(bgvMatcher.group(1)); } catch (NumberFormatException e) { e.printStackTrace(); } } mBackgroundAudioFiles[i] = currentBackgroundAudio; mBackgroundAudioVolumes[i] = currentVolume; } mRTLBook = fileReader.getBooleanMetaProperty("isRtl", false); // The body tag captured here is parsed in setFeatureEffects after we know our orientation. Matcher bodyMatcher = sBodyPattern.matcher(startFrame); if (bodyMatcher.find()){ mBodyTag = bodyMatcher.group(0); } else { mBodyTag = "<body>"; // a trivial default, saves messing with nulls. } mAdapter = new BookPagerAdapter(pages, quiz, ReaderActivity.this, bookHtmlFile, startFrame, endFrame); reportLoadBook(path); } catch (IOException ex) { Log.e("Reader", "Error loading " + path + " " + ex); mFailedToLoadBookMessage = (ex.getMessage() != null && ex.getMessage().contains("ENOSPC")) ? getString(R.string.device_storage_is_full) : getString(R.string.failed_to_open_book); return null; } return bookDirectory; } @Override protected void onPostExecute(String bookDirectory){ if(bookDirectory == null){ if(mFailedToLoadBookMessage != null) Toast.makeText(ReaderActivity.this, mFailedToLoadBookMessage, Toast.LENGTH_LONG).show(); finish(); return; } final String audioDirectoryPath = bookDirectory + "/audio/"; mPager = (ViewPager) findViewById(R.id.book_pager); if(mRTLBook) mPager.setRotationY(180); mPager.setAdapter(mAdapter); final BloomPageChangeListener listener = new BloomPageChangeListener(audioDirectoryPath); mPager.addOnPageChangeListener(listener); // Now we're ready to display the book, so hide the 'progress bar' (spinning circle) findViewById(R.id.loadingPanel).setVisibility(View.GONE); // A design flaw in the ViewPager is that its onPageSelected method does not // get called for the page that is initially displayed. But we want to do all the // same things to the first page as the others. So we will call it // manually. Using post delays this until everything is initialized and the view // starts to process events. I'm not entirely sure why this should be done; // I copied this from something on StackOverflow. Probably it means that the // first-page call happens in a more similar situation to the change-page calls. // It might work to just call it immediately. mPager.post(new Runnable() { @Override public void run() { listener.onPageSelected(mPager.getCurrentItem()); } }); } } private boolean isMultiMediaBook(String html) { String htmlNoSpaces = html.replace(" ", ""); return sAutoAdvance.matcher(html).find() || // This is a fairly crude search, we really want the doc to have spans with class // audio-sentence; but I think it's a sufficiently unlikely string to find elsewhere // that this is good enough. And actually the crudeness of the search allows it to find // audio recorded "by box" as well as by sentence. But now we need to detect video and // Ken Burns style animation too. // I (gjm) tried just asking the javascript (BloomPlayer) if the book is multimedia, // but I had trouble getting the context right on this end for a call that would work. html.contains("audio-sentence") || htmlNoSpaces.contains("src=\"video") || htmlNoSpaces.contains("data-initialrect="); } private class BloomPageChangeListener extends ViewPager.SimpleOnPageChangeListener { String audioDirectoryPath; BloomPageChangeListener(String audioDirectoryPath){ this.audioDirectoryPath = audioDirectoryPath; } @Override public void onPageSelected(int position) { Log.d("Reader", "onPageSelected("+position+")"); super.onPageSelected(position); clearNextPageTimer(); // in case user manually moved to a new page while waiting WebView oldView = mCurrentView; mCurrentView = mAdapter.getActiveView(position); mTimeLastPageSwitch = System.currentTimeMillis(); if (oldView != null) oldView.clearCache(false); // Fix for BL-5555 hideSystemUI(); if (mIsMultiMediaBook) { mSwitchedPagesWhilePaused = WebAppInterface.isMediaPaused(); stopVideos(oldView); WebAppInterface.stopNarration(); // don't want to hear rest of anything on another page String backgroundAudioPath = ""; if (mPlayMusic) { if (mBackgroundAudioFiles[position].length() > 0) { backgroundAudioPath = audioDirectoryPath + mBackgroundAudioFiles[position]; } WebAppInterface.SetBackgroundAudio(backgroundAudioPath, mBackgroundAudioVolumes[position]); } // This new page may not be in the correct paused state. // (a) maybe we paused this page, moved to another, started narration, moved // back to this (adapter decided to reuse it), this one needs to not be paused. // (b) maybe we moved to another page while not paused, paused there, moved // back to this one (again, reused) and old animation is still running if (mCurrentView != null && mCurrentView.getWebAppInterface() != null) { WebAppInterface appInterface = mCurrentView.getWebAppInterface(); appInterface.initializeCurrentPage(); if (!WebAppInterface.isMediaPaused()) { appInterface.enableAnimation(mPlayAnimation); // startNarration also starts the animation (both handled by the BloomPlayer // code) iff we passed true to enableAnimation(). mAdapter.startNarrationForPage(position); // Note: this isn't super-reliable. We tried to narrate this page, but it may not // have any audio. All we know is that it's part of a book which has // audio (or animation) somewhere, and we tried to play any audio it has. mAudioPagesPlayed++; } else { mNonAudioPagesShown++; } } } else { // Switching to a new page in a non-multimedia book mNonAudioPagesShown++; } if (position == mLastNumberedPageIndex) mLastNumberedPageRead = true; } }; // Minimum time a page must be visible before we automatically switch to the next // (if playing audio...usually this only affects pages with no audio) final int MIN_PAGE_SWITCH_MILLIS = 3000; // This is the routine that is invoked as a result of a call-back from javascript indicating // that the current page is complete (which in turn typically follows a notification from // Java that a sound finished playing...but it is the JS that knows it is the last audio // on the page). Basically it is responsible for flipping to the next page (see goToNextPageNow). // But, we get the notification instantly if there is NO audio on the page. // So we do complicated things with a timer to make sure we don't flip the page too soon... // the minimum delay is specified in MIN_PAGE_SWITCH_MILLIS. public void pageAudioCompleted() { if (!mAutoAdvance) return; clearNextPageTimer(); long millisSinceLastSwitch = System.currentTimeMillis() - mTimeLastPageSwitch; if (millisSinceLastSwitch >= MIN_PAGE_SWITCH_MILLIS) { goToNextPageNow(); return; } // If nothing else happens, we will go to next page when the minimum time has elapsed. // Unfortunately, the only way to stop scheduled events in a Java timer is to destroy it. // So that's what clearNextPageTimer() does (e.g., if the user manually changes pages). // Consequently, we have to make a new one each time. synchronized (this) { mNextPageTimer = new Timer(); mNextPageTimer.schedule(new TimerTask() { @Override public void run() { goToNextPageNow(); } }, MIN_PAGE_SWITCH_MILLIS - millisSinceLastSwitch); } } void clearNextPageTimer() { synchronized (this) { if (mNextPageTimer == null) return; mNextPageTimer.cancel(); mNextPageTimer = null; } } private void goToNextPageNow() { clearNextPageTimer(); runOnUiThread(new Runnable() { @Override public void run() { // In case some race condition has this getting called while we are paused, // don't let it happen. if (WebAppInterface.isMediaPaused()) { return; } int current = mPager.getCurrentItem(); if (current < mAdapter.getCount() - 1) { mPager.setCurrentItem(current + 1); } } } ); } public int indexOfCurrentPage() { return mPager.getCurrentItem(); } public void mediaPausedChanged() { final ImageView view = (ImageView)findViewById(R.id.playPause); if (WebAppInterface.isMediaPaused()) { clearNextPageTimer(); // any pending automatic page flip should be prevented. view.setImageResource(R.drawable.pause_on_circle); // black circle around android.R.drawable.ic_media_pause); } else { view.setImageResource(R.drawable.play_on_circle); if(mSwitchedPagesWhilePaused) { final int position = mPager.getCurrentItem(); mAdapter.startNarrationForPage(position); // also starts animation if any } } mSwitchedPagesWhilePaused = false; final Animation anim = AnimationUtils.loadAnimation(this, R.anim.grow_and_fade); // Make the view hidden when the animation finishes. Otherwise it returns to full visibility. anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { // required method for abstract class } @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { // required method for abstract class } }); view.setVisibility(View.VISIBLE); view.startAnimation(anim); } @Override protected void onNewOrUpdatedBook(String fullPath) { ((BloomReaderApplication)this.getApplication()).setBookToHighlight(fullPath); Intent intent = new Intent(this, MainActivity.class); // Clears the history so now the back button doesn't take from the main activity back to here. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } private void reportLoadBook(String path) { try { String filenameWithExtension = new File(path).getName(); // this mBookName is used by subsequent analytics reports mBookName = filenameWithExtension.substring(0, filenameWithExtension.length() - IOUtilities.BOOK_FILE_EXTENSION.length()); Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("totalNumberedPages", mNumberedPageCount); p.putValue("contentLang", mContentLang1); p.putValue("questionCount", mAdapter.mQuiz.numberOfQuestions()); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("BookOrShelf opened", p); } catch (Exception error) { Log.e("Reader", "Error reporting load of " + path + ". "+ error); BloomReaderApplication.VerboseToast("Error reporting load of "+path); } } // Given something like <body data-bfplaymusic="landscape;bloomReader"> for bodyTag // and a request to find the playmusic feature, returns landscape. // defValue is returned if // - the relevant attribute is not found // - bloomReader does not occur in the value (after the semi-colon) private String getFeatureValue(String featureName, String defValue) { final Pattern featurePattern = Pattern.compile("data-bf" + featureName + "\\s*=\\s*['\"]([^'\"]*?);([^'\"]*?)bloomReader"); Matcher matcher = featurePattern.matcher(mBodyTag); if (!matcher.find()) { return defValue; } return matcher.group(1); } private boolean getBooleanFeature(String featureName, boolean defValue, boolean inLandscape) { String rawValue = getFeatureValue(featureName, defValue ? "allOrientations" : "never"); if (rawValue.equals("allOrientations")) return true; if (inLandscape && rawValue.equals("landscape")) return true; if (!inLandscape && rawValue.equals("portrait")) return true; return false; } private void setFeatureEffects(boolean inLandscape) { mAutoAdvance = getBooleanFeature("autoadvance", false, inLandscape); mPlayMusic = getBooleanFeature("playmusic", true, inLandscape); mPlayAnimation = getBooleanFeature("playanimations", true, inLandscape); } private void stopVideos(WebView webView){ if(webView != null) { WebAppInterface waInterface = ((ScaledWebView)webView).getWebAppInterface(); waInterface.stopVideo(webView); } } private void AddPage(ArrayList<String> pages, String pageContent) { pages.add(pageContent); if (sNumberedPagePattern.matcher(pageContent).find()) { mLastNumberedPageIndex = pages.size() - 1; mNumberedPageCount++; } } private String getPrimaryLanguage(String html) { Matcher matcher = sMainLanguage.matcher(html); if (!matcher.find()) return "en"; return matcher.group(1); } private String addAssetsStylesheetLink(String htmlSnippet) { final Matcher matcher = sHeadElementEndPattern.matcher(htmlSnippet); if (matcher.find()) { return htmlSnippet.substring(0, matcher.start()) + sAssetsStylesheetLink + htmlSnippet.substring(matcher.start()); } return htmlSnippet; } // Prefer to base device landscape on mOrientation if it's determinative private boolean isDeviceInLandscape() { switch (mOrientation) { case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE: return true; case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT: return false; case ActivityInfo.SCREEN_ORIENTATION_SENSOR: default: return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } } private int getPageOrientationAndRotateScreen(String page){ // default: fixed in portrait mode mOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; Matcher matcher = sClassAttrPattern.matcher(page); if (matcher.find()) { String classNames = matcher.group(2); if (classNames.contains("Landscape")) mOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; // fixed landscape } if (getFeatureValue("canrotate", "never").equals("allOrientations")) mOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR; // change as rotated setRequestedOrientation(mOrientation); return mOrientation; } // Transforms [x]Portrait or [x]Landscape class to Device16x9Portrait / Device16x9Landscape private String pageUsingDeviceLayout(String page) { // Get the content of the class attribute and its position Matcher matcher = sClassAttrPattern.matcher(page); if (!matcher.find()) return page; // don't think this can happen, we create pages by finding class attr. int start = matcher.start(2); int end = matcher.end(2); String classNames = matcher.group(2); String replacementClass = "Device16x9$1"; String newClassNames = sLayoutPattern.matcher(classNames).replaceFirst(replacementClass); return page.substring(0,start) // everything up to the opening quote in class=" + newClassNames + page.substring(end, page.length()); // because this includes the original closing quote from class attr } private int getPageScale(int viewWidth, int viewHeight){ // 378 x 674 are the dimensions of the Device16x9 layouts in pixels int longSide = (viewWidth > viewHeight) ? viewWidth : viewHeight; int shortSide = (viewWidth > viewHeight) ? viewHeight : viewWidth; Double longScale = new Double(longSide / new Double(674)); Double shortScale = new Double(shortSide / new Double(378)); Double scale = Math.min(longScale, shortScale); scale = scale * 100d; return scale.intValue(); } enum pageAnswerState { unanswered, firstTimeCorrect, secondTimeCorrect, wrongOnce, wrong } // Class that provides individual page views as needed. // possible enhancement: can we reuse the same browser, just change which page is visible? private class BookPagerAdapter extends PagerAdapter implements QuestionAnsweredHandler { // Each item is the full HTML text of one page div (div with class bloom-page). // the concatenation of mHtmlBeforeFirstPageDiv, mHtmlPageDivs, and mHtmlAfterLastPageDiv // is the whole book HTML file. (The code here assumes there is nothing in the body // of the document except page divs.) // The concatenation of mHtmlBeforeFirstPageDiv, one item from mHtmlPageDivs, and // mHtmlAfterLastPageDiv is the content we put in a browser representing a single page. private List<String> mHtmlPageDivs; Quiz mQuiz; pageAnswerState[] mAnswerStates; boolean mQuestionAnalyticsSent; private String mHtmlBeforeFirstPageDiv; private String mHtmlAfterLastPageDiv; ReaderActivity mParent; File mBookHtmlPath; int mLastPageIndex; int mThisPageIndex; // This map allows us to convert from the page index we get from the ViewPager to // the actual child WebView on that page. There ought to be a way to get the actual // current child control from the ViewPager, but I haven't found it yet. // Note that it only tracks WebViews for items that have been instantiated and not // yet destroyed; this is important to allow others to be garbage-collected. private HashMap<Integer, ScaledWebView> mActiveViews = new HashMap<Integer, ScaledWebView>(); BookPagerAdapter(List<String> htmlPageDivs, Quiz quiz, ReaderActivity parent, File bookHtmlPath, String htmlBeforeFirstPageDiv, String htmlAfterLastPageDiv) { mHtmlPageDivs = htmlPageDivs; mQuiz = quiz; mAnswerStates = new pageAnswerState[mQuiz.numberOfQuestions()]; for (int i = 0; i < mAnswerStates.length; i++) { mAnswerStates[i] = pageAnswerState.unanswered; } mParent = parent; mBookHtmlPath = bookHtmlPath; mHtmlBeforeFirstPageDiv = htmlBeforeFirstPageDiv; mHtmlAfterLastPageDiv = htmlAfterLastPageDiv; } @Override public void destroyItem(ViewGroup collection, int position, Object view) { Log.d("Reader", "destroyItem " + position); collection.removeView((View) view); mActiveViews.remove(position); } @Override public int getCount() { //Log.d("Reader", "getCount = "+ mHtmlPageDivs.size()); return mHtmlPageDivs.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { Log.d("Reader", "instantiateItem " + position); assert(container.getChildCount() == 0); String page = mHtmlPageDivs.get(position); View pageView; if (page.startsWith("<")) { // normal content page pageView = MakeBrowserForPage(position); } else { final int questionIndex = position - mFirstQuestionPage; QuestionPageGenerator questionPageGenerator = new QuestionPageGenerator(ReaderActivity.this); pageView = questionPageGenerator.generate(mQuiz.getQuizQuestion(questionIndex), mQuiz.numberOfQuestions(), this); } container.addView(pageView); return pageView; } public void questionAnswered(int questionIndex, boolean correct) { ReaderActivity.pageAnswerState oldAnswerState = mAnswerStates[questionIndex]; if (correct) { if (oldAnswerState == ReaderActivity.pageAnswerState.wrongOnce) mAnswerStates[questionIndex] = ReaderActivity.pageAnswerState.secondTimeCorrect; else if (oldAnswerState == ReaderActivity.pageAnswerState.unanswered) mAnswerStates[questionIndex] = ReaderActivity.pageAnswerState.firstTimeCorrect; // if they already got it wrong twice they get no credit. // if they already got it right no credit for clicking again. } else { if (oldAnswerState == ReaderActivity.pageAnswerState.unanswered) mAnswerStates[questionIndex] = ReaderActivity.pageAnswerState.wrongOnce; else if (oldAnswerState == ReaderActivity.pageAnswerState.wrongOnce) mAnswerStates[questionIndex] = ReaderActivity.pageAnswerState.wrong; // if they previously got it right we won't hold it against them // that they now get it wrong. } if (!mQuestionAnalyticsSent) { boolean allAnswered = true; int rightFirstTime = 0; for (int i = 0; i < mAnswerStates.length; i++) { if (mAnswerStates[i] == ReaderActivity.pageAnswerState.unanswered) { allAnswered = false; break; } else if (mAnswerStates[i] == ReaderActivity.pageAnswerState.firstTimeCorrect) { rightFirstTime++; } } if (allAnswered) { Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("questionCount", mAnswerStates.length); p.putValue("rightFirstTime", rightFirstTime); p.putValue("percentRight", rightFirstTime * 100 / mAnswerStates.length); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("Questions correct", p); // Don't send again unless they re-open the book and start over. mQuestionAnalyticsSent = true; } } } // position should in fact be the position of the pager. public ScaledWebView getActiveView(int position) { return mActiveViews.get(position); } public void prepareForAnimation(int position) { final ScaledWebView pageView = mActiveViews.get(position); if (pageView == null) { Log.d("Reader", "prepareForAnimation() can't find page for " + position); return; } if (pageView.getWebAppInterface() != null) pageView.getWebAppInterface().prepareDocumentWhenDocLoaded(); } public void startNarrationForPage(int position) { ScaledWebView pageView = mActiveViews.get(position); if (pageView == null) { Log.d("Reader", "startNarration() can't find page for " + position); return; } if (pageView.getWebAppInterface() != null) pageView.getWebAppInterface().startNarrationWhenDocLoaded(); } private WebView MakeBrowserForPage(int position) { ScaledWebView browser = null; boolean inLandscape; try { String page = mHtmlPageDivs.get(position); if(position == 0) { getPageOrientationAndRotateScreen(page); inLandscape = isDeviceInLandscape(); setFeatureEffects(inLandscape); // depends on what orientation we're actually in, so can't do sooner. } else { inLandscape = isDeviceInLandscape(); } browser = new ScaledWebView(mParent, position); mActiveViews.put(position, browser); if (mIsMultiMediaBook) { WebAppInterface appInterface = new WebAppInterface(this.mParent, mBookHtmlPath.getParent(), browser, position); browser.setWebAppInterface(appInterface); } // Styles to force 0 border and to vertically center books String moreStyles = "<style>html{ height: 100%; } body{ min-height:100%; display:flex; align-items:center; } div.bloom-page { border:0 !important; }</style>\n"; String doc = mHtmlBeforeFirstPageDiv + moreStyles + pageUsingDeviceLayout(page) + mHtmlAfterLastPageDiv; browser.loadDataWithBaseURL("file:///" + mBookHtmlPath.getAbsolutePath(), doc, inLandscape); prepareForAnimation(position); }catch (Exception ex) { Log.e("Reader", "Error loading " + mBookHtmlPath.getAbsolutePath() + " " + ex); } return browser; } @Override public boolean isViewFromObject(View view, Object object) { Log.d("Reader", "isViewFromObject = " + (view == object)); return view == object; } } private class ScaledWebView extends WebView { private String data; private String baseUrl; private int page; private int scale = 0; public ScaledWebView(Context context, int page) { super(context); this.page = page; if(mRTLBook) setRotationY(180); getSettings().setJavaScriptEnabled(true); getSettings().setMediaPlaybackRequiresUserGesture(false); } public void loadDataWithBaseURL(String baseUrl, String data, boolean inLandscape){ this.baseUrl = baseUrl; if (inLandscape) data = data.replace("Device16x9Portrait", "Device16x9Landscape"); else data = data.replace("Device16x9Landscape", "Device16x9Portrait"); this.data = data; loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", null); } public void setWebAppInterface(WebAppInterface appInterface){ addJavascriptInterface(appInterface, "Android"); // Save the WebAppInterface in the browser's tag because there's no simple // way to get from the browser to the object we set as the JS interface. setTag(appInterface); } @Nullable public WebAppInterface getWebAppInterface(){ if(getTag() instanceof WebAppInterface) return (WebAppInterface) getTag(); return null; } // This method will be called on all Webviews in memory when orientation changes public void reloadPage(boolean inLandscape){ setFeatureEffects(inLandscape); loadDataWithBaseURL(baseUrl, data, inLandscape); resetMultiMedia(); } // This method will be called on all Webviews in memory when orientation changes // Actions that should only run once are in the if block that checks the current page private void resetMultiMedia(){ WebAppInterface appInterface = getWebAppInterface(); if (appInterface != null) { appInterface.reset(); appInterface.prepareDocumentWhenDocLoaded(); } if(page == mPager.getCurrentItem()){ mTimeLastPageSwitch = System.currentTimeMillis(); clearNextPageTimer(); WebAppInterface.stopAllAudio(); if (appInterface != null) appInterface.startNarrationWhenDocLoaded(); } } @Override protected void onSizeChanged(int w, int h, int ow, int oh){ // if width is zero, this method will be called again if (w != 0) { if (scale == 0) { scale = getPageScale(w, h); setInitialScale(scale); } // boolean deviceInLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; // This method seems to lag and give wrong results boolean deviceInLandscape = w > h; boolean pageInLandscape = data.contains("Device16x9Landscape"); if (deviceInLandscape != pageInLandscape) { reloadPage(deviceInLandscape); // The viewport ratio can change with orientation changes when the Back/Home/Recent menu moves to a different side // Unfortunately we can't rescale a Webview once it's been scaled, so if we want to fix this, we'll have to make a new Webview if (scale > getPageScale(w, h)) Log.w("BloomScale", "The viewport size has changed and now the page is too big. Some elements may go off-screen."); } } super.onSizeChanged(w, h, ow, oh); } private float mXLocationForActionDown; private float mYLocationForActionDown; // After trying many things this is the only approach that worked so far for detecting // a tap on the window. Things I tried: // - setOnClickListener on the ViewPager. This is known not to work, e.g., // - the ClickableViewPager described as an answer there (captures move events, but for // no obvious reason does not capture down and up or detect clicks) // - setOnClickListener on the WebView. This is also known not to work. @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mXLocationForActionDown = event.getX(); mYLocationForActionDown = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_UP) { ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext()); if (Math.abs(event.getX() - mXLocationForActionDown) > viewConfiguration.getScaledTouchSlop() || Math.abs(event.getY() - mYLocationForActionDown) > viewConfiguration.getScaledTouchSlop()) { // We don't want to register a touch if the user is swiping. // Without this, we had some bizarre behavior wherein the user could swipe slightly more // vertical distance than horizontal and cause a play/pause event. } else if (event.getEventTime() - event.getDownTime() < viewConfiguration.getJumpTapTimeout()) { if (mCurrentView != null && mCurrentView.getWebAppInterface() != null) { // OK, here we have finally decided the user tapped the screen. // In the case of a non-multimedia page, all we want to do is toggle the // system ui bars. In the case of a multimedia page, we want to toggle both // the system ui bars and play/pause. boolean hideSystemMenu = isSystemUIShowing(); // default toggle action for non-multimedia page WebAppInterface appInterface = mCurrentView.getWebAppInterface(); if (appInterface.mPageHasMultimedia) { appInterface.toggleAudioOrVideoPaused(); mediaPausedChanged(); hideSystemMenu = !WebAppInterface.isMediaPaused(); // show if paused for multimedia page } if (hideSystemMenu) { hideSystemUI(); } else { showSystemUI(); } } } } return super.onTouchEvent(event); } } }
package org.jcodec.containers.mkv; import static java.lang.Long.toHexString; import static org.jcodec.containers.mkv.util.EbmlUtil.toHexString; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.jcodec.containers.mkv.boxes.EbmlBase; import org.jcodec.containers.mkv.boxes.EbmlBin; import org.jcodec.containers.mkv.boxes.EbmlDate; import org.jcodec.containers.mkv.boxes.EbmlFloat; import org.jcodec.containers.mkv.boxes.EbmlMaster; import org.jcodec.containers.mkv.boxes.EbmlSint; import org.jcodec.containers.mkv.boxes.EbmlString; import org.jcodec.containers.mkv.boxes.EbmlUint; import org.jcodec.containers.mkv.boxes.EbmlVoid; import org.jcodec.containers.mkv.boxes.MkvBlock; import org.jcodec.containers.mkv.boxes.MkvSegment; import org.jcodec.platform.Platform; public final class MKVType { // EBML Id's public final static MKVType Void = new MKVType(new byte[]{(byte)0xEC}, EbmlVoid.class); public final static MKVType CRC32 = new MKVType(new byte[]{(byte)0xBF}, EbmlBin.class); public final static MKVType EBML = new MKVType(new byte[]{0x1A, 0x45, (byte)0xDF, (byte)0xA3}, EbmlMaster.class); public final static MKVType EBMLVersion = new MKVType(new byte[]{0x42, (byte)0x86}, EbmlUint.class); public final static MKVType EBMLReadVersion = new MKVType(new byte[]{0x42, (byte)0xF7}, EbmlUint.class); public final static MKVType EBMLMaxIDLength = new MKVType(new byte[]{0x42, (byte)0xF2}, EbmlUint.class); public final static MKVType EBMLMaxSizeLength = new MKVType(new byte[]{0x42, (byte)0xF3}, EbmlUint.class); //All strings are UTF8 in java, this EbmlBase is specified as pure ASCII EbmlBase in Matroska spec public final static MKVType DocType = new MKVType(new byte[]{0x42, (byte)0x82}, EbmlString.class); public final static MKVType DocTypeVersion = new MKVType(new byte[]{0x42, (byte)0x87}, EbmlUint.class); public final static MKVType DocTypeReadVersion = new MKVType(new byte[]{0x42, (byte)0x85}, EbmlUint.class); public final static MKVType Segment = new MKVType(new byte[]{0x18, 0x53, (byte)0x80, 0x67}, MkvSegment.class); public final static MKVType SeekHead = new MKVType(new byte[]{0x11, 0x4D, (byte)0x9B, 0x74}, EbmlMaster.class); public final static MKVType Seek = new MKVType(new byte[]{0x4D, (byte)0xBB}, EbmlMaster.class); public final static MKVType SeekID = new MKVType(new byte[]{0x53, (byte)0xAB}, EbmlBin.class); public final static MKVType SeekPosition = new MKVType(new byte[]{0x53, (byte)0xAC}, EbmlUint.class); public final static MKVType Info = new MKVType(new byte[]{0x15, (byte)0x49, (byte)0xA9, (byte)0x66}, EbmlMaster.class); public final static MKVType SegmentUID = new MKVType(new byte[]{0x73, (byte)0xA4}, EbmlBin.class); //All strings are UTF8 in java public final static MKVType SegmentFilename = new MKVType(new byte[]{0x73, (byte)0x84}, EbmlString.class); public final static MKVType PrevUID = new MKVType(new byte[]{0x3C, (byte)0xB9, 0x23}, EbmlBin.class); public final static MKVType PrevFilename = new MKVType(new byte[]{0x3C, (byte)0x83, (byte)0xAB}, EbmlString.class); public final static MKVType NextUID = new MKVType(new byte[]{0x3E, (byte)0xB9, 0x23}, EbmlBin.class); //An escaped filename corresponding to the next segment. public final static MKVType NextFilenam = new MKVType(new byte[]{0x3E, (byte)0x83, (byte)0xBB}, EbmlString.class); // A randomly generated unique ID that all segments related to each other must use (128 bits). public final static MKVType SegmentFamily = new MKVType(new byte[]{0x44,0x44}, EbmlBin.class); // A tuple of corresponding ID used by chapter codecs to represent this segment. public final static MKVType ChapterTranslate = new MKVType(new byte[]{0x69,0x24}, EbmlMaster.class); //Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment. public final static MKVType ChapterTranslateEditionUID = new MKVType(new byte[]{0x69, (byte) 0xFC}, EbmlUint.class); //The chapter codec using this ID (0: Matroska Script, 1: DVD-menu). public final static MKVType ChapterTranslateCodec = new MKVType(new byte[]{0x69, (byte) 0xBF}, EbmlUint.class); // The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used. public final static MKVType ChapterTranslateID = new MKVType(new byte[]{0x69, (byte)0xA5}, EbmlBin.class); // Timecode scale in nanoseconds (1.000.000 means all timecodes in the segment are expressed in milliseconds). // Every timecode of a block (cluster timecode + block timecode ) is multiplied by this value to obtain real timecode of a block public final static MKVType TimecodeScale = new MKVType(new byte[]{0x2A, (byte)0xD7, (byte)0xB1}, EbmlUint.class); public final static MKVType Duration = new MKVType(new byte[]{0x44, (byte)0x89}, EbmlFloat.class); public final static MKVType DateUTC = new MKVType(new byte[]{0x44, (byte)0x61}, EbmlDate.class); public final static MKVType Title = new MKVType(new byte[]{0x7B, (byte)0xA9}, EbmlString.class); public final static MKVType MuxingApp = new MKVType(new byte[]{0x4D, (byte)0x80}, EbmlString.class); public final static MKVType WritingApp = new MKVType(new byte[]{0x57, 0x41}, EbmlString.class); //The lower level EbmlBase containing the (monolithic) Block structure. public final static MKVType Cluster = new MKVType(new byte[]{0x1F, (byte)0x43, (byte)0xB6, (byte)0x75}, EbmlMaster.class); //Absolute timecode of the cluster (based on TimecodeScale). public final static MKVType Timecode = new MKVType(new byte[]{(byte)0xE7}, EbmlUint.class); // The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use. public final static MKVType SilentTracks = new MKVType(new byte[]{0x58, 0x54}, EbmlMaster.class); // One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster public final static MKVType SilentTrackNumber = new MKVType(new byte[]{0x58, (byte)0xD7}, EbmlUint.class); // The Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams. public final static MKVType Position = new MKVType(new byte[]{(byte)0xA7}, EbmlUint.class); // Size of the previous Cluster, in octets. Can be useful for backward playing. public final static MKVType PrevSize = new MKVType(new byte[]{(byte)0xAB}, EbmlUint.class); //Similar to Block but without all the extra information, mostly used to reduced overhead when no extra feature is needed. (see SimpleBlock Structure) public final static MKVType SimpleBlock = new MKVType(new byte[]{(byte)0xA3}, MkvBlock.class); //Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock. public final static MKVType BlockGroup = new MKVType(new byte[]{(byte)0xA0}, EbmlMaster.class); // Block containing the actual data to be rendered and a timecode relative to the Cluster Timecode. (see Block Structure) public final static MKVType Block = new MKVType(new byte[]{(byte)0xA1}, MkvBlock.class); // Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data. public final static MKVType BlockAdditions = new MKVType(new byte[]{0x75, (byte) 0xA1}, EbmlMaster.class); // Contain the BlockAdditional and some parameters. public final static MKVType BlockMore = new MKVType(new byte[]{(byte)0xA6}, EbmlMaster.class); // An ID to identify the BlockAdditional level. public final static MKVType BlockAddID = new MKVType(new byte[]{(byte)0xEE}, EbmlUint.class); // Interpreted by the codec as it wishes (using the BlockAddID). public final static MKVType BlockAdditional = new MKVType(new byte[]{(byte) 0xA5}, EbmlBin.class); /** * The duration of the Block (based on TimecodeScale). * This EbmlBase is mandatory when DefaultDuration is set for the track (but can be omitted as other default values). * When not written and with no DefaultDuration, the value is assumed to be the difference between the timecode * of this Block and the timecode of the next Block in "display" order (not coding order). * This EbmlBase can be useful at the end of a Track (as there is not other Block available); * or when there is a break in a track like for subtitle tracks. * When set to 0 that means the frame is not a keyframe. */ public final static MKVType BlockDuration = new MKVType(new byte[]{(byte)0x9B}, EbmlUint.class); // This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced public final static MKVType ReferencePriority = new MKVType(new byte[]{(byte) 0xFA}, EbmlUint.class); //Timecode of another frame used as a reference (ie: B or P frame). The timecode is relative to the block it's attached to. public final static MKVType ReferenceBlock = new MKVType(new byte[]{(byte)0xFB}, EbmlSint.class); // The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry. public final static MKVType CodecState = new MKVType(new byte[]{(byte)0xA4}, EbmlBin.class); // Contains slices description. public final static MKVType Slices = new MKVType(new byte[]{(byte)0x8E}, EbmlMaster.class); // Contains extra time information about the data contained in the Block. While there are a few files in the wild with this EbmlBase, it is no longer in use and has been deprecated. Being able to interpret this EbmlBase is not required for playback. public final static MKVType TimeSlice = new MKVType(new byte[]{(byte)0xE8}, EbmlMaster.class); // The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this EbmlBase, it is no longer in use and has been deprecated. Being able to interpret this EbmlBase is not required for playback. public final static MKVType LaceNumber = new MKVType(new byte[]{(byte)0xCC}, EbmlUint.class); //A top-level block of information with many tracks described. public final static MKVType Tracks = new MKVType(new byte[]{0x16, (byte)0x54, (byte)0xAE, (byte)0x6B}, EbmlMaster.class); //Describes a track with all EbmlBases. public final static MKVType TrackEntry = new MKVType(new byte[]{(byte)0xAE}, EbmlMaster.class); //The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number). public final static MKVType TrackNumber = new MKVType(new byte[]{(byte)0xD7}, EbmlUint.class); //A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file. public final static MKVType TrackUID = new MKVType(new byte[]{0x73, (byte)0xC5}, EbmlUint.class); //A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control). public final static MKVType TrackType = new MKVType(new byte[]{(byte)0x83}, EbmlUint.class); // Set if the track is usable. (1 bit) public final static MKVType FlagEnabled = new MKVType(new byte[]{(byte)0xB9}, EbmlUint.class); // Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference. (1 bit) public final static MKVType FlagDefault = new MKVType(new byte[]{(byte)0x88}, EbmlUint.class); // Set if that track MUST be active during playback. There can be many forced track for a kind (audio, video or subs); the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. (1 bit) public final static MKVType FlagForced = new MKVType(new byte[]{0x55,(byte)0xAA}, EbmlUint.class); // Set if the track may contain blocks using lacing. (1 bit) public final static MKVType FlagLacing = new MKVType(new byte[]{(byte)0x9C}, EbmlUint.class); // The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used. public final static MKVType MinCache = new MKVType(new byte[]{0x6D,(byte)0xE7}, EbmlUint.class); // The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed. public final static MKVType MaxCache = new MKVType(new byte[]{0x6D,(byte)0xF8}, EbmlUint.class); //Number of nanoseconds (not scaled via TimecodeScale) per frame ('frame' in the Matroska sense -- one EbmlBase put into a (Simple)Block). public final static MKVType DefaultDuration = new MKVType(new byte[]{0x23, (byte)0xE3, (byte)0x83}, EbmlUint.class); // The maximum value of BlockAddID. A value 0 means there is no BlockAdditions for this track. public final static MKVType MaxBlockAdditionID = new MKVType(new byte[]{0x55, (byte)0xEE}, EbmlUint.class); //A human-readable track name. public final static MKVType Name = new MKVType(new byte[]{0x53, 0x6E}, EbmlString.class); // Specifies the language of the track in the Matroska languages form. public final static MKVType Language = new MKVType(new byte[]{0x22, (byte)0xB5, (byte)0x9C}, EbmlString.class); // An ID corresponding to the codec, see the codec page for more info. public final static MKVType CodecID = new MKVType(new byte[]{(byte)0x86}, EbmlString.class); //Private data only known to the codec. public final static MKVType CodecPrivate = new MKVType(new byte[]{(byte)0x63, (byte)0xA2}, EbmlBin.class); // A human-readable string specifying the codec. public final static MKVType CodecName = new MKVType(new byte[]{(byte)0x25,(byte)0x86,(byte)0x88}, EbmlString.class); // The UID of an attachment that is used by this codec. public final static MKVType AttachmentLink = new MKVType(new byte[]{0x74, 0x46}, EbmlUint.class); // The codec can decode potentially damaged data (1 bit). public final static MKVType CodecDecodeAll = new MKVType(new byte[]{(byte)0xAA}, EbmlUint.class); // Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc. public final static MKVType TrackOverlay = new MKVType(new byte[]{0x6F,(byte)0xAB}, EbmlUint.class); // The track identification for the given Chapter Codec. public final static MKVType TrackTranslate = new MKVType(new byte[]{0x66, 0x24}, EbmlMaster.class); // Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment. public final static MKVType TrackTranslateEditionUID = new MKVType(new byte[]{0x66,(byte)0xFC}, EbmlUint.class); // The chapter codec using this ID (0: Matroska Script, 1: DVD-menu). public final static MKVType TrackTranslateCodec = new MKVType(new byte[]{0x66,(byte)0xBF}, EbmlUint.class); // The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used. public final static MKVType TrackTranslateTrackID = new MKVType(new byte[]{0x66,(byte)0xA5}, EbmlBin.class); public final static MKVType Video = new MKVType(new byte[]{(byte)0xE0}, EbmlMaster.class); // Set if the video is interlaced. (1 bit) public final static MKVType FlagInterlaced = new MKVType(new byte[]{(byte)0x9A}, EbmlUint.class); // Stereo-3D video mode (0: mono, 1: side by side (left eye is first); 2: top-bottom (right eye is first); 3: top-bottom (left eye is first); 4: checkboard (right is first); 5: checkboard (left is first); 6: row interleaved (right is first); 7: row interleaved (left is first); 8: column interleaved (right is first); 9: column interleaved (left is first); 10: anaglyph (cyan/red); 11: side by side (right eye is first); 12: anaglyph (green/magenta); 13 both eyes laced in one Block (left eye is first); 14 both eyes laced in one Block (right eye is first)) . There are some more details on 3D support in the Specification Notes. public final static MKVType StereoMode = new MKVType(new byte[]{0x53,(byte)0xB8}, EbmlUint.class); // Alpha Video Mode. Presence of this EbmlBase indicates that the BlockAdditional EbmlBase could contain Alpha data. public final static MKVType AlphaMode = new MKVType(new byte[]{0x53,(byte)0xC0}, EbmlUint.class); public final static MKVType PixelWidth = new MKVType(new byte[]{(byte)0xB0}, EbmlUint.class); public final static MKVType PixelHeight = new MKVType(new byte[]{(byte)0xBA}, EbmlUint.class); // The number of video pixels to remove at the bottom of the image (for HDTV content). public final static MKVType PixelCropBottom = new MKVType(new byte[]{0x54,(byte)0xAA}, EbmlUint.class); // The number of video pixels to remove at the top of the image. public final static MKVType PixelCropTop = new MKVType(new byte[]{0x54,(byte)0xBB}, EbmlUint.class); // The number of video pixels to remove on the left of the image. public final static MKVType PixelCropLeft = new MKVType(new byte[]{0x54,(byte)0xCC}, EbmlUint.class); // The number of video pixels to remove on the right of the image. public final static MKVType PixelCropRight = new MKVType(new byte[]{0x54,(byte)0xDD}, EbmlUint.class); public final static MKVType DisplayWidth = new MKVType(new byte[]{0x54, (byte)0xB0}, EbmlUint.class); public final static MKVType DisplayHeight = new MKVType(new byte[]{0x54, (byte)0xBA}, EbmlUint.class); // How DisplayWidth & DisplayHeight should be interpreted (0: pixels, 1: centimeters, 2: inches, 3: Display Aspect Ratio). public final static MKVType DisplayUnit = new MKVType(new byte[]{0x54,(byte)0xB2}, EbmlUint.class); // Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed). public final static MKVType AspectRatioType = new MKVType(new byte[]{0x54,(byte)0xB3}, EbmlUint.class); // Same value as in AVI (32 bits). public final static MKVType ColourSpace = new MKVType(new byte[]{0x2E, (byte)0xB5,0x24}, EbmlBin.class); public final static MKVType Audio = new MKVType(new byte[]{(byte)0xE1}, EbmlMaster.class); public final static MKVType SamplingFrequency = new MKVType(new byte[]{(byte)0xB5}, EbmlFloat.class); public final static MKVType OutputSamplingFrequency = new MKVType(new byte[]{0x78, (byte)0xB5}, EbmlFloat.class); public final static MKVType Channels = new MKVType(new byte[]{(byte)0x9F}, EbmlUint.class); public final static MKVType BitDepth = new MKVType(new byte[]{0x62, 0x64}, EbmlUint.class); // Operation that needs to be applied on tracks to create this virtual track. For more details look at the Specification Notes on the subject. public final static MKVType TrackOperation = new MKVType(new byte[]{(byte)0xE2}, EbmlMaster.class); // Contains the list of all video plane tracks that need to be combined to create this 3D track public final static MKVType TrackCombinePlanes = new MKVType(new byte[]{(byte)0xE3}, EbmlMaster.class); // Contains a video plane track that need to be combined to create this 3D track public final static MKVType TrackPlane = new MKVType(new byte[]{(byte)0xE4}, EbmlMaster.class); // The trackUID number of the track representing the plane. public final static MKVType TrackPlaneUID = new MKVType(new byte[]{(byte)0xE5}, EbmlUint.class); // The kind of plane this track corresponds to (0: left eye, 1: right eye, 2: background). public final static MKVType TrackPlaneType = new MKVType(new byte[]{(byte)0xE6}, EbmlUint.class); // Contains the list of all tracks whose Blocks need to be combined to create this virtual track public final static MKVType TrackJoinBlocks = new MKVType(new byte[]{(byte)0xE9}, EbmlMaster.class); // The trackUID number of a track whose blocks are used to create this virtual track. public final static MKVType TrackJoinUID = new MKVType(new byte[]{(byte)0xED}, EbmlUint.class); // Settings for several content encoding mechanisms like compression or encryption. public final static MKVType ContentEncodings = new MKVType(new byte[]{0x6D, (byte)0x80}, EbmlMaster.class); // Settings for one content encoding like compression or encryption. public final static MKVType ContentEncoding = new MKVType(new byte[]{0x62, 0x40}, EbmlMaster.class); // Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder EbmlBases in the segment. public final static MKVType ContentEncodingOrder = new MKVType(new byte[]{0x50, 0x31}, EbmlUint.class); // A bit field that describes which EbmlBases have been modified in this way. Values (big endian) can be OR'ed. Possible values: 1 - all frame contents, 2 - the track's private data, 4 - the next ContentEncoding (next ContentEncodingOrder. Either the data inside ContentCompression and/or ContentEncryption) public final static MKVType ContentEncodingScope = new MKVType(new byte[]{0x50, 0x32}, EbmlUint.class); // A value describing what kind of transformation has been done. Possible values: 0 - compression, 1 - encryption public final static MKVType ContentEncodingType = new MKVType(new byte[]{0x50, 0x33}, EbmlUint.class); // Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking. public final static MKVType ContentCompression = new MKVType(new byte[]{0x50, 0x34}, EbmlMaster.class); // The compression algorithm used. Algorithms that have been specified so far are: 0 - zlib, 1 - bzlib, 2 - lzo1x, 3 - Header Stripping public final static MKVType ContentCompAlgo = new MKVType(new byte[]{0x42, (byte)0x54}, EbmlUint.class); // Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3); the bytes that were removed from the beggining of each frames of the track. public final static MKVType ContentCompSettings = new MKVType(new byte[]{0x42, 0x55}, EbmlBin.class); // Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise. public final static MKVType ContentEncryption = new MKVType(new byte[]{0x50, 0x35}, EbmlMaster.class); // The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values: 1 - DES, 2 - 3DES, 3 - Twofish, 4 - Blowfish, 5 - AES public final static MKVType ContentEncAlgo = new MKVType(new byte[]{0x47, (byte)0xE1}, EbmlUint.class); // For public key algorithms this is the ID of the public key the the data was encrypted with. public final static MKVType ContentEncKeyID = new MKVType(new byte[]{0x47, (byte)0xE2}, EbmlBin.class); // A cryptographic signature of the contents. public final static MKVType ContentSignature = new MKVType(new byte[]{0x47, (byte)0xE3}, EbmlBin.class); // This is the ID of the private key the data was signed with. public final static MKVType ContentSigKeyID = new MKVType(new byte[]{0x47, (byte)0xE4}, EbmlBin.class); // The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - RSA public final static MKVType ContentSigAlgo = new MKVType(new byte[]{0x47, (byte)0xE5}, EbmlUint.class); // The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - SHA1-160, 2 - MD5 public final static MKVType ContentSigHashAlgo = new MKVType(new byte[]{0x47, (byte)0xE6}, EbmlUint.class); public final static MKVType Cues = new MKVType(new byte[]{0x1C,0x53,(byte)0xBB,0x6B}, EbmlMaster.class); public final static MKVType CuePoint = new MKVType(new byte[]{(byte)0xBB}, EbmlMaster.class); public final static MKVType CueTime = new MKVType(new byte[]{(byte)0xB3}, EbmlUint.class); public final static MKVType CueTrackPositions = new MKVType(new byte[]{(byte)0xB7}, EbmlMaster.class); public final static MKVType CueTrack = new MKVType(new byte[]{(byte)0xF7}, EbmlUint.class); public final static MKVType CueClusterPosition = new MKVType(new byte[]{(byte)0xF1}, EbmlUint.class); // The relative position of the referenced block inside the cluster with 0 being the first possible position for an EbmlBase inside that cluster. public final static MKVType CueRelativePosition = new MKVType(new byte[]{(byte)0xF0}, EbmlUint.class); // The duration of the block according to the segment time base. If missing the track's DefaultDuration does not apply and no duration information is available in terms of the cues. public final static MKVType CueDuration = new MKVType(new byte[]{(byte)0xB2}, EbmlUint.class); //Number of the Block in the specified Cluster. public final static MKVType CueBlockNumber = new MKVType(new byte[]{0x53, 0x78}, EbmlUint.class); // The position of the Codec State corresponding to this Cue EbmlBase. 0 means that the data is taken from the initial Track Entry. public final static MKVType CueCodecState = new MKVType(new byte[]{(byte)0xEA}, EbmlUint.class); // The Clusters containing the required referenced Blocks. public final static MKVType CueReference = new MKVType(new byte[]{(byte)0xDB}, EbmlMaster.class); // Timecode of the referenced Block. public final static MKVType CueRefTime = new MKVType(new byte[]{(byte)0x96}, EbmlUint.class); public final static MKVType Attachments = new MKVType(new byte[]{0x19, 0x41, (byte)0xA4, 0x69}, EbmlMaster.class); public final static MKVType AttachedFile = new MKVType(new byte[]{0x61, (byte)0xA7}, EbmlMaster.class); public final static MKVType FileDescription = new MKVType(new byte[]{0x46, (byte)0x7E}, EbmlString.class); public final static MKVType FileName = new MKVType(new byte[]{0x46, (byte)0x6E}, EbmlString.class); public final static MKVType FileMimeType = new MKVType(new byte[]{0x46, (byte)0x60}, EbmlString.class); public final static MKVType FileData = new MKVType(new byte[]{0x46, (byte)0x5C}, EbmlBin.class); public final static MKVType FileUID = new MKVType(new byte[]{0x46, (byte)0xAE}, EbmlUint.class); public final static MKVType Chapters = new MKVType(new byte[]{0x10, (byte)0x43, (byte)0xA7, (byte)0x70}, EbmlMaster.class); public final static MKVType EditionEntry = new MKVType(new byte[]{(byte)0x45, (byte)0xB9}, EbmlMaster.class); public final static MKVType EditionUID = new MKVType(new byte[]{(byte)0x45, (byte)0xBC}, EbmlUint.class); public final static MKVType EditionFlagHidden = new MKVType(new byte[]{(byte)0x45, (byte)0xBD}, EbmlUint.class); public final static MKVType EditionFlagDefault = new MKVType(new byte[]{(byte)0x45, (byte)0xDB}, EbmlUint.class); public final static MKVType EditionFlagOrdered = new MKVType(new byte[]{(byte)0x45, (byte)0xDD}, EbmlUint.class); public final static MKVType ChapterAtom = new MKVType(new byte[]{(byte)0xB6}, EbmlMaster.class); public final static MKVType ChapterUID = new MKVType(new byte[]{(byte)0x73, (byte)0xC4}, EbmlUint.class); // A unique string ID to identify the Chapter. Use for WebVTT cue identifier storage. public final static MKVType ChapterStringUID = new MKVType(new byte[]{0x56,0x54}, EbmlString.class); public final static MKVType ChapterTimeStart = new MKVType(new byte[]{(byte)0x91}, EbmlUint.class); public final static MKVType ChapterTimeEnd = new MKVType(new byte[]{(byte)0x92}, EbmlUint.class); public final static MKVType ChapterFlagHidden = new MKVType(new byte[]{(byte)0x98}, EbmlUint.class); public final static MKVType ChapterFlagEnabled = new MKVType(new byte[]{(byte)0x45, (byte)0x98}, EbmlUint.class); // A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used. public final static MKVType ChapterSegmentUID = new MKVType(new byte[]{0x6E,0x67}, EbmlBin.class); // The EditionUID to play from the segment linked in ChapterSegmentUID. public final static MKVType ChapterSegmentEditionUID = new MKVType(new byte[]{0x6E,(byte)0xBC}, EbmlUint.class); public final static MKVType ChapterPhysicalEquiv = new MKVType(new byte[]{(byte)0x63, (byte)0xC3}, EbmlUint.class); public final static MKVType ChapterTrack = new MKVType(new byte[]{(byte)0x8F}, EbmlMaster.class); public final static MKVType ChapterTrackNumber = new MKVType(new byte[]{(byte)0x89}, EbmlUint.class); public final static MKVType ChapterDisplay = new MKVType(new byte[]{(byte)0x80}, EbmlMaster.class); public final static MKVType ChapString = new MKVType(new byte[]{(byte)0x85}, EbmlString.class); public final static MKVType ChapLanguage = new MKVType(new byte[]{(byte)0x43, (byte)0x7C}, EbmlString.class); public final static MKVType ChapCountry = new MKVType(new byte[]{(byte)0x43, (byte)0x7E}, EbmlString.class); // Contains all the commands associated to the Atom. public final static MKVType ChapProcess = new MKVType(new byte[]{0x69, 0x44}, EbmlMaster.class); // Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined); a value of 1 means the DVD command set is used. More codec IDs can be added later. public final static MKVType ChapProcessCodecID = new MKVType(new byte[]{0x69, 0x55}, EbmlUint.class); // Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent. public final static MKVType ChapProcessPrivate = new MKVType(new byte[]{0x45, 0x0D}, EbmlBin.class); // Contains all the commands associated to the Atom. public final static MKVType ChapProcessCommand = new MKVType(new byte[]{0x69, 0x11}, EbmlMaster.class); // Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter). public final static MKVType ChapProcessTime = new MKVType(new byte[]{0x69, 0x22}, EbmlUint.class); // Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands. public final static MKVType ChapProcessData = new MKVType(new byte[]{0x69, 0x33}, EbmlBin.class); public final static MKVType Tags = new MKVType(new byte[]{0x12, (byte)0x54, (byte)0xC3, (byte)0x67}, EbmlMaster.class); public final static MKVType Tag = new MKVType(new byte[]{0x73, (byte)0x73}, EbmlMaster.class); public final static MKVType Targets = new MKVType(new byte[]{0x63, (byte)0xC0}, EbmlMaster.class); public final static MKVType TargetTypeValue = new MKVType(new byte[]{0x68, (byte) 0xCA}, EbmlUint.class); public final static MKVType TargetType = new MKVType(new byte[]{0x63,(byte)0xCA}, EbmlString.class); public final static MKVType TagTrackUID = new MKVType(new byte[]{0x63, (byte)0xC5}, EbmlUint.class); // A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment. public final static MKVType TagEditionUID = new MKVType(new byte[]{0x63,(byte)0xC9}, EbmlUint.class); public final static MKVType TagChapterUID = new MKVType(new byte[]{0x63, (byte)0xC4}, EbmlUint.class); public final static MKVType TagAttachmentUID = new MKVType(new byte[]{0x63, (byte)0xC6}, EbmlUint.class); public final static MKVType SimpleTag = new MKVType(new byte[]{0x67, (byte)0xC8}, EbmlMaster.class); public final static MKVType TagName = new MKVType(new byte[]{0x45, (byte)0xA3}, EbmlString.class); public final static MKVType TagLanguage = new MKVType(new byte[]{0x44, 0x7A}, EbmlString.class); public final static MKVType TagDefault = new MKVType(new byte[]{0x44, (byte)0x84}, EbmlUint.class); public final static MKVType TagString = new MKVType(new byte[]{0x44, (byte)0x87}, EbmlString.class); public final static MKVType TagBinary = new MKVType(new byte[]{0x44, (byte)0x85}, EbmlBin.class); static public MKVType[] firstLevelHeaders = {SeekHead, Info, Cluster, Tracks, Cues, Attachments, Chapters, Tags, EBMLVersion, EBMLReadVersion, EBMLMaxIDLength, EBMLMaxSizeLength, DocType, DocTypeVersion, DocTypeReadVersion }; public final byte [] id; public final Class<? extends EbmlBase> clazz; private final static List<MKVType> _values =new ArrayList<MKVType>(); private MKVType(byte[] id, Class<? extends EbmlBase> clazz) { this.id = id; this.clazz = clazz; _values.add(this); } public static MKVType[] values() { return _values.toArray(new MKVType[0]); } @SuppressWarnings("unchecked") public static <T extends EbmlBase> T createByType(MKVType g) { try { T elem = (T) Platform.newInstance(g.clazz, new Object[] { g.id }); elem.type = g; return elem; } catch (Exception e) { e.printStackTrace(); return (T) new EbmlBin(g.id); } } @SuppressWarnings("unchecked") public static <T extends EbmlBase> T createById(byte[] id, long offset) { MKVType[] values = values(); for (int i = 0; i < values.length; i++) { MKVType t = values[i]; if (Platform.arrayEqualsByte(t.id, id)) return createByType(t); } System.err.println("WARNING: unspecified ebml ID (" + toHexString(id) + ") encountered at position 0x" + toHexString(offset).toUpperCase()); T t = (T) new EbmlVoid(id); t.type = Void; return t; } public static boolean isHeaderFirstByte(byte b) { MKVType[] values = values(); for (int i = 0; i < values.length; i++) { MKVType t = values[i]; if (t.id[0] == b) return true; } return false; } public static boolean isSpecifiedHeader(byte[] b) { MKVType[] values = values(); for (int i = 0; i < values.length; i++) { MKVType firstLevelHeader = values[i]; if (Platform.arrayEqualsByte(firstLevelHeader.id, b)) return true; } return false; } public static boolean isFirstLevelHeader(byte[] b){ for (MKVType firstLevelHeader : firstLevelHeaders) if (Platform.arrayEqualsByte(firstLevelHeader.id, b)) return true; return false; } public static final Map<MKVType, Set<MKVType>> children = new HashMap<MKVType, Set<MKVType>>(); static { children.put(EBML, new HashSet<MKVType>(Arrays.asList(new MKVType[]{EBMLVersion, EBMLReadVersion, EBMLMaxIDLength, EBMLMaxSizeLength, DocType, DocTypeVersion, DocTypeReadVersion}))); children.put(Segment, new HashSet<MKVType>(Arrays.asList(new MKVType[]{SeekHead, Info, Cluster, Tracks, Cues, Attachments, Chapters, Tags}))); children.put(SeekHead, new HashSet<MKVType>(Arrays.asList(new MKVType[]{Seek}))); children.put(Seek, new HashSet<MKVType>(Arrays.asList(new MKVType[]{SeekID, SeekPosition}))); children.put(Info, new HashSet<MKVType>(Arrays.asList(new MKVType[]{SegmentUID, SegmentFilename, PrevUID, PrevFilename, NextUID, NextFilenam, SegmentFamily, ChapterTranslate, TimecodeScale, Duration , DateUTC, Title, MuxingApp, WritingApp}))); children.put(ChapterTranslate, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapterTranslateEditionUID, ChapterTranslateCodec, ChapterTranslateID}))); children.put(Cluster, new HashSet<MKVType>(Arrays.asList(new MKVType[]{Timecode, SilentTracks, Position, PrevSize, SimpleBlock, BlockGroup}))); children.put(SilentTracks, new HashSet<MKVType>(Arrays.asList(new MKVType[]{SilentTrackNumber}))); children.put(BlockGroup, new HashSet<MKVType>(Arrays.asList(new MKVType[]{Block, BlockAdditions, BlockDuration, ReferencePriority, ReferenceBlock, CodecState, Slices}))); children.put(BlockAdditions, new HashSet<MKVType>(Arrays.asList(new MKVType[]{BlockMore}))); children.put(BlockMore, new HashSet<MKVType>(Arrays.asList(new MKVType[]{BlockAddID, BlockAdditional}))); children.put(Slices, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TimeSlice}))); children.put(TimeSlice, new HashSet<MKVType>(Arrays.asList(new MKVType[]{LaceNumber}))); children.put(Tracks, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackEntry}))); children.put(TrackEntry, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackNumber, TrackUID, TrackType, TrackType, FlagDefault, FlagForced, FlagLacing, MinCache, MaxCache, DefaultDuration, MaxBlockAdditionID, Name, Language, CodecID, CodecPrivate, CodecName, AttachmentLink, CodecDecodeAll, TrackOverlay, TrackTranslate, Video, Audio, TrackOperation, ContentEncodings}))); children.put(TrackTranslate, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackTranslateEditionUID, TrackTranslateCodec, TrackTranslateTrackID}))); children.put(Video, new HashSet<MKVType>(Arrays.asList(new MKVType[]{FlagInterlaced, StereoMode, AlphaMode, PixelWidth, PixelHeight, PixelCropBottom, PixelCropTop, PixelCropLeft, PixelCropRight, DisplayWidth, DisplayHeight, DisplayUnit, AspectRatioType, ColourSpace}))); children.put(Audio, new HashSet<MKVType>(Arrays.asList(new MKVType[]{SamplingFrequency, OutputSamplingFrequency, Channels, BitDepth}))); children.put(TrackOperation, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackCombinePlanes, TrackJoinBlocks}))); children.put(TrackCombinePlanes, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackPlane}))); children.put(TrackPlane, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackPlaneUID, TrackPlaneType}))); children.put(TrackJoinBlocks, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TrackJoinUID}))); children.put(ContentEncodings, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ContentEncoding}))); children.put(ContentEncoding, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ContentEncodingOrder, ContentEncodingScope, ContentEncodingType, ContentCompression, ContentEncryption}))); children.put(ContentCompression, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ContentCompAlgo, ContentCompSettings}))); children.put(ContentEncryption, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ContentEncAlgo, ContentEncKeyID, ContentSignature, ContentSigKeyID, ContentSigAlgo, ContentSigHashAlgo}))); children.put(Cues, new HashSet<MKVType>(Arrays.asList(new MKVType[]{CuePoint}))); children.put(CuePoint, new HashSet<MKVType>(Arrays.asList(new MKVType[]{CueTime, CueTrackPositions}))); children.put(CueTrackPositions, new HashSet<MKVType>(Arrays.asList(new MKVType[]{CueTrack, CueClusterPosition, CueRelativePosition, CueDuration, CueBlockNumber, CueCodecState, CueReference}))); children.put(CueReference, new HashSet<MKVType>(Arrays.asList(new MKVType[]{CueRefTime}))); children.put(Attachments, new HashSet<MKVType>(Arrays.asList(new MKVType[]{AttachedFile}))); children.put(AttachedFile, new HashSet<MKVType>(Arrays.asList(new MKVType[]{FileDescription, FileName, FileMimeType, FileData, FileUID}))); children.put(Chapters, new HashSet<MKVType>(Arrays.asList(new MKVType[]{EditionEntry}))); children.put(EditionEntry, new HashSet<MKVType>(Arrays.asList(new MKVType[]{EditionUID, EditionFlagHidden, EditionFlagDefault, EditionFlagOrdered, ChapterAtom}))); children.put(ChapterAtom, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapterUID, ChapterStringUID, ChapterTimeStart, ChapterTimeEnd, ChapterFlagHidden, ChapterFlagEnabled, ChapterSegmentUID, ChapterSegmentEditionUID, ChapterPhysicalEquiv, ChapterTrack, ChapterDisplay, ChapProcess}))); children.put(ChapterTrack, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapterTrackNumber}))); children.put(ChapterDisplay, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapString, ChapLanguage, ChapCountry}))); children.put(ChapProcess, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapProcessCodecID, ChapProcessPrivate, ChapProcessCommand}))); children.put(ChapProcessCommand, new HashSet<MKVType>(Arrays.asList(new MKVType[]{ChapProcessTime, ChapProcessData}))); children.put(Tags, new HashSet<MKVType>(Arrays.asList(new MKVType[]{Tag}))); children.put(Tag, new HashSet<MKVType>(Arrays.asList(new MKVType[]{Targets, SimpleTag}))); children.put(Targets, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TargetTypeValue, TargetType, TagTrackUID, TagEditionUID, TagChapterUID, TagAttachmentUID}))); children.put(SimpleTag, new HashSet<MKVType>(Arrays.asList(new MKVType[]{TagName, TagLanguage, TagDefault, TagString, TagBinary}))); } // TODO: this may be optimized of-course if it turns out to be a frequently called method public static MKVType getParent(MKVType t){ for(Entry<MKVType, Set<MKVType>> ent : children.entrySet()){ if (ent.getValue().contains(t)) return ent.getKey(); } return null; } public static boolean possibleChild(EbmlMaster parent, EbmlBase child) { if (parent == null) if (child.type == EBML || child.type == Segment) return true; else return false; // Any unknown EbmlBase is assigned type of Void by parses, thus two different checks // 1. since Void/CRC32 can occur anywhere in the tree, // look if they violate size-offset contract of the parent. // Violated size-offset contract implies the global EbmlBase actually belongs to parent if (Platform.arrayEqualsByte(child.id, Void.id) || Platform.arrayEqualsByte(child.id, CRC32.id)) return !(child.offset == (parent.dataOffset+parent.dataLen)); // 2. In case Void/CRC32 type is assigned, child EbmlBase is assumed as global, // thus it can appear anywhere in the tree if (child.type == Void || child.type == CRC32) return true; Set<MKVType> candidates = children.get(parent.type); return candidates != null && candidates.contains(child.type); } public static boolean possibleChildById(EbmlMaster parent, byte[] typeId) { // Only EBML or Segment are allowed at top level if (parent == null && (Platform.arrayEqualsByte(EBML.id, typeId) || Platform.arrayEqualsByte(Segment.id, typeId))) return true; // Other EbmlBases at top level are not allowed if (parent == null) return false; // Void and CRC32 EbmlBases are global and are allowed everywhere in the hierarchy if (Platform.arrayEqualsByte(Void.id, typeId) || Platform.arrayEqualsByte(CRC32.id, typeId)) return true; // for any other EbmlBase we have to check the spec for(MKVType aCandidate : children.get(parent.type)) if (Platform.arrayEqualsByte(aCandidate.id, typeId)) return true; return false; } public static EbmlBase findFirst(EbmlBase master, MKVType[] path){ List<MKVType> tlist = new LinkedList<MKVType>(Arrays.asList(path)); return findFirstSub(master, tlist); } @SuppressWarnings("unchecked") public static <T> T findFirstTree(List<? extends EbmlBase> tree, MKVType[] path){ List<MKVType> tlist = new LinkedList<MKVType>(Arrays.asList(path)); for(EbmlBase e : tree){ EbmlBase z = findFirstSub(e, tlist); if (z != null) return (T) z; } return null; } private static EbmlBase findFirstSub(EbmlBase elem, List<MKVType> path) { if (path.size() == 0) return null; if (!elem.type.equals(path.get(0))) return null; if (path.size() == 1) return elem; MKVType head = path.remove(0); EbmlBase result = null; if (elem instanceof EbmlMaster) { Iterator<EbmlBase> iter = ((EbmlMaster) elem).children.iterator(); while(iter.hasNext() && result == null) result = findFirstSub(iter.next(), path); } path.add(0, head); return result; } public static <T> List<T> findList(List<? extends EbmlBase> tree, Class<T> class1, MKVType[] path) { List<T> result = new LinkedList<T>(); List<MKVType> tlist = new LinkedList<MKVType>(Arrays.asList(path)); if (tlist.size() > 0) for (EbmlBase node : tree) { MKVType head = tlist.remove(0); if (head == null || head.equals(node.type)) { findSubList(node, tlist, result); } tlist.add(0, head); } return result; } @SuppressWarnings("unchecked") private static <T> void findSubList(EbmlBase element, List<MKVType> path, Collection<T> result) { if (path.size() > 0) { MKVType head = path.remove(0); if (element instanceof EbmlMaster) { EbmlMaster nb = (EbmlMaster) element; for (EbmlBase candidate : nb.children) { if (head == null || head.equals(candidate.type)) { findSubList(candidate, path, result); } } } path.add(0, head); } else { result.add((T)element); } } @SuppressWarnings("unchecked") public static <T> T[] findAllTree(List<? extends EbmlBase> tree, Class<T> class1, MKVType[] path) { List<EbmlBase> result = new LinkedList<EbmlBase>(); List<MKVType> tlist = new LinkedList<MKVType>(Arrays.asList(path)); if (tlist.size() > 0) for (EbmlBase node : tree) { MKVType head = tlist.remove(0); if (head == null || head.equals(node.type)) { findSub(node, tlist, result); } tlist.add(0, head); } return result.toArray((T[]) Array.newInstance(class1, 0)); } @SuppressWarnings("unchecked") public static <T> T[] findAll(EbmlBase master, Class<T> class1, boolean ga, MKVType[] path) { List<EbmlBase> result = new LinkedList<EbmlBase>(); List<MKVType> tlist = new LinkedList<MKVType>(Arrays.asList(path)); if (!master.type.equals(tlist.get(0))) return result.toArray((T[]) Array.newInstance(class1, 0)); tlist.remove(0); findSub(master, tlist, result); return result.toArray((T[]) Array.newInstance(class1, 0)); } private static void findSub(EbmlBase master, List<MKVType> path, Collection<EbmlBase> result) { if (path.size() > 0) { MKVType head = path.remove(0); if (master instanceof EbmlMaster) { EbmlMaster nb = (EbmlMaster) master; for (EbmlBase candidate : nb.children) { if (head == null || head.equals(candidate.type)) { findSub(candidate, path, result); } } } path.add(0, head); } else { result.add(master); } } }
package org.myrobotlab.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Set; import org.apache.commons.codec.binary.Hex; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.myrobotlab.service.interfaces.I2CController; import org.slf4j.Logger; import com.google.gson.Gson; /** * * Esp8266_01 - This is the MyRobotLab Service for the ESP8266-01. The * ESP8266-01 is a small WiFi enabled device with limited number of i/o pins * This service makes it possible to use the ESP8266-01 and i2c devices * */ // TODO Ensure that only one instance of RasPi can execute on each RaspBerry PI public class Esp8266_01 extends Service implements I2CController { public static class I2CDeviceMap { public transient I2CControl control; public String serviceName; public String busAddress; public String deviceAddress; } class i2cParms { public String getBus() { return bus; } public void setBus(String bus) { this.bus = bus; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getWriteSize() { return writeSize; } public void setWriteSize(String writeSize) { this.writeSize = writeSize; } public String getReadSize() { return readSize; } public void setReadSize(String readSize) { this.readSize = readSize; } public String getBuffer() { return buffer; } public void setBuffer(String buffer) { this.buffer = buffer; } String bus; String device; String writeSize; String readSize; String buffer; } private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Esp8266_01.class); transient HttpClient httpclient; transient HashMap<String, I2CDeviceMap> i2cDevices = new HashMap<String, I2CDeviceMap>(); transient HashMap<String, String> i2cWriteData = new HashMap<String, String>(); String host = "192.168.1.99"; public static void main(String[] args) { LoggingFactory.init(Level.DEBUG); } public Esp8266_01(String n) { super(n); httpclient = HttpClientBuilder.create().build(); } @Override public void i2cWrite(I2CControl control, int busAddress, int deviceAddress, byte[] buffer, int size) { Gson gson = new Gson(); String stringBuffer = Hex.encodeHexString(buffer); i2cParms senddata = new i2cParms(); senddata.setBus(Integer.toString(busAddress)); senddata.setDevice(Integer.toString(deviceAddress)); senddata.setWriteSize(Integer.toString(size)); senddata.setReadSize("0"); senddata.setBuffer(stringBuffer); String method = "i2cWrite"; String url = "http://" + host + "/" + method; // log.info(url); HttpPost post = new HttpPost(url); StringEntity postingString = null; try { postingString = new StringEntity(gson.toJson(senddata)); } catch (UnsupportedEncodingException e) { Logging.logError(e); } // log.info(String.format("postingString: %s", postingString)); post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } int code = response.getStatusLine().getStatusCode(); // log.info(response.toString()); if (code == 200) { BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (UnsupportedOperationException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { Logging.logError(e); } // log.info(result.toString()); // JSONObject o = new JSONObject(result.toString()); } } @Override public int i2cRead(I2CControl control, int busAddress, int deviceAddress, byte[] buffer, int size) { Gson gson = new Gson(); i2cParms senddata = new i2cParms(); senddata.setBus(Integer.toString(busAddress)); senddata.setDevice(Integer.toString(deviceAddress)); senddata.setWriteSize("0"); senddata.setReadSize(Integer.toString(size)); String method = "i2cRead"; String url = "http://" + host + "/" + method; HttpPost post = new HttpPost(url); StringEntity postingString = null; try { postingString = new StringEntity(gson.toJson(senddata)); } catch (UnsupportedEncodingException e) { Logging.logError(e); } post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } int code = response.getStatusLine().getStatusCode(); // log.info(response.toString()); i2cParms returndata = null; if (code == 200) { BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (UnsupportedOperationException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { Logging.logError(e); } // log.info(result.toString()); Gson resultGson = new Gson(); returndata = resultGson.fromJson(result.toString(), i2cParms.class); // log.info(resultGson.fromJson(result.toString(), // i2cParms.class).toString()); log.info("bus {}, device {}, size {}, buffer {}", returndata.bus, returndata.device, returndata.readSize, returndata.buffer); } hexStringToArray(returndata.buffer, buffer); return size; } void hexStringToArray(String inBuffer, byte[] outArray) { // log.info(String.format("inBuffer %s",inBuffer)); for (int i = 0; i < outArray.length; i++) { String hex = "0x" + inBuffer.substring((i * 2), (i * 2) + 2); outArray[i] = (byte) (int) Integer.decode(hex); // log.info(String.format("in %s, outArray %d",hex,outArray[i])); } } /* * @Override public int i2cWriteRead(I2CControl control, int busAddress, int * deviceAddress, byte[] writeBuffer, int writeSize, byte[] readBuffer, int * readSize) { * * i2cWrite(control, busAddress, deviceAddress, writeBuffer, writeSize); * return i2cRead(control, busAddress, deviceAddress, readBuffer, readSize); } */ @Override public int i2cWriteRead(I2CControl control, int busAddress, int deviceAddress, byte[] writeBuffer, int writeSize, byte[] readBuffer, int readSize) { Gson gson = new Gson(); String stringBuffer = Hex.encodeHexString(writeBuffer); i2cParms senddata = new i2cParms(); senddata.setBus(Integer.toString(busAddress)); senddata.setDevice(Integer.toString(deviceAddress)); senddata.setWriteSize(Integer.toString(writeSize)); senddata.setReadSize(Integer.toString(readSize)); senddata.setBuffer(stringBuffer); String method = "i2cWriteRead"; String url = "http://" + host + "/" + method; // log.info(url); HttpPost post = new HttpPost(url); StringEntity postingString = null; try { postingString = new StringEntity(gson.toJson(senddata)); } catch (UnsupportedEncodingException e) { Logging.logError(e); } // log.info(String.format("postingString: %s", postingString)); post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } int code = response.getStatusLine().getStatusCode(); // log.info(response.toString()); i2cParms returndata = null; if (code == 200) { BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (UnsupportedOperationException e) { Logging.logError(e); } catch (IOException e) { Logging.logError(e); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { Logging.logError(e); } // log.info(result.toString()); Gson resultGson = new Gson(); returndata = resultGson.fromJson(result.toString(), i2cParms.class); // log.info(resultGson.fromJson(result.toString(), // i2cParms.class).toString()); log.info("bus {}, device {}, readSize {}, buffer {}", returndata.bus, returndata.device, returndata.readSize, returndata.buffer); } hexStringToArray(returndata.buffer, readBuffer); return Integer.decode(returndata.readSize); } public void setHost(String host) { this.host = host; } @Override public void attachI2CControl(I2CControl control) { // This part adds the service to the mapping between // busAddress||DeviceAddress // and the service name to be able to send data back to the invoker String key = String.format("%s.%s", control.getDeviceBus(), control.getDeviceAddress()); I2CDeviceMap devicedata = new I2CDeviceMap(); if (i2cDevices.containsKey(key)) { devicedata = i2cDevices.get(key); if (control.getName() != devicedata.serviceName) { log.error("Attach of {} failed: {} already exists on bus %s address {}", control.getName(), devicedata.serviceName, control.getDeviceBus(), control.getDeviceAddress()); } } else { devicedata.serviceName = control.getName(); devicedata.busAddress = control.getDeviceBus(); devicedata.deviceAddress = control.getDeviceAddress(); devicedata.control = control; i2cDevices.put(key, devicedata); control.attachI2CController(this); } } @Override public void detachI2CControl(I2CControl control) { // This method should delete the i2c device entry from the list of // I2CDevices // The order of the detach is important because the higher level service may // want to execute something that // needs this service to still be availabe String key = String.format("%s.%s", control.getDeviceBus(), control.getDeviceAddress()); if (i2cDevices.containsKey(key)) { log.info("detach : " + control.getName()); i2cDevices.remove(key); control.detachI2CController(this); } } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Esp8266_01.class.getCanonicalName()); meta.addDescription("ESP8266-01 service to communicate using WiFi and i2c"); meta.addCategory("i2c", "control"); meta.setSponsor("Mats"); // FIXME - add HttpClient as a peer .. and use its interface .. :) // then remove direct dependencies to httpcomponents ... // One HttpClient to Rule them all !! /* * Runtime currently includes these dependencies * meta.addDependency("org.apache.httpcomponents", "httpclient", "4.5.2"); * meta.addDependency("org.apache.httpcomponents", "httpcore", "4.4.6"); */ return meta; } @Override public Set<String> getAttached() { return i2cDevices.keySet(); } }
import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.SortedSet; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public final class RedisMock extends AbstractRedisMock { private RedisStringCache stringCache; private RedisListCache listCache; private RedisSetCache setCache; private RedisHashCache hashCache; private List<IRedisCache> caches; private Map<String, Timer> timers; public RedisMock() { stringCache = new RedisStringCache(); listCache = new RedisListCache(); setCache = new RedisSetCache(); hashCache = new RedisHashCache(); caches = new ArrayList<IRedisCache>(); caches.add(stringCache); caches.add(listCache); caches.add(setCache); caches.add(hashCache); timers = new HashMap<String, Timer>(); } /* IRedisKeys implementations */ @Override public synchronized Long del(String ... keys) { long deleted = 0L; String key; for (int idx = 0; idx < keys.length; idx += 1) { key = keys[idx]; for (IRedisCache cache : caches) { if (cache.exists(key)) { cache.remove(key); deleted += 1L; break; } } } return deleted; } @Override public synchronized Boolean exists(String key) { for (IRedisCache cache : caches) { if (cache.exists(key)) { return true; } } return false; } @Override public synchronized Boolean expire(String key, int seconds) { return this.pexpire(key, seconds*1000); } @Override public synchronized Boolean expireat(String key, long timestamp) { Date now = new Date(); return pexpire(key, timestamp*1000 - now.getTime()); } @Override public synchronized Boolean persist(String key) { if (exists(key) && timers.containsKey(key)) { timers.get(key).cancel(); timers.remove(key); return true; } return false; } @Override public synchronized Boolean pexpire(final String key, long milliseconds) { if (exists(key)) { Timer timer = new Timer(); timers.put(key, timer); timer.schedule(new TimerTask() { @Override public void run() { del(key); } }, milliseconds); return true; } return false; } @Override public synchronized Boolean pexpireat(String key, long timestamp) { Date now = new Date(); return this.pexpire(key, timestamp - now.getTime()); } @Override public synchronized String type(String key) { for (IRedisCache cache : caches) { if (cache.exists(key)) { return cache.type(); } } return "none"; } /* IRedisString implementations */ @Override public synchronized Long append(String key, String value) throws WrongTypeException { if (exists(key) && type(key) != "string") { throw new WrongTypeException(); } if (!exists(key)) { try { set(key, value); } catch (Exception e) {} } else { stringCache.set(key, stringCache.get(key) + value); } return strlen(key); } @Override public synchronized Long bitcount(String key, long ... options) throws WrongTypeException { if (!exists(key)) { return 0L; } if (exists(key) && type(key) != "string") { throw new WrongTypeException(); } String str = stringCache.get(key); long len = str.length(); long start = options.length > 0 ? options[0] : 0L; long end = options.length > 1 ? options[1] : len - 1; if (end >= len) { end = len - 1; } if (start < 0) { start = len + start; } if (end < 0) { end = len + end; } if (start > end) { return 0L; } long count = 0; // TODO: Slow bit-counting, do map to do fast bit counting; for (long idx = start; idx <= end; ++idx) { int n = Character.codePointAt(str, (int)idx); while (n != 0) { count += (n & 1); n >>= 1; } } return count; } @Override public synchronized Long bitop(String operation, String destkey, String ... keys) throws WrongTypeException, SyntaxErrorException { String[] strs = new String[keys.length]; int longest = 0; for (int idx = 0; idx < keys.length; ++idx) { String key = keys[idx]; if (!exists(key)) { strs[idx] = ""; continue; } if (exists(key) && type(key) != "string") { throw new WrongTypeException(); } strs[idx] = stringCache.get(key); if (longest < strs[idx].length()) { longest = strs[idx].length(); } } for (int idx = 0; idx < strs.length; ++idx) { while (strs[idx].length() < longest) { strs[idx] += "\0"; } } String s = strs[0]; for (int idx = 0; idx < strs.length; ++idx) { String str = strs[idx]; String cur = ""; for (int jdx = 0; jdx < longest; ++jdx) { int n = 0; if (operation == "and") { n = Character.codePointAt(s, jdx) & Character.codePointAt(str, jdx); } else if (operation == "or") { n = Character.codePointAt(s, jdx) | Character.codePointAt(str, jdx); } else if (operation == "xor") { // a XOR a = 0, so avoid XOR'ing the first string with itself. if (idx > 0) { n = Character.codePointAt(s, jdx) ^ Character.codePointAt(str, jdx); } else { n = Character.codePointAt(s, jdx); } } else if (operation == "not") { n = ~Character.codePointAt(s, jdx); } cur += (char)n; } s = cur; if (operation == "not") { break; } } set(destkey, s); return (long)s.length(); } @Override public synchronized Long bitpos(String key, long bit, long ... options) throws WrongTypeException, BitArgException { if (bit != 0L && bit != 1L) { throw new BitArgException(); } if (exists(key) && type(key) != "string") { throw new WrongTypeException(); } if (!exists(key)) { if (bit == 0L) { return 0L; } return -1L; } String value = stringCache.get(key); long len = (long)value.length(); long start = options.length > 0 ? options[0] : 0; long end = options.length > 1 ? options[1] : len - 1; boolean noend = !(options.length > 1); if (start < 0) { start = len + start; } if (end < 0) { end = len + start; } if (start > end) { return -1L; } long idx; for (idx = start; idx <= end; ++idx) { int ch = Character.codePointAt(value, (int)idx); int cnt = 0; while (cnt < 8) { if (bit == 0L && (ch & 0x80) != 0x80) { return (long)(idx)*8L + (long)cnt; } if (bit == 1L && (ch & 0x80) == 0x80) { return (long)(idx)*8L + (long)cnt; } ch <<= 1; cnt += 1; } } if (bit == 1) { return -1L; } if (bit == 0 && noend) { return (long)(idx)*8L; } return -1L; } @Override public synchronized String get(String key) throws WrongTypeException { if (!exists(key)) { return null; } if (!stringCache.exists(key)) { throw new WrongTypeException(); } return stringCache.get(key); } @Override public synchronized String set(String key, String value, String ... options) throws SyntaxErrorException { boolean nx = false, xx = false; int ex = -1; long px = -1; for (Object option : options) { } for (int idx = 0; idx < options.length; ++idx) { String option = options[idx]; if (option == "nx") { nx = true; } else if (option == "xx") { xx = true; } else if (option == "ex") { if (idx + 1 >= options.length) { throw new SyntaxErrorException(); } ex = Integer.parseInt(options[idx + 1]); } else if (option == "px") { if (idx + 1 >= options.length) { throw new SyntaxErrorException(); } px = Long.parseLong(options[idx + 1]); } } if (nx) { if (exists(key)) { return null; } } if (xx) { if (!exists(key)) { return null; } del(key); } if (!nx && !xx) { if (exists(key)) { del(key); } } stringCache.set(key, value); if (ex != -1) { expire(key, ex); } if (px != -1) { pexpire(key, px); } return "OK"; } @Override public synchronized Long strlen(String key) throws WrongTypeException { if (!exists(key)) { return 0L; } if (type(key) != "string") { throw new WrongTypeException(); } return (long)stringCache.get(key).length(); } /* IRedisList implementations */ @Override public synchronized Long lpush(String key, String element) throws WrongTypeException { if (exists(key) && type(key) != "list") { throw new WrongTypeException(); } listCache.set(key, element); return llen(key); } @Override public synchronized Long llen(String key) throws WrongTypeException { if (exists(key) && type(key) != "list") { throw new WrongTypeException(); } List<String> lst = listCache.get(key); Long len = 0L; int size = lst.size(); len += (long)size; if (size == Integer.MAX_VALUE) { // Hm, we may have _more_ elements, so count the rest. for (String elem : lst) { len += 1; } } return len; } }
package org.sanju.log.reader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URISyntaxException; import java.net.URL; /** * @author Sanju Thomas */ public class WebLogReader{ public static void main(final String[] args) throws URISyntaxException, IOException, InterruptedException { Authenticator.setDefault(new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication("admin", "admin".toCharArray()); } }); String uri = null; if(args.length == 1){ uri = args[0]; }else{ System.out.println("Usage : org.sanju.log.streamer.WebLogReader <<URL>>"); System.exit(0); } final URL uriObject = new URL(uri); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(uriObject.openStream())); while(true){ final String line = reader.readLine(); if(null == line){ Thread.sleep(1000); } System.out.println(line); } } finally{ if(null != reader) { reader.close(); } } } }
package org.scijava.script; import java.util.Collections; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import org.scijava.module.Module; import org.scijava.plugin.Plugin; import org.scijava.plugin.RichPlugin; import org.scijava.plugin.SingletonPlugin; import org.scijava.util.VersionUtils; public interface ScriptLanguage extends ScriptEngineFactory, RichPlugin, SingletonPlugin { /** True iff this language requires a compilation step. */ default boolean isCompiledLanguage() { return false; } /** * Performs any necessary conversion of an encoded object retrieved from the * language's script engine. * * @see ScriptEngine#get(String) */ default Object decode(final Object object) { // NB: No decoding by default. return object; } /** * Gets a helper object capable of generating autocomplete suggestions for a * code fragment. */ default AutoCompleter getAutoCompleter() { return new DefaultAutoCompleter(this); } // -- ScriptEngineFactory methods -- @Override default String getMethodCallSyntax(final String obj, final String m, final String... args) { throw new UnsupportedOperationException(); } @Override default String getOutputStatement(final String toDisplay) { throw new UnsupportedOperationException(); } @Override default String getProgram(final String... statements) { throw new UnsupportedOperationException(); } @Override default List<String> getExtensions() { return Collections.<String> emptyList(); } @Override default List<String> getNames() { return Collections.<String> singletonList(getEngineName()); } @Override default String getLanguageVersion() { return VersionUtils.getVersion(getClass()); } @Override default List<String> getMimeTypes() { return Collections.<String> emptyList(); } @Override default Object getParameter(final String key) { if (key.equals(ScriptEngine.ENGINE)) { return getEngineName(); } else if (key.equals(ScriptEngine.ENGINE_VERSION)) { return getEngineVersion(); } else if (key.equals(ScriptEngine.NAME)) { final List<String> list = getNames(); return list.size() > 0 ? list.get(0) : null; } else if (key.equals(ScriptEngine.LANGUAGE)) { return getLanguageName(); } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { return getLanguageVersion(); } return null; } @Override default String getEngineVersion() { return VersionUtils.getVersion(getClass()); } }
package org.wahlzeit.servlets; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import org.wahlzeit.handlers.*; import org.wahlzeit.model.*; import org.wahlzeit.services.*; import org.wahlzeit.webparts.*; /** * * @author dirkriehle * */ @MultipartConfig // Servlet 3.0 support for file upload public class MainServlet extends AbstractServlet { private static final long serialVersionUID = 42L; // any one does; class never serialized public void myGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); UserSession us = ensureUserSession(request); String link = request.getRequestURI(); int linkStart = link.lastIndexOf("/") + 1; int linkEnd = link.indexOf(".html"); if (linkEnd == -1) { linkEnd = link.length(); } link = link.substring(linkStart, linkEnd); UserLog.logUserInfo("requested", link); WebPageHandler handler = WebPartHandlerManager.getWebPageHandler(link); String newLink = PartUtil.DEFAULT_PAGE_NAME; if (handler != null) { Map args = getRequestArgs(request); SysLog.logSysInfo("GET arguments: " + getRequestArgsAsString(us, args)); newLink = handler.handleGet(us, link, args); } if (newLink.equals(link)) { // no redirect necessary WebPart result = handler.makeWebPart(us); us.addProcessingTime(System.currentTimeMillis() - startTime); configureResponse(us, response, result); us.clearSavedArgs(); // saved args go from post to next get us.resetProcessingTime(); } else { SysLog.logSysInfo("redirect", newLink); redirectRequest(response, newLink); us.addProcessingTime(System.currentTimeMillis() - startTime); } } public void myPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); UserSession us = ensureUserSession(request); String link = request.getRequestURI(); int linkStart = link.lastIndexOf("/") + 1; int linkEnd = link.indexOf(".form"); if (linkEnd != -1) { link = link.substring(linkStart, linkEnd); } else { link = PartUtil.NULL_FORM_NAME; } UserLog.logUserInfo("postedto", link); Map args = getRequestArgs(request); SysLog.logSysInfo("POST arguments: " + getRequestArgsAsString(us, args)); WebFormHandler formHandler = WebPartHandlerManager.getWebFormHandler(link); link = PartUtil.DEFAULT_PAGE_NAME; if (formHandler != null) { link = formHandler.handlePost(us, args); } redirectRequest(response, link); us.addProcessingTime(System.currentTimeMillis() - startTime); } protected Map getRequestArgs(HttpServletRequest request) throws IOException, ServletException { String contentType = request.getContentType(); if ((contentType != null) && contentType.startsWith("multipart/form-data")) { return getMultiPartRequestArgs(request); } else { return request.getParameterMap(); } } protected Map getMultiPartRequestArgs(HttpServletRequest request) throws IOException, ServletException { Map<String, String> result = new HashMap<String, String>(); Collection<Part> parts = request.getParts(); for (Iterator<Part> i = parts.iterator(); i.hasNext(); ) { Part part = i.next(); String key = part.getName(); if (key.equals("file")) { String tempFileName = SysConfig.getTempDir().asString() + Thread.currentThread().getId(); saveImgToDirectory(tempFileName, part.getInputStream()); result.put("fileName", tempFileName); } else { result.put(key, request.getParameter(key)); } } return result; } private void saveImgToDirectory(String filePath, InputStream imgStream) throws IOException { Files.copy(imgStream, Paths.get(filePath)); } }
package edu.unlv.sudo.checkers.model; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import edu.unlv.sudo.checkers.model.exception.InvalidMoveException; import edu.unlv.sudo.checkers.model.exception.OutOfTurnException; /** * This class represents the rules utilities for the checkers game. */ public final class Rules { /** * This method returns all the valid moves a {@link Piece} can make on the provided {@link Board}. * @param piece the {@link Piece} in question * @param board the {@link Board} on which the piece resides * @return the {@link Set} of valid {@link Location}s where the {@link Piece} can move */ public static Set<Location> getValidMoves(final Piece piece, final Board board) { final Set<Location> validMoves = new HashSet<>(); int moveY = 0; int jumpY = 0; //check for single moves if (piece.getTeam() == Team.BLACK) { moveY = 1; jumpY = 2; } else if (piece.getTeam() == Team.RED) { moveY = -1; jumpY = -2; } final int startX = piece.getLocation().getX(); final int startY = piece.getLocation().getY(); final Location moveNW = new Location(startX - 1, startY + moveY); final Location moveNE = new Location(startX + 1, startY + moveY); final Location moveSW = new Location(startX - 1, startY - moveY); final Location moveSE = new Location(startX + 1, startY - moveY); final Location jumpNW = new Location(startX - 2, startY + jumpY); final Location jumpNE = new Location(startX + 2, startY + jumpY); final Location jumpSW = new Location(startX - 2, startY - jumpY); final Location jumpSE = new Location(startX + 2, startY - jumpY); if (isSpaceOnBoard(moveNW, board) && board.getPieceAtLocation(moveNW) == null) { validMoves.add(moveNW); } if (isSpaceOnBoard(moveNE, board) && board.getPieceAtLocation(moveNE) == null) { validMoves.add(moveNE); } if (isSpaceOnBoard(moveSW, board) && board.getPieceAtLocation(moveSW) == null && piece.isKing()) { validMoves.add(moveSW); } if (isSpaceOnBoard(moveSE, board) && board.getPieceAtLocation(moveSE) == null && piece.isKing()) { validMoves.add(moveSE); } if (isSpaceOnBoard(jumpNW, board) && board.getPieceAtLocation(jumpNW) == null && board.getPieceAtLocation(moveNW) != null) { validMoves.add(jumpNW); } if (isSpaceOnBoard(jumpNE, board) && board.getPieceAtLocation(jumpNE) == null && board.getPieceAtLocation(moveNE) != null) { validMoves.add(jumpNE); } if (isSpaceOnBoard(jumpSW, board) && board.getPieceAtLocation(jumpSW) == null && board.getPieceAtLocation(moveSW) != null && piece.isKing()) { validMoves.add(jumpSW); } if (isSpaceOnBoard(jumpSE, board) && board.getPieceAtLocation(jumpSE) == null && board.getPieceAtLocation(moveSE) != null && piece.isKing()) { validMoves.add(jumpSE); } return validMoves; } /** * Determine if the provided {@link Location} is on the {@link Board}. * @param location the {@link Location} to check * @param board the {@link Board} to check against * @return true if and only if the {@link Location} is on the {@link Board} */ public static boolean isSpaceOnBoard(final Location location, final Board board) { return location.getX() >= 0 && location.getX() < board.getSpacesPerSide() && location.getY() >= 0 && location.getY() < board.getSpacesPerSide(); } /** * Determine if the proposed new move is valid. * @param piece the {@link Piece} making the moves * @param previousMoves the {@link Set} of previous moves the piece has made * @param move the new move to determine if valid * @param board the {@link Board} on which the moves are taking place * @return true if the new move is valid */ public static boolean isValidMove(final Piece piece, final List<Location> previousMoves, final Location move, final Board board) { final Piece theoreticalPiece; if (previousMoves.size() > 0) { final Location previousLocation = previousMoves.get(previousMoves.size() - 1); final Location prevPrevLocation = previousMoves.size() > 1 ? previousMoves.get(previousMoves.size() - 2) : piece.getLocation(); if (!isJump(previousLocation, move) || !isJump(prevPrevLocation, previousLocation)) { return false; } theoreticalPiece = new Piece(piece.getTeam(), previousLocation); } else { theoreticalPiece = piece; } return getValidMoves(theoreticalPiece, board).contains(move); } /** * Determine if a move is a jump. * @param location the {@link Location} of the start * @param move the {@link Location} being moved to * @return true if the move is a jump */ public static boolean isJump(final Location location, final Location move) { return Math.abs(move.getX() - location.getX()) > 1; } /** * Move a {@link Piece} in a {@link Game}. * @param game the {@link Game} in which to move the piece * @param piece the {@link Piece} to move in the game * @param moves the {@link Set} of moves the piece will make */ public static void move(final Game game, final Piece piece, final List<Location> moves) { if (piece.getTeam() != game.getTurn()) { throw new OutOfTurnException(game.getTurn(), piece.getTeam()); } for (Location location : moves) { if (!Rules.getValidMoves(piece, game.getBoard()).contains(location)) { throw new InvalidMoveException(piece, location); } final Iterator<Piece> iterator = game.getBoard().getPieces().iterator(); while (iterator.hasNext()) { final Piece jumped = iterator.next(); if (jumped.getLocation().isBetween(piece.getLocation(), location)) { iterator.remove(); } } piece.setLocation(location); if (piece.getTeam() == Team.RED) { if (piece.getLocation().getY() == game.getBoard().getSpacesPerSide() - 1) { piece.makeKing(); } } else if (piece.getTeam() == Team.BLACK) { if (piece.getLocation().getY() == 0) { piece.makeKing(); } } } } /** * A private constructor to prevent instantiation of this utility class. */ private Rules() { } }
package seedu.address.commons.core; import java.util.Objects; import java.util.logging.Level; /** * Config values used by the app */ public class Config { public static final String DEFAULT_CONFIG_FILE = "config.json"; // Config values customizable through config file private String appTitle = "Doit"; private Level logLevel = Level.INFO; private String userPrefsFilePath = "preferences.json"; private String addressBookFilePath = "data/addressbook.xml"; private String addressBookName = "MyAddressBook"; public String getAppTitle() { return appTitle; } public void setAppTitle(String appTitle) { this.appTitle = appTitle; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getUserPrefsFilePath() { return userPrefsFilePath; } public void setUserPrefsFilePath(String userPrefsFilePath) { this.userPrefsFilePath = userPrefsFilePath; } public String getAddressBookFilePath() { return addressBookFilePath; } public void setAddressBookFilePath(String addressBookFilePath) { this.addressBookFilePath = addressBookFilePath; } public String getAddressBookName() { return addressBookName; } public void setAddressBookName(String addressBookName) { this.addressBookName = addressBookName; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Config)) { //this handles null as well. return false; } Config o = (Config) other; return Objects.equals(appTitle, o.appTitle) && Objects.equals(logLevel, o.logLevel) && Objects.equals(userPrefsFilePath, o.userPrefsFilePath) && Objects.equals(addressBookFilePath, o.addressBookFilePath) && Objects.equals(addressBookName, o.addressBookName); } @Override public int hashCode() { return Objects.hash(appTitle, logLevel, userPrefsFilePath, addressBookFilePath, addressBookName); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("App title : " + appTitle); sb.append("\nCurrent log level : " + logLevel); sb.append("\nPreference file Location : " + userPrefsFilePath); sb.append("\nLocal data file location : " + addressBookFilePath); sb.append("\nTaskManager name : " + addressBookName); return sb.toString(); } }
package seedu.address.logic.parser; import seedu.address.logic.commands.*; import seedu.address.commons.util.StringUtil; import seedu.address.commons.exceptions.IllegalValueException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" // + " (?<isPhonePrivate>p?)p/(?<phone>[^/]+)" // + " (?<isEmailPrivate>p?)e/(?<email>[^/]+)" // + " (?<isAddressPrivate>p?)a/(?<address>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags public Parser() { } /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case UpdateCommand.COMMAND_WORD: return prepareUpdate(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args) { final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return new AddCommand(matcher.group("name"), // matcher.group("phone"), // matcher.group("email"), // matcher.group("address"), getTagsFromArgs(matcher.group("tagArguments"))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete task command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the select task command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned * integer is given as the index. Returns an {@code Optional.empty()} * otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the update task command. * * @param args full command args string * @return the prepared command */ private Command prepareUpdate(String args) { Matcher matcher = BASIC_COMMAND_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE)); } int index=Integer.parseInt(matcher.group("commandWord")); matcher = TASK_DATA_ARGS_FORMAT.matcher(matcher.group("arguments")); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE)); } try { if (matcher.group("tagArguments").isEmpty()) { } return new UpdateCommand(index, matcher.group("name"), getTagsFromArgs(matcher.group("tagArguments"))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the find task command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } }
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.StringUtil; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.DoneCommand; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.SelectCommand; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern PERSON_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern PERSON_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "( d/(?<description>[^/]+)){0,1}" + "( date/(?<date>[^/]+)){0,1}" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags private static final Pattern EDIT_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<index>[\\d]+)" + "( (?<name>[^/]+)){0,1}" + "( d/(?<description>[^/]+)){0,1}" + "( date/(?<date>[^/]*)){0,1}" // group <date> can be blank to edit DatedTask -> UndatedTask + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DoneCommand.COMMAND_WORD: return prepareDone(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return prepareList(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add person command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher = PERSON_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return new AddCommand( matcher.group("name"), matcher.group("description"), matcher.group("date"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new person's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete person command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the done task command. * * @param args full command args string * @return the prepared command */ private Command prepareDone(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DoneCommand(index.get()); } /** * Parses arguments in the context of the edit person command. * * @param args full command args string * @return the prepared command */ private Command prepareEdit(String args) { final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { return new EditCommand( Integer.parseInt(matcher.group("index")), matcher.group("name"), matcher.group("description"), matcher.group("date"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the select person command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = PERSON_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find person command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } /** * Parses arguments in the context of the list task command. * * @param args full command args string * @return the prepared command */ private Command prepareList(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } final String[] keywords = matcher.group("keywords").split("\\s+"); if (keywords.length > 1) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } try { return new ListCommand(keywords[0]); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } }
package seedu.forgetmenot.model.task; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.forgetmenot.commons.exceptions.IllegalValueException; import seedu.forgetmenot.logic.parser.DatePreParse; //@@author A0147619W /** * Represents a Task's time in the task manager. * Guarantees: immutable; is valid as declared in {@link #isValidStart(String)} */ public class Time { public static final String MESSAGE_TIME_CONSTRAINTS = "Invalid Time!"; public static final String MESSAGE_INCORRECT_DATE_FORMAT = "The date provided is invalid. Follow the dd/mm/yy format and make sure a valid date is provided"; private static final String DEFAULT_DATE = "Thu Jan 01 07:30:00 SGT 1970"; public Calendar time; public Time(String input) throws IllegalValueException { input = input.trim(); if (input.equals("") || input.equals(new Date(0).toString())) { System.out.println("a blank string was detected"); time = Calendar.getInstance(); time.setTime(new Date(0)); } // System.out.println("CHEEYEO CHECK HERE : " + input); // if (input.equals("-")) // input = ""; // if (input.equals(DEFAULT_DATE)) // input = ""; // if (input.equals(new Date(0))) // input = ""; // if (input.equals((new Date(0)).toString())) // input = ""; time = Calendar.getInstance(); if(input.contains("/")) { if(!isValidDate(input)) { throw new IllegalValueException(MESSAGE_INCORRECT_DATE_FORMAT); } } String taskTime = DatePreParse.preparse(input); if(!taskTime.isEmpty() && !taskTime.equals(new Date(0).toString())){ List<DateGroup> dates = new Parser().parse(taskTime); // Using the Natty Parser() if(dates.isEmpty()){ System.out.println("CHEEYEO LOOK HERE taskTime: " + taskTime + " && input: " + input); throw new IllegalValueException(MESSAGE_TIME_CONSTRAINTS); } else if(dates.get(0).getDates().isEmpty()){ throw new IllegalValueException(MESSAGE_TIME_CONSTRAINTS); } else{ time.setTime(dates.get(0).getDates().get(0)); } } else{ time.setTime(new Date(0)); } } /** * * @return true if the time parameter is missing */ public boolean isMissing() { return time.getTime().toString().equalsIgnoreCase(DEFAULT_DATE); } public String appearOnUIFormat() { if(time.getTime().equals(new Date(0))) { return ""; } else { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy h:mm a"); return dateFormat.format(time.getTime()); } } //@@author /** * @return a String for a date and time thats easy to read. Example, "Thu, Feb 17, 2016, 10:11 AM" * @@author A0139671X */ public String easyReadDateFormatForUI() { if(time.getTime().equals(new Date(0))) { return "-"; } else { SimpleDateFormat dateFormatter = new SimpleDateFormat("E, MMM d, yyyy, hh:mm a"); return dateFormatter.format(time.getTime()); } } //@@author A0139198N public String appearOnUIFormatForDate() { if(time.getTime().equals(new Date(0))) { return "-"; } else { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); return dateFormat.format(time.getTime()); } } public boolean isToday(String date) { Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); if (date.equals(dateFormat.format(cal.getTime()))){ return true; } return false; } public boolean isTomorrow(String date) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); if(date.equals(dateFormat.format(cal.getTime()))) { return true; } return false; } public boolean isUpcoming(String date) { Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); String d0 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d1 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d2 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d3 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d4 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d5 = dateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 1); String d6 = dateFormat.format(cal.getTime()); if (date.equals(d0) || date.equals(d1) || date.equals(d2) || date.equals(d3) || date.equals(d4) || date.equals(d5) || date.equals(d6)) { return true; } return false; } //@@author //@@author A0147619W /** * * @param token * @return true if the given date is a valid date */ public static boolean isValidDate(String token) { String[] date = token.split(" "); Pattern dateType = Pattern.compile("(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/(\\d\\d)"); for(String input: date) { if(input.contains("/")) { token = input; break; } } Matcher matcher = dateType.matcher(token); if(!matcher.matches()){ return false; } else { int day = Integer.parseInt(matcher.group(1)); int month = Integer.parseInt(matcher.group(2)); int year = Integer.parseInt(matcher.group(3)); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return day < 32; case 4: case 6: case 9: case 11: return day < 31; case 2: if (year % 4 == 0) return day < 30; //its a leap year else return day < 29; default: break; } return false; } } public static boolean checkOrderOfDates(String time1, String time2) throws IllegalValueException { Time start = new Time(time1); Time end = new Time(time2); return end.isMissing() || start.time.compareTo(end.time) <= 0; } public static boolean checkOrderOfTime(Time firstTime, Time secondTime) { return firstTime.time.compareTo(secondTime.time) <= 0; } public static boolean taskTimeisAfterCurrentTime(String checkTime) throws IllegalValueException { Time now = new Time("today"); Time time = new Time(checkTime); return time.isMissing() || time.time.compareTo(now.time) >= 0; } @Override public String toString() { SimpleDateFormat dateFormatter = new SimpleDateFormat("E, MMM d, yyyy, hh:mm a"); if(time.getTime().equals(new Date(0))) { return dateFormatter.format(new Date(0)); } else return dateFormatter.format(time.getTime()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (this.time != null && ((Time)other).time != null) && (other instanceof Time // instanceOf handles nulls && this.time.equals(((Time) other).time)); // state check } @Override public int hashCode() { return time.hashCode(); } }
package seedu.malitio.logic.parser; import seedu.malitio.commons.exceptions.IllegalValueException; import seedu.malitio.commons.util.StringUtil; import seedu.malitio.logic.commands.*; import static seedu.malitio.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.malitio.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>)[e|d|f|E|D|F]\\d+"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags private static final Pattern EDIT_DATA_ARGS_FORMAT = Pattern.compile("(?<targetIndex>[e|d|f|E|D|F]\\d+)" + "(?<name>(?:\\s[^/]+)?)" + "(?<tagArguments>(?: t/[^/]+)*)"); private static final Pattern COMPLETE_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>[d|f|D|F]\\d+)"); private static final Set<String> TYPES_OF_TASKS = new HashSet<String>(Arrays.asList("f", "d", "e" )); public static final String MESSAGE_MISSING_START_END = "Expecting start and end times\nExample: start thursday 800 end thursday 900"; public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case CompleteCommand.COMMAND_WORD: return prepareComplete(arguments); case UncompleteCommand.COMMAND_WORD: return prepareUncomplete(arguments); case MarkCommand.COMMAND_WORD: return prepareMark(arguments); case UnmarkCommand.COMMAND_WORD: return prepareUnmark(arguments); case ClearCommand.COMMAND_WORD: return prepareClear(arguments); case ListAllCommand.COMMAND_WORD: return new ListAllCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return prepareList(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case UndoCommand.COMMAND_WORD: return new UndoCommand(); case RedoCommand.COMMAND_WORD: return new RedoCommand(); case SaveCommand.COMMAND_WORD: return prepareSave(arguments); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } //@@author a0126633j /** * Parses arguments in the context of the clear command. Also checks validity of arguments */ private Command prepareClear(String arguments) { if (!Arrays.asList(ClearCommand.VALID_ARGUMENTS).contains(arguments.trim().toLowerCase())) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ClearCommand.MESSAGE_USAGE)); } return new ClearCommand(arguments.trim().toLowerCase()); } /** * Parses arguments in the context of the save command. Also ensure the argument is not empty */ private Command prepareSave(String arguments) { if (arguments.trim().isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE)); } return new SaveCommand(arguments.trim()); } //@@author /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command * @@author A0153006W */ private Command prepareAdd(String args){ final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim()); boolean hasStart = false; boolean hasEnd = false; // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { String name = matcher.group("name"); String deadline = getDeadlineFromArgs(StringUtil.removeTagsFromString(name)); String start = getStartFromArgs(StringUtil.removeTagsFromString(name)); if (!start.isEmpty()) { name = name.substring(0, name.lastIndexOf("start")).trim(); hasStart = true; } String end = getEndFromArgs(StringUtil.removeTagsFromString(args)); if (!end.isEmpty()) { hasEnd = true; } if (!deadline.isEmpty()) { name = name.substring(0, name.lastIndexOf("by")).trim(); } if (!deadline.isEmpty() && !hasStart && !hasEnd) { return new AddCommand( name, deadline, getTagsFromArgs(matcher.group("tagArguments")) ); } else if (hasStart && hasEnd) { return new AddCommand( name, start, end, getTagsFromArgs(matcher.group("tagArguments")) ); } else if (hasStart ^ hasEnd) { return new IncorrectCommand(MESSAGE_MISSING_START_END); } return new AddCommand( name, getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author A0129595N /** * Parses arguments in the context of the edit task command. * * @param arguments * @return the prepared command */ private Command prepareEdit(String args) { final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { String index = parseIndex(matcher.group("targetIndex")); if (index.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); String name = matcher.group("name"); System.out.println(name); if (name.equals("") && getTagsFromArgs(matcher.group("tagArguments")).isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } String deadline = getDeadlineFromArgs(name); if (!deadline.isEmpty()) { name = name.replaceAll(" by " + deadline, ""); } String start = getStartFromArgs(name); if (!start.isEmpty()) { name = name.replaceAll(" start " + start, ""); } String end = getEndFromArgs(name); if (!end.isEmpty()) { name = name.replaceAll(" end " + end, ""); } name = name.trim(); return new EditCommand( taskType, taskNum, name, deadline, start, end, getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author A0122460W /** * Parses arguments in the context of the complete task command. * * @param args full command args string * @return the prepared command */ private Command prepareComplete(String args) { final Matcher matcher = COMPLETE_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE)); } try { String index = parseIndex(matcher.group("targetIndex")); if (index.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); return new CompleteCommand(taskType,taskNum); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the uncomplete task command. * * @param args full command args string * @return the prepared command */ private Command prepareUncomplete(String args) { final Matcher matcher = COMPLETE_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UncompleteCommand.MESSAGE_USAGE)); } try { String index = parseIndex(matcher.group("targetIndex")); if (index.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UncompleteCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); return new UncompleteCommand(taskType,taskNum); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author /** * Parses arguments in the context of the delete task command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { String index = parseIndex(args); if(index.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); return new DeleteCommand(Character.toString(taskType), taskNum); } /** * Parses arguments in the context of the mark task command. * * @param args full command args string * @return the prepared command */ private Command prepareMark(String args) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE)); } String index = parseIndex(args); if (index.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); return new MarkCommand(taskType, taskNum); } /** * Parses arguments in the context of the unmark task command. * * @param args full command args string * @return the prepared command */ private Command prepareUnmark(String args) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE)); } String index = parseIndex(args); if (index.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE)); } char taskType = index.charAt(0); int taskNum = Integer.parseInt(index.substring(1)); return new UnmarkCommand(taskType, taskNum); } /** * Parses arguments in the context of the find task command. * * @param args full command args string * @return the prepared command * @@author */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace String[] keywords = matcher.group("keywords").split("\\s+"); String typeOfTask = ""; if(TYPES_OF_TASKS.contains(keywords[0])) { typeOfTask = keywords[0]; keywords = removeFirstFromArray(keywords); } if (keywords.length < 1) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(typeOfTask, keywordSet); } //@@author a0126633j private String[] removeFirstFromArray(String[] arg) { String[] result = new String[arg.length - 1]; for(int i = 1; i < arg.length; i++) { result[i - 1] = arg[i]; } return result; } /** * Parses arguments in the context of the list task command. * * @param args full command args string * @return the prepared command * @@author A0153006W */ private Command prepareList(String args) { if (args.isEmpty()) { return new ListCommand(); } try { args = args.trim().toLowerCase(); return new ListCommand(args); } catch (IllegalValueException ive) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } } /** * Returns the specified index as a String in the {@code command} */ private String parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return ""; } String index = command.trim().toLowerCase(); return index; } /** * Extracts the task's deadline from the command's arguments string. */ private static String getDeadlineFromArgs(String args) throws IllegalValueException { int byIndex = args.lastIndexOf(" by "); String deadline = ""; if(byIndex >= 0 && byIndex < args.length() - 4) { deadline = args.substring(byIndex + 4); } return deadline; } /** * Extracts the task's event start from the command's arguments string. */ private static String getStartFromArgs(String args) throws IllegalValueException { int startIndex = args.lastIndexOf(" start "); int endIndex = args.lastIndexOf(" end"); if (startIndex >= 0 && endIndex > 0) { return args.substring(startIndex + 7, endIndex); } else if (startIndex >= 0 && endIndex < 0) { return args.substring(startIndex + 7); } else { return ""; } } /** * Extracts the task's event end from the command's arguments string. */ private static String getEndFromArgs(String args) throws IllegalValueException { int endIndex = args.lastIndexOf(" end "); if (endIndex >= 0) { return args.substring(endIndex + 5); } else { return ""; } } /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. * @@author */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } }
package seedu.taskitty.model; import javafx.collections.transformation.FilteredList; import seedu.taskitty.commons.core.ComponentManager; import seedu.taskitty.commons.core.LogsCenter; import seedu.taskitty.commons.core.UnmodifiableObservableList; import seedu.taskitty.commons.events.model.TaskManagerChangedEvent; import seedu.taskitty.commons.util.StringUtil; import seedu.taskitty.model.task.ReadOnlyTask; import seedu.taskitty.model.task.Task; import seedu.taskitty.model.task.UniqueTaskList; import seedu.taskitty.model.task.UniqueTaskList.DuplicateMarkAsDoneException; import seedu.taskitty.model.task.UniqueTaskList.TaskNotFoundException; import java.time.LocalDate; import java.util.Set; import java.util.Stack; import java.util.function.Predicate; import java.util.logging.Logger; /** * Represents the in-memory model of the task manager data. * All changes to any model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private final TaskManager taskManager; private final FilteredList<Task> allTasks; private FilteredList<Task> filteredTodos; private FilteredList<Task> filteredDeadlines; private FilteredList<Task> filteredEvents; private final Stack<ReadOnlyTaskManager> historyTaskManagers; private final Stack<String> historyCommands; private final Stack<Predicate> historyPredicates; /** * Initializes a ModelManager with the given TaskManager * TaskManager and its variables should not be null */ public ModelManager(TaskManager src, UserPrefs userPrefs) { super(); assert src != null; assert userPrefs != null; logger.fine("Initializing with task manager: " + src + " and user prefs " + userPrefs); taskManager = new TaskManager(src); allTasks = new FilteredList<>(taskManager.getAllTasks()); filteredTodos = new FilteredList<>(taskManager.getFilteredTodos()); filteredDeadlines = new FilteredList<>(taskManager.getFilteredDeadlines()); filteredEvents = new FilteredList<>(taskManager.getFilteredEvents()); historyTaskManagers = new Stack<ReadOnlyTaskManager>(); historyCommands = new Stack<String>(); historyPredicates = new Stack<Predicate>(); } public ModelManager() { this(new TaskManager(), new UserPrefs()); } public ModelManager(ReadOnlyTaskManager initialData, UserPrefs userPrefs) { taskManager = new TaskManager(initialData); allTasks = new FilteredList<>(taskManager.getAllTasks()); filteredTodos = new FilteredList<>(taskManager.getFilteredTodos()); filteredDeadlines = new FilteredList<>(taskManager.getFilteredDeadlines()); filteredEvents = new FilteredList<>(taskManager.getFilteredEvents()); historyTaskManagers = new Stack<ReadOnlyTaskManager>(); historyCommands = new Stack<String>(); historyPredicates = new Stack<Predicate>(); } @Override public void resetData(ReadOnlyTaskManager newData) { taskManager.resetData(newData); indicateTaskManagerChanged(); } @Override public ReadOnlyTaskManager getTaskManager() { return taskManager; } /** Raises an event to indicate the model has changed */ private void indicateTaskManagerChanged() { raise(new TaskManagerChangedEvent(taskManager)); } @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { taskManager.removeTask(target); updateFilters(); indicateTaskManagerChanged(); } @Override public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException { taskManager.addTask(task); updateFilters(); updateFilteredListToShowAll(); indicateTaskManagerChanged(); } public synchronized String undo() { resetData(historyTaskManagers.pop()); updateFilteredTaskList(historyPredicates.pop()); return historyCommands.pop(); } private void updateFilters() { filteredTodos = new FilteredList<>(taskManager.getFilteredTodos()); filteredDeadlines = new FilteredList<>(taskManager.getFilteredDeadlines()); filteredEvents = new FilteredList<>(taskManager.getFilteredEvents()); } public synchronized void saveState(String command) { historyTaskManagers.push(new TaskManager(taskManager)); historyCommands.push(command); historyPredicates.push(filteredTodos.getPredicate()); } public synchronized void removeUnchangedState() { historyTaskManagers.pop(); historyPredicates.pop(); } @Override public synchronized void doneTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException, DuplicateMarkAsDoneException{ taskManager.doneTask(target); updateFilteredListToShowAll(); indicateTaskManagerChanged(); } @Override public synchronized void editTask(ReadOnlyTask target, Task task, int index) throws UniqueTaskList.TaskNotFoundException, UniqueTaskList.DuplicateTaskException { taskManager.removeTask(target); indicateTaskManagerChanged(); taskManager.addTask(task, index); updateFilteredListToShowAll(); indicateTaskManagerChanged(); } @Override public UnmodifiableObservableList<ReadOnlyTask> getTaskList() { return new UnmodifiableObservableList<>(allTasks); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTodoList() { return new UnmodifiableObservableList<>(filteredTodos); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredDeadlineList() { return new UnmodifiableObservableList<>(filteredDeadlines); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredEventList() { return new UnmodifiableObservableList<>(filteredEvents); } @Override public void updateFilteredListToShowAll() { allTasks.setPredicate(null); filteredTodos.setPredicate(null); filteredDeadlines.setPredicate(null); filteredEvents.setPredicate(null); } @Override public void updateFilteredTaskList(Set<String> keywords){ updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords))); } @Override public void updateFilteredDoneList() { updateFilteredTaskList(new PredicateExpression(p -> p.getIsDone() == true)); } @Override public void updateFilteredDateTaskList(LocalDate date, boolean hasDate) { allTasks.setPredicate(p -> p.isTodo() || (p.isDeadline() && !p.getEndDate().getDate().isAfter(date)) || (p.isEvent() && !(p.getEndDate().getDate().isBefore(date) || p.getStartDate().getDate().isAfter(date)))); filteredTodos.setPredicate(null); if (hasDate) { filteredDeadlines.setPredicate(p -> p.isDeadline() && !p.getEndDate().getDate().isAfter(date)); } filteredEvents.setPredicate(p -> p.isEvent() && !(p.getEndDate().getDate().isBefore(date) || p.getStartDate().getDate().isAfter(date))); } private void updateFilteredTaskList(Expression expression) { allTasks.setPredicate(expression::satisfies); filteredTodos.setPredicate(expression::satisfies); filteredDeadlines.setPredicate(expression::satisfies); filteredEvents.setPredicate(expression::satisfies); } private void updateFilteredTaskList(Predicate previousPredicate) { allTasks.setPredicate(previousPredicate); filteredTodos.setPredicate(previousPredicate); filteredDeadlines.setPredicate(previousPredicate); filteredEvents.setPredicate(previousPredicate); } interface Expression { boolean satisfies(ReadOnlyTask person); String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask person) { return qualifier.run(person); } @Override public String toString() { return qualifier.toString(); } } interface Qualifier { boolean run(ReadOnlyTask person); String toString(); } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; NameQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; } @Override public boolean run(ReadOnlyTask person) { return nameKeyWords.stream() .filter(keyword -> StringUtil.containsIgnoreCase(person.getName().fullName, keyword)) .findAny() .isPresent(); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } }
package seedu.tasklist.model; import javafx.collections.transformation.FilteredList; import seedu.tasklist.commons.core.Config; import seedu.tasklist.commons.core.ComponentManager; import seedu.tasklist.commons.core.LogsCenter; import seedu.tasklist.commons.core.UnmodifiableObservableList; import seedu.tasklist.commons.events.model.TaskListChangedEvent; import seedu.tasklist.commons.exceptions.IllegalValueException; import seedu.tasklist.logic.commands.UndoCommand; import seedu.tasklist.model.tag.UniqueTagList; import seedu.tasklist.model.task.EndTime; import seedu.tasklist.model.task.Priority; import seedu.tasklist.model.task.ReadOnlyTask; import seedu.tasklist.model.task.StartTime; import seedu.tasklist.model.task.Task; import seedu.tasklist.model.task.TaskDetails; import seedu.tasklist.model.task.UniqueTaskList; import seedu.tasklist.model.task.UniqueTaskList.DuplicateTaskException; import seedu.tasklist.model.task.UniqueTaskList.TaskNotFoundException; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.time.DateUtils; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; /** * Represents the in-memory model of the task list data. All changes to any * model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private static final int MAXIMUM_UNDO_REDO_SIZE = 3; public static LinkedList<UndoInfo> undoStack = new LinkedList<UndoInfo>(); public static LinkedList<UndoInfo> redoStack = new LinkedList<UndoInfo>(); private final TaskList taskList; private final FilteredList<Task> filteredTasks; private final TaskCounter taskCounter; /** * Initializes a ModelManager with the given TaskList TaskList and its * variables should not be null */ public ModelManager(TaskList src, UserPrefs userPrefs) { super(); assert src != null; assert userPrefs != null; logger.fine("Initializing with tasklist: " + src + " and user prefs " + userPrefs); taskList = new TaskList(src); filteredTasks = new FilteredList<>(taskList.getTasks()); taskCounter = new TaskCounter(src); } public ModelManager() { this(new TaskList(), new UserPrefs()); } public ModelManager(ReadOnlyTaskList initialData, UserPrefs userPrefs) { taskList = new TaskList(initialData); filteredTasks = new FilteredList<>(taskList.getTasks()); taskCounter = new TaskCounter(initialData); } @Override public void resetData(ReadOnlyTaskList newData) { if (newData.isEmpty()) { // clear or redo clear was executed List<Task> listOfTasks = (List<Task>) (List<?>) taskList.getTaskList(); addToUndoStack(UndoCommand.CLR_CMD_ID, null, listOfTasks.toArray(new Task[listOfTasks.size()])); } taskList.resetData(newData); indicateTaskListChanged(); clearRedoStack(); } private void clearRedoStack() { redoStack.clear(); } @Override public void clearTaskUndo(ArrayList<Task> tasks) throws TaskNotFoundException { TaskList oldTaskList = new TaskList(); oldTaskList.setTasks(tasks); taskList.resetData(oldTaskList); } @Override public ReadOnlyTaskList getTaskList() { return taskList; } @Override public TaskCounter getTaskCounter(){ return taskCounter; } /** Raises an event to indicate the model has changed */ private void indicateTaskListChanged() { raise(new TaskListChangedEvent(taskList)); } @Override public void deleteTaskUndo(ReadOnlyTask target) throws TaskNotFoundException { taskList.removeTask(target); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); } @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { taskList.removeTask(target); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.DEL_CMD_ID, null, (Task) target); clearRedoStack(); } @Override public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException { taskList.addTask(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.ADD_CMD_ID, null, task); clearRedoStack(); } @Override public boolean isOverlapping(Task task) { return taskList.isOverlapping(task); } @Override public void addTaskUndo(Task task) throws UniqueTaskList.DuplicateTaskException { taskList.addTask(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); } @Override public synchronized void updateTask(Task taskToUpdate, TaskDetails taskDetails, String startTime, String endTime, Priority priority, UniqueTagList tags, String frequency) throws IllegalValueException { Task originalTask = new Task(taskToUpdate); taskList.updateTask(taskToUpdate, taskDetails, startTime, endTime, priority, frequency); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.UPD_CMD_ID, null, taskToUpdate, originalTask); clearRedoStack(); } @Override public void updateTaskUndo(Task taskToUpdate, TaskDetails taskDetails, StartTime startTime, EndTime endTime, Priority priority, UniqueTagList tags, String frequency) throws IllegalValueException { taskList.updateTask(taskToUpdate, taskDetails, startTime, endTime, priority, frequency); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); } @Override public synchronized void markTaskAsComplete(ReadOnlyTask task) throws TaskNotFoundException { taskList.markTaskAsComplete(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.DONE_CMD_ID, null, (Task) task); clearRedoStack(); } @Override public synchronized void markTaskAsIncomplete(ReadOnlyTask task) throws TaskNotFoundException { taskList.markTaskAsIncomplete(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); } @Override public void addToUndoStack(int undoID, String filePath, Task... tasks) { if (undoStack.size() == MAXIMUM_UNDO_REDO_SIZE) { undoStack.remove(undoStack.size() - 1); } UndoInfo undoInfo = new UndoInfo(undoID, filePath, tasks); undoStack.push(undoInfo); } @Override public void updateFilteredListToShowPriority(String priority) { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new PriorityQualifier(priority))); } @Override public void updateFilteredListToShowDate(String date) { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new DateQualifier(date))); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() { return new UnmodifiableObservableList<>(filteredTasks); } public UnmodifiableObservableList<Task> getListOfTasks() { return new UnmodifiableObservableList<>(filteredTasks); } @Override public void updateFilteredListToShowAll() { sortByDateAndPriority(); filteredTasks.setPredicate(null); } @Override public void updateFilteredListToShowIncomplete() { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new DefaultDisplayQualifier())); } public void updateFilteredList() { updateFilteredListToShowIncomplete(); indicateTaskListChanged(); } @Override public void updateFilteredTaskList(Set<String> keywords) { sortByDateAndPriority(); updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords))); } private void updateFilteredTaskList(Expression expression) { filteredTasks.setPredicate(expression::satisfies); } public Set<String> getKeywordsFromList(List<ReadOnlyTask> tasks) { Set<String> keywords = new HashSet<String>(); for (ReadOnlyTask task : tasks) { keywords.addAll(Arrays.asList(task.getTaskDetails().toString().split(" "))); } return keywords; } @Override public void updateFilteredListToShowComplete() { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new CompletedQualifier())); } @Override public void updateFilteredListToShowFloating() { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new FloatingQualifier())); } @Override public void updateFilteredListToShowOverDue() { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new OverDueQualifier())); } @Override public void updateFilteredListToShowRecurring() { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new RecurringQualifier())); } @Override public void updateFilteredListToShowOverlapping(Task task) { updateFilteredListToShowAll(); updateFilteredTaskList(new PredicateExpression(new OverlappingQualifier(task))); } private void sortByDateAndPriority() { // Collections.sort(taskList.getListOfTasks(), Comparators.DATE_TIME); Collections.sort(taskList.getListOfTasks(), Comparators.PRIORITY); } private static class Comparators { public static Comparator<Task> DATE_TIME = new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o1.getStartTime().compareTo(o2.getStartTime()); } }; public static Comparator<Task> PRIORITY = new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { // extract only the date without time from the card string for // start time String date1 = o1.getStartTime().toCardString().split(" ")[0]; String date2 = o2.getStartTime().toCardString().split(" ")[0]; if (date1.equals(date2)) return o1.getPriority().compareTo(o2.getPriority()); else return o1.getStartTime().compareTo(o2.getStartTime()); } }; } interface Expression { boolean satisfies(ReadOnlyTask person); String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask person) { return qualifier.run(person); } @Override public String toString() { return qualifier.toString(); } } interface Qualifier { boolean run(ReadOnlyTask person); String toString(); } private class DefaultDisplayQualifier implements Qualifier { DefaultDisplayQualifier() { } @Override public boolean run(ReadOnlyTask person) { return !person.isComplete(); } } private class CompletedQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask person) { return person.isComplete(); } } private class FloatingQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask person) { return person.isFloating(); } } private class PriorityQualifier implements Qualifier { private String priority; public PriorityQualifier(String priority) { this.priority = priority.replaceFirst("p/", ""); } @Override public boolean run(ReadOnlyTask person) { return person.getPriority().priorityLevel.equals(this.priority); } } private class DateQualifier implements Qualifier { private final Calendar requestedTime; public DateQualifier(String time) { requestedTime = Calendar.getInstance(); List<DateGroup> dates = new Parser().parse(time); requestedTime.setTime(dates.get(0).getDates().get(0)); } @Override public boolean run(ReadOnlyTask person) { return DateUtils.isSameDay(person.getStartTime().time, requestedTime) || (person.getStartTime().toCardString().equals("-") && DateUtils.isSameDay(person.getEndTime().time, requestedTime)); } } private class OverDueQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask person) { return person.isOverDue(); } } private class RecurringQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask person) { return person.isRecurring(); } } private class OverlappingQualifier implements Qualifier { private Task task; public OverlappingQualifier(Task task) { this.task = task; } @Override public boolean run(ReadOnlyTask person) { // Overlapping task is task w/start only and compared task is an event if (task.getEndTime().toCardString().equals("-") && !person.getEndTime().toCardString().equals("-")) { return !task.getStartTime().toCardString().equals("-") && !person.getStartTime().toCardString().equals("-") && !task.getStartTime().getAsCalendar().after(person.getEndTime().getAsCalendar()) && !person.getStartTime().getAsCalendar().after(task.getStartTime().getAsCalendar()); } // Overlapping task is an event and compared task is task w/start only DONE else if (!task.getEndTime().toCardString().equals("-") && person.getEndTime().toCardString().equals("-")) { return !person.getStartTime().toCardString().equals("-") && !task.getStartTime().getAsCalendar().after(person.getStartTime().getAsCalendar()) && !task.getEndTime().getAsCalendar().before(person.getStartTime().getAsCalendar()); } // Compare 2 events DONE else if (!task.getEndTime().toCardString().equals("-") && !person.getEndTime().toCardString().equals("-")) { return !person.getStartTime().toCardString().equals("-") && !task.getStartTime().getAsCalendar().after(person.getStartTime().getAsCalendar()) && !person.getStartTime().getAsCalendar().after(task.getEndTime().getAsCalendar()); } // Compare 2 tasks w/start only DONE return task.getStartTime().getAsCalendar().equals(person.getStartTime().getAsCalendar()); } } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; private Pattern NAME_QUERY; NameQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; this.NAME_QUERY = Pattern.compile(getRegexFromString(), Pattern.CASE_INSENSITIVE); } private String getRegexFromString() { String result = ""; for (String keyword : nameKeyWords) { for (char c : keyword.toCharArray()) { switch (c) { case '*': result += ".*"; break; default: result += c; } } } return result; } @Override public boolean run(ReadOnlyTask person) { Matcher matcher = NAME_QUERY.matcher(person.getTaskDetails().taskDetails); return matcher.matches(); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } @Override public LinkedList<UndoInfo> getUndoStack() { return undoStack; } @Override public LinkedList<UndoInfo> getRedoStack() { return redoStack; } @Override public void changeFileStorage(String filePath) throws IOException, ParseException, JSONException { if (filePath.equals("default")) { filePath = "/data/tasklist.xml"; } File targetListFile = new File(filePath); FileReader read = new FileReader("config.json"); JSONObject obj = (JSONObject) new JSONParser().parse(read); String currentFilePath = (String) obj.get("taskListFilePath"); File currentTaskListPath = new File(currentFilePath); Config config = new Config(); try { Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } config.setTaskListFilePath(filePath); addToUndoStack(UndoCommand.STR_CMD_ID, currentFilePath); clearRedoStack(); } @Override public String changeFileStorageUndo(String filePath) throws IOException, ParseException, JSONException { if (filePath.equals("default")) { filePath = "/data/tasklist.xml"; } File targetListFile = new File(filePath); FileReader read = new FileReader("config.json"); JSONObject obj = (JSONObject) new JSONParser().parse(read); String currentFilePath = (String) obj.get("taskListFilePath"); File currentTaskListPath = new File(currentFilePath); Config config = new Config(); try { Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } config.setTaskListFilePath(filePath); return currentFilePath; } @Override public void deleteTaskRedo(Task target) throws TaskNotFoundException { taskList.removeTask(target); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.DEL_CMD_ID, null, (Task) target); } @Override public void addTaskRedo(Task task) throws DuplicateTaskException { taskList.addTask(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.ADD_CMD_ID, null, task); } @Override public void markTaskAsCompleteRedo(Task task) throws TaskNotFoundException { taskList.markTaskAsComplete(task); updateFilteredListToShowIncomplete(); indicateTaskListChanged(); addToUndoStack(UndoCommand.DONE_CMD_ID, null, (Task) task); } @Override public void resetDataRedo(ReadOnlyTaskList newData) { if (newData.isEmpty()) { // clear or redo clear was executed List<Task> listOfTasks = (List<Task>) (List<?>) taskList.getTaskList(); addToUndoStack(UndoCommand.CLR_CMD_ID, null, listOfTasks.toArray(new Task[listOfTasks.size()])); } taskList.resetData(newData); indicateTaskListChanged(); } @Override public void changeFileStorageRedo(String filePath) throws IOException, ParseException, JSONException { if (filePath.equals("default")) { filePath = "/data/tasklist.xml"; } File targetListFile = new File(filePath); FileReader read = new FileReader("config.json"); JSONObject obj = (JSONObject) new JSONParser().parse(read); String currentFilePath = (String) obj.get("taskListFilePath"); File currentTaskListPath = new File(currentFilePath); Config config = new Config(); try { Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } config.setTaskListFilePath(filePath); addToUndoStack(UndoCommand.STR_CMD_ID, currentFilePath); } }
package seedu.tasklist.ui; import java.util.Date; import java.util.logging.Logger; import org.controlsfx.control.StatusBar; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import seedu.tasklist.commons.core.LogsCenter; import seedu.tasklist.commons.events.model.TaskListChangedEvent; import seedu.tasklist.commons.util.FxViewUtil; /** * A ui for the status bar that is displayed at the footer of the application. */ public class StatusBarFooter extends UiPart<Region> { private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class); @FXML private StatusBar syncStatus; @FXML private StatusBar saveLocationStatus; private static final String FXML = "StatusBarFooter.fxml"; public StatusBarFooter(AnchorPane placeHolder, String saveLocation) { super(FXML); addToPlaceholder(placeHolder); setSyncStatus("Not updated yet in this session"); setSaveLocation("File will be saved at: " + "./" + saveLocation); registerAsAnEventHandler(this); } private void addToPlaceholder(AnchorPane placeHolder) { FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0); placeHolder.getChildren().add(getRoot()); } private void setSaveLocation(String location) { this.saveLocationStatus.setText(location); } private void setSyncStatus(String status) { this.syncStatus.setText(status); } @Subscribe public void handleAddressBookChangedEvent(TaskListChangedEvent abce) { String lastUpdated = (new Date()).toString(); logger.info(LogsCenter.getEventHandlingLogMessage(abce, "Setting last updated status to " + lastUpdated)); setSyncStatus("Last Updated: " + lastUpdated); } }
package sizebay.catalog.client; import java.util.*; import lombok.NonNull; import sizebay.catalog.client.http.*; import sizebay.catalog.client.model.*; import sizebay.catalog.client.model.filters.*; /** * A Basic wrapper on generated Swagger client. * * @author Miere L. Teixeira */ public class CatalogAPI { final static String DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/", ENDPOINT_DASHBOARD = "/dashboard", ENDPOINT_BRAND = "/brands", ENDPOINT_MODELING = "/modelings", ENDPOINT_PRODUCT = "/products", ENDPOINT_CATEGORIES = "/categories", ENDPOINT_TENANTS = "/tenants", ENDPOINT_USER = "/user", ENDPOINT_SIZE_STYLE = "/style", ENDPOINT_DEVOLUTION = "/devolution", ENDPOINT_IMPORTATION_ERROR = "/importations", ENDPOINT_STRONG_CATEGORY_TYPE = "types", ENDPOINT_STRONG_CATEGORY = "/types/categories/strong", ENDPOINT_STRONG_SUBCATEGORY = "/types/categories/strong/sub", ENDPOINT_STRONG_MODEL = "models/strong", SEARCH_BY_TEXT = "/search/all?text="; final RESTClient client; /** * Constructs the Catalog API. * * @param applicationToken * @param securityToken */ public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) { this(DEFAULT_BASE_URL, applicationToken, securityToken); } /** * Constructs the Catalog API. * * @param basePath * @param applicationToken * @param securityToken */ public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) { final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken ); final MimeType mimeType = new JSONMimeType(); client = new RESTClient( basePath, mimeType, authentication ); } /** * Starting dashboard management */ public List<Dashboard> retrieveDashboard() { return client.getList(ENDPOINT_DASHBOARD, Dashboard.class); } /** * End dashboard management */ /** * Starting user profile management */ public void insertUser (UserProfile userProfile) { client.post(ENDPOINT_USER, userProfile); } public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){ return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class); } public UserProfile retrieveUser (String userId) { return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class); } public UserProfile retrieveUserByFacebook(String facebookToken) { return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class); } public UserProfile retrieveUserByGoogle(String googleToken) { return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class); } public Profile retrieveProfile (long profileId) { return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class); } public void updateUserFacebookToken(String userId, String facebookToken) { client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken); } public void updateUserGoogleToken(String userId, String googleToken) { client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken); } public void insertProfile (Profile profile) { client.post(ENDPOINT_USER + "/profile", profile); } public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); } /* User history */ public long insertProductInUserHistory(String userId, UserHistory newProductToUserHistory) { return client.post(ENDPOINT_USER + "/history/single/"+ userId, newProductToUserHistory); } public List<UserHistory> retrieveUserHistory(int page, String userId) { return client.getList(ENDPOINT_USER + "/history/all/" + userId + "?page=" + page, UserHistory.class); } public void deleteUserHistoryProduct(String userId, Long userHistoryId) { client.delete(ENDPOINT_USER + "/history/single/" + userId + "?userHistoryId=" + userHistoryId); } /* User liked products */ public long insertLikeInTheProduct(String userId, LikedProduct likedProduct) { return client.post(ENDPOINT_USER + "/liked-products/single/"+ userId, likedProduct); } public List<LikedProduct> retrieveLikedProductsByUser(int page, String userId) { return client.getList(ENDPOINT_USER + "/liked-products/all/" + userId + "?page=" + page, LikedProduct.class); } public void deleteLikeInTheProduct(String userId, Long likedProductId) { client.delete(ENDPOINT_USER + "/liked-products/single/" + userId + "?likedProductId=" + likedProductId); } /* * End user profile management */ /* * Starting size style management */ public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) { return client.getList(ENDPOINT_SIZE_STYLE + "/search/all" + "?" + filter.createQuery(), SizeStyle.class); } public SizeStyle getSingleSizeStyle(long id) { return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class); } public long insertSizeStyle(SizeStyle sizeStyle) { return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle); } public void updateWeightStyle(long id, SizeStyle sizeStyle) { client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle); } public void bulkUpdateSizeStyles(BulkUpdateSizeStyle bulkUpdateSizeStyle) { client.patch(ENDPOINT_SIZE_STYLE, bulkUpdateSizeStyle); } public void bulkUpdateModeling(BulkUpdateSizeStyle bulkUpdateSizeStyle) { client.patch(ENDPOINT_SIZE_STYLE + "/bulk/modeling", bulkUpdateSizeStyle); } public void deleteSizeStyle(long id) { client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id); } public void deleteSizeStyles(List<Integer> ids) { client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids); } /* * End size style management */ /* * Starting devolution management */ public List<DevolutionError> retrieveDevolutionErrors() { return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class); } public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) { return client.getList(ENDPOINT_DEVOLUTION + "/errors" + "?" + filter.createQuery(), DevolutionError.class); } public long insertDevolutionError(DevolutionError devolution) { return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution); } public void deleteDevolutionErrors() { client.delete(ENDPOINT_DEVOLUTION + "/errors"); } public DevolutionSummary retrieveDevolutionSummaryLastBy() { return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class); } public long insertDevolutionSummary(DevolutionSummary devolutionSummary) { return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary); } public void deleteDevolutionSummary() { client.delete(ENDPOINT_DEVOLUTION + "/summary"); } /* * End devolution management */ /* * Starting user (MySizebay) management */ public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) { return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class ); } /* * End user (MySizebay) management */ /* * Starting product management */ public List<Product> getProducts(int page) { return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class); } public List<Product> getProducts(ProductFilter filter) { return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class); } public Product getProduct(long id) { return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class); } public Long getProductIdFromPermalink(String permalink){ return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id" + "?permalink=" + permalink, Long.class); } public Long getAvailableProductIdFromPermalink(String permalink){ return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id" + "?permalink=" + permalink + "&onlyAvailable=true", Long.class); } public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) { return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id" + "/" + tenantId + "/" + feedProductId, ProductIntegration.class); } public ProductBasicInformation retrieveProductByBarcode(Long barcode) { return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class); } public ProductBasicInformation getProductBasicInfo(long id){ return client.getSingle(ENDPOINT_PRODUCT + "/" + id + "/basic-info", ProductBasicInformation.class); } public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){ return client.getSingle( ENDPOINT_PRODUCT + "/" + id + "/basic-info-filter-sizes" + "?sizes=" + sizes, ProductBasicInformation.class); } public long insertProduct(Product product) { return client.post(ENDPOINT_PRODUCT + "/single", product); } public ProductIntegration insertProductIntegration(ProductIntegration product) { return client.post(ENDPOINT_PRODUCT + "/single/integration", product, ProductIntegration.class); } public long insertMockedProduct(String permalink) { return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class); } public void updateProduct(long id, Product product) { client.put(ENDPOINT_PRODUCT + "/single/" + id, product); } public void bulkUpdateProducts(BulkUpdateProducts products) { client.patch(ENDPOINT_PRODUCT, products); } public void deleteProducts() { client.delete(ENDPOINT_PRODUCT); } public void deleteProduct(long id) { client.delete(ENDPOINT_PRODUCT + "/single/" + id); } public void deleteProducts(List<Integer> ids) { client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids); } /* * End product management */ /* * Starting brand management */ public List<Brand> searchForBrands(String text){ return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class); } public List<Brand> getBrands(BrandFilter filter) { return client.getList(ENDPOINT_BRAND + "?" + filter.createQuery(), Brand.class); } public List<Brand> getBrands(int page) { return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class); } public List<Brand> getBrands(int page, String name) { return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class); } public Brand getBrand(long id) { return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class); } public long insertBrand(Brand brand) { return client.post(ENDPOINT_BRAND + "/single", brand); } public void updateBrand(long id, Brand brand) { client.put(ENDPOINT_BRAND + "/single/" + id, brand); } public void deleteBrands() { client.delete(ENDPOINT_BRAND); } public void deleteBrand(long id) { client.delete(ENDPOINT_BRAND + "/single/" + id); } public void deleteBrands(List<Integer> ids) { client.delete(ENDPOINT_BRAND + "/bulk/some", ids); } /* * End brand management */ /* * Starting category management */ public List<Category> getCategories() { return client.getList(ENDPOINT_CATEGORIES, Category.class); } public List<Category> getCategories(int page) { return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class); } public List<Category> getCategories(int page, String name) { return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class); } public List<Category> getCategories(CategoryFilter filter) { return client.getList(ENDPOINT_CATEGORIES + "?" + filter.createQuery(), Category.class); } public List<Category> searchForCategories(String text){ return client.getList(ENDPOINT_CATEGORIES + SEARCH_BY_TEXT + text, Category.class); } public Category getCategory(long id) { return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class); } public long insertCategory(Category brand) { return client.post(ENDPOINT_CATEGORIES + "/single", brand); } public void updateCategory(long id, Category brand) { client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand); } public void bulkUpdateCategories(BulkUpdateCategories categories) { client.patch(ENDPOINT_CATEGORIES, categories); } public void deleteCategories() { client.delete(ENDPOINT_CATEGORIES); } public void deleteCategory(long id) { client.delete(ENDPOINT_CATEGORIES + "/single/" + id); } public void deleteCategories(List<Integer> ids) { client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids); } /* * End category management */ /* * Starting modeling management */ public List<Modeling> searchForModelings(long brandId, String gender) { return searchForModelings(String.valueOf(brandId), gender); } public List<Modeling> searchForModelings(String brandId, String gender){ return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class); } public List<Modeling> getModelings(int page){ return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class); } public List<Modeling> getModelings(ModelingFilter filter) { return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class); } public List<Modeling> getAllSimplifiedModeling() { return client.getList(ENDPOINT_MODELING + "/simplified/all", Modeling.class); } public Modeling getModeling(long id) { return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class); } public long insertModeling(Modeling modeling) { return client.post(ENDPOINT_MODELING + "/single", modeling); } public void updateModeling(long id, Modeling modeling) { client.put(ENDPOINT_MODELING + "/single/" + id, modeling); } public void deleteModelings() { client.delete(ENDPOINT_MODELING); } public void deleteModeling(long id) { client.delete(ENDPOINT_MODELING + "/single/" + id); } public void deleteModelings(List<Integer> ids) { client.delete(ENDPOINT_MODELING + "/bulk/some", ids); } /* * End modeling management */ /* * Starting importation error management */ public List<ImportationError> getImportationErrors(String page){ return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class); } public long insertImportationError(ImportationError importationError){ return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError); } public void deleteImportationErrors() { client.delete(ENDPOINT_PRODUCT + "/importation-errors/all"); } public ImportationSummary getImportationSummary(){ return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class); } public long insertImportationSummary(ImportationSummary importationSummary){ return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary); } public void deleteImportationSummary() { client.delete(ENDPOINT_IMPORTATION_ERROR); } /* * End importation error management */ /* * Starting strong brand management */ public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) { return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class); } public StrongBrand getSingleBrand(long id) { return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class); } public long insertStrongBrand(StrongBrand strongBrand){ return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand); } public void updateStrongBrand(long id, StrongBrand strongBrand) { client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand); } public void deleteStrongBrand(long id) { client.delete(ENDPOINT_BRAND + "/strong/single/" + id); } public void deleteStrongBrands(List<Integer> ids) { client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids); } /* * End strong brand management */ /* * Starting strong category management */ public List<StrongCategory> getAllStrongCategories(){ return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class); } public List<StrongCategory> getAllStrongCategories(int page, String categoryName, Long typeId){ String condition; condition = categoryName == null ? "" : "&name=" + categoryName; condition += typeId == null ? "" : "&typeId=" + typeId; return client.getList(ENDPOINT_STRONG_CATEGORY + "/search/all?page=" + page + condition, StrongCategory.class); } public StrongCategory getSingleStrongCategory(long id) { return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class); } public long insertStrongCategory(StrongCategory strongCategory){ return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory); } public void updateStrongCategory(long id, StrongCategory strongCategory) { client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory); } public void deleteStrongCategory(long id) { client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id); } /* * End strong category management */ /* * Starting strong subcategory management */ public List<StrongSubcategory> getAllStrongSubcategories(int page){ return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class); } public List<StrongSubcategory> getAllStrongSubcategories(int page, String subcategoryName){ return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page + "&name=" + subcategoryName, StrongSubcategory.class); } public StrongSubcategory getSingleStrongSubcategory(long id) { return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class); } public long insertStrongSubcategory(StrongSubcategory strongSubcategory){ return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory); } public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) { client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory); } public void deleteStrongSubcategory(long id) { client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id); } /* * End strong subcategory management */ /* * Starting strong category type management */ public List<StrongCategoryType> getAllStrongCategoryTypes(int page){ return client.getList(ENDPOINT_STRONG_CATEGORY_TYPE + "?page=" + page, StrongCategoryType.class); } public List<StrongCategoryType> getAllStrongCategoryTypes(int page, String categoryTypeName){ return client.getList(ENDPOINT_STRONG_CATEGORY_TYPE + "?page=" + page + "&name=" + categoryTypeName, StrongCategoryType.class); } public StrongCategoryType getSingleStrongCategoryType(long id) { return client.getSingle(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id, StrongCategoryType.class); } public long insertStrongCategoryType(StrongCategoryType strongCategoryType){ return client.post(ENDPOINT_STRONG_CATEGORY_TYPE + "/single", strongCategoryType); } public void updateStrongCategoryType(long id, StrongCategoryType strongCategoryType) { client.put(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id, strongCategoryType); } public void deleteStrongCategoryType(long id) { client.delete(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id); } /* * End strong category type management */ /* * Starting strong model management */ public List<StrongModel> getAllStrongModels(int page){ return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class); } public List<StrongModel> getAllStrongModels(int page, String modelName){ return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class); } public StrongModel getSingleStrongModel(long id) { return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class); } public long insertStrongModel(StrongModel strongModel){ return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel); } public void updateStrongModel(long id, StrongModel strongModel) { client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel); } public void deleteStrongModel(long id) { client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id); } /* * End strong model management */ /* * Starting strong brand management */ public List<StrongModeling> getStrongModelings(int page) { return client.getList(ENDPOINT_MODELING + "/strong?page=" + page, StrongModeling.class); } public List<StrongModeling> getStrongModelings(StrongModelingFilter filter) { return client.getList(ENDPOINT_MODELING + "/strong?" + filter.createQuery(), StrongModeling.class); } public StrongModeling getSingleStrongModeling(long id) { return client.getSingle(ENDPOINT_MODELING + "/strong/single/" + id, StrongModeling.class); } public long insertStrongModeling(StrongModeling strongModeling){ return client.post(ENDPOINT_MODELING + "/strong/single", strongModeling); } public void updateStrongModeling(long id, StrongModeling strongModeling) { client.put(ENDPOINT_MODELING + "/strong/single/" + id, strongModeling); } public void deleteStrongModeling(long id) { client.delete(ENDPOINT_MODELING + "/strong/single/" + id); } public void deleteStrongModelings(List<Integer> ids) { client.delete(ENDPOINT_MODELING + "/strong/bulk/some", ids); } /* * End strong brand management */ /* * Starting tenant management */ public Tenant getTenant( String appToken ){ return client.getSingle( ENDPOINT_TENANTS+ "/single/" + appToken, Tenant.class ); } public List<Tenant> retrieveAllTenants(){ return client.getList( ENDPOINT_TENANTS, Tenant.class ); } public List<Tenant> searchTenants(TenantFilter filter) { return client.getList( ENDPOINT_TENANTS + "/search?monitored=" + filter.getMonitored(), Tenant.class); } public List<Tenant> searchAllTenants() { return client.getList( ENDPOINT_TENANTS + "/search/all", Tenant.class); } public Long insertTenant(Tenant tenant) { return client.post(ENDPOINT_TENANTS, tenant); } public void updateTenant(long id, Tenant tenant) { client.put(ENDPOINT_TENANTS + "/single/" + id, tenant); } public void updateHashXML(String hash) { client.put(ENDPOINT_TENANTS + "/hash", hash); } public void deleteTenant(long id) { client.delete(ENDPOINT_TENANTS + "/" + id); } /* * End tenant management */ /* * Starting tenant management */ public List<MySizebayUser> attachedUsersToTenant(long id) { return client.getList(ENDPOINT_TENANTS + "/" + id + "/users", MySizebayUser.class); } public void attachUserToTenant(long id, String email) { client.getSingle(ENDPOINT_TENANTS + "/" + id + "/users/" + email); } public void detachUserToTenant(long id, String email) { client.delete(ENDPOINT_TENANTS + "/" + id + "/users/" + email); } /* * End tenant management */ /* * Starting importation rules management */ public String retrieveImportRules(long id) { return client.getSingle(ENDPOINT_TENANTS + "/" + id + "/rules", String.class); } public Long insertImportationRules(long id, ImportationRules rules) { return client.post(ENDPOINT_TENANTS + "/" + id + "/rules", rules); } /* * End importation rules management */ /* * Starting my sizebay user management */ public MySizebayUser getMySizebayUser(String username){ return client.getSingle( "/users/" + username, MySizebayUser.class); } public Long insertMySizebayUser(MySizebayUser user){ return client.post("/users/", user); } /* * End my sizebay user management */ public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) { client.post( "/importations/tenantId/"+tenantId, importationSummary ); } }
package org.jboss.as.cli; import java.util.Properties; import java.io.File; /** * A utility class for replacing properties in strings. * * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> * @author <a href="Scott.Stark@jboss.org">Scott Stark</a> * @author <a href="claudio.vesco@previnet.it">Claudio Vesco</a> * @author <a href="mailto:adrian@jboss.com">Adrian Brock</a> * @author <a href="mailto:dimitris@jboss.org">Dimitris Andreadis</a> * @version <tt>$Revision$</tt> */ final class StringPropertyReplacer { /** New line string constant */ public static final String NEWLINE = Util.LINE_SEPARATOR; /** File separator value */ private static final String FILE_SEPARATOR = File.separator; /** Path separator value */ private static final String PATH_SEPARATOR = File.pathSeparator; /** File separator alias */ private static final String FILE_SEPARATOR_ALIAS = "/"; /** Path separator alias */ private static final String PATH_SEPARATOR_ALIAS = ":"; // States used in property parsing private static final int NORMAL = 0; private static final int SEEN_DOLLAR = 1; private static final int IN_BRACKET = 2; /** * Go through the input string and replace any occurance of ${p} with the * System.getProperty(p) value. If there is no such property p defined, then * the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such * property p, then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the * primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with * System.getProperty("path.separator"). * * @param string * - the string with possible ${} references * @return the input string with all property references replaced if any. If * there are no valid references the input string will be returned. */ public static String replaceProperties(final String string) { return replaceProperties(string, null); } /** * Go through the input string and replace any occurance of ${p} with the * props.getProperty(p) value. If there is no such property p defined, then * the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such * property p, then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the * primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with * System.getProperty("path.separator"). * * @param string * - the string with possible ${} references * @param props * - the source for ${x} property ref values, null means use * System.getProperty() * @return the input string with all property references replaced if any. If * there are no valid references the input string will be returned. */ public static String replaceProperties(final String string, final Properties props) { final char[] chars = string.toCharArray(); StringBuffer buffer = new StringBuffer(); boolean properties = false; int state = NORMAL; int start = 0; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; // Dollar sign outside brackets if (c == '$' && state != IN_BRACKET) state = SEEN_DOLLAR; // Open bracket immediatley after dollar else if (c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state = IN_BRACKET; start = i - 1; } // No open bracket after dollar else if (state == SEEN_DOLLAR) state = NORMAL; // Closed bracket after open bracket else if (c == '}' && state == IN_BRACKET) { // No content if (start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else { // Collect the system property String value = null; String key = string.substring(start + 2, i); // check for alias if (FILE_SEPARATOR_ALIAS.equals(key)) { value = FILE_SEPARATOR; } else if (PATH_SEPARATOR_ALIAS.equals(key)) { value = PATH_SEPARATOR; } else { // check from the properties if (props != null) value = props.getProperty(key); else value = SecurityActions.getSystemProperty(key); if (value == null) { // Check for a default value ${key:default} int colon = key.indexOf(':'); if (colon > 0) { String realKey = key.substring(0, colon); if (props != null) value = props.getProperty(realKey); else value = SecurityActions .getSystemProperty(realKey); if (value == null) { // Check for a composite key, "key1,key2" value = resolveCompositeKey(realKey, props); // Not a composite key either, use the // specified default if (value == null) value = key.substring(colon + 1); } } else { // No default, check for a composite key, // "key1,key2" value = resolveCompositeKey(key, props); } } } if (value != null) { properties = true; buffer.append(value); } else { buffer.append("${"); buffer.append(key); buffer.append('}'); } } start = i + 1; state = NORMAL; } } // No properties if (properties == false) return string; // Collect the trailing characters if (start != chars.length) buffer.append(string.substring(start, chars.length)); // Done return buffer.toString(); } /** * Try to resolve a "key" from the provided properties by checking if it is * actually a "key1,key2", in which case try first "key1", then "key2". If * all fails, return null. * * It also accepts "key1," and ",key2". * * @param key * the key to resolve * @param props * the properties to use * @return the resolved key or null */ private static String resolveCompositeKey(String key, Properties props) { String value = null; // Look for the comma int comma = key.indexOf(','); if (comma > -1) { // If we have a first part, try resolve it if (comma > 0) { // Check the first part String key1 = key.substring(0, comma); if (props != null) value = props.getProperty(key1); else value = SecurityActions.getSystemProperty(key1); } // Check the second part, if there is one and first lookup failed if (value == null && comma < key.length() - 1) { String key2 = key.substring(comma + 1); if (props != null) value = props.getProperty(key2); else value = SecurityActions.getSystemProperty(key2); } } // Return whatever we've found or null return value; } }
package tigase.muc.modules; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import tigase.criteria.Criteria; import tigase.criteria.ElementCriteria; import tigase.muc.Affiliation; import tigase.muc.IChatRoomLogger; import tigase.muc.MucConfig; import tigase.muc.Role; import tigase.muc.Room; import tigase.muc.RoomConfig; import tigase.muc.XMPPDateTimeFormatter; import tigase.muc.RoomConfig.Anonymity; import tigase.muc.exceptions.MUCException; import tigase.muc.modules.PresenceModule.DelayDeliveryThread.DelDeliverySend; import tigase.muc.repository.IMucRepository; import tigase.server.Packet; import tigase.util.TigaseStringprepException; import tigase.xml.Element; import tigase.xmpp.Authorization; import tigase.xmpp.BareJID; import tigase.xmpp.JID; /** * @author bmalkow * */ public class PresenceModule extends AbstractModule { public static class DelayDeliveryThread extends Thread { public static interface DelDeliverySend { void sendDelayedPacket(Packet packet); } private final LinkedList<Element[]> items = new LinkedList<Element[]>(); private final DelDeliverySend sender; public DelayDeliveryThread(DelDeliverySend component) { this.sender = component; } public void put(Element element) { items.add(new Element[] { element }); } /** * @param elements */ public void put(List<Element> elements) { if (elements != null && elements.size() > 0) { items.push(elements.toArray(new Element[] {})); } } @Override public void run() { try { do { sleep(553); if (items.size() > 0) { Element[] toSend = items.poll(); if (toSend != null) { for (Element element : toSend) { try { sender.sendDelayedPacket(Packet.packetInstance(element)); } catch (TigaseStringprepException ex) { log.info("Packet addressing problem, stringprep failed: " + element); } } } } } while (true); } catch (InterruptedException e) { e.printStackTrace(); } } } private static final Criteria CRIT = ElementCriteria.name("presence"); protected static final Logger log = Logger.getLogger(PresenceModule.class.getName()); private final static XMPPDateTimeFormatter sdf = new XMPPDateTimeFormatter(); private static Role getDefaultRole(final RoomConfig config, final Affiliation affiliation) { Role newRole; if (config.isRoomModerated() && affiliation == Affiliation.none) { newRole = Role.visitor; } else { switch (affiliation) { case admin: newRole = Role.moderator; break; case member: newRole = Role.participant; break; case none: newRole = Role.participant; break; case outcast: newRole = Role.none; break; case owner: newRole = Role.moderator; break; default: newRole = Role.none; break; } } return newRole; } private final IChatRoomLogger chatRoomLogger; private final DelayDeliveryThread delayDeliveryThread; private boolean lockNewRoom = true; public PresenceModule(MucConfig config, IMucRepository mucRepository, IChatRoomLogger chatRoomLogger, DelDeliverySend sender) { super(config, mucRepository); this.chatRoomLogger = chatRoomLogger; this.delayDeliveryThread = new DelayDeliveryThread(sender); this.delayDeliveryThread.start(); } @Override public String[] getFeatures() { return null; } @Override public Criteria getModuleCriteria() { return CRIT; } public boolean isLockNewRoom() { return lockNewRoom; } private List<Element> preparePresenceToAllOccupants(Room room, BareJID roomJID, String nickName, Affiliation affiliation, Role role, JID senderJID, boolean newRoomCreated, String newNickName) { List<Element> result = new ArrayList<Element>(); Anonymity anonymity = room.getConfig().getRoomAnonymity(); for (JID occupantJid : room.getOccupantsJids()) { final Affiliation occupantAffiliation = room.getAffiliation(occupantJid.getBareJID()); Element presence; if (newNickName != null) { presence = new Element("presence"); presence.setAttribute("type", "unavailable"); } else if (room.getOccupantsNicknameByBareJid(senderJID.getBareJID()) == null) { presence = new Element("presence"); presence.setAttribute("type", "unavailable"); } else { presence = room.getLastPresenceCopyByJid(senderJID); } try { presence.setAttribute("from", JID.jidInstance(roomJID, nickName).toString()); } catch (TigaseStringprepException e) { presence.setAttribute("from", roomJID + "/" + nickName); } presence.setAttribute("to", occupantJid.toString()); Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" }); Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] { affiliation.name(), role.name(), nickName }); if (senderJID.equals(occupantJid)) { x.addChild(new Element("status", new String[] { "code" }, new String[] { "110" })); if (anonymity == Anonymity.nonanonymous) { x.addChild(new Element("status", new String[] { "code" }, new String[] { "100" })); } if (room.getConfig().isLoggingEnabled()) { x.addChild(new Element("status", new String[] { "code" }, new String[] { "170" })); } } if (newRoomCreated) { x.addChild(new Element("status", new String[] { "code" }, new String[] { "201" })); } if (anonymity == Anonymity.nonanonymous || (anonymity == Anonymity.semianonymous && occupantAffiliation.isViewOccupantsJid())) { item.setAttribute("jid", senderJID.toString()); } if (newNickName != null) { x.addChild(new Element("status", new String[] { "code" }, new String[] { "303" })); item.setAttribute("nick", newNickName); } x.addChild(item); presence.addChild(x); result.add(presence); } return result; } @Override public List<Element> process(Element element) throws MUCException { try { ArrayList<Element> result = new ArrayList<Element>(); final JID senderJID = JID.jidInstance(element.getAttribute("from")); final BareJID roomJID = BareJID.bareJIDInstance(element.getAttribute("to")); final String nickName = getNicknameFromJid(JID.jidInstance(element.getAttribute("to"))); final String presenceType = element.getAttribute("type"); boolean newRoomCreated = false; boolean exitingRoom = presenceType != null && "unavailable".equals(presenceType); final Element $x = element.getChild("x", "http://jabber.org/protocol/muc"); final Element password = $x == null ? null : $x.getChild("password"); if (nickName == null) { throw new MUCException(Authorization.JID_MALFORMED); } Room room = repository.getRoom(roomJID); if (room == null) { log.info("Creating new room '" + roomJID + "' by user " + nickName + "' <" + senderJID.toString() + ">"); room = repository.createNewRoom(roomJID, senderJID); room.addAffiliationByJid(senderJID.getBareJID(), Affiliation.owner); room.setRoomLocked(this.lockNewRoom); newRoomCreated = true; } boolean newOccupant = !room.isOccupantExistsByJid(senderJID); if (newOccupant && room.getConfig().isPasswordProtectedRoom()) { final String psw = password == null ? null : password.getCData(); final String roomPassword = room.getConfig().getPassword(); if (psw == null || !psw.equals(roomPassword)) { log.finest("Password '" + psw + "' is not match to room passsword '" + roomPassword + "' "); throw new MUCException(Authorization.NOT_AUTHORIZED); } } final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID()); // TODO // przepuszczac wlasciciela konta!!! if (!newRoomCreated && room.isRoomLocked() && !exitingRoom && affiliation != Affiliation.owner) { throw new MUCException(Authorization.ITEM_NOT_FOUND, "Room is locked"); } if (exitingRoom && !room.isOccupantExistsByJid(senderJID)) { return null; } Anonymity anonymity = room.getConfig().getRoomAnonymity(); if (!affiliation.isEnterOpenRoom()) { log.info("User " + nickName + "' <" + senderJID.toString() + "> is on rooms '" + roomJID + "' blacklist"); throw new MUCException(Authorization.FORBIDDEN); } else if (room.getConfig().isRoomMembersOnly() && !affiliation.isEnterMembersOnlyRoom()) { log.info("User " + nickName + "' <" + senderJID.toString() + "> is NOT on rooms '" + roomJID + "' member list."); throw new MUCException(Authorization.REGISTRATION_REQUIRED); } final boolean changeNickName = !newOccupant && !room.getOccupantsNickname(senderJID).equals(nickName); if ((newOccupant || changeNickName) && room.isNickNameExistsForDifferentJid(nickName, senderJID.getBareJID())) { throw new MUCException(Authorization.CONFLICT); } if (newOccupant) { // Service Sends Presence from Existing Occupants to New // Occupant for (JID occupantJid : room.getOccupantsJids()) { final String occupantNickname = room.getOccupantsNickname(occupantJid); final Affiliation occupantAffiliation = room.getAffiliation(occupantJid.getBareJID()); final Role occupantRole = room.getRoleByJid(occupantJid); Element presence = room.getLastPresenceCopyByJid(occupantJid); presence.setAttribute("from", roomJID + "/" + occupantNickname); presence.setAttribute("to", senderJID.toString()); Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" }); Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] { occupantAffiliation.name(), occupantRole.name(), occupantNickname }); if (anonymity == Anonymity.nonanonymous || (anonymity == Anonymity.semianonymous && (affiliation == Affiliation.admin || affiliation == Affiliation.owner))) { item.setAttribute("jid", occupantJid.toString()); } x.addChild(item); presence.addChild(x); result.add(presence); } final Role newRole = getDefaultRole(room.getConfig(), affiliation); log.finest("Occupant '" + nickName + "' <" + senderJID.toString() + "> is entering room " + roomJID + " as role=" + newRole.name() + ", affiliation=" + affiliation.name()); room.addOccupantByJid(JID.jidInstance(senderJID.toString()), nickName, newRole); } room.updatePresenceByJid(senderJID, element); final Role role = exitingRoom ? Role.none : room.getRoleByJid(senderJID); if (changeNickName) { String nck = room.getOccupantsNickname(senderJID); log.finest("Occupant '" + nck + "' <" + senderJID.toString() + "> is changing his nickname to '" + nickName + "'"); result.addAll(preparePresenceToAllOccupants(room, roomJID, nck, affiliation, role, senderJID, newRoomCreated, nickName)); room.changeNickName(senderJID, nickName); } if (exitingRoom) { log.finest("Occupant '" + nickName + "' <" + senderJID.toString() + "> is leaving room " + roomJID); room.removeOccupantByJid(senderJID); if (room.getOccupantsNicknameByBareJid(senderJID.getBareJID()) == null) { // Service Sends New Occupant's Presence to All Occupants result.addAll(preparePresenceToAllOccupants(room, roomJID, nickName, affiliation, role, senderJID, newRoomCreated, null)); } } else { // Service Sends New Occupant's Presence to All Occupants result.addAll(preparePresenceToAllOccupants(room, roomJID, nickName, affiliation, role, senderJID, newRoomCreated, null)); } if (newOccupant) { this.delayDeliveryThread.put(room.getHistoryMessages(senderJID)); } if (newOccupant && room.getSubject() != null && room.getSubjectChangerNick() != null && room.getSubjectChangeDate() != null) { Element message = new Element("message", new String[] { "type", "from", "to" }, new String[] { "groupchat", roomJID + "/" + room.getSubjectChangerNick(), senderJID.toString() }); message.addChild(new Element("subject", room.getSubject())); String stamp = sdf.format(room.getSubjectChangeDate()); Element delay = new Element("delay", new String[] { "xmlns", "stamp" }, new String[] { "urn:xmpp:delay", stamp }); delay.setAttribute("jid", roomJID + "/" + room.getSubjectChangerNick()); Element x = new Element("x", new String[] { "xmlns", "stamp" }, new String[] { "jabber:x:delay", sdf.formatOld(room.getSubjectChangeDate()) }); message.addChild(delay); message.addChild(x); this.delayDeliveryThread.put(message); } if (room.isRoomLocked() && newOccupant) { result.addAll(prepareMucMessage(room, room.getOccupantsNickname(senderJID), "Room is locked. Please configure.")); } if (this.chatRoomLogger != null && room.getConfig().isLoggingEnabled() && newOccupant) { this.chatRoomLogger.addJoin(room.getConfig().getLoggingFormat(), roomJID, new Date(), nickName); } else if (this.chatRoomLogger != null && room.getConfig().isLoggingEnabled() && exitingRoom) { this.chatRoomLogger.addLeave(room.getConfig().getLoggingFormat(), roomJID, new Date(), nickName); } final int occupantsCount = room.getOccupantsCount(); if (occupantsCount == 0) { this.repository.leaveRoom(room); } return result; } catch (MUCException e1) { throw e1; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public void setLockNewRoom(boolean lockNewRoom) { this.lockNewRoom = lockNewRoom; } }
package org.onlab.onos.cli.net; import static com.google.common.collect.Lists.newArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onlab.onos.cli.AbstractShellCommand; import org.onlab.onos.net.Device; import org.onlab.onos.net.DeviceId; import org.onlab.onos.net.device.DeviceService; import org.onlab.onos.net.flow.FlowRule; import org.onlab.onos.net.flow.FlowRuleService; import com.google.common.collect.Maps; /** * Lists all currently-known hosts. */ @Command(scope = "onos", name = "flows", description = "Lists all currently-known flows.") public class FlowsListCommand extends AbstractShellCommand { private static final String FMT = " id=%s, state=%s, bytes=%s, packets=%s, duration=%s, priority=%s"; private static final String TFMT = " treatment=%s"; private static final String SFMT = " selector=%s"; @Argument(index = 0, name = "uri", description = "Device ID", required = false, multiValued = false) String uri = null; @Override protected void execute() { DeviceService deviceService = get(DeviceService.class); FlowRuleService service = get(FlowRuleService.class); Map<Device, List<FlowRule>> flows = getSortedFlows(deviceService, service); for (Device d : flows.keySet()) { printFlows(d, flows.get(d)); } } /** * Returns the list of devices sorted using the device ID URIs. * * @param service device service * @return sorted device list */ protected Map<Device, List<FlowRule>> getSortedFlows(DeviceService deviceService, FlowRuleService service) { Map<Device, List<FlowRule>> flows = Maps.newHashMap(); List<FlowRule> rules = newArrayList(); Iterable<Device> devices = uri == null ? deviceService.getDevices() : Collections.singletonList(deviceService.getDevice(DeviceId.deviceId(uri))); for (Device d : devices) { rules = newArrayList(service.getFlowEntries(d.id())); Collections.sort(rules, Comparators.FLOW_RULE_COMPARATOR); flows.put(d, rules); } return flows; } /** * Prints flows. * @param d the device * @param flows the set of flows for that device. */ protected void printFlows(Device d, List<FlowRule> flows) { print("Device: " + d.id()); if (flows == null | flows.isEmpty()) { print(" %s", "No flows installed."); return; } for (FlowRule f : flows) { print(FMT, Long.toHexString(f.id().value()), f.state(), f.bytes(), f.packets(), f.lifeMillis(), f.priority()); print(SFMT, f.selector().criteria()); print(TFMT, f.treatment().instructions()); } } }
package ui.components.pickers; import backend.resource.TurboIssue; import backend.resource.TurboLabel; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleBooleanProperty; import javafx.stage.Stage; import javafx.util.Pair; import ui.UI; import util.events.ShowLabelPickerEventHandler; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class LabelPicker { private UI ui; private Stage stage; private Map<Pair<String, Integer>, LabelPickerDialog> openDialogs; public LabelPicker(UI ui, Stage stage) { this.ui = ui; this.stage = stage; openDialogs = new HashMap<>(); ui.registerEvent((ShowLabelPickerEventHandler) e -> Platform.runLater(() -> showLabelPicker(e.issue))); } // TODO implement multiple dialogs, currently, only one dialog is allowed and it blocks the main UI when open private void showLabelPicker(TurboIssue issue) { if (!openDialogs.containsKey(new Pair<>(issue.getRepoId(), issue.getId()))) { List<TurboLabel> allLabels = ui.logic.getRepo(issue.getRepoId()).getLabels(); LabelPickerDialog labelPickerDialog = new LabelPickerDialog(issue, allLabels, stage); openDialogs.put(new Pair<>(issue.getRepoId(), issue.getId()), labelPickerDialog); Optional<List<String>> result = labelPickerDialog.showAndWait(); if (result.isPresent()) { ui.logic.replaceIssueLabels(issue, result.get()) .thenRun(() -> ui.getBrowserComponent().showIssue( issue.getRepoId(), issue.getId(), issue.isPullRequest(), true) ); } openDialogs.remove(new Pair<>(issue.getRepoId(), issue.getId())); } else { // TODO focus on the already open dialog when having multiple dialogs openDialogs.get(new Pair<>(issue.getRepoId(), issue.getId())).requestFocus(); } } public static class Label { private ReadOnlyStringWrapper name = new ReadOnlyStringWrapper(); private ReadOnlyStringWrapper style = new ReadOnlyStringWrapper(); private BooleanProperty checked = new SimpleBooleanProperty(); private BooleanProperty selected = new SimpleBooleanProperty(false); public Label(String name, String style, boolean checked) { this.name.set(name); this.style.set(style); this.checked.set(checked); } public String getName() { return name.get(); } public String getStyle() { return style.get(); } public BooleanProperty checkedProperty() { return checked; } public boolean isSelected() { return selected.get(); } public void setSelected(boolean selected) { this.selected.set(selected); } public void toggleChecked() { checked.set(!checked.get()); } } }
package utask.ui.dialogs; import java.util.ArrayList; import java.util.List; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.OverrunStyle; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import utask.model.tag.Tag; import utask.staging.ui.helper.TagColorHelper; public class UTTagColorDialog extends UTDialog { private static final String LABEL_CSS = "-fx-padding: 1 3 1 3; -fx-text-fill: WHITE; -fx-background-color: %s;"; public UTTagColorDialog(StackPane parent) { super(parent); } @Override protected void initialize() { contentLayout.setHeading(new Label("Tags")); List<Node> labels = new ArrayList<Node>(); labels.add(setLabelSizeForDialogDisplay(createLabel("Important"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Urgent"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Todo"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Friends"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Important"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Urgent"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Todo"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Friends"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Important"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Urgent"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Todo"))); labels.add(setLabelSizeForDialogDisplay(createLabel("Friends"))); FlowPane pane = new FlowPane(); pane.getChildren().addAll(labels); contentLayout.setBody(pane); } private Node setLabelSizeForDialogDisplay(Label label) { label.setMinHeight(20); label.setMaxHeight(20); label.setPrefHeight(20); label.setMinWidth(75); label.setMaxWidth(75); label.setPrefWidth(75); VBox vb = new VBox(); vb.setPadding(new Insets(2, 2, 2, 2)); // vb.setSpacing(10); vb.getChildren().add(label); return vb; } public void show(List<Tag> tags) { super.show(); } //TODO: COPYPASTA FROM UTTASKLISTCARD REUSEABLE CODE!!! private Label createLabel(String name) { Label label = new Label(name); addStylingPropertiesToLabel(label); return label; } private void addStylingPropertiesToLabel(Label label) { label.setAlignment(Pos.CENTER); label.setTextAlignment(TextAlignment.CENTER); label.setTextOverrun(OverrunStyle.CLIP); label.setMinWidth(15.0); label.setStyle(String.format(LABEL_CSS, TagColorHelper.getARandomColor())); HBox.setMargin(label, new Insets(5, 5, 5, 0)); } }
package watodo.logic.commands; import java.util.List; import java.util.Set; import watodo.logic.commands.exceptions.CommandException; import watodo.model.tag.UniqueTagList; import watodo.model.task.Name; import watodo.model.task.Priority; import watodo.model.task.ReadOnlyTask; import watodo.model.task.Status; import watodo.model.task.Task; import watodo.model.task.Time; import watodo.model.task.UniqueTaskList.TaskNotFoundException; //@@author A0164393Y /** * Finds and lists all tasks in task manager whose name contains any of the * argument keywords. Keyword matching is case sensitive. */ public class MarkCommand extends Command { public static final String COMMAND_WORD = "mark"; public static final String MESSAGE_INVALID_TASK = "This task is missing in the task manager."; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks the task completed or not completed \n" + "Parameters: KEYWORD [MORE_KEYWORDS]...\n" + "Example: " + COMMAND_WORD + " task_number completed OR not_completed"; private final Set<String> keywords; public MarkCommand(Set<String> keywords) { this.keywords = keywords; } @Override public CommandResult execute() throws CommandException { List<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); String[] parameters = keywords.toArray(new String[keywords.size()]); int filteredTaskListIndex = Integer.parseInt(parameters[0]) - 1; ReadOnlyTask taskToEdit; if (filteredTaskListIndex < lastShownList.size() && filteredTaskListIndex != -1) taskToEdit = lastShownList.get(filteredTaskListIndex); else throw new CommandException(MESSAGE_INVALID_TASK); Task editedTask = createEditedTask(taskToEdit, parameters[1]); //@@author A0119505J try { model.markTask(filteredTaskListIndex, editedTask); } catch (TaskNotFoundException e) { throw new CommandException(MESSAGE_INVALID_TASK); } return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size())); } /** * Creates and returns a {@code Task} with the details of {@code taskToEdit} * edited with {@code editTaskDescriptor}. */ private static Task createEditedTask(ReadOnlyTask taskToEdit, String status) { assert taskToEdit != null; int flag; if (status.equals("completed")) { flag = 1; } else { flag = 0; } Status stat = new Status(flag); Name updatedName = taskToEdit.getName(); Time updatedEndTime = taskToEdit.getEndTime(); Time updatedStartTime = taskToEdit.getStartTime(); Status updatedStatus = stat; Priority updatedPriority = taskToEdit.getPriority(); UniqueTagList updatedTags = taskToEdit.getTags(); return new Task(updatedName, updatedStartTime, updatedEndTime, updatedPriority, updatedTags, updatedStatus); } }
package uk.ac.ebi.spot.goci.curation.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import uk.ac.ebi.spot.goci.curation.exception.FileUploadException; import uk.ac.ebi.spot.goci.curation.exception.NoStudyDirectoryException; import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException; import uk.ac.ebi.spot.goci.curation.model.Assignee; import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport; import uk.ac.ebi.spot.goci.curation.model.StatusAssignment; import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter; import uk.ac.ebi.spot.goci.curation.service.CurrentUserDetailsService; import uk.ac.ebi.spot.goci.curation.service.EventsViewService; import uk.ac.ebi.spot.goci.curation.service.MappingDetailsService; import uk.ac.ebi.spot.goci.curation.service.StudyDeletionService; import uk.ac.ebi.spot.goci.curation.service.StudyDuplicationService; import uk.ac.ebi.spot.goci.curation.service.StudyFileService; import uk.ac.ebi.spot.goci.curation.service.StudyOperationsService; import uk.ac.ebi.spot.goci.curation.service.StudyUpdateService; import uk.ac.ebi.spot.goci.curation.service.PublicationOperationsService; import uk.ac.ebi.spot.goci.curation.service.deposition.DepositionSubmissionService; import uk.ac.ebi.spot.goci.model.*; import uk.ac.ebi.spot.goci.model.deposition.DepositionProvenance; import uk.ac.ebi.spot.goci.model.deposition.Submission; import uk.ac.ebi.spot.goci.repository.*; import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.concurrent.Callable; @Controller @RequestMapping("/studies") public class StudyController { @Value("${deposition.ui.uri}") private String depositionUiURL; private final StudyExtensionRepository studyExtensionRepository; private final DepositionSubmissionService submissionService; // Repositories allowing access to database objects associated with a study private StudyRepository studyRepository; private HousekeepingRepository housekeepingRepository; private DiseaseTraitRepository diseaseTraitRepository; private EfoTraitRepository efoTraitRepository; private CuratorRepository curatorRepository; private CurationStatusRepository curationStatusRepository; private PlatformRepository platformRepository; private AssociationRepository associationRepository; private AncestryRepository ancestryRepository; private UnpublishReasonRepository unpublishReasonRepository; private GenotypingTechnologyRepository genotypingTechnologyRepository; private PublicationOperationsService publicationOperationsService; // Services //private DefaultPubMedSearchService defaultPubMedSearchService; private StudyOperationsService studyOperationsService; private MappingDetailsService mappingDetailsService; private CurrentUserDetailsService currentUserDetailsService; private StudyFileService studyFileService; private StudyDuplicationService studyDuplicationService; private StudyDeletionService studyDeletionService; private EventsViewService eventsViewService; private StudyUpdateService studyUpdateService; private static final int MAX_PAGE_ITEM_DISPLAY = 25; private Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } @Autowired public StudyController(StudyRepository studyRepository, HousekeepingRepository housekeepingRepository, DiseaseTraitRepository diseaseTraitRepository, EfoTraitRepository efoTraitRepository, CuratorRepository curatorRepository, CurationStatusRepository curationStatusRepository, PlatformRepository platformRepository, AssociationRepository associationRepository, AncestryRepository ancestryRepository, UnpublishReasonRepository unpublishReasonRepository, GenotypingTechnologyRepository genotypingTechnologyRepository, StudyOperationsService studyOperationsService, MappingDetailsService mappingDetailsService, CurrentUserDetailsService currentUserDetailsService, StudyFileService studyFileService, StudyDuplicationService studyDuplicationService, StudyDeletionService studyDeletionService, @Qualifier("studyEventsViewService") EventsViewService eventsViewService, StudyUpdateService studyUpdateService, PublicationOperationsService publicationOperationsService, StudyExtensionRepository studyExtensionRepository, DepositionSubmissionService submissionService) { this.studyRepository = studyRepository; this.housekeepingRepository = housekeepingRepository; this.diseaseTraitRepository = diseaseTraitRepository; this.efoTraitRepository = efoTraitRepository; this.curatorRepository = curatorRepository; this.curationStatusRepository = curationStatusRepository; this.platformRepository = platformRepository; this.associationRepository = associationRepository; this.ancestryRepository = ancestryRepository; this.unpublishReasonRepository = unpublishReasonRepository; this.genotypingTechnologyRepository = genotypingTechnologyRepository; this.studyOperationsService = studyOperationsService; this.mappingDetailsService = mappingDetailsService; this.currentUserDetailsService = currentUserDetailsService; this.studyFileService = studyFileService; this.studyDuplicationService = studyDuplicationService; this.studyDeletionService = studyDeletionService; this.eventsViewService = eventsViewService; this.studyUpdateService = studyUpdateService; this.publicationOperationsService = publicationOperationsService; this.studyExtensionRepository = studyExtensionRepository; this.submissionService = submissionService; } /* All studies and various filtered lists */ @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String allStudiesPage(Model model, @RequestParam(required = false) Integer page, @RequestParam(required = false) String pubmed, @RequestParam(required = false) String author, @RequestParam(value = "studytype", required = false) String studyType, @RequestParam(value = "efotraitid", required = false) Long efoTraitId, @RequestParam(value = "notesquery", required = false) String notesQuery, @RequestParam(required = false) String gcstId, @RequestParam(required = false) String studyId, @RequestParam(required = false) Long status, @RequestParam(required = false) Long curator, @RequestParam(value = "sorttype", required = false) String sortType, @RequestParam(value = "diseasetraitid", required = false) Long diseaseTraitId, @RequestParam(required = false) Integer year, @RequestParam(required = false) Integer month) { model.addAttribute("baseUrl", depositionUiURL); // This is passed back to model and determines if pagination is applied Boolean pagination = true; // Return all studies ordered by date if no page number given if (page == null) { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } // This will be returned to view and store what curator has searched for StudySearchFilter studySearchFilter = new StudySearchFilter(); // Store filters which will be need for pagination bar and to build URI passed back to view String filters = ""; // Set sort object and sort string for URI Sort sort = findSort(sortType); String sortString = ""; if (sortType != null && !sortType.isEmpty()) { sortString = "&sorttype=" + sortType; } // This is the default study page will all studies Page<Study> studyPage = studyRepository.findAll(constructPageSpecification(page - 1, sort)); // For multi-snp and snp interaction studies pagination is not applied as the query leads to duplicates List<Study> studies = null; // THOR // Search by pubmed ID option available from landing page if (pubmed != null && !pubmed.isEmpty()) { studyPage = studyRepository.findByPublicationIdPubmedId(pubmed, constructPageSpecification(page - 1, sort)); filters = filters + "&pubmed=" + pubmed; studySearchFilter.setPubmedId(pubmed); } // Search by author option available from landing page // THOR if (author != null && !author.isEmpty()) { studyPage = studyRepository.findByPublicationIdFirstAuthorFullnameStandardContainingIgnoreCase(author, constructPageSpecification(page - 1, sort)); filters = filters + "&author=" + author; studySearchFilter.setAuthor(author); } // Search by study type if (studyType != null && !studyType.isEmpty()) { if (studyType.equals("GXE")) { studyPage = studyRepository.findByGxe(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("GXG")) { studyPage = studyRepository.findByGxg(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("CNV")) { studyPage = studyRepository.findByCnv(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("Genome-wide genotyping array studies")) { // studyPage = studyRepository.findByGenomewideArray(true, constructPageSpecification(page - 1, // sort)); studyPage = studyRepository.findByGenotypingTechnologiesGenotypingTechnology("Genome-wide genotyping array", constructPageSpecification(page - 1, sort)); } if (studyType.equals("Targeted genotyping array studies")) { studyPage = studyRepository.findByGenotypingTechnologiesGenotypingTechnology("Targeted genotyping array", constructPageSpecification(page - 1, sort)); } if (studyType.equals("Exome genotyping array studies")) { studyPage = studyRepository.findByGenotypingTechnologiesGenotypingTechnology("Exome genotyping array", constructPageSpecification(page - 1, sort)); } if (studyType.equals("Exome-wide sequencing studies")) { studyPage = studyRepository.findByGenotypingTechnologiesGenotypingTechnology("Exome-wide sequencing", constructPageSpecification(page - 1, sort)); } if (studyType.equals("Genome-wide sequencing studies")) { studyPage = studyRepository.findByGenotypingTechnologiesGenotypingTechnology("Genome-wide sequencing", constructPageSpecification(page - 1, sort)); } if (studyType.equals("Studies in curation queue")) { CurationStatus errorStatus = curationStatusRepository.findByStatus("Publish study"); Long errorStatusId = errorStatus.getId(); studyPage = studyRepository.findByHousekeepingCurationStatusIdNot(errorStatusId, constructPageSpecification( page - 1, sort)); } if (studyType.equals("p-Value Set")) { studyPage = studyRepository.findByFullPvalueSet(true,constructPageSpecification(page - 1, sort)); } if (studyType.equals("User Requested")) { studyPage = studyRepository.findByUserRequested(true,constructPageSpecification(page - 1, sort)); } if (studyType.equals("Open Targets")) { studyPage = studyRepository.findByOpenTargets(true,constructPageSpecification(page - 1, sort)); } if (studyType.equals("Multi-SNP haplotype studies")) { studies = studyRepository.findStudyDistinctByAssociationsMultiSnpHaplotypeTrue(sort); pagination = false; } if (studyType.equals("SNP Interaction studies")) { studies = studyRepository.findStudyDistinctByAssociationsSnpInteractionTrue(sort); pagination = false; } studySearchFilter.setStudyType(studyType); filters = filters + "&studytype=" + studyType; } // Search by efo trait id if (efoTraitId != null) { studyPage = studyRepository.findByEfoTraitsId(efoTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setEfoTraitSearchFilterId(efoTraitId); filters = filters + "&efotraitid=" + efoTraitId; } // Search by disease trait id if (diseaseTraitId != null) { studyPage = studyRepository.findByDiseaseTraitId(diseaseTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setDiseaseTraitSearchFilterId(diseaseTraitId); filters = filters + "&diseasetraitid=" + diseaseTraitId; } // Search by notes for entered string -- Removed Distinct because publicationDate is another table if (notesQuery != null && !notesQuery.isEmpty()) { studyPage = studyRepository.findByNotesTextNoteContainingIgnoreCase(notesQuery, constructPageSpecification(page - 1, sort)); studySearchFilter.setNotesQuery(notesQuery); filters = filters + "&notesquery=" + notesQuery; } // If user entered a status if (status != null) { // If we have curator and status find by both if (curator != null) { // This is just used to link from reports tab if (year != null && month != null) { studyPage = studyRepository.findByPublicationDateAndCuratorAndStatus(curator, status, year, month, constructPageSpecification( page - 1, sort)); studySearchFilter.setMonthFilter(month); studySearchFilter.setYearFilter(year); filters = filters + "&status=" + status + "&curator=" + curator + "&year=" + year + "&month=" + month; } else { studyPage = studyRepository.findByHousekeepingCurationStatusIdAndHousekeepingCuratorId(status, curator, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status + "&curator=" + curator; } // Return these values so they appear in filter results studySearchFilter.setCuratorSearchFilterId(curator); studySearchFilter.setStatusSearchFilterId(status); } else { studyPage = studyRepository.findByHousekeepingCurationStatusId(status, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status; // Return this value so it appears in filter result studySearchFilter.setStatusSearchFilterId(status); } } // If user entered curator else if (curator != null) { studyPage = studyRepository.findByHousekeepingCuratorId(curator, constructPageSpecification( page - 1, sort)); filters = filters + "&curator=" + curator; // Return this value so it appears in filter result studySearchFilter.setCuratorSearchFilterId(curator); } else if (gcstId != null) { studyPage = studyRepository.findByAccessionId(gcstId, constructPageSpecification( page - 1, sort)); filters = filters + "&gcstId=" + gcstId; // Return this value so it appears in filter result studySearchFilter.setGcstId(gcstId); } else if (studyId != null) { studyPage = studyRepository.findById(Long.valueOf(studyId), constructPageSpecification( page - 1, sort)); filters = filters + "&studyId=" + studyId; // Return this value so it appears in filter result studySearchFilter.setStudyId(studyId); } // Return URI, this will build thymeleaf links using by sort buttons. // At present, do not add the current sort to the URI, // just maintain any filter values (pubmed id, author etc) used by curator String uri = "/studies?page=1"; if (!filters.isEmpty()) { uri = uri + filters; } model.addAttribute("uri", uri); // Return study page and filters, // filters will be used by pagination bar if (!filters.isEmpty()) { if (!sortString.isEmpty()) { filters = filters + sortString; } } // If user has just sorted without any filter we need // to pass this back to pagination bar else { if (!sortString.isEmpty()) { filters = sortString; } } model.addAttribute("filters", filters); long totalStudies; int current = 1; // Construct table using pagination if (studies == null) { model.addAttribute("studies", studyPage); //Pagination variables totalStudies = studyPage.getTotalElements(); current = studyPage.getNumber() + 1; int begin = Math.max(1, current - 5); // Returns the greater of two values int end = Math.min(begin + 10, studyPage.getTotalPages()); // how many pages to display in the pagination bar model.addAttribute("beginIndex", begin); model.addAttribute("endIndex", end); model.addAttribute("currentIndex", current); } else { model.addAttribute("studies", studies); totalStudies = studies.size(); } model.addAttribute("totalStudies", totalStudies); model.addAttribute("pagination", pagination); // Add studySearchFilter to model so user can filter table model.addAttribute("studySearchFilter", studySearchFilter); // Add assignee and status assignment so user can assign // study to curator or assign a status // Also set uri so we can redirect to page user was on Assignee assignee = new Assignee(); StatusAssignment statusAssignment = new StatusAssignment(); assignee.setUri("/studies?page=" + current + filters); statusAssignment.setUri("/studies?page=" + current + filters); model.addAttribute("assignee", assignee); model.addAttribute("statusAssignment", statusAssignment); Map<String, String> pubmedMap = submissionService.getSubmissionPubMedIds(); studyPage.forEach(study->{ if(pubmedMap.containsKey(study.getPublicationId().getPubmedId())){ study.getPublicationId().setActiveSubmission(true); study.getPublicationId().setSubmissionId(pubmedMap.get(study.getPublicationId().getPubmedId())); } }); return "studies"; } // Redirects from landing page and main page @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter) { // Get ids of objects searched for Long status = studySearchFilter.getStatusSearchFilterId(); Long curator = studySearchFilter.getCuratorSearchFilterId(); String pubmedId = studySearchFilter.getPubmedId(); String author = studySearchFilter.getAuthor(); String studyType = studySearchFilter.getStudyType(); Long efoTraitId = studySearchFilter.getEfoTraitSearchFilterId(); String notesQuery = studySearchFilter.getNotesQuery(); Long diseaseTraitId = studySearchFilter.getDiseaseTraitSearchFilterId(); String gcstId = studySearchFilter.getGcstId(); String studyId = studySearchFilter.getStudyId(); // Search by pubmed ID option available from landing page if (pubmedId != null && !pubmedId.isEmpty()) { return "redirect:/studies?page=1&pubmed=" + pubmedId; } // Search by author option available from landing page else if (author != null && !author.isEmpty()) { return "redirect:/studies?page=1&author=" + author; } // Search by study type else if (studyType != null && !studyType.isEmpty()) { return "redirect:/studies?page=1&studytype=" + studyType; } // Search by efo trait else if (efoTraitId != null) { return "redirect:/studies?page=1&efotraitid=" + efoTraitId; } // Search by disease trait else if (diseaseTraitId != null) { return "redirect:/studies?page=1&diseasetraitid=" + diseaseTraitId; } // Search by string in notes else if (notesQuery != null && !notesQuery.isEmpty()) { return "redirect:/studies?page=1&notesquery=" + notesQuery; } // If user entered a status else if (status != null) { // If we have curator and status find by both if (curator != null) { return "redirect:/studies?page=1&status=" + status + "&curator=" + curator; } else { return "redirect:/studies?page=1&status=" + status; } } // If user entered curator else if (curator != null) { return "redirect:/studies?page=1&curator=" + curator; } else if(gcstId != null){ return "redirect:/studies?page=1&gcstId=" + gcstId; } else if(studyId != null){ return "redirect:/studies?page=1&studyId=" + studyId; } // If all else fails return all studies else { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } } /* New Study: * * Adding a study is synchronised to ensure the method can only be accessed once. * * */ // Add a new study // Directs user to an empty form to which they can create a new study @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String newStudyForm(Model model) { model.addAttribute("study", new Study()); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } // Save study found by Pubmed Id // @ModelAttribute is a reference to the object holding the data entered in the form @CrossOrigin @RequestMapping(value = "/new/import", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<ArrayList<HashMap<String,String>>> importStudy(@RequestBody String pubmedIdForImport, HttpServletRequest request) { ArrayList<HashMap<String,String>> result = new ArrayList<>(); SecureUser currentUser = currentUserDetailsService.getUserFromRequest(request); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/json; charset=utf-8"); result = publicationOperationsService.importNewPublications(pubmedIdForImport, currentUser); return new ResponseEntity<>(result,responseHeaders,HttpStatus.OK); } // Option 2: move this functionality as JAVA migration. @RequestMapping(value = "/new/migratePublications", produces = MediaType.TEXT_HTML_VALUE, method = {RequestMethod.GET,RequestMethod.POST}) public synchronized String importAllStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport, HttpServletRequest request, Model model) throws PubmedImportException, NoStudyDirectoryException { publicationOperationsService.importPublicationsWithoutFirstAuthor(); return "redirect:/studies/"; } // Save newly added study details // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public synchronized String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model, HttpServletRequest request) throws NoStudyDirectoryException { // If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix if (bindingResult.hasErrors()) { model.addAttribute("study", study); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } Study savedStudy = studyOperationsService.createStudy(study, currentUserDetailsService.getUserFromRequest(request)); // Create directory to store associated files try { studyFileService.createStudyDir(savedStudy.getId()); } catch (NoStudyDirectoryException e) { getLog().error("No study directory exception"); model.addAttribute("study", savedStudy); return "error_pages/study_dir_failure"; } return "redirect:/studies/" + savedStudy.getId(); } /* Existing study*/ // View a study @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudy(Model model, @PathVariable Long studyId) { Study studyToView = studyRepository.findOne(studyId); Map<String, String> pubmedMap = submissionService.getSubmissionPubMedIds(); if(pubmedMap.containsKey(studyToView.getPublicationId().getPubmedId())){ studyToView.getPublicationId().setActiveSubmission(true); studyToView.getPublicationId().setSubmissionId(pubmedMap.get(studyToView.getPublicationId().getPubmedId())); } model.addAttribute("study", studyToView); if(studyToView.getStudyExtension() == null){ StudyExtension extension = new StudyExtension(); extension.setStudy(studyToView); studyToView.setStudyExtension(extension); } model.addAttribute("extension", studyToView.getStudyExtension()); DepositionProvenance depositionProvenance = submissionService.getProvenance(studyToView.getPublicationId().getPubmedId()); model.addAttribute("submitter", depositionProvenance.getUser()); return "study"; } // Edit an existing study // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudy(@ModelAttribute Study study, @ModelAttribute StudyExtension extension, @PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { // xintodo edit study if(extension == null){ extension = new StudyExtension(); } studyUpdateService.updateStudy(studyId, study, extension, currentUserDetailsService.getUserFromRequest(request)); // Add save message String message = "Changes saved successfully"; redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId(); } //For @RequestParam we can use, @RequestParam(value="somevalue", required=false) and for optional params rather than a pathVariable @CrossOrigin @RequestMapping(value = "/{studyId}/changeFirstAuthor/{authorId}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<HashMap<String,String>> changeFirstAuthor(@PathVariable(value="studyId") Long studyId, @PathVariable(value="authorId") Long authorId) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/json; charset=utf-8"); HashMap<String, String> result = new HashMap<String, String>(); Boolean isChangeAuthor = publicationOperationsService.changeFirstAuthorByStudyId(studyId,authorId); String key = (isChangeAuthor) ? "success": "error"; result.put(key, ""); return new ResponseEntity<>(result,responseHeaders,HttpStatus.OK); } // Delete an existing study @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyToDelete(Model model, @PathVariable Long studyId) { Study studyToDelete = studyRepository.findOne(studyId); // Check if it has any associations Collection<Association> associations = associationRepository.findByStudyId(studyId); Long housekeepingId = studyToDelete.getHousekeeping().getId(); Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId); model.addAttribute("studyToDelete", studyToDelete); if (housekeepingAttachedToStudy.getCatalogPublishDate() != null) { return "delete_published_study_warning"; } else if (!associations.isEmpty()) { return "delete_study_with_associations_warning"; } else { return "delete_study"; } } @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String deleteStudy(@PathVariable Long studyId, HttpServletRequest request) { // Find our study based on the ID Study studyToDelete = studyRepository.findOne(studyId); studyDeletionService.deleteStudy(studyToDelete, currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies"; } // Duplicate a study /* @RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find study user wants to duplicate, based on the ID Study studyToDuplicate = studyRepository.findOne(studyId); Study duplicateStudy = studyDuplicationService.duplicateStudy(studyToDuplicate, currentUserDetailsService.getUserFromRequest( request)); // Add duplicate message String message = "Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId(); redirectAttributes.addFlashAttribute("duplicateMessage", message); return "redirect:/studies/" + duplicateStudy.getId(); } */ // Duplicate a study GET form @RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String duplicateStudyGet(Model model, @PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { Study studyToDuplicate = studyRepository.findOne(studyId); model.addAttribute("study", studyToDuplicate); return "study_duplication"; } // Duplication a study POST form @RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<String> duplicateStudyPost(@PathVariable Long studyId, @RequestBody String tagsNoteList, HttpServletRequest request) { String result = ""; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/json; charset=utf-8"); // Find study user wants to duplicate, based on the ID Study studyToDuplicate = studyRepository.findOne(studyId); SecureUser secureUser = currentUserDetailsService.getUserFromRequest(request); result = studyDuplicationService.create(studyToDuplicate,tagsNoteList, secureUser); if (result == "") { result = new StringBuilder("{\"success\":\"studies?page=1&pubmed=").append(studyToDuplicate.getPublicationId().getPubmedId()).append("\"}").toString(); } return new ResponseEntity<>(result,responseHeaders,HttpStatus.OK); } // Assign a curator to a study @RequestMapping(value = "/{studyId}/assign", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String assignStudyCurator(@PathVariable Long studyId, @ModelAttribute Assignee assignee, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find the study and the curator user wishes to assign Study study = studyRepository.findOne(studyId); if (assignee.getCuratorId() == null) { String blankAssignee = "Cannot assign a blank value as a curator for study: " + study.getPublicationId().getFirstAuthor().getFullnameShort(30) + ", " + " pubmed = " + study.getPublicationId().getPubmedId(); redirectAttributes.addFlashAttribute("blankAssignee", blankAssignee); } else { studyOperationsService.assignStudyCurator(study, assignee, currentUserDetailsService.getUserFromRequest(request)); } return "redirect:" + assignee.getUri(); } // Assign a status to a study @RequestMapping(value = "/{studyId}/status_update", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String assignStudyStatus(@PathVariable Long studyId, @ModelAttribute StatusAssignment statusAssignment, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find the study and the curator user wishes to assign Study study = studyRepository.findOne(studyId); if (statusAssignment.getStatusId() == null) { String blankStatus = "Cannot assign a blank value as a status for study: " + study.getPublicationId().getFirstAuthor().getFullnameShort(30) + ", " + " pubmed = " + study.getPublicationId().getPubmedId(); redirectAttributes.addFlashAttribute("blankStatus", blankStatus); } else { String message = studyOperationsService.assignStudyStatus(study, statusAssignment, currentUserDetailsService.getUserFromRequest( request)); redirectAttributes.addFlashAttribute("studySnpsNotApproved", message); } return "redirect:" + statusAssignment.getUri(); } /* Study housekeeping/curator information */ // Generate page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) { // Find study Study study = studyRepository.findOne(studyId); // If we don't have a housekeeping object create one, this should not occur though as they are created when study is created if (study.getHousekeeping() == null) { model.addAttribute("studyHousekeeping", new Housekeeping()); } else { model.addAttribute("studyHousekeeping", study.getHousekeeping()); } // Return the housekeeping object attached to study and return the study model.addAttribute("study", study); // Return a DTO that holds a summary of any automated mappings model.addAttribute("mappingDetails", mappingDetailsService.createMappingSummary(study)); return "study_housekeeping"; } // Update page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping, @PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Establish linked study Study study = studyRepository.findOne(studyId); // Update housekeeping String message = studyOperationsService.updateHousekeeping(housekeeping, study, currentUserDetailsService.getUserFromRequest(request)); // Add save message if (message == null) { message = "Changes saved successfully"; redirectAttributes.addFlashAttribute("changesSaved", message); } else{ redirectAttributes.addFlashAttribute("publishError", message); } // redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId() + "/housekeeping"; } @RequestMapping(value = "/{studyId}/unpublish", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyToUnpublish(Model model, @PathVariable Long studyId) { Study studyToUnpublish = studyRepository.findOne(studyId); // Check if it has any associations or ancestry information // Collection<Association> associations = associationRepository.findByStudyId(studyId); // Collection<Ancestry> ancestryInfo = ancestryRepository.findByStudyId(studyId); // // If so warn the curator // if (!associations.isEmpty() || !ancestryInfo.isEmpty()) { // model.addAttribute("study", studyToUnpublish); // return "unpublish_study_with_associations_warning"; // else { model.addAttribute("studyToUnpublish", studyToUnpublish); return "unpublish_study"; } @RequestMapping(value = "/{studyId}/unpublish", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String unpublishStudy(@ModelAttribute Study studyToUnpublish, @PathVariable Long studyId, HttpServletRequest request) { // studyToUnpuplish attribute is used simply to retrieve unpublsih reason studyOperationsService.unpublishStudy(studyId, studyToUnpublish.getHousekeeping().getUnpublishReason(), currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies/" + studyToUnpublish.getId() + "/housekeeping"; } // Find correct sorting type and direction private Sort findSort(String sortType) { // Default sort by date Sort sort = sortByPublicationDateDesc(); Map<String, Sort> sortTypeMap = new HashMap<>(); sortTypeMap.put("authorsortasc", sortByAuthorAsc()); sortTypeMap.put("authorsortdesc", sortByAuthorDesc()); sortTypeMap.put("titlesortasc", sortByTitleAsc()); sortTypeMap.put("titlesortdesc", sortByTitleDesc()); sortTypeMap.put("publicationdatesortasc", sortByPublicationDateAsc()); sortTypeMap.put("publicationdatesortdesc", sortByPublicationDateDesc()); sortTypeMap.put("pubmedsortasc", sortByPubmedIdAsc()); sortTypeMap.put("pubmedsortdesc", sortByPubmedIdDesc()); sortTypeMap.put("userrequestedsortasc", sortByUserRequestedAsc()); sortTypeMap.put("userrequestedsortdesc", sortByUserRequestedDesc()); sortTypeMap.put("opentargetssortasc", sortByOpenTargetsAsc()); sortTypeMap.put("opentargetssortdesc", sortByOpenTargetsDesc()); sortTypeMap.put("publicationsortasc", sortByPublicationAsc()); sortTypeMap.put("publicationsortdesc", sortByPublicationDesc()); sortTypeMap.put("efotraitsortasc", sortByEfoTraitAsc()); sortTypeMap.put("efotraitsortdesc", sortByEfoTraitDesc()); sortTypeMap.put("diseasetraitsortasc", sortByDiseaseTraitAsc()); sortTypeMap.put("diseasetraitsortdesc", sortByDiseaseTraitDesc()); sortTypeMap.put("curatorsortasc", sortByCuratorAsc()); sortTypeMap.put("curatorsortdesc", sortByCuratorDesc()); sortTypeMap.put("curationstatussortasc", sortByCurationStatusAsc()); sortTypeMap.put("curationstatussortdesc", sortByCurationStatusDesc()); if (sortType != null && !sortType.isEmpty()) { sort = sortTypeMap.get(sortType); } return sort; } /* Functionality to view, upload and download a study file(s)*/ @RequestMapping(value = "/{studyId}/studyfiles", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String getStudyFiles(Model model, @PathVariable Long studyId) { model.addAttribute("files", studyFileService.getStudyFiles(studyId)); model.addAttribute("study", studyRepository.findOne(studyId)); return "study_files"; } @RequestMapping(value = "/{studyId}/studyfiles/{fileName}", method = RequestMethod.GET) @ResponseBody public FileSystemResource downloadStudyFile(@PathVariable Long studyId, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException { // Using this logic so can get full file name, if it was an @PathVariable everything after final '.' would be removed String path = request.getServletPath(); String fileName = path.substring(path.lastIndexOf('/') + 1); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); return new FileSystemResource(studyFileService.getFileFromFileName(studyId, fileName)); } @RequestMapping(value = "/{studyId}/studyfiles/{fileName}/delete", method = RequestMethod.GET) public String deleteStudyFile(@PathVariable Long studyId, @PathVariable String fileName) { studyFileService.deleteFile(studyId, fileName); return "redirect:/studies/" + studyId + "/studyfiles"; } @RequestMapping(value = "/{studyId}/studyfiles", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public Callable<String> uploadStudyFile(@RequestParam("file") MultipartFile file, @PathVariable Long studyId, Model model, HttpServletRequest request) throws FileUploadException, IOException { model.addAttribute("study", studyRepository.findOne(studyId)); // Return view return () -> { try { studyFileService.upload(file, studyId); studyFileService.createFileUploadEvent(studyId, currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies/" + studyId + "/studyfiles"; } catch (FileUploadException | IOException e) { getLog().error("File upload exception", e); return "error_pages/study_file_upload_failure"; } }; } @RequestMapping(value = "/{studyId}/tracking", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String getStudyEvents(Model model, @PathVariable Long studyId) { model.addAttribute("events", eventsViewService.createViews(studyId)); model.addAttribute("study", studyRepository.findOne(studyId)); return "study_events"; } /* Exception handling */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(PubmedLookupException.class) public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) { getLog().error("pubmed lookup exception", pubmedLookupException); return "pubmed_lookup_warning"; } @ExceptionHandler(PubmedImportException.class) public String handlePubmedImportException(PubmedImportException pubmedImportException) { getLog().error("pubmed import exception", pubmedImportException); return "pubmed_import_warning"; } @ExceptionHandler({FileNotFoundException.class}) public String handleFileNotFound() { return "error_pages/file_not_found"; } /* Model Attributes : * Used for dropdowns in HTML forms */ // Disease Traits @ModelAttribute("diseaseTraits") public List<DiseaseTrait> populateDiseaseTraits() { return diseaseTraitRepository.findAll(sortByTraitAsc()); } // EFO traits @ModelAttribute("efoTraits") public List<EfoTrait> populateEFOTraits() { return efoTraitRepository.findAll(sortByTraitAsc()); } // // Background traits // @ModelAttribute("studyExtensions") // public List<StudyExtension> populateBackgroundTraits() { // return studyExtensionRepository.findAll(sortByTraitAsc()); // Curators @ModelAttribute("curators") public List<Curator> populateCurators() { return curatorRepository.findAll(sortByLastNameAsc()); } //Platforms @ModelAttribute("platforms") public List<Platform> populatePlatforms() {return platformRepository.findAll(); } @ModelAttribute("genotypingTechnologies") public List<GenotypingTechnology> populateGenotypingTechnologies() {return genotypingTechnologyRepository.findAll();} // Curation statuses @ModelAttribute("curationstatuses") public List<CurationStatus> populateCurationStatuses() { return curationStatusRepository.findAll(sortByStatusAsc()); } // Unpublish reasons @ModelAttribute("unpublishreasons") public List<UnpublishReason> populateUnpublishReasons() { return unpublishReasonRepository.findAll(); } // Study types @ModelAttribute("studyTypes") public List<String> populateStudyTypeOptions() { List<String> studyTypesOptions = new ArrayList<String>(); studyTypesOptions.add("GXE"); studyTypesOptions.add("GXG"); studyTypesOptions.add("CNV"); studyTypesOptions.add("Genome-wide genotyping array studies"); studyTypesOptions.add("Targeted genotyping array studies"); studyTypesOptions.add("Exome genotyping array studies"); studyTypesOptions.add("Genome-wide sequencing studies"); studyTypesOptions.add("Exome-wide sequencing studies"); studyTypesOptions.add("Studies in curation queue"); studyTypesOptions.add("Multi-SNP haplotype studies"); studyTypesOptions.add("SNP Interaction studies"); studyTypesOptions.add("p-Value Set"); studyTypesOptions.add("User Requested"); studyTypesOptions.add("Open Targets"); return studyTypesOptions; } @ModelAttribute("qualifiers") public List<String> populateQualifierOptions() { List<String> qualifierOptions = new ArrayList<>(); qualifierOptions.add("up to"); qualifierOptions.add("at least"); qualifierOptions.add("~"); qualifierOptions.add(">"); return qualifierOptions; } // Authors // THOR @ModelAttribute("authors") public List<String> populateAuthors() { return publicationOperationsService.listFirstAuthors(); } /* Sorting options */ private Sort sortByLastNameAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "lastName").ignoreCase()); } private Sort sortByStatusAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "status").ignoreCase()); } // Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case private Sort sortByTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase()); } private Sort sortByPublicationDateAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationId.publicationDate")); } private Sort sortByPublicationDateDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationId.publicationDate")); } private Sort sortByAuthorAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationId.firstAuthor.fullname").ignoreCase()); } private Sort sortByAuthorDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationId.firstAuthor.fullname").ignoreCase()); } private Sort sortByTitleAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationId.title").ignoreCase()); } private Sort sortByTitleDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationId.title").ignoreCase()); } private Sort sortByPublicationAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationId.publication").ignoreCase()); } private Sort sortByPublicationDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationId.publication").ignoreCase()); } private Sort sortByPubmedIdAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationId.pubmedId")); } private Sort sortByUserRequestedAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "userRequested")); } private Sort sortByUserRequestedDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "userRequested")); } private Sort sortByOpenTargetsAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "openTargets")); } private Sort sortByOpenTargetsDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "openTargets")); } private Sort sortByPubmedIdDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationId.pubmedId")); } private Sort sortByDiseaseTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "diseaseTrait.trait").ignoreCase()); } private Sort sortByDiseaseTraitDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "diseaseTrait.trait").ignoreCase()); } private Sort sortByEfoTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "efoTraits.trait").ignoreCase()); } private Sort sortByEfoTraitDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "efoTraits.trait").ignoreCase()); } private Sort sortByCuratorAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curator.lastName").ignoreCase()); } private Sort sortByCuratorDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curator.lastName").ignoreCase()); } private Sort sortByCurationStatusAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curationStatus.status")); } private Sort sortByCurationStatusDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curationStatus.status")); } /* Pagination */ // Pagination, method passed page index and includes max number of studies, sorted by study date, to return private Pageable constructPageSpecification(int pageIndex, Sort sort) { return new PageRequest(pageIndex, MAX_PAGE_ITEM_DISPLAY, sort); } }
package ai.grakn.engine.backgroundtasks.taskstatestorage; import ai.grakn.engine.backgroundtasks.TaskStateStorage; import ai.grakn.engine.backgroundtasks.TaskState; import ai.grakn.engine.TaskStatus; import ai.grakn.engine.backgroundtasks.distributed.ZookeeperConnection; import ai.grakn.exception.EngineStorageException; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.engine.backgroundtasks.config.ZookeeperPaths.TASKS_PATH_PREFIX; import static ai.grakn.engine.backgroundtasks.config.ZookeeperPaths.TASK_LOCK_SUFFIX; import static ai.grakn.engine.backgroundtasks.config.ZookeeperPaths.TASK_STATE_SUFFIX; import static java.lang.String.format; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang.SerializationUtils.deserialize; import static org.apache.commons.lang.SerializationUtils.serialize; import static org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace; /** * <p> * Manages the state of background {@link ai.grakn.engine.backgroundtasks.BackgroundTask} in * a synchronized manner withing a cluster. This means that all updates must be performed * by acquiring a distributed mutex so that no concurrent writes are possible. * </p> * * @author Denis Lobanov, Alexandra Orth * */ public class TaskStateZookeeperStore implements TaskStateStorage { private static final String ZK_TASK_PATH = TASKS_PATH_PREFIX + "/%s" + TASK_STATE_SUFFIX; private final Logger LOG = LoggerFactory.getLogger(TaskStateZookeeperStore.class); private final CuratorFramework zookeeperConnection; public TaskStateZookeeperStore(ZookeeperConnection connection) { zookeeperConnection = connection.connection(); } @Override public String newState(TaskState task){ InterProcessMutex mutex = mutex(task.getId()); acquire(mutex); try { zookeeperConnection.create() .creatingParentContainersIfNeeded() .forPath(format(ZK_TASK_PATH, task.getId()), serialize(task)); } catch (Exception exception){ throw new EngineStorageException("Could not write state to storage " + getFullStackTrace(exception)); } finally { release(mutex); } return task.getId(); } @Override public Boolean updateState(TaskState task){ InterProcessMutex mutex = mutex(task.getId()); acquire(mutex); try { zookeeperConnection.setData() .forPath(format(ZK_TASK_PATH, task.getId()), serialize(task)); } catch (Exception e) { LOG.error("Could not write to ZooKeeper! - "+e); return false; } finally { release(mutex); } return true; } /** * Retrieve the TaskState associated with the given ID. Acquire a distributed mutex before executing * to ensure most up-to-date state. * @param id String id of task. * @return State of the given task */ @Override public TaskState getState(String id) { InterProcessMutex mutex = mutex(id); try { mutex.acquire(); byte[] b = zookeeperConnection.getData().forPath(TASKS_PATH_PREFIX+"/"+id+TASK_STATE_SUFFIX); return (TaskState) deserialize(b); } catch (Exception e) { throw new EngineStorageException("Could not get state from storage " + getFullStackTrace(e)); } finally { release(mutex); } } /** * This implementation will fetch all of the tasks from zookeeper and then * filer them out. * * ZK stores tasks by ID, so at the moment there is no more efficient way to search * within the storage itself. */ @Override public Set<TaskState> getTasks(TaskStatus taskStatus, String taskClassName, String createdBy, int limit, int offset){ try { Stream<TaskState> stream = zookeeperConnection.getChildren() .forPath(TASKS_PATH_PREFIX).stream() .map(this::getState); if (taskStatus != null) { stream = stream.filter(t -> t.status().equals(taskStatus)); } if (taskClassName != null) { stream = stream.filter(t -> t.taskClassName().equals(taskClassName)); } if (createdBy != null) { stream = stream.filter(t -> t.creator().equals(createdBy)); } stream = stream.skip(offset); if(limit > 0){ stream = stream.limit(limit); } return stream.collect(toSet()); } catch (Exception e){ throw new EngineStorageException("Could not get state from storage " + getFullStackTrace(e)); } } private InterProcessMutex mutex(String id){ return new InterProcessMutex(zookeeperConnection, TASKS_PATH_PREFIX + id + TASK_LOCK_SUFFIX); } private void acquire(InterProcessMutex mutex){ try { mutex.acquire(); } catch (Exception e) { throw new EngineStorageException("Error acquiring mutex from zookeeper."); } } private void release(InterProcessMutex mutex){ try { mutex.release(); } catch (Exception e) { throw new EngineStorageException("Error releasing mutex from zookeeper."); } } }
package org.eclipse.hawkbit.repository; import java.util.Collection; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; /** * Encapsulates a set of filters that may be specified (optionally). Properties * that are not specified (e.g. <code>null</code> for simple properties) When * applied, these filters are AND-gated. * */ public class FilterParams { Collection<TargetUpdateStatus> filterByStatus; Boolean overdueState; String filterBySearchText; Boolean selectTargetWithNoTag; String[] filterByTagNames; Long filterByDistributionId; /** * Constructor. * * @param filterByDistributionId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(Long filterByDistributionId, Collection<TargetUpdateStatus> filterByStatus, Boolean overdueState, String filterBySearchText, Boolean selectTargetWithNoTag, String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByDistributionId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. <br> * If set to <code>null</code> this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Sets {@link DistributionSet#getId()} to filter the result. * * @param filterByDistributionId */ public void setFilterByDistributionId(Long filterByDistributionId) { this.filterByDistributionId = filterByDistributionId; } /** * Gets a collection of target states to filter for. <br> * If set to <code>null</code> this filter is disabled. * * @return collection of target states to filter for */ public Collection<TargetUpdateStatus> getFilterByStatus() { return filterByStatus; } /** * Sets the collection of target states to filter for. * * @param filterByStatus */ public void setFilterByStatus(Collection<TargetUpdateStatus> filterByStatus) { this.filterByStatus = filterByStatus; } /** * Gets the flag for overdue filter; if set to <code>true</code>, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. <br> * If set to <code>null</code> this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Sets the flag for overdue filter; if set to <code>true</code>, the * overdue filter is activated. * * @param overdueState */ public void setOverdueState(Boolean overdueState) { this.overdueState = overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description <br> * If set to <code>null</code> this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Sets the search text to filter for. * * @param filterBySearchText */ public void setFilterBySearchText(String filterBySearchText) { this.filterBySearchText = filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. <br> * If set to <code>null</code> this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Sets the flag indicating if tagging filter is used. * * @param selectTargetWithNoTag */ public void setSelectTargetWithNoTag(Boolean selectTargetWithNoTag) { this.selectTargetWithNoTag = selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } /** * Sets the tags that are used to filter for. * * @param filterByTagNames */ public void setFilterByTagNames(String[] filterByTagNames) { this.filterByTagNames = filterByTagNames; } }
package com.temenos.interaction.core.hypermedia; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.odata4j.core.OCollection; import org.odata4j.core.OCollections; import org.odata4j.core.OComplexObjects; import org.odata4j.core.OProperties; import org.odata4j.core.OProperty; import org.odata4j.edm.EdmCollectionType; import org.odata4j.edm.EdmComplexType; import org.odata4j.edm.EdmEntitySet; import org.odata4j.edm.EdmEntityType; import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmSimpleType; public class TestHypermediaTemplateHelper { @Test public void testGetBaseUri() { assertEquals("http://localhost:8080/responder/rest/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetBaseUriSimple() { assertEquals("http://localhost:8080/responder/rest/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUri() { assertEquals("http://localhost:8080/responder/rest/MockCompany001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriSimple() { assertEquals("http://localhost:8080/responder/rest/MockCompany001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriNested() { assertEquals("http://localhost:8080/responder/rest/MockCompany001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriQueryParameters() { assertEquals("http://localhost:8080/responder/rest/MockCompany001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLookBehind() { assertEquals("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/GB0010001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLookBehind_FundsTransferNew() { assertEquals("http://portal3.xlb2.lo/tapt24-iris/tapt24.svc/LU0010001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLookBehind_FundsTransferValidate() { assertEquals("http://portal3.xlb2.lo/tapt24-iris/tapt24.svc/LU0010001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLookBehind_FundsTransferFtTaps() { assertEquals("http://portal3.xlb2.lo/tapt24-iris/tapt24.svc/LU0010001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLookBehind_FundsTransferFtTapsNewHol() { assertEquals("http://portal3.xlb2.lo/tapt24-iris/tapt24.svc/LU0010001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testGetTemplatedBaseUriLastCharacter() { assertEquals("http://localhost:8080/example/interaction-odata-multicompany.svc/MockCompany001/", HypermediaTemplateHelper.getTemplatedBaseUri("http: } @Test public void testTemplateReplace() { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("companyid", "GB0010001"); assertEquals("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/GB0010001/", HypermediaTemplateHelper.templateReplace("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/{companyid}/", properties)); } @Test public void testSpecialCharacterTemplateReplace() { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("companyid", "GB0010001"); assertEquals("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/GB0010001/$metadata", HypermediaTemplateHelper.templateReplace("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/{companyid}/$metadata", properties)); } @Test public void testPartialTemplateReplace() { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("companyid", "GB0010001"); assertEquals("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/GB0010001/flights/{id}", HypermediaTemplateHelper.templateReplace("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/{companyid}/flights/{id}", properties)); } @Test public void testMultiValueTemplateReplace() { EdmEntitySet setType; EdmEntityType airportsType; EdmCollectionType airportCollectionType; EdmComplexType airportType; List<EdmProperty.Builder> subprops = new ArrayList<EdmProperty.Builder>(); subprops.add(EdmProperty.newBuilder("AirportName").setType(EdmSimpleType.STRING)); airportType = EdmComplexType.newBuilder().setNamespace("InteractionTest").setName("AirportsAirport").addProperties(subprops).build(); List<EdmProperty.Builder> eprops = new ArrayList<EdmProperty.Builder>(); eprops.add(EdmProperty.newBuilder("airport").setType(new EdmCollectionType(EdmProperty.CollectionKind.Bag, airportType))); EdmEntityType.Builder eet = EdmEntityType.newBuilder().setNamespace("InteractionTest").setName("Airports").addKeys(Arrays.asList("ID")).addProperties(eprops); EdmEntitySet.Builder ees = EdmEntitySet.newBuilder().setName("Airports").setEntityType(eet); setType = ees.build(); airportsType = (EdmEntityType)setType.getType(); airportCollectionType = (EdmCollectionType)airportsType.findDeclaredProperty("airport").getType(); airportType = (EdmComplexType)airportCollectionType.getItemType(); List<OProperty<?>> oPropertiesCity1 = new ArrayList<OProperty<?>>(); oPropertiesCity1.add(OProperties.string("AirportName", "London")); List<OProperty<?>> oPropertiesCity2 = new ArrayList<OProperty<?>>(); oPropertiesCity2.add(OProperties.string("AirportName", "Lisbon")); List<OProperty<?>> oPropertiesCity3 = new ArrayList<OProperty<?>>(); oPropertiesCity3.add(OProperties.string("AirportName", "Madrid")); OCollection<?> city1 = OCollections.newBuilder(airportCollectionType). add(OComplexObjects.create(airportType, oPropertiesCity1)).build(); OCollection<?> city2 = OCollections.newBuilder(airportCollectionType). add(OComplexObjects.create(airportType, oPropertiesCity2)).build(); OCollection<?> city3 = OCollections.newBuilder(airportCollectionType). add(OComplexObjects.create(airportType, oPropertiesCity3)).build(); Map<String,Object> properties = new LinkedHashMap<String,Object>(); properties.put("multivaluegroup1", city1); properties.put("multivaluegroup2", city2); properties.put("multivaluegroup3", city3); assertEquals("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/{companyid}/flights/London", HypermediaTemplateHelper.templateReplace("http://127.0.0.1:9081/hothouse-iris/Hothouse.svc/{companyid}/flights/{AirportName}", properties)); } }
package org.intermine.webservice.server.lists; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.mail.MessagingException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.api.InterMineAPI; import org.intermine.api.bag.SharedBagManager; import org.intermine.api.bag.SharingInvite; import org.intermine.api.bag.SharingInvite.NotFoundException; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.api.profile.UserAlreadyShareBagException; import org.intermine.api.profile.UserNotFoundException; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.Emailer; import org.intermine.web.context.InterMineContext; import org.intermine.webservice.client.exceptions.InternalErrorException; import org.intermine.webservice.server.core.JSONService; import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.exceptions.ResourceNotFoundException; import org.intermine.webservice.server.exceptions.ServiceException; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; public class ListSharingInvitationAcceptanceService extends JSONService { private static final Logger LOG = Logger.getLogger(ListSharingInvitationAcceptanceService.class); private static final Set<String> acceptableAcceptances = new HashSet<String>(Arrays.asList("true", "false")); private final SharedBagManager sbm; public ListSharingInvitationAcceptanceService(InterMineAPI im) { super(im); sbm = SharedBagManager.getInstance(im.getProfileManager()); } @Override protected String getResultsKey() { return "list"; } /** * Parameter object, holding the storage of the parsed parameters, and the * logic for weedling them out of the HTTP parameters. */ private final class UserInput { final boolean accepted; final SharingInvite invite; final Profile accepter; final boolean notify; /** * Do the dance of parameter parsing and validation. */ UserInput() { accepter = getPermission().getProfile(); if (!accepter.isLoggedIn()) { throw new ServiceForbiddenException("You must be logged in"); } String token, pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.matches("/[^/]{20}")) { token = pathInfo.substring(1, 21); } else { token = request.getParameter("uid"); } if (StringUtils.isBlank(token)) { throw new BadRequestException("Missing required parameter: 'uid'"); } String isAccepted = request.getParameter("accepted"); if (StringUtils.isBlank(isAccepted)) { throw new BadRequestException("Missing required parameter: 'accepted'"); } else if (!acceptableAcceptances.contains(isAccepted.toLowerCase())) { throw new BadRequestException("The value of the 'accepted' parameter must be one of " + acceptableAcceptances); } accepted = Boolean.parseBoolean(isAccepted); try { invite = SharingInvite.getByToken(im, token); } catch (SQLException e) { throw new InternalErrorException("Error retrieving invitation", e); } catch (ObjectStoreException e) { throw new InternalErrorException("Corrupt invitation", e); } catch (NotFoundException e) { throw new ResourceNotFoundException("invitation does not exist", e); } if (invite == null) { throw new ResourceNotFoundException("Could not find invitation"); } String sendEmail = request.getParameter("notify"); if (StringUtils.isNotBlank(sendEmail) && "true".equalsIgnoreCase(sendEmail)) { notify = true; } else { notify = false; } } } @Override protected void execute() throws ServiceException, NotFoundException { UserInput input = new UserInput(); // Do the acceptance. try { sbm.resolveInvitation(input.invite, input.accepter, input.accepted); } catch (UserNotFoundException e) { throw new InternalErrorException( "Inconsistent state: p.isLoggedIn() but not found in DB"); } catch (UserAlreadyShareBagException e) { LOG.warn("User accepted an invitation to a list they already have access to", e); } // Send back information about the new list, if they accepted. if (input.accepted) { JSONListFormatter formatter = new JSONListFormatter(im, input.accepter, false); addResultItem(formatter.bagToMap(input.invite.getBag()), false); } else { addResultItem((Map) Collections.emptyMap(), false); } if (input.notify) { notifyOwner(input.invite); } } private void notifyOwner(SharingInvite invite) { Emailer emailer = InterMineContext.getEmailer(); ProfileManager pm = im.getProfileManager(); Profile receiver = getPermission().getProfile(); try { emailer.email( pm.getProfileUserName(invite.getBag().getProfileId()), "was-accepted", invite.getCreatedAt(), invite.getInvitee(), invite.getBag(), receiver.getUsername(), webProperties.getProperty("project.title")); } catch (MessagingException e) { LOG.error("Could not notify owner", e); } } }
package com.kumuluz.ee; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.KumuluzServer; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.DataSourceConfig; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.*; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.filters.PoweredByFilter; import com.kumuluz.ee.common.utils.ResourceUtils; import com.kumuluz.ee.common.wrapper.ComponentWrapper; import com.kumuluz.ee.common.wrapper.EeComponentWrapper; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.loaders.ComponentLoader; import com.kumuluz.ee.loaders.ServerLoader; import com.zaxxer.hikari.HikariDataSource; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Tilen Faganel * @since 1.0.0 */ public class EeApplication { private Logger log = Logger.getLogger(EeApplication.class.getSimpleName()); private EeConfig eeConfig; private KumuluzServerWrapper server; private List<EeComponentWrapper> eeComponents; public EeApplication() { this.eeConfig = new EeConfig(); initialize(); } public EeApplication(EeConfig eeConfig) { this.eeConfig = eeConfig; initialize(); } public static void main(String args[]) { EeApplication app = new EeApplication(); } public void initialize() { log.info("Initializing KumuluzEE"); log.info("Checking for requirements"); checkRequirements(); log.info("Checks passed"); log.info("Initializing components"); // Loading the kumuluz server and extracting its metadata KumuluzServer kumuluzServer = ServerLoader.loadServletServer(); processKumuluzServer(kumuluzServer); // Loading all the present components, extracting their metadata and process dependencies List<Component> components = ComponentLoader.loadComponents(); processEeComponents(components); // Initiate the server server.getServer().setServerConfig(eeConfig.getServerConfig()); server.getServer().initServer(); // Depending on the server type, initiate server specific functionality if (server.getServer() instanceof ServletServer) { ServletServer servletServer = (ServletServer) server.getServer(); servletServer.initWebContext(); // Create and register datasources to the underlying server if (eeConfig.getDatasources().size() > 0) { for (DataSourceConfig dsc : eeConfig.getDatasources()) { HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl(dsc.getConnectionUrl()); ds.setUsername(dsc.getUsername()); ds.setPassword(dsc.getPassword()); if (dsc.getDriverClass() != null && !dsc.getDriverClass().isEmpty()) ds.setDriverClassName(dsc.getDriverClass()); if (dsc.getMaxPoolSize() != null ) ds.setMaximumPoolSize(dsc.getMaxPoolSize()); servletServer.registerDataSource(ds, dsc.getJndiName()); } } // Add all included filters Map<String, String> filterParams = new HashMap<>(); filterParams.put("name", "KumuluzEE/" + eeConfig.getVersion());
package net.time4j.scale; import net.time4j.base.GregorianDate; import net.time4j.base.GregorianMath; import net.time4j.base.MathUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.ServiceLoader; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArrayList; /** * <p>Holds all leap seconds occurred since the official start of UTC in * 1972. </p> * * <p>The source is either an implementation of the SPI-interface * {@code Provider} loaded by a {@code ServiceLoader} or an internal * standard implementation of {@code Provider} which accesses the file * &quot;leapseconds.data&quot;. This resource file must be in the * classpath (in folder data). It has the format of a CSV-ASCII-text * which has two columns separated by comma. The first column denotes * the calendar day after the leap second shift in ISO-8601-format (for * example 1972-07-01). The second column determines the sign of the * leap second (+/-). </p> * * <p>The source will mainly be loaded by the context classloader else * by application classloader. If there is no source at all then Time4J * assumes that leap seconds shall not be used. </p> * * <p>The system property &quot;time4j.scale.leapseconds.suppressed&quot; * determines if leap seconds shall be active at all. If this system * property has the value {@code true} then this class will never * register any leap seconds equal if the underlying sources are filled * or not. Furthermore, the system property * &quot;time4j.scale.leapseconds.final&quot; determines if leap seconds * are only registered at system start or if new ones can be lazily * registered at runtime using the methods {@code registerXYZ()}. * Setting one of both properties can improve the performance. </p> * * @author Meno Hochschild * @concurrency <threadsafe> */ /*[deutsch] * <p>Ermittelt alle seit dem offiziellen Start von UTC 1972 aufgetretenen * Schaltsekunden. </p> * * <p>Als Quelle dient entweder eine &uuml;ber einen {@code ServiceLoader} * gefundene Implementierung des SPI-Interface {@code Provider} oder * bei Nichtvorhandensein eine interne Standard-Implementierung, die auf * die Datei &quot;leapseconds.data&quot; zugreift. Diese Datei mu&szlig; * im Klassenpfad liegen (im data-Ordner). Sie hat das Format einer * CSV-ASCII-Textdatei, worin zwei Spalten mit Komma getrennt vorkommen. * Die erste Spalte definiert den Tag nach der Umstellung im ISO-8601-Format * als reines Datum ohne Uhrzeitanteil (z.B. 1972-07-01). Die zweite Spalte * repr&auml;sentiert das Vorzeichen der Schaltsekunde (+/-). </p> * * <p>Geladen wird die Quelle bevorzugt &uuml;ber den Kontext-ClassLoader. * Wird die Quelle nicht gefunden, so wird angenommen, da&szlig; keine * Schaltsekunden verwendet werden sollen. </p> * * <p>Die System-Property &quot;time4j.scale.leapseconds.suppressed&quot; * entscheidet, ob Schaltsekunden &uuml;berhaupt aktiviert sind. Wenn diese * System-Property den Wert {@code true} hat, wird diese Klasse niemals * Schaltsekunden registrieren, gleichg&uuml;ltig, ob die zugrundeliegenden * Quellen gef&uuml;llt sind. Daneben gibt es noch die System-Property * &quot;time4j.scale.leapseconds.final&quot;, die festlegt, ob Schaltsekunden * nur zum Systemstart registriert werden oder auch nachtr&auml;glich zur * Laufzeit mittels {@code registerXYZ()} registriert werden k&ouml;nnen. Das * Setzen einer der beiden Properties kann die Performance verbessern. </p> * * @author Meno Hochschild * @concurrency <threadsafe> */ public final class LeapSeconds implements Iterable<LeapSecondEvent> { /** * <p>System property &quot;net.time4j.scale.leapseconds.suppressed&quot; * which determines that no leap seconds shall be loaded and used. </p> * * <p>Defined values: &quot;true&quot; (suppressed) or &quot;false&quot; * (active - default). </p> */ /*[deutsch] * <p>System-Property &quot;net.time4j.scale.leapseconds.suppressed&quot;, * die regelt, da&szlig; keine Schaltsekunden geladen werden. </p> * * <p>Definierte Werte: &quot;true&quot; (unterdr&uuml;ckt) oder & quot;false&quot; (aktiv - Standard). </p> */ public static final boolean SUPPRESS_UTC_LEAPSECONDS = Boolean.getBoolean("net.time4j.scale.leapseconds.suppressed"); /** * <p>System property &quot;net.time4j.scale.leapseconds.final&quot; * which determines that leap seconds can be loaded only one time at * system start. </p> * * <p>Defined values: &quot;true&quot; (final) or &quot;false&quot; * (enables lazy regisration - default). </p> */ /*[deutsch] * <p>System-Property &quot;net.time4j.scale.leapseconds.final&quot;, die * regelt, da&szlig; Schaltsekunden nur einmalig zum Systemstart festgelegt * werden k&ouml;nnen. </p> * * <p>Definierte Werte: &quot;true&quot; (final) oder &quot;false&quot; * (nachtr&auml;gliche Registrierung m&oumL;glich - Standard). </p> */ public static final boolean FINAL_UTC_LEAPSECONDS = Boolean.getBoolean("net.time4j.scale.leapseconds.final"); private static final ExtendedLSE[] EMPTY_ARRAY = new ExtendedLSE[0]; private static final LeapSeconds INSTANCE = new LeapSeconds(); private static final long UNIX_OFFSET = 2 * 365 * 86400; private static final long MJD_OFFSET = 40587; private final String provider; private final List<ExtendedLSE> list; private final ExtendedLSE[] reverseFinal; private volatile ExtendedLSE[] reverseVolatile; private final boolean supportsNegativeLS; private LeapSeconds() { super(); if (SUPPRESS_UTC_LEAPSECONDS) { this.provider = "<none>"; this.list = Collections.emptyList(); this.reverseFinal = EMPTY_ARRAY; this.reverseVolatile = EMPTY_ARRAY; this.supportsNegativeLS = false; } else { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = LeapSecondProvider.class.getClassLoader(); } ServiceLoader<LeapSecondProvider> sl = ServiceLoader.load(LeapSecondProvider.class, cl); LeapSecondProvider loaded = null; int leapCount = 0; for (LeapSecondProvider temp : sl) { int currentCount = temp.getLeapSecondTable().size(); if (currentCount > leapCount) { loaded = temp; leapCount = currentCount; } } if (loaded == null) { loaded = new DefaultLeapSecondService(); // leapseconds.data } SortedSet<ExtendedLSE> sortedLS = new TreeSet<ExtendedLSE>(new EventComparator()); for ( Map.Entry<GregorianDate, Integer> entry : loaded.getLeapSecondTable().entrySet() ) { GregorianDate date = entry.getKey(); long unixTime = toPosix(date); sortedLS.add( new SimpleLeapSecondEvent( date, unixTime + (1 - 2 * 365) * 86400 - 1, entry.getValue().intValue() ) ); } extend(sortedLS); if (FINAL_UTC_LEAPSECONDS) { this.list = Collections.unmodifiableList( new ArrayList<ExtendedLSE>(sortedLS)); } else { this.list = new CopyOnWriteArrayList<ExtendedLSE>(sortedLS); } this.reverseFinal = this.initReverse(); this.reverseVolatile = this.reverseFinal; this.provider = loaded.toString(); if (FINAL_UTC_LEAPSECONDS) { boolean snls = loaded.supportsNegativeLS(); if (snls) { boolean hasNegativeLS = false; for (ExtendedLSE event : this.list) { if (event.getShift() < 0) { hasNegativeLS = true; break; } } snls = hasNegativeLS; } this.supportsNegativeLS = snls; } else { this.supportsNegativeLS = true; } } } /** * <p>Returns the singleton instance. </p> * * @return singleton instance */ /*[deutsch] * <p>Liefert die Singleton-Instanz. </p> * * @return singleton instance */ public static LeapSeconds getInstance() { return INSTANCE; } /** * <p>Queries if the leap second support is activated. </p> * * @return {@code true} if leap seconds are supported and are also * registered else {@code false} * @see #SUPPRESS_UTC_LEAPSECONDS */ /*[deutsch] * <p>Ist die Schaltsekundenunterst&uuml;tzung aktiviert? </p> * * @return {@code true} if leap seconds are supported and are also * registered else {@code false} * @see #SUPPRESS_UTC_LEAPSECONDS */ public boolean isEnabled() { return !this.list.isEmpty(); } /** * <p>Queries if a lazy registration of leap seconds is possible. </p> * * <p>If the leap second support is switched off then a registration of * leap seconds is never possible so this method will be ignored. </p> * * @return {@code true} if the method {@code registerXYZ()} can be * called without exception else {@code false} * @see #registerPositiveLS(int, int, int) * @see #registerNegativeLS(int, int, int) * @see #FINAL_UTC_LEAPSECONDS * @see #isEnabled() */ /*[deutsch] * <p>K&ouml;nnen nachtr&auml;glich UTC-Schaltsekunden registriert * werden? </p> * * <p>Ist die Schaltsekundenunterst&uuml;tzung abgeschaltet, dann ist * eine Registrierung niemals m&ouml;glich, und diese Methode wird dann * de facto ignoriert. </p> * * @return {@code true} if the method {@code registerXYZ()} can be * called without exception else {@code false} * @see #registerPositiveLS(int, int, int) * @see #registerNegativeLS(int, int, int) * @see #FINAL_UTC_LEAPSECONDS * @see #isEnabled() */ public boolean isExtensible() { return (!FINAL_UTC_LEAPSECONDS && this.isEnabled()); } /** * <p>Yields the count of all registered leap seconds. </p> * * @return count of registered leap seconds */ /*[deutsch] * <p>Ermittelt die Anzahl aller registrierten Schaltsekunden. </p> * * @return count of registered leap seconds */ public int getCount() { return this.getEventsInDescendingOrder().length; } public void registerPositiveLS( int year, int month, int dayOfMonth ) { this.register(year, month, dayOfMonth, false); } public void registerNegativeLS( int year, int month, int dayOfMonth ) { this.register(year, month, dayOfMonth, true); } /** * <p>Queries if negative leap seconds are supported. </p> * * @return {@code true} if negative leap seconds are supported * else {@code false} * @see LeapSecondProvider#supportsNegativeLS() */ /*[deutsch] * <p>Werden auch negative Schaltsekunden unterst&uuml;tzt? </p> * * @return {@code true} if negative leap seconds are supported * else {@code false} * @see LeapSecondProvider#supportsNegativeLS() */ public boolean supportsNegativeLS() { return this.supportsNegativeLS; } /** * <p>Iterates over all leap second events in descending temporal * order. </p> * * @return {@code Iterator} over all stored leap second events * which enables for-each-support */ /*[deutsch] * <p>Iteriert &uuml;ber alle Schaltsekundenereignisse in zeitlich * absteigender Reihenfolge. </p> * * @return {@code Iterator} over all stored leap second events * which enables for-each-support */ @Override public Iterator<LeapSecondEvent> iterator() { final LeapSecondEvent[] events = this.getEventsInDescendingOrder(); return new Iterator<LeapSecondEvent>() { private int index = 0; @Override public boolean hasNext() { return (this.index < events.length); } @Override public LeapSecondEvent next() { if (this.index >= events.length) { throw new NoSuchElementException(); } LeapSecondEvent event = events[this.index]; this.index++; return event; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * <p>Yields the shift in seconds suitable for the last minute * of given calendar date. </p> * * <p>The result of this method can be added to the second value * {@code 59} in order to calculate the maximum of the element * SECOND_OF_MINUTE in given time context. The behaviour of the * method is undefined if given calendar date is undefined. </p> * * @param date day of possible leap second event in the last minute * @return shift of second element (most of the times just {@code 0}) */ /*[deutsch] * <p>Ermittelt die Verschiebung in Sekunden passend zur letzten Minute * des angegebenen Datums. </p> * * <p>Das Ergebnis der Methode kann zum Sekundenwert {@code 59} addiert * werden, um das Maximum des Elements SECOND_OF_MINUTE im angegebenen * Zeitkontext zu erhalten. Das Verhalten der Methode ist undefiniert, * wenn die angegebenen Bereichsgrenzen der Argumentwerte nicht beachtet * werden. </p> * * @param date day of possible leap second event in the last minute * @return shift of second element (most of the times just {@code 0}) */ public int getShift(GregorianDate date) { int year = date.getYear(); // Schaltsekundenereignisse gibt es erst seit Juni 1972 if (year >= 1972) { ExtendedLSE[] events = this.getEventsInDescendingOrder(); for (int i = 0; i < events.length; i++) { ExtendedLSE event = events[i]; GregorianDate lsDate = event.getDate(); // Ist es der Umstellungstag? if ( (year == lsDate.getYear()) && (date.getMonth() == lsDate.getMonth()) && (date.getDayOfMonth() == lsDate.getDayOfMonth()) ) { return event.getShift(); } } } return 0; } /** * <p>Yields the shift in seconds dependent on if given UTC time point * represents a leap second or not. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return {@code 1, 0, -1} if the argument denotes a positive leap second, no leap second or a negative leap second */ /*[deutsch] * <p>Ermittelt die Verschiebung in Sekunden, wenn dieser Zeitpunkt * &uuml;berhaupt eine Schaltsekunde repr&auml;sentiert. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return {@code 1, 0, -1} if the argument denotes a positive leap second, no leap second or a negative leap second */ public int getShift(long utc) { if (utc <= 0) { return 0; } ExtendedLSE[] events = this.getEventsInDescendingOrder(); for (int i = 0; i < events.length; i++) { ExtendedLSE lse = events[i]; if (utc > lse.utc()) { return 0; } else { long start = lse.utc() - lse.getShift(); if (utc > start) { // Schaltbereich return (int) (utc - start); } } } return 0; } /** * <p>Yields the next leap second event after given UTC time point. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return following leap second event or {@code null} if not known * @since 2.1 */ /*[deutsch] * <p>Ermittelt das zum angegebenen UTC-Zeitstempel n&auml;chste * Schaltsekundenereignis. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return following leap second event or {@code null} if not known * @since 2.1 */ public LeapSecondEvent getNextEvent(long utc) { ExtendedLSE[] events = this.getEventsInDescendingOrder(); LeapSecondEvent result = null; for (int i = 0; i < events.length; i++) { ExtendedLSE lse = events[i]; if (utc >= lse.utc()) { break; } else { result = lse; } } return result; } /** * <p>Enhances an UNIX-timestamp with leap seconds and converts it to an * UTC-timestamp. </p> * * <p>Note: A leap second itself cannot be restored because the mapping * between UNIX- and UTC-time is not bijective. Hence the result of this * method can not represent a leap second. </p> * * @param unixTime elapsed time in seconds relative to UNIX epoch * [1970-01-01T00:00:00Z] without leap seconds * @return elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @see #strip(long) */ /*[deutsch] * <p>Reichert einen UNIX-Zeitstempel mit Schaltsekunden an und wandelt * ihn in einen UTC-Zeitstempel um. </p> * * <p>Notiz: Eine Schaltsekunde kann selbst nicht wiederhergestellt werden, * da die Abbildung zwischen der UNIX- und UTC-Zeit nicht bijektiv ist. * Das Ergebnis dieser Methode stellt also keine aktuelle Schaltsekunde * dar. </p> * * @param unixTime elapsed time in seconds relative to UNIX epoch * [1970-01-01T00:00:00Z] without leap seconds * @return elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @see #strip(long) */ public long enhance(long unixTime) { long epochTime = unixTime - UNIX_OFFSET; if (unixTime <= 0) { return unixTime; } // Praxis meistens mit aktuellen Datumswerten gesucht wird final ExtendedLSE[] events = this.getEventsInDescendingOrder(); for (int i = 0; i < events.length; i++) { ExtendedLSE lse = events[i]; if (lse.raw() < epochTime) { return MathUtils.safeAdd(epochTime, lse.utc() - lse.raw()); } } return epochTime; } /** * <p>Converts given UTC-timestamp to an UNIX-timestamp without * leap seconds. </p> * * <p>This method is the reversal of {@code enhance()}. Note that * there is no bijective mapping, that is sometimes the expression * {@code enhance(strip(val)) != val} is {@code true}. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return elapsed time in seconds relative to UNIX epoch * [1970-01-01T00:00:00Z] without leap seconds * @see #enhance(long) */ /*[deutsch] * <p>Konvertiert die UTC-Angabe zu einem UNIX-Zeitstempel ohne * Schaltsekunden. </p> * * <p>Diese Methode ist die Umkehrung zu {@code enhance()}. Zu * beachten ist, da&szlig; keine bijektive Abbildung besteht, d.h. es gilt * manchmal: {@code enhance(strip(val)) != val}. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return elapsed time in seconds relative to UNIX epoch * [1970-01-01T00:00:00Z] without leap seconds * @see #enhance(long) */ public long strip(long utc) { if (utc <= 0) { return utc + UNIX_OFFSET; } // Praxis meistens mit aktuellen Datumswerten gesucht wird final ExtendedLSE[] events = this.getEventsInDescendingOrder(); boolean snls = this.supportsNegativeLS; for (int i = 0; i < events.length; i++) { ExtendedLSE lse = events[i]; if ( (lse.utc() - lse.getShift() < utc) || (snls && (lse.getShift() < 0) && (lse.utc() < utc)) ) { utc = MathUtils.safeAdd(utc, lse.raw() - lse.utc()); break; } } return utc + UNIX_OFFSET; } /** * <p>Queries if given UTC-timestamp represents a registered * positive leap second. </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return {@code true} if the argument represents a registered * positive leap second else {@code false} */ /*[deutsch] * <p>Ist die angegebene UTC-Zeit eine registrierte positive * Schaltsekunde? </p> * * @param utc elapsed SI-seconds relative to UTC epoch * [1972-01-01T00:00:00Z] including leap seconds * @return {@code true} if the argument represents a registered * positive leap second else {@code false} */ public boolean isPositiveLS(long utc) { if (utc <= 0) { return false; } final ExtendedLSE[] events = this.getEventsInDescendingOrder(); for (int i = 0; i < events.length; i++) { long comp = events[i].utc(); if (comp == utc) { return (events[i].getShift() == 1); } else if (comp < utc) { break; } } return false; } /** * <p>For debugging purposes. </p> * * @return table of leap seconds as String */ /*[deutsch] * <p>F&uuml;r Debugging-Zwecke. </p> * * @return table of leap seconds as String */ @Override public String toString() { StringBuilder sb = new StringBuilder(2048); sb.append("[PROVIDER="); sb.append(this.provider); sb.append(",EVENTS=["); if (this.isEnabled()) { boolean first = true; for (Object event : this.list) { if (first) { first = false; } else { sb.append('|'); } sb.append(event); } } else { sb.append("NOT SUPPORTED"); } return sb.append("]]").toString(); } private void register( int year, int month, int dayOfMonth, boolean negativeLS ) { if (FINAL_UTC_LEAPSECONDS) { throw new IllegalStateException( "Leap seconds are final, " + "change requires edit of system property " + "\"time4j.utc.leapseconds.final\" " + "and reboot of JVM."); } else if (SUPPRESS_UTC_LEAPSECONDS) { throw new IllegalStateException( "Leap seconds are not supported, " + "change requires edit of system property " + "\"time4j.utc.leapseconds.suppressed\" " + "and reboot of JVM."); } synchronized (this) { GregorianMath.checkDate(year, month, dayOfMonth); if (!this.isEnabled()) { throw new IllegalStateException("Leap seconds not activated."); } ExtendedLSE last = this.reverseVolatile[0]; GregorianDate date = last.getDate(); boolean ok = false; if (year > date.getYear()) { ok = true; } else if (year == date.getYear()) { if (month > date.getMonth()) { ok = true; } else if (month == date.getMonth()) { if (dayOfMonth > date.getDayOfMonth()) { ok = true; } } } if (!ok) { throw new IllegalArgumentException( "New leap second must be after last leap second."); } GregorianDate newLS = new IsoDate(year, month, dayOfMonth); int shift = (negativeLS ? -1 : 1); this.list.add(createLSE(newLS, shift, last)); this.reverseVolatile = this.initReverse(); } } // Ereignisse in zeitlich absteigender Reihenfolge auf (das neueste zuerst) private ExtendedLSE[] getEventsInDescendingOrder() { if (SUPPRESS_UTC_LEAPSECONDS || FINAL_UTC_LEAPSECONDS) { return this.reverseFinal; } else { return this.reverseVolatile; } } private static void extend(SortedSet<ExtendedLSE> sortedColl) { List<ExtendedLSE> tmp = new ArrayList<ExtendedLSE>(sortedColl.size()); int diff = 0; for (ExtendedLSE lse : sortedColl) { if (lse.utc() == Long.MIN_VALUE) { diff += lse.getShift(); tmp.add(new SimpleLeapSecondEvent(lse, diff)); } else { tmp.add(lse); } } sortedColl.clear(); sortedColl.addAll(tmp); } private static ExtendedLSE createLSE( final GregorianDate date, final int shift, ExtendedLSE last ) { ExtendedLSE lse = new ExtendedLSE() { @Override public GregorianDate getDate() { return date; } @Override public int getShift() { return shift; } @Override public long utc() { return Long.MIN_VALUE; } @Override public long raw() { return toPosix(date) + (1 - 2 * 365) * 86400 - 1; } }; int diff = (int) (last.utc() - last.raw() + shift); return new SimpleLeapSecondEvent(lse, diff); } private static long toPosix(GregorianDate date) { return MathUtils.safeMultiply( MathUtils.safeSubtract( GregorianMath.toMJD(date), MJD_OFFSET ), 86400 ); } private ExtendedLSE[] initReverse() { List<ExtendedLSE> tmp = new ArrayList<ExtendedLSE>(this.list.size()); tmp.addAll(this.list); Collections.reverse(tmp); return tmp.toArray(new ExtendedLSE[tmp.size()]); } private static class IsoDate implements GregorianDate, Serializable { private static final long serialVersionUID = 786391662682108754L; /** * @serial proleptic iso year */ private final int year; /** * @serial gregorian month in range (1-12) */ private final int month; /** * @serial day of month in range (1-31) */ private final int dayOfMonth; IsoDate( int year, int month, int dayOfMonth ) { super(); GregorianMath.checkDate(year, month, dayOfMonth); this.year = year; this.month = month; this.dayOfMonth = dayOfMonth; } @Override public int getYear() { return this.year; } @Override public int getMonth() { return this.month; } @Override public int getDayOfMonth() { return this.dayOfMonth; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof IsoDate) { IsoDate that = (IsoDate) obj; return ( (this.dayOfMonth == that.dayOfMonth) && (this.month == that.month) && (this.year == that.year) ); } else { return false; } } @Override public int hashCode() { return this.year + 31 * this.month + 37 * this.dayOfMonth; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.year < 0) { sb.append('-'); } int y = Math.abs(this.year); if (y < 1000) { sb.append('0'); if (y < 100) { sb.append('0'); if (y < 10) { sb.append('0'); } } } sb.append(y); sb.append('-'); if (this.month < 10) { sb.append('0'); } sb.append(this.month); sb.append('-'); if (this.dayOfMonth < 10) { sb.append('0'); } sb.append(this.dayOfMonth); return sb.toString(); } /** * @serialData Checks the consistency. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int y = this.year; int m = this.month; int d = this.dayOfMonth; if (!GregorianMath.isValid(y, m, d)) { throw new InvalidObjectException("Corrupt date."); } } } private static class SimpleLeapSecondEvent implements ExtendedLSE, Serializable { private static final long serialVersionUID = 5986185471610524587L; /** * @serial date of leap second day */ private final GregorianDate date; /** * @serial shift in seconds */ private final int shift; /** * @serial UTC time including leap seconds */ private final long _utc; /** * @serial UTC time without leap seconds */ private final long _raw; // Standard-Konstruktor SimpleLeapSecondEvent( GregorianDate date, long rawTime, int shift ) { super(); this.date = new IsoDate( // defensives Kopieren date.getYear(), date.getMonth(), date.getDayOfMonth()); this.shift = shift; this._utc = Long.MIN_VALUE; this._raw = rawTime; } // Anreicherung mit der UTC-Zeit SimpleLeapSecondEvent( ExtendedLSE lse, int diff ) { super(); this.date = lse.getDate(); this.shift = lse.getShift(); this._utc = lse.raw() + diff; this._raw = lse.raw(); } @Override public GregorianDate getDate() { return this.date; } @Override public int getShift() { return this.shift; } @Override public long utc() { return this._utc; } @Override public long raw() { return this._raw; } @Override public String toString() { StringBuilder sb = new StringBuilder(128); sb.append(LeapSecondEvent.class.getName()); sb.append('['); sb.append(this.date); sb.append(": utc="); sb.append(this._utc); sb.append(", raw="); sb.append(this._raw); sb.append(" (shift="); sb.append(this.shift); sb.append(")]"); return sb.toString(); } } private static class DefaultLeapSecondService implements LeapSecondProvider { private final String source; private final Map<GregorianDate, Integer> table; DefaultLeapSecondService() { super(); this.table = new LinkedHashMap<GregorianDate, Integer>(50); InputStream is = null; String name = "data/leapseconds.data"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { is = cl.getResourceAsStream(name); } if (is == null) { cl = LeapSecondProvider.class.getClassLoader(); is = cl.getResourceAsStream(name); } if (is != null) { this.source = cl.getResource(name).toString(); try { BufferedReader br = new BufferedReader( new InputStreamReader(is, "US-ASCII")); String line; while ((line = br.readLine()) != null) { if (line.startsWith(" continue; } int comma = line.indexOf(','); String date; Boolean sign = null; if (comma == -1) { date = line.trim(); sign = Boolean.TRUE; } else { date = line.substring(0, comma).trim(); String s = line.substring(comma + 1).trim(); if (s.length() == 1) { char c = s.charAt(0); if (c == '+') { sign = Boolean.TRUE; } else if (c == '-') { sign = Boolean.FALSE; } } if (sign == null) { throw new IllegalStateException( "Missing leap second sign."); } } int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(5, 7)); int dom = Integer.parseInt(date.substring(8, 10)); Object old = this.table.put( new IsoDate(year, month, dom), Integer.valueOf(sign.booleanValue() ? 1 : -1) ); if (old != null) { throw new IllegalStateException( "Duplicate leap second event found."); } } } catch (UnsupportedEncodingException uee) { throw new AssertionError(uee); } catch (IllegalStateException ise) { throw ise; } catch (Exception ex) { throw new IllegalStateException(ex); } finally { try { is.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } } } else { this.source = ""; System.out.println("Warning: File \"" + name + "\" not found."); } } @Override public Map<GregorianDate, Integer> getLeapSecondTable() { return Collections.unmodifiableMap(this.table); } @Override public boolean supportsNegativeLS() { return true; } @Override public String toString() { return this.source; } } private static class EventComparator implements Comparator<ExtendedLSE> { @Override public int compare( ExtendedLSE o1, ExtendedLSE o2 ) { GregorianDate d1 = o1.getDate(); GregorianDate d2 = o2.getDate(); int y1 = d1.getYear(); int y2 = d2.getYear(); if (y1 < y2) { return -1; } else if (y1 > y2) { return 1; } int m1 = d1.getMonth(); int m2 = d2.getMonth(); if (m1 < m2) { return -1; } else if (m1 > m2) { return 1; } int dom1 = d1.getDayOfMonth(); int dom2 = d2.getDayOfMonth(); return (dom1 < dom2 ? -1 : (dom1 == dom2 ? 0 : 1)); } } }
package org.mwg.internal; import org.mwg.*; import org.mwg.base.BaseNode; import org.mwg.chunk.*; import org.mwg.plugin.*; import org.mwg.struct.Buffer; import org.mwg.struct.BufferIterator; import org.mwg.struct.LongLongMap; import org.mwg.struct.StringIntMap; import org.mwg.utility.HashHelper; import org.mwg.utility.KeyHelper; import static org.mwg.chunk.ChunkType.STATE_CHUNK; final class MWGResolver implements Resolver { private final Storage _storage; private final ChunkSpace _space; private final org.mwg.Graph _graph; private StateChunk dictionary; private WorldOrderChunk globalWorldOrderChunk; private static int KEY_SIZE = 3; public MWGResolver(final Storage p_storage, final ChunkSpace p_space, final Graph p_graph) { _space = p_space; _storage = p_storage; _graph = p_graph; } @Override public final void init() { dictionary = (StateChunk) this._space.getAndMark(STATE_CHUNK, CoreConstants.GLOBAL_DICTIONARY_KEY[0], CoreConstants.GLOBAL_DICTIONARY_KEY[1], CoreConstants.GLOBAL_DICTIONARY_KEY[2]); globalWorldOrderChunk = (WorldOrderChunk) this._space.getAndMark(ChunkType.WORLD_ORDER_CHUNK, 0, 0, Constants.NULL_LONG); } @Override public final int typeCode(Node node) { final BaseNode casted = (BaseNode) node; final WorldOrderChunk worldOrderChunk = (WorldOrderChunk) this._space.get(casted._index_worldOrder); if (worldOrderChunk == null) { return -1; } return (int) worldOrderChunk.extra(); } @Override public final void initNode(final org.mwg.Node node, final long codeType) { final BaseNode casted = (BaseNode) node; final StateChunk cacheEntry = (StateChunk) this._space.createAndMark(STATE_CHUNK, node.world(), node.time(), node.id()); //declare dirty now because potentially no insert could be done this._space.notifyUpdate(cacheEntry.index()); //initiate superTime management final TimeTreeChunk superTimeTree = (TimeTreeChunk) this._space.createAndMark(ChunkType.TIME_TREE_CHUNK, node.world(), Constants.NULL_LONG, node.id()); superTimeTree.insert(node.time()); //initiate time management final TimeTreeChunk timeTree = (TimeTreeChunk) this._space.createAndMark(ChunkType.TIME_TREE_CHUNK, node.world(), node.time(), node.id()); timeTree.insert(node.time()); //initiate universe management final WorldOrderChunk objectWorldOrder = (WorldOrderChunk) this._space.createAndMark(ChunkType.WORLD_ORDER_CHUNK, 0, 0, node.id()); objectWorldOrder.put(node.world(), node.time()); if (codeType != Constants.NULL_LONG) { objectWorldOrder.setExtra(codeType); } casted._index_stateChunk = cacheEntry.index(); casted._index_timeTree = timeTree.index(); casted._index_superTimeTree = superTimeTree.index(); casted._index_worldOrder = objectWorldOrder.index(); casted._world_magic = -1; casted._super_time_magic = -1; casted._time_magic = -1; //monitor the node object //this._tracker.monitor(node); //last step call the user code casted.init(); } @Override public final void initWorld(long parentWorld, long childWorld) { globalWorldOrderChunk.put(childWorld, parentWorld); } @Override public final void freeNode(org.mwg.Node node) { final BaseNode casted = (BaseNode) node; casted.cacheLock(); if (!casted._dead) { this._space.unmark(casted._index_stateChunk); this._space.unmark(casted._index_timeTree); this._space.unmark(casted._index_superTimeTree); this._space.unmark(casted._index_worldOrder); casted._dead = true; } casted.cacheUnlock(); } @Override public final void externalLock(org.mwg.Node node) { final BaseNode casted = (BaseNode) node; final WorldOrderChunk worldOrderChunk = (WorldOrderChunk) this._space.get(casted._index_worldOrder); worldOrderChunk.externalLock(); } @Override public final void externalUnlock(org.mwg.Node node) { final BaseNode casted = (BaseNode) node; final WorldOrderChunk worldOrderChunk = (WorldOrderChunk) this._space.get(casted._index_worldOrder); worldOrderChunk.externalUnlock(); } @Override public final void setTimeSensitivity(final Node node, final long deltaTime, final long offset) { final BaseNode casted = (BaseNode) node; final TimeTreeChunk superTimeTree = (TimeTreeChunk) this._space.get(casted._index_superTimeTree); superTimeTree.setExtra(deltaTime); superTimeTree.setExtra2(offset); } @Override public long[] getTimeSensitivity(final Node node) { final BaseNode casted = (BaseNode) node; final long[] result = new long[2]; final TimeTreeChunk superTimeTree = (TimeTreeChunk) this._space.get(casted._index_superTimeTree); result[0] = superTimeTree.extra(); result[1] = superTimeTree.extra2(); return result; } @Override public final <A extends org.mwg.Node> void lookup(final long world, final long time, final long id, final Callback<A> callback) { final MWGResolver selfPointer = this; selfPointer._space.getOrLoadAndMark(ChunkType.WORLD_ORDER_CHUNK, 0, 0, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeWorldOrder) { if (theNodeWorldOrder == null) { callback.on(null); } else { final long closestWorld = selfPointer.resolve_world(globalWorldOrderChunk, (WorldOrderChunk) theNodeWorldOrder, time, world); selfPointer._space.getOrLoadAndMark(ChunkType.TIME_TREE_CHUNK, closestWorld, Constants.NULL_LONG, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeSuperTimeTree) { if (theNodeSuperTimeTree == null) { selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { final long closestSuperTime = ((TimeTreeChunk) theNodeSuperTimeTree).previousOrEqual(time); if (closestSuperTime == Constants.NULL_LONG) { selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); return; } selfPointer._space.getOrLoadAndMark(ChunkType.TIME_TREE_CHUNK, closestWorld, closestSuperTime, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeTimeTree) { if (theNodeTimeTree == null) { selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { final long closestTime = ((TimeTreeChunk) theNodeTimeTree).previousOrEqual(time); if (closestTime == Constants.NULL_LONG) { selfPointer._space.unmark(theNodeTimeTree.index()); selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); return; } selfPointer._space.getOrLoadAndMark(STATE_CHUNK, closestWorld, closestTime, id, new Callback<Chunk>() { @Override public void on(Chunk theObjectChunk) { if (theObjectChunk == null) { selfPointer._space.unmark(theNodeTimeTree.index()); selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { WorldOrderChunk castedNodeWorldOrder = (WorldOrderChunk) theNodeWorldOrder; int extraCode = (int) castedNodeWorldOrder.extra(); NodeFactory resolvedFactory = null; if (extraCode != -1) { resolvedFactory = ((CoreGraph) selfPointer._graph).factoryByCode(extraCode); } BaseNode resolvedNode; if (resolvedFactory == null) { resolvedNode = new BaseNode(world, time, id, selfPointer._graph); } else { resolvedNode = (BaseNode) resolvedFactory.create(world, time, id, selfPointer._graph); } resolvedNode._dead = false; resolvedNode._index_stateChunk = theObjectChunk.index(); resolvedNode._index_superTimeTree = theNodeSuperTimeTree.index(); resolvedNode._index_timeTree = theNodeTimeTree.index(); resolvedNode._index_worldOrder = theNodeWorldOrder.index(); if (closestWorld == world && closestTime == time) { resolvedNode._world_magic = -1; resolvedNode._super_time_magic = -1; resolvedNode._time_magic = -1; } else { resolvedNode._world_magic = ((WorldOrderChunk) theNodeWorldOrder).magic(); resolvedNode._super_time_magic = ((TimeTreeChunk) theNodeSuperTimeTree).magic(); resolvedNode._time_magic = ((TimeTreeChunk) theNodeTimeTree).magic(); } //selfPointer._tracker.monitor(resolvedNode); if (callback != null) { final Node casted = resolvedNode; callback.on((A) casted); } } } }); } } }); } } }); } } }); } @SuppressWarnings("Duplicates") @Override public void lookupBatch(long[] worlds, long[] times, long[] ids, Callback<Node[]> callback) { final int idsSize = ids.length; if (!(worlds.length == times.length && times.length == idsSize)) { throw new RuntimeException("Bad API usage"); } final MWGResolver selfPointer = this; final Node[] finalResult = new Node[idsSize]; //init as null for JS compatibility for (int i = 0; i < idsSize; i++) { finalResult[i] = null; } final boolean[] isEmpty = {true}; final long[] keys = new long[idsSize * Constants.KEY_SIZE]; for (int i = 0; i < idsSize; i++) { isEmpty[0] = false; keys[i * Constants.KEY_SIZE] = ChunkType.WORLD_ORDER_CHUNK; keys[(i * Constants.KEY_SIZE) + 1] = 0; keys[(i * Constants.KEY_SIZE) + 2] = 0; keys[(i * Constants.KEY_SIZE) + 3] = ids[i]; } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, null, null, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeWorldOrders) { if (theNodeWorldOrders == null) { lookupAll_end(finalResult, callback, idsSize, null, null, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeWorldOrders[i] != null) { isEmpty[0] = false; keys[i * Constants.KEY_SIZE] = ChunkType.TIME_TREE_CHUNK; keys[(i * Constants.KEY_SIZE) + 1] = selfPointer.resolve_world(globalWorldOrderChunk, (WorldOrderChunk) theNodeWorldOrders[i], times[i], worlds[i]); keys[(i * Constants.KEY_SIZE) + 2] = Constants.NULL_LONG; } else { keys[i * Constants.KEY_SIZE] = -1; } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, null, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeSuperTimeTrees) { if (theNodeSuperTimeTrees == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, null, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeSuperTimeTrees[i] != null) { final long closestSuperTime = ((TimeTreeChunk) theNodeSuperTimeTrees[i]).previousOrEqual(times[i]); if (closestSuperTime == Constants.NULL_LONG) { keys[i * Constants.KEY_SIZE] = -1; //skip } else { isEmpty[0] = false; keys[(i * Constants.KEY_SIZE) + 2] = closestSuperTime; } } else { keys[i * Constants.KEY_SIZE] = -1; //skip } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeTimeTrees) { if (theNodeTimeTrees == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeTimeTrees[i] != null) { final long closestTime = ((TimeTreeChunk) theNodeTimeTrees[i]).previousOrEqual(times[i]); if (closestTime == Constants.NULL_LONG) { keys[i * Constants.KEY_SIZE] = -1; //skip } else { isEmpty[0] = false; keys[(i * Constants.KEY_SIZE)] = ChunkType.STATE_CHUNK; keys[(i * Constants.KEY_SIZE) + 2] = closestTime; } } else { keys[i * Constants.KEY_SIZE] = -1; //skip } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(Chunk[] theObjectChunks) { if (theObjectChunks == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, null); } else { for (int i = 0; i < idsSize; i++) { if (theObjectChunks[i] != null) { WorldOrderChunk castedNodeWorldOrder = (WorldOrderChunk) theNodeWorldOrders[i]; int extraCode = (int) castedNodeWorldOrder.extra(); NodeFactory resolvedFactory = null; if (extraCode != -1) { resolvedFactory = ((CoreGraph) selfPointer._graph).factoryByCode(extraCode); } BaseNode resolvedNode; if (resolvedFactory == null) { resolvedNode = new BaseNode(worlds[i], times[i], ids[i], selfPointer._graph); } else { resolvedNode = (BaseNode) resolvedFactory.create(worlds[i], times[i], ids[i], selfPointer._graph); } resolvedNode._dead = false; resolvedNode._index_stateChunk = theObjectChunks[i].index(); resolvedNode._index_superTimeTree = theNodeSuperTimeTrees[i].index(); resolvedNode._index_timeTree = theNodeTimeTrees[i].index(); resolvedNode._index_worldOrder = theNodeWorldOrders[i].index(); if (theObjectChunks[i].world() == worlds[i] && theObjectChunks[i].time() == times[i]) { resolvedNode._world_magic = -1; resolvedNode._super_time_magic = -1; resolvedNode._time_magic = -1; } else { resolvedNode._world_magic = ((WorldOrderChunk) theNodeWorldOrders[i]).magic(); resolvedNode._super_time_magic = ((TimeTreeChunk) theNodeSuperTimeTrees[i]).magic(); resolvedNode._time_magic = ((TimeTreeChunk) theNodeTimeTrees[i]).magic(); } finalResult[i] = resolvedNode; } } lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, theObjectChunks); } } }); } } } }); } } } }); } } } }); } } @Override public void lookupTimes(long world, long from, long to, long id, Callback<Node[]> callback) { final MWGResolver selfPointer = this; try { selfPointer._space.getOrLoadAndMark(ChunkType.WORLD_ORDER_CHUNK, 0, 0, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeWorldOrder) { if (theNodeWorldOrder == null) { callback.on(null); } else { /* final long closestWorld = selfPointer.resolve_world(globalWorldOrderChunk, (WorldOrderChunk) theNodeWorldOrder, time, world); selfPointer._space.getOrLoadAndMark(ChunkType.TIME_TREE_CHUNK, closestWorld, Constants.NULL_LONG, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeSuperTimeTree) { if (theNodeSuperTimeTree == null) { selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { final long closestSuperTime = ((TimeTreeChunk) theNodeSuperTimeTree).previousOrEqual(time); if (closestSuperTime == Constants.NULL_LONG) { selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); return; } selfPointer._space.getOrLoadAndMark(ChunkType.TIME_TREE_CHUNK, closestWorld, closestSuperTime, id, new Callback<Chunk>() { @Override public void on(final Chunk theNodeTimeTree) { if (theNodeTimeTree == null) { selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { final long closestTime = ((TimeTreeChunk) theNodeTimeTree).previousOrEqual(time); if (closestTime == Constants.NULL_LONG) { selfPointer._space.unmark(theNodeTimeTree.index()); selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); return; } selfPointer._space.getOrLoadAndMark(STATE_CHUNK, closestWorld, closestTime, id, new Callback<Chunk>() { @Override public void on(Chunk theObjectChunk) { if (theObjectChunk == null) { selfPointer._space.unmark(theNodeTimeTree.index()); selfPointer._space.unmark(theNodeSuperTimeTree.index()); selfPointer._space.unmark(theNodeWorldOrder.index()); callback.on(null); } else { WorldOrderChunk castedNodeWorldOrder = (WorldOrderChunk) theNodeWorldOrder; long extraCode = castedNodeWorldOrder.extra(); NodeFactory resolvedFactory = null; if (extraCode != Constants.NULL_LONG) { resolvedFactory = ((CoreGraph) selfPointer._graph).factoryByCode(extraCode); } BaseNode resolvedNode; if (resolvedFactory == null) { resolvedNode = new CoreNode(world, time, id, selfPointer._graph); } else { resolvedNode = (BaseNode) resolvedFactory.create(world, time, id, selfPointer._graph); } resolvedNode._dead = false; resolvedNode._index_stateChunk = theObjectChunk.index(); resolvedNode._index_superTimeTree = theNodeSuperTimeTree.index(); resolvedNode._index_timeTree = theNodeTimeTree.index(); resolvedNode._index_worldOrder = theNodeWorldOrder.index(); if (closestWorld == world && closestTime == time) { resolvedNode._world_magic = -1; resolvedNode._super_time_magic = -1; resolvedNode._time_magic = -1; } else { resolvedNode._world_magic = ((WorldOrderChunk) theNodeWorldOrder).magic(); resolvedNode._super_time_magic = ((TimeTreeChunk) theNodeSuperTimeTree).magic(); resolvedNode._time_magic = ((TimeTreeChunk) theNodeTimeTree).magic(); } //selfPointer._tracker.monitor(resolvedNode); if (callback != null) { final Node casted = resolvedNode; callback.on((A) casted); } } } }); } } }); } } });*/ } } }); } catch (Exception e) { e.printStackTrace(); } } private void lookupAll_end(final Node[] finalResult, final Callback<Node[]> callback, final int sizeIds, final Chunk[] worldOrders, final Chunk[] superTimes, final Chunk[] times, final Chunk[] chunks) { if (worldOrders != null || superTimes != null || times != null || chunks != null) { for (int i = 0; i < sizeIds; i++) { if (finalResult[i] == null) { if (worldOrders != null && worldOrders[i] != null) { _space.unmark(worldOrders[i].index()); } if (superTimes != null && superTimes[i] != null) { _space.unmark(superTimes[i].index()); } if (times != null && times[i] != null) { _space.unmark(times[i].index()); } if (chunks != null && chunks[i] != null) { _space.unmark(chunks[i].index()); } } } } callback.on(finalResult); } @Override public final void lookupAll(final long world, final long time, final long ids[], final Callback<Node[]> callback) { final MWGResolver selfPointer = this; final int idsSize = ids.length; final Node[] finalResult = new Node[idsSize]; //init as null for JS compatibility for (int i = 0; i < idsSize; i++) { finalResult[i] = null; } final boolean[] isEmpty = {true}; final long[] keys = new long[idsSize * Constants.KEY_SIZE]; for (int i = 0; i < idsSize; i++) { isEmpty[0] = false; keys[i * Constants.KEY_SIZE] = ChunkType.WORLD_ORDER_CHUNK; keys[(i * Constants.KEY_SIZE) + 1] = 0; keys[(i * Constants.KEY_SIZE) + 2] = 0; keys[(i * Constants.KEY_SIZE) + 3] = ids[i]; } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, null, null, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeWorldOrders) { if (theNodeWorldOrders == null) { lookupAll_end(finalResult, callback, idsSize, null, null, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeWorldOrders[i] != null) { isEmpty[0] = false; keys[i * Constants.KEY_SIZE] = ChunkType.TIME_TREE_CHUNK; keys[(i * Constants.KEY_SIZE) + 1] = selfPointer.resolve_world(globalWorldOrderChunk, (WorldOrderChunk) theNodeWorldOrders[i], time, world); keys[(i * Constants.KEY_SIZE) + 2] = Constants.NULL_LONG; } else { keys[i * Constants.KEY_SIZE] = -1; } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, null, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeSuperTimeTrees) { if (theNodeSuperTimeTrees == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, null, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeSuperTimeTrees[i] != null) { final long closestSuperTime = ((TimeTreeChunk) theNodeSuperTimeTrees[i]).previousOrEqual(time); if (closestSuperTime == Constants.NULL_LONG) { keys[i * Constants.KEY_SIZE] = -1; //skip } else { isEmpty[0] = false; keys[(i * Constants.KEY_SIZE) + 2] = closestSuperTime; } } else { keys[i * Constants.KEY_SIZE] = -1; //skip } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, null, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] theNodeTimeTrees) { if (theNodeTimeTrees == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, null, null); } else { isEmpty[0] = true; for (int i = 0; i < idsSize; i++) { if (theNodeTimeTrees[i] != null) { final long closestTime = ((TimeTreeChunk) theNodeTimeTrees[i]).previousOrEqual(time); if (closestTime == Constants.NULL_LONG) { keys[i * Constants.KEY_SIZE] = -1; //skip } else { isEmpty[0] = false; keys[(i * Constants.KEY_SIZE)] = ChunkType.STATE_CHUNK; keys[(i * Constants.KEY_SIZE) + 2] = closestTime; } } else { keys[i * Constants.KEY_SIZE] = -1; //skip } } if (isEmpty[0]) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, null); } else { selfPointer._space.getOrLoadAndMarkAll(keys, new Callback<Chunk[]>() { @Override public void on(Chunk[] theObjectChunks) { if (theObjectChunks == null) { lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, null); } else { for (int i = 0; i < idsSize; i++) { if (theObjectChunks[i] != null) { WorldOrderChunk castedNodeWorldOrder = (WorldOrderChunk) theNodeWorldOrders[i]; int extraCode = (int) castedNodeWorldOrder.extra(); NodeFactory resolvedFactory = null; if (extraCode != -1) { resolvedFactory = ((CoreGraph) selfPointer._graph).factoryByCode(extraCode); } BaseNode resolvedNode; if (resolvedFactory == null) { resolvedNode = new BaseNode(world, time, ids[i], selfPointer._graph); } else { resolvedNode = (BaseNode) resolvedFactory.create(world, time, ids[i], selfPointer._graph); } resolvedNode._dead = false; resolvedNode._index_stateChunk = theObjectChunks[i].index(); resolvedNode._index_superTimeTree = theNodeSuperTimeTrees[i].index(); resolvedNode._index_timeTree = theNodeTimeTrees[i].index(); resolvedNode._index_worldOrder = theNodeWorldOrders[i].index(); if (theObjectChunks[i].world() == world && theObjectChunks[i].time() == time) { resolvedNode._world_magic = -1; resolvedNode._super_time_magic = -1; resolvedNode._time_magic = -1; } else { resolvedNode._world_magic = ((WorldOrderChunk) theNodeWorldOrders[i]).magic(); resolvedNode._super_time_magic = ((TimeTreeChunk) theNodeSuperTimeTrees[i]).magic(); resolvedNode._time_magic = ((TimeTreeChunk) theNodeTimeTrees[i]).magic(); } finalResult[i] = resolvedNode; } } lookupAll_end(finalResult, callback, idsSize, theNodeWorldOrders, theNodeSuperTimeTrees, theNodeTimeTrees, theObjectChunks); } } }); } } } }); } } } }); } } } }); } } @Override public void lookupAllTimes(long world, long from, long to, long[] ids, Callback<Node[]> callback) { //TODO } private long resolve_world(final LongLongMap globalWorldOrder, final LongLongMap nodeWorldOrder, final long timeToResolve, long originWorld) { if (globalWorldOrder == null || nodeWorldOrder == null) { return originWorld; } long currentUniverse = originWorld; long previousUniverse = Constants.NULL_LONG; long divergenceTime = nodeWorldOrder.get(currentUniverse); while (currentUniverse != previousUniverse) { //check range if (divergenceTime != Constants.NULL_LONG && divergenceTime <= timeToResolve) { return currentUniverse; } //next round previousUniverse = currentUniverse; currentUniverse = globalWorldOrder.get(currentUniverse); divergenceTime = nodeWorldOrder.get(currentUniverse); } return originWorld; } /* private void getOrLoadAndMark(final byte type, final long world, final long time, final long id, final Callback<Chunk> callback) { if (world == CoreConstants.NULL_KEY[0] && time == CoreConstants.NULL_KEY[1] && id == CoreConstants.NULL_KEY[2]) { callback.on(null); return; } final MWGResolver selfPointer = this; final Chunk cached = this._space.getAndMark(type, world, time, id); if (cached != null) { callback.on(cached); } else { final Buffer buffer = selfPointer._graph.newBuffer(); KeyHelper.keyToBuffer(buffer, type, world, time, id); this._storage.get(buffer, new Callback<Buffer>() { @Override public void on(Buffer payloads) { buffer.free(); Chunk result = null; final BufferIterator it = payloads.iterator(); if (it.hasNext()) { final Buffer view = it.next(); if (view.length() > 0) { result = selfPointer._space.create(type, world, time, id, view, null); selfPointer._space.putAndMark(type, world, time, id, result); } } payloads.free(); callback.on(result); } }); } }*/ private void getOrLoadAndMarkAll(final byte[] types, final long[] keys, final Callback<Chunk[]> callback) { int nbKeys = keys.length / KEY_SIZE; final boolean[] toLoadIndexes = new boolean[nbKeys]; int nbElem = 0; final Chunk[] result = new Chunk[nbKeys]; for (int i = 0; i < nbKeys; i++) { if (keys[i * KEY_SIZE] == CoreConstants.NULL_KEY[0] && keys[i * KEY_SIZE + 1] == CoreConstants.NULL_KEY[1] && keys[i * KEY_SIZE + 2] == CoreConstants.NULL_KEY[2]) { toLoadIndexes[i] = false; result[i] = null; } else { result[i] = this._space.getAndMark(types[i], keys[i * KEY_SIZE], keys[i * KEY_SIZE + 1], keys[i * KEY_SIZE + 2]); if (result[i] == null) { toLoadIndexes[i] = true; nbElem++; } else { toLoadIndexes[i] = false; } } } if (nbElem == 0) { callback.on(result); } else { final Buffer keysToLoad = _graph.newBuffer(); final int[] reverseIndex = new int[nbElem]; int lastInsertedIndex = 0; for (int i = 0; i < nbKeys; i++) { if (toLoadIndexes[i]) { reverseIndex[lastInsertedIndex] = i; if (lastInsertedIndex != 0) { keysToLoad.write(CoreConstants.BUFFER_SEP); } KeyHelper.keyToBuffer(keysToLoad, types[i], keys[i * KEY_SIZE], keys[i * KEY_SIZE + 1], keys[i * KEY_SIZE + 2]); lastInsertedIndex = lastInsertedIndex + 1; } } final MWGResolver selfPointer = this; this._storage.get(keysToLoad, new Callback<Buffer>() { @Override public void on(Buffer fromDbBuffers) { keysToLoad.free(); BufferIterator it = fromDbBuffers.iterator(); int i = 0; while (it.hasNext()) { int reversedIndex = reverseIndex[i]; final Buffer view = it.next(); if (view.length() > 0) { result[reversedIndex] = selfPointer._space.createAndMark(types[reversedIndex], keys[reversedIndex * KEY_SIZE], keys[reversedIndex * KEY_SIZE + 1], keys[reversedIndex * KEY_SIZE + 2]); result[reversedIndex].load(view); } else { result[reversedIndex] = null; } i++; } fromDbBuffers.free(); callback.on(result); } }); } } @Override public final NodeState resolveState(final org.mwg.Node node) { return internal_resolveState(node, true); } private StateChunk internal_resolveState(final org.mwg.Node node, final boolean safe) { final BaseNode castedNode = (BaseNode) node; StateChunk stateResult = null; if (safe) { castedNode.cacheLock(); } if (castedNode._dead) { if (safe) { castedNode.cacheUnlock(); } throw new RuntimeException(CoreConstants.DEAD_NODE_ERROR + " node id: " + node.id()); } /* OPTIMIZATION #1: NO DEPHASING */ if (castedNode._world_magic == -1 && castedNode._time_magic == -1 && castedNode._super_time_magic == -1) { stateResult = (StateChunk) this._space.get(castedNode._index_stateChunk); } else { /* OPTIMIZATION #2: SAME DEPHASING */ final WorldOrderChunk nodeWorldOrder = (WorldOrderChunk) this._space.get(castedNode._index_worldOrder); TimeTreeChunk nodeSuperTimeTree = (TimeTreeChunk) this._space.get(castedNode._index_superTimeTree); TimeTreeChunk nodeTimeTree = (TimeTreeChunk) this._space.get(castedNode._index_timeTree); if (nodeWorldOrder != null && nodeSuperTimeTree != null && nodeTimeTree != null) { if (castedNode._world_magic == nodeWorldOrder.magic() && castedNode._super_time_magic == nodeSuperTimeTree.magic() && castedNode._time_magic == nodeTimeTree.magic()) { stateResult = (StateChunk) this._space.get(castedNode._index_stateChunk); } else { /* NOMINAL CASE, LET'S RESOLVE AGAIN */ if (safe) { nodeWorldOrder.lock(); } final long nodeTime = castedNode.time(); final long nodeId = castedNode.id(); final long nodeWorld = castedNode.world(); //Common case, we have to traverseIndex World Order and Time chunks final long resolvedWorld = resolve_world(globalWorldOrderChunk, nodeWorldOrder, nodeTime, nodeWorld); if (resolvedWorld != nodeSuperTimeTree.world()) { //we have to update the superTree final TimeTreeChunk tempNodeSuperTimeTree = (TimeTreeChunk) this._space.getAndMark(ChunkType.TIME_TREE_CHUNK, resolvedWorld, CoreConstants.NULL_LONG, nodeId); if (tempNodeSuperTimeTree != null) { _space.unmark(nodeSuperTimeTree.index()); nodeSuperTimeTree = tempNodeSuperTimeTree; } } long resolvedSuperTime = nodeSuperTimeTree.previousOrEqual(nodeTime); if (resolvedSuperTime != nodeTimeTree.time()) { //we have to update the timeTree final TimeTreeChunk tempNodeTimeTree = (TimeTreeChunk) this._space.getAndMark(ChunkType.TIME_TREE_CHUNK, resolvedWorld, resolvedSuperTime, nodeId); if (tempNodeTimeTree != null) { _space.unmark(nodeTimeTree.index()); nodeTimeTree = tempNodeTimeTree; } } final long resolvedTime = nodeTimeTree.previousOrEqual(nodeTime); //are we still unphased if (resolvedWorld == nodeWorld && resolvedTime == nodeTime) { castedNode._world_magic = -1; castedNode._time_magic = -1; castedNode._super_time_magic = -1; } else { //save magic numbers castedNode._world_magic = nodeWorldOrder.magic(); castedNode._time_magic = nodeTimeTree.magic(); castedNode._super_time_magic = nodeSuperTimeTree.magic(); //save updated index castedNode._index_superTimeTree = nodeSuperTimeTree.index(); castedNode._index_timeTree = nodeTimeTree.index(); } stateResult = (StateChunk) this._space.get(castedNode._index_stateChunk); if (resolvedWorld != stateResult.world() || resolvedTime != stateResult.time()) { final StateChunk tempNodeState = (StateChunk) this._space.getAndMark(STATE_CHUNK, resolvedWorld, resolvedTime, nodeId); if (tempNodeState != null) { this._space.unmark(stateResult.index()); stateResult = tempNodeState; } } castedNode._index_stateChunk = stateResult.index(); if (safe) { nodeWorldOrder.unlock(); } } } } if (safe) { castedNode.cacheUnlock(); } return stateResult; } @Override public final NodeState alignState(final org.mwg.Node node) { final BaseNode castedNode = (BaseNode) node; castedNode.cacheLock(); if (castedNode._dead) { castedNode.cacheUnlock(); throw new RuntimeException(CoreConstants.DEAD_NODE_ERROR + " node id: " + node.id()); } //OPTIMIZATION #1: NO DEPHASING if (castedNode._world_magic == -1 && castedNode._time_magic == -1 && castedNode._super_time_magic == -1) { final StateChunk currentEntry = (StateChunk) this._space.get(castedNode._index_stateChunk); if (currentEntry != null) { castedNode.cacheUnlock(); return currentEntry; } } //NOMINAL CASE final WorldOrderChunk nodeWorldOrder = (WorldOrderChunk) this._space.get(castedNode._index_worldOrder); if (nodeWorldOrder == null) { castedNode.cacheUnlock(); return null; } nodeWorldOrder.lock(); //Get the previous StateChunk final StateChunk previouStateChunk = internal_resolveState(node, false); if (castedNode._world_magic == -1 && castedNode._time_magic == -1 && castedNode._super_time_magic == -1) { //it has been already rePhased, just return nodeWorldOrder.unlock(); castedNode.cacheUnlock(); return previouStateChunk; } final long nodeWorld = node.world(); long nodeTime = node.time(); final long nodeId = node.id(); //compute time sensitivity final TimeTreeChunk superTimeTree = (TimeTreeChunk) this._space.get(castedNode._index_superTimeTree); final long timeSensitivity = superTimeTree.extra(); if (timeSensitivity != 0 && timeSensitivity != Constants.NULL_LONG) { if (timeSensitivity < 0) { nodeTime = previouStateChunk.time(); } else { long timeSensitivityOffset = superTimeTree.extra2(); if (timeSensitivityOffset == Constants.NULL_LONG) { timeSensitivityOffset = 0; } nodeTime = nodeTime - (nodeTime % timeSensitivity) + timeSensitivityOffset; } } final StateChunk clonedState = (StateChunk) this._space.createAndMark(STATE_CHUNK, nodeWorld, nodeTime, nodeId); clonedState.loadFrom(previouStateChunk); castedNode._world_magic = -1; castedNode._super_time_magic = -1; castedNode._time_magic = -1; castedNode._index_stateChunk = clonedState.index(); _space.unmark(previouStateChunk.index()); if (previouStateChunk.world() == nodeWorld || nodeWorldOrder.get(nodeWorld) != CoreConstants.NULL_LONG) { //final TimeTreeChunk superTimeTree = (TimeTreeChunk) this._space.get(castedNode._index_superTimeTree); final TimeTreeChunk timeTree = (TimeTreeChunk) this._space.get(castedNode._index_timeTree); //manage super tree here long superTreeSize = superTimeTree.size(); long threshold = CoreConstants.SCALE_1 * 2; if (superTreeSize > threshold) { threshold = CoreConstants.SCALE_2 * 2; } if (superTreeSize > threshold) { threshold = CoreConstants.SCALE_3 * 2; } if (superTreeSize > threshold) { threshold = CoreConstants.SCALE_4 * 2; } timeTree.insert(nodeTime); if (timeTree.size() == threshold) { final long[] medianPoint = {-1}; //we iterate over the tree without boundaries for values, but with boundaries for number of collected times timeTree.range(CoreConstants.BEGINNING_OF_TIME, CoreConstants.END_OF_TIME, timeTree.size() / 2, new TreeWalker() { @Override public void elem(long t) { medianPoint[0] = t; } }); TimeTreeChunk rightTree = (TimeTreeChunk) this._space.createAndMark(ChunkType.TIME_TREE_CHUNK, nodeWorld, medianPoint[0], nodeId); //TODO second iterate that can be avoided, however we need the median point to create the right tree //we iterate over the tree without boundaries for values, but with boundaries for number of collected times final TimeTreeChunk finalRightTree = rightTree; //rang iterate readVar the end of the tree timeTree.range(CoreConstants.BEGINNING_OF_TIME, CoreConstants.END_OF_TIME, timeTree.size() / 2, new TreeWalker() { @Override public void elem(long t) { finalRightTree.unsafe_insert(t); } }); _space.notifyUpdate(finalRightTree.index()); superTimeTree.insert(medianPoint[0]); //remove times insert in the right tree timeTree.clearAt(medianPoint[0]); //ok ,now manage marks if (nodeTime < medianPoint[0]) { _space.unmark(rightTree.index()); } else { castedNode._index_timeTree = finalRightTree.index(); _space.unmark(timeTree.index()); } } } else { //create a new node superTimeTree TimeTreeChunk newSuperTimeTree = (TimeTreeChunk) this._space.createAndMark(ChunkType.TIME_TREE_CHUNK, nodeWorld, CoreConstants.NULL_LONG, nodeId); newSuperTimeTree.insert(nodeTime); //create a new node timeTree TimeTreeChunk newTimeTree = (TimeTreeChunk) this._space.createAndMark(ChunkType.TIME_TREE_CHUNK, nodeWorld, nodeTime, nodeId); newTimeTree.insert(nodeTime); //insert into node world order nodeWorldOrder.put(nodeWorld, nodeTime); //let's store the new state if necessary _space.unmark(castedNode._index_timeTree); _space.unmark(castedNode._index_superTimeTree); castedNode._index_timeTree = newTimeTree.index(); castedNode._index_superTimeTree = newSuperTimeTree.index(); } nodeWorldOrder.unlock(); castedNode.cacheUnlock(); return clonedState; } @Override public NodeState newState(Node node, long world, long time) { final BaseNode castedNode = (BaseNode) node; NodeState resolved; castedNode.cacheLock(); BaseNode fakeNode = new BaseNode(world, time, node.id(), node.graph()); fakeNode._index_worldOrder = castedNode._index_worldOrder; fakeNode._index_superTimeTree = castedNode._index_superTimeTree; fakeNode._index_timeTree = castedNode._index_timeTree; fakeNode._index_stateChunk = castedNode._index_stateChunk; fakeNode._time_magic = castedNode._time_magic; fakeNode._super_time_magic = castedNode._super_time_magic; fakeNode._world_magic = castedNode._world_magic; resolved = alignState(fakeNode); castedNode._index_worldOrder = fakeNode._index_worldOrder; castedNode._index_superTimeTree = fakeNode._index_superTimeTree; castedNode._index_timeTree = fakeNode._index_timeTree; castedNode._index_stateChunk = fakeNode._index_stateChunk; castedNode._time_magic = fakeNode._time_magic; castedNode._super_time_magic = fakeNode._super_time_magic; castedNode._world_magic = fakeNode._world_magic; castedNode.cacheUnlock(); return resolved; } @Override public void resolveTimepoints(final org.mwg.Node node, final long beginningOfSearch, final long endOfSearch, final Callback<long[]> callback) { final MWGResolver selfPointer = this; _space.getOrLoadAndMark(ChunkType.WORLD_ORDER_CHUNK, 0, 0, node.id(), new Callback<Chunk>() { @Override public void on(Chunk resolved) { if (resolved == null) { callback.on(new long[0]); return; } final WorldOrderChunk objectWorldOrder = (WorldOrderChunk) resolved; //worlds collector final int[] collectionSize = {CoreConstants.MAP_INITIAL_CAPACITY}; final long[][] collectedWorlds = {new long[collectionSize[0]]}; int collectedIndex = 0; long currentWorld = node.world(); while (currentWorld != CoreConstants.NULL_LONG) { long divergenceTimepoint = objectWorldOrder.get(currentWorld); if (divergenceTimepoint != CoreConstants.NULL_LONG) { if (divergenceTimepoint <= beginningOfSearch) { //take the first one before leaving collectedWorlds[0][collectedIndex] = currentWorld; collectedIndex++; break; } else if (divergenceTimepoint > endOfSearch) { //next round, go to parent world currentWorld = selfPointer.globalWorldOrderChunk.get(currentWorld); } else { //that's fit, add to search collectedWorlds[0][collectedIndex] = currentWorld; collectedIndex++; if (collectedIndex == collectionSize[0]) { //reallocate long[] temp_collectedWorlds = new long[collectionSize[0] * 2]; System.arraycopy(collectedWorlds[0], 0, temp_collectedWorlds, 0, collectionSize[0]); collectedWorlds[0] = temp_collectedWorlds; collectionSize[0] = collectionSize[0] * 2; } //go to parent currentWorld = selfPointer.globalWorldOrderChunk.get(currentWorld); } } else { //go to parent currentWorld = selfPointer.globalWorldOrderChunk.get(currentWorld); } } //create request concat keys selfPointer.resolveTimepointsFromWorlds(objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedWorlds[0], collectedIndex, callback); } }); } private void resolveTimepointsFromWorlds(final WorldOrderChunk objectWorldOrder, final org.mwg.Node node, final long beginningOfSearch, final long endOfSearch, final long[] collectedWorlds, final int collectedWorldsSize, final Callback<long[]> callback) { final MWGResolver selfPointer = this; final long[] timeTreeKeys = new long[collectedWorldsSize * 3]; final byte[] types = new byte[collectedWorldsSize]; for (int i = 0; i < collectedWorldsSize; i++) { timeTreeKeys[i * 3] = collectedWorlds[i]; timeTreeKeys[i * 3 + 1] = CoreConstants.NULL_LONG; timeTreeKeys[i * 3 + 2] = node.id(); types[i] = ChunkType.TIME_TREE_CHUNK; } getOrLoadAndMarkAll(types, timeTreeKeys, new Callback<Chunk[]>() { @Override public void on(final Chunk[] superTimeTrees) { if (superTimeTrees == null) { selfPointer._space.unmark(objectWorldOrder.index()); callback.on(new long[0]); } else { //time collector final int[] collectedSize = {CoreConstants.MAP_INITIAL_CAPACITY}; final long[][] collectedSuperTimes = {new long[collectedSize[0]]}; final long[][] collectedSuperTimesAssociatedWorlds = {new long[collectedSize[0]]}; final int[] insert_index = {0}; long previousDivergenceTime = endOfSearch; for (int i = 0; i < collectedWorldsSize; i++) { final TimeTreeChunk timeTree = (TimeTreeChunk) superTimeTrees[i]; if (timeTree != null) { long currentDivergenceTime = objectWorldOrder.get(collectedWorlds[i]); //if (currentDivergenceTime < beginningOfSearch) { // currentDivergenceTime = beginningOfSearch; final long finalPreviousDivergenceTime = previousDivergenceTime; timeTree.range(currentDivergenceTime, previousDivergenceTime, CoreConstants.END_OF_TIME, new TreeWalker() { @Override public void elem(long t) { if (t != finalPreviousDivergenceTime) { collectedSuperTimes[0][insert_index[0]] = t; collectedSuperTimesAssociatedWorlds[0][insert_index[0]] = timeTree.world(); insert_index[0]++; if (collectedSize[0] == insert_index[0]) { //reallocate long[] temp_collectedSuperTimes = new long[collectedSize[0] * 2]; long[] temp_collectedSuperTimesAssociatedWorlds = new long[collectedSize[0] * 2]; System.arraycopy(collectedSuperTimes[0], 0, temp_collectedSuperTimes, 0, collectedSize[0]); System.arraycopy(collectedSuperTimesAssociatedWorlds[0], 0, temp_collectedSuperTimesAssociatedWorlds, 0, collectedSize[0]); collectedSuperTimes[0] = temp_collectedSuperTimes; collectedSuperTimesAssociatedWorlds[0] = temp_collectedSuperTimesAssociatedWorlds; collectedSize[0] = collectedSize[0] * 2; } } } }); previousDivergenceTime = currentDivergenceTime; } selfPointer._space.unmark(timeTree.index()); } //now we have superTimes, lets convert them to all times selfPointer.resolveTimepointsFromSuperTimes(objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedSuperTimesAssociatedWorlds[0], collectedSuperTimes[0], insert_index[0], callback); } } }); } private void resolveTimepointsFromSuperTimes(final WorldOrderChunk objectWorldOrder, final org.mwg.Node node, final long beginningOfSearch, final long endOfSearch, final long[] collectedWorlds, final long[] collectedSuperTimes, final int collectedSize, final Callback<long[]> callback) { final MWGResolver selfPointer = this; final long[] timeTreeKeys = new long[collectedSize * 3]; final byte[] types = new byte[collectedSize]; for (int i = 0; i < collectedSize; i++) { timeTreeKeys[i * 3] = collectedWorlds[i]; timeTreeKeys[i * 3 + 1] = collectedSuperTimes[i]; timeTreeKeys[i * 3 + 2] = node.id(); types[i] = ChunkType.TIME_TREE_CHUNK; } getOrLoadAndMarkAll(types, timeTreeKeys, new Callback<Chunk[]>() { @Override public void on(Chunk[] timeTrees) { if (timeTrees == null) { selfPointer._space.unmark(objectWorldOrder.index()); callback.on(new long[0]); } else { //time collector final int[] collectedTimesSize = {CoreConstants.MAP_INITIAL_CAPACITY}; final long[][] collectedTimes = {new long[collectedTimesSize[0]]}; final int[] insert_index = {0}; long previousDivergenceTime = endOfSearch; for (int i = 0; i < collectedSize; i++) { final TimeTreeChunk timeTree = (TimeTreeChunk) timeTrees[i]; if (timeTree != null) { long currentDivergenceTime = objectWorldOrder.get(collectedWorlds[i]); if (currentDivergenceTime < beginningOfSearch) { currentDivergenceTime = beginningOfSearch; } final long finalPreviousDivergenceTime = previousDivergenceTime; timeTree.range(currentDivergenceTime, previousDivergenceTime, CoreConstants.END_OF_TIME, new TreeWalker() { @Override public void elem(long t) { if (t != finalPreviousDivergenceTime) { collectedTimes[0][insert_index[0]] = t; insert_index[0]++; if (collectedTimesSize[0] == insert_index[0]) { //reallocate long[] temp_collectedTimes = new long[collectedTimesSize[0] * 2]; System.arraycopy(collectedTimes[0], 0, temp_collectedTimes, 0, collectedTimesSize[0]); collectedTimes[0] = temp_collectedTimes; collectedTimesSize[0] = collectedTimesSize[0] * 2; } } } }); if (i < collectedSize - 1) { if (collectedWorlds[i + 1] != collectedWorlds[i]) { //world overriding semantic previousDivergenceTime = currentDivergenceTime; } } } selfPointer._space.unmark(timeTree.index()); } //now we have times if (insert_index[0] != collectedTimesSize[0]) { long[] tempTimeline = new long[insert_index[0]]; System.arraycopy(collectedTimes[0], 0, tempTimeline, 0, insert_index[0]); collectedTimes[0] = tempTimeline; } selfPointer._space.unmark(objectWorldOrder.index()); callback.on(collectedTimes[0]); } } }); } @Override public int stringToHash(String name, boolean insertIfNotExists) { int hash = HashHelper.hash(name); if (insertIfNotExists) { StringIntMap dictionaryIndex = (StringIntMap) this.dictionary.get(0); if (dictionaryIndex == null) { dictionaryIndex = (StringIntMap) this.dictionary.getOrCreate(0, Type.STRING_TO_INT_MAP); } if (!dictionaryIndex.containsHash(hash)) { dictionaryIndex.put(name, hash); } } return hash; } @Override public String hashToString(int key) { final StringIntMap dictionaryIndex = (StringIntMap) this.dictionary.get(0); if (dictionaryIndex != null) { return dictionaryIndex.getByHash(key); } return null; } }
package no.steria.osgi.jsr330activator.testbundle1; import java.util.UUID; public interface StorageService { public boolean save(UUID id, String data); String load(UUID id); }
// Triple Play - utilities for use in PlayN-based games package tripleplay.util; import java.util.HashSet; import java.util.Set; import react.Function; import react.IntValue; import react.RSet; import react.Slot; import react.Value; import playn.core.Storage; import static playn.core.PlayN.log; /** * Makes using PlayN {@link Storage} more civilized. Provides getting and setting of typed values * (ints, booleans, etc.). Provides support for default values. Provides {@link Value} interface to * storage items. */ public class TypedStorage { public TypedStorage (Storage storage) { _storage = storage; } /** * Returns whether the specified key is mapped to some value. */ public boolean contains (String key) { return _storage.getItem(key) != null; } /** * Returns the specified property as a string, returning null if the property does not exist. */ public String get (String key) { return _storage.getItem(key); } /** * Returns the specified property as a string, returning the supplied defautl value if the * property does not exist. */ public String get (String key, String defval) { String value = _storage.getItem(key); return (value == null) ? defval : value; } /** * Sets the specified property to the supplied string value. */ public void set (String key, String value) { _storage.setItem(key, value); } /** * Returns the specified property as an int. If the property does not exist, the default value * will be returned. If the property cannot be parsed as an int, an error will be logged and * the default value will be returned. */ public int get (String key, int defval) { String value = null; try { value = _storage.getItem(key); return (value == null) ? defval : Integer.parseInt(value); } catch (Exception e) { log().warn("Failed to parse int prop [key=" + key + ", value=" + value + "]", e); return defval; } } /** * Sets the specified property to the supplied int value. */ public void set (String key, int value) { _storage.setItem(key, String.valueOf(value)); } /** * Returns the specified property as a long. If the property does not exist, the default value * will be returned. If the property cannot be parsed as a long, an error will be logged and * the default value will be returned. */ public long get (String key, long defval) { String value = null; try { value = _storage.getItem(key); return (value == null) ? defval : Long.parseLong(value); } catch (Exception e) { log().warn("Failed to parse long prop [key=" + key + ", value=" + value + "]", e); return defval; } } /** * Sets the specified property to the supplied long value. */ public void set (String key, long value) { _storage.setItem(key, String.valueOf(value)); } /** * Returns the specified property as a double. If the property does not exist, the default * value will be returned. If the property cannot be parsed as a double, an error will be * logged and the default value will be returned. */ public double get (String key, double defval) { String value = null; try { value = _storage.getItem(key); return (value == null) ? defval : Double.parseDouble(value); } catch (Exception e) { log().warn("Failed to parse double prop [key=" + key + ", value=" + value + "]", e); return defval; } } /** * Sets the specified property to the supplied double value. */ public void set (String key, double value) { _storage.setItem(key, String.valueOf(value)); } /** * Returns the specified property as a boolean. If the property does not exist, the default * value will be returned. Any existing value equal to {@code t} (ignoring case) will be * considered true; all others, false. */ public boolean get (String key, boolean defval) { String value = _storage.getItem(key); return (value == null) ? defval : value.equalsIgnoreCase("t"); } /** * Sets the specified property to the supplied boolean value. */ public void set (String key, boolean value) { _storage.setItem(key, value ? "t" : "f"); } /** * Returns the specified property as an enum. If the property does not exist, the default value * will be returned. * @throws NullPointerException if {@code defval} is null. */ public <E extends Enum<E>> E get (String key, E defval) { @SuppressWarnings("unchecked") Class<E> eclass = (Class<E>)defval.getClass(); String value = null; try { value = _storage.getItem(key); return (value == null) ? defval : Enum.valueOf(eclass, value); } catch (Exception e) { log().warn("Failed to parse enum prop [key=" + key + ", value=" + value + "]", e); return defval; } } /** * Sets the specified property to the supplied enum value. */ public void set (String key, Enum<?> value) { _storage.setItem(key, value.name()); } /** * Removes the specified key (and its value) from storage. */ public void remove (String key) { _storage.removeItem(key); } /** * Exposes the specified property as a {@link Value}. The supplied default value will be used * if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link Value} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public Value<String> valueFor (final String key, String defval) { Value<String> value = Value.create(get(key, defval)); value.connect(new Slot<String>() { @Override public void onEmit (String value) { set(key, value); } }); return value; } /** * Exposes the specified property as an {@link IntValue}. The supplied default value will be * used if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link IntValue} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public IntValue valueFor (final String key, int defval) { IntValue value = new IntValue(get(key, defval)); value.connect(new Slot<Integer>() { @Override public void onEmit (Integer value) { set(key, value); } }); return value; } /** * Exposes the specified property as a {@link Value}. The supplied default value will be used * if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link Value} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public Value<Long> valueFor (final String key, long defval) { Value<Long> value = Value.create(get(key, defval)); value.connect(new Slot<Long>() { @Override public void onEmit (Long value) { set(key, value); } }); return value; } /** * Exposes the specified property as a {@link Value}. The supplied default value will be used * if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link Value} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public Value<Double> valueFor (final String key, double defval) { Value<Double> value = Value.create(get(key, defval)); value.connect(new Slot<Double>() { @Override public void onEmit (Double value) { set(key, value); } }); return value; } /** * Exposes the specified property as a {@link Value}. The supplied default value will be used * if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link Value} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public Value<Boolean> valueFor (final String key, boolean defval) { Value<Boolean> value = Value.create(get(key, defval)); value.connect(new Slot<Boolean>() { @Override public void onEmit (Boolean value) { set(key, value); } }); return value; } /** * Exposes the specified property as a {@link Value}. The supplied default value will be used * if the property has no current value. Updates to the value will be written back to the * storage system. Note that each call to this method yields a new {@link Value} and those * values will not coordinate with one another, so the caller must be sure to only call this * method once for a given property and share that value properly. */ public <E extends Enum<E>> Value<E> valueFor (final String key, E defval) { Value<E> value = Value.create(get(key, defval)); value.connect(new Slot<E>() { @Override public void onEmit (E value) { set(key, value); } }); return value; } /** * Exposes the specified property as an {@link RSet}. The contents of the set will be encoded * as a comma separated string and the supplied {@code toFunc} and {@code fromFunc} will be * used to convert an individual set item to and from a string. The to and from functions * should perform escaping and unescaping of commas if the encoded representation of the items * might naturally contain commas. * * <p>Any modifications to the set will be immediately persisted back to storage. Note that * each call to this method yields a new {@link RSet} and those sets will not coordinate with * one another, so the caller must be sure to only call this method once for a given property * and share that set properly. Changes to the underlying persistent value that do not take * place through the returned set will <em>not</em> be reflected in the set and will be * overwritten if the set changes.</p> */ public <E> RSet<E> setFor (String key, Function<String,E> toFunc, Function<E,String> fromFunc) { return setFor(key, toFunc, fromFunc, new HashSet<E>()); } /** * Exposes the specified property as an {@link RSet} using {@code impl} as the concrete set * implementation. See {@link #setFor(String,Function,Function)} for more details. */ public <E> RSet<E> setFor (final String key, Function<String,E> toFunc, final Function<E,String> fromFunc, Set<E> impl) { final RSet<E> rset = RSet.create(impl); String data = get(key, (String)null); if (data != null) { for (String value : data.split(",")) { try { rset.add(toFunc.apply(value)); } catch (Exception e) { log().warn("Invalid value (key=" + key + "): " + value, e); } } } rset.connect(new RSet.Listener<E>() { @Override public void onAdd (E unused) { save(); } @Override public void onRemove (E unused) { save(); } protected void save () { if (rset.isEmpty()) remove(key); else { StringBuilder buf = new StringBuilder(); int ii = 0; for (E value : rset) { if (ii++ > 0) buf.append(","); buf.append(fromFunc.apply(value)); } set(key, buf.toString()); } } }); return rset; } protected final Storage _storage; }
package org.languagetool.rules.en; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.en.translation.BeoLingusTranslator; import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule; import org.languagetool.rules.translation.Translator; import org.languagetool.synthesis.en.EnglishSynthesizer; import org.languagetool.tools.StringTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule { private static Logger logger = LoggerFactory.getLogger(AbstractEnglishSpellerRule.class); private static final EnglishSynthesizer synthesizer = (EnglishSynthesizer) Languages.getLanguageForShortCode("en").getSynthesizer(); private final BeoLingusTranslator translator; public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException { this(messages, language, null, Collections.emptyList()); } /** * @since 4.4 */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException { this(messages, language, null, userConfig, altLanguages, null, null); } protected static Map<String,String> loadWordlist(String path, int column) { if (column != 0 && column != 1) { throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column); } Map<String,String> words = new HashMap<>(); List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } String[] parts = line.split(";"); if (parts.length != 2) { throw new RuntimeException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'"); } words.put(parts[column].toLowerCase(), parts[column == 1 ? 0 : 1]); } return words; } /** * @since 4.5 * optional: language model for better suggestions */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, GlobalConfig globalConfig, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel, Language motherTongue) throws IOException { super(messages, language, globalConfig, userConfig, altLanguages, languageModel, motherTongue); super.ignoreWordsWithLength = 1; setCheckCompound(true); addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."), Example.fixed("This <marker>sentence</marker> contains a spelling mistake.")); String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt"); for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) { addIgnoreWords(ignoreWord); } translator = BeoLingusTranslator.getInstance(globalConfig); topSuggestions = getTopSuggestions(); topSuggestionsIgnoreCase = getTopSuggestionsIgnoreCase(); } @Override protected List<SuggestedReplacement> filterSuggestions(List<SuggestedReplacement> suggestions, AnalyzedSentence sentence, int i) { List<SuggestedReplacement> result = super.filterSuggestions(suggestions, sentence, i); List<SuggestedReplacement> clean = new ArrayList<>(); for (SuggestedReplacement suggestion : result) { if (!suggestion.getReplacement().matches(".* (s|t|d|ll|ve)")) { // e.g. 'timezones' suggests 'timezone s' clean.add(suggestion); } } return clean; } @Override protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException { List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens); if (ruleMatches.size() > 0) { // so 'word' is misspelled: IrregularForms forms = getIrregularFormsOrNull(word); if (forms != null) { String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) + "</suggestion>, the " + forms.formName + " form of the " + forms.posName + " '" + forms.baseform + "'?"; addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms); } else { VariantInfo variantInfo = isValidInOtherVariant(word); if (variantInfo != null) { String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + "."; String suggestion = StringTools.startsWithUppercase(word) ? StringTools.uppercaseFirstChar(variantInfo.otherVariant()) : variantInfo.otherVariant(); replaceFormsOfFirstMatch(message, sentence, ruleMatches, suggestion); } } } // filter "re ..." (#2562): for (RuleMatch ruleMatch : ruleMatches) { List<SuggestedReplacement> cleaned = ruleMatch.getSuggestedReplacementObjects().stream() .filter(k -> !k.getReplacement().startsWith("re ") && !k.getReplacement().startsWith("en ") && !k.getReplacement().startsWith("inter ") && !k.getReplacement().endsWith(" able") && !k.getReplacement().endsWith(" ed")) .collect(Collectors.toList()); ruleMatch.setSuggestedReplacementObjects(cleaned); } return ruleMatches; } /** * @since 4.5 */ @Nullable protected VariantInfo isValidInOtherVariant(String word) { return null; } private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); List<String> allSuggestions = new ArrayList<>(forms); for (String repl : oldMatch.getSuggestedReplacements()) { if (!allSuggestions.contains(repl)) { allSuggestions.add(repl); } } newMatch.setSuggestedReplacements(allSuggestions); ruleMatches.set(0, newMatch); } private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); SuggestedReplacement sugg = new SuggestedReplacement(suggestion); sugg.setShortDescription(language.getName()); newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg)); ruleMatches.set(0, newMatch); } @SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"}) @Nullable private IrregularForms getIrregularFormsOrNull(String word) { IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative"); return irregularFormsOrNull; } @Nullable private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) { try { for (String suffix : suffixes) { if (word.endsWith(wordSuffix)) { String baseForm = word.substring(0, word.length() - suffix.length()); String[] forms = Objects.requireNonNull(language.getSynthesizer()).synthesize(new AnalyzedToken(word, null, baseForm), posTag); List<String> result = new ArrayList<>(); for (String form : forms) { if (!speller1.isMisspelled(form)) { // only accept suggestions that the spellchecker will accept result.add(form); } } // the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'), // but we trust the spell checker in this case: result.remove(word); result.remove("badder"); // non-standard usage result.remove("baddest"); // non-standard usage result.remove("spake"); // can be removed after dict update if (result.size() > 0) { return new IrregularForms(baseForm, posName, formName, result); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } } protected final Map<String, List<String>> topSuggestions; protected final Map<String, List<String>> topSuggestionsIgnoreCase; protected Map<String, List<String>> getTopSuggestionsIgnoreCase() { Map<String, List<String>> s = new HashMap<>(); s.put("xml", Arrays.asList("XML")); s.put("php", Arrays.asList("PHP")); s.put("asp", Arrays.asList("ASP")); s.put("rss", Arrays.asList("RSS")); s.put("ssd", Arrays.asList("SSD")); s.put("ssds", Arrays.asList("SSDs")); s.put("hdds", Arrays.asList("HDDs")); s.put("isp", Arrays.asList("ISP")); s.put("isps", Arrays.asList("ISPs")); s.put("suv", Arrays.asList("SUV")); s.put("suvs", Arrays.asList("SUVs")); s.put("gif", Arrays.asList("GIF")); s.put("gifs", Arrays.asList("GIFs")); s.put("atm", Arrays.asList("ATM")); s.put("atms", Arrays.asList("ATMs")); s.put("png", Arrays.asList("PNG")); s.put("pngs", Arrays.asList("PNGs")); s.put("csv", Arrays.asList("CSV")); s.put("csvs", Arrays.asList("CSVs")); s.put("pdf", Arrays.asList("PDF")); s.put("pdfs", Arrays.asList("PDFs")); s.put("jpeg", Arrays.asList("JPEG")); s.put("jpegs", Arrays.asList("JPEGs")); s.put("jpg", Arrays.asList("JPG")); s.put("jpgs", Arrays.asList("JPGs")); s.put("bmp", Arrays.asList("BMP")); s.put("bmps", Arrays.asList("BMPs")); s.put("docx", Arrays.asList("DOCX")); s.put("xlsx", Arrays.asList("XLSX")); s.put("btw", Arrays.asList("BTW")); s.put("idk", Arrays.asList("IDK")); s.put("ai", Arrays.asList("AI")); s.put("ip", Arrays.asList("IP")); s.put("rfc", Arrays.asList("RFC")); s.put("ppt", Arrays.asList("PPT")); s.put("ppts", Arrays.asList("PPTs")); s.put("pptx", Arrays.asList("PPTX")); s.put("vpn", Arrays.asList("VPN")); s.put("psn", Arrays.asList("PSN")); s.put("usd", Arrays.asList("USD")); s.put("tv", Arrays.asList("TV")); s.put("eur", Arrays.asList("EUR")); s.put("tbh", Arrays.asList("TBH")); s.put("tbd", Arrays.asList("TBD")); s.put("tba", Arrays.asList("TBA")); s.put("omg", Arrays.asList("OMG")); s.put("lol", Arrays.asList("LOL")); s.put("lmao", Arrays.asList("LMAO")); s.put("wtf", Arrays.asList("WTF")); s.put("fyi", Arrays.asList("FYI")); s.put("url", Arrays.asList("URL")); s.put("urls", Arrays.asList("URLs")); s.put("usb", Arrays.asList("USB")); s.put("bbq", Arrays.asList("BBQ")); s.put("bbqs", Arrays.asList("BBQs")); s.put("ngo", Arrays.asList("NGO")); s.put("ngos", Arrays.asList("NGOs")); s.put("js", Arrays.asList("JS")); s.put("css", Arrays.asList("CSS")); s.put("roi", Arrays.asList("ROI")); s.put("pov", Arrays.asList("POV")); s.put("ctrl", Arrays.asList("Ctrl")); s.put("italia", Arrays.asList("Italy")); s.put("macboook", Arrays.asList("MacBook")); s.put("macboooks", Arrays.asList("MacBooks")); s.put("paypal", Arrays.asList("PayPal")); s.put("youtube", Arrays.asList("YouTube")); s.put("whatsapp", Arrays.asList("WhatsApp")); s.put("webex", Arrays.asList("WebEx")); s.put("jira", Arrays.asList("Jira")); s.put("applepay", Arrays.asList("Apple Pay")); s.put("&&", Arrays.asList("&")); s.put("wensday", Arrays.asList("Wednesday")); s.put("linkedin", Arrays.asList("LinkedIn")); s.put("ebay", Arrays.asList("eBay")); s.put("interweb", Arrays.asList("internet")); s.put("interwebs", Arrays.asList("internet")); s.put("afro-american", Arrays.asList("Afro-American")); s.put("oconnor", Arrays.asList("O'Connor")); s.put("oconor", Arrays.asList("O'Conor")); s.put("obrien", Arrays.asList("O'Brien")); s.put("odonnell", Arrays.asList("O'Donnell")); s.put("oneill", Arrays.asList("O'Neill")); s.put("oneil", Arrays.asList("O'Neil")); s.put("oconnell", Arrays.asList("O'Connell")); s.put("todo", Arrays.asList("To-do", "To do")); s.put("todos", Arrays.asList("To-dos")); s.put("ecommerce", Arrays.asList("e-commerce")); s.put("elearning", Arrays.asList("e-learning")); s.put("esport", Arrays.asList("e-sport")); s.put("esports", Arrays.asList("e-sports")); s.put("g-mail", Arrays.asList("Gmail")); s.put("playstation", Arrays.asList("PlayStation")); return s; } protected Map<String, List<String>> getTopSuggestions() { Map<String, List<String>> s = new HashMap<>(); s.put("on-prem", Arrays.asList("on-premise")); s.put("sin-off", Arrays.asList("sign-off")); s.put("sin-offs", Arrays.asList("sign-offs")); s.put("Sin-off", Arrays.asList("Sign-off")); s.put("Sin-offs", Arrays.asList("Sign-offs")); s.put("Alot", Arrays.asList("A lot")); s.put("alot", Arrays.asList("a lot")); s.put("DDOS", Arrays.asList("DDoS")); s.put("async", Arrays.asList("asynchronous", "asynchronously")); s.put("Async", Arrays.asList("Asynchronous", "Asynchronously")); s.put("endevours", Arrays.asList("endeavours")); s.put("endevors", Arrays.asList("endeavors")); s.put("endevour", Arrays.asList("endeavour")); s.put("endevor", Arrays.asList("endeavor")); s.put("countrys", Arrays.asList("countries", "country's", "country")); s.put("ad-hoc", Arrays.asList("ad hoc")); s.put("adhoc", Arrays.asList("ad hoc")); s.put("Ad-hoc", Arrays.asList("Ad hoc")); s.put("Adhoc", Arrays.asList("Ad hoc")); s.put("ad-on", Arrays.asList("add-on")); s.put("add-o", Arrays.asList("add-on")); s.put("acc", Arrays.asList("account", "accusative")); s.put("Acc", Arrays.asList("Account", "Accusative")); s.put("ºC", Arrays.asList("°C")); s.put("jus", Arrays.asList("just", "juice")); s.put("Jus", Arrays.asList("Just", "Juice")); s.put("sayed", Arrays.asList("said")); s.put("sess", Arrays.asList("says", "session", "cess")); s.put("Addon", Arrays.asList("Add-on")); s.put("Addons", Arrays.asList("Add-ons")); s.put("ios", Arrays.asList("iOS")); s.put("yrs", Arrays.asList("years")); s.put("standup", Arrays.asList("stand-up")); s.put("standups", Arrays.asList("stand-ups")); s.put("Standup", Arrays.asList("Stand-up")); s.put("Standups", Arrays.asList("Stand-ups")); s.put("Playdough", Arrays.asList("Play-Doh")); s.put("playdough", Arrays.asList("Play-Doh")); s.put("biggy", Arrays.asList("biggie")); s.put("lieing", Arrays.asList("lying")); s.put("preffered", Arrays.asList("preferred")); s.put("preffering", Arrays.asList("preferring")); s.put("reffered", Arrays.asList("referred")); s.put("reffering", Arrays.asList("referring")); s.put("passthrough", Arrays.asList("pass-through")); s.put("&&", Arrays.asList("&")); s.put("cmon", Arrays.asList("c'mon")); s.put("Cmon", Arrays.asList("C'mon")); s.put("da", Arrays.asList("the")); s.put("Da", Arrays.asList("The")); s.put("Vue", Arrays.asList("Vue.JS")); s.put("errornous", Arrays.asList("erroneous")); s.put("brang", Arrays.asList("brought")); s.put("brung", Arrays.asList("brought")); s.put("thru", Arrays.asList("through")); s.put("pitty", Arrays.asList("pity")); s.put("barbwire", Arrays.asList("barbed wire")); s.put("barbwires", Arrays.asList("barbed wires")); s.put("monkie", Arrays.asList("monkey")); s.put("Monkie", Arrays.asList("Monkey")); s.put("monkies", Arrays.asList("monkeys")); s.put("Monkies", Arrays.asList("Monkeys")); // the replacement pairs would prefer "speak" s.put("speach", Arrays.asList("speech")); s.put("icecreem", Arrays.asList("ice cream")); // in en-gb it's 'maths' s.put("math", Arrays.asList("maths")); s.put("fora", Arrays.asList("for a")); s.put("fomr", Arrays.asList("form", "from")); s.put("lotsa", Arrays.asList("lots of")); s.put("tryna", Arrays.asList("trying to")); s.put("coulda", Arrays.asList("could have")); s.put("shoulda", Arrays.asList("should have")); s.put("woulda", Arrays.asList("would have")); s.put("tellem", Arrays.asList("tell them")); s.put("Tellem", Arrays.asList("Tell them")); s.put("Webex", Arrays.asList("WebEx")); s.put("didint", Arrays.asList("didn't")); s.put("Didint", Arrays.asList("Didn't")); s.put("wasint", Arrays.asList("wasn't")); s.put("hasint", Arrays.asList("hasn't")); s.put("doesint", Arrays.asList("doesn't")); s.put("ist", Arrays.asList("is")); s.put("Boing", Arrays.asList("Boeing")); s.put("te", Arrays.asList("the")); s.put("todays", Arrays.asList("today's")); s.put("Todays", Arrays.asList("Today's")); s.put("todo", Arrays.asList("to-do", "to do")); s.put("todos", Arrays.asList("to-dos", "to do")); s.put("heres", Arrays.asList("here's")); s.put("Heres", Arrays.asList("Here's")); s.put("aways", Arrays.asList("always")); s.put("McDonalds", Arrays.asList("McDonald's")); s.put("ux", Arrays.asList("UX")); s.put("ive", Arrays.asList("I've")); s.put("infos", Arrays.asList("informations")); s.put("Infos", Arrays.asList("Informations")); s.put("prios", Arrays.asList("priorities")); s.put("Prio", Arrays.asList("Priority")); s.put("prio", Arrays.asList("priority")); s.put("Ecommerce", Arrays.asList("E-Commerce")); s.put("ebook", Arrays.asList("e-book")); s.put("ebooks", Arrays.asList("e-books")); s.put("eBook", Arrays.asList("e-book")); s.put("eBooks", Arrays.asList("e-books")); s.put("Ebook", Arrays.asList("E-Book")); s.put("Ebooks", Arrays.asList("E-Books")); s.put("Esport", Arrays.asList("E-Sport")); s.put("Esports", Arrays.asList("E-Sports")); s.put("R&B", Arrays.asList("R & B", "R 'n' B")); s.put("ie", Arrays.asList("i.e.")); s.put("eg", Arrays.asList("e.g.")); s.put("ppl", Arrays.asList("people")); s.put("kiddin", Arrays.asList("kidding")); s.put("doin", Arrays.asList("doing")); s.put("nothin", Arrays.asList("nothing")); s.put("SPOC", Arrays.asList("SpOC")); s.put("Thx", Arrays.asList("Thanks")); s.put("thx", Arrays.asList("thanks")); s.put("ty", Arrays.asList("thank you", "thanks")); s.put("Sry", Arrays.asList("Sorry")); s.put("sry", Arrays.asList("sorry")); s.put("im", Arrays.asList("I'm")); s.put("spoilt", Arrays.asList("spoiled")); s.put("Lil", Arrays.asList("Little")); s.put("lil", Arrays.asList("little")); s.put("gmail", Arrays.asList("Gmail")); s.put("Sucka", Arrays.asList("Sucker")); s.put("sucka", Arrays.asList("sucker")); s.put("whaddya", Arrays.asList("what are you", "what do you")); s.put("Whaddya", Arrays.asList("What are you", "What do you")); s.put("sinc", Arrays.asList("sync")); s.put("sweety", Arrays.asList("sweetie")); s.put("sweetys", Arrays.asList("sweeties")); s.put("sowwy", Arrays.asList("sorry")); s.put("Sowwy", Arrays.asList("Sorry")); s.put("grandmum", Arrays.asList("grandma", "grandmother")); s.put("Grandmum", Arrays.asList("Grandma", "Grandmother")); s.put("Hongkong", Arrays.asList("Hong Kong")); // For non-US English s.put("center", Arrays.asList("centre")); s.put("ur", Arrays.asList("your", "you are")); s.put("Ur", Arrays.asList("Your", "You are")); s.put("ure", Arrays.asList("your", "you are")); s.put("Ure", Arrays.asList("Your", "You are")); s.put("mins", Arrays.asList("minutes", "min")); s.put("addon", Arrays.asList("add-on")); s.put("addons", Arrays.asList("add-ons")); s.put("afterparty", Arrays.asList("after-party")); s.put("Afterparty", Arrays.asList("After-party")); s.put("wellbeing", Arrays.asList("well-being")); s.put("cuz", Arrays.asList("because")); s.put("coz", Arrays.asList("because")); s.put("pls", Arrays.asList("please")); s.put("Pls", Arrays.asList("Please")); s.put("plz", Arrays.asList("please")); s.put("Plz", Arrays.asList("Please")); // AtD irregular plurals - START s.put("addendums", Arrays.asList("addenda")); s.put("algas", Arrays.asList("algae")); s.put("alumnas", Arrays.asList("alumnae")); s.put("alumnuses", Arrays.asList("alumni")); s.put("analysises", Arrays.asList("analyses")); s.put("appendixs", Arrays.asList("appendices")); s.put("axises", Arrays.asList("axes")); s.put("bacilluses", Arrays.asList("bacilli")); s.put("bacteriums", Arrays.asList("bacteria")); s.put("basises", Arrays.asList("bases")); s.put("beaus", Arrays.asList("beaux")); s.put("bisons", Arrays.asList("bison")); s.put("buffalos", Arrays.asList("buffaloes")); s.put("calfs", Arrays.asList("calves")); s.put("Childs", Arrays.asList("Children")); s.put("childs", Arrays.asList("children")); s.put("crisises", Arrays.asList("crises")); s.put("criterions", Arrays.asList("criteria")); s.put("curriculums", Arrays.asList("curricula")); s.put("datums", Arrays.asList("data")); s.put("deers", Arrays.asList("deer")); s.put("diagnosises", Arrays.asList("diagnoses")); s.put("echos", Arrays.asList("echoes")); s.put("elfs", Arrays.asList("elves")); s.put("ellipsises", Arrays.asList("ellipses")); s.put("embargos", Arrays.asList("embargoes")); s.put("erratums", Arrays.asList("errata")); s.put("firemans", Arrays.asList("firemen")); s.put("fishs", Arrays.asList("fishes", "fish")); s.put("genuses", Arrays.asList("genera")); s.put("gooses", Arrays.asList("geese")); s.put("halfs", Arrays.asList("halves")); s.put("heros", Arrays.asList("heroes")); s.put("indexs", Arrays.asList("indices", "indexes")); s.put("lifes", Arrays.asList("lives")); s.put("mans", Arrays.asList("men")); s.put("matrixs", Arrays.asList("matrices")); s.put("meanses", Arrays.asList("means")); s.put("mediums", Arrays.asList("media")); s.put("memorandums", Arrays.asList("memoranda")); s.put("mooses", Arrays.asList("moose")); s.put("mosquitos", Arrays.asList("mosquitoes")); s.put("neurosises", Arrays.asList("neuroses")); s.put("nucleuses", Arrays.asList("nuclei")); s.put("oasises", Arrays.asList("oases")); s.put("ovums", Arrays.asList("ova")); s.put("oxs", Arrays.asList("oxen")); s.put("oxes", Arrays.asList("oxen")); s.put("paralysises", Arrays.asList("paralyses")); s.put("potatos", Arrays.asList("potatoes")); s.put("radiuses", Arrays.asList("radii")); s.put("selfs", Arrays.asList("selves")); s.put("serieses", Arrays.asList("series")); s.put("sheeps", Arrays.asList("sheep")); s.put("shelfs", Arrays.asList("shelves")); s.put("scissorses", Arrays.asList("scissors")); s.put("specieses", Arrays.asList("species")); s.put("stimuluses", Arrays.asList("stimuli")); s.put("stratums", Arrays.asList("strata")); s.put("tableaus", Arrays.asList("tableaux")); s.put("thats", Arrays.asList("those")); s.put("thesises", Arrays.asList("theses")); s.put("thiefs", Arrays.asList("thieves")); s.put("thises", Arrays.asList("these")); s.put("tomatos", Arrays.asList("tomatoes")); s.put("tooths", Arrays.asList("teeth")); s.put("torpedos", Arrays.asList("torpedoes")); s.put("vertebras", Arrays.asList("vertebrae")); s.put("vetos", Arrays.asList("vetoes")); s.put("vitas", Arrays.asList("vitae")); s.put("watchs", Arrays.asList("watches")); s.put("wifes", Arrays.asList("wives", "wife's")); s.put("womans", Arrays.asList("women", "woman's")); s.put("womens", Arrays.asList("women's")); // AtD irregular plurals - END // "tippy-top" is an often used word by Donald Trump s.put("tippy-top", Arrays.asList("tip-top", "top most")); s.put("tippytop", Arrays.asList("tip-top", "top most")); s.put("imma", Arrays.asList("I'm going to", "I'm a")); s.put("Imma", Arrays.asList("I'm going to", "I'm a")); s.put("dontcha", Arrays.asList("don't you")); s.put("tobe", Arrays.asList("to be")); s.put("Gi", Arrays.asList("Hi")); s.put("Ji", Arrays.asList("Hi")); s.put("Dontcha", Arrays.asList("don't you")); s.put("greatfruit", Arrays.asList("grapefruit", "great fruit")); s.put("ur", Arrays.asList("your", "you are")); s.put("Insta", Arrays.asList("Instagram")); s.put("IO", Arrays.asList("I/O")); s.put("wierd", Arrays.asList("weird")); s.put("Wierd", Arrays.asList("Weird")); return s; } /** * @since 2.7 */ @Override protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException { if (word.length() < 20 && word.matches("[a-zA-Z-]+.?")) { List<String> prefixes = Arrays.asList("inter", "pre"); for (String prefix : prefixes) { if (word.startsWith(prefix)) { String lastPart = word.substring(prefix.length()); if (!isMisspelled(lastPart)) { // as these are only single words and both the first part and the last part are spelled correctly // (but the combination is not), it's okay to log the words from a privacy perspective: logger.info("UNKNOWN-EN: " + word); } } } } List<String> curatedSuggestions = new ArrayList<>(); curatedSuggestions.addAll(topSuggestions.getOrDefault(word, Collections.emptyList())); curatedSuggestions.addAll(topSuggestionsIgnoreCase.getOrDefault(word.toLowerCase(), Collections.emptyList())); if (!curatedSuggestions.isEmpty()) { return SuggestedReplacement.convert(curatedSuggestions); } else if (word.endsWith("ys")) { String suggestion = word.replaceFirst("ys$", "ies"); if (!speller1.isMisspelled(suggestion)) { return SuggestedReplacement.convert(Arrays.asList(suggestion)); } } return super.getAdditionalTopSuggestions(suggestions, word); } @Override protected Translator getTranslator(GlobalConfig globalConfig) { return translator; } private static class IrregularForms { final String baseform; final String posName; final String formName; final List<String> forms; private IrregularForms(String baseform, String posName, String formName, List<String> forms) { this.baseform = baseform; this.posName = posName; this.formName = formName; this.forms = forms; } } }
package org.languagetool.rules.en; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.language.English; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.en.translation.BeoLingusTranslator; import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule; import org.languagetool.rules.translation.Translator; import org.languagetool.synthesis.en.EnglishSynthesizer; import org.languagetool.tools.StringTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule { private static Logger logger = LoggerFactory.getLogger(AbstractEnglishSpellerRule.class); private static final EnglishSynthesizer synthesizer = new EnglishSynthesizer(new English()); private final BeoLingusTranslator translator; public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException { this(messages, language, null, Collections.emptyList()); } /** * @since 4.4 */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException { this(messages, language, null, userConfig, altLanguages, null, null); } protected static Map<String,String> loadWordlist(String path, int column) { if (column != 0 && column != 1) { throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column); } Map<String,String> words = new HashMap<>(); List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } String[] parts = line.split(";"); if (parts.length != 2) { throw new RuntimeException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'"); } words.put(parts[column].toLowerCase(), parts[column == 1 ? 0 : 1]); } return words; } /** * @since 4.5 * optional: language model for better suggestions */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, GlobalConfig globalConfig, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel, Language motherTongue) throws IOException { super(messages, language, globalConfig, userConfig, altLanguages, languageModel, motherTongue); super.ignoreWordsWithLength = 1; setCheckCompound(true); addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."), Example.fixed("This <marker>sentence</marker> contains a spelling mistake.")); String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt"); for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) { addIgnoreWords(ignoreWord); } translator = BeoLingusTranslator.getInstance(globalConfig); } @Override protected List<String> filterSuggestions(List<String> suggestions, AnalyzedSentence sentence, int i) { List<String> result = super.filterSuggestions(suggestions, sentence, i); List<String> clean = new ArrayList<>(); for (String suggestion : result) { if (!suggestion.matches(".* (s|t|d|ll|ve)")) { // e.g. 'timezones' suggests 'timezone s' clean.add(suggestion); } } return clean; } @Override protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException { List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens); if (ruleMatches.size() > 0) { // so 'word' is misspelled: IrregularForms forms = getIrregularFormsOrNull(word); if (forms != null) { String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) + "</suggestion>, the " + forms.formName + " form of the " + forms.posName + " '" + forms.baseform + "'?"; addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms); } else { VariantInfo variantInfo = isValidInOtherVariant(word); if (variantInfo != null) { String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + "."; String suggestion = StringTools.startsWithUppercase(word) ? StringTools.uppercaseFirstChar(variantInfo.otherVariant()) : variantInfo.otherVariant(); replaceFormsOfFirstMatch(message, sentence, ruleMatches, suggestion); } } } // filter "re ..." (#2562): for (RuleMatch ruleMatch : ruleMatches) { List<SuggestedReplacement> cleaned = ruleMatch.getSuggestedReplacementObjects().stream() .filter(k -> !k.getReplacement().startsWith("re ") && !k.getReplacement().startsWith("en ") && !k.getReplacement().startsWith("inter ") && !k.getReplacement().endsWith(" able") && !k.getReplacement().endsWith(" ed")) .collect(Collectors.toList()); ruleMatch.setSuggestedReplacementObjects(cleaned); } return ruleMatches; } /** * @since 4.5 */ @Nullable protected VariantInfo isValidInOtherVariant(String word) { return null; } private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); List<String> allSuggestions = new ArrayList<>(forms); for (String repl : oldMatch.getSuggestedReplacements()) { if (!allSuggestions.contains(repl)) { allSuggestions.add(repl); } } newMatch.setSuggestedReplacements(allSuggestions); ruleMatches.set(0, newMatch); } private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); SuggestedReplacement sugg = new SuggestedReplacement(suggestion); sugg.setShortDescription(language.getName()); newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg)); ruleMatches.set(0, newMatch); } @SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"}) @Nullable private IrregularForms getIrregularFormsOrNull(String word) { IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative"); return irregularFormsOrNull; } @Nullable private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) { try { for (String suffix : suffixes) { if (word.endsWith(wordSuffix)) { String baseForm = word.substring(0, word.length() - suffix.length()); String[] forms = synthesizer.synthesize(new AnalyzedToken(word, null, baseForm), posTag); List<String> result = new ArrayList<>(); for (String form : forms) { if (!speller1.isMisspelled(form)) { // only accept suggestions that the spellchecker will accept result.add(form); } } // the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'), // but we trust the spell checker in this case: result.remove(word); result.remove("badder"); // non-standard usage result.remove("baddest"); // non-standard usage result.remove("spake"); // can be removed after dict update if (result.size() > 0) { return new IrregularForms(baseForm, posName, formName, result); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } } /** * @since 2.7 */ @Override protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException { if (word.length() < 20 && word.matches("[a-zA-Z-]+.?")) { List<String> prefixes = Arrays.asList("inter", "pre"); for (String prefix : prefixes) { if (word.startsWith(prefix)) { String lastPart = word.substring(prefix.length()); if (!isMisspelled(lastPart)) { // as these are only single words and both the first part and the last part are spelled correctly // (but the combination is not), it's okay to log the words from a privacy perspective: logger.info("UNKNOWN-EN: " + word); } } } } if ("Alot".equals(word)) { return Arrays.asList("A lot"); } else if ("alot".equals(word)) { return Arrays.asList("a lot"); } else if ("css".equals(word)) { return Arrays.asList("CSS"); } else if ("endevours".equals(word)) { return Arrays.asList("endeavours"); } else if ("endevors".equals(word)) { return Arrays.asList("endeavors"); } else if ("endevour".equals(word)) { return Arrays.asList("endeavour"); } else if ("endevor".equals(word)) { return Arrays.asList("endeavor"); } else if ("ad-hoc".equals(word) || "adhoc".equals(word)) { return Arrays.asList("ad hoc"); } else if ("Ad-hoc".equals(word) || "Adhoc".equals(word)) { return Arrays.asList("Ad hoc"); } else if ("ad-on".equals(word) || "add-o".equals(word)) { return Arrays.asList("add-on"); } else if ("acc".equals(word)) { return Arrays.asList("account", "accusative"); } else if ("Acc".equals(word)) { return Arrays.asList("Account", "Accusative"); } else if ("ºC".equals(word)) { return Arrays.asList("°C"); } else if ("jus".equals(word)) { return Arrays.asList("just", "juice"); } else if ("Jus".equals(word)) { return Arrays.asList("Just", "Juice"); } else if ("sayed".equals(word)) { return Arrays.asList("said"); } else if ("sess".equals(word)) { return Arrays.asList("says", "session", "cess"); } else if ("Addon".equals(word)) { return Arrays.asList("Add-on"); } else if ("Addons".equals(word)) { return Arrays.asList("Add-ons"); } else if ("ios".equals(word)) { return Arrays.asList("iOS"); } else if ("yrs".equals(word)) { return Arrays.asList("years"); } else if ("standup".equals(word)) { return Arrays.asList("stand-up"); } else if ("standups".equals(word)) { return Arrays.asList("stand-ups"); } else if ("Standup".equals(word)) { return Arrays.asList("Stand-up"); } else if ("Standups".equals(word)) { return Arrays.asList("Stand-ups"); } else if ("Playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("biggy".equals(word)) { return Arrays.asList("biggie"); } else if ("lieing".equals(word)) { return Arrays.asList("lying"); } else if ("preffered".equals(word)) { return Arrays.asList("preferred"); } else if ("preffering".equals(word)) { return Arrays.asList("preferring"); } else if ("reffered".equals(word)) { return Arrays.asList("referred"); } else if ("reffering".equals(word)) { return Arrays.asList("referring"); } else if ("passthrough".equals(word)) { return Arrays.asList("pass-through"); } else if ("&&".equals(word)) { return Arrays.asList("&"); } else if ("cmon".equals(word)) { return Arrays.asList("c'mon"); } else if ("Cmon".equals(word)) { return Arrays.asList("C'mon"); } else if ("da".equals(word)) { return Arrays.asList("the"); } else if ("Da".equals(word)) { return Arrays.asList("The"); } else if ("Vue".equals(word)) { return Arrays.asList("Vue.JS"); } else if ("errornous".equals(word)) { return Arrays.asList("erroneous"); } else if ("brang".equals(word) || "brung".equals(word)) { return Arrays.asList("brought"); } else if ("thru".equals(word)) { return Arrays.asList("through"); } else if ("pitty".equals(word)) { return Arrays.asList("pity"); } else if ("speach".equals(word)) { // the replacement pairs would prefer "speak" return Arrays.asList("speech"); } else if ("icecreem".equals(word)) { return Arrays.asList("ice cream"); } else if ("math".equals(word)) { // in en-gb it's 'maths' return Arrays.asList("maths"); } else if ("fora".equals(word)) { return Arrays.asList("for a"); } else if ("lotsa".equals(word)) { return Arrays.asList("lots of"); } else if ("tryna".equals(word)) { return Arrays.asList("trying to"); } else if ("coulda".equals(word)) { return Arrays.asList("could have"); } else if ("shoulda".equals(word)) { return Arrays.asList("should have"); } else if ("woulda".equals(word)) { return Arrays.asList("would have"); } else if ("tellem".equals(word)) { return Arrays.asList("tell them"); } else if ("Tellem".equals(word)) { return Arrays.asList("Tell them"); } else if ("afro-american".equalsIgnoreCase(word)) { return Arrays.asList("Afro-American"); } else if ("Oconnor".equalsIgnoreCase(word)) { return Arrays.asList("O'Connor"); } else if ("Oconor".equalsIgnoreCase(word)) { return Arrays.asList("O'Conor"); } else if ("Obrien".equalsIgnoreCase(word)) { return Arrays.asList("O'Brien"); } else if ("Odonnell".equalsIgnoreCase(word)) { return Arrays.asList("O'Donnell"); } else if ("Oneill".equalsIgnoreCase(word)) { return Arrays.asList("O'Neill"); } else if ("Oneil".equalsIgnoreCase(word)) { return Arrays.asList("O'Neil"); } else if ("Oconnell".equalsIgnoreCase(word)) { return Arrays.asList("O'Connell"); } else if ("Webex".equals(word)) { return Arrays.asList("WebEx"); } else if ("didint".equals(word)) { return Arrays.asList("didn't"); } else if ("Didint".equals(word)) { return Arrays.asList("Didn't"); } else if ("wasint".equals(word)) { return Arrays.asList("wasn't"); } else if ("hasint".equals(word)) { return Arrays.asList("hasn't"); } else if ("doesint".equals(word)) { return Arrays.asList("doesn't"); } else if ("ist".equals(word)) { return Arrays.asList("is"); } else if ("Boing".equals(word)) { return Arrays.asList("Boeing"); } else if ("te".equals(word)) { return Arrays.asList("the"); } else if ("todays".equals(word)) { return Arrays.asList("today's"); } else if ("Todays".equals(word)) { return Arrays.asList("Today's"); } else if ("todo".equals(word)) { return Arrays.asList("to-do", "to do"); } else if ("todos".equals(word)) { return Arrays.asList("to-dos", "to do"); } else if ("Todo".equalsIgnoreCase(word)) { return Arrays.asList("To-do", "To do"); } else if ("Todos".equalsIgnoreCase(word)) { return Arrays.asList("To-dos"); } else if ("heres".equals(word)) { return Arrays.asList("here's"); } else if ("Heres".equals(word)) { return Arrays.asList("Here's"); } else if ("aways".equals(word)) { return Arrays.asList("always"); } else if ("McDonalds".equals(word)) { return Arrays.asList("McDonald's"); } else if ("ux".equals(word)) { return Arrays.asList("UX"); } else if ("ive".equals(word)) { return Arrays.asList("I've"); } else if ("infos".equals(word)) { return Arrays.asList("informations"); } else if ("Infos".equals(word)) { return Arrays.asList("Informations"); } else if ("prios".equals(word)) { return Arrays.asList("priorities"); } else if ("Prio".equals(word)) { return Arrays.asList("Priority"); } else if ("prio".equals(word)) { return Arrays.asList("Priority"); } else if ("Ecommerce".equals(word)) { return Arrays.asList("E-Commerce"); } else if ("ecommerce".equalsIgnoreCase(word)) { return Arrays.asList("e-commerce"); } else if ("elearning".equalsIgnoreCase(word)) { return Arrays.asList("e-learning"); } else if ("ebook".equals(word)) { return Arrays.asList("e-book"); } else if ("ebooks".equals(word)) { return Arrays.asList("e-books"); } else if ("eBook".equals(word)) { return Arrays.asList("e-book"); } else if ("eBooks".equals(word)) { return Arrays.asList("e-books"); } else if ("Ebook".equals(word)) { return Arrays.asList("E-Book"); } else if ("Ebooks".equals(word)) { return Arrays.asList("E-Books"); } else if ("Esport".equals(word)) { return Arrays.asList("E-Sport"); } else if ("Esports".equals(word)) { return Arrays.asList("E-Sports"); } else if ("esport".equalsIgnoreCase(word)) { return Arrays.asList("e-sport"); } else if ("esports".equalsIgnoreCase(word)) { return Arrays.asList("e-sports"); } else if ("R&B".equals(word)) { return Arrays.asList("R & B", "R 'n' B"); } else if ("ie".equals(word)) { return Arrays.asList("i.e."); } else if ("eg".equals(word)) { return Arrays.asList("e.g."); } else if ("ppl".equals(word)) { return Arrays.asList("people"); } else if ("kiddin".equals(word)) { return Arrays.asList("kidding"); } else if ("doin".equals(word)) { return Arrays.asList("doing"); } else if ("nothin".equals(word)) { return Arrays.asList("nothing"); } else if ("Thx".equals(word)) { return Arrays.asList("Thanks"); } else if ("thx".equals(word)) { return Arrays.asList("thanks"); } else if ("ty".equals(word)) { return Arrays.asList("thank you", "thanks"); } else if ("Sry".equals(word)) { return Arrays.asList("Sorry"); } else if ("sry".equals(word)) { return Arrays.asList("sorry"); } else if ("im".equals(word)) { return Arrays.asList("I'm"); } else if ("spoilt".equals(word)) { return Arrays.asList("spoiled"); } else if ("Lil".equals(word)) { return Arrays.asList("Little"); } else if ("lil".equals(word)) { return Arrays.asList("little"); } else if ("gmail".equals(word) || "g-mail".equalsIgnoreCase(word)) { return Arrays.asList("Gmail"); } else if ("Sucka".equals(word)) { return Arrays.asList("Sucker"); } else if ("sucka".equals(word)) { return Arrays.asList("sucker"); } else if ("whaddya".equals(word)) { return Arrays.asList("what are you", "what do you"); } else if ("Whaddya".equals(word)) { return Arrays.asList("What are you", "What do you"); } else if ("sinc".equals(word)) { return Arrays.asList("sync"); } else if ("sweety".equals(word)) { return Arrays.asList("sweetie"); } else if ("sweetys".equals(word)) { return Arrays.asList("sweeties"); } else if ("Hongkong".equals(word)) { return Arrays.asList("Hong Kong"); } else if ("Playstation".equalsIgnoreCase(word)) { return Arrays.asList("PlayStation"); } else if ("center".equals(word)) { // For non-US English return Arrays.asList("centre"); } else if ("ur".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ur".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("ure".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ure".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("mins".equals(word)) { return Arrays.asList("minutes", "min"); } else if ("addon".equals(word)) { return Arrays.asList("add-on"); } else if ("addons".equals(word)) { return Arrays.asList("add-ons"); } else if ("afterparty".equals(word)) { return Arrays.asList("after-party"); } else if ("Afterparty".equals(word)) { return Arrays.asList("After-party"); } else if ("wellbeing".equals(word)) { return Arrays.asList("well-being"); } else if ("cuz".equals(word) || "coz".equals(word)) { return Arrays.asList("because"); } else if ("pls".equals(word)) { return Arrays.asList("please"); } else if ("Pls".equals(word)) { return Arrays.asList("Please"); } else if ("plz".equals(word)) { return Arrays.asList("please"); } else if ("Plz".equals(word)) { return Arrays.asList("Please"); // AtD irregular plurals - START } else if ("addendums".equals(word)) { return Arrays.asList("addenda"); } else if ("algas".equals(word)) { return Arrays.asList("algae"); } else if ("alumnas".equals(word)) { return Arrays.asList("alumnae"); } else if ("alumnuses".equals(word)) { return Arrays.asList("alumni"); } else if ("analysises".equals(word)) { return Arrays.asList("analyses"); } else if ("appendixs".equals(word)) { return Arrays.asList("appendices"); } else if ("axises".equals(word)) { return Arrays.asList("axes"); } else if ("bacilluses".equals(word)) { return Arrays.asList("bacilli"); } else if ("bacteriums".equals(word)) { return Arrays.asList("bacteria"); } else if ("basises".equals(word)) { return Arrays.asList("bases"); } else if ("beaus".equals(word)) { return Arrays.asList("beaux"); } else if ("bisons".equals(word)) { return Arrays.asList("bison"); } else if ("buffalos".equals(word)) { return Arrays.asList("buffaloes"); } else if ("calfs".equals(word)) { return Arrays.asList("calves"); } else if ("childs".equals(word)) { return Arrays.asList("children"); } else if ("crisises".equals(word)) { return Arrays.asList("crises"); } else if ("criterions".equals(word)) { return Arrays.asList("criteria"); } else if ("curriculums".equals(word)) { return Arrays.asList("curricula"); } else if ("datums".equals(word)) { return Arrays.asList("data"); } else if ("deers".equals(word)) { return Arrays.asList("deer"); } else if ("diagnosises".equals(word)) { return Arrays.asList("diagnoses"); } else if ("echos".equals(word)) { return Arrays.asList("echoes"); } else if ("elfs".equals(word)) { return Arrays.asList("elves"); } else if ("ellipsises".equals(word)) { return Arrays.asList("ellipses"); } else if ("embargos".equals(word)) { return Arrays.asList("embargoes"); } else if ("erratums".equals(word)) { return Arrays.asList("errata"); } else if ("firemans".equals(word)) { return Arrays.asList("firemen"); } else if ("fishs".equals(word)) { return Arrays.asList("fishes", "fish"); } else if ("genuses".equals(word)) { return Arrays.asList("genera"); } else if ("gooses".equals(word)) { return Arrays.asList("geese"); } else if ("halfs".equals(word)) { return Arrays.asList("halves"); } else if ("heros".equals(word)) { return Arrays.asList("heroes"); } else if ("indexs".equals(word)) { return Arrays.asList("indices", "indexes"); } else if ("lifes".equals(word)) { return Arrays.asList("lives"); } else if ("mans".equals(word)) { return Arrays.asList("men"); } else if ("matrixs".equals(word)) { return Arrays.asList("matrices"); } else if ("meanses".equals(word)) { return Arrays.asList("means"); } else if ("mediums".equals(word)) { return Arrays.asList("media"); } else if ("memorandums".equals(word)) { return Arrays.asList("memoranda"); } else if ("mooses".equals(word)) { return Arrays.asList("moose"); } else if ("mosquitos".equals(word)) { return Arrays.asList("mosquitoes"); } else if ("neurosises".equals(word)) { return Arrays.asList("neuroses"); } else if ("nucleuses".equals(word)) { return Arrays.asList("nuclei"); } else if ("oasises".equals(word)) { return Arrays.asList("oases"); } else if ("ovums".equals(word)) { return Arrays.asList("ova"); } else if ("oxs".equals(word)) { return Arrays.asList("oxen"); } else if ("oxes".equals(word)) { return Arrays.asList("oxen"); } else if ("paralysises".equals(word)) { return Arrays.asList("paralyses"); } else if ("potatos".equals(word)) { return Arrays.asList("potatoes"); } else if ("radiuses".equals(word)) { return Arrays.asList("radii"); } else if ("selfs".equals(word)) { return Arrays.asList("selves"); } else if ("serieses".equals(word)) { return Arrays.asList("series"); } else if ("sheeps".equals(word)) { return Arrays.asList("sheep"); } else if ("shelfs".equals(word)) { return Arrays.asList("shelves"); } else if ("scissorses".equals(word)) { return Arrays.asList("scissors"); } else if ("specieses".equals(word)) { return Arrays.asList("species"); } else if ("stimuluses".equals(word)) { return Arrays.asList("stimuli"); } else if ("stratums".equals(word)) { return Arrays.asList("strata"); } else if ("tableaus".equals(word)) { return Arrays.asList("tableaux"); } else if ("thats".equals(word)) { return Arrays.asList("those"); } else if ("thesises".equals(word)) { return Arrays.asList("theses"); } else if ("thiefs".equals(word)) { return Arrays.asList("thieves"); } else if ("thises".equals(word)) { return Arrays.asList("these"); } else if ("tomatos".equals(word)) { return Arrays.asList("tomatoes"); } else if ("tooths".equals(word)) { return Arrays.asList("teeth"); } else if ("torpedos".equals(word)) { return Arrays.asList("torpedoes"); } else if ("vertebras".equals(word)) { return Arrays.asList("vertebrae"); } else if ("vetos".equals(word)) { return Arrays.asList("vetoes"); } else if ("vitas".equals(word)) { return Arrays.asList("vitae"); } else if ("watchs".equals(word)) { return Arrays.asList("watches"); } else if ("wifes".equals(word)) { return Arrays.asList("wives"); } else if ("womans".equals(word)) { return Arrays.asList("women"); // AtD irregular plurals - END } else if ("tippy-top".equals(word) || "tippytop".equals(word)) { // "tippy-top" is an often used word by Donald Trump return Arrays.asList("tip-top", "top most"); } else if ("imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("Imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("tobe".equals(word)) { return Arrays.asList("to be"); } else if ("Gi".equals(word) || "Ji".equals(word)) { return Arrays.asList("Hi"); } else if ("Dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("greatfruit".equals(word)) { return Arrays.asList("grapefruit", "great fruit"); } else if (word.endsWith("ys")) { String suggestion = word.replaceFirst("ys$", "ies"); if (!speller1.isMisspelled(suggestion)) { return Arrays.asList(suggestion); } } return super.getAdditionalTopSuggestions(suggestions, word); } @Override protected Translator getTranslator(GlobalConfig globalConfig) { return translator; } private static class IrregularForms { final String baseform; final String posName; final String formName; final List<String> forms; private IrregularForms(String baseform, String posName, String formName, List<String> forms) { this.baseform = baseform; this.posName = posName; this.formName = formName; this.forms = forms; } } }
package org.xcolab.service.admin.web; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.TestPropertySource; 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.setup.MockMvcBuilders; import org.xcolab.model.tables.pojos.ConfigurationAttribute; import org.xcolab.service.admin.AdminTestUtils; import org.xcolab.service.admin.domain.configurationattribute.ConfigurationAttributeDao; import org.xcolab.service.admin.pojo.Notification; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Optional; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.atLeast; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 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(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) @WebMvcTest(AdminController.class) @ComponentScan("org.xcolab.service.admin") @ComponentScan("com.netflix.discovery") @TestPropertySource( properties = { "cache.enabled=false", "eureka.client.enabled=false" } ) @WebAppConfiguration public class AdminControllerTest { private MockMvc mockMvc; private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Mock private ConfigurationAttributeDao configurationAttributeDao; @InjectMocks private AdminController controller; @Autowired private ObjectMapper objectMapper; private HttpMessageConverter mappingJackson2HttpMessageConverter; @Before public void before(){ this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); Mockito.when(configurationAttributeDao.getConfigurationAttribute(anyString())) .thenAnswer(invocation -> { if("ACTIVE_THEMEZ".equals(invocation.getArguments()[0])){ return Optional.of(getConfigAttribute()); }else{ return Optional.empty(); } }); //.thenAnswer( Optional.of(getConfigAttribute())); Mockito.when(configurationAttributeDao.create(anyObject())) .thenAnswer(invocationOnMock -> getConfigAttribute()); } private ConfigurationAttribute getConfigAttribute(){ ConfigurationAttribute ca = AdminTestUtils.getConfigurationAttribute("a"); ca.setStringValue("CLIMATE_COLAB"); return ca; } @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.stream(converters) .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .findAny() .orElse(null); assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); } @Test public void shouldReturnConfigurationAttributeInGet() throws Exception { this.mockMvc.perform(get("/attributes/ACTIVE_THEMEZ").contentType(contentType).accept(contentType)) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.stringValue", is("CLIMATE_COLAB"))); } @Test public void shouldReturn404ForNotFoundConfigurationAttributeInGet() throws Exception { this.mockMvc.perform(get("/attributes/ACTIVE_THEME") .contentType(contentType).accept(contentType)) .andExpect(status().isNotFound()); } @Test public void shouldCreateNewConfigurationAttributeInPost() throws Exception { ConfigurationAttribute ca = getConfigAttribute(); this.mockMvc.perform( post("/attributes") .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(ca))) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)); Mockito.verify(configurationAttributeDao,atLeast(1)).create(anyObject()); } @Test public void shouldUpdateConfigurationAttributeInPut() throws Exception { ConfigurationAttribute ca = getConfigAttribute(); this.mockMvc.perform( put("/attributes/"+ca.getName()) .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(ca))) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)); Mockito.verify(configurationAttributeDao,atLeast(1)).update(anyObject()); } private Notification getNotification(Long id) { Notification notification = new Notification(); notification.setBeginTime(new Date()); Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 2); notification.setEndTime(cal.getTime()); notification.setNotificationId(id); notification.setNotificationText("Notification text"); return notification; } @Test public void shouldCreateAndDeleteNotificationInPost() throws Exception { //TODO: this test does a lot - not clear what it's testing Notification notification = getNotification(1L); this.mockMvc.perform( get("/notifications/") .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(notification))) .andExpect(status().isOk()) .andExpect(jsonPath("$").isArray()) .andExpect(content().contentType(contentType)); this.mockMvc.perform( post("/notifications/") .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(notification))) .andExpect(status().isOk()); this.mockMvc.perform( get("/notifications/") .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(notification))) .andExpect(status().isOk()) .andExpect(jsonPath("$").isArray()) .andExpect(content().contentType(contentType)); this.mockMvc.perform( delete("/notifications/" + notification.getNotificationId()) .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(notification))) .andExpect(status().isOk()); this.mockMvc.perform( get("/notifications/") .contentType(contentType).accept(contentType) .content(objectMapper.writeValueAsString(notification))) .andExpect(status().isOk()) .andExpect(jsonPath("$").isEmpty()) .andExpect(content().contentType(contentType)); } }
package org.navalplanner.web.limitingresources; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import org.apache.commons.lang.Validate; import org.hibernate.Hibernate; import org.hibernate.proxy.HibernateProxy; import org.joda.time.LocalDate; import org.navalplanner.business.calendars.entities.BaseCalendar; import org.navalplanner.business.calendars.entities.CalendarAvailability; import org.navalplanner.business.calendars.entities.CalendarData; import org.navalplanner.business.calendars.entities.CalendarException; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.orders.daos.IOrderElementDAO; import org.navalplanner.business.orders.entities.Order; import org.navalplanner.business.orders.entities.OrderElement; import org.navalplanner.business.planner.daos.IDependencyDAO; import org.navalplanner.business.planner.daos.ITaskElementDAO; import org.navalplanner.business.planner.entities.DayAssignment; import org.navalplanner.business.planner.entities.Dependency; import org.navalplanner.business.planner.entities.GenericResourceAllocation; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.TaskElement; import org.navalplanner.business.planner.limiting.daos.ILimitingResourceQueueDAO; import org.navalplanner.business.planner.limiting.daos.ILimitingResourceQueueDependencyDAO; import org.navalplanner.business.planner.limiting.daos.ILimitingResourceQueueElementDAO; import org.navalplanner.business.planner.limiting.entities.AllocationAttempt; import org.navalplanner.business.planner.limiting.entities.DateAndHour; import org.navalplanner.business.planner.limiting.entities.Gap; import org.navalplanner.business.planner.limiting.entities.InsertionRequirements; import org.navalplanner.business.planner.limiting.entities.LimitingResourceAllocator; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueDependency; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueElement; import org.navalplanner.business.planner.limiting.entities.Gap.GapOnQueue; import org.navalplanner.business.resources.entities.Criterion; import org.navalplanner.business.resources.entities.CriterionSatisfaction; import org.navalplanner.business.resources.entities.LimitingResourceQueue; import org.navalplanner.business.resources.entities.Resource; import org.navalplanner.business.scenarios.bootstrap.PredefinedScenarios; import org.navalplanner.business.scenarios.entities.Scenario; import org.navalplanner.business.users.daos.IOrderAuthorizationDAO; import org.navalplanner.business.users.daos.IUserDAO; import org.navalplanner.business.users.entities.OrderAuthorization; import org.navalplanner.business.users.entities.OrderAuthorizationType; import org.navalplanner.business.users.entities.User; import org.navalplanner.business.users.entities.UserRole; import org.navalplanner.web.planner.order.SaveCommand; import org.navalplanner.web.security.SecurityUtils; 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.springframework.transaction.annotation.Transactional; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.Interval; @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { @Autowired private IOrderElementDAO orderElementDAO; @Autowired private IUserDAO userDAO; @Autowired private IOrderAuthorizationDAO orderAuthorizationDAO; @Autowired private ILimitingResourceQueueElementDAO limitingResourceQueueElementDAO; @Autowired private ILimitingResourceQueueDAO limitingResourceQueueDAO; @Autowired private ITaskElementDAO taskDAO; @Autowired private ILimitingResourceQueueDependencyDAO limitingResourceQueueDependencyDAO; private QueuesState queuesState; private Interval viewInterval; private LimitingResourceQueueElement beingEdited; private Set<LimitingResourceQueueElement> toBeRemoved = new HashSet<LimitingResourceQueueElement>(); private Set<LimitingResourceQueueElement> toBeSaved = new HashSet<LimitingResourceQueueElement>(); private Scenario master; @Override @Transactional(readOnly = true) public void initGlobalView() { doGlobalView(); } private void doGlobalView() { master = PredefinedScenarios.MASTER.getScenario(); List<LimitingResourceQueueElement> unassigned = findUnassignedLimitingResourceQueueElements(); List<LimitingResourceQueue> queues = loadLimitingResourceQueues(); queuesState = new QueuesState(queues, unassigned); final Date startingDate = getEarliestDate(); Date endDate = (new LocalDate(startingDate)).plusYears(2) .toDateTimeAtCurrentTime().toDate(); viewInterval = new Interval(startingDate, endDate); Date currentDate = new Date(); viewInterval = new Interval( startingDate.after(currentDate) ? currentDate : startingDate, endDate); } private Date getEarliestDate() { final LimitingResourceQueueElement element = getEarliestQueueElement(); return (element != null) ? element.getStartDate() .toDateTimeAtCurrentTime().toDate() : new Date(); } private LimitingResourceQueueElement getEarliestQueueElement() { LimitingResourceQueueElement earliestQueueElement = null; for (LimitingResourceQueue each : queuesState.getQueues()) { LimitingResourceQueueElement element = getFirstLimitingResourceQueueElement(each); if (element == null) { continue; } if (earliestQueueElement == null || isEarlier(element, earliestQueueElement)) { earliestQueueElement = element; } } return earliestQueueElement; } private boolean isEarlier(LimitingResourceQueueElement arg1, LimitingResourceQueueElement arg2) { return (arg1.getStartDate().isBefore(arg2.getStartDate())); } private LimitingResourceQueueElement getFirstLimitingResourceQueueElement( LimitingResourceQueue queue) { return getFirstChild(queue.getLimitingResourceQueueElements()); } private LimitingResourceQueueElement getFirstChild( SortedSet<LimitingResourceQueueElement> elements) { return (elements.isEmpty()) ? null : elements.iterator().next(); } /** * Loads unassigned {@link LimitingResourceQueueElement} from DB * * @return */ private List<LimitingResourceQueueElement> findUnassignedLimitingResourceQueueElements() { return initializeLimitingResourceQueueElements(limitingResourceQueueElementDAO .getUnassigned()); } private List<LimitingResourceQueueElement> initializeLimitingResourceQueueElements( List<LimitingResourceQueueElement> elements) { for (LimitingResourceQueueElement each : elements) { initializeLimitingResourceQueueElement(each); } return elements; } private void initializeLimitingResourceQueueElement( LimitingResourceQueueElement element) { ResourceAllocation<?> resourceAllocation = element .getResourceAllocation(); resourceAllocation.switchToScenario(master); resourceAllocation = initializeResourceAllocationIfNecessary(resourceAllocation); element.setResourceAllocation(resourceAllocation); initializeTask(resourceAllocation.getTask()); initializeResourceIfAny(element.getResource()); } private void initializeTask(Task task) { Hibernate.initialize(task); for (ResourceAllocation<?> each: task.getAllResourceAllocations()) { Hibernate.initialize(each); } for (Dependency each: task.getDependenciesWithThisOrigin()) { Hibernate.initialize(each); } for (Dependency each: task.getDependenciesWithThisDestination()) { Hibernate.initialize(each); } initializeRootOrder(task); } // FIXME: Needed to fetch order.name in QueueComponent.composeTooltiptext. // Try to replace it with a HQL query instead of iterating all the way up // through order private void initializeRootOrder(Task task) { Hibernate.initialize(task.getOrderElement()); OrderElement order = task.getOrderElement(); do { Hibernate.initialize(order.getParent()); order = order.getParent(); } while (order.getParent() != null); } private void initializeCalendarIfAny(BaseCalendar calendar) { if (calendar != null) { Hibernate.initialize(calendar); initializeCalendarAvailabilities(calendar); initializeCalendarExceptions(calendar); initializeCalendarDataVersions(calendar); } } private void initializeCalendarAvailabilities(BaseCalendar calendar) { for (CalendarAvailability each : calendar.getCalendarAvailabilities()) { Hibernate.initialize(each); } } private void initializeCalendarExceptions(BaseCalendar calendar) { for (CalendarException each : calendar.getExceptions()) { Hibernate.initialize(each); Hibernate.initialize(each.getType()); } } private void initializeCalendarDataVersions(BaseCalendar calendar) { for (CalendarData each : calendar.getCalendarDataVersions()) { Hibernate.initialize(each); Hibernate.initialize(each.getHoursPerDay()); initializeCalendarIfAny(each.getParent()); } } private ResourceAllocation<?> initializeResourceAllocationIfNecessary( ResourceAllocation<?> resourceAllocation) { if (resourceAllocation instanceof HibernateProxy) { resourceAllocation = (ResourceAllocation<?>) ((HibernateProxy) resourceAllocation) .getHibernateLazyInitializer().getImplementation(); if (resourceAllocation instanceof GenericResourceAllocation) { GenericResourceAllocation generic = (GenericResourceAllocation) resourceAllocation; initializeCriteria(generic.getCriterions()); } Hibernate.initialize(resourceAllocation.getAssignments()); Hibernate.initialize(resourceAllocation.getLimitingResourceQueueElement()); } return resourceAllocation; } private void initializeCriteria(Set<Criterion> criteria) { for (Criterion each: criteria) { initializeCriterion(each); } } private void initializeCriterion(Criterion criterion) { Hibernate.initialize(criterion); Hibernate.initialize(criterion.getType()); } private List<LimitingResourceQueue> loadLimitingResourceQueues() { return initializeLimitingResourceQueues(limitingResourceQueueDAO .getAll()); } private List<LimitingResourceQueue> initializeLimitingResourceQueues( List<LimitingResourceQueue> queues) { for (LimitingResourceQueue each : queues) { initializeLimitingResourceQueue(each); } return queues; } private void initializeLimitingResourceQueue(LimitingResourceQueue queue) { initializeResourceIfAny(queue.getResource()); for (LimitingResourceQueueElement each : queue .getLimitingResourceQueueElements()) { initializeLimitingResourceQueueElement(each); } } private void initializeResourceIfAny(Resource resource) { if (resource != null) { Hibernate.initialize(resource); initializeCalendarIfAny(resource.getCalendar()); resource.getAssignments(); for (CriterionSatisfaction each : resource .getCriterionSatisfactions()) { Hibernate.initialize(each); initializeCriterion(each.getCriterion()); } } } @Override @Transactional(readOnly = true) public Order getOrderByTask(TaskElement task) { return orderElementDAO .loadOrderAvoidingProxyFor(task.getOrderElement()); } @Override public Interval getViewInterval() { return viewInterval; } @Override @Transactional(readOnly = true) public boolean userCanRead(Order order, String loginName) { if (SecurityUtils.isUserInRole(UserRole.ROLE_READ_ALL_ORDERS) || SecurityUtils.isUserInRole(UserRole.ROLE_EDIT_ALL_ORDERS)) { return true; } try { User user = userDAO.findByLoginName(loginName); for (OrderAuthorization authorization : orderAuthorizationDAO .listByOrderUserAndItsProfiles(order, user)) { if (authorization.getAuthorizationType() == OrderAuthorizationType.READ_AUTHORIZATION || authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION) { return true; } } } catch (InstanceNotFoundException e) { // this case shouldn't happen, because it would mean that there // isn't a logged user // anyway, if it happenned we don't allow the user to pass } return false; } @Override public List<LimitingResourceQueue> getLimitingResourceQueues() { return queuesState.getQueues(); } @Override public List<LimitingResourceQueueElement> getUnassignedLimitingResourceQueueElements() { return queuesState.getUnassigned(); } public ZoomLevel calculateInitialZoomLevel() { Interval interval = getViewInterval(); return ZoomLevel.getDefaultZoomByDates(new LocalDate(interval .getStart()), new LocalDate(interval.getFinish())); } @Override public List<LimitingResourceQueueElement> assignLimitingResourceQueueElement( LimitingResourceQueueElement externalQueueElement) { List<LimitingResourceQueueElement> result = new ArrayList<LimitingResourceQueueElement>(); for (LimitingResourceQueueElement each : queuesState .getInsertionsToBeDoneFor(externalQueueElement)) { InsertionRequirements requirements = queuesState.getRequirementsFor(each); boolean inserted = insertAtGap(requirements); if (!inserted) { break; } result.add(requirements.getElement()); } return result; } private boolean insertAtGap(InsertionRequirements requirements) { List<GapOnQueue> potentiallyValidGapsFor = queuesState .getPotentiallyValidGapsFor(requirements); boolean generic = requirements.getElement().isGeneric(); for (GapOnQueue each : potentiallyValidGapsFor) { for (GapOnQueue eachSubGap : getSubGaps(each, requirements .getElement(), generic)) { AllocationAttempt allocation = requirements .guessValidity(eachSubGap); if (allocation.isValid()) { doAllocation(requirements, allocation, eachSubGap.getOriginQueue()); return true; } } } return false; } private List<GapOnQueue> getSubGaps(GapOnQueue each, LimitingResourceQueueElement element, boolean generic) { if (generic) { return each.splitIntoGapsSatisfyingCriteria(element.getCriteria()); } return Collections.singletonList(each); } private void doAllocation(InsertionRequirements requirements, AllocationAttempt allocation, LimitingResourceQueue queue) { Resource resource = queue.getResource(); ResourceAllocation<?> resourceAllocation = requirements .getElement().getResourceAllocation(); List<DayAssignment> assignments = allocation .getAssignmentsFor(resourceAllocation, resource); resourceAllocation .allocateLimitingDayAssignments(assignments); updateStartAndEndTimes(requirements.getElement(), allocation.getStartInclusive(), allocation .getEndExclusive()); addLimitingResourceQueueElement(queue, requirements .getElement()); markAsModified(requirements.getElement()); } private DateAndHour getEndsAfterBecauseOfGantt( LimitingResourceQueueElement queueElement) { return DateAndHour.from(LocalDate.fromDateFields(queueElement .getEarliestEndDateBecauseOfGantt())); } private boolean assignLimitingResourceQueueElementToQueueAt( LimitingResourceQueueElement element, LimitingResourceQueue queue, DateAndHour startTime, DateAndHour endsAfter) { // Allocate day assignments and adjust start and end times for element List<DayAssignment> dayAssignments = LimitingResourceAllocator .generateDayAssignments(element.getResourceAllocation(), queue .getResource(), startTime, endsAfter); element.getResourceAllocation().allocateLimitingDayAssignments( dayAssignments); DateAndHour endTime = LimitingResourceAllocator .getLastElementTime(dayAssignments); // the assignments can be generated after the required start startTime = DateAndHour.Max(startTime, startFor(dayAssignments)); if (sameDay(startTime, endTime)) { endTime = new DateAndHour(endTime.getDate(), startTime.getHour() + endTime.getHour()); } updateStartAndEndTimes(element, startTime, endTime); // Add element to queue addLimitingResourceQueueElement(queue, element); markAsModified(element); return true; } private DateAndHour startFor(List<DayAssignment> dayAssignments) { return new DateAndHour(dayAssignments .get(0).getDay(), 0); } private boolean sameDay(DateAndHour startTime, DateAndHour endTime) { return startTime.getDate().equals(endTime.getDate()); } private void markAsModified(LimitingResourceQueueElement element) { if (!toBeSaved.contains(element)) { toBeSaved.add(element); } } public Gap createGap(Resource resource, DateAndHour startTime, DateAndHour endTime) { return Gap.create(resource, startTime, endTime); } private void updateStartAndEndTimes(LimitingResourceQueueElement element, DateAndHour startTime, DateAndHour endTime) { element.setStartDate(startTime.getDate()); element.setStartHour(startTime.getHour()); element.setEndDate(endTime.getDate()); element.setEndHour(endTime.getHour()); // Update starting and ending dates for associated Task Task task = element.getResourceAllocation().getTask(); updateStartingAndEndingDate(task, startTime.getDate(), endTime .getDate()); } private void updateStartingAndEndingDate(Task task, LocalDate startDate, LocalDate endDate) { task.setStartDate(toDate(startDate)); task.setEndDate(endDate.toDateTimeAtStartOfDay().toDate()); task.explicityMoved(toDate(startDate)); } private Date toDate(LocalDate date) { return date.toDateTimeAtStartOfDay().toDate(); } private void addLimitingResourceQueueElement(LimitingResourceQueue queue, LimitingResourceQueueElement element) { queuesState.assignedToQueue(element, queue); } @Override @Transactional public void confirm() { applyChanges(); } private void applyChanges() { removeQueueElements(); saveQueueElements(); } private void saveQueueElements() { for (LimitingResourceQueueElement each: toBeSaved) { if (each != null) { saveQueueElement(each); } } SaveCommand.dontPoseAsTransientAndChildrenObjects(getAllocations(toBeSaved)); toBeSaved.clear(); } private List<ResourceAllocation<?>> getAllocations( Collection<? extends LimitingResourceQueueElement> elements) { List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); for (LimitingResourceQueueElement each : elements) { if (each.getResourceAllocation() != null) { result.add(each.getResourceAllocation()); } } return result; } private void saveQueueElement(LimitingResourceQueueElement element) { limitingResourceQueueElementDAO.save(element); taskDAO.save(getAssociatedTask(element)); } private Task getAssociatedTask(LimitingResourceQueueElement element) { return element.getResourceAllocation().getTask(); } private void removeQueueElements() { for (LimitingResourceQueueElement each: toBeRemoved) { removeQueueElement(each); } toBeRemoved.clear(); } private void removeQueueElement(LimitingResourceQueueElement element) { Task task = getAssociatedTask(element); removeQueueDependenciesIfAny(task); removeQueueElementById(element.getId()); } private void removeQueueElementById(Long id) { try { limitingResourceQueueElementDAO.remove(id); } catch (InstanceNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Trying to remove non-existing entity"); } } private void removeQueueDependenciesIfAny(Task task) { for (Dependency each: task.getDependenciesWithThisOrigin()) { removeQueueDependencyIfAny(each); } for (Dependency each: task.getDependenciesWithThisDestination()) { removeQueueDependencyIfAny(each); } } private void removeQueueDependencyIfAny(Dependency dependency) { LimitingResourceQueueDependency queueDependency = dependency.getQueueDependency(); if (queueDependency != null) { queueDependency.getHasAsOrigin().remove(queueDependency); queueDependency.getHasAsDestiny().remove(queueDependency); dependency.setQueueDependency(null); dependencyDAO.save(dependency); removeQueueDependencyById(queueDependency.getId()); } } @Autowired private IDependencyDAO dependencyDAO; private void removeQueueDependencyById(Long id) { try { limitingResourceQueueDependencyDAO.remove(id); } catch (InstanceNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Trying to remove non-existing entity"); } } /** * Unschedules an element from the list of queue elements. The element is * later added to the list of unassigned elements */ @Override public void unschedule(LimitingResourceQueueElement queueElement) { queuesState.unassingFromQueue(queueElement); markAsModified(queueElement); } /** * Removes an {@link LimitingResourceQueueElement} from the list of * unassigned elements * */ @Override public void removeUnassignedLimitingResourceQueueElement( LimitingResourceQueueElement element) { LimitingResourceQueueElement queueElement = queuesState.getEquivalent(element); queueElement.getResourceAllocation().setLimitingResourceQueueElement(null); queueElement.getResourceAllocation().getTask() .removeAllResourceAllocations(); queuesState.removeUnassigned(queueElement); markAsRemoved(queueElement); } private void markAsRemoved(LimitingResourceQueueElement element) { if (toBeSaved.contains(element)) { toBeSaved.remove(element); } if (!toBeRemoved.contains(element)) { toBeRemoved.add(element); } } @Override public List<LimitingResourceQueue> getAssignableQueues( LimitingResourceQueueElement element) { return queuesState.getAssignableQueues(element); } @Override public boolean nonAppropriativeAllocation( LimitingResourceQueueElement element, LimitingResourceQueue queue, DateAndHour startTime) { Validate.notNull(element); Validate.notNull(queue); Validate.notNull(startTime); if (element.getLimitingResourceQueue() != null) { unschedule(element); } return assignLimitingResourceQueueElementToQueueAt(element, queue, startTime, getEndsAfterBecauseOfGantt(element)); } @Override public void init(LimitingResourceQueueElement element) { beingEdited = queuesState.getEquivalent(element); } @Override public LimitingResourceQueueElement getLimitingResourceQueueElement() { return beingEdited; } @Override public void appropriativeAllocation(LimitingResourceQueueElement _element, LimitingResourceQueue _queue, DateAndHour allocationTime) { LimitingResourceQueue queue = queuesState.getEquivalent(_queue); LimitingResourceQueueElement element = queuesState.getEquivalent(_element); if (element.getLimitingResourceQueue() != null) { unschedule(element); } List<LimitingResourceQueueElement> unscheduledElements = new ArrayList<LimitingResourceQueueElement>(); Gap gap; do { gap = LimitingResourceAllocator.getFirstValidGapSince(element, queue, allocationTime); if (gap != null) { final LocalDate startDate = gap.getStartTime().getDate(); if (startDate.equals(allocationTime.getDate())) { assignLimitingResourceQueueElementToQueueAt(element, queue, allocationTime, getEndsAfterBecauseOfGantt(element)); break; } else { LimitingResourceQueueElement elementAtTime = getFirstElementFrom( queue, allocationTime); if (elementAtTime != null) { unschedule(elementAtTime); unscheduledElements.add(elementAtTime); } } } } while (gap != null); for (LimitingResourceQueueElement each: unscheduledElements) { gap = LimitingResourceAllocator.getFirstValidGap(queue, each); assignLimitingResourceQueueElementToQueueAt(each, queue, gap .getStartTime(), getEndsAfterBecauseOfGantt(element)); } } @SuppressWarnings("unchecked") public LimitingResourceQueueElement getFirstElementFrom(LimitingResourceQueue queue, DateAndHour allocationTime) { final List<LimitingResourceQueueElement> elements = new ArrayList(queue.getLimitingResourceQueueElements()); // First element final LimitingResourceQueueElement first = elements.get(0); if (isAfter(first, allocationTime)) { return first; } // Rest of elements for (int i = 0; i < elements.size(); i++) { final LimitingResourceQueueElement each = elements.get(i); if (isInTheMiddle(each, allocationTime) || isAfter(each, allocationTime)) { return each; } } return null; } private boolean isAfter(LimitingResourceQueueElement element, DateAndHour time) { return element.getStartTime().isAfter(time); } private boolean isInTheMiddle(LimitingResourceQueueElement element, DateAndHour time) { return (element.getStartTime().isBefore(time) || element.getStartTime().isEquals(time)) && (element.getEndTime().isAfter(time) || element.getEndTime().isEquals(time)); } }
package org.gbif.occurrence.search.heatmap.es; import com.google.inject.Inject; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter; import org.elasticsearch.search.aggregations.bucket.geogrid.ParsedGeoHashGrid; import org.elasticsearch.search.aggregations.metrics.geobounds.ParsedGeoBounds; import org.gbif.occurrence.search.SearchException; import org.gbif.occurrence.search.heatmap.OccurrenceHeatmapRequest; import org.gbif.occurrence.search.heatmap.OccurrenceHeatmapService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static org.gbif.occurrence.search.es.EsQueryUtils.HEADERS; import static org.gbif.occurrence.search.heatmap.es.EsHeatmapRequestBuilder.*; public class OccurrenceHeatmapsEsService implements OccurrenceHeatmapService<EsOccurrenceHeatmapResponse> { private static final Logger LOG = LoggerFactory.getLogger(OccurrenceHeatmapsEsService.class); private final RestHighLevelClient esClient; private final String esIndex; @Inject public OccurrenceHeatmapsEsService(RestHighLevelClient esClient, String esIndex) { this.esIndex = esIndex; this.esClient = esClient; } @Override public EsOccurrenceHeatmapResponse searchHeatMap(@Nullable OccurrenceHeatmapRequest request) { Objects.requireNonNull(request); // build request SearchRequest searchRequest = EsHeatmapRequestBuilder.buildRequest(request, esIndex); LOG.debug("ES query: {}", searchRequest); // perform search SearchResponse response = null; try { response = esClient.search(searchRequest, HEADERS.get()); } catch (IOException e) { LOG.error("Error executing the search operation", e); throw new SearchException(e); } // parse response return parseResponse(response); } private static EsOccurrenceHeatmapResponse parseResponse(SearchResponse response) { ParsedFilter boxAggs = response.getAggregations().get(BOX_AGGS); ParsedGeoHashGrid heatmapAggs = boxAggs.getAggregations().get(HEATMAP_AGGS); List<EsOccurrenceHeatmapResponse.GeoGridBucket> buckets = heatmapAggs .getBuckets() .stream() .map( b -> { // build bucket EsOccurrenceHeatmapResponse.GeoGridBucket bucket = new EsOccurrenceHeatmapResponse.GeoGridBucket(); bucket.setKey(b.getKeyAsString()); bucket.setDocCount((int) b.getDocCount()); // build bounds EsOccurrenceHeatmapResponse.Bounds bounds = new EsOccurrenceHeatmapResponse.Bounds(); ParsedGeoBounds cellAggs = b.getAggregations().get(CELL_AGGS); // topLeft EsOccurrenceHeatmapResponse.Coordinate topLeft = new EsOccurrenceHeatmapResponse.Coordinate(); topLeft.setLat(cellAggs.topLeft().getLat()); topLeft.setLon(cellAggs.topLeft().getLon()); bounds.setTopLeft(topLeft); // bottomRight EsOccurrenceHeatmapResponse.Coordinate bottomRight = new EsOccurrenceHeatmapResponse.Coordinate(); bottomRight.setLat(cellAggs.bottomRight().getLat()); bottomRight.setLon(cellAggs.bottomRight().getLon()); bounds.setBottomRight(bottomRight); // build cell EsOccurrenceHeatmapResponse.Cell cell = new EsOccurrenceHeatmapResponse.Cell(); cell.setBounds(bounds); bucket.setCell(cell); return bucket; }) .collect(Collectors.toList()); // build result EsOccurrenceHeatmapResponse result = new EsOccurrenceHeatmapResponse(); result.setBuckets(buckets); return result; } }
package KataProgramming; public class ResizingArrayStackOfString { String [] s; int N = 0; public ResizingArrayStackOfString() { s = new String[1]; } public void push(String item){ if(N == s.length) resize(2 * s.length); s[N++] = item; } private void resize(int i) { String[] copy = new String[i]; for (int j = 0; j < N; j++) { copy[j] = s[j]; } s = copy; } public String pop() { String item = s[--N]; s[N] = null; if(N > 0 && N == s.length / 4) resize(s.length/2); // diviser le tableau a 1/2 une fois il est rempli a 1/4 return item; } }
package net.kevxu.purdueassist.course; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.kevxu.purdueassist.course.elements.Predefined.Subject; import net.kevxu.purdueassist.course.elements.Predefined.Term; import net.kevxu.purdueassist.course.elements.Predefined.Type; import net.kevxu.purdueassist.course.shared.CourseNotFoundException; import net.kevxu.purdueassist.course.shared.HttpParseException; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync.OnRequestFinishedListener; import net.kevxu.purdueassist.shared.httpclient.HttpClientAsync.HttpMethod; import net.kevxu.purdueassist.shared.httpclient.MethodNotPostException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class CatalogDetail implements OnRequestFinishedListener { private static final String URL_HEAD = "https://selfservice.mypurdue.purdue.edu/prod/" + "bzwsrch.p_catalog_detail"; private Term term; private Subject subject; private int cnbr; private OnCatalogDetailFinishedListener mListener; private BasicHttpClientAsync httpClient; public interface OnCatalogDetailFinishedListener { public void onCatalogDetailFinished(CatalogDetailEntry entry); public void onCatalogDetailFinished(IOException e); public void onCatalogDetailFinished(HttpParseException e); public void onCatalogDetailFinished(CourseNotFoundException e); } public CatalogDetail(Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { this(Term.CURRENT, subject, cnbr, onCatalogDetailFinishedListener); } public CatalogDetail(Term term, Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { if (term != null) this.term = term; else this.term = Term.CURRENT; this.subject = subject; this.cnbr = cnbr; this.mListener = onCatalogDetailFinishedListener; } public void getResult() { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("term", term.getLinkName())); parameters.add(new BasicNameValuePair("subject", subject.name())); parameters.add(new BasicNameValuePair("cnbr", Integer.toString(cnbr))); httpClient = new BasicHttpClientAsync(URL_HEAD, HttpMethod.POST, this); try { httpClient.setParameters(parameters); httpClient.getResponse(); } catch (MethodNotPostException e) { e.printStackTrace(); } } @Override public void onRequestFinished(HttpResponse httpResponse) { try { InputStream stream = httpResponse.getEntity().getContent(); Header encoding = httpResponse.getEntity().getContentEncoding(); Document document; if (encoding == null) { document = Jsoup.parse(stream, null, URL_HEAD); } else { document = Jsoup.parse(stream, encoding.getValue(), URL_HEAD); } stream.close(); CatalogDetailEntry entry = parseDocument(document); mListener.onCatalogDetailFinished(entry); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { mListener.onCatalogDetailFinished(e); } catch (HttpParseException e) { mListener.onCatalogDetailFinished(e); } catch (CourseNotFoundException e) { mListener.onCatalogDetailFinished(e); } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestFinished(ClientProtocolException e) { e.printStackTrace(); } @Override public void onRequestFinished(IOException e) { mListener.onCatalogDetailFinished(e); } private CatalogDetailEntry parseDocument(Document document) throws HttpParseException, CourseNotFoundException { CatalogDetailEntry entry = new CatalogDetailEntry(subject, cnbr); Elements tableElements = document .getElementsByAttributeValue("summary", "This table is used to present the detailed class information."); return entry; } public class CatalogDetailEntry { private Subject searchSubject; private int searchCnbr; public CatalogDetailEntry(Subject subject, int cnbr) { this.searchSubject = subject; this.searchCnbr = cnbr; } private Subject subject; private int cnbr; private String name; private String description; private List<String> levels; private Type type; private String offeredBy; private String department; private List<String> campuses; private String restrictions; private String prerequisites; private String generalRequirements; private Subject getSearchSubject() { return searchSubject; } private int getSearchCnbr() { return searchCnbr; } public Subject getSubject() { return subject; } public int getCnbr() { return cnbr; } public String getName() { return name; } public void setName(String name){ this.name=name; } public String getDescription() { return description; } public void setDescription(String description){ this.description=description; } public List<String> getLevels() { return levels; } public void setLevels(List<String> levels){ this.levels=levels; } public Type getType() { return type; } public void setType(Type type){ this.type=type; } public String getOfferedBy() { return offeredBy; } public void setOfferedBy(String offeredBy){ this.offeredBy=offeredBy; } public String getDepartment() { return department; } public void setDepartment(String department){ this.department=department; } public List<String> getCampuses() { return campuses; } public void setCampuses(List<String> campuses){ this.campuses=campuses; } public String getRestrictions() { return restrictions; } public void setRestrictions(String restrictions){ this.restrictions=restrictions; } public String getPrerequisites() { return prerequisites; } public void setPrerequisites(String prerequisites){ this.prerequisites=prerequisites; } public String getGeneralRequirements() { return generalRequirements; } public void setGeneralRequirements(String generalRequirements){ this.generalRequirements=generalRequirements; } } }
package net.sf.jsqlparser.expression; import java.io.Serializable; import java.sql.SQLException; import net.sf.jsqlparser.schema.PrimitiveType; /** * A terminal expression that can not be evaluated further (e.g., a Number or String) */ public interface PrimitiveValue extends Serializable, Expression { public class InvalidPrimitive extends SQLException {} public long toLong() throws InvalidPrimitive; public double toDouble() throws InvalidPrimitive; public boolean toBool() throws InvalidPrimitive; public PrimitiveType getType(); }
package nl.sense_os.service.ambience; import java.util.ArrayList; import java.util.Iterator; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensePrefs; import nl.sense_os.service.constants.SensePrefs.SensorSpecifics; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.provider.SNTP; /* scales to max and min */ public class LoudnessSensor { private class TimestampValueTuple { long timestamp; double value; TimestampValueTuple(long timestamp, double value) { this.timestamp = timestamp; this.value = value; } }; //private static final String TAG = "Loudness sensor"; private static final float DEFAULT_TOTAL_SILENCE = Float.MAX_VALUE; private static final float DEFAULT_LOUDEST = Float.MIN_VALUE; private final long AVERAGING_PERIOD; private static final long DEFAULT_AVERAGING_PERIOD = 10 * 60 * 1000; private Context context; private ArrayList<TimestampValueTuple> window = new ArrayList<LoudnessSensor.TimestampValueTuple>(); private double totalSilence; private double loudest; private boolean filled = false; public LoudnessSensor(Context context) { this.context = context; AVERAGING_PERIOD = DEFAULT_AVERAGING_PERIOD; //restore silence SharedPreferences sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS, Context.MODE_PRIVATE); totalSilence = sensorSpecifics.getFloat(SensorSpecifics.Loudness.TOTAL_SILENCE, DEFAULT_TOTAL_SILENCE); loudest = sensorSpecifics.getFloat(SensorSpecifics.Loudness.LOUDEST, DEFAULT_LOUDEST); } public void onNewNoise(long ms, double dB) { addNoiseInDb(ms, dB); // double value = relativeLoudnessOf(dB); // Log.v(TAG, "new noise value " + dB + ", loudness: " + value); if (filled) sendSensorValue(loudness(), ms); } /* private void addOldDataToNoisePD() { try { // get data Uri volatileUri = Uri.parse("content://" + context.getString(R.string.local_storage_authority) + DataPoint.CONTENT_URI_PATH); Uri persistentUri = Uri.parse("content://" + context.getString(R.string.local_storage_authority) + DataPoint.CONTENT_PERSISTED_URI_PATH); insertValuesFrom(volatileUri); insertValuesFrom(persistentUri); } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } private void insertValuesFrom(Uri uri) throws Exception { long startTime = SNTP.getInstance().getTime() - timePeriod; LocalStorage storage = LocalStorage.getInstance(context); String[] projection = new String[] { DataPoint.VALUE, DataPoint.TIMESTAMP, DataPoint.SENSOR_NAME }; String where = DataPoint.SENSOR_NAME + "='" + SensorNames.NOISE + "'" + " AND " + DataPoint.TIMESTAMP + ">" + startTime; Cursor cursor = storage.query(uri, projection, where, null, null); // add data to noisePD, TODO: weight with interval so we can // correctly handle data sampled with a varying interval int count = 0; if (cursor.moveToFirst()) { do { double dB = cursor.getFloat(0); noisePD.addValue(dB); } while (cursor.moveToNe xt()); } Log.v(TAG, "got " + cursor.getCount() + " values from " + uri); cursor.close(); } */ private void addNoiseInDb(long timestamp, double dB) { // TODO: should we calculate something like phon or sone to better fit // perceived volume by humans? if (dB == 0) return; //discard 0 window.add(new TimestampValueTuple(timestamp, dB)); if (timestamp - window.get(0).timestamp > AVERAGING_PERIOD) filled = true; } private double loudness() { long startTime = SNTP.getInstance().getTime() - AVERAGING_PERIOD; // remove old values and average over past period // average over past period double meanSum = 0; int values = 0; Iterator<TimestampValueTuple> iter = window.iterator(); while (iter.hasNext()) { TimestampValueTuple tuple = iter.next(); if (tuple.timestamp < startTime) iter.remove(); else { meanSum += Math.pow(10, tuple.value / 20); values += 1; } } double mean = 20 * Math.log(meanSum / values) / Math.log(2); if (mean < totalSilence) setLowestEver(mean); if (mean > loudest) setHighestEver(mean); // make relative return (mean - totalSilence) / (loudest - totalSilence) * 10; } private void setLowestEver(double lowest) { totalSilence = lowest; Editor sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS, Context.MODE_PRIVATE).edit(); sensorSpecifics.putFloat(SensorSpecifics.Loudness.TOTAL_SILENCE, (float)totalSilence); sensorSpecifics.commit(); } private void setHighestEver(double highest) { loudest = highest; Editor sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS, Context.MODE_PRIVATE).edit(); sensorSpecifics.putFloat(SensorSpecifics.Loudness.LOUDEST, (float)loudest); sensorSpecifics.commit(); } private void sendSensorValue(double value, long ms) { Intent sensorData = new Intent( context.getString(R.string.action_sense_new_data)); sensorData.putExtra(DataPoint.SENSOR_NAME, SensorNames.LOUDNESS); sensorData.putExtra(DataPoint.VALUE, (float)value); sensorData.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.FLOAT); sensorData.putExtra(DataPoint.TIMESTAMP, ms); context.startService(sensorData); } }
package org.eclipse.mylyn.internal.tasks.ui.wizards; import java.io.File; import java.util.SortedMap; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import com.ibm.icu.text.DateFormat; /** * Wizard Page for the Task Data Import Wizard * * @author Wesley Coelho * @author Mik Kersten * @author Rob Elves (Adaption to Import wizard) */ public class TaskDataImportWizardPage extends WizardPage { private Button browseButtonZip = null; private Text sourceZipText = null; private Button importViaBackupButton; private Button importViaZipButton; private Table backupFilesTable; // Key values for the dialog settings object private final static String SETTINGS_SAVED = Messages.TaskDataImportWizardPage_Import_Settings_saved; private final static String SOURCE_ZIP_SETTING = Messages.TaskDataImportWizardPage_Import_Source_zip_file_setting; private final static String IMPORT_ZIPMETHOD_SETTING = Messages.TaskDataImportWizardPage_Import_method_zip; private final static String IMPORT_BACKUPMETHOD_SETTING = Messages.TaskDataImportWizardPage_Import_method_backup; public TaskDataImportWizardPage() { super("org.eclipse.mylyn.tasklist.importPage"); //$NON-NLS-1$ setPageComplete(false); setMessage(Messages.TaskDataImportWizardPage_Importing_overwrites_current_tasks_and_repositories, IMessageProvider.WARNING); setImageDescriptor(CommonImages.BANNER_IMPORT); setTitle(Messages.TaskDataImportWizardPage_Restore_tasks_from_history); } public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(3, false); layout.verticalSpacing = 15; container.setLayout(layout); createImportFromZipControl(container); createImportFromBackupControl(container); addRadioListeners(); initSettings(); Dialog.applyDialogFont(container); setControl(container); setPageComplete(validate()); } private void addRadioListeners() { SelectionListener radioListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { browseButtonZip.setEnabled(importViaZipButton.getSelection()); backupFilesTable.setEnabled(importViaBackupButton.getSelection()); sourceZipText.setEnabled(importViaZipButton.getSelection()); controlChanged(); } public void widgetDefaultSelected(SelectionEvent e) { // ignore } }; importViaZipButton.addSelectionListener(radioListener); importViaBackupButton.addSelectionListener(radioListener); } /** * Create widgets for specifying the source zip */ private void createImportFromZipControl(Composite parent) { importViaZipButton = new Button(parent, SWT.RADIO); importViaZipButton.setText(Messages.TaskDataImportWizardPage_From_zip_file); sourceZipText = new Text(parent, SWT.BORDER); sourceZipText.setEditable(true); GridDataFactory.fillDefaults().grab(true, false).hint(250, SWT.DEFAULT).applyTo(sourceZipText); sourceZipText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { controlChanged(); } }); browseButtonZip = new Button(parent, SWT.PUSH); browseButtonZip.setText(Messages.TaskDataImportWizardPage_Browse_); browseButtonZip.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getShell()); dialog.setText(Messages.TaskDataImportWizardPage_Zip_File_Selection); String dir = sourceZipText.getText(); dialog.setFilterPath(dir); dir = dialog.open(); if (dir == null || dir.equals("")) { //$NON-NLS-1$ return; } sourceZipText.setText(dir); } }); } private void createImportFromBackupControl(Composite container) { importViaBackupButton = new Button(container, SWT.RADIO); importViaBackupButton.setText(Messages.TaskDataImportWizardPage_From_snapshot); addBackupFileView(container); } private void addBackupFileView(Composite composite) { backupFilesTable = new Table(composite, SWT.BORDER); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).grab(true, true).applyTo(backupFilesTable); TableColumn filenameColumn = new TableColumn(backupFilesTable, SWT.LEFT); filenameColumn.setWidth(200); SortedMap<Long, File> backupFilesMap = TasksUiPlugin.getBackupManager().getBackupFiles(); for (Long time : backupFilesMap.keySet()) { File file = backupFilesMap.get(time); TableItem item = new TableItem(backupFilesTable, SWT.NONE); item.setData(file.getAbsolutePath()); item.setText(DateFormat.getDateTimeInstance().format(time)); } backupFilesTable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { controlChanged(); } }); } /** * Initializes controls with values from the Dialog Settings object */ protected void initSettings() { IDialogSettings settings = getDialogSettings(); if (settings.get(SETTINGS_SAVED) == null) { importViaZipButton.setSelection(true); sourceZipText.setEnabled(true); backupFilesTable.setEnabled(false); } else { // Retrieve previous values from the dialog settings importViaZipButton.setSelection(settings.getBoolean(IMPORT_ZIPMETHOD_SETTING)); importViaBackupButton.setSelection(settings.getBoolean(IMPORT_BACKUPMETHOD_SETTING)); browseButtonZip.setEnabled(importViaZipButton.getSelection()); sourceZipText.setEnabled(importViaZipButton.getSelection()); backupFilesTable.setEnabled(importViaBackupButton.getSelection()); String zipFile = settings.get(SOURCE_ZIP_SETTING); if (zipFile != null) { sourceZipText.setText(settings.get(SOURCE_ZIP_SETTING)); } } } @Override public void setVisible(boolean visible) { if (visible) { if (importViaZipButton.getSelection()) { sourceZipText.setFocus(); } else { importViaBackupButton.setFocus(); } } super.setVisible(visible); } /** * Saves the control values in the dialog settings to be used as defaults the next time the page is opened */ public void saveSettings() { IDialogSettings settings = getDialogSettings(); settings.put(IMPORT_ZIPMETHOD_SETTING, importViaZipButton.getSelection()); settings.put(IMPORT_BACKUPMETHOD_SETTING, importViaBackupButton.getSelection()); settings.put(SETTINGS_SAVED, SETTINGS_SAVED); } /** Called to indicate that a control's value has changed */ public void controlChanged() { setPageComplete(validate()); } /** Returns true if the information entered by the user is valid */ protected boolean validate() { if (importViaZipButton.getSelection() && sourceZipText.getText().equals("")) { //$NON-NLS-1$ return false; } if (importViaBackupButton.getSelection() && backupFilesTable.getSelection().length == 0) { return false; } return true; } public String getSourceZipFile() { if (importViaZipButton.getSelection()) { return sourceZipText.getText(); } else { if (backupFilesTable.getSelectionIndex() != -1) { return (String) (backupFilesTable.getSelection()[0].getData()); } } return Messages.TaskDataImportWizardPage__unspecified_; } /** For testing only. Sets controls to the specified values */ public void setSource(boolean zip, String sourceZip) { sourceZipText.setText(sourceZip); importViaZipButton.setSelection(zip); } }
package org.jcryptool.crypto.classic.xor.algorithm; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.classic.xor.XorPlugin; /** * Class which provides the function to export/import chars by using a specified * charset or a default (UTF-8) one. * * @author Amro Al-Akkad */ public class FileTransferManager { /** * buffer size for im- and exporting files */ public static final int BUFFER_SIZE = 2048; /** * auxiliary variable for checking if an input file contains a BOM * (byte-order mark) */ public static final int BOM_VALUE = 65279; /** * stream for exporting data */ private OutputStreamWriter out; /** * stream for importing data */ private InputStreamReader in; /** * aux var */ private int token; private int eof = 0; /** * Constructor * * @param inputPath of the to be imported data * @param outputPath of the to be exported data * @param dataObject contains information like the input charset, output * charset, input path etc * @throws Exception if a transfer error occurs */ public FileTransferManager(String inputPath, String outputPath) { try { in = new InputStreamReader(inputPath == null ? System.in : new FileInputStream(inputPath)); out = new OutputStreamWriter(new FileOutputStream(outputPath)); } catch (Exception e) { LogUtil .logError( XorPlugin.PLUGIN_ID, "File Transfer Error: Check the following options: -i, -I, -o and -O for having the invalid argument", //$NON-NLS-1$ e, false); } } /** * Constructor * * @param inputPath of the to be imported data * @param outputPath of the to be exported data * @param dataObject contains information like the input charset, output * charset, input path etc * @throws Exception if a transfer error occures */ public FileTransferManager(String inputPath) { try { in = new InputStreamReader(inputPath == null ? System.in : new FileInputStream(inputPath)); } catch (Exception e) { LogUtil .logError( XorPlugin.PLUGIN_ID, "File Transfer Error: Check the following options: -i, -I, -o and -O for having the invalid argument", //$NON-NLS-1$ e, false); } } /** * writes out the specified char data * * @param chars to be exported data * @param numberOfChars the read in chars, smaller or equals the * BUFFER_SIZE=2048 means 4 KB */ public void writeOutput(char[] chars, int numberOfChars) { // write out string try { out.write(chars, 0, numberOfChars); } catch (Exception e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while writing to the output stream", e, false); //$NON-NLS-1$ } } /** * writes out the special token for Little Endian */ public void writeOutSpecialToken() { try { out.write(BOM_VALUE); } catch (Exception e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while writing to the output stream", e, false); //$NON-NLS-1$ } } /** * Imports the data. * * @param plainBlock the imported chars by using a buffer of 4KB * @return the read in data * @throws Exception if an error occures during the process of importing * chars */ public char[] readInput() { char[] readArray = new char[FileTransferManager.BUFFER_SIZE]; int charPos = 0; try { while (eof != -1 && charPos < FileTransferManager.BUFFER_SIZE) { eof = in.read(readArray, charPos, 1); charPos++; } if (charPos < FileTransferManager.BUFFER_SIZE - 1) { char[] lastArray = new char[charPos - 1]; for (int i = 0; i < charPos - 1; i++) { lastArray[i] = readArray[i]; } readArray = lastArray; } } catch (IOException e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while reading from the input stream", e, false); //$NON-NLS-1$ } return readArray; } /** * checks if the input file contains a BOM at the beginning * * @return true if the input file contains a BOM */ public boolean readInSpecialToken() { try { token = in.read(); } catch (IOException e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while reading from the input stream", e, false); //$NON-NLS-1$ } if (token == BOM_VALUE) { return true; } else { return false; } } /** * closes the output stream */ public void closeOutputStream() { try { out.close(); } catch (IOException e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while closing the output stream", e, false); //$NON-NLS-1$ } } /** * closes the input stream */ public void closeInputStream() { try { in.close(); } catch (IOException e) { LogUtil.logError(XorPlugin.PLUGIN_ID, "Exception while closing the input stream", e, false); //$NON-NLS-1$ } } public int getToken() { return token; } public void setToken(int token) { this.token = token; } public int getEof() { return eof; } }
package org.mwc.debrief.lite.gui.custom.narratives; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; // import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JToggleButton; import org.mwc.debrief.lite.gui.LiteStepControl; import MWC.GUI.Editable; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Layers.DataListener; import MWC.TacticalData.NarrativeEntry; import MWC.TacticalData.NarrativeWrapper; public class NarrativePanelToolbar extends JPanel { /** * Generated Serial Version ID. */ private static final long serialVersionUID = 349058868680231476L; public static final String ACTIVE_STATE = "ACTIVE"; public static final String INACTIVE_STATE = "INACTIVE"; public static final String STATE_PROPERTY = "STATE"; public static final String NARRATIVES_PROPERTY = "NARRATIVES"; public static final String NARRATIVES_REMOVE_COMPLETE_LAYER = "REMOVE_LAYER"; private String _state = INACTIVE_STATE; private final LiteStepControl _stepControl; private final List<JComponent> componentsToDisable = new ArrayList<>(); /** * Maybe this should be inside the abstract model. */ private final DefaultListModel<NarrativeEntryItem> _narrativeListModel = new DefaultListModel<>(); private final JList<NarrativeEntryItem> _narrativeList = new JList<>( _narrativeListModel); private final TreeMap<NarrativeEntry, NarrativeEntryItem> entry2entryItem = new TreeMap<>(); private final AbstractNarrativeConfiguration _model; private final PropertyChangeListener enableDisableButtonsListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { if (STATE_PROPERTY.equals(event.getPropertyName())) { final boolean isActive = ACTIVE_STATE.equals(event.getNewValue()); for (final JComponent component : componentsToDisable) { component.setEnabled(isActive); } } } }; private final PropertyChangeListener updatingNarrativesListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { if (NARRATIVES_PROPERTY.equals(evt.getPropertyName())) { if (evt.getNewValue() instanceof NarrativeWrapper) { final NarrativeWrapper narrativeWrapper = (NarrativeWrapper) evt .getNewValue(); final Set<NarrativeEntry> toRemove = new TreeSet<>(); final Set<NarrativeEntry> toAdd = new TreeSet<>(); // Check difference if (_model.getRegisteredNarrativeWrapper().contains( narrativeWrapper)) { final Set<NarrativeEntry> newEntries = new TreeSet<>(); final Enumeration<Editable> items = narrativeWrapper.elements(); while (items.hasMoreElements()) { final Editable thisE = items.nextElement(); newEntries.add((NarrativeEntry) thisE); } for (final NarrativeEntry currentEntry : _model .getCurrentNarrativeEntries(narrativeWrapper)) { if (!newEntries.contains(currentEntry)) { toRemove.add(currentEntry); } } for (final NarrativeEntry newEntry : newEntries) { if (!_model.getCurrentNarrativeEntries(narrativeWrapper) .contains(newEntry)) { toAdd.add(newEntry); } } } else { _model.addNarrativeWrapper(narrativeWrapper); final Enumeration<Editable> items = narrativeWrapper.elements(); while (items.hasMoreElements()) { final Editable thisE = items.nextElement(); toAdd.add((NarrativeEntry) thisE); } } for (final NarrativeEntry entry : toAdd) { final NarrativeEntryItem entryItem = new NarrativeEntryItem(entry, _model); _narrativeListModel.addElement(entryItem); entry2entryItem.put(entry, entryItem); _model.registerNewNarrativeEntry(narrativeWrapper, entry); } for (final NarrativeEntry entry : toRemove) { _narrativeListModel.removeElement(entry2entryItem.get(entry)); } // Sort it. } } else if (NARRATIVES_REMOVE_COMPLETE_LAYER.equals(evt .getPropertyName())) { final NarrativeWrapper wrapperRemoved = (NarrativeWrapper) evt .getNewValue(); final Enumeration<Editable> iteratorToRemove = wrapperRemoved .elements(); while (iteratorToRemove.hasMoreElements()) { final Editable thisE = iteratorToRemove.nextElement(); _narrativeListModel.removeElement(entry2entryItem.get(thisE)); } _model.removeNarrativeWrapper(wrapperRemoved); } if (!_narrativeListModel.isEmpty()) { setState(ACTIVE_STATE); } else { setState(INACTIVE_STATE); } } }; private final ArrayList<PropertyChangeListener> stateListeners; public NarrativePanelToolbar(final LiteStepControl stepControl, final AbstractNarrativeConfiguration model) { super(new FlowLayout(FlowLayout.LEFT)); this._narrativeList.setCellRenderer(new NarrativeEntryItemRenderer()); this._stepControl = stepControl; this._model = model; init(); stateListeners = new ArrayList<>(Arrays.asList(enableDisableButtonsListener, updatingNarrativesListener)); setState(INACTIVE_STATE); } protected void checkNewNarratives(final Layers layers) { final Enumeration<Editable> elem = layers.elements(); final Set<NarrativeWrapper> loadedNarratives = new TreeSet<>(); while (elem.hasMoreElements()) { final Editable nextItem = elem.nextElement(); if (nextItem instanceof NarrativeWrapper) { final NarrativeWrapper newNarrative = (NarrativeWrapper) nextItem; loadedNarratives.add(newNarrative); if (!_model.getRegisteredNarrativeWrapper().contains(nextItem)) { _model.addNarrativeWrapper(newNarrative); newNarrative.getSupport().addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { notifyListenersStateChanged(nextItem, NARRATIVES_PROPERTY, null, nextItem); } }); notifyListenersStateChanged(nextItem, NARRATIVES_PROPERTY, null, nextItem); } } } for (final NarrativeWrapper narrativeWrappersInPanel : _model .getRegisteredNarrativeWrapper()) { // Some items has been removed. if (!loadedNarratives.contains(narrativeWrappersInPanel)) { notifyListenersStateChanged(narrativeWrappersInPanel, NARRATIVES_REMOVE_COMPLETE_LAYER, null, narrativeWrappersInPanel); } } } /*private JButton createCommandButton(final String command, final String image) { final ImageIcon icon = Utils.getIcon(image); final JButton button = new JButton(icon); button.setToolTipText(command); return button; }*/ private JToggleButton createJToggleButton(final String command, final String image) { final ImageIcon icon = Utils.getIcon(image); final JToggleButton button = new JToggleButton(icon); button.setToolTipText(command); return button; } public JList<NarrativeEntryItem> getNarrativeList() { return _narrativeList; } private void init() { final JSelectTrackFilter selectTrack = new JSelectTrackFilter(_model); final JComboBox<String> tracksFilterLabel = createTracksComboFilter( selectTrack); final JSelectTypeFilter typeFilter = new JSelectTypeFilter(_model); final JComboBox<String> typeFilterLabel = createTypeFilterCombo(selectTrack, typeFilter); final JToggleButton wrapTextButton = createWrapButton(); /*final JButton copyButton = createCommandButton("Copy Selected Entrey", "icons/16/copy_to_clipboard.png"); copyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { System.out.println("Copy selected entry not implemented"); } }); final JButton addBulkEntriesButton = createCommandButton("Add Bulk Entries", "icons/16/list.png"); addBulkEntriesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { System.out.println("Add Bulk Entries not implemented"); } }); final JButton addSingleEntryButton = createCommandButton("Add Single Entry", "icons/16/add.png"); addBulkEntriesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { System.out.println("Add single entry not implemented"); } });*/ add(tracksFilterLabel); add(typeFilterLabel); add(wrapTextButton); /*add(copyButton); add(addBulkEntriesButton); add(addSingleEntryButton);*/ componentsToDisable.addAll(Arrays.asList(new JComponent[] {tracksFilterLabel, typeFilterLabel, wrapTextButton/*, copyButton, addBulkEntriesButton, addSingleEntryButton*/})); createDataListeners(); } private JComboBox<String> createTracksComboFilter( final JSelectTrackFilter selectTrack) { final JComboBox<String> tracksFilterLabel = new JComboBox<>(new String[] {"Sources"}); tracksFilterLabel.setEnabled(true); tracksFilterLabel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mouseEntered(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mouseExited(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mousePressed(final MouseEvent e) { if (tracksFilterLabel.isEnabled()) { // Get the event source final Component component = (Component) e.getSource(); selectTrack.show(component, 0, 0); // Get the location of the point 'on the screen' final Point p = component.getLocationOnScreen(); selectTrack.setLocation(p.x, p.y + component.getHeight()); } } @Override public void mouseReleased(final MouseEvent e) { System.out.println(); // Removing Codacy warning } }); return tracksFilterLabel; } private JComboBox<String> createTypeFilterCombo( final JSelectTrackFilter selectTrack, final JSelectTypeFilter typeFilter) { final JComboBox<String> typeFilterLabel = new JComboBox<>(new String[] {"Types"}); typeFilterLabel.setEnabled(true); typeFilterLabel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mouseEntered(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mouseExited(final MouseEvent e) { System.out.println(); // Removing Codacy warning } @Override public void mousePressed(final MouseEvent e) { if (typeFilterLabel.isEnabled()) { // Get the event source final Component component = (Component) e.getSource(); typeFilter.show(component, 0, 0); // Get the location of the point 'on the screen' final Point p = component.getLocationOnScreen(); selectTrack.setLocation(p.x, p.y + component.getHeight()); } } @Override public void mouseReleased(final MouseEvent e) { System.out.println(); // Removing Codacy warning } }); return typeFilterLabel; } private JToggleButton createWrapButton() { final JToggleButton wrapTextButton = createJToggleButton("Wrap Text", "icons/16/wrap.png"); wrapTextButton.setSelected(true); wrapTextButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { _model.setWrapping(wrapTextButton.isSelected()); if ( wrapTextButton.isSelected() ) { _narrativeList.setFixedCellHeight(-1); }else { _narrativeList.setFixedCellHeight(45); } _narrativeList.repaint(); } }); return wrapTextButton; } private void createDataListeners() { if (_stepControl != null && _stepControl.getLayers() != null) { final DataListener registerNarrativeListener = new DataListener() { @Override public void dataExtended(final Layers theData) { checkNewNarratives(theData); } @Override public void dataModified(final Layers theData, final Layer changedLayer) { checkNewNarratives(theData); } @Override public void dataReformatted(final Layers theData, final Layer changedLayer) { checkNewNarratives(theData); } }; _stepControl.getLayers().addDataExtendedListener( registerNarrativeListener); _stepControl.getLayers().addDataModifiedListener( registerNarrativeListener); _stepControl.getLayers().addDataReformattedListener( registerNarrativeListener); } } private void notifyListenersStateChanged(final Object source, final String property, final Object oldValue, final Object newValue) { for (final PropertyChangeListener event : stateListeners) { event.propertyChange(new PropertyChangeEvent(source, property, oldValue, newValue)); } } public void setState(final String newState) { final String oldState = _state; this._state = newState; if (newState != null && !newState.equals(oldState)) { notifyListenersStateChanged(this, STATE_PROPERTY, oldState, newState); } } }
package ua.com.fielden.platform.web.test.server.config; import static java.lang.String.format; import static ua.com.fielden.platform.web.action.pre.ConfirmationPreAction.okCancel; import static ua.com.fielden.platform.web.centre.api.actions.impl.EntityActionBuilder.action; import static ua.com.fielden.platform.web.centre.api.context.impl.EntityCentreContextSelector.context; import static ua.com.fielden.platform.web.test.server.config.StandardMessages.DELETE_CONFIRMATION; import java.util.function.Function; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractFunctionalEntityWithCentreContext; import ua.com.fielden.platform.entity.EntityDeleteAction; import ua.com.fielden.platform.entity.EntityEditAction; import ua.com.fielden.platform.entity.EntityExportAction; import ua.com.fielden.platform.entity.EntityNewAction; import ua.com.fielden.platform.reflection.TitlesDescsGetter; import ua.com.fielden.platform.web.PrefDim; import ua.com.fielden.platform.web.action.post.FileSaverPostAction; import ua.com.fielden.platform.web.action.pre.ExportPreAction; import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig; import ua.com.fielden.platform.web.centre.api.context.IEntityCentreContextSelectorDone; /** * Enumeration of standard UI action configurations that can be uniformly used throughout Web UI configuration for different entities. * * @author TTGAMS Team * */ public enum StandardActions { NEW_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, null, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { return mkAction(entityType, null, prefDim); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { return mkAction(entityType, computation, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withSelectionCrit().withComputation(computation); } else { contextConfig = context().withSelectionCrit().withComputation(entity -> entityType); } return action(EntityNewAction.class). withContext(contextConfig.build()). icon("add-circle-outline"). shortDesc(format("Add new %s", entityTitle)). longDesc(format("Start creation of %s", entityTitle)). shortcut("alt+n"). prefDimForView(prefDim). withNoParentCentreRefresh(). build(); } }, NEW_WITH_MASTER_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, null, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { return mkAction(entityType, null, prefDim); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { return mkAction(entityType, computation, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withMasterEntity().withSelectionCrit().withComputation(computation); } else { contextConfig = context().withMasterEntity().withSelectionCrit().withComputation(entity -> entityType); } return action(EntityNewAction.class). withContext(contextConfig.build()). icon("add-circle-outline"). shortDesc(format("Add new %s", entityTitle)). longDesc(format("Start creation of %s", entityTitle)). shortcut("alt+n"). prefDimForView(prefDim). withNoParentCentreRefresh(). build(); } }, EDIT_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, null, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { return mkAction(entityType, null, prefDim); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { return mkAction(entityType, computation, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withCurrentEntity().withSelectionCrit().withComputation(computation); } else { contextConfig = context().withCurrentEntity().withSelectionCrit().withComputation(entity -> entityType); } return action(EntityEditAction.class). withContext(contextConfig.build()). icon("editor:mode-edit"). shortDesc(format("Edit %s", entityTitle)). longDesc(format("Opens master for editing %s", entityTitle)). prefDimForView(prefDim). withNoParentCentreRefresh(). build(); } }, DELETE_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, (Function<AbstractFunctionalEntityWithCentreContext<?>, Object>) null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final String desc = format("Delete selected %s entities", entityTitle); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withSelectedEntities().withComputation(computation); } else { contextConfig = context().withSelectedEntities().withComputation(entity -> entityType); } return action(EntityDeleteAction.class). withContext(contextConfig.build()). preAction(okCancel(DELETE_CONFIRMATION.msg)). icon("remove-circle-outline"). shortDesc(desc). longDesc(desc). shortcut("alt+d"). build(); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { throw new UnsupportedOperationException("It's imposible to set preferred dimension for noUI maser!"); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { throw new UnsupportedOperationException("It's imposible to set preferred dimension for noUI maser!"); } }, EXPORT_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, null, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { return mkAction(entityType, null, prefDim); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { return mkAction(entityType, computation, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final String desc = format("Export selected %s entities", entityTitle); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withSelectionCrit().withSelectedEntities().withComputation(computation); } else { contextConfig = context().withSelectionCrit().withSelectedEntities().withComputation(entity -> entityType); } return action(EntityExportAction.class). withContext(contextConfig.build()). preAction(new ExportPreAction()). postActionSuccess(new FileSaverPostAction()). icon("icons:save"). shortDesc(desc). longDesc(desc). prefDimForView(prefDim). withNoParentCentreRefresh(). build(); } }, EXPORT_EMBEDDED_CENTRE_ACTION { @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType) { return mkAction(entityType, null, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final PrefDim prefDim) { return mkAction(entityType, null, prefDim); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation) { return mkAction(entityType, computation, null); } @Override public EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, final PrefDim prefDim) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(); final String desc = format("Export selected %s entities", entityTitle); final IEntityCentreContextSelectorDone<AbstractEntity<?>> contextConfig; if (computation != null) { contextConfig = context().withSelectionCrit().withSelectedEntities().withComputation(computation); } else { contextConfig = context().withSelectionCrit().withSelectedEntities().withComputation(entity -> entityType); } return action(EntityExportAction.class). withContext(contextConfig.build()). preAction(new ExportPreAction()). postActionSuccess(new FileSaverPostAction()). icon("icons:save"). shortDesc(desc). longDesc(desc). prefDimForView(prefDim). withNoParentCentreRefresh(). build(); } }; public abstract EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType); public abstract EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, PrefDim prefDim); public abstract EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation); public abstract EntityActionConfig mkAction(final Class<? extends AbstractEntity<?>> entityType, final Function<AbstractFunctionalEntityWithCentreContext<?>, Object> computation, PrefDim prefDim); }
package cc.topicexplorer.plugin.wiki.preprocessing; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.commons.chain.Context; import tools.BracketPositions; import tools.CategoryElement; import tools.ExtraInformations; import tools.WikiIDTitlePair; import wikiParser.SupporterForBothTypes; import cc.topicexplorer.chain.CommunicationContext; import cc.topicexplorer.chain.commands.DependencyCommand; public class CategoryResolver extends DependencyCommand { private wikiParser.Database db; private Properties prop; public static String categoryFileName = "categories.csv"; private final HashSet<String> catChilds = new HashSet<String>(); private wikiParser.SupporterForBothTypes s; private BufferedWriter bw; private final LinkedList<String> stack = new LinkedList<String>(); private static final String CATPARENTTEXT = ""; // "has_no_parent"; @Override public void specialExecute(Context context) { if (logger != null) { logger.info("[ " + getClass() + " ] - " + " resolve categorys from wiki-db"); } CommunicationContext communicationContext = (CommunicationContext) context; prop = (Properties) communicationContext.get("properties"); try { init(); start(); } catch (IOException e) { logger.error("Category resolver caused a problem"); throw new RuntimeException(e); } } @Override public void addDependencies() { beforeDependencies.add("Wiki_CategoryTreeCreate"); }; private void init() throws IOException { // eigene DB Zugriff auf Wikidb try { String outputFolder = prop.getProperty("Wiki_outputFolder"); File dir = new File(outputFolder); if (!dir.exists()) { dir.mkdir(); } db = new wikiParser.Database(prop); s = new SupporterForBothTypes(db); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputFolder + "/" + categoryFileName)))); } catch (SQLException e) { logger.error("Database for category resolver could not be constructed, due to a database error."); throw new RuntimeException(e); } catch (InstantiationException e) { logger.error("Database for category resolver could not be constructed, due to a programming error."); throw new RuntimeException(e); } catch (IllegalAccessException e) { logger.error("Database for category resolver could not be constructed, due to a programming error."); throw new RuntimeException(e); } catch (ClassNotFoundException e) { logger.error("Database for category resolver could not be constructed, due to a programming error."); throw new RuntimeException(e); } } private void start() throws IOException { try { ResultSet rs; WikiIDTitlePair child; String sql = "Select page_title , page_latest from page where page_namespace = 14 ;"; System.out.println(sql); rs = db.executeQuery(sql); while (rs.next()) { child = new WikiIDTitlePair(Integer.valueOf(rs.getString("page_latest")), rs.getString("page_title")); // wenn das kind noch nicht untersucht worden ist if (!catChilds.contains(getTitleWithUnderscores(child.getWikiTitle()))) { getParentCategoriesOfWikiIdTitle(child); } emptyingStackAndResolveElements(); } } catch (SQLException e) { if (logger != null) { logger.warn("[ " + getClass() + " ] - " + e.getMessage()); } } finally { bw.flush(); bw.close(); } } private void getParentCategoriesOfWikiIdTitle(WikiIDTitlePair child) { try { String wikiText; List<CategoryElement> listOfLinks; BracketPositions bp; wikiText = s.getWikiTextOnlyWithID(child.getOld_id()); bp = new BracketPositions(wikiText, child.getOld_id(), child.getWikiTitle()); listOfLinks = bp.getCategoryLinkList(); catChilds.add(getTitleWithUnderscores(child.getWikiTitle())); for (CategoryElement e : listOfLinks) { addToBW(e); // wenn noch nicht in hashset kann es auf den stack if (!catChilds.contains(getTitleWithUnderscores(e.getText()))) { stack.add(getTitleWithUnderscores(ExtraInformations.getTargetWithoutCategoryInformation(e.getText()))); } } bp = null; } catch (SQLException e) { if (logger != null) { logger.warn("[ " + getClass() + ".getParentCategoriesOfWikiIdTitle() ] - " + e.getMessage() + ", only subfunction"); } } catch (IOException e) { if (logger != null) { logger.warn("[ " + getClass() + ".getParentCategoriesOfWikiIdTitle() ] - " + e.getMessage() + ", only subfunction"); } } } private void addToBW(CategoryElement e) throws IOException { this.bw.append(e.getCategroryTreeOutput() + "\n"); } private String getTitleWithUnderscores(String title) { if (title.contains(" ")) { title = s.fillSpacesWithUnderscores(title); } return title; } private void emptyingStackAndResolveElements() { while (stack.size() > 0) { String e = stack.remove(); if (!catChilds.contains(e)) { getParentCategoriesOfString(e, false); } } } private void getParentCategoriesOfString(String category, Boolean trueIfCommesFromSource) { try { String sql = "SELECT page_title, page_latest FROM page where page_namespace = 14 and page_title like '" + category + "' "; ResultSet rs; WikiIDTitlePair id_title; rs = db.executeQuery(sql); if (rs.next()) { id_title = s .getOldIdAndWikiTitleFromWikiPageIdFromDatabase(Integer.valueOf(rs.getString("page_latest"))); getParentCategoriesOfWikiIdTitle(id_title); } else { // for finding cat-pages who has no parent because of failed // import or something, perhaps it doesn't matter with fully // imported dumps if (!trueIfCommesFromSource) { CategoryElement ce = new CategoryElement(); // ce.setOldId(old_id); ce.setTitle(category); ce.setText(CATPARENTTEXT); addToBW(ce); catChilds.add(category); } } } catch (NumberFormatException e) { if (logger != null) { logger.warn("[ " + getClass() + ".getParentCategoriesOfString() ] - " + e.getMessage() + ", only subfunction"); } } catch (SQLException e) { if (logger != null) { logger.warn("[ " + getClass() + ".getParentCategoriesOfString() ] - " + e.getMessage() + ", only subfunction"); } } catch (IOException e) { if (logger != null) { logger.warn("[ " + getClass() + ".getParentCategoriesOfString() ] - " + e.getMessage() + ", only subfunction"); } } } private static Properties forLocalExcetution() throws IOException { Properties prop; String fileName = "src/test/resources/localwikiconfig.ini"; File f = new File(fileName); if (f.exists()) { prop = new Properties(); // prop.load(this.getClass().getResourceAsStream("/config.ini")); FileInputStream fis = new FileInputStream(fileName); prop.load(fis); return prop; } else { System.err.print(f.getAbsolutePath() + "\n"); throw new FileNotFoundException(f + "not found."); } } private void setProperties(Properties prop) { this.prop = prop; } public static void main(String[] args) { try { CategoryResolver c = new CategoryResolver(); c.setProperties(CategoryResolver.forLocalExcetution()); c.init(); c.start(); } catch (IOException e) { e.printStackTrace(); } } }
package gov.nih.nci.cabig.caaers.rules.business.service; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.Grade; import gov.nih.nci.cabig.caaers.domain.Hospitalization; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.rules.brxml.Action; import gov.nih.nci.cabig.caaers.rules.brxml.Column; import gov.nih.nci.cabig.caaers.rules.brxml.Condition; import gov.nih.nci.cabig.caaers.rules.brxml.FieldConstraint; import gov.nih.nci.cabig.caaers.rules.brxml.LiteralRestriction; import gov.nih.nci.cabig.caaers.rules.brxml.MetaData; import gov.nih.nci.cabig.caaers.rules.brxml.ReadableRule; import gov.nih.nci.cabig.caaers.rules.brxml.Rule; import gov.nih.nci.cabig.caaers.rules.brxml.RuleSet; import gov.nih.nci.cabig.caaers.rules.common.BRXMLHelper; import gov.nih.nci.cabig.caaers.rules.common.CategoryConfiguration; import gov.nih.nci.cabig.caaers.rules.common.RuleType; import gov.nih.nci.cabig.caaers.rules.common.RuleUtil; import gov.nih.nci.cabig.caaers.service.EvaluationService; import java.io.File; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.NamingException; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.jndi.SimpleNamingContextBuilder; public class RulesEngineServiceTest extends TestCase { private RulesEngineService rulesEngineService; private static Log log = LogFactory.getLog(RulesEngineServiceTest.class); private static RuntimeException acLoadFailure = null; private static ApplicationContext applicationContext = null; protected Set<Object> mocks = new HashSet<Object>(); private EvaluationService aees; private static String SERIOUS_ADVERSE_EVENT = "SERIOUS_ADVERSE_EVENT"; protected void setUp() throws Exception { super.setUp(); Connection db; // A connection to the database Statement sql; // Our statement to run queries with Class.forName("org.postgresql.Driver"); db = DriverManager.getConnection( "jdbc:postgresql://localhost/caaers", "postgres", "postgres"); sql = db.createStatement(); String sqlText_1 = "drop table rep_binval"; String sqlText_2 = "drop table rep_fsentry"; String sqlText_3 = "drop table rep_node"; String sqlText_4 = "drop table rep_prop"; String sqlText_5 = "drop table rep_refs"; String sqlText_6 = "drop table rep_ver_binval"; String sqlText_7 = "drop table rep_ver_fsentry"; String sqlText_8 = "drop table rep_ver_node"; String sqlText_9 = "drop table rep_ver_prop"; String sqlText_0 = "drop table rep_ver_refs"; try { sql.executeUpdate(sqlText_1); System.out.println(sqlText_1 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_2); System.out.println(sqlText_2 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_3); System.out.println(sqlText_3 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_4); System.out.println(sqlText_4 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_5); System.out.println(sqlText_5 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_6); System.out.println(sqlText_6 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_7); System.out.println(sqlText_7 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_8); System.out.println(sqlText_8 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_9); System.out.println(sqlText_9 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } try { sql.executeUpdate(sqlText_0); System.out.println(sqlText_0 + " successfully executed"); } catch (org.postgresql.util.PSQLException pe) { if (pe.getErrorCode() != 0) throw pe; } db.close(); deleteDir(new File("/tmp/rules_repo/repo")); File f = new File("/tmp/rules_repo/repo"); f.mkdir(); this.rulesEngineService = new RulesEngineServiceImpl(); aees = (EvaluationServiceImpl)getDeployedApplicationContext().getBean("evaluationService"); } public void testRulesEngineService() throws Exception { String sponsorName = "National Cancer Institute"; String ruleSetType = RuleType.AE_ASSESMENT_RULES.getName(); String studyName = "cgems"; //rulePreview(sponsorName,ruleSetType,studyName); sponserAEAssesmentRuleFlow(sponsorName,ruleSetType,studyName); /* getRuleSetForSponsor(); createRuleSetForInstitution(); getRuleSetForInstitution(); saveRulesForInstitution(); createRuleSetForStudy(); getRuleSetForStudy(); saveRulesForStudy(); createRuleForInstitution(); createRuleForSponsor(); createRuleForStudy(); getAllRuleSetsForSponsor(); getAllRuleSetsForStudy(); getAllRuleSets(); deployRuleSet(); */ // updateRuleSet(RuleSet ruleSet) // deployRuleSet(RuleSet ruleSet) throws Exception; // unDeployRuleSet(RuleSet set) throws Exception; } private void sponserAEAssesmentRuleFlow(String sponsorName,String ruleSetType, String studyName) throws Exception { RuleSet rs = this.createRulesForSponsor(1, sponsorName); RulesEngineService res = new RulesEngineServiceImpl(); res.saveRulesForSponsor(rs, sponsorName); rs = res.getRuleSetForSponsor(rs.getDescription(),sponsorName); // display readable info ReadableRule readable = rs.getRule().get(0).getReadableRule(); System.out.println(" "); for (String line:readable.getLine()) { System.out.println(line); } // deploy rules... res.deployRuleSet(rs); } private void sponsorDefinedStudyAEAssesmentRuleFlow(String sponsorName,String ruleSetType, String studyName) throws Exception { RuleSet rs = this.createRulesForSponsorDefinedStudy(3, sponsorName, studyName); RulesEngineService res = new RulesEngineServiceImpl(); res.saveRulesForSponsorDefinedStudy(rs, studyName, sponsorName); rs = res.getRuleSetForSponsorDefinedStudy(rs.getDescription(),studyName,sponsorName); // deploy rules... res.deployRuleSet(rs); } private void institutionSAEReportingRuleFlow(String institutionName,String ruleSetType, String studyName) throws Exception { RuleSet rs = this.createRulesForInstitution(2, institutionName); RulesEngineService res = new RulesEngineServiceImpl(); res.saveRulesForInstitution(rs, institutionName); rs = res.getRuleSetForInstitution(rs.getDescription(),institutionName); // deploy rules... res.deployRuleSet(rs); } private void createRuleSetForSponsor(String sponsorName, String ruleSetName) throws Exception { rulesEngineService.createRuleSetForSponsor(ruleSetName, sponsorName); } private RuleSet createRulesForSponsor(int id, String sponsorName) { RuleSet rs = new RuleSet(); rs.setDescription(RuleType.AE_ASSESMENT_RULES.getName()); Rule r = makeRule(id,SERIOUS_ADVERSE_EVENT); // sponser based rules // need to add sponser name in the crieteria. r.getCondition().getColumn().add(this.createCriteriaForSponsor(sponsorName)); rs.getRule().add(r); return rs; } private RuleSet createRulesForInstitution(int id, String institutionName) throws Exception { RuleSet rs = new RuleSet(); rs.setDescription(RuleType.REPORT_SCHEDULING_RULES.getName()); Rule r = makeRule(id,"10 Day Report"); // sponser based rules // need to add sponser name in the crieteria. r.getCondition().getColumn().add(this.createCriteriaForInstitute(institutionName)); rs.getRule().add(r); return rs; } private RuleSet createRulesForSponsorDefinedStudy(int id, String sponsorName,String studyName) { RuleSet rs = new RuleSet(); rs.setDescription(RuleType.AE_ASSESMENT_RULES.getName()); Rule r = makeRule(id,SERIOUS_ADVERSE_EVENT); // sponser based rules // need to add sponser name in the crieteria. r.getCondition().getColumn().add(this.createCriteriaForSponsor(sponsorName)); r.getCondition().getColumn().add(this.createCriteriaForStudy(studyName)); rs.getRule().add(r); return rs; } private void createAdverseEvents(String studyName, String orgName) throws Exception { createAdverseEvent1( studyName, orgName); createAdverseEvent2( studyName, orgName); } private void createAdverseEvent1(String studyName, String orgName) throws Exception { // execute rules... AdverseEvent ae1 = new AdverseEvent(); ae1.setGrade(Grade.MILD); ae1.setHospitalization(Hospitalization.NONE); Study s = new Study(); Organization org = new Organization(); org.setName(orgName); s.setPrimaryFundingSponsorOrganization(org); s.setShortTitle(studyName); AdverseEventEvaluationService aees = new AdverseEventEvaluationServiceImpl(); String msg = aees.assesAdverseEvent(ae1, s); System.out.println(msg); assertEquals(msg, "CAN_NOT_DETERMINED"); } private void createAdverseEvent2(String studyName, String orgName) throws Exception { // execute rules... AdverseEvent ae1 = new AdverseEvent(); ae1.setGrade(Grade.MILD); ae1.setHospitalization(Hospitalization.HOSPITALIZATION); Study s = new Study(); Organization org = new Organization(); org.setName(orgName); s.setPrimaryFundingSponsorOrganization(org); s.setShortTitle(studyName); AdverseEventEvaluationService aees = new AdverseEventEvaluationServiceImpl(); String msg = aees.assesAdverseEvent(ae1, s); System.out.println(msg); assertEquals(msg, "SERIOUS_ADVERSE_EVENT"); } private RuleSet createRulesForInstitute(int id) { RuleSet rs = new RuleSet(); rs.setDescription(RuleType.AE_ASSESMENT_RULES.getName()); Rule r = makeRule(id,""); // inst based rules // need to add inst name in the crieteria. r.getCondition().getColumn().add( this.createCriteriaForInstitute("Wake Forest Comprehensive Cancer Center")); rs.getRule().add(r); return rs; } /* * THis method is used to create criteria for institute * name */ private Column createCriteriaForInstitute(String criteriaValue) { Column column = BRXMLHelper.newColumn(); column.setObjectType("gov.nih.nci.cabig.caaers.domain.Organization"); column.setIdentifier("siteSDO"); column.setExpression("getName()"); List<FieldConstraint> fieldConstraints = new ArrayList<FieldConstraint>(); FieldConstraint fieldConstraint = new FieldConstraint(); fieldConstraint.setFieldName("name"); fieldConstraints.add(fieldConstraint); ArrayList<LiteralRestriction> literalRestrictions = new ArrayList<LiteralRestriction>(); LiteralRestriction literalRestriction = new LiteralRestriction(); literalRestriction.setEvaluator("=="); literalRestriction.getValue().add(criteriaValue); literalRestrictions.add(literalRestriction); fieldConstraint.setLiteralRestriction(literalRestrictions); column.setFieldConstraint(fieldConstraints); return column; } /* * THis method is used to create criteria for sponsor based on the sponsor * name */ private Column createCriteriaForSponsor(String criteriaValue) { Column column = BRXMLHelper.newColumn(); column.setObjectType("gov.nih.nci.cabig.caaers.domain.Study"); column.setIdentifier("studySDO"); column.setExpression("getPrimaryFundingSponsorOrganization().getName()"); List<FieldConstraint> fieldConstraints = new ArrayList<FieldConstraint>(); FieldConstraint fieldConstraint = new FieldConstraint(); fieldConstraint.setFieldName("primarySponsorCode"); fieldConstraints.add(fieldConstraint); ArrayList<LiteralRestriction> literalRestrictions = new ArrayList<LiteralRestriction>(); LiteralRestriction literalRestriction = new LiteralRestriction(); literalRestriction.setEvaluator("=="); literalRestriction.getValue().add(criteriaValue); literalRestrictions.add(literalRestriction); fieldConstraint.setLiteralRestriction(literalRestrictions); column.setFieldConstraint(fieldConstraints); return column; } private Column createCriteriaForStudy(String criteriaValue) { Column column = BRXMLHelper.newColumn(); column.setObjectType("gov.nih.nci.cabig.caaers.domain.Study"); column.setIdentifier("studySDO"); column.setExpression("getShortTitle()"); List<FieldConstraint> fieldConstraints = new ArrayList<FieldConstraint>(); FieldConstraint fieldConstraint = new FieldConstraint(); fieldConstraint.setFieldName("primarySponsorCode"); fieldConstraints.add(fieldConstraint); ArrayList<LiteralRestriction> literalRestrictions = new ArrayList<LiteralRestriction>(); LiteralRestriction literalRestriction = new LiteralRestriction(); literalRestriction.setEvaluator("=="); literalRestriction.getValue().add(criteriaValue); literalRestrictions.add(literalRestriction); fieldConstraint.setLiteralRestriction(literalRestrictions); column.setFieldConstraint(fieldConstraints); return column; } private boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } private RuleSet getRuleSetForSponsor(String sponsorName) throws Exception { String ruleSetName = RuleType.AE_ASSESMENT_RULES.getName(); RuleSet ruleSet = rulesEngineService.getRuleSetForSponsor(ruleSetName, sponsorName); return ruleSet; } private void getRuleSetForInstitution() throws Exception { String ruleSetName = RuleType.AE_ASSESMENT_RULES.getName(); String institutionName = "Duke Medical Center"; RuleSet ruleSet = rulesEngineService.getRuleSetForInstitution( ruleSetName, institutionName); String packageName = RuleUtil.getPackageName( CategoryConfiguration.INSTITUTION_BASE.getPackagePrefix(), institutionName, ruleSetName); assertEquals(packageName, ruleSet.getName()); } private void createRuleSetForStudy() throws Exception { String ruleSetName = RuleType.REPORT_SCHEDULING_RULES.getName(); String studyShortTitle = "Our test Study"; String sponsorName = "Loudoun Medical Center"; rulesEngineService.createRuleSetForSponsorDefinedStudy(ruleSetName, studyShortTitle, sponsorName); } private void getRuleSetForStudy() throws Exception { String ruleSetName = RuleType.REPORT_SCHEDULING_RULES.getName(); String studyShortTitle = "Our test Study"; String sponsorName = "Loudoun Medical Center"; RuleSet ruleSet = rulesEngineService.createRuleSetForSponsorDefinedStudy(ruleSetName, studyShortTitle, sponsorName); String packageName = RuleUtil.getStudySponsorSpecificPackageName( CategoryConfiguration.SPONSOR_DEFINED_STUDY_BASE.getPackagePrefix(), studyShortTitle, sponsorName, ruleSetName); assertEquals(packageName, ruleSet.getName()); } private void getAllRuleSetsForSponsor() throws Exception { String sponsorName = "National Cancer Institute"; List<RuleSet> ruleSets = rulesEngineService .getAllRuleSetsForSponsor(sponsorName); assertEquals(1, ruleSets.size()); } private void getAllRuleSetsForStudy() throws Exception { String studyShortTitle = "Our test Study"; String sponsorName = "Loudoun Medical Center"; List<RuleSet> ruleSets = rulesEngineService.getAllRuleSetsForSponsorDefinedStudy( studyShortTitle, sponsorName); assertEquals(1, ruleSets.size()); } private void getAllRuleSetsForInstitution() throws Exception { String institutionName = "Duke Medical Center"; List<RuleSet> ruleSets = rulesEngineService .getAllRuleSetsForInstitution(institutionName); assertEquals(1, ruleSets.size()); } private void getRulesByCategory() throws Exception { String catPath = "/CAAERS_BASE/SPONSOR/National_Cancer_Institute/AE_Assesment_Rules"; List<Rule> rules = rulesEngineService.getRulesByCategory(catPath); assertEquals(4, rules.size()); } private void getAllRuleSets() throws Exception { List<RuleSet> ruleSets = rulesEngineService.getAllRuleSets(); for (RuleSet rs : ruleSets) { System.out.println("Rule Set Name:" + rs.getDescription()); } assertEquals(4, ruleSets.size()); } private void deployRuleSet() throws Exception { String ruleSetName = RuleType.REPORT_SCHEDULING_RULES.getName(); String studyShortTitle = "Our test Study"; String sponsorName = "Loudoun Medical Center"; RuleSet ruleSet = rulesEngineService.getRuleSetForSponsorDefinedStudy(ruleSetName, studyShortTitle, sponsorName); rulesEngineService.deployRuleSet(ruleSet); } private Rule makeRule(int i, String actionStr) { Rule rule1 = new Rule(); rule1.setMetaData(new MetaData()); rule1.getMetaData().setName("Rule" + i); rule1.getMetaData().setDescription("Our test rule" + i); Condition condition = new Condition(); // condition.getEval().add("adverseEvent.getGrade().getCode() <= // Grade.MODERATE.getCode()"); Column column1 = new Column(); column1.setObjectType("AdverseEvent"); column1.setIdentifier("adverseEvent"); column1.setExpression("getGrade().getCode().intValue()"); column1.setDisplayUri("Adverse Event"); FieldConstraint fieldConstraint1 = new FieldConstraint(); fieldConstraint1.setFieldName("grade"); fieldConstraint1.setGrammerPrefix(" has a "); fieldConstraint1.setDisplayUri("Grade"); LiteralRestriction literalRestriction1 = new LiteralRestriction(); literalRestriction1.setEvaluator("=="); literalRestriction1.setDisplayUri("Equal To"); List<String> values1 = new ArrayList<String>(); values1.add("1"); literalRestriction1.setValue(values1); List<LiteralRestriction> lr1 = new ArrayList<LiteralRestriction>(); lr1.add(literalRestriction1); fieldConstraint1.setLiteralRestriction(lr1); ArrayList<FieldConstraint> fields1 = new ArrayList<FieldConstraint>(); fields1.add(fieldConstraint1); column1.setFieldConstraint(fields1); condition.getColumn().add(column1); Column column2 = new Column(); column2.setObjectType("AdverseEvent"); column2.setIdentifier("adverseEvent"); column2.setExpression("getHospitalization().getCode().intValue()"); column2.setDisplayUri("Adverse Event"); FieldConstraint fieldConstraint2 = new FieldConstraint(); fieldConstraint2.setFieldName("hospitalization"); fieldConstraint2.setGrammerPrefix(" has a "); fieldConstraint2.setDisplayUri("Hospitalization"); LiteralRestriction literalRestriction2 = new LiteralRestriction(); literalRestriction2.setEvaluator("=="); literalRestriction2.setDisplayUri("Equal To"); List<String> values2 = new ArrayList<String>(); values2.add("1"); values2.add("2"); literalRestriction2.setValue(values2); List<LiteralRestriction> lr2 = new ArrayList<LiteralRestriction>(); lr2.add(literalRestriction2); fieldConstraint2.setLiteralRestriction(lr2); ArrayList<FieldConstraint> fields2 = new ArrayList<FieldConstraint>(); fields2.add(fieldConstraint2); column2.setFieldConstraint(fields2); condition.getColumn().add(column2); /** * Make it or break it */ // Column column_fixed = new Column(); // column_fixed.setObjectType("gov.nih.nci.cabig.caaers.rules.domain.AdverseEventEvaluationResult"); // column_fixed.setIdentifier("adverseEventEvaluationResult"); // condition.getColumn().add(column_fixed); rule1.setCondition(condition); // Notification action = new Notification(); // action.setActionId("ROUTINE_AE"); Action action = new Action(); action.setActionId(actionStr); rule1.setAction(action); ReadableRule readable = new ReadableRule(); List<String> line = new ArrayList<String>(); // add lines.. line.add("If"); for (Column column:rule1.getCondition().getColumn()) { // skip rule type filters if (!column.getExpression().equals("getPrimaryFundingSponsorOrganization().getName()")) { line.add(RuleUtil.readableColumn(column)); line.add("AND"); } } line.remove(line.size()-1); readable.setLine(line); rule1.setReadableRule(readable); return rule1; } public static String[] getConfigLocations() { return new String[] { "classpath*:gov/nih/nci/cabig/caaers/applicationContext-configProperties.xml", "classpath*:gov/nih/nci/cabig/caaers/applicationContext-core-spring.xml", "classpath*:gov/nih/nci/cabig/caaers/applicationContext-core-db.xml", "classpath*:gov/nih/nci/cabig/caaers/applicationContext-core-dao.xml", "classpath*:gov/nih/nci/cabig/caaers/applicationContext-core-service.xml", "classpath*:config/spring/applicationContext-rules-services.xml" }; } public synchronized static ApplicationContext getDeployedApplicationContext() { if (acLoadFailure == null && applicationContext == null) { // This might not be the right place for this try { SimpleNamingContextBuilder.emptyActivatedContextBuilder(); } catch (NamingException e) { throw new RuntimeException("", e); } try { log.debug("Initializing test version of deployed application context"); applicationContext = new ClassPathXmlApplicationContext(getConfigLocations()); } catch (RuntimeException e) { acLoadFailure = e; throw e; } } else if (acLoadFailure != null) { throw new CaaersSystemException( "Application context loading already failed. Will not retry. " + "Original cause attached.", acLoadFailure); } return applicationContext; } public void atestNewRuleScheme() { } }
package pl.grzeslowski.jsupla.protocol.encoders; import pl.grzeslowski.jsupla.protocol.structs.TSuplaDataPacket; import pl.grzeslowski.jsupla.protocol.structs.sd.TSD_SuplaRegisterDeviceResult; import static java.util.Objects.requireNonNull; import static pl.grzeslowski.jsupla.Preconditions.min; import static pl.grzeslowski.jsupla.protocol.encoders.PrimitiveEncoder.writeInteger; public class TSD_SuplaRegisterDeviceResultEncoder implements Encoder<TSD_SuplaRegisterDeviceResult> { private final int version; private final DataPacketIdGenerator idGenerator; public TSD_SuplaRegisterDeviceResultEncoder(int version, DataPacketIdGenerator idGenerator) { this.version = min(version, 1); this.idGenerator = requireNonNull(idGenerator); } @SuppressWarnings("UnusedAssignment") @Override public TSuplaDataPacket encode(TSD_SuplaRegisterDeviceResult proto) { byte[] data = new byte[proto.size()]; int offset = 0; offset += writeInteger(proto.resultCode, data, offset); offset += PrimitiveEncoder.writeByte(proto.activityTimeout, data, offset); offset += PrimitiveEncoder.writeByte(proto.version, data, offset); offset += PrimitiveEncoder.writeByte(proto.versionMin, data, offset); return new TSuplaDataPacket( (short) version, idGenerator.nextId(), proto.callType().getValue(), data.length, data); } }
package org.sagebionetworks.repo.web.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.ConflictingUpdateException; import org.sagebionetworks.repo.model.DatastoreException; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.InvalidModelException; import org.sagebionetworks.repo.model.PaginatedResults; import org.sagebionetworks.repo.model.ProjectHeader; import org.sagebionetworks.repo.model.ProjectSettingsDAO; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.model.UnauthorizedException; import org.sagebionetworks.repo.model.UserGroupHeaderResponsePage; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.attachment.PresignedUrl; import org.sagebionetworks.repo.model.attachment.S3AttachmentToken; import org.sagebionetworks.repo.model.project.ProjectSetting; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.repo.web.UrlHelpers; import org.sagebionetworks.repo.web.rest.doc.ControllerInfo; import org.sagebionetworks.repo.web.service.ServiceProvider; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerInfo(displayName = "Project Settings Services", path = "repo/v1") @Controller @RequestMapping(UrlHelpers.REPO_PATH) public class ProjectSettingsController extends BaseController { @Autowired ServiceProvider serviceProvider; @ResponseStatus(HttpStatus.OK) @RequestMapping(value = UrlHelpers.PROJECT_SETTINGS_BY_ID, method = RequestMethod.GET) public @ResponseBody ProjectSetting getProjectSetting(@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @PathVariable String id) throws DatastoreException, UnauthorizedException, NotFoundException { return serviceProvider.getProjectSettingsService().getProjectSetting(userId, id); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = UrlHelpers.PROJECT_SETTINGS_BY_PROJECT_ID_AND_TYPE, method = RequestMethod.GET) public @ResponseBody ProjectSetting getProjectSettingByProjectAndType(@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @PathVariable String projectId, @PathVariable String type) throws DatastoreException, UnauthorizedException, NotFoundException { return serviceProvider.getProjectSettingsService().getProjectSettingByProjectAndType(userId, projectId, type); } @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.PROJECT_SETTINGS }, method = RequestMethod.POST) public @ResponseBody ProjectSetting createProjectSetting(@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestBody ProjectSetting projectSetting, HttpServletRequest request) throws NotFoundException, DatastoreException, UnauthorizedException, InvalidModelException { return serviceProvider.getProjectSettingsService().createProjectSetting(userId, projectSetting); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { UrlHelpers.PROJECT_SETTINGS }, method = RequestMethod.PUT) public @ResponseBody void updateProjectSetting(@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestBody ProjectSetting projectSetting, HttpServletRequest request) throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, JSONObjectAdapterException { serviceProvider.getProjectSettingsService().updateProjectSetting(userId, projectSetting); } @ResponseStatus(HttpStatus.NO_CONTENT) @RequestMapping(value = { UrlHelpers.PROJECT_SETTINGS_BY_ID }, method = RequestMethod.DELETE) public @ResponseBody void deleteProjectSetting(@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @PathVariable String id, HttpServletRequest request) throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, JSONObjectAdapterException { serviceProvider.getProjectSettingsService().deleteProjectSetting(userId, id); } }
package aQute.libg.version; import java.util.regex.*; public class Version implements Comparable<Version> { final int major; final int minor; final int micro; final String qualifier; public final static String VERSION_STRING = "(\\d+)(\\.(\\d+)(\\.(\\d+)(\\.([-_\\da-zA-Z]+))?)?)?"; public final static Pattern VERSION = Pattern .compile(VERSION_STRING); public final static Version LOWEST = new Version(); public final static Version HIGHEST = new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, "\uFFFF"); public static final Version emptyVersion = LOWEST; public static final Version ONE = new Version(1,0,0); public Version() { this(0); } public Version(int major, int minor, int micro, String qualifier) { this.major = major; this.minor = minor; this.micro = micro; this.qualifier = qualifier; } public Version(int major, int minor, int micro) { this(major, minor, micro, null); } public Version(int major, int minor) { this(major, minor, 0, null); } public Version(int major) { this(major, 0, 0, null); } public Version(String version) { version = version.trim(); Matcher m = VERSION.matcher(version); if (!m.matches()) throw new IllegalArgumentException("Invalid syntax for version: " + version); major = Integer.parseInt(m.group(1)); if (m.group(3) != null) minor = Integer.parseInt(m.group(3)); else minor = 0; if (m.group(5) != null) micro = Integer.parseInt(m.group(5)); else micro = 0; qualifier = m.group(7); } public int getMajor() { return major; } public int getMinor() { return minor; } public int getMicro() { return micro; } public String getQualifier() { return qualifier; } public int compareTo(Version other) { if (other == this) return 0; if (!(other instanceof Version)) throw new IllegalArgumentException( "Can only compare versions to versions"); Version o = (Version) other; if (major != o.major) return major - o.major; if (minor != o.minor) return minor - o.minor; if (micro != o.micro) return micro - o.micro; int c = 0; if (qualifier != null) c = 1; if (o.qualifier != null) c += 2; switch (c) { case 0: return 0; case 1: return 1; case 2: return -1; } return qualifier.compareTo(o.qualifier); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(major); sb.append("."); sb.append(minor); sb.append("."); sb.append(micro); if (qualifier != null) { sb.append("."); sb.append(qualifier); } return sb.toString(); } public boolean equals(Object ot) { if ( ! (ot instanceof Version)) return false; return compareTo((Version)ot) == 0; } public int hashCode() { return major * 97 ^ minor * 13 ^ micro + (qualifier == null ? 97 : qualifier.hashCode()); } public int get(int i) { switch(i) { case 0 : return major; case 1 : return minor; case 2 : return micro; default: throw new IllegalArgumentException("Version can only get 0 (major), 1 (minor), or 2 (micro)"); } } public static Version parseVersion(String version) { if (version == null) { return LOWEST; } version = version.trim(); if (version.length() == 0) { return LOWEST; } return new Version(version); } public Version getWithoutQualifier() { return new Version(major,minor,micro); } }
package org.sagebionetworks.repo.web.filter; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.*; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sagebionetworks.repo.model.AuthorizationConstants; public class UnexpectedExceptionFilterTest { HttpServletRequest mockRequest; HttpServletResponse mockResponse; FilterChain mockChain; UnexpectedExceptionFilter filter; PrintWriter mockWriter; @Before public void before() throws IOException{ mockRequest = Mockito.mock(HttpServletRequest.class); mockResponse = Mockito.mock(HttpServletResponse.class); mockChain = Mockito.mock(FilterChain.class); mockWriter = Mockito.mock(PrintWriter.class); filter = new UnexpectedExceptionFilter(); when(mockResponse.getWriter()).thenReturn(mockWriter); } @Test public void testNoException() throws IOException, ServletException{ filter.doFilter(mockRequest, mockResponse, mockChain); // The response should not be changed verify(mockResponse, never()).setStatus(anyInt()); verify(mockResponse, never()).getWriter(); } /** * We expect the server to recover from exceptions, so 503 is returned. * @throws IOException * @throws ServletException */ @Test public void testServletException() throws IOException, ServletException{ ServletException error = new ServletException("Exception"); doThrow(error).when(mockChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); filter.doFilter(mockRequest, mockResponse, mockChain); // The response should not be changed verify(mockResponse).setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); verify(mockWriter).println("{\"reason\":\"Server error, try again later: Exception\"}"); } /** * We do not expect the server to recover from errors, so 500 is returned. * @throws IOException * @throws ServletException */ @Test public void testOutOfMemoryError() throws IOException, ServletException{ OutOfMemoryError error = new OutOfMemoryError("Exception"); doThrow(error).when(mockChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); filter.doFilter(mockRequest, mockResponse, mockChain); // The response should not be changed verify(mockResponse).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); verify(mockWriter).println(AuthorizationConstants.REASON_SERVER_ERROR); } }
package internal.org.springframework.content.rest.utils; import java.io.InputStream; import java.io.Serializable; import java.net.URI; import java.util.List; import internal.org.springframework.content.rest.annotations.ContentStoreRestResource; import internal.org.springframework.content.rest.io.AssociatedResource; import internal.org.springframework.content.rest.io.RenderedResource; import org.atteo.evo.inflector.English; import org.springframework.content.commons.annotations.ContentId; import org.springframework.content.commons.renditions.Renderable; import org.springframework.content.commons.repository.ContentStore; import org.springframework.content.commons.repository.Store; import org.springframework.content.commons.storeservice.ContentStoreInfo; import org.springframework.content.commons.storeservice.ContentStoreService; import org.springframework.content.commons.utils.BeanUtils; import org.springframework.content.rest.StoreRestResource; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.util.Assert; import org.springframework.util.MimeType; import org.springframework.util.StringUtils; import static org.springframework.util.StringUtils.trimTrailingCharacter; public final class ContentStoreUtils { private ContentStoreUtils() { } /** * Given a store and a collection of mime types this method will iterate the * mime-types to find a data source of mathcing content. This might be the content itself * or, if the store implements Renderable, a rendition. * * @param store store the store to fetch the content from * @param entity the entity whose content is being fetched * @param property * @param mimeTypes the requested mime types * @return resource plan (a wrapper around the resource to serve and the resolved mimetype) */ @SuppressWarnings("unchecked") public static ResourcePlan resolveResource(ContentStore<Object, Serializable> store, Object entity, Object property, List<MediaType> mimeTypes) { Object entityMimeType = BeanUtils.getFieldWithAnnotation(property != null ? property : entity, org.springframework.content.commons.annotations.MimeType.class); if (entityMimeType == null) return null; MediaType targetMimeType = MediaType.valueOf(entityMimeType.toString()); MediaType.sortBySpecificityAndQuality(mimeTypes); MediaType[] arrMimeTypes = mimeTypes.toArray(new MediaType[] {}); Serializable contentId = (Serializable)BeanUtils.getFieldWithAnnotation(property != null ? property : entity, ContentId.class); Resource r = null; MimeType mimeType = null; for (int i = 0; i < arrMimeTypes.length /*&& content == null*/; i++) { mimeType = arrMimeTypes[i]; if (mimeType.includes(targetMimeType)) { r = ((Store)store).getResource(contentId); r = new AssociatedResource(entity, r); mimeType = targetMimeType; break; } else if (store instanceof Renderable) { InputStream content = ((Renderable<Object>) store).getRendition(property != null ? property : entity, mimeType.toString()); if (content != null) { Resource original = ((Store)store).getResource(contentId); r = new AssociatedResource(entity, original); r = new RenderedResource(content, r); break; } } } if (r != null) { } return new ResourcePlan(r, mimeType); } public static ContentStoreInfo findContentStore(ContentStoreService stores, Class<?> contentEntityClass) { for (ContentStoreInfo info : stores.getStores(ContentStore.class)) { if (contentEntityClass.equals(info.getDomainObjectClass())) return info; } return null; } public static ContentStoreInfo findContentStore(ContentStoreService stores, String store) { for (ContentStoreInfo info : stores.getStores(ContentStore.class)) { if (store.equals(storePath(info))) { return info; } } return null; } public static ContentStoreInfo findStore(ContentStoreService stores, String store) { for (ContentStoreInfo info : stores.getStores(Store.class)) { if (store.equals(storePath(info))) { return info; } } return null; } public static String storePath(ContentStoreInfo info) { Class<?> clazz = info.getInterface(); String path = null; ContentStoreRestResource oldAnnotation = AnnotationUtils.findAnnotation(clazz, ContentStoreRestResource.class); if (oldAnnotation != null) { path = oldAnnotation == null ? null : oldAnnotation.path().trim(); } else { StoreRestResource newAnnotation = AnnotationUtils.findAnnotation(clazz, StoreRestResource.class); path = newAnnotation == null ? null : newAnnotation.path().trim(); } path = StringUtils.hasText(path) ? path : English.plural(StringUtils.uncapitalize(getSimpleName(info))); return path; } public static String getSimpleName(ContentStoreInfo info) { Class<?> clazz = info.getDomainObjectClass(); return clazz != null ? clazz.getSimpleName() : stripStoreName(info.getInterface()); } public static String stripStoreName(Class<?> iface) { return iface.getSimpleName().replaceAll("Store", ""); } public static String propertyName(String fieldName) { String name = stripId(fieldName); name = stripLength(name); return stripMimeType(name); } private static String stripId(String fieldName) { String name = fieldName.replaceAll("_Id", ""); name = name.replaceAll("Id", ""); name = name.replaceAll("_id", ""); return name.replaceAll("id", ""); } private static String stripLength(String fieldName) { String name = fieldName.replaceAll("_Length", ""); name = name.replaceAll("Length", ""); name = name.replaceAll("_length", ""); name = name.replaceAll("length", ""); name = fieldName.replaceAll("_len", ""); name = name.replaceAll("Len", ""); name = name.replaceAll("_len", ""); return name.replaceAll("len", ""); } private static String stripMimeType(String fieldName) { String name = fieldName.replaceAll("_MimeType", ""); name = name.replaceAll("_Mime_Type", ""); name = name.replaceAll("MimeType", ""); name = name.replaceAll("_mimetype", ""); name = name.replaceAll("_mime_type", ""); name = name.replaceAll("mimetype", ""); name = fieldName.replaceAll("_ContentType", ""); name = name.replaceAll("_Content_Type", ""); name = name.replaceAll("ContentType", ""); name = name.replaceAll("_contenttype", ""); name = name.replaceAll("_content_type", ""); return name.replaceAll("contenttype", ""); } public static String storeLookupPath(String lookupPath, URI baseUri) { Assert.notNull(lookupPath, "Lookup path must not be null!"); // Temporary fix for SPR-13455 lookupPath = lookupPath.replaceAll(" lookupPath = trimTrailingCharacter(lookupPath, '/'); if (baseUri.isAbsolute()) { throw new UnsupportedOperationException("Absolute BaseUri is not supported"); } String uri = baseUri.toString(); if (!StringUtils.hasText(uri)) { return lookupPath; } uri = uri.startsWith("/") ? uri : "/".concat(uri); return lookupPath.startsWith(uri) ? lookupPath.substring(uri.length(), lookupPath.length()) : null; } public static class ResourcePlan { private Resource resource; private MimeType mimeType; public ResourcePlan(Resource r, MimeType mimeType) { this.resource = r; this.mimeType = mimeType; } public Resource getResource() { return resource; } public MimeType getMimeType() { return mimeType; } } }
package com.creativemd.littletiles.common.structure.type.premade.signal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import com.creativemd.creativecore.common.utils.math.RotationUtils; import com.creativemd.creativecore.common.utils.math.VectorUtils; import com.creativemd.creativecore.common.utils.math.box.AlignedBox; import com.creativemd.creativecore.common.utils.mc.ColorUtils; import com.creativemd.creativecore.common.utils.type.HashMapList; import com.creativemd.creativecore.common.utils.type.Pair; import com.creativemd.littletiles.LittleTiles; import com.creativemd.littletiles.client.render.tile.LittleRenderBox; import com.creativemd.littletiles.common.structure.LittleStructure; import com.creativemd.littletiles.common.structure.attribute.LittleStructureAttribute; import com.creativemd.littletiles.common.structure.exception.CorruptedConnectionException; import com.creativemd.littletiles.common.structure.exception.NotYetConnectedException; import com.creativemd.littletiles.common.structure.registry.LittleStructureType; import com.creativemd.littletiles.common.structure.signal.component.ISignalComponent; import com.creativemd.littletiles.common.structure.signal.component.ISignalStructureBase; import com.creativemd.littletiles.common.structure.signal.component.SignalComponentType; import com.creativemd.littletiles.common.structure.signal.network.SignalNetwork; import com.creativemd.littletiles.common.structure.type.premade.LittleStructurePremade; import com.creativemd.littletiles.common.tile.LittleTile; import com.creativemd.littletiles.common.tile.math.box.LittleAbsoluteBox; import com.creativemd.littletiles.common.tile.math.box.LittleBox; import com.creativemd.littletiles.common.tile.math.vec.LittleVec; import com.creativemd.littletiles.common.tile.parent.IParentTileList; import com.creativemd.littletiles.common.tile.parent.IStructureTileList; import com.creativemd.littletiles.common.tile.preview.LittlePreviews; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.util.grid.LittleGridContext; import com.creativemd.littletiles.common.util.vec.SurroundingBox; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumFacing.AxisDirection; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public abstract class LittleSignalCableBase extends LittleStructurePremade implements ISignalStructureBase { public static final int DEFAULT_CABLE_COLOR = -13619152; private SignalNetwork network; public int color; protected LittleConnectionFace[] faces; public LittleSignalCableBase(LittleStructureType type, IStructureTileList mainBlock) { super(type, mainBlock); this.faces = new LittleConnectionFace[getNumberOfConnections()]; } @Override public boolean compatible(ISignalStructureBase other) { if (ISignalStructureBase.super.compatible(other)) { if (other.getType() == SignalComponentType.TRANSMITTER && this.getType() == SignalComponentType.TRANSMITTER) return other.getColor() == DEFAULT_CABLE_COLOR || this.getColor() == DEFAULT_CABLE_COLOR || getColor() == other.getColor(); return true; } return false; } @Override public boolean hasStructureColor() { return true; } @Override public int getStructureColor() { return color; } @Override public int getDefaultColor() { return DEFAULT_CABLE_COLOR; } @Override public void paint(int color) { this.color = color; } @Override public int getColor() { return color; } @Override public SignalNetwork getNetwork() { return network; } @Override public void setNetwork(SignalNetwork network) { this.network = network; } @Override public World getStructureWorld() { return getWorld(); } @Override protected void loadFromNBTExtra(NBTTagCompound nbt) { int[] result = nbt.getIntArray("faces"); if (result != null && result.length == getNumberOfConnections() * 3) { for (int i = 0; i < faces.length; i++) { int distance = result[i * 3]; if (distance < 0) faces[i] = null; else { faces[i] = new LittleConnectionFace(); faces[i].distance = distance; faces[i].context = LittleGridContext.get(result[i * 3 + 1]); faces[i].oneSidedRenderer = result[i * 3 + 2] == 1; } } } else if (result != null && result.length == getNumberOfConnections() * 2) for (int i = 0; i < faces.length; i++) { int distance = result[i * 2]; if (distance < 0) faces[i] = null; else { faces[i] = new LittleConnectionFace(); faces[i].distance = distance; faces[i].context = LittleGridContext.get(result[i * 2 + 1]); } } if (nbt.hasKey("color")) color = nbt.getInteger("color"); else color = DEFAULT_CABLE_COLOR; } @Override protected void writeToNBTExtraInternal(NBTTagCompound nbt, boolean preview) { super.writeToNBTExtraInternal(nbt, preview); if (!preview && faces != null) { int[] result = new int[getNumberOfConnections() * 3]; for (int i = 0; i < faces.length; i++) { if (faces[i] != null) { result[i * 3] = faces[i].distance; result[i * 3 + 1] = faces[i].context.size; result[i * 3 + 2] = faces[i].oneSidedRenderer ? 1 : 0; } else { result[i * 3] = -1; result[i * 3 + 1] = 0; result[i * 3 + 2] = 0; } } nbt.setIntArray("faces", result); } if (color != -1) nbt.setInteger("color", color); } @Override protected void writeToNBTExtra(NBTTagCompound nbt) {} public abstract EnumFacing getFacing(int index); public abstract int getIndex(EnumFacing facing); @Override public int getBandwidth() { return ((LittleStructureTypeNetwork) type).bandwidth; } public int getNumberOfConnections() { return ((LittleStructureTypeNetwork) type).numberOfConnections; } @Override public boolean connect(EnumFacing facing, ISignalStructureBase base, LittleGridContext context, int distance, boolean oneSidedRenderer) { int index = getIndex(facing); if (faces[index] != null) { if (faces[index].getConnection() == base) return false; faces[index].disconnect(facing); } else faces[index] = new LittleConnectionFace(); faces[index].connect(base, context, distance, oneSidedRenderer); return true; } @Override public void disconnect(EnumFacing facing, ISignalStructureBase base) { int index = getIndex(facing); if (faces[index] != null) { faces[index] = null; updateStructure(); } } @Override public void neighbourChanged() { try { load(); if (getWorld().isRemote) return; LittleAbsoluteBox box = getSurroundingBox().getAbsoluteBox(); boolean changed = false; for (int i = 0; i < faces.length; i++) { EnumFacing facing = getFacing(i); LittleConnectResult result = checkConnection(facing, box); if (result != null) { changed |= this.connect(facing, result.base, result.context, result.distance, result.oneSidedRenderer); changed |= result.base.connect(facing.getOpposite(), this, result.context, result.distance, result.oneSidedRenderer); } else { if (faces[i] != null) { faces[i].disconnect(facing); changed = true; } faces[i] = null; } } if (changed) findNetwork(); } catch (CorruptedConnectionException | NotYetConnectedException e) {} } @Override public Iterator<ISignalStructureBase> connections() { try { load(); return new Iterator<ISignalStructureBase>() { LittleAbsoluteBox box = getSurroundingBox().getAbsoluteBox(); int index = searchForNextIndex(0); int searchForNextIndex(int index) { while (index < faces.length && (faces[index] == null || !faces[index].verifyConnect(getFacing(index), box))) { faces[index] = null; index++; } return index; } @Override public boolean hasNext() { return index < faces.length && faces[index] != null; } @Override public ISignalStructureBase next() { ISignalStructureBase next = faces[index].getConnection(); this.index = searchForNextIndex(index + 1); return next; } }; } catch (CorruptedConnectionException | NotYetConnectedException e) {} return new Iterator<ISignalStructureBase>() { @Override public boolean hasNext() { return false; } @Override public ISignalStructureBase next() { return null; } }; } protected LittleConnectResult checkConnection(World world, LittleAbsoluteBox box, EnumFacing facing, BlockPos pos) throws ConnectionException { try { TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { TileEntityLittleTiles te = (TileEntityLittleTiles) tileEntity; LittleTile closest = null; IParentTileList parent = null; int minDistance = 0; for (Pair<IParentTileList, LittleTile> pair : te.allTiles()) { LittleTile tile = pair.value; if (!pair.key.isStructureChild(this)) { int distance = box.getDistanceIfEqualFromOneSide(facing, tile.getBox(), pair.key.getPos(), pair.key.getContext()); if (distance < 0) continue; if (closest == null || minDistance > distance) { closest = tile; parent = pair.key; minDistance = distance; } } } if (closest != null && parent.isStructure()) { LittleStructure structure = parent.getStructure(); if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).compatible(this)) { box = box.createBoxFromFace(facing, minDistance); HashMapList<BlockPos, LittleBox> boxes = box.splitted(); for (Entry<BlockPos, ArrayList<LittleBox>> entry : boxes.entrySet()) { TileEntity toSearchIn = world.getTileEntity(entry.getKey()); if (toSearchIn instanceof TileEntityLittleTiles) { TileEntityLittleTiles parsedSearch = (TileEntityLittleTiles) toSearchIn; LittleBox toCheck = entry.getValue().get(0); try { parsedSearch.convertToAtMinimum(box.getContext()); if (parsedSearch.getContext().size > box.getContext().size) toCheck.convertTo(box.getContext(), parsedSearch.getContext()); if (!parsedSearch.isSpaceForLittleTile(toCheck)) throw new ConnectionException("No space"); } finally { parsedSearch.convertToSmallest(); } } else if (!world.getBlockState(entry.getKey()).getMaterial().isReplaceable()) throw new ConnectionException("Block in the way"); } ISignalStructureBase base = (ISignalStructureBase) structure; if (base.canConnect(facing.getOpposite())) return new LittleConnectResult(base, box.getContext(), minDistance, false); throw new ConnectionException("Side is invalid"); } else if (closest != null) throw new ConnectionException("Tile in the way"); } } else if (tileEntity instanceof ISignalStructureBase && ((ISignalStructureBase) tileEntity).compatible(this)) { Axis axis = facing.getAxis(); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; LittleGridContext context = box.context; int minDistance = positive ? 0 - context.toGrid(VectorUtils.get(axis, box.pos) - VectorUtils.get(axis, pos)) - box.box.getMax(axis) : box.box .getMin(axis) - (context.size - context.toGrid(VectorUtils.get(axis, box.pos) - VectorUtils.get(axis, pos))); box = box.createBoxFromFace(facing, minDistance); HashMapList<BlockPos, LittleBox> boxes = box.splitted(); for (Entry<BlockPos, ArrayList<LittleBox>> entry : boxes.entrySet()) { TileEntity toSearchIn = world.getTileEntity(entry.getKey()); if (toSearchIn instanceof TileEntityLittleTiles) { TileEntityLittleTiles parsedSearch = (TileEntityLittleTiles) toSearchIn; LittleBox toCheck = entry.getValue().get(0); try { parsedSearch.convertToAtMinimum(box.getContext()); if (parsedSearch.getContext().size > box.getContext().size) toCheck.convertTo(box.getContext(), parsedSearch.getContext()); if (!parsedSearch.isSpaceForLittleTile(toCheck)) throw new ConnectionException("No space"); } finally { parsedSearch.convertToSmallest(); } } else if (!world.getBlockState(entry.getKey()).getMaterial().isReplaceable()) throw new ConnectionException("Block in the way"); } ISignalStructureBase base = (ISignalStructureBase) tileEntity; if (base.canConnect(facing.getOpposite())) return new LittleConnectResult(base, box.getContext(), minDistance, true); throw new ConnectionException("Side is invalid"); } } catch (CorruptedConnectionException | NotYetConnectedException e) {} return null; } public LittleConnectResult checkConnection(EnumFacing facing, LittleAbsoluteBox box) { if (!canConnect(facing)) return null; BlockPos pos = box.getMinPos(); Axis axis = facing.getAxis(); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; if (positive) pos = VectorUtils.set(pos, box.getMaxPos(axis), axis); World world = getWorld(); try { if (positive ? box.getMaxGridFrom(axis, pos) < box.getContext().size : box.getMinGridFrom(axis, pos) > 0) { LittleConnectResult result = checkConnection(world, box, facing, pos); if (result != null) return result; } return checkConnection(world, box, facing, pos.offset(facing)); } catch (ConnectionException e) { return null; } } @Override @SideOnly(Side.CLIENT) public void getRenderingCubes(BlockPos pos, BlockRenderLayer layer, List<LittleRenderBox> cubes) { if (layer != BlockRenderLayer.SOLID) return; try { SurroundingBox box = getSurroundingBox(); LittleVec min = box.getMinPosOffset(); LittleVec max = box.getSize(); max.add(min); LittleBox overallBox = new LittleBox(min, max); BlockPos difference = pos.subtract(box.getMinPos()); overallBox.sub(box.getContext().toGrid(difference.getX()), box.getContext().toGrid(difference.getY()), box.getContext().toGrid(difference.getZ())); render(box, overallBox, cubes); } catch (CorruptedConnectionException | NotYetConnectedException e) {} } @SideOnly(Side.CLIENT) public void renderFace(EnumFacing facing, LittleGridContext context, LittleBox renderBox, int distance, Axis axis, Axis one, Axis two, boolean positive, boolean oneSidedRenderer, List<LittleRenderBox> cubes) { if (positive) { renderBox.setMin(axis, renderBox.getMax(axis)); renderBox.setMax(axis, renderBox.getMax(axis) + distance); } else { renderBox.setMax(axis, renderBox.getMin(axis)); renderBox.setMin(axis, renderBox.getMin(axis) - distance); } LittleRenderBox cube = renderBox.getRenderingCube(context, LittleTiles.singleCable, axis.ordinal()); if (!oneSidedRenderer) { if (positive) cube.setMax(axis, cube.getMin(axis) + cube.getSize(axis) / 2); else cube.setMin(axis, cube.getMax(axis) - cube.getSize(axis) / 2); } cube.color = color; cube.keepVU = true; cube.allowOverlap = true; float shrink = 0.18F; float shrinkOne = cube.getSize(one) * shrink; float shrinkTwo = cube.getSize(two) * shrink; cube.setMin(one, cube.getMin(one) + shrinkOne); cube.setMax(one, cube.getMax(one) - shrinkOne); cube.setMin(two, cube.getMin(two) + shrinkTwo); cube.setMax(two, cube.getMax(two) - shrinkTwo); cubes.add(cube); } @SideOnly(Side.CLIENT) public void render(SurroundingBox box, LittleBox overallBox, List<LittleRenderBox> cubes) { for (int i = 0; i < faces.length; i++) { if (faces[i] == null) continue; int distance = faces[i].distance; EnumFacing facing = getFacing(i); Axis axis = facing.getAxis(); Axis one = RotationUtils.getOne(axis); Axis two = RotationUtils.getTwo(axis); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; LittleGridContext context = faces[i].context; LittleBox renderBox = overallBox.copy(); if (box.getContext().size > context.size) { distance *= box.getContext().size / context.size; context = box.getContext(); } else if (context.size > box.getContext().size) renderBox.convertTo(box.getContext(), context); renderFace(facing, context, renderBox, distance, axis, one, two, positive, faces[i].oneSidedRenderer, cubes); } } @Override public void onStructureDestroyed() { if (network != null) if (network.remove(this)) { for (int i = 0; i < faces.length; i++) { if (faces[i] != null) { ISignalStructureBase connection = faces[i].connection; faces[i].disconnect(getFacing(i)); connection.findNetwork(); } } } } @Override public void unload() { super.unload(); if (network != null) network.unload(this); } public class LittleConnectionFace { public ISignalStructureBase connection; public int distance; public LittleGridContext context; public boolean oneSidedRenderer; public LittleConnectionFace() { } public void disconnect(EnumFacing facing) { if (connection != null) connection.disconnect(facing.getOpposite(), LittleSignalCableBase.this); if (hasNetwork()) getNetwork().remove(connection); connection = null; updateStructure(); } public void connect(ISignalStructureBase connection, LittleGridContext context, int distance, boolean oneSidedRenderer) { if (this.connection != null) throw new RuntimeException("Cannot connect until old connection is closed"); this.oneSidedRenderer = oneSidedRenderer; if (hasNetwork()) getNetwork().add(connection); this.connection = connection; this.context = context; this.distance = distance; updateStructure(); } public boolean verifyConnect(EnumFacing facing, LittleAbsoluteBox box) { if (connection != null) return true; LittleConnectResult result = checkConnection(facing, box); if (result != null) { this.connection = result.base; this.context = result.context; this.distance = result.distance; return true; } return false; } public ISignalStructureBase getConnection() { return connection; } } public static class LittleConnectResult { public final ISignalStructureBase base; public final LittleGridContext context; public final int distance; public final boolean oneSidedRenderer; public LittleConnectResult(ISignalStructureBase base, LittleGridContext context, int distance, boolean oneSidedRenderer) { this.base = base; this.context = context; this.distance = distance; this.oneSidedRenderer = oneSidedRenderer; } } public static class ConnectionException extends Exception { public ConnectionException(String msg) { super(msg); } } public static abstract class LittleStructureTypeNetwork extends LittleStructureTypePremade implements ISignalComponent { public final int bandwidth; public final int numberOfConnections; public LittleStructureTypeNetwork(String id, String category, Class<? extends LittleStructure> structureClass, int attribute, String modid, int bandwidth, int numberOfConnections) { super(id, category, structureClass, attribute | LittleStructureAttribute.NEIGHBOR_LISTENER, modid); this.bandwidth = bandwidth; this.numberOfConnections = numberOfConnections; } public int getColor(LittlePreviews previews) { if (previews.structureNBT.hasKey("color")) return previews.structureNBT.getInteger("color"); return DEFAULT_CABLE_COLOR; } @Override @SideOnly(Side.CLIENT) public List<LittleRenderBox> getPositingCubes(World world, BlockPos pos, ItemStack stack) { try { List<LittleRenderBox> cubes = new ArrayList<>(); for (int i = 0; i < 6; i++) { EnumFacing facing = EnumFacing.VALUES[i]; Axis axis = facing.getAxis(); TileEntity tileEntity = world.getTileEntity(pos.offset(facing)); if (tileEntity instanceof TileEntityLittleTiles) { for (LittleStructure structure : ((TileEntityLittleTiles) tileEntity).loadedStructures()) { if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).getBandwidth() == bandwidth && ((ISignalStructureBase) structure) .canConnect(facing.getOpposite())) { LittleRenderBox cube = new LittleRenderBox(new AlignedBox(structure.getSurroundingBox().getAABB() .offset(-tileEntity.getPos().getX(), -tileEntity.getPos().getY(), -tileEntity.getPos().getZ())), null, Blocks.AIR, 0); cube.setMin(axis, 0); cube.setMax(axis, 1); cubes.add(cube); } } } } TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { for (LittleStructure structure : ((TileEntityLittleTiles) tileEntity).loadedStructures()) { if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).getBandwidth() == bandwidth) { AxisAlignedBB box = structure.getSurroundingBox().getAABB() .offset(-tileEntity.getPos().getX(), -tileEntity.getPos().getY(), -tileEntity.getPos().getZ()); LittleRenderBox cube; if (((ISignalStructureBase) structure).canConnect(EnumFacing.WEST) || ((ISignalStructureBase) structure).canConnect(EnumFacing.EAST)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.WEST)) cube.setMin(Axis.X, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.EAST)) cube.setMax(Axis.X, 1); cubes.add(cube); } if (((ISignalStructureBase) structure).canConnect(EnumFacing.DOWN) || ((ISignalStructureBase) structure).canConnect(EnumFacing.UP)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.DOWN)) cube.setMin(Axis.Y, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.UP)) cube.setMax(Axis.Y, 1); cubes.add(cube); } if (((ISignalStructureBase) structure).canConnect(EnumFacing.NORTH) || ((ISignalStructureBase) structure).canConnect(EnumFacing.SOUTH)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.NORTH)) cube.setMin(Axis.Z, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.SOUTH)) cube.setMax(Axis.Z, 1); cubes.add(cube); } } } } if (cubes.isEmpty()) return null; for (LittleRenderBox cube : cubes) cube.color = ColorUtils.RGBAToInt(255, 255, 255, 90); return cubes; } catch (CorruptedConnectionException | NotYetConnectedException e) {} return null; } @Override public World getWorld() { return null; } @Override public LittleStructure getStructure() { return null; } } }
package com.db.data.format; public class RiffChunkHeader { /** * The 4 byte chunk identifier. "JUNK" for junk chunks. */ protected String mId; /** * The size of the chunk. */ protected long mChunkSize; /** * Whether or not this chunk is valid. */ protected boolean mValid; /** * The header size for a RIFF chunk. */ public static final int CHUNK_HEADER_SIZE = 8; /** * Constructs a Riff Chunk Header with default values. */ public RiffChunkHeader() { this(null, CHUNK_HEADER_SIZE); } /** * Constructs a Riff Chunk Header with the passed parameters. * * @param id the identifier of the chunk. */ public RiffChunkHeader(String id) { this(id, CHUNK_HEADER_SIZE); } /** * Constructs a Riff Chunk Header with the passed parameters. * * @param id the identifier of the chunk. * @param size the size of the chunk. */ public RiffChunkHeader(String id, int size) { if(id == null || id.length() != 4) { id = ""; } else { mId = id; } mChunkSize = size; mValid = true; } /** * Converts size into a 4 byte array. The array is ordered from least * significant byte to most. * * @return a 4 byte array representing the size. */ protected byte[] convertSizeToBytes() { byte[] size = new byte[4]; // convert to 4 bytes, convert most significant byte first (as // the last byte) for(int i = 3; i >= 0; i { size[i] = (byte)(((mChunkSize >> (i * 8))) & 0xFF); } return size; } /** * Converts a 4 bytes from an array into an integer size. The 4 bytes are * ordered from least significant byte to most. * * @param b the byte array to read from. * @param offset the offset to start reading from. * @param length number of valid bytes in the buffer following the * offset. * * @return true if successful, false if not. */ protected boolean convertBytesToSize(byte[] b, int offset, int length) { boolean rval = false; if(b != null && length > 3) { mChunkSize = 0; // convert most significant byte first (it is the last byte) // and then shift it left for(int i = 3; i >= 0; i { mChunkSize |= ((b[offset + i] & 0xFF) << (i * 8)); } rval = true; } return rval; } /** * Converts the chunk header into an 8 byte array. * * @return the chunk header into an 8 byte array. */ public byte[] convertToBytes() { byte[] chunk = new byte[CHUNK_HEADER_SIZE]; if(mId.length() == 4) { chunk[0] = (byte)mId.charAt(0); chunk[1] = (byte)mId.charAt(1); chunk[2] = (byte)mId.charAt(2); chunk[3] = (byte)mId.charAt(3); } byte[] size = convertSizeToBytes(); chunk[4] = size[0]; chunk[5] = size[1]; chunk[6] = size[2]; chunk[7] = size[3]; return chunk; } /** * Converts the chunk header from a byte array with at least 8 bytes. * * @param b the byte array to convert from. * @param offset the offset to start converting from. * @param length the number of valid bytes in the buffer following the * offset. * * @return true if successful, false if not. */ public boolean convertFromBytes(byte[] b, int offset, int length) { boolean rval = false; if(b != null && length >= CHUNK_HEADER_SIZE) { mId = ""; mId += (char)b[offset]; mId += (char)b[offset + 1]; mId += (char)b[offset + 2]; mId += (char)b[offset + 3]; rval = true; rval &= convertBytesToSize(b, offset + 4, length); } setValid(rval); return rval; } /** * Sets the 4 byte identifier for this chunk if the passed string is * 4 characters long. * * @param id the identifier to set. * * @return true if set, false if not. */ public boolean setIdentifier(String id) { boolean rval = false; if(id != null && id.length() == 4) { mId = id; rval = true; } return rval; } /** * Gets the 4 byte identifier for this chunk. * * @return the chunk identifier. */ public String getIdentifier() { return mId; } /** * Sets the size. This is the size of the chunk. * * @param size the size to use. */ public void setChunkSize(long size) { mChunkSize = size; } /** * Returns the chunk size as reported in the chunk. * * @return the chunk size. */ public long getChunkSize() { return mChunkSize; } /** * Returns whether or not this chunk is valid. * * @return true if valid, false if not. */ public boolean isValid() { return mValid; } /** * Sets whether or not this chunk is valid. * * @param valid true to set to valid, false to set to invalid. */ public void setValid(boolean valid) { mValid = valid; } }
package com.psddev.dari.db; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.TypeDefinition; /** Description of how field methods can be indexed in a state. */ @ObjectField.Embedded public class ObjectMethod extends ObjectField { public static final String JAVA_METHOD_NAME_KEY = "java.method"; private static final String HAS_SINGLE_OBJECT_METHOD_PARAMETER_EXTRA = "dari.objectMethod.hasSingleParam"; @InternalName(JAVA_METHOD_NAME_KEY) private String javaMethodName; public ObjectMethod(ObjectMethod method) { super(method); javaMethodName = method.getJavaMethodName(); } public ObjectMethod(ObjectStruct parent, Map<String, Object> definition) { super(parent, definition); if (definition == null) { return; } javaMethodName = (String) definition.remove(JAVA_METHOD_NAME_KEY); } public String getJavaMethodName() { return javaMethodName; } public void setJavaMethodName(String javaMethodName) { this.javaMethodName = javaMethodName; } public List<String> getJavaParameterTypeNames() { List<String> javaParameterTypeNames = new ArrayList<>(); Method method = getJavaMethod(ObjectUtils.getClassByName(getJavaDeclaringClassName())); if (method != null) { for (Class<?> cls : method.getParameterTypes()) { javaParameterTypeNames.add(cls.getName()); } } return Collections.unmodifiableList(javaParameterTypeNames); } public boolean hasSingleObjectMethodParameter() { Object hasSingleParam = getState().getExtra(HAS_SINGLE_OBJECT_METHOD_PARAMETER_EXTRA); if (!(hasSingleParam instanceof Boolean)) { List<String> params = getJavaParameterTypeNames(); hasSingleParam = params.size() == 1 && ObjectMethod.class.getName().equals(params.get(0)); getState().getExtras().put(HAS_SINGLE_OBJECT_METHOD_PARAMETER_EXTRA, hasSingleParam); } return (Boolean) hasSingleParam; } public Method getJavaMethod(Class<?> objectClass) { if (getJavaMethodName() == null) { return null; } Class<?> declaringClass = ObjectUtils.getClassByName(getJavaDeclaringClassName()); return declaringClass != null && declaringClass.isAssignableFrom(objectClass) ? javaMethodCache.getUnchecked(objectClass) : null; } private final transient LoadingCache<Class<?>, Method> javaMethodCache = CacheBuilder .newBuilder() .build(new CacheLoader<Class<?>, Method>() { @Override public Method load(Class<?> objectClass) { return TypeDefinition.getInstance(objectClass).getMethod(getJavaMethodName()); } }); /** Returns the display name. */ public String getDisplayName() { if (!ObjectUtils.isBlank(displayName)) { return displayName; } String name = getJavaMethodName(); if (ObjectUtils.isBlank(name)) { name = getInternalName(); } int dotAt = name.lastIndexOf('.'); if (dotAt > -1) { name = name.substring(dotAt + 1); } int dollarAt = name.lastIndexOf('$'); if (dollarAt > -1) { name = name.substring(dollarAt + 1); } Matcher nameMatcher = StringUtils.getMatcher(name, "^(get|(is|has))([^a-z])(.*)$"); if (nameMatcher.matches()) { name = ObjectUtils.isBlank(nameMatcher.group(2)) ? nameMatcher.group(3).toLowerCase(Locale.ENGLISH) + nameMatcher.group(4) : name; } name = StringUtils.toLabel(name); if (!name.endsWith("?") && BOOLEAN_TYPE.equals(getInternalItemType())) { name += "?"; } return name; } public void recalculate(State state) { if (state == null || state.getType() == null) { return; } Database db = state.getDatabase(); Set<ObjectIndex> indexes = findIndexes(state.getType()); db.recalculate(state, indexes.toArray(new ObjectIndex[indexes.size()])); } public Set<ObjectIndex> findIndexes(ObjectType type) { Set<ObjectIndex> indexes = new HashSet<ObjectIndex>(); for (ObjectIndex idx : type.getIndexes()) { if (idx.getFields().contains(getInternalName())) { indexes.add(idx); } } for (ObjectIndex idx : type.getEnvironment().getIndexes()) { if (idx.getFields().contains(getInternalName())) { indexes.add(idx); } } return indexes; } @Deprecated public static final String JAVA_PARAMETER_TYPES_KEY = "java.parameterTypes"; @Deprecated public void setJavaParameterTypeNames(List<String> ignored) { } }
package com.msc.serverbrowser.util; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.StringTokenizer; import com.msc.serverbrowser.data.Player; public class SampQuery implements AutoCloseable { private static final String PACKET_GET_SERVERINFO = "i"; private static final String PACKET_GET_RULES = "r"; private static final String PACKET_MIRROR_CHARACTERS = "p0101"; private static final String PACKET_GET_BASIC_PLAYERINFO = "c"; private final DatagramSocket socket; private final InetAddress server; private final String serverAddress; private final int serverPort; /** * Configures the socket and the address that will be used for doing the queries. * * @param serverAddress * hostname / ip * @param serverPort * port * @param timeout * the maximum time, that the socket tries connecting * @throws SocketException * Thrown if the connection is closed unexpectedly / has never beenopened properly * @throws UnknownHostException * if the host is unknown */ public SampQuery(final String serverAddress, final int serverPort, final int timeout) throws SocketException, UnknownHostException { this.serverAddress = serverAddress; this.server = InetAddress.getByName(serverAddress); socket = new DatagramSocket(); socket.setSoTimeout(timeout); this.serverPort = serverPort; checkConnection(); } /** * Configures the socket and the address. * * @param serverAddress * hostname / ip * @param serverPort * port * @throws SocketException * if the connection couldn't be established * @throws UnknownHostException * if the host is unknown */ public SampQuery(final String serverAddress, final int serverPort) throws SocketException, UnknownHostException { this(serverAddress, serverPort, 1250); } /** * Returns whether a successful connection was made. */ private void checkConnection() throws SocketException { // TODO(MSC) Check if server deactivated querying, since this will only tell if // the server // is online, but will still work with servers that have deactivated querying send(PACKET_MIRROR_CHARACTERS); final String reply = receive(); // Removed the checks if the reply was valid, i think its not even necessary if (Objects.isNull(reply)) { throw new SocketException("Couldn't connect to Server"); } } @Override public void close() throws SocketException { socket.close(); } /** * Returns a String array, containing information about the server. * * @return String[]:<br /> * Index 0: password (0 or 1)<br /> * Index 1: players<br /> * Index 2: maxplayers<br /> * Index 3: hostname<br /> * Index 4: gamemode<br /> * Index 5: language */ public Optional<String[]> getBasicServerInfo() { if (send(PACKET_GET_SERVERINFO)) { final byte[] reply = receiveBytes(); if (Objects.nonNull(reply)) { final ByteBuffer buffer = wrapReply(reply); final String[] serverInfo = new String[6]; final String encoding = Encoding.getEncoding(reply).orElse(StandardCharsets.UTF_8.toString()); // Password Yes / No final short password = buffer.get(); serverInfo[0] = String.valueOf(password); // Players connected final short players = buffer.getShort(); serverInfo[1] = String.valueOf(players); // Max Players final short maxPlayers = buffer.getShort(); serverInfo[2] = String.valueOf(maxPlayers); // Hostname int len = buffer.getInt(); final byte[] hostname = new byte[len]; for (int i = 0; i < len; i++) { hostname[i] = buffer.get(); } serverInfo[3] = Encoding.decodeUsingCharsetIfPossible(hostname, encoding); // Gamemode len = buffer.getInt(); final byte[] gamemode = new byte[len]; for (int i = 0; i < len; i++) { gamemode[i] = buffer.get(); } serverInfo[4] = Encoding.decodeUsingCharsetIfPossible(gamemode, encoding); // Language len = buffer.getInt(); final byte[] language = new byte[len]; for (int i = 0; i < len; i++) { language[i] = buffer.get(); } serverInfo[5] = Encoding.decodeUsingCharsetIfPossible(language, encoding); return Optional.of(serverInfo); } } return Optional.empty(); } /** * Returns an {@link Optional} of a {@link List} of {@link Player} objects, containing all * players on the server. * * @return an {@link Optional} containg a {@link List} of {@link Player Players} or an empty * {@link Optional} incase the query failed. */ public Optional<List<Player>> getBasicPlayerInfo() { List<Player> players = null; if (send(PACKET_GET_BASIC_PLAYERINFO)) { final byte[] reply = receiveBytes(); if (Objects.nonNull(reply)) { final ByteBuffer buffer = wrapReply(reply); final int numberOfPlayers = buffer.getShort(); players = new ArrayList<>(); for (int i = 0; i < numberOfPlayers; i++) { final byte len = buffer.get(); final byte[] playerName = new byte[len]; for (int j = 0; j < len; j++) { playerName[j] = buffer.get(); } players.add(new Player(new String(playerName), buffer.getInt())); } } } return Optional.ofNullable(players); } /** * Returns a Map containing all server rules. The Key is always the rules name. * * @return a Map containing all server rules */ public Optional<Map<String, String>> getServersRules() { if (send(PACKET_GET_RULES)) { final byte[] reply = receiveBytes(); if (Objects.nonNull(reply)) { final ByteBuffer buffer = wrapReply(reply); final Map<String, String> rules = new HashMap<>(); final short ruleCount = buffer.getShort(); for (int i = 0; i < ruleCount; i++) { int len = buffer.get(); final byte[] ruleName = new byte[len]; for (int j = 0; j < len; j++) { ruleName[j] = buffer.get(); } len = buffer.get(); final byte[] ruleValue = new byte[len]; for (int j = 0; j < len; j++) { ruleValue[j] = buffer.get(); } rules.put(new String(ruleName), new String(ruleValue)); } return Optional.of(rules); } } return Optional.empty(); } /** * <p> * Wraps the received bytes in a {@link ByteBuffer} for easier usage. * </p> * Contents of the byte array: * <ul> * <li>Byte 0 - 3: "SAMP"</li> * <li>Byte 4 - 7: IP</li> * <li>Byte 8 - 9: Port</li> * <li>Byte 10: Message Type</li> * <li>Byte 11+: Data</li> * </ul> * <p> * Because the Data contains multiple informations that we do not care for as of now, we are * setting the byte buffers initial position to eleven. * </p> * * @param the * byte array to be wrapped * @return the {@link ByteBuffer} that wraps the byte array */ private static ByteBuffer wrapReply(final byte[] reply) { final ByteBuffer buffer = ByteBuffer.wrap(reply); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.position(11); return buffer; } /** * Returns the server's ping. * * @return ping */ public long getPing() { final long beforeSend = System.currentTimeMillis(); send(PACKET_MIRROR_CHARACTERS); receiveBytes(); return System.currentTimeMillis() - beforeSend; } private Optional<DatagramPacket> assemblePacket(final String type) { try { final StringTokenizer tok = new StringTokenizer(serverAddress, "."); final StringBuffer packetData = new StringBuffer("SAMP"); while (tok.hasMoreTokens()) { packetData.append((char) Integer.parseInt(tok.nextToken())); } packetData .append((char) (serverPort & 0xFF)) .append((char) (serverPort >> 8 & 0xFF)) .append(type); final byte[] data = packetData.toString().getBytes(StandardCharsets.US_ASCII); final DatagramPacket sendPacket = new DatagramPacket(data, data.length, server, serverPort); return Optional.ofNullable(sendPacket); } catch (@SuppressWarnings("unused") final NumberFormatException exception) { return Optional.empty(); } } /** * Sends a packet to te server * * @param packet * that is supposed to be sent */ private boolean send(final String packetType) { final Optional<DatagramPacket> packet = assemblePacket(packetType); if (packet.isPresent()) { try { socket.send(packet.get()); return true; } catch (@SuppressWarnings("unused") final IOException exception) { return false; } } return false; } /** * Reseives a package from the server * * @return the package data as a string */ private String receive() { final byte[] bytes = receiveBytes(); if (Objects.nonNull(bytes)) { return new String(bytes); } return null; } /** * Reseives a package from the server * * @return the package data as a byte array or null on fail */ private byte[] receiveBytes() { try { // This is enough for at least 100 players information. final byte[] receivedData = new byte[14000]; final DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length); socket.receive(receivedPacket); return receivedPacket.getData(); } catch (@SuppressWarnings("unused") final IOException exception) { return null; } } }
package org.jetel.component; //import org.w3c.dom.Node; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.graph.Node; import org.jetel.graph.TransformationGraph; import org.jetel.graph.distribution.NodeDistribution; import org.jetel.plugin.Extension; import org.jetel.plugin.PluginDescriptor; import org.jetel.plugin.Plugins; import org.jetel.util.property.ComponentXMLAttributes; import org.w3c.dom.Element; /** * Description of the Class * * @author dpavlis * @since May 27, 2002 * @revision $Revision$ */ public class ComponentFactory { private static Log logger = LogFactory.getLog(ComponentFactory.class); private final static String NAME_OF_STATIC_LOAD_FROM_XML = "fromXML"; private final static Class[] PARAMETERS_FOR_METHOD = new Class[] { TransformationGraph.class, Element.class }; private final static Map<String, ComponentDescription> componentMap = new HashMap<String, ComponentDescription>(); public static void init() { //ask plugin framework for components List<Extension> componentExtensions = Plugins.getExtensions(ComponentDescription.EXTENSION_POINT_ID); //register all components for(Extension extension : componentExtensions) { try { ComponentDescription description = new ComponentDescription(extension); description.init(); registerComponent(description); } catch(Exception e) { logger.error("Cannot create component description, extension in plugin manifest is not valid.\n" + "pluginId = " + extension.getPlugin().getId() + "\n" + extension + "\nReason: " + e.getMessage()); } } } public final static void registerComponents(ComponentDescription[] components) { for(int i = 0; i < components.length; i++) { registerComponent(components[i]); } } public final static void registerComponent(ComponentDescription component){ componentMap.put(component.getType(), component); } /** * @param componentType * @return class from the given component type */ public final static Class getComponentClass(String componentType) { String className = null; ComponentDescription componentDescription = componentMap.get(componentType); try { if(componentDescription == null) { //unknown component type, we suppose componentType as full class name classification className = componentType; //find class of component return Class.forName(componentType); } else { className = componentDescription.getClassName(); PluginDescriptor pluginDescriptor = componentDescription.getPluginDescriptor(); //find class of component return Class.forName(className, true, pluginDescriptor.getClassLoader()); } } catch(ClassNotFoundException ex) { logger.error("Unknown component: " + componentType + " class: " + className, ex); throw new RuntimeException("Unknown component: " + componentType + " class: " + className, ex); } catch(Exception ex) { logger.error("Unknown component type: " + componentType, ex); throw new RuntimeException("Unknown component type: " + componentType, ex); } } /** * Method for creating various types of Components based on component type & XML parameter definition.<br> * If component type is not registered, it tries to use componentType parameter directly as a class name. * * @param componentType Type of the component (e.g. SimpleCopy, Gather, Join ...) * @param xmlNode XML element containing appropriate Node parameters * @return requested Component (Node) object or null if creation failed * @since May 27, 2002 */ public final static Node createComponent(TransformationGraph graph, String componentType, org.w3c.dom.Node nodeXML) { Class tClass = getComponentClass(componentType); try { //create instance of component Method method = tClass.getMethod(NAME_OF_STATIC_LOAD_FROM_XML, PARAMETERS_FOR_METHOD); Node result = (org.jetel.graph.Node) method.invoke(null, new Object[] {graph, nodeXML}); ComponentXMLAttributes xattribs = new ComponentXMLAttributes((Element) nodeXML, graph); //nodeDistribution attribute parsing //hack for extracting of node layout information - Clover3 solves this issue //it is the easiest way how to add new common attribute for all nodes if (xattribs.exists(Node.XML_DISTRIBUTION_ATTRIBUTE)) { NodeDistribution nodeDistribution = NodeDistribution.createFromString(xattribs.getString(Node.XML_DISTRIBUTION_ATTRIBUTE)); result.setDistribution(nodeDistribution); } //name attribute parsing if (xattribs.exists(Node.XML_NAME_ATTRIBUTE)) { String nodeName = xattribs.getString(Node.XML_NAME_ATTRIBUTE); result.setName(nodeName); } return result; } catch(InvocationTargetException e) { logger.error("Can't create object of type " + componentType + " with reason: " + e.getTargetException().getMessage()); throw new RuntimeException("Can't create object of type " + componentType + " with reason: " + e.getTargetException().getMessage()); } catch(NoSuchMethodException e) { logger.error("Can't create object of type " + componentType + " with reason: " + e.getMessage()); throw new RuntimeException("Can't create object of type " + componentType + " with reason: " + e.getMessage()); } catch(Exception ex) { logger.error("Can't create object of : " + componentType + " exception: " + ex); throw new RuntimeException("Can't create object of : " + componentType + " exception: " + ex); } } /** * Method for creating various types of Components based on component type, parameters and theirs types for component constructor.<br> * If component type is not registered, it tries to use componentType parameter directly as a class name.<br> * i.e.<br> * <code> * Node reformatNode = ComponentFactory.createComponent(myGraph, "REFORMAT", new Object[] { "REF_UNIQUE_CNT", myRecordTransform}, new Class[] {String.class, RecordTransform.class}); * </code> * @param graph * @param componentType * @param constructorParameters parameters passsed to component constructor * @param parametersType types of all constructor parameters * @return */ public final static Node createComponent(TransformationGraph graph, String componentType, Object[] constructorParameters, Class[] parametersType) { Class tClass = getComponentClass(componentType); try { //create instance of component Constructor constructor = tClass.getConstructor(parametersType); return (org.jetel.graph.Node) constructor.newInstance(constructorParameters); } catch(InvocationTargetException e) { logger.error("Can't create object of type " + componentType + " with reason: " + e.getTargetException().getMessage()); throw new RuntimeException("Can't create object of type " + componentType + " with reason: " + e.getTargetException().getMessage()); } catch(NoSuchMethodException e) { logger.error("Can't create object of type " + componentType + " with reason: " + e.getMessage()); throw new RuntimeException("Can't create object of type " + componentType + " with reason: " + e.getMessage()); } catch(Exception ex) { logger.error("Can't create object of : " + componentType + " exception: " + ex); throw new RuntimeException("Can't create object of : " + componentType + " exception: " + ex); } } }
package org.jetel.component; //import org.w3c.dom.Node; import java.util.Map; import java.util.HashMap; import java.lang.reflect.Method; import org.jetel.graph.Node; /** * Description of the Class * * @author dpavlis * @since May 27, 2002 * @revision $Revision$ */ public class ComponentFactory { private final static String NAME_OF_STATIC_LOAD_FROM_XML = "fromXML"; private final static Class[] PARAMETERS_FOR_METHOD = new Class[] { org.w3c.dom.Node.class }; private final static Map componentMap = new HashMap(); static{ // register known components // parameters <component type>,<full class name including package> registerComponent(SimpleCopy.COMPONENT_TYPE,"org.jetel.component.SimpleCopy"); registerComponent(Concatenate.COMPONENT_TYPE,"org.jetel.component.Concatenate"); registerComponent(DelimitedDataReader.COMPONENT_TYPE,"org.jetel.component.DelimitedDataReader"); registerComponent(DelimitedDataWriter.COMPONENT_TYPE,"org.jetel.component.DelimitedDataWriter"); registerComponent(SimpleGather.COMPONENT_TYPE,"org.jetel.component.SimpleGather"); registerComponent(DelimitedDataWriterNIO.COMPONENT_TYPE,"org.jetel.component.DelimitedDataWriterNIO"); registerComponent(DelimitedDataReaderNIO.COMPONENT_TYPE,"org.jetel.component.DelimitedDataReaderNIO"); registerComponent(Reformat.COMPONENT_TYPE,"org.jetel.component.Reformat"); registerComponent(DBInputTable.COMPONENT_TYPE,"org.jetel.component.DBInputTable"); registerComponent(Sort.COMPONENT_TYPE,"org.jetel.component.Sort"); registerComponent(DBOutputTable.COMPONENT_TYPE,"org.jetel.component.DBOutputTable"); registerComponent(FixLenDataWriterNIO.COMPONENT_TYPE,"org.jetel.component.FixLenDataWriterNIO"); registerComponent(Dedup.COMPONENT_TYPE,"org.jetel.component.Dedup"); registerComponent(FixLenDataReaderNIO.COMPONENT_TYPE,"org.jetel.component.FixLenDataReaderNIO"); registerComponent("FIXED_DATA_READER_NIO","org.jetel.component.FixLenDataReaderNIO"); registerComponent(Merge.COMPONENT_TYPE,"org.jetel.component.Merge"); registerComponent(MergeJoin.COMPONENT_TYPE,"org.jetel.component.MergeJoin"); registerComponent("SORTED_JOIN","org.jetel.component.MergeJoin"); // synonym for MergeJoin (former name) registerComponent(Trash.COMPONENT_TYPE,"org.jetel.component.Trash"); registerComponent(Filter.COMPONENT_TYPE,"org.jetel.component.Filter"); registerComponent(DBExecute.COMPONENT_TYPE,"org.jetel.component.DBExecute"); registerComponent(HashJoin.COMPONENT_TYPE,"org.jetel.component.HashJoin"); registerComponent(CheckForeignKey.COMPONENT_TYPE,"org.jetel.component.CheckForeignKey"); registerComponent(DBFDataReader.COMPONENT_TYPE,"org.jetel.component.DBFDataReader"); registerComponent(ExtFilter.COMPONENT_TYPE,"org.jetel.component.ExtFilter"); registerComponent(ExtSort.COMPONENT_TYPE,"org.jetel.component.ExtSort"); registerComponent(Partition.COMPONENT_TYPE,"org.jetel.component.Partition"); } public final static void registerComponent(Node component){ componentMap.put(component.getType(),component.getName()); } public final static void registerComponent(String componentType,String className){ componentMap.put(componentType,className); } /** * Method for creating various types of Components based on component type & XML parameter definition.<br> * If component type is not registered, it tries to use componentType parameter directly as a class name. * This way new components can be added withou modifying ComponentFactory code. * * @param componentType Type of the component (e.g. SimpleCopy, Gather, Join ...) * @param xmlNode XML element containing appropriate Node parameters * @return requested Component (Node) object or null if creation failed * @since May 27, 2002 */ public final static Node createComponent(String componentType, org.w3c.dom.Node nodeXML) { // try to load the component (use type as a full name) Class tClass; Method method; String className=null; try{ className=(String)componentMap.get(componentType); if (className==null){ // if it cannot be translated into class name, try to use the component // type as fully qualified component name className=componentType; } tClass = Class.forName(className); }catch(ClassNotFoundException ex){ throw new RuntimeException("Unknown component: " + componentType + " class: "+className); }catch(Exception ex){ throw new RuntimeException("Unknown exception: " + ex); } try{ Object[] args={nodeXML}; //Class.forName("org.w3c.dom.Node") method=tClass.getMethod(NAME_OF_STATIC_LOAD_FROM_XML, PARAMETERS_FOR_METHOD); //return newNode.fromXML(nodeXML); return (org.jetel.graph.Node)method.invoke(null,args); }catch(Exception ex){ throw new RuntimeException("Can't create object of : " + componentType + " exception: "+ex); } } }