answer stringlengths 17 10.2M |
|---|
package au.edu.wsu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.graphics.ImageDisplay;
import ch.unizh.ini.jaer.projects.davis.frames.DavisComplementaryFilter;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.TobiLogger;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
/**
* Extracts Polarization information using Cedric's complementary filter to
* obtain the absolute light intensity.
*
* @author Damien Joubert, Tobi Delbruck
*/
@Description("Method to extract polarization information from a stream of APS/DVS events using Cedric's complementary filter")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class PolarizationComplementaryFilter extends DavisComplementaryFilter {
// offset of f0, f45, f90 and f135 acording to the index
private int[] indexf0, indexf45, indexf90, indexf135;
private JFrame apsFramePola = null;
public ImageDisplay apsDisplayPola;
private float[] apsDisplayPixmapBufferAop;
private float[] aop;
private float[] dop;
FloatFunction exp = (s) -> (float) Math.exp(s); // lambda function to linearize log intensity
private TobiLogger tobiLogger = new TobiLogger("PolarizationComplementaryFilter", "PolarizationComplementaryFilter");
private DescriptiveStatistics aopStats = new DescriptiveStatistics(), dopStats = new DescriptiveStatistics(); // mean values, computed after the ROI is processed
private float meanAoP = Float.NaN, meanDoP = Float.NaN;
public PolarizationComplementaryFilter(final AEChip chip) {
super(chip);
apsDisplayPola = ImageDisplay.createOpenGLCanvas();
apsFramePola = new JFrame("Polarization Information DoP - AoP");
apsFramePola.setPreferredSize(new Dimension(600, 600));
apsFramePola.getContentPane().add(apsDisplayPola, BorderLayout.CENTER);
apsFramePola.pack();
apsFramePola.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
setShowAPSFrameDisplay(false);
}
});
initFilter();
tobiLogger.setColumnHeaderLine("lastTimestamp(s),ROINumPixels,AoP(deg),AoPStd(deg),DoLP,DoLPStd"); // CSV columns, not including the first column which is system time in ms since epoch
setPropertyTooltip("writePolarizationCSV", "Write a CSV file with the the mean and std of polarization AoP and DoLP for the ROI");
}
@Override
public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) {
checkMaps();
in = super.filterPacket(in);
computeAndShowPolarization(in);
if (showAPSFrameDisplay) {
apsDisplayPola.repaint();
}
return in; // should be denoised output
}
private void checkMaps() {
apsDisplayPola.checkPixmapAllocation();
if (showAPSFrameDisplay && !apsFramePola.isVisible()) {
apsFramePola.setVisible(true);
}
}
@Override
public void initFilter() {
super.initFilter();
if (maxIDX > 0) {
indexf0 = new int[maxIDX];
indexf45 = new int[maxIDX];
indexf90 = new int[maxIDX];
indexf135 = new int[maxIDX];
apsDisplayPixmapBufferAop = new float[3 * maxIDX / 4 * 3];
aop = new float[maxIDX / 4];
dop = new float[maxIDX / 4];
apsDisplayPola.setImageSize(width / 2, height / 2 * 3);
PolarizationUtils.fillIndex(indexf0, indexf45, indexf90, indexf135, height, width);
PolarizationUtils.drawLegend(apsDisplayPixmapBufferAop, height, width);
}
}
synchronized private void computeAndShowPolarization(EventPacket<? extends BasicEvent> in) {
if (maxIDX != indexf0.length && maxIDX > 0) {
indexf0 = new int[maxIDX];
indexf45 = new int[maxIDX];
indexf90 = new int[maxIDX];
indexf135 = new int[maxIDX];
apsDisplayPixmapBufferAop = new float[3 * maxIDX / 4 * 3];
aop = new float[maxIDX / 4];
dop = new float[maxIDX / 4];
apsDisplayPola.setImageSize(width / 2, height / 2 * 3);
PolarizationUtils.fillIndex(indexf0, indexf45, indexf90, indexf135, height, width);
PolarizationUtils.drawLegend(apsDisplayPixmapBufferAop, height, width);
}
// compute the AoP and DoLP in the ROI, using exp lambda function to linearize the estimated log intensity
PolarizationUtils.computeAoPDoP(logFinalFrame, aop, dop, exp, indexf0, indexf45, indexf90, indexf135, height, width);
if (roiRect != null) {
// compute mean values
int nb = 0, idx;
aopStats.clear();
dopStats.clear();
for (double x = roiRect.getCenterX() - roiRect.getWidth() / 2; x < roiRect.getCenterX() + roiRect.getWidth() / 2; x += 2) {
for (double y = roiRect.getCenterY() - roiRect.getHeight() / 2; y < roiRect.getCenterY() + roiRect.getHeight() / 2; y += 2) {
idx = (int) (x / 2 + y / 2 * width / 2);
aopStats.addValue(aop[idx]);
dopStats.addValue(dop[idx]);
nb += 1;
}
}
meanAoP = (float) aopStats.getMean(); // compute the means to show in ellipse
meanDoP = (float) dopStats.getMean();
// log the mean values to the CSV if open, should match the header line
if (tobiLogger.isEnabled()) {
tobiLogger.log(String.format("%f,%d,%f,%f,%f,%f", 1e-6f*in.getLastTimestamp(), nb, meanAoP, aopStats.getStandardDeviation(), meanDoP, dopStats.getStandardDeviation()));
}
}
// System.out.printf("Angle: %f", m_aop * 180);
// Show the polarization display; the ROI values are shown in annotate
PolarizationUtils.setDisplay(apsDisplayPixmapBufferAop, aop, dop, height, width);
apsDisplayPola.setPixmapArray(apsDisplayPixmapBufferAop);
// PolarizationUtils.computeAoPDoP(logFinalFrame, aop, dop, exp, indexf0, indexf45, indexf90, indexf135, height, width);
// PolarizationUtils.setDisplay(apsDisplayPixmapBuffer, aop, dop, height, width);
// if(apsDisplayPixmapBufferAop.length > 0)
// apsDisplayPola.setPixmapArray(apsDisplayPixmapBufferAop);
}
public float getDoP(int x, int y) {
return dop[getIndex(x, y)];
}
public float getAoP(int x, int y) {
return aop[getIndex(x, y)];
}
@Override
public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable); // draws the ROI selection rectangle
GL2 gl = drawable.getGL().getGL2();
if (roiRect == null) {
return;
}
// draw the polarization ellipse
gl.glColor3f(1, 1, 1); // set the RGB color
gl.glLineWidth(3); // set the line width in screen pixels
// draw the polarization ellipse
gl.glPushMatrix();
DrawGL.drawEllipse(gl, (float) roiRect.getCenterX(), (float) roiRect.getCenterY(), (float) (20), (float) (20 * (1 - meanDoP)), meanAoP * 2.0f, 32);
gl.glPopMatrix();
}
public void doToggleOnWritePolarizationCSV() {
tobiLogger.setEnabled(true);
}
public void doToggleOffWritePolarizationCSV() {
tobiLogger.setEnabled(false);
tobiLogger.showFolderInDesktop();
}
} |
package org.demyo.model;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SortComparator;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.URL;
import org.demyo.model.util.AlbumComparator;
import org.demyo.model.util.DefaultOrder;
import org.demyo.model.util.IdentifyingNameComparator;
import org.demyo.model.util.StartsWithField;
/**
* Represents a Series.
*/
@Entity
@Table(name = "SERIES")
@DefaultOrder(expression = @DefaultOrder.Order(property = "name"))
@NamedEntityGraphs({
@NamedEntityGraph(name = "Series.forView", attributeNodes =
{ @NamedAttributeNode("relatedSeries"),
@NamedAttributeNode(value = "albums", subgraph = "Series.Album") }, subgraphs =
{ @NamedSubgraph(name = "Series.Album", attributeNodes = { @NamedAttributeNode("writers"),
@NamedAttributeNode("artists"), @NamedAttributeNode("colorists"),
@NamedAttributeNode("publisher"), @NamedAttributeNode("collection"),
@NamedAttributeNode("tags"), @NamedAttributeNode("cover") }) }),
@NamedEntityGraph(name = "Series.forEdition", attributeNodes = @NamedAttributeNode("relatedSeries")) })
public class Series extends AbstractModel {
/** The name. */
@Column(name = "name")
@NotBlank
@StartsWithField
private String name;
/** The summary. */
@Column(name = "summary")
private String summary;
/** The comment. */
@Column(name = "comment")
private String comment;
/** The website. */
@Column(name = "website")
@URL
private String website;
/** The flag indicating whether the series is completed. */
@Column(name = "completed")
private Boolean completed;
/** The physical location of this Series. */
@Column(name = "location")
private String location;
/** The series related to this one. */
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "series_relations", joinColumns = @JoinColumn(name = "main"),
inverseJoinColumns = @JoinColumn(name = "sub"))
@SortComparator(IdentifyingNameComparator.class)
private SortedSet<Series> relatedSeries;
/** The albums belonging to this series. */
@OneToMany(mappedBy = "series", fetch = FetchType.LAZY)
@SortComparator(AlbumComparator.class)
private SortedSet<Album> albums;
/** The {@link Reader}s who favourited this Series. */
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "favouriteSeries")
@SortComparator(IdentifyingNameComparator.class)
private SortedSet<Reader> readersFavourites;
@Override
public String getIdentifyingName() {
return name;
}
// TODO [Java 8]: refactor all aggregator methods to use a single method with
// lamba expressions
/**
* Returns all tags used by the albums of this series.
*
* @return the {@link Tag} set.
*/
public SortedSet<Tag> getAlbumTags() {
SortedSet<Tag> albumTags = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumTags.addAll(a.getTags());
}
return albumTags;
}
/**
* Returns all the writers who participated to the albums of this series.
*
* @return the {@link Author} set.
*/
public SortedSet<Author> getAlbumWriters() {
SortedSet<Author> albumAuthors = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumAuthors.addAll(a.getWriters());
}
return albumAuthors;
}
/**
* Returns all the artists who participated to the albums of this series.
*
* @return the {@link Author} set.
*/
public SortedSet<Author> getAlbumArtists() {
SortedSet<Author> albumAuthors = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumAuthors.addAll(a.getArtists());
}
return albumAuthors;
}
/**
* Returns all the colorists who participated to the albums of this series.
*
* @return the {@link Author} set.
*/
public SortedSet<Author> getAlbumColorists() {
SortedSet<Author> albumAuthors = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumAuthors.addAll(a.getColorists());
}
return albumAuthors;
}
/**
* Returns all the inkers who participated to the albums of this series.
*
* @return the {@link Author} set.
*/
public SortedSet<Author> getAlbumInkers() {
SortedSet<Author> albumAuthors = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumAuthors.addAll(a.getInkers());
}
return albumAuthors;
}
/**
* Returns all the translators who participated to the albums of this series.
*
* @return the {@link Author} set.
*/
public SortedSet<Author> getAlbumTranslators() {
SortedSet<Author> albumAuthors = new TreeSet<>(new IdentifyingNameComparator());
for (Album a : albums) {
albumAuthors.addAll(a.getTranslators());
}
return albumAuthors;
}
/**
* Gets the number of {@link Album}s encoded in the library for this Series, and actually owned.
*
* @return the album count (excl. wishlist)
*/
public int getOwnedAlbumCount() {
int count = 0;
for (Album a : albums) {
if (!a.isWishlist()) {
count++;
}
}
return count;
}
/**
* Gets the number of {@link Album}s encoded in the library for this Series.
*
* @return the album count (incl. wishlist)
*/
public int getTotalAlbumCount() {
return albums.size();
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the summary.
*
* @return the summary
*/
public String getSummary() {
return summary;
}
/**
* Sets the summary.
*
* @param summary the new summary
*/
public void setSummary(String summary) {
this.summary = summary;
}
/**
* Gets the comment.
*
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* Sets the comment.
*
* @param comment the new comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Gets the website.
*
* @return the website
*/
public String getWebsite() {
return website;
}
/**
* Sets the website.
*
* @param website the new website
*/
public void setWebsite(String website) {
this.website = website;
}
/**
* Gets the flag indicating whether the series is completed.
*
* @return the flag indicating whether the series is completed
*/
public Boolean getCompleted() {
return completed;
}
/**
* Sets the flag indicating whether the series is completed.
*
* @param completed the new flag indicating whether the series is completed
*/
public void setCompleted(Boolean completed) {
this.completed = completed;
}
/**
* Gets the physical location of this Series.
*
* @return the physical location of this Series
*/
public String getLocation() {
return location;
}
/**
* Sets the physical location of this Series.
*
* @param location the new physical location of this Series
*/
public void setLocation(String location) {
this.location = location;
}
/**
* Gets the series related to this one.
*
* @return the series related to this one
*/
public Set<Series> getRelatedSeries() {
return relatedSeries;
}
/**
* Sets the series related to this one.
*
* @param relatedSeries the new series related to this one
*/
public void setRelatedSeries(SortedSet<Series> relatedSeries) {
this.relatedSeries = relatedSeries;
}
/**
* Gets the albums belonging to this series.
*
* @return the albums belonging to this series
*/
public SortedSet<Album> getAlbums() {
return albums;
}
} |
package org.realityforge.arez;
import javax.annotation.Nonnull;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* TODO: This class does not fully test the Observable.
*/
public class ObservableTest
extends AbstractArezTest
{
@Test
public void initialState()
throws Exception
{
final ArezContext context = new ArezContext();
final String name = ValueUtil.randomString();
final TestObservable observable = new TestObservable( context, name, null );
assertEquals( observable.getName(), name );
assertEquals( observable.getContext(), context );
assertEquals( observable.toString(), name );
assertEquals( observable.isPendingDeactivation(), false );
assertEquals( observable.getObservers().size(), 0 );
assertEquals( observable.hasObservers(), false );
observable.invariantLeastStaleObserverState();
}
@Test
public void addObserver()
throws Exception
{
final ArezContext context = new ArezContext();
final Observer observer = new Observer( context, ValueUtil.randomString() );
setCurrentTransaction( context, observer );
final TestObservable observable = new TestObservable( context, ValueUtil.randomString(), null );
assertEquals( observable.getObservers().size(), 0 );
assertEquals( observable.hasObservers(), false );
assertEquals( observable.getLeastStaleObserverState(), ObserverState.INACTIVE );
// Handle addition of observer in correct state
observable.addObserver( observer );
assertEquals( observable.getObservers().size(), 1 );
assertEquals( observable.hasObservers(), true );
assertEquals( observable.hasObserver( observer ), true );
assertEquals( observable.getLeastStaleObserverState(), ObserverState.INACTIVE );
observable.invariantLeastStaleObserverState();
}
@Test
public void addObserver_updatesLestStaleObserverState()
throws Exception
{
final ArezContext context = new ArezContext();
final Observer observer = new Observer( context, ValueUtil.randomString() );
setCurrentTransaction( context, observer );
final TestObservable observable = new TestObservable( context, ValueUtil.randomString(), null );
observable.setLeastStaleObserverState( ObserverState.STALE );
observer.setState( ObserverState.POSSIBLY_STALE );
observable.addObserver( observer );
assertEquals( observable.getLeastStaleObserverState(), ObserverState.POSSIBLY_STALE );
observable.invariantLeastStaleObserverState();
}
@Test
public void addObserver_duplicate()
throws Exception
{
final ArezContext context = new ArezContext();
final Observer observer = new Observer( context, ValueUtil.randomString() );
setCurrentTransaction( context, observer );
final TestObservable observable = new TestObservable( context, ValueUtil.randomString(), null );
assertEquals( observable.getObservers().size(), 0 );
assertEquals( observable.hasObservers(), false );
// Handle addition of observer in correct state
observable.addObserver( observer );
observer.getDependencies().add( observable );
assertEquals( observable.getObservers().size(), 1 );
assertEquals( observable.hasObservers(), true );
assertEquals( observable.hasObserver( observer ), true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> observable.addObserver( observer ) );
assertEquals( exception.getMessage(),
"Attempting to add observer named '" + observer.getName() + "' to observable named '" +
observable.getName() + "' when observer is already observing observable." );
assertEquals( observable.getObservers().size(), 1 );
assertEquals( observable.hasObservers(), true );
assertEquals( observable.hasObserver( observer ), true );
observable.invariantLeastStaleObserverState();
}
@Test
public void addObserver_noActiveTransaction()
throws Exception
{
final ArezContext context = new ArezContext();
final Observer observer = new Observer( context, ValueUtil.randomString() );
final TestObservable observable = new TestObservable( context, ValueUtil.randomString(), null );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> observable.addObserver( observer ) );
assertEquals( exception.getMessage(),
"Attempt to invoke addObserver on observable named '" +
observable.getName() + "' when there is no active transaction." );
assertEquals( observable.getObservers().size(), 0 );
assertEquals( observable.hasObservers(), false );
observable.invariantLeastStaleObserverState();
}
private void setCurrentTransaction( @Nonnull final ArezContext context, @Nonnull final Observer observer )
{
context.setTransaction( new Transaction( context,
null,
ValueUtil.randomString(),
observer.getMode(),
observer ) );
}
} |
// TestJSONDecoding.java
// xal
package xal.tools.text;
import org.junit.*;
/** test the ScientificNumberFormat class */
public class TestScientificNumberFormat {
@Test
public void testPositiveSimpleFormats() {
assertFormat( " 4", 1, 5, 4.32 );
assertFormat( " -5", 1, 5, -5.13 );
assertFormat( " 3.1416", 5, 10, 3.14159265 );
}
@Test
public void testNegativeSimpleFormats() {
assertFormat( " -3.1416", 5, 10, -3.14159265 );
}
@Test
public void testPositiveExponentialFormats() {
assertFormat( " 1.000E1", 4, 10, 10.0 );
assertFormat( " 3.00E2", 3, 10, 300.0 );
assertFormat( " 5.24E250", 3, 10, 5.2395E+250 );
assertFormat( " 1.000E-1", 4, 10, 0.1 );
assertFormat( " 9.900E-1", 4, 10, 0.99 );
}
@Test
public void testNegativeExponentialFormats() {
assertFormat( " -1.000E1", 4, 10, -10.0 );
assertFormat( " -1.000E-1", 4, 10, -0.1 );
assertFormat( " -9.900E-1", 4, 10, -0.99 );
assertFormat( " -3.00E2", 3, 10, -300.0 );
assertFormat( " -5.2395E250", 5, 13, -5.2395E+250 );
assertFormat( " -5.2395E-250", 5, 13, -5.2395E-250 );
}
@Test
public void testRoundingFormats() {
assertFormat( " 1.49", 3, 8, 1.494999 );
assertFormat( " 1.50", 3, 8, 1.495 );
}
/** Assert whether the formatted output matches the specified reference */
static private void assertFormat( final String reference, final int significantDigits, final int width, final double value ) {
final ScientificNumberFormat format = new ScientificNumberFormat( significantDigits, width );
final String output = format.format( value );
Assert.assertEquals( "Failed format equality for number: " + value + " with output: " + output + " of length: " + output.length(), reference, output );
}
} |
package org.sbolstandard.core2;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import uk.co.turingatemyhamster.opensmiles.OpenSmilesParser;
/**
* Provides functionality for validating SBOL data models.
*
* @author Zhen Zhang
* @author Chris Myers
* @version 2.1
*/
public class SBOLValidate {
/**
* the current SBOL version
*/
private static final String SBOLVersion = "2.0";
private static final String libSBOLj_Version = "2.1";
private static List<String> errors = null;
/**
* Empties the error list that is used to store SBOL validation exceptions.
*/
public static void clearErrors() {
errors = new ArrayList<String>();
}
/**
* Returns the error list used to store SBOL validation exceptions.
*
* @return the error list used to store SBOL validation exceptions
*/
public static List<String> getErrors() {
return errors;
}
/**
* Returns the number of errors in the error list.
* @return the number of errors in the error list
*/
public static int getNumErrors() {
return errors.size();
}
/**
* Validates if SBOL instances are compliant in the given SBOL document.
*
* @param sbolDocument the SBOL document to be validated
*/
static void validateCompliance(SBOLDocument sbolDocument) {
for (TopLevel topLevel : sbolDocument.getTopLevels()) {
try {
topLevel.isURIcompliant();
}
catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
private static void checkCollectionCompleteness(SBOLDocument sbolDocument,Collection collection) {
for (URI member : collection.getMemberURIs()) {
if (sbolDocument.getTopLevel(member)==null) {
SBOLValidationException e = new SBOLValidationException("sbol-12103", collection);
errors.add(e.getMessage());
}
}
}
private static void checkComponentDefinitionCompleteness(SBOLDocument sbolDocument,ComponentDefinition componentDefinition) {
for (URI sequenceURI : componentDefinition.getSequenceURIs()) {
if (sbolDocument.getSequence(sequenceURI)==null) {
errors.add(new SBOLValidationException("sbol-10513", componentDefinition).getMessage());
}
}
for (Component component : componentDefinition.getComponents()) {
if (component.getDefinition()==null) {
errors.add(new SBOLValidationException("sbol-10604", component).getMessage());
}
for (MapsTo mapsTo : component.getMapsTos()) {
if (mapsTo.getRemote()==null) {
errors.add(new SBOLValidationException("sbol-10808", mapsTo).getMessage());
continue;
}
if (mapsTo.getRemote().getAccess().equals(AccessType.PRIVATE)) {
errors.add(new SBOLValidationException("sbol-10807", mapsTo).getMessage());
}
if (mapsTo.getRefinement().equals(RefinementType.VERIFYIDENTICAL)) {
if (!mapsTo.getLocal().getDefinitionURI().equals(mapsTo.getRemote().getDefinitionURI())) {
errors.add(new SBOLValidationException("sbol-10811").getMessage());
}
}
}
}
}
/**
* @param componentDefinition
* @param mapsTo
* @throws SBOLValidationException the following SBOL validation rule was violated: 10526
*/
static void checkComponentDefinitionMapsTos(ComponentDefinition componentDefinition,MapsTo mapsTo) throws SBOLValidationException {
for (Component component : componentDefinition.getComponents()) {
for (MapsTo mapsTo2 : component.getMapsTos()) {
if (mapsTo==mapsTo2) continue;
if (mapsTo.getLocalURI().equals(mapsTo2.getLocalURI()) &&
mapsTo.getRefinement().equals(RefinementType.USEREMOTE) &&
mapsTo2.getRefinement().equals(RefinementType.USEREMOTE)) {
throw new SBOLValidationException("sbol-10526",componentDefinition);
}
}
}
}
/**
* @param moduleDefinition
* @param mapsTo
* @throws SBOLValidationException the following SBOL validation rule was violated: 11609.
*/
static void checkModuleDefinitionMapsTos(ModuleDefinition moduleDefinition,MapsTo mapsTo) throws SBOLValidationException {
for (Module module : moduleDefinition.getModules()) {
for (MapsTo mapsTo2 : module.getMapsTos()) {
if (mapsTo==mapsTo2) continue;
if (mapsTo.getLocalURI().equals(mapsTo2.getLocalURI()) &&
mapsTo.getRefinement().equals(RefinementType.USEREMOTE) &&
mapsTo2.getRefinement().equals(RefinementType.USEREMOTE)) {
throw new SBOLValidationException("sbol-11609",moduleDefinition);
}
}
}
for (FunctionalComponent functionalComponent : moduleDefinition.getFunctionalComponents()) {
for (MapsTo mapsTo2 : functionalComponent.getMapsTos()) {
if (mapsTo==mapsTo2) continue;
if (mapsTo.getLocalURI().equals(mapsTo2.getLocalURI()) &&
mapsTo.getRefinement().equals(RefinementType.USEREMOTE) &&
mapsTo2.getRefinement().equals(RefinementType.USEREMOTE)) {
throw new SBOLValidationException("sbol-11609",moduleDefinition);
}
}
}
}
private static void validateMapsTos(SBOLDocument sbolDocument) {
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
for (Component component : componentDefinition.getComponents()) {
for (MapsTo mapsTo : component.getMapsTos()) {
try {
checkComponentDefinitionMapsTos(componentDefinition,mapsTo);
}
catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
}
for (ModuleDefinition moduleDefinition : sbolDocument.getModuleDefinitions()) {
for (Module module : moduleDefinition.getModules()) {
for (MapsTo mapsTo : module.getMapsTos()) {
try {
checkModuleDefinitionMapsTos(moduleDefinition,mapsTo);
}
catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
for (FunctionalComponent functionalComponent : moduleDefinition.getFunctionalComponents()) {
for (MapsTo mapsTo : functionalComponent.getMapsTos()) {
try {
checkModuleDefinitionMapsTos(moduleDefinition,mapsTo);
}
catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
}
}
private static void checkModuleDefinitionCompleteness(SBOLDocument sbolDocument,ModuleDefinition moduleDefinition) {
for (URI modelURI : moduleDefinition.getModelURIs()) {
if (sbolDocument.getModel(modelURI) == null) {
errors.add(new SBOLValidationException("sbol-11608", moduleDefinition).getMessage());
}
}
for (FunctionalComponent functionalComponent : moduleDefinition.getFunctionalComponents()) {
if (functionalComponent.getDefinition() == null) {
errors.add(new SBOLValidationException("sbol-10604", functionalComponent).getMessage());
}
for (MapsTo mapsTo : functionalComponent.getMapsTos()) {
if (mapsTo.getRemote()==null) {
errors.add(new SBOLValidationException("sbol-10808", mapsTo).getMessage());
continue;
}
if (mapsTo.getRemote().getAccess().equals(AccessType.PRIVATE)) {
errors.add(new SBOLValidationException("sbol-10807", mapsTo).getMessage());
}
if (mapsTo.getRefinement().equals(RefinementType.VERIFYIDENTICAL)) {
if (!mapsTo.getLocal().getDefinitionURI().equals(mapsTo.getRemote().getDefinitionURI())) {
errors.add(new SBOLValidationException("sbol-10811").getMessage());
}
}
}
}
for (Module module : moduleDefinition.getModules()) {
if (module.getDefinition() == null) {
errors.add(new SBOLValidationException("sbol-11703", module).getMessage());
}
for (MapsTo mapsTo : module.getMapsTos()) {
if (mapsTo.getRemote()==null) {
errors.add(new SBOLValidationException("sbol-10809", mapsTo).getMessage());
continue;
}
if (mapsTo.getRemote().getAccess().equals(AccessType.PRIVATE)) {
errors.add(new SBOLValidationException("sbol-10807", mapsTo).getMessage());
}
if (mapsTo.getRefinement().equals(RefinementType.VERIFYIDENTICAL)) {
if (!mapsTo.getLocal().getDefinitionURI().equals(mapsTo.getRemote().getDefinitionURI())) {
errors.add(new SBOLValidationException("sbol-10811").getMessage());
}
}
}
}
}
/**
* Validates if all URI references to SBOL objects are in the same given SBOL document.
*
* @param sbolDocument the given SBOL document to be validated for completeness
*/
private static void validateCompleteness(SBOLDocument sbolDocument) {
for (Collection collection : sbolDocument.getCollections()) {
checkCollectionCompleteness(sbolDocument,collection);
}
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
checkComponentDefinitionCompleteness(sbolDocument,componentDefinition);
}
for (ModuleDefinition moduleDefinition : sbolDocument.getModuleDefinitions()) {
checkModuleDefinitionCompleteness(sbolDocument,moduleDefinition);
}
}
/**
* @param sbolDocument
* @param componentDefinition
* @param visited
* @throws SBOLValidationException if either of the following SBOL validation rule was violated: 10603, 10605.
*/
static void checkComponentDefinitionCycle(SBOLDocument sbolDocument,
ComponentDefinition componentDefinition, Set<URI> visited) throws SBOLValidationException {
if (componentDefinition==null) return;
visited.add(componentDefinition.getIdentity());
for (Component component : componentDefinition.getComponents()) {
ComponentDefinition cd = component.getDefinition();
if (cd==null) continue;
if (visited.contains(cd.getIdentity())) {
throw new SBOLValidationException("sbol-10603",component);
}
try {
checkComponentDefinitionCycle(sbolDocument,cd,visited);
} catch (SBOLValidationException e) {
throw new SBOLValidationException("sbol-10605",component);
}
}
visited.remove(componentDefinition.getIdentity());
return;
}
static void checkModuleDefinitionCycle(SBOLDocument sbolDocument,
ModuleDefinition moduleDefinition, Set<URI> visited) throws SBOLValidationException {
if (moduleDefinition==null) return;
visited.add(moduleDefinition.getIdentity());
for (Module module : moduleDefinition.getModules()) {
ModuleDefinition md = module.getDefinition();
if (md==null) continue;
if (visited.contains(md.getIdentity())) {
throw new SBOLValidationException("sbol-11704",module);
}
try {
checkModuleDefinitionCycle(sbolDocument,md,visited);
} catch (SBOLValidationException e) {
throw new SBOLValidationException("sbol-11705",module);
}
}
visited.remove(moduleDefinition.getIdentity());
return;
}
static boolean checkWasDerivedFromVersion(SBOLDocument sbolDocument, Identified identified,
URI wasDerivedFrom) {
Identified derivedFrom = sbolDocument.getTopLevel(wasDerivedFrom);
if ((derivedFrom!=null) &&
(derivedFrom.isSetPersistentIdentity() && identified.isSetPersistentIdentity()) &&
(derivedFrom.getPersistentIdentity().equals(identified.getPersistentIdentity())) &&
(derivedFrom.isSetVersion() && identified.isSetVersion()) &&
(Version.isFirstVersionNewer(derivedFrom.getVersion(), identified.getVersion()))) {
return false;
}
return true;
}
private static void validateWasDerivedFromVersion(SBOLDocument sbolDocument) {
for (TopLevel topLevel : sbolDocument.getTopLevels()) {
if (topLevel.isSetWasDerivedFrom()) {
if (!checkWasDerivedFromVersion(sbolDocument,topLevel,topLevel.getWasDerivedFrom())) {
errors.add(new SBOLValidationException("sbol-10302", topLevel).getMessage());
}
}
}
}
/**
* @param sbolDocument
* @param identified
* @param wasDerivedFrom
* @param visited
* @throws SBOLValidationException if any of the following SBOL validation rule was violated: 10303, 10304.
*/
static void checkWasDerivedFromCycle(SBOLDocument sbolDocument,
Identified identified, URI wasDerivedFrom, Set<URI> visited) throws SBOLValidationException {
visited.add(identified.getIdentity());
TopLevel tl = sbolDocument.getTopLevel(wasDerivedFrom);
if (tl!=null) {
if (visited.contains(tl.getIdentity())) {
throw new SBOLValidationException("sbol-10303",identified);
}
if (tl.isSetWasDerivedFrom()) {
try {
checkWasDerivedFromCycle(sbolDocument,tl,tl.getWasDerivedFrom(),visited);
} catch (SBOLValidationException e) {
throw new SBOLValidationException("sbol-10304",identified);
}
} else {
return;
}
}
visited.remove(identified.getIdentity());
return;
}
/**
* Validates if there are circular references in the given SBOL document.
*
* @param sbolDocument the given SBOL document to be validated for circular references
*/
private static void validateCircularReferences(SBOLDocument sbolDocument) {
for (TopLevel topLevel : sbolDocument.getTopLevels()) {
if (topLevel.isSetWasDerivedFrom()) {
try {
checkWasDerivedFromCycle(sbolDocument,topLevel,topLevel.getWasDerivedFrom(), new HashSet<URI>());
} catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
try {
checkComponentDefinitionCycle(sbolDocument,componentDefinition,new HashSet<URI>());
} catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
for (ModuleDefinition moduleDefinition : sbolDocument.getModuleDefinitions()) {
try {
checkModuleDefinitionCycle(sbolDocument,moduleDefinition,new HashSet<URI>());
} catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
/**
* @param componentDefinition
* @param sequenceConstraint
* @throws SBOLValidationException if any of the following SBOL validation rules was violated:
* 11409, 11410, 11411.
*/
static void checkSequenceConstraint(ComponentDefinition componentDefinition,SequenceConstraint sequenceConstraint) throws SBOLValidationException {
SequenceAnnotation saSubject = componentDefinition.getSequenceAnnotation(sequenceConstraint.getSubject());
SequenceAnnotation saObject = componentDefinition.getSequenceAnnotation(sequenceConstraint.getObject());
if (saSubject==null || saObject==null) return;
if (sequenceConstraint.getRestriction().equals(RestrictionType.PRECEDES)) {
if (saObject.compareTo(saSubject) != (-1)*Integer.MAX_VALUE
&& saObject.compareTo(saSubject) < 0) {
throw new SBOLValidationException("sbol-11409", sequenceConstraint);
}
} else if (sequenceConstraint.getRestriction().equals(RestrictionType.SAME_ORIENTATION_AS)) {
for (Location locSubject : saSubject.getLocations()) {
for (Location locObject : saObject.getLocations()) {
if (!locSubject.getOrientation().equals(locObject.getOrientation())) {
throw new SBOLValidationException("sbol-11410", sequenceConstraint);
}
}
}
} else if (sequenceConstraint.getRestriction().equals(RestrictionType.OPPOSITE_ORIENTATION_AS)) {
for (Location locSubject : saSubject.getLocations()) {
for (Location locObject : saObject.getLocations()) {
if (locSubject.getOrientation().equals(locObject.getOrientation())) {
throw new SBOLValidationException("sbol-11411", sequenceConstraint);
}
}
}
}
}
private static void checkInteractionTypeParticipationRole(Interaction interaction,URI type,URI role) {
if (type.equals(SystemsBiologyOntology.INHIBITION)) {
if (!role.equals(SystemsBiologyOntology.INHIBITOR) && !role.equals(SystemsBiologyOntology.PROMOTER)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
} else if (type.equals(SystemsBiologyOntology.STIMULATION)) {
if (!role.equals(SystemsBiologyOntology.STIMULATOR) && !role.equals(SystemsBiologyOntology.PROMOTER)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
} else if (type.equals(SystemsBiologyOntology.NON_COVALENT_BINDING)) {
if (!role.equals(SystemsBiologyOntology.REACTANT) && !role.equals(SystemsBiologyOntology.PRODUCT)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
} else if (type.equals(SystemsBiologyOntology.DEGRADATION)) {
if (!role.equals(SystemsBiologyOntology.REACTANT)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
} else if (type.equals(SystemsBiologyOntology.BIOCHEMICAL_REACTION)) {
if (!role.equals(SystemsBiologyOntology.REACTANT) && !role.equals(SystemsBiologyOntology.PRODUCT) &&
!role.equals(SystemsBiologyOntology.MODIFIER)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
} else if (type.equals(SystemsBiologyOntology.GENETIC_PRODUCTION)) {
if (!role.equals(SystemsBiologyOntology.PROMOTER) && !role.equals(SystemsBiologyOntology.PRODUCT)) {
errors.add(new SBOLValidationException("sbol-11907",interaction).getMessage());
}
}
}
private static void validateOntologyUsage(SBOLDocument sbolDocument) {
SequenceOntology so = new SequenceOntology();
SystemsBiologyOntology sbo = new SystemsBiologyOntology();
EDAMOntology edam = new EDAMOntology();
for (Sequence sequence : sbolDocument.getSequences()) {
if (!sequence.getEncoding().equals(Sequence.IUPAC_DNA) &&
!sequence.getEncoding().equals(Sequence.IUPAC_RNA) &&
!sequence.getEncoding().equals(Sequence.IUPAC_PROTEIN) &&
!sequence.getEncoding().equals(Sequence.SMILES)) {
errors.add(new SBOLValidationException("sbol-10407", sequence).getMessage());
}
}
for (ComponentDefinition compDef : sbolDocument.getComponentDefinitions()) {
int numBioPAXtypes = 0;
for (URI type : compDef.getTypes()) {
if (type.equals(ComponentDefinition.DNA) ||
type.equals(ComponentDefinition.RNA) ||
type.equals(ComponentDefinition.PROTEIN) ||
type.equals(ComponentDefinition.COMPLEX) ||
type.equals(ComponentDefinition.SMALL_MOLECULE)) {
numBioPAXtypes++;
}
}
if (numBioPAXtypes == 0) {
errors.add(new SBOLValidationException("sbol-10525", compDef).getMessage());
} else if (numBioPAXtypes > 1){
errors.add(new SBOLValidationException("sbol-10503", compDef).getMessage());
}
int numSO = 0;;
for (URI role : compDef.getRoles()) {
try {
if (so.isDescendantOf(role, SequenceOntology.SEQUENCE_FEATURE)) {
numSO++;
}
} catch (Exception e){
}
}
if (compDef.getTypes().contains(ComponentDefinition.DNA) || compDef.getTypes().contains(ComponentDefinition.RNA)) {
if (numSO!=1) {
errors.add(new SBOLValidationException("sbol-10527", compDef).getMessage());
}
} else if (!compDef.getTypes().contains(ComponentDefinition.RNA)) {
if (numSO!=0) {
errors.add(new SBOLValidationException("sbol-10511", compDef).getMessage());
}
}
for (SequenceConstraint sc : compDef.getSequenceConstraints()) {
try {
RestrictionType.convertToRestrictionType(sc.getRestrictionURI());
}
catch (Exception e) {
errors.add(new SBOLValidationException("sbol-11412", sc).getMessage());
}
}
}
for (Model model : sbolDocument.getModels()) {
try {
if (!edam.isDescendantOf(model.getLanguage(), EDAMOntology.FORMAT)) {
errors.add(new SBOLValidationException("sbol-11507", model).getMessage());
}
}
catch (Exception e) {
errors.add(new SBOLValidationException("sbol-11507", model).getMessage());
}
try {
if (!sbo.isDescendantOf(model.getFramework(), SystemsBiologyOntology.MODELING_FRAMEWORK)) {
errors.add(new SBOLValidationException("sbol-11511", model).getMessage());
}
}
catch (Exception e) {
errors.add(new SBOLValidationException("sbol-11511", model).getMessage());
}
}
for (ModuleDefinition modDef : sbolDocument.getModuleDefinitions()) {
for (Interaction interaction : modDef.getInteractions()) {
int numSBOtype = 0;
URI SBOtype = null;
for (URI type : interaction.getTypes()) {
try {
if (sbo.isDescendantOf(type, SystemsBiologyOntology.OCCURRING_ENTITY_REPRESENTATION)) {
numSBOtype++;
SBOtype = type;
}
}
catch (Exception e) {
}
}
if (numSBOtype != 1) {
errors.add(new SBOLValidationException("sbol-11905").getMessage());
}
for (Participation participation : interaction.getParticipations()) {
int numSBOrole = 0;
URI SBOrole = null;
for (URI role : participation.getRoles()) {
try {
if (sbo.isDescendantOf(role, SystemsBiologyOntology.PARTICIPANT_ROLE)) {
numSBOrole++;
SBOrole = role;
}
}
catch (Exception e) {
}
}
if (numSBOrole != 1) {
errors.add(new SBOLValidationException("sbol-12007", participation).getMessage());
} else {
checkInteractionTypeParticipationRole(interaction,SBOtype,SBOrole);
}
}
}
}
}
private static void validateComponentDefinitionSequences(SBOLDocument sbolDocument) {
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
if (componentDefinition.getSequences().size() < 1) continue;
boolean foundNucleic = false;
boolean foundProtein = false;
boolean foundSmiles = false;
int nucleicLength = -1;
int proteinLength = -1;
int smilesLength = -1;
for (Sequence sequence : componentDefinition.getSequences()) {
if (sequence.getEncoding().equals(Sequence.IUPAC_DNA) ||
sequence.getEncoding().equals(Sequence.IUPAC_RNA)) {
if (foundNucleic) {
if (nucleicLength != sequence.getElements().length()) {
errors.add(new SBOLValidationException("sbol-10518", componentDefinition).getMessage());
}
} else {
foundNucleic = true;
nucleicLength = sequence.getElements().length();
}
for (SequenceAnnotation sa : componentDefinition.getSequenceAnnotations()) {
for (Location location : sa.getLocations()) {
if (location instanceof Range) {
Range range = (Range)location;
if (range.getStart() <= 0 || range.getEnd() > nucleicLength) {
errors.add(new SBOLValidationException("sbol-10523", componentDefinition).getMessage());
}
} else if (location instanceof Cut) {
Cut cut = (Cut)location;
if (cut.getAt() < 0 || cut.getAt() > nucleicLength) {
errors.add(new SBOLValidationException("sbol-10523", componentDefinition).getMessage());
}
}
}
}
} else if (sequence.getEncoding().equals(Sequence.IUPAC_PROTEIN)) {
if (foundProtein) {
if (proteinLength != sequence.getElements().length()) {
errors.add(new SBOLValidationException("sbol-10518", componentDefinition).getMessage());
}
} else {
foundProtein = true;
proteinLength = sequence.getElements().length();
}
} else if (sequence.getEncoding().equals(Sequence.SMILES)) {
if (foundSmiles) {
if (smilesLength != sequence.getElements().length()) {
errors.add(new SBOLValidationException("sbol-10518", componentDefinition).getMessage());
}
} else {
foundSmiles = true;
smilesLength = sequence.getElements().length();
}
}
}
if (componentDefinition.getTypes().contains(ComponentDefinition.DNA) && !foundNucleic) {
errors.add(new SBOLValidationException("sbol-10516", componentDefinition).getMessage());
} else if (componentDefinition.getTypes().contains(ComponentDefinition.RNA) && !foundNucleic) {
errors.add(new SBOLValidationException("sbol-10516", componentDefinition).getMessage());
} else if (componentDefinition.getTypes().contains(ComponentDefinition.PROTEIN) && !foundProtein) {
errors.add(new SBOLValidationException("sbol-10516", componentDefinition).getMessage());
} else if (componentDefinition.getTypes().contains(ComponentDefinition.SMALL_MOLECULE) && !foundSmiles) {
errors.add(new SBOLValidationException("sbol-10516", componentDefinition).getMessage());
}
if (foundNucleic) {
if (componentDefinition.getSequenceAnnotations().size()>0) {
String impliedElements = componentDefinition.getImpliedNucleicAcidSequence();
Sequence dnaSequence = componentDefinition.getSequenceByEncoding(Sequence.IUPAC_DNA);
if (!includesSequence(dnaSequence.getElements(),impliedElements)) {
errors.add(new SBOLValidationException("sbol-10520", componentDefinition).getMessage());
}
}
}
// Cannot check this one separately, since it either violates 10516 also OR it violates
// best practices and does not use encodings from Table 1 or types from Table 2.
/*
if ((!componentDefinition.getTypes().contains(ComponentDefinition.DNA) &&
!componentDefinition.getTypes().contains(ComponentDefinition.RNA))
&& foundNucleic) {
errors.add(new SBOLValidationException("sbol-10517", componentDefinition).getMessage());
} else if (!componentDefinition.getTypes().contains(ComponentDefinition.PROTEIN) && foundProtein) {
errors.add(new SBOLValidationException("sbol-10517", componentDefinition).getMessage());
} else if (!componentDefinition.getTypes().contains(ComponentDefinition.SMALL_MOLECULE) && foundSmiles) {
errors.add(new SBOLValidationException("sbol-10517", componentDefinition).getMessage());
}
*/
}
}
private static boolean includesSequence(String specificSequence,String generalSequence) {
//if (specificSequence.length()!=generalSequence.length()) return false;
specificSequence = specificSequence.toLowerCase();
generalSequence = generalSequence.toLowerCase();
for (int i = 0; i < specificSequence.length(); i++) {
switch (generalSequence.charAt(i)) {
case 'a':
case 'c':
case 'g':
case 't':
case 'u':
if (specificSequence.charAt(i)!=generalSequence.charAt(i)) {
return false;
}
break;
case '.':
if (specificSequence.charAt(i)!='.' && specificSequence.charAt(i)!='-') {
return false;
}
break;
case '-':
if (specificSequence.charAt(i)!='.' && specificSequence.charAt(i)!='-') {
return false;
}
break;
case 'r':
if (specificSequence.charAt(i)!='r' && specificSequence.charAt(i)!='a' &&
specificSequence.charAt(i)!='g') {
return false;
}
break;
case 'y':
if (specificSequence.charAt(i)!='y' && specificSequence.charAt(i)!='c' &&
specificSequence.charAt(i)!='t') {
return false;
}
break;
case 's':
if (specificSequence.charAt(i)!='s' && specificSequence.charAt(i)!='c' &&
specificSequence.charAt(i)!='g') {
return false;
}
break;
case 'w':
if (specificSequence.charAt(i)!='w' && specificSequence.charAt(i)!='a' &&
specificSequence.charAt(i)!='t') {
return false;
}
break;
case 'k':
if (specificSequence.charAt(i)!='k' && specificSequence.charAt(i)!='g' &&
specificSequence.charAt(i)!='t') {
return false;
}
break;
case 'm':
if (specificSequence.charAt(i)!='m' && specificSequence.charAt(i)!='a' &&
specificSequence.charAt(i)!='c') {
return false;
}
break;
case 'b':
if (specificSequence.charAt(i)!='k' && specificSequence.charAt(i)!='g' &&
specificSequence.charAt(i)!='t' && specificSequence.charAt(i)!='c') {
return false;
}
break;
case 'd':
if (specificSequence.charAt(i)!='d' && specificSequence.charAt(i)!='g' &&
specificSequence.charAt(i)!='t' && specificSequence.charAt(i)!='a') {
return false;
}
break;
case 'h':
if (specificSequence.charAt(i)!='h' && specificSequence.charAt(i)!='c' &&
specificSequence.charAt(i)!='t' && specificSequence.charAt(i)!='a') {
return false;
}
break;
case 'v':
if (specificSequence.charAt(i)!='v' && specificSequence.charAt(i)!='g' &&
specificSequence.charAt(i)!='c' && specificSequence.charAt(i)!='a') {
return false;
}
break;
case 'n':
break;
default:
return false;
}
}
return true;
}
// TODO: this should be checked in object construction, so removed from validator, need to verify
/*
private static void validateSequenceConstraints(SBOLDocument sbolDocument) {
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
for (SequenceConstraint sequenceConstraint : componentDefinition.getSequenceConstraints()) {
try {
checkSequenceConstraint(componentDefinition,sequenceConstraint);
}
catch (SBOLValidationException e) {
errors.add(e.getMessage());
}
}
}
}
*/
private static void validateSequenceAnnotations(SBOLDocument sbolDocument) {
for (ComponentDefinition componentDefinition : sbolDocument.getComponentDefinitions()) {
for (SequenceAnnotation sequenceAnnotation : componentDefinition.getSequenceAnnotations()) {
Object[] locations = sequenceAnnotation.getLocations().toArray();
for (int i = 0; i < locations.length-1; i++) {
for (int j = i + 1; j < locations.length; j++) {
Location location1 = (Location) locations[i];
Location location2 = (Location) locations[j];
if (location1.getIdentity().equals(location2.getIdentity())) continue;
if (location1 instanceof Range && location2 instanceof Range) {
if (((((Range)location1).getStart() >= ((Range)location2).getStart()) &&
(((Range)location1).getStart() <= ((Range)location2).getEnd()))
||
((((Range)location2).getStart() >= ((Range)location1).getStart()) &&
(((Range)location2).getStart() <= ((Range)location1).getEnd()))) {
errors.add(new SBOLValidationException("sbol-10903", location1, location2).getMessage());
}
} else if (location1 instanceof Range && location2 instanceof Cut) {
if ((((Range)location1).getEnd() > ((Cut)location2).getAt()) &&
(((Cut)location2).getAt() >= ((Range)location1).getStart())) {
errors.add(new SBOLValidationException("sbol-10903", location1, location2).getMessage());
}
} else if (location2 instanceof Range && location1 instanceof Cut) {
if ((((Range)location2).getEnd() > ((Cut)location1).getAt()) &&
(((Cut)location1).getAt() >= ((Range)location2).getStart())) {
errors.add(new SBOLValidationException("sbol-10903", location1, location2).getMessage());
}
} else if (location2 instanceof Cut && location1 instanceof Cut) {
if (((Cut)location2).getAt() == ((Cut)location1).getAt()) {
errors.add(new SBOLValidationException("sbol-10903", location1, location2).getMessage());
}
}
}
}
}
}
}
private static final String IUPAC_DNA_PATTERN = "([ACGTURYSWKMBDHVN\\-\\.]*)";
private static final Pattern iupacDNAparser = Pattern.compile(IUPAC_DNA_PATTERN);
private static final String IUPAC_PROTEIN_PATTERN = "([ABCDEFGHIKLMNPQRSTVWXYZ]*)";
private static final Pattern iupacProteinParser = Pattern.compile(IUPAC_PROTEIN_PATTERN);
private static OpenSmilesParser openSmilesParser = new OpenSmilesParser();
static boolean checkSequenceEncoding(Sequence sequence) {
if (sequence.getEncoding().equals(Sequence.IUPAC_DNA) ||
(sequence.getEncoding().equals(Sequence.IUPAC_RNA))) {
Matcher m = iupacDNAparser.matcher(sequence.getElements().toUpperCase());
return m.matches();
} else if (sequence.getEncoding().equals(Sequence.IUPAC_PROTEIN)) {
Matcher m = iupacProteinParser.matcher(sequence.getElements().toUpperCase());
return m.matches();
} else if (sequence.getEncoding().equals(Sequence.SMILES)) {
return openSmilesParser.check(sequence.getElements());
}
return true;
}
// TODO: this should be checked in object construction, so removed from validator, need to verify
/*
private static void validateSequenceEncodings(SBOLDocument sbolDocument) {
for (Sequence sequence : sbolDocument.getSequences()) {
if (!checkSequenceEncoding(sequence)) {
errors.add(new SBOLValidationException("sbol-10405", sequence).getMessage());
}
}
}
*/
private static void validatePersistentIdentityUniqueness(SBOLDocument sbolDocument) {
HashMap<URI, Identified> elements = new HashMap<>();
for (TopLevel topLevel : sbolDocument.getTopLevels()) {
if (!topLevel.isSetPersistentIdentity()) continue;
if (elements.get(topLevel.getPersistentIdentity())!=null) {
Identified identified = elements.get(topLevel.getPersistentIdentity());
if (!topLevel.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", topLevel).getMessage());
}
}
elements.put(topLevel.getPersistentIdentity(),topLevel);
if (topLevel instanceof ComponentDefinition) {
for (Component c : ((ComponentDefinition) topLevel).getComponents()) {
if (!c.isSetPersistentIdentity()) continue;
if (elements.get(c.getPersistentIdentity())!=null) {
Identified identified = elements.get(c.getPersistentIdentity());
if (!c.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", c).getMessage());
}
}
elements.put(c.getPersistentIdentity(),c);
for (MapsTo m : c.getMapsTos()) {
if (!m.isSetPersistentIdentity()) continue;
if (elements.get(m.getPersistentIdentity())!=null) {
Identified identified = elements.get(m.getPersistentIdentity());
if (!m.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", m).getMessage());
}
}
elements.put(m.getPersistentIdentity(),m);
}
}
for (SequenceAnnotation sa : ((ComponentDefinition) topLevel).getSequenceAnnotations()) {
if (!sa.isSetPersistentIdentity()) continue;
if (elements.get(sa.getPersistentIdentity())!=null) {
Identified identified = elements.get(sa.getPersistentIdentity());
if (!sa.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", sa).getMessage());
}
}
elements.put(sa.getPersistentIdentity(),sa);
for (Location l : sa.getLocations()) {
if (!l.isSetPersistentIdentity()) continue;
if (elements.get(l.getPersistentIdentity())!=null) {
Identified identified = elements.get(l.getPersistentIdentity());
if (!l.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", l).getMessage());
}
}
elements.put(l.getPersistentIdentity(),l);
}
}
for (SequenceConstraint sc : ((ComponentDefinition) topLevel).getSequenceConstraints()) {
if (!sc.isSetPersistentIdentity()) continue;
if (elements.get(sc.getPersistentIdentity())!=null) {
Identified identified = elements.get(sc.getPersistentIdentity());
if (!sc.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", sc).getMessage());
}
}
elements.put(sc.getPersistentIdentity(),sc);
}
}
if (topLevel instanceof ModuleDefinition) {
for (FunctionalComponent c : ((ModuleDefinition) topLevel).getFunctionalComponents()) {
if (!c.isSetPersistentIdentity()) continue;
if (elements.get(c.getPersistentIdentity())!=null) {
Identified identified = elements.get(c.getPersistentIdentity());
if (!c.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", c).getMessage());
}
}
elements.put(c.getPersistentIdentity(),c);
for (MapsTo m : c.getMapsTos()) {
if (!m.isSetPersistentIdentity()) continue;
if (elements.get(m.getPersistentIdentity())!=null) {
Identified identified = elements.get(m.getPersistentIdentity());
if (!m.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", m).getMessage());
}
}
elements.put(m.getPersistentIdentity(),m);
}
}
for (Module mod : ((ModuleDefinition) topLevel).getModules()) {
if (!mod.isSetPersistentIdentity()) continue;
if (elements.get(mod.getPersistentIdentity())!=null) {
Identified identified = elements.get(mod.getPersistentIdentity());
if (!mod.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", mod).getMessage());
}
}
elements.put(mod.getPersistentIdentity(),mod);
for (MapsTo m : mod.getMapsTos()) {
if (!m.isSetPersistentIdentity()) continue;
if (elements.get(m.getPersistentIdentity())!=null) {
Identified identified = elements.get(m.getPersistentIdentity());
if (!m.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", m).getMessage());
}
}
elements.put(m.getPersistentIdentity(),m);
}
}
for (Interaction i : ((ModuleDefinition) topLevel).getInteractions()) {
if (!i.isSetPersistentIdentity()) continue;
if (elements.get(i.getPersistentIdentity())!=null) {
Identified identified = elements.get(i.getPersistentIdentity());
if (!i.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", i).getMessage());
}
}
elements.put(i.getPersistentIdentity(),i);
for (Participation p : i.getParticipations()) {
if (!p.isSetPersistentIdentity()) continue;
if (elements.get(p.getPersistentIdentity())!=null) {
Identified identified = elements.get(p.getPersistentIdentity());
if (!p.getClass().equals(identified.getClass())) {
errors.add(new SBOLValidationException("sbol-10220", p).getMessage());
}
}
elements.put(p.getPersistentIdentity(),p);
}
}
}
}
}
private static void validateURIuniqueness(SBOLDocument sbolDocument) {
HashMap<URI, Identified> elements = new HashMap<>();
for (TopLevel topLevel : sbolDocument.getTopLevels()) {
if (elements.get(topLevel.getIdentity())!=null) {
Identified identified = elements.get(topLevel.getIdentity());
if (!topLevel.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", topLevel).getMessage());
}
}
elements.put(topLevel.getIdentity(),topLevel);
if (topLevel instanceof ComponentDefinition) {
for (Component c : ((ComponentDefinition) topLevel).getComponents()) {
if (elements.get(c.getIdentity())!=null) {
Identified identified = elements.get(c.getIdentity());
if (!c.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", c).getMessage());
}
}
elements.put(c.getIdentity(),c);
for (MapsTo m : c.getMapsTos()) {
if (elements.get(m.getIdentity())!=null) {
Identified identified = elements.get(m.getIdentity());
if (!m.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", m).getMessage());
}
}
elements.put(m.getIdentity(),m);
}
}
for (SequenceAnnotation sa : ((ComponentDefinition) topLevel).getSequenceAnnotations()) {
if (elements.get(sa.getIdentity())!=null) {
Identified identified = elements.get(sa.getIdentity());
if (!sa.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", sa).getMessage());
}
}
elements.put(sa.getIdentity(),sa);
for (Location l : sa.getLocations()) {
if (elements.get(l.getIdentity())!=null) {
Identified identified = elements.get(l.getIdentity());
if (!l.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", l).getMessage());
}
}
elements.put(l.getIdentity(),l);
}
}
for (SequenceConstraint sc : ((ComponentDefinition) topLevel).getSequenceConstraints()) {
if (elements.get(sc.getIdentity())!=null) {
Identified identified = elements.get(sc.getIdentity());
if (!sc.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", sc).getMessage());
}
}
elements.put(sc.getIdentity(),sc);
}
}
if (topLevel instanceof ModuleDefinition) {
for (FunctionalComponent c : ((ModuleDefinition) topLevel).getFunctionalComponents()) {
if (elements.get(c.getIdentity())!=null) {
Identified identified = elements.get(c.getIdentity());
if (!c.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", c).getMessage());
}
}
elements.put(c.getIdentity(),c);
for (MapsTo m : c.getMapsTos()) {
if (elements.get(m.getIdentity())!=null) {
Identified identified = elements.get(m.getIdentity());
if (!m.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", m).getMessage());
}
}
elements.put(m.getIdentity(),m);
}
}
for (Module mod : ((ModuleDefinition) topLevel).getModules()) {
if (elements.get(mod.getIdentity())!=null) {
Identified identified = elements.get(mod.getIdentity());
if (!mod.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", mod).getMessage());
}
}
elements.put(mod.getIdentity(),mod);
for (MapsTo m : mod.getMapsTos()) {
if (elements.get(m.getIdentity())!=null) {
Identified identified = elements.get(m.getIdentity());
if (!m.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", m).getMessage());
}
}
elements.put(m.getIdentity(),m);
}
}
for (Interaction i : ((ModuleDefinition) topLevel).getInteractions()) {
if (elements.get(i.getIdentity())!=null) {
Identified identified = elements.get(i.getIdentity());
if (!i.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", i).getMessage());
}
}
elements.put(i.getIdentity(),i);
for (Participation p : i.getParticipations()) {
if (elements.get(p.getIdentity())!=null) {
Identified identified = elements.get(p.getIdentity());
if (!p.equals(identified)) {
errors.add(new SBOLValidationException("sbol-10202", p).getMessage());
}
}
elements.put(p.getIdentity(),p);
}
}
}
}
}
/**
* Validates the given SBOL document. Errors encountered either throw exceptions or, if not fatal, are added to the list of errors
* that can be accessed using the {@link #getErrors()} method. Interpretations of the complete, compliant, and bestPractice parameters
* are as follows:
* <ul>
* <li> complete: A {@code true} value means that all identity URI references in the given SBOL document can dereference to objects
* in the same document; a {@code false} value means otherwise.</li>
* <li> compliant: A {@code true} value means that all URIs in the given SBOL document are compliant; a {@code false} value means otherwise.</li>
* <li> best practice: A {@code true} value means that validation rules with the RECOMMENDED condition in the SBOL specification are
* checked against the given SBOLDocuemnt object; a {@code false} value means otherwise.</li>
* </ul>
*
* @param sbolDocument the given {@code SBOLDocument} object
* @param complete the given {@code complete} flag
* @param compliant the given {@code compliant} flag
* @param bestPractice the given {@code bestPractice} flag
*/
public static void validateSBOL(SBOLDocument sbolDocument, boolean complete, boolean compliant,
boolean bestPractice) {
clearErrors();
//validateSequenceEncodings(sbolDocument);
//validateSequenceConstraints(sbolDocument);
validateWasDerivedFromVersion(sbolDocument);
validateCircularReferences(sbolDocument);
validateURIuniqueness(sbolDocument);
validatePersistentIdentityUniqueness(sbolDocument);
validateMapsTos(sbolDocument);
if (compliant) validateCompliance(sbolDocument);
if (complete) validateCompleteness(sbolDocument);
if (bestPractice) {
validateOntologyUsage(sbolDocument);
validateSequenceAnnotations(sbolDocument);
validateComponentDefinitionSequences(sbolDocument);
}
}
/**
* Compares the given two SBOL documents and outputs the "standard" error output stream (System.err).
*
* @param file1 the file name associated with {@code doc1}
* @param doc1 the first SBOL document
* @param file2 the file name associated with {@code doc2}
* @param doc2 the second SBOL document
*/
public static void compareDocuments(String file1, SBOLDocument doc1, String file2, SBOLDocument doc2) {
/*if (!doc1.getNamespaces().equals(doc2.getNamespaces())) {
System.err.println("Namespaces do not match");
System.err.println(doc1.getNamespaces().toString());
System.err.println(doc2.getNamespaces().toString());
}*/
for (QName namespace : doc1.getNamespaces()) {
if (doc2.getNamespaces().contains(namespace)) continue;
System.err.println("Namesapce " + namespace.toString() + " not found in " + file2);
}
for (QName namespace : doc2.getNamespaces()) {
if (doc1.getNamespaces().contains(namespace)) continue;
System.err.println("Namesapce " + namespace.toString() + " not found in " + file1);
}
for (GenericTopLevel genericTopLevel1 : doc1.getGenericTopLevels()) {
GenericTopLevel genericTopLevel2 = doc2.getGenericTopLevel(genericTopLevel1.getIdentity());
if (genericTopLevel2==null) {
System.err.println("Collection " + genericTopLevel1.getIdentity() + " not found in " + file2);
} else if (!genericTopLevel1.equals(genericTopLevel2)) {
System.err.println("Collection " + genericTopLevel1.getIdentity() + " differ.");
}
}
for (GenericTopLevel genericTopLevel2 : doc2.getGenericTopLevels()) {
GenericTopLevel genericTopLevel1 = doc1.getGenericTopLevel(genericTopLevel2.getIdentity());
if (genericTopLevel1==null) {
System.err.println("Collection " + genericTopLevel2.getIdentity() + " not found in " + file1);
}
}
/*
if (!doc1.getCollections().equals(doc2.getCollections())) {
System.err.println("Collections do not match");
System.out.println(doc1.getCollections().toString());
System.out.println(doc2.getCollections().toString());
}
*/
for (Collection collection1 : doc1.getCollections()) {
Collection collection2 = doc2.getCollection(collection1.getIdentity());
if (collection2==null) {
System.err.println("Collection " + collection1.getIdentity() + " not found in " + file2);
} else if (!collection1.equals(collection2)) {
System.err.println("Collection " + collection1.getIdentity() + " differ.");
}
}
for (Collection collection2 : doc2.getCollections()) {
Collection collection1 = doc1.getCollection(collection2.getIdentity());
if (collection1==null) {
System.err.println("Collection " + collection2.getIdentity() + " not found in " + file1);
}
}
/*
if (!doc1.getSequences().equals(doc2.getSequences())) {
System.err.println("Sequences do not match");
}
*/
for (Sequence sequence1 : doc1.getSequences()) {
Sequence sequence2 = doc2.getSequence(sequence1.getIdentity());
if (sequence2==null) {
System.err.println("Sequence " + sequence1.getIdentity() + " not found in " + file2);
} else if (!sequence1.equals(sequence2)) {
System.err.println("Sequence " + sequence1.getIdentity() + " differ.");
}
}
for (Sequence sequence2 : doc2.getSequences()) {
Sequence sequence1 = doc1.getSequence(sequence2.getIdentity());
if (sequence1==null) {
System.err.println("Sequence " + sequence2.getIdentity() + " not found in " + file1);
}
}
/*
if (!doc1.getComponentDefinitions().equals(doc2.getComponentDefinitions())) {
System.err.println("ComponentDefinitions do not match");
}
*/
for (ComponentDefinition componentDefinition1 : doc1.getComponentDefinitions()) {
ComponentDefinition componentDefinition2 = doc2.getComponentDefinition(componentDefinition1.getIdentity());
if (componentDefinition2==null) {
System.err.println("ComponentDefinition " + componentDefinition1.getIdentity() + " not found in " + file2);
} else if (!componentDefinition1.equals(componentDefinition2)) {
System.err.println("ComponentDefinition " + componentDefinition1.getIdentity() + " differ.");
//System.err.println(componentDefinition1.toString());
//System.err.println(componentDefinition2.toString());
}
}
for (ComponentDefinition componentDefinition2 : doc2.getComponentDefinitions()) {
ComponentDefinition componentDefinition1 = doc1.getComponentDefinition(componentDefinition2.getIdentity());
if (componentDefinition1==null) {
System.err.println("ComponentDefinition " + componentDefinition2.getIdentity() + " not found in " + file1);
}
}
for (ModuleDefinition moduleDefinition1 : doc1.getModuleDefinitions()) {
ModuleDefinition moduleDefinition2 = doc2.getModuleDefinition(moduleDefinition1.getIdentity());
if (moduleDefinition2==null) {
System.err.println("ModuleDefinition " + moduleDefinition1.getIdentity() + " not found in " + file2);
} else if (!moduleDefinition1.equals(moduleDefinition2)) {
System.err.println("ModuleDefinition " + moduleDefinition1.getIdentity() + " differ.");
}
}
for (ModuleDefinition moduleDefinition2 : doc2.getModuleDefinitions()) {
ModuleDefinition moduleDefinition1 = doc1.getModuleDefinition(moduleDefinition2.getIdentity());
if (moduleDefinition1==null) {
System.err.println("ModuleDefinition " + moduleDefinition2.getIdentity() + " not found in " + file1);
}
}
for (Model model1 : doc1.getModels()) {
Model model2 = doc2.getModel(model1.getIdentity());
if (model2==null) {
System.err.println("Model " + model1.getIdentity() + " not found in " + file2);
} else if (!model1.equals(model2)) {
System.err.println("Model " + model1.getIdentity() + " differ.");
}
}
for (Model model2 : doc2.getModels()) {
Model model1 = doc1.getModel(model2.getIdentity());
if (model1==null) {
System.err.println("Model " + model2.getIdentity() + " not found in " + file1);
}
}
}
private static void usage() {
System.err.println("libSBOLj version " + libSBOLj_Version);
System.err.println("Description: validates the contents of an SBOL " + SBOLVersion + " document, can compare two documents,\n"
+ "and can convert to/from SBOL 1.1, GenBank, and FASTA formats.");
System.err.println();
System.err.println("Usage:");
System.err.println("\tjava --jar libSBOLj.jar [options] <inputFile> [-o <outputFile> -e <compareFile>]");
System.err.println();
System.err.println("Options:");
System.err.println("\t-l <language> specfies language (SBOL1/SBOL2/GenBank/FASTA) for output (default=SBOL2)");
System.err.println("\t-s <topLevelURI> select only this object and those it references");
System.err.println("\t-p <URIprefix> used for converted objects");
System.err.println("\t-v <version> used for converted objects");
System.err.println("\t-t uses types in URIs");
System.err.println("\t-n allow non-compliant URIs");
System.err.println("\t-i allow SBOL document to be incomplete");
System.err.println("\t-b check best practices");
System.err.println("\t-f fail on first error");
System.err.println("\t-d display detailed error trace");
System.exit(1);
}
/**
* Command line method for reading an input file and producing an output file.
* <p>
* By default, validations on compliance and completeness are performed, and types
* for top-level objects are not used in URIs.
* <p>
* Options:
* <p>
* "-o" specifies an output filename
* <p>
* "-e" specifies a file to compare if equal to
* <p>
* "-l" indicates the language for output (default=SBOL2, other options SBOL1, GenBank, FASTA)
* <p>
* "-s" select only this topLevel object and those it references
* <p>
* "-p" specifies the default URI prefix for converted objects
* <p>
* "-v" specifies version to use for converted objects
* <p>
* "-t" uses types in URIs
* <p>
* "-n" allow non-compliant URIs
* <p>
* "-i" allow SBOL document to be incomplete
* <p>
* "-b" check best practices
* <p>
* "-f" fail on first error
* <p>
* "-d" display detailed error trace
*
* @param args arguments supplied at command line
*/
public static void main(String[] args) {
String fileName = "";
String outputFile = "";
String compareFile = "";
String topLevelURIStr = "";
String URIPrefix = "";
String version = "";
boolean complete = true;
boolean compliant = true;
boolean typesInURI = false;
boolean bestPractice = false;
boolean keepGoing = true;
boolean showDetail = false;
boolean genBankOut = false;
boolean fastaOut = false;
boolean sbolV1out = false;
int i = 0;
while (i < args.length) {
if (args[i].equals("-i")) {
complete = false;
} else if (args[i].equals("-t")) {
typesInURI = true;
} else if (args[i].equals("-b")) {
bestPractice = true;
} else if (args[i].equals("-n")) {
compliant = false;
} else if (args[i].equals("-f")) {
keepGoing = false;
} else if (args[i].equals("-d")) {
showDetail = true;
} else if (args[i].equals("-s")) {
if (i+1 >= args.length) {
usage();
}
topLevelURIStr = args[i+1];
i++;
} else if (args[i].equals("-l")) {
if (i+1 >= args.length) {
usage();
}
if (args[i+1].equals("SBOL1")) {
sbolV1out = true;
} else if (args[i+1].equals("GenBank")) {
genBankOut = true;
} else if (args[i+1].equals("FASTA")) {
fastaOut = true;
} else if (args[i+1].equals("SBOL2")) {
} else {
usage();
}
i++;
} else if (args[i].equals("-o")) {
if (i+1 >= args.length) {
usage();
}
outputFile = args[i+1];
i++;
} else if (args[i].equals("-e")) {
if (i+1 >= args.length) {
usage();
}
compareFile = args[i+1];
i++;
} else if (args[i].equals("-p")) {
if (i+1 >= args.length) {
usage();
}
URIPrefix = args[i+1];
i++;
} else if (args[i].equals("-v")) {
if (i+1 >= args.length) {
usage();
}
version = args[i+1];
i++;
} else if (fileName.equals("")) {
fileName = args[i];
} else {
usage();
}
i++;
}
if (fileName.equals("")) usage();
try {
SBOLDocument doc = null;
if (!URIPrefix.equals("")) {
SBOLReader.setURIPrefix(URIPrefix);
}
if (!compliant) {
SBOLReader.setCompliant(false);
}
SBOLReader.setTypesInURI(typesInURI);
SBOLReader.setVersion(version);
SBOLReader.setKeepGoing(keepGoing);
SBOLWriter.setKeepGoing(keepGoing);
if (FASTA.isFastaFile(fileName)) {
System.err.println("Converting FASTA to SBOL Version 2");
} else if (GenBank.isGenBankFile(fileName)) {
System.err.println("Converting GenBank to SBOL Version 2");
} else if (SBOLReader.getSBOLVersion(fileName).equals(SBOLReader.SBOLVERSION1)) {
System.err.println("Converting SBOL Version 1 to SBOL Version 2");
}
doc = SBOLReader.read(fileName);
doc.setTypesInURIs(typesInURI);
if (!compareFile.equals("")) {
SBOLDocument doc2 = SBOLReader.read(compareFile);
File f = new File(fileName);
String fileNameStr = f.getName();
f = new File(compareFile);
String compareFileStr = f.getName();
compareDocuments(fileNameStr, doc, compareFileStr, doc2);
}
validateSBOL(doc, complete, compliant, bestPractice);
if (getNumErrors()==0 && SBOLReader.getNumErrors()==0) {
if (!topLevelURIStr.equals("")) {
TopLevel topLevel = doc.getTopLevel(URI.create(topLevelURIStr));
if (topLevel==null) {
System.err.println("TopLevel " + topLevelURIStr + " not found.");
return;
}
doc = doc.createRecursiveCopy(topLevel);
}
if (genBankOut) {
if (outputFile.equals("")) {
SBOLWriter.write(doc, (System.out), SBOLDocument.GENBANK);
} else {
System.out.println("Validation successful, no errors.");
SBOLWriter.write(doc, outputFile, SBOLDocument.GENBANK);
}
} else if (sbolV1out) {
if (outputFile.equals("")) {
SBOLWriter.write(doc, (System.out), SBOLDocument.RDFV1);
} else {
System.out.println("Validation successful, no errors.");
SBOLWriter.write(doc, outputFile, SBOLDocument.RDFV1);
}
if (SBOLWriter.getNumErrors()!=0) {
for (String error : SBOLWriter.getErrors()) {
System.err.println(error);
}
}
} else if (fastaOut) {
if (outputFile.equals("")) {
SBOLWriter.write(doc, (System.out), SBOLDocument.FASTAformat);
} else {
System.out.println("Validation successful, no errors.");
SBOLWriter.write(doc, outputFile, SBOLDocument.FASTAformat);
}
} else {
if (outputFile.equals("")) {
SBOLWriter.write(doc, (System.out));
} else {
System.out.println("Validation successful, no errors.");
SBOLWriter.write(doc, outputFile);
}
}
} else {
if (getNumErrors()!=0) {
for (String error : getErrors()) {
System.err.println(error);
}
}
if (SBOLReader.getNumErrors()!=0) {
for (String error : SBOLReader.getErrors()) {
System.err.println(error);
}
}
System.err.println("Validation failed.\n");
}
}
catch (Exception e) {
if (showDetail) {
e.printStackTrace();
}
if (e.getMessage()!=null) {
System.err.println(e.getMessage()+"\nValidation failed.");
} else {
e.printStackTrace();
System.err.println("\nValidation failed.");
}
}
catch (Throwable e) {
if (showDetail) {
e.printStackTrace();
}
if (e.getMessage()!=null) {
System.err.println(e.getMessage()+"\nValidation failed.");
} else {
e.printStackTrace();
System.err.println("\nValidation failed.");
}
}
}
} |
package codeOrchestra.colt.core;
import codeOrchestra.colt.core.loading.LiveCodingHandlerLoadingException;
import codeOrchestra.colt.core.loading.LiveCodingHandlerManager;
import codeOrchestra.colt.core.logging.Logger;
import codeOrchestra.colt.core.model.Project;
import codeOrchestra.colt.core.model.ProjectHandlerIdParser;
import codeOrchestra.colt.core.model.listener.ProjectListener;
import codeOrchestra.colt.core.model.monitor.ChangingMonitor;
import codeOrchestra.util.FileUtils;
import codeOrchestra.util.ProjectHelper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* @author Alexander Eliseyev
*/
public class ColtProjectManager {
private static ColtProjectManager instance;
public static synchronized ColtProjectManager getInstance() {
if (instance == null) {
instance = new ColtProjectManager();
}
return instance;
}
private List<ProjectListener> projectListeners = new ArrayList<>();
private Project currentProject;
private ColtProjectManager() {
addProjectListener(new ProjectListener() {
@Override
public void onProjectLoaded(Project project) {
RecentProjects.addRecentProject(project.getPath());
Logger.getLogger(ColtProjectManager.class).info("Loaded " + project.getProjectType() + " project " + project.getName() + " on "
+ DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US).format(new Date()));
}
@Override
public void onProjectUnloaded(Project project) {
}
});
}
public synchronized Project getCurrentProject() {
return currentProject;
}
public synchronized void fireProjectLoaded() {
for (ProjectListener projectListener : projectListeners) {
projectListener.onProjectLoaded(getCurrentProject());
}
}
public synchronized void fireProjectClosed() {
for (ProjectListener projectListener : projectListeners) {
projectListener.onProjectUnloaded(getCurrentProject());
}
}
public synchronized void addProjectListener(ProjectListener projectListener) {
projectListeners.add(projectListener);
}
public synchronized void removeProjectListener(ProjectListener projectListener) {
projectListeners.remove(projectListener);
}
public synchronized void load(String path) throws ColtException {
if (currentProject != null) {
unload();
}
File projectFile = new File(path);
String projectFileContents = FileUtils.read(projectFile);
if (ProjectHelper.isLegacyProject(projectFileContents)) {
importProject(projectFile);
return;
}
ProjectHandlerIdParser coltProjectHandlerIdParser = new ProjectHandlerIdParser(projectFileContents);
String handlerId = coltProjectHandlerIdParser.getHandlerId();
if (handlerId == null) {
throw new ColtException("Can't figure out the handler ID for the project path " + path);
}
try {
LiveCodingHandlerManager.getInstance().load(handlerId);
} catch (LiveCodingHandlerLoadingException e) {
throw new ColtException("Can't load the handler for the project type " + handlerId);
}
// Parse the project
LiveCodingLanguageHandler handler = LiveCodingHandlerManager.getInstance().getCurrentHandler();
currentProject = handler.parseProject(coltProjectHandlerIdParser.getNode(), path);
ChangingMonitor.getInstance().reset();
fireProjectLoaded();
}
public synchronized void save() throws ColtException {
File file = new File(currentProject.getPath());
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
fileWriter.write(currentProject.toXmlString());
fileWriter.close();
ChangingMonitor.getInstance().reset();
} catch (IOException e) {
throw new ColtException("Can't write COLT project file to " + file.getPath());
}
}
public synchronized void create(String handlerId, String pName, File pFile) throws ColtException {
try {
LiveCodingHandlerManager.getInstance().load(handlerId);
} catch (LiveCodingHandlerLoadingException e) {
throw new ColtException("Can't load the handler for the project type " + handlerId);
}
LiveCodingLanguageHandler handler = LiveCodingHandlerManager.getInstance().getCurrentHandler();
currentProject = handler.createProject(pName, pFile);
currentProject.setPath(pFile.getPath());
save();
fireProjectLoaded();
}
private synchronized void importProject(File file) throws ColtException {
String handlerId = "AS";
try {
LiveCodingHandlerManager.getInstance().load(handlerId);
} catch (LiveCodingHandlerLoadingException e) {
throw new ColtException("Can't load the handler for the project type " + handlerId);
}
LiveCodingLanguageHandler handler = LiveCodingHandlerManager.getInstance().getCurrentHandler();
currentProject = handler.importProject(file);
currentProject.setPath(file.getPath());
ChangingMonitor.getInstance().reset();
fireProjectLoaded();
}
public synchronized void unload() throws ColtException {
// TODO: implement
fireProjectClosed();
}
public synchronized void dispose() {
try {
unload();
} catch (ColtException e) {
// ignore
}
projectListeners.clear();
currentProject = null;
}
} |
package com.afollestad.silk.cache;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import com.afollestad.silk.adapters.SilkAdapter;
import com.afollestad.silk.fragments.SilkCachedFeedFragment;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Handles caching feeds locally.
*
* @author Aidan Follestad (afollestad)
*/
public final class SilkCacheManager<T extends SilkComparable> {
public interface AddCallback<T> {
public void onAdded(T item);
public void onIgnored(T item);
public void onError(Exception e);
}
public interface UpdateCallback<T> {
public void onUpdated(T item, boolean added);
public void onError(Exception e);
}
public interface WriteCallback<T> {
public void onWrite(List<T> items, boolean isAppended);
public void onError(Exception e);
}
public interface ReadCallback<T> {
public void onRead(List<T> results);
public void onError(Exception e);
public void onCacheEmpty();
}
public interface RemoveCallback<T> {
public void onRemoved(List<T> items);
public void onError(Exception e);
}
public interface RemoveFilter<T> {
public boolean shouldRemove(T item);
}
/**
* Initializes a new SilkCacheManager, using the default cache file and default cache directory.
*/
public SilkCacheManager() {
init(null, null, null);
}
/**
* Initializes a new SilkCacheManager, using the default cache directory.
*
* @param cacheName The name of the cache, must be unique from other feed caches, but must also be valid for being in a file name.
*/
public SilkCacheManager(String cacheName) {
init(cacheName, null, null);
}
/**
* Initializes a new SilkCacheManager.
*
* @param cacheName The name of the cache, must be unique from other feed caches, but must also be valid for being in a file name.
* @param cacheDir The directory that the cache file will be stored in, defaults to "/sdcard/Silk".
*/
public SilkCacheManager(String cacheName, File cacheDir) {
init(cacheName, cacheDir, null);
}
public SilkCacheManager(String cacheName, File cacheDir, Handler handler) {
init(cacheName, cacheDir, handler);
}
private Handler mHandler;
private File cacheFile;
private void init(String cacheName, File cacheDir, Handler handler) {
if (cacheName == null || cacheName.trim().isEmpty())
cacheName = "default";
if (handler == null)
mHandler = new Handler();
else mHandler = handler;
if (cacheDir == null)
cacheDir = new File(Environment.getExternalStorageDirectory(), "Silk");
if (!cacheDir.exists())
cacheDir.mkdirs();
cacheFile = new File(cacheDir, cacheName.toLowerCase() + ".cache");
}
private void log(String message) {
Log.d("SilkCacheManager", message);
}
/**
* Writes a single object to the cache, without overwriting previous entries.
*
* @param toAdd the item to add to the cache.
*/
public boolean add(T toAdd) throws Exception {
if (toAdd.shouldIgnore()) return false;
List<T> temp = new ArrayList<T>();
temp.add(toAdd);
write(temp, true);
return true;
}
/**
* Updates an item in the cache. If it's not found, it's added.
*
* @param toUpdate The item to update, or add.
*/
public boolean update(T toUpdate) throws Exception {
if (toUpdate.shouldIgnore()) return false;
List<T> cache = read();
boolean found = false;
for (int i = 0; i < cache.size(); i++) {
if (cache.get(i).isSameAs(toUpdate)) {
cache.set(i, toUpdate);
found = true;
break;
}
}
if (found) write(cache);
else add(toUpdate);
return found;
}
/**
* Writes an list of items to the cache from the calling thread. Allows you set whether to overwrite the cache
* or append to it.
*/
public void write(List<T> items, boolean append) throws Exception {
if (items == null || items.size() == 0) {
if (cacheFile.exists() && !append) {
log(cacheFile.getName() + " is empty, deleting file...");
cacheFile.delete();
}
return;
}
int subtraction = 0;
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile, append);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (T item : items) {
if (item.shouldIgnore()) {
subtraction++;
continue;
}
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
log("Wrote " + (items.size() - subtraction) + " items to " + cacheFile.getName());
}
/**
* Writes an list of items to the cache from the calling thread, overwriting all current entries in the cache.
*/
public void write(List<T> items) throws Exception {
write(items, false);
}
/**
* Writes an adapter to the cache. The adapter will not be written if its isChanged() method returns false.
* The adapter's isChanged() is reset to false every time the cache reads to it or if it's reset elsewhere by you.
*/
public void write(SilkAdapter<T> adapter) throws Exception {
if (!adapter.isChanged()) {
log("The adapter has not been changed, skipped writing to " + cacheFile.getName());
return;
}
adapter.resetChanged();
write(adapter.getItems(), false);
}
/**
* Reads from the cache file on the calling thread and returns the results.
*/
public List<T> read() throws Exception {
final List<T> results = new ArrayList<T>();
if (cacheFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(cacheFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while (true) {
try {
final T item = (T) objectInputStream.readObject();
if (item != null) results.add(item);
} catch (EOFException eof) {
break;
}
}
objectInputStream.close();
}
log("Read " + results.size() + " items from " + cacheFile.getName());
return results;
}
/**
* Removes a single item from the cache, uses isSameAs() from the {@link SilkComparable} to find the item.
*/
public void remove(final T toRemove) throws Exception {
remove(new RemoveFilter<T>() {
@Override
public boolean shouldRemove(T item) {
return item.isSameAs(toRemove);
}
});
}
/**
* Removes multiple items from the cache, uses isSameAs() from the {@link SilkComparable} to find the item.
*/
public void remove(final T... toRemove) throws Exception {
remove(new RemoveFilter<T>() {
@Override
public boolean shouldRemove(T item) {
boolean found = false;
for (int i = 0; i < toRemove.length; i++) {
if (toRemove[i].isSameAs(item)) {
found = true;
break;
}
}
return found;
}
});
}
/**
* Removes items from the cache based on a filter that makes decisions. Returns a list of items that were removed.
*/
public List<T> remove(RemoveFilter<T> filter) throws Exception {
if (filter == null) throw new IllegalArgumentException("You must specify a filter");
List<T> toReturn = new ArrayList<T>();
List<T> cache = read();
if (cache.size() == 0) return toReturn;
for (int i = 0; i < cache.size(); i++) {
if (filter.shouldRemove(cache.get(i))) {
cache.remove(i);
toReturn.add(cache.get(i));
}
}
write(cache, false);
log("Removed " + toReturn.size() + " items from " + cacheFile.getName());
return toReturn;
}
private void runPriorityThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
/**
* Writes a single object to the cache from a separate thread, posting results to a callback.
*/
public void addAsync(final T toAdd, final AddCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
if (add(toAdd)) callback.onAdded(toAdd);
else callback.onIgnored(toAdd);
} catch (Exception e) {
log("Cache write error: " + e.getMessage());
callback.onError(e);
}
}
});
}
/**
* Updates an item in the cache. If it's not found, it's added. This is done on a separate thread and results are
* posted to a callback.
*/
public void updateAsync(final T toUpdate, final UpdateCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
boolean isAdded = update(toUpdate);
callback.onUpdated(toUpdate, isAdded);
} catch (Exception e) {
log("Cache write error: " + e.getMessage());
callback.onError(e);
}
}
});
}
/**
* Writes a list of items to the cache from a separate thread. Posts results to a callback.
*/
public void writeAsync(final List<T> items, final WriteCallback<T> callback) {
writeAsync(items, false, callback);
}
/**
* Writes an adapter to the cache from a separate thread. The adapter will not be written if its
* isChanged() method returns false. The adapter's isChanged() is reset to false every time the cache reads
* to it or if it's reset elsewhere by you.
*/
public void writeAsync(final SilkAdapter<T> adapter, final WriteCallback<T> callback) {
if (!adapter.isChanged()) {
log("The adapter has not been changed, skipped writing to " + cacheFile.getName());
return;
}
adapter.resetChanged();
writeAsync(adapter.getItems(), false, callback);
}
/**
* Writes a list of items to the cache from a separate thread. Allows you set whether to overwrite the cache
* or append to it. Posts results to a callback.
*/
public void writeAsync(final List<T> items, final boolean append, final WriteCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
write(items, append);
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onWrite(items, append);
}
});
} catch (final Exception e) {
log("Cache write error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
/**
* Reads from the cache file on a separate thread and posts results to a callback.
*/
public void readAsync(final ReadCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
if (!cacheFile.exists()) {
log("No cache for " + cacheFile.getName());
callback.onCacheEmpty();
return;
}
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final List<T> results = read();
mHandler.post(new Runnable() {
@Override
public void run() {
if (results.size() == 0) callback.onCacheEmpty();
else callback.onRead(results);
}
});
} catch (final Exception e) {
log("Cache read error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
/**
* Reads from the manager's cache file into a {@link SilkAdapter}, and notifies a {@link SilkCachedFeedFragment} when it's loading and done loading.
*
* @param adapter The adapter that items will be added to.
* @param fragment The optional fragment that will receive loading notifications.
*/
public void readAsync(final SilkAdapter<T> adapter, final SilkCachedFeedFragment fragment) {
if (adapter == null)
throw new IllegalArgumentException("The adapter parameter cannot be null.");
else if (fragment != null && fragment.isLoading()) return;
if (fragment != null) fragment.setLoading(false);
readAsync(new ReadCallback<T>() {
@Override
public void onRead(List<T> results) {
for (T item : results) adapter.add(item);
if (fragment != null) fragment.setLoadFromCacheComplete(false);
adapter.resetChanged();
}
@Override
public void onError(Exception e) {
if (fragment != null) {
fragment.setLoadFromCacheComplete(true);
if (adapter.getCount() == 0) fragment.onCacheEmpty();
}
adapter.resetChanged();
}
@Override
public void onCacheEmpty() {
if (fragment != null) {
fragment.setLoadFromCacheComplete(false);
fragment.onCacheEmpty();
}
adapter.resetChanged();
}
});
}
/**
* Removes a single item from the cache, uses isSameAs() remove the {@link RemoveFilter} to find the item. Results are
* posted to a callback.
*/
public void removeAsync(final T toRemove, final RemoveCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final List<T> results = remove(new RemoveFilter<T>() {
@Override
public boolean shouldRemove(T item) {
return item.isSameAs(toRemove);
}
});
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onRemoved(results);
}
});
} catch (final Exception e) {
log("Cache remove error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
/**
* Removes items from the cache based on a filter that makes decisions. Results are posted to a callback.
*/
public void removeAsync(final RemoveFilter<T> filter, final RemoveCallback<T> callback) {
if (filter == null) throw new IllegalArgumentException("You must specify a filter");
else if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final List<T> results = remove(filter);
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onRemoved(results);
}
});
} catch (final Exception e) {
log("Cache remove error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
} |
package com.ecyrd.jspwiki.workflow;
import java.security.Principal;
import java.util.*;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.WikiSession;
import com.ecyrd.jspwiki.auth.acl.UnresolvedPrincipal;
import com.ecyrd.jspwiki.event.WikiEvent;
import com.ecyrd.jspwiki.event.WikiEventListener;
import com.ecyrd.jspwiki.event.WorkflowEvent;
/**
* <p>
* Monitor class that tracks running Workflows. The WorkflowManager also keeps
* track of the names of users or groups expected to approve particular
* Workflows.
* </p>
*
* @author Andrew Jaquith
*/
public class WorkflowManager implements WikiEventListener
{
private final DecisionQueue m_queue = new DecisionQueue();
private final Set m_workflows;
private final Map m_approvers;
private final List m_completed;
protected final String PROPERTY_APPROVER_PREFIX = "jspwiki.approver.";
/**
* Constructs a new WorkflowManager, with an empty workflow cache. New
* Workflows are automatically assigned unique identifiers, starting with 1.
*/
public WorkflowManager()
{
next = 1;
m_workflows = new HashSet();
m_approvers = new HashMap();
m_completed = new ArrayList();
}
/**
* Adds a new workflow to the set of workflows and starts it. The new
* workflow is automatically assigned a unique ID. If another workflow with
* the same ID already exists, this method throws a WikIException.
*
* @param workflow
* the workflow to start
*/
public void start( Workflow workflow ) throws WikiException
{
m_workflows.add( workflow );
workflow.setWorkflowManager( this );
workflow.setId( nextId() );
workflow.start();
}
/**
* Returns a collection of the currently active workflows.
*
* @return the current workflows
*/
public Collection getWorkflows()
{
return new HashSet( m_workflows );
}
/**
* Returns a collection of finished workflows; that is, those that have aborted or completed.
* @return the finished workflows
*/
public List getCompletedWorkflows() {
return new ArrayList( m_completed );
}
private WikiEngine m_engine = null;
/**
* Initializes the WorkflowManager using a specfied WikiEngine and
* properties.
*
* @param engine
* the wiki engine to associate with this WorkflowManager
* @param props
* the wiki engine's properties
*/
public void initialize( WikiEngine engine, Properties props )
{
m_engine = engine;
// Identify the workflows requiring approvals
for ( Iterator it = props.keySet().iterator(); it.hasNext(); )
{
String prop = (String) it.next();
if ( prop.startsWith( PROPERTY_APPROVER_PREFIX ) )
{
// For the key, everything after the prefix is the workflow name
String key = prop.substring( PROPERTY_APPROVER_PREFIX.length() );
if ( key != null && key.length() > 0 )
{
// Only use non-null/non-blank approvers
String approver = props.getProperty( prop );
if ( approver != null && approver.length() > 0 )
{
m_approvers.put( key, new UnresolvedPrincipal( approver ) );
}
}
}
}
}
/**
* Returns <code>true</code> if a workflow matching a particular key
* contains an approval step.
*
* @param messageKey
* the name of the workflow; corresponds to the value returned by
* {@link Workflow#getMessageKey()}.
* @return the result
*/
public boolean requiresApproval( String messageKey )
{
return ( m_approvers.containsKey( messageKey ) );
}
/**
* Looks up and resolves the actor who approves a Decision for a particular
* Workflow, based on the Workflow's message key. If not found, or if
* Principal is Unresolved, throws WikiException. This particular
* implementation always returns the GroupPrincipal <code>Admin</code>
*
* @param messageKey
* @return the actor who approves Decisions
* @throws WikiException
*/
public Principal getApprover( String messageKey ) throws WikiException
{
Principal approver = (Principal) m_approvers.get( messageKey );
if ( approver == null )
{
throw new WikiException( "Workflow '" + messageKey + "' does not require approval." );
}
// Try to resolve UnresolvedPrincipals
if ( approver instanceof UnresolvedPrincipal )
{
String name = approver.getName();
approver = m_engine.getAuthorizationManager().resolvePrincipal( name );
// If still unresolved, throw exception; otherwise, freshen our
// cache
if ( approver instanceof UnresolvedPrincipal )
{
throw new WikiException( "Workflow approver '" + name + "' cannot not be resolved." );
}
m_approvers.put( messageKey, approver );
}
return approver;
}
/**
* Protected helper method that returns the associated WikiEngine
*
* @return the wiki engine
*/
protected WikiEngine getEngine()
{
if ( m_engine == null )
{
throw new IllegalStateException( "WikiEngine cannot be null; please initialize WorkflowManager first." );
}
return m_engine;
}
/**
* Returns the DecisionQueue associated with this WorkflowManager
*
* @return the decision queue
*/
public DecisionQueue getDecisionQueue()
{
return m_queue;
}
private volatile int next;
/**
* Returns the next available unique identifier, which is subsequently
* incremented.
*
* @return the id
*/
private synchronized int nextId()
{
int current = next;
next++;
return current;
}
/**
* Returns the current workflows a wiki session owns. These are workflows whose
* {@link Workflow#getOwner()} method returns a Principal also possessed by the
* wiki session (see {@link com.ecyrd.jspwiki.WikiSession#getPrincipals()}). If the
* wiki session is not authenticated, this method returns an empty Collection.
* @param session the wiki session
* @return the collection workflows the wiki session owns, which may be empty
*/
public Collection getOwnerWorkflows(WikiSession session) {
List workflows = new ArrayList();
if ( session.isAuthenticated() )
{
Principal[] sessionPrincipals = session.getPrincipals();
for ( Iterator it = m_workflows.iterator(); it.hasNext(); ) {
Workflow w = (Workflow)it.next();
Principal owner = w.getOwner();
for ( int i = 0; i < sessionPrincipals.length; i++ ) {
if ( sessionPrincipals[i].equals(owner) ) {
workflows.add( w );
break;
}
}
}
}
return workflows;
}
/**
* Listens for {@link com.ecyrd.jspwiki.event.WorkflowEvent} objects emitted
* by Workflows. In particular, this method listens for
* {@link com.ecyrd.jspwiki.event.WorkflowEvent#CREATED},
* {@link com.ecyrd.jspwiki.event.WorkflowEvent#ABORTED} and
* {@link com.ecyrd.jspwiki.event.WorkflowEvent#COMPLETED} events. If a
* workflow is created, it is automatically added to the cache. If one is
* aborted or completed, it is automatically removed.
*/
public void actionPerformed(WikiEvent event)
{
if (event instanceof WorkflowEvent)
{
Workflow workflow = (Workflow) event.getSource();
switch ( event.getType() )
{
case WorkflowEvent.ABORTED:
// Remove from manager
remove( workflow );
break;
case WorkflowEvent.COMPLETED:
// Remove from manager
remove( workflow );
break;
case WorkflowEvent.CREATED:
// Add to manager
add( workflow );
break;
}
}
}
/**
* Protected helper method that adds a newly created Workflow to the cache,
* and sets its <code>workflowManager</code> and <code>Id</code>
* properties if not set.
*
* @param workflow
* the workflow to add
*/
protected synchronized void add( Workflow workflow )
{
if ( workflow.getWorkflowManager() == null )
{
workflow.setWorkflowManager( this );
}
if ( workflow.getId() == Workflow.ID_NOT_SET )
{
workflow.setId( nextId() );
}
m_workflows.add( workflow );
}
/**
* Protected helper method that removes a specified Workflow from the cache,
* and moves it to the workflow history list. This method defensively
* checks to see if the workflow has not yet been removed.
*
* @param workflow
* the workflow to remove
*/
protected synchronized void remove(Workflow workflow)
{
if ( m_workflows.contains( workflow ) ) {
m_workflows.remove( workflow );
m_completed.add( workflow );
}
}
} |
package com.fsck.k9.controller;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
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.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.SearchSpecification;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Folder.OpenMode;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.mail.store.LocalStore.PendingCommand;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable
{
/**
* Immutable empty {@link String} array
*/
private static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* Immutable empty {@link Message} array
*/
private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0];
/**
* Immutable empty {@link Folder} array
*/
private static final Folder[] EMPTY_FOLDER_ARRAY = new Folder[0];
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
public enum SORT_TYPE
{
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending)
{
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending)
{
if (ascending)
{
return ascendingToast;
}
else
{
return descendingToast;
}
}
public boolean isDefaultAscending()
{
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
private String createMessageKey(Account account, String folder, Message message)
{
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid)
{
return account.getUuid() + ":" + folder + ":" + uid;
}
private void suppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
String messKey = createMessageKey(account, folder, message);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, String uid)
{
if (account == null || folder == null || uid == null)
{
return;
}
String messKey = createMessageKey(account, folder, uid);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return false;
}
String messKey = createMessageKey(account, folder, message);
if (deletedUids.containsKey(messKey))
{
return true;
}
return false;
}
private MessagingController(Application application)
{
mApplication = application;
mThread = new Thread(this);
mThread.start();
if (memorizingListener != null)
{
addListener(memorizingListener);
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application)
{
if (inst == null)
{
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy()
{
return mBusy;
}
public void run()
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true)
{
String commandDescription = null;
try
{
Command command = mCommands.take();
if (command != null)
{
commandDescription = command.description;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
command.runnable.run();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") +
" Command '" + command.description + "' completed");
for (MessagingListener l : getListeners(command.listener))
{
l.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground)
{
int retries = 10;
Exception e = null;
while (retries
{
try
{
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
}
catch (InterruptedException ie)
{
try
{
Thread.sleep(200);
}
catch (InterruptedException ne)
{
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener)
{
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener)
{
if (memorizingListener != null && listener != null)
{
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener)
{
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners()
{
return mListeners;
}
public Set<MessagingListener> getListeners(MessagingListener listener)
{
if (listener == null)
{
return mListeners;
}
Set<MessagingListener> listeners = new HashSet<MessagingListener>(mListeners);
listeners.add(listener);
return listeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener)
{
new Thread(new Runnable()
{
public void run()
{
for (MessagingListener l : getListeners(listener))
{
l.listFoldersStarted(account);
}
List<? extends Folder> localFolders = null;
try
{
Store localStore = account.getLocalStore();
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY);
if (refreshRemote || localFolders == null || localFolders.size() == 0)
{
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners(listener))
{
l.listFolders(account, folderArray);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners(listener))
{
l.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, null, e);
return;
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
for (MessagingListener l : getListeners(listener))
{
l.listFoldersFinished(account);
}
}
}).start();
}
private void doRefreshRemote(final Account account, MessagingListener listener)
{
put("doRefreshRemote", listener, new Runnable()
{
public void run()
{
List<? extends Folder> localFolders = null;
try
{
Store store = account.getRemoteStore();
List<? extends Folder> remoteFolders = store.getPersonalNamespaces(false);
LocalStore localStore = account.getLocalStore();
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.size(); i < count; i++)
{
LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName());
if (!localFolder.exists())
{
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders.get(i).getName());
}
localFolders = localStore.getPersonalNamespaces(false);
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders)
{
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(K9.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName()))
{
continue;
}
if (!remoteFolderNames.contains(localFolder.getName()))
{
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY);
for (MessagingListener l : getListeners())
{
l.listFolders(account, folderArray);
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, "");
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
}
});
}
/**
* List the messages in the local message store for the given folder asynchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder, final MessagingListener listener)
{
new Thread(new Runnable()
{
public void run()
{
listLocalMessagesSynchronous(account, folder, listener);
}
}).start();
}
/**
* List the messages in the local message store for the given folder synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener)
{
for (MessagingListener l : getListeners(listener))
{
l.listLocalMessagesStarted(account, folder);
}
Folder localFolder = null;
MessageRetrievalListener retrievalListener =
new MessageRetrievalListener()
{
List<Message> pendingMessages = new ArrayList<Message>();
int totalDone = 0;
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(account, folder, message) == false)
{
pendingMessages.add(message);
totalDone++;
if (pendingMessages.size() > 10)
{
addPendingMessages();
}
}
else
{
for (MessagingListener l : getListeners(listener))
{
l.listLocalMessagesRemoveMessage(account, folder, message);
}
}
}
public void messagesFinished(int number)
{
addPendingMessages();
}
private void addPendingMessages()
{
for (MessagingListener l : getListeners(listener))
{
l.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
pendingMessages.clear();
}
};
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
localFolder.getMessages(
retrievalListener,
false // Skip deleted messages
);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished");
for (MessagingListener l : getListeners(listener))
{
l.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners(listener))
{
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener)
{
searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages,
searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener);
}
/**
* Find all messages in any local account which match the query 'query'
* @param folderNames TODO
* @param query
* @param listener
* @param searchAccounts TODO
* @param account TODO
* @param account
* @throws MessagingException
*/
public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate,
final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener)
{
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "searchLocalMessages ("
+ "accountUuids=" + Utility.combine(accountUuids, ',')
+ ", folderNames = " + Utility.combine(folderNames, ',')
+ ", messages.size() = " + (messages != null ? messages.length : null)
+ ", query = " + query
+ ", integrate = " + integrate
+ ", requiredFlags = " + Utility.combine(requiredFlags, ',')
+ ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',')
+ ")");
}
new Thread(new Runnable()
{
public void run()
{
final AccountStats stats = new AccountStats();
final Set<String> accountUuidsSet = new HashSet<String>();
if (accountUuids != null)
{
for (String accountUuid : accountUuids)
{
accountUuidsSet.add(accountUuid);
}
}
final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext());
Account[] accounts = prefs.getAccounts();
List<LocalFolder> foldersToSearch = null;
boolean displayableOnly = false;
boolean noSpecialFolders = true;
for (final Account account : accounts)
{
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false)
{
continue;
}
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true)
{
displayableOnly = true;
noSpecialFolders = true;
}
else if (integrate == false && folderNames == null)
{
Account.Searchable searchableFolders = account.getSearchableFolders();
switch (searchableFolders)
{
case NONE:
continue;
case DISPLAYABLE:
displayableOnly = true;
break;
}
}
List<Message> messagesToSearch = null;
if (messages != null)
{
messagesToSearch = new LinkedList<Message>();
for (Message message : messages)
{
if (message.getFolder().getAccount().getUuid().equals(account.getUuid()))
{
messagesToSearch.add(message);
}
}
if (messagesToSearch.isEmpty())
{
continue;
}
}
if (listener != null)
{
listener.listLocalMessagesStarted(account, null);
}
if (integrate || displayableOnly || folderNames != null || noSpecialFolders)
{
List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>();
try
{
LocalStore store = account.getLocalStore();
List<? extends Folder> folders = store.getPersonalNamespaces(false);
Set<String> folderNameSet = null;
if (folderNames != null)
{
folderNameSet = new HashSet<String>();
for (String folderName : folderNames)
{
folderNameSet.add(folderName);
}
}
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
boolean include = true;
folder.refresh(prefs);
String localFolderName = localFolder.getName();
if (integrate)
{
include = localFolder.isIntegrate();
}
else
{
if (folderNameSet != null)
{
if (folderNameSet.contains(localFolderName) == false)
{
include = false;
}
}
// Never exclude the INBOX (see issue 1817)
else if (noSpecialFolders && !localFolderName.equals(K9.INBOX) && (
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName())))
{
include = false;
}
else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass()))
{
include = false;
}
}
if (include)
{
tmpFoldersToSearch.add(localFolder);
}
}
if (tmpFoldersToSearch.size() < 1)
{
continue;
}
foldersToSearch = tmpFoldersToSearch;
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me);
addErrorMessage(account, null, me);
}
}
MessageRetrievalListener retrievalListener = new MessageRetrievalListener()
{
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message) == false)
{
List<Message> messages = new ArrayList<Message>();
messages.add(message);
stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0;
stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0;
if (listener != null)
{
listener.listLocalMessagesAddMessages(account, null, messages);
}
}
}
public void messagesFinished(int number)
{
}
};
try
{
String[] queryFields = {"html_content","subject","sender_list"};
LocalStore localStore = account.getLocalStore();
localStore.searchForMessages(retrievalListener, queryFields
, query, foldersToSearch,
messagesToSearch == null ? null : messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY),
requiredFlags, forbiddenFlags);
}
catch (Exception e)
{
if (listener != null)
{
listener.listLocalMessagesFailed(account, null, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (listener != null)
{
listener.listLocalMessagesFinished(account, null);
}
}
}
if (listener != null)
{
listener.searchStats(stats);
}
}
}).start();
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
synchronizeMailbox(account, folder, listener, null);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts)
{
for (Account account : accounts)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
* @param providedRemoteFolder TODO
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder)
{
putBackground("synchronizeMailbox", listener, new Runnable()
{
public void run()
{
synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
* @param providedRemoteFolder TODO
*/
private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder)
{
Folder remoteFolder = null;
LocalFolder tLocalFolder = null;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder);
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxStarted(account, folder);
}
/*
* We don't ever sync the Outbox or errors folder
*/
if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName()))
{
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
return;
}
Exception commandException = null;
try
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " +
account.getDescription());
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages)
{
localUidMap.put(message.getUid(), message);
}
if (providedRemoteFolder != null)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder);
remoteFolder = providedRemoteFolder;
}
else
{
Store remoteStore = account.getRemoteStore();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
remoteFolder = remoteStore.getFolder(folder);
if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener))
{
return;
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
remoteFolder.open(OpenMode.READ_WRITE);
if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
if (visibleLimit < 1)
{
visibleLimit = K9.DEFAULT_VISIBLE_LIMIT;
}
Message[] remoteMessageArray = EMPTY_MESSAGE_ARRAY;
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
// final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount);
final Date earliestDate = account.getEarliestPollDate();
if (remoteMessageCount > 0)
{
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
final AtomicInteger headerProgress = new AtomicInteger(0);
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxHeadersStarted(account, folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null);
int messageCount = remoteMessageArray.length;
for (Message thisMess : remoteMessageArray)
{
headerProgress.incrementAndGet();
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount);
}
Message localMessage = localUidMap.get(thisMess.getUid());
if (localMessage == null || localMessage.olderThan(earliestDate) == false)
{
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
remoteMessageArray = null;
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size());
}
}
else if (remoteMessageCount < 0)
{
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store or are too old
*/
if (account.syncRemoteDeletions())
{
for (Message localMessage : localMessages)
{
if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages);
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, unreadMessageCount);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages + " new messages");
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
finally
{
if (providedRemoteFolder == null && remoteFolder != null)
{
remoteFolder.close();
}
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException
{
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName()))
{
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
for (MessagingListener l : getListeners(listener))
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return false;
}
}
}
return true;
}
private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException
{
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount != -1)
{
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
else
{
int unreadCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false)
{
unreadCount++;
}
}
localFolder.setUnreadMessageCount(unreadCount);
}
return localFolder.getUnreadMessageCount();
}
private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException
{
int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount();
if (remoteFlaggedMessageCount != -1)
{
localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount);
}
else
{
int flaggedCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false)
{
flaggedCount++;
}
}
localFolder.setFlaggedMessageCount(flaggedCount);
}
}
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final Date earliestDate = account.getEarliestPollDate();
if (earliestDate != null)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
int unreadBeforeStart = 0;
try
{
AccountStats stats = account.getStats(mApplication);
unreadBeforeStart = stats.unreadMessageCount;
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (message.isSet(Flag.DELETED))
{
syncFlagMessages.add(message);
}
else if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
}
else
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages,largeMessages, progress, todo, fp);
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, unreadBeforeStart, newMessages, todo, fp);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, unreadBeforeStart, newMessages, todo, fp);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
refreshLocalMessageFlags(account,remoteFolder,localFolder,syncFlagMessages,progress,todo);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
List<Message> unsyncedMessages,
final ArrayList<Message> smallMessages,
final ArrayList<Message> largeMessages,
final AtomicInteger progress,
final int todo,
FetchProfile fp) throws MessagingException
{
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
remoteFolder.fetch(unsyncedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
if (message.isSet(Flag.DELETED))
{
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was marked deleted on server, skipping");
}
else
{
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (message.getSize() > account.getMaximumAutoDownloadMessageSize())
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
}
private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate)
{
if (isMessageSuppressed(account, folder, message))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+
"but just downloaded. "+
"The race condition means we wasted some bandwidth. Oh well.");
}
return false;
}
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
return false;
}
return true;
}
private void downloadSmallMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> smallMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException
{
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (!shouldImportMessage(account, folder, message, progress, earliestDate))
{
progress.incrementAndGet();
return;
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
progress.incrementAndGet();
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, message))
{
newMessages.incrementAndGet();
notifyAccount(mApplication, account, message, unreadBeforeStart, newMessages);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
private void downloadLargeMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> largeMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException
{
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (!shouldImportMessage(account, folder, message, progress, earliestDate))
{
progress.incrementAndGet();
continue;
}
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* Mark the message as fully downloaded if the message size is smaller than
* the account's autodownload size limit, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < account.getMaximumAutoDownloadMessageSize())
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
Message localMessage = localFolder.getMessage(message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, message))
{
newMessages.incrementAndGet();
notifyAccount(mApplication, account, message, unreadBeforeStart, newMessages);
}
}//for large messsages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> syncFlagMessages,
final AtomicInteger progress,
final int todo
) throws MessagingException
{
final String folder = remoteFolder.getName();
if (remoteFolder.supportsFetchingFlags())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages)
{
if (message.isSet(Flag.DELETED) == false)
{
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
else
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException
{
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED))
{
return false;
}
if (remoteMessage.isSet(Flag.DELETED))
{
if (localMessage.getFolder().getAccount().syncRemoteDeletions())
{
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
}
else
{
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED })
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag))
{
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
}
while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.addPendingCommand(command);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account)
{
putBackground("processPendingCommands", null, new Runnable()
{
public void run()
{
try
{
processPendingCommandsSynchronous(account);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, null, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException
{
LocalStore localStore = account.getLocalStore();
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0)
{
return;
}
for (MessagingListener l : getListeners())
{
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands)
{
processingCommand = command;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners())
{
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command))
{
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command))
{
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command))
{
processPendingSetFlagOld(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command))
{
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command))
{
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command))
{
processPendingMoveOrCopyOld(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command))
{
processPendingEmptyTrash(command, account);
}
else if (PENDING_COMMAND_EXPUNGE.equals(command.command))
{
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
finally
{
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
finally
{
for (MessagingListener l : getListeners())
{
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null)
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null)
{
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
localMessage
}
, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else
{
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0)
{
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.X_DESTROYED, true);
}
else
{
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
if (remoteDate != null)
{
remoteMessage.setFlag(Flag.DELETED, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[])
{
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
try
{
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
Store remoteStore = account.getRemoteStore();
remoteSrcFolder = remoteStore.getFolder(srcFolder);
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteSrcFolder.getMessage(uid));
}
}
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName))
{
destFolderName = null;
}
remoteSrcFolder.delete(messages.toArray(EMPTY_MESSAGE_ARRAY), destFolderName);
}
else
{
remoteDestFolder = remoteStore.getFolder(destFolder);
if (isCopy)
{
remoteSrcFolder.copyMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder);
}
}
if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
}
finally
{
if (remoteSrcFolder != null)
{
remoteSrcFolder.close();
}
if (remoteDestFolder != null)
{
remoteDestFolder.close();
}
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids)
{
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists() ||
/*
* Don't proceed if the remote folder doesn't support flags and
* the flag to be changed isn't the deleted flag. This avoids
* unnecessary connections to POP3 servers.
*/
// TODO: This should actually call a supportsSettingFlag(flag) method.
(!remoteFolder.supportsFetchingFlags() && !Flag.DELETED.equals(flag)))
{
return;
}
try
{
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.size() == 0)
{
return;
}
remoteFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] { flag }, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Folder remoteFolder = null;
try
{
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null)
{
return;
}
remoteMessage.setFlag(flag, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
private void queueExpunge(final Account account, final String folderName)
{
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException
{
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = account.getRemoteStore();
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null)
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy)
{
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException
{
String folder = command.arguments[0];
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners())
{
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, 0);
}
if (account.getErrorFolderName().equals(folder))
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true);
remoteFolder.close();
}
catch (UnsupportedOperationException uoe)
{
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, String subject, Throwable t)
{
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
if (subject == null)
{
subject = getRootCauseMessage(t);
}
addErrorMessage(account, subject, baos.toString());
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(
final Message[] messages,
final Flag flag,
final boolean newState)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
String[] uids = new String[messages.size()];
for (int i = 0; i < messages.size(); i++)
{
uids[i] = messages.get(i).getUid();
}
setFlag(account, folder.getName(), uids, flag, newState);
}
});
}
public void setFlag(
final Account account,
final String folderName,
final String[] uids,
final Flag flag,
final boolean newState)
{
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
ArrayList<Message> messages = new ArrayList<Message>();
for (String uid : uids)
{
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folderName))
{
sendCount.remove(uid);
}
Message msg = localFolder.getMessage(uid);
if (msg != null)
{
messages.add(msg);
}
}
localFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] {flag}, newState);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount());
}
if (account.getErrorFolderName().equals(folderName))
{
return;
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException(me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}//setMesssageFlag
public void clearAllPending(final Account account)
{
try
{
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = account.getLocalStore();
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, null, me);
}
}
public void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener)
{
put("loadMessageForViewRemote", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
}
else
{
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
fp.add(FetchProfile.Item.ENVELOPE);
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// now that we have the full message, refresh the headers
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
finally
{
if (remoteFolder!=null)
{
remoteFolder.close();
}
if (localFolder!=null)
{
localFolder.close();
}
}//finally
}//run
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener)
{
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewStarted(account, folder, uid);
}
new Thread(new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
LocalMessage message = (LocalMessage)localFolder.getMessage(uid);
if (message==null
|| message.getId()==0)
{
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
if (!message.isSet(Flag.SEEN))
{
message.setFlag(Flag.SEEN, true);
setFlag(new Message[] { message }, Flag.SEEN, true);
}
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
message
}, fp, null);
localFolder.close();
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners(listener))
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
}
}).start();
}
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener)
{
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try
{
if (part.getBody() != null)
{
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, false);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me)
{
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, true);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
put("loadAttachment", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments)
{
attachment.setBody(null);
}
Store remoteStore = account.getRemoteStore();
localFolder = localStore.getFolder(message.getFolder().getName());
remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
//FIXME: This is an ugly hack that won't be needed once the Message objects have been united.
Message remoteMessage = remoteFolder.getMessage(message.getUid());
remoteMessage.setBody(message.getBody());
remoteFolder.fetchPart(remoteMessage, part, null);
localFolder.updateMessage((LocalMessage)message);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Exception loading attachment", me);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
if (listener != null)
{
listener.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, null, me);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, null);
}
catch (Exception e)
{
/*
for (MessagingListener l : getListeners())
{
// TODO general failed
}
*/
addErrorMessage(account, null, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener)
{
putBackground("sendPendingMessages", listener, new Runnable()
{
public void run()
{
sendPendingMessagesSynchronous(account);
}
});
}
public boolean messagesPendingSend(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return false;
}
localFolder.open(OpenMode.READ_WRITE);
int localMessages = localFolder.getMessageCount();
if (localMessages > 0)
{
return true;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return;
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
int progress = 0;
int todo = localMessages.length;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account);
for (Message message : localMessages)
{
if (message.isSet(Flag.DELETED))
{
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try
{
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS)
{
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try
{
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
if (K9.FOLDER_NONE.equals(account.getSentFolderName()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message");
message.setFlag(Flag.DELETED, true);
}
else
{
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
localSentFolder.getName(),
message.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
}
catch (Exception e)
{
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
if (localFolder.getMessageCount() == 0)
{
localFolder.delete(false);
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void getAccountStats(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
try
{
AccountStats stats = account.getStats(context);
l.accountStatusChanged(account, stats);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
}
};
put("getAccountStats:" + account.getDescription(), l, unreadRunnable);
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
int unreadMessageCount = 0;
try
{
Folder localFolder = account.getLocalStore().getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public boolean isMoveCapable(Message message)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
return true;
}
else
{
return false;
}
}
public boolean isCopyCapable(Message message)
{
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
for (Message message : messages)
{
suppressMessage(account, srcFolder, message);
}
putBackground("moveMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener);
}
});
}
public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
putBackground("copyMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener);
}
});
}
public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false))
{
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false))
{
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
List<String> uids = new LinkedList<String>();
for (Message message : inMessages)
{
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
uids.add(uid);
}
}
Message[] messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null);
if (messages.length > 0)
{
Map<String, Message> origUidMap = new HashMap<String, Message>();
for (Message message : messages)
{
origUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy)
{
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(messages, fp, null);
localSrcFolder.copyMessages(messages, localDestFolder);
}
else
{
localSrcFolder.moveMessages(messages, localDestFolder);
for (String origUid : origUidMap.keySet())
{
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(EMPTY_STRING_ARRAY));
}
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener)
{
putBackground("expunge", null, new Runnable()
{
public void run()
{
queueExpunge(account, folder);
}
});
}
public void deleteDraft(final Account account, String uid)
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message != null)
{
deleteMessages(new Message[] { message }, null);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void deleteMessages(final Message[] messages, final MessagingListener listener)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
for (Message message : messages)
{
suppressMessage(account, folder.getName(), message);
}
putBackground("deleteMessages", null, new Runnable()
{
public void run()
{
deleteMessagesSynchronous(account, folder.getName(), messages.toArray(EMPTY_MESSAGE_ARRAY), listener);
}
});
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages,
MessagingListener listener)
{
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try
{
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages)
{
if (listener != null)
{
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners())
{
l.messageDeleted(account, folder, message);
}
}
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
else
{
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (!localTrashFolder.exists())
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount());
if (localTrashFolder != null)
{
l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount());
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
if (folder.equals(account.getOutboxFolderName()))
{
for (Message message : messages)
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
}
else
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
for (String uid : uids)
{
unsuppressMessage(account, folder, uid);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (localTrashFolder != null)
{
localTrashFolder.close();
}
}
}
private String[] getUidsFromMessages(Message[] messages)
{
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++)
{
uids[i] = messages[i].getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException
{
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try
{
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
public void emptyTrash(final Account account, MessagingListener listener)
{
putBackground("emptyTrash", listener, new Runnable()
{
public void run()
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
for (MessagingListener l : getListeners())
{
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null)
{
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null)
{
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener)
{
TracingWakeLock twakeLock = null;
if (useManualWakeLock)
{
TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final TracingWakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners())
{
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable()
{
public void run()
{
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null)
{
accounts = new Account[]
{
account
};
}
else
{
accounts = prefs.getAccounts();
}
for (final Account account : accounts)
{
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
account.setRingNotified(false);
putBackground("sendPending " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (messagesPendingSend(account))
{
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never sync a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aSyncMode, fSyncClass))
{
// Do not sync folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
continue;
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder tLocalFolder = null;
try
{
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName(), listener, null);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
}
);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
putBackground("clear notification flag for " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription());
account.setRingNotified(false);
try
{
if (account.getStats(context).unreadMessageCount == 0)
{
notifyAccountCancel(context, account);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
}
}
);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, null, e);
}
putBackground("finalize sync", null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null)
{
wakeLock.release();
}
for (MessagingListener l : getListeners())
{
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e);
}
}
});
}
public void recreate(final Account account, final MessagingListener ml)
{
putBackground("recreate:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.recreate();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e);
}
}
});
}
private boolean shouldNotifyForMessage(Account account, Message message)
{
// Do not notify if the user does not have notifications
// enabled or if the message has been read
if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN) || (account.getName() == null))
{
return false;
}
Folder folder = message.getFolder();
if (folder != null)
{
// No notification for new messages in Trash, Drafts, or Sent folder.
// But do notify if it's the INBOX (see issue 1817).
String folderName = folder.getName();
if (!K9.INBOX.equals(folderName) &&
(account.getTrashFolderName().equals(folderName)
|| account.getDraftsFolderName().equals(folderName)
|| account.getSentFolderName().equals(folderName)))
{
return false;
}
}
return true;
}
/** Creates a notification of new email messages
* ringtone, lights, and vibration to be played
*/
private boolean notifyAccount(Context context, Account account, Message message, int previousUnreadMessageCount, AtomicInteger newMessageCount)
{
// If we have a message, set the notification to "<From>: <Subject>"
StringBuffer messageNotice = new StringBuffer();
try
{
if (message != null && message.getFrom() != null)
{
Address[] fromAddrs = message.getFrom();
String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null;
String subject = message.getSubject();
if (subject == null)
{
subject = context.getString(R.string.general_no_subject);
}
if (from != null)
{
// Show From: address by default
if (account.isAnIdentity(fromAddrs) == false)
{
messageNotice.append(from + ": " + subject);
}
// show To: if the message was sent from me
else
{
if (!account.isNotifySelfNewMail())
{
return false;
}
Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null;
if (to != null)
{
messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject);
}
else
{
messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject);
}
}
}
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e);
}
// If we could not set a per-message notification, revert to a default message
if (messageNotice.length() == 0)
{
messageNotice.append(context.getString(R.string.notification_new_title));
}
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis());
notif.number = previousUnreadMessageCount + newMessageCount.get();
Intent i = FolderList.actionHandleNotification(context, account, account.getAutoExpandFolderName());
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
String accountNotice = context.getString(R.string.notification_new_one_account_fmt, notif.number, account.getDescription());
notif.setLatestEventInfo(context, accountNotice, messageNotice, pi);
// Only ring or vibrate if we have not done so already on this
// account and fetch
if (!account.isRingNotified())
{
account.setRingNotified(true);
if (account.shouldRing())
{
String ringtone = account.getRingtone();
notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
}
if (account.isVibrate())
{
long[] pattern = getVibratePattern(account.getVibratePattern(), account.getVibrateTimes());
notif.vibrate = pattern;
}
}
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
notif.audioStreamType = AudioManager.STREAM_NOTIFICATION;
notifMgr.notify(account.getAccountNumber(), notif);
return true;
}
/*
* Fetch a vibration pattern.
*
* @param vibratePattern Vibration pattern index to use.
* @param vibrateTimes Number of times to do the vibration pattern.
* @return Pattern multiplied by the number of times requested.
*/
public static long[] getVibratePattern(int vibratePattern, int vibrateTimes)
{
// These are "off, on" patterns, specified in milliseconds
long[] pattern0 = new long[] {300,200}; // like the default pattern
long[] pattern1 = new long[] {100,200};
long[] pattern2 = new long[] {100,500};
long[] pattern3 = new long[] {200,200};
long[] pattern4 = new long[] {200,500};
long[] pattern5 = new long[] {500,500};
long[] selectedPattern = pattern0; //default pattern
switch (vibratePattern)
{
case 1:
selectedPattern = pattern1;
break;
case 2:
selectedPattern = pattern2;
break;
case 3:
selectedPattern = pattern3;
break;
case 4:
selectedPattern = pattern4;
break;
case 5:
selectedPattern = pattern5;
break;
}
long[] repeatedPattern = new long[selectedPattern.length * vibrateTimes];
for (int n = 0; n < vibrateTimes; n++)
{
System.arraycopy(selectedPattern, 0, repeatedPattern, n * selectedPattern.length, selectedPattern.length);
}
// Do not wait before starting the vibration pattern.
repeatedPattern[0] = 0;
return repeatedPattern;
}
/** Cancel a notification of new email messages */
public void notifyAccountCancel(Context context, Account account)
{
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(account.getAccountNumber());
notifMgr.cancel(-1000 - account.getAccountNumber());
}
public Message saveDraft(final Account account, final Message message)
{
Message localMessage = null;
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[]
{
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, null, e);
}
return localMessage;
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode)
{
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS))
{
return true;
}
else
{
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
class Command implements Comparable<Command>
{
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
@Override
public int compareTo(Command other)
{
if (other.isForeground == true && isForeground == false)
{
return 1;
}
else if (other.isForeground == false && isForeground == true)
{
return -1;
}
else
{
return (sequence - other.sequence);
}
}
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
public Collection<Pusher> getPushers()
{
return pushers.values();
}
public boolean setupPushing(final Account account)
{
try
{
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null)
{
previousPusher.stop();
}
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
if (folder.getName().equals(account.getErrorFolderName())
|| folder.getName().equals(account.getOutboxFolderName()))
{
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which should never be pushed");
continue;
}
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never push a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aPushMode, fPushClass))
{
// Do not push folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (names.size() > 0)
{
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try
{
Store store = account.getRemoteStore();
if (store.isPushCapable() == false)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
if (pusher != null)
{
Pusher oldPusher = pushers.putIfAbsent(account, pusher);
if (oldPusher == null)
{
pusher.start(names);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
}
else
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext())
{
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder= localStore.getFolder(remoteFolder.getName());
localFolder.open(OpenMode.READ_WRITE);
account.setRingNotified(false);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size());
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0)
{
notifyAccountCancel(mApplication, account);
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
}
catch (Exception e)
{
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try
{
localFolder.setStatus(errorMessage);
}
catch (Exception se)
{
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to close localFolder", e);
}
}
latch.countDown();
}
}
});
try
{
latch.await();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
enum MemorizingState { STARTED, FINISHED, FAILED };
class Memory
{
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName)
{
account = nAccount;
folderName = nFolderName;
}
String getKey()
{
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName)
{
return taccount.getDescription() + ":" + tfolderName;
}
class MemorizingListener extends MessagingListener
{
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName)
{
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null)
{
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
@Override
public synchronized void synchronizeMailboxStarted(Account account, String folder)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
@Override
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other)
{
if (other != null)
{
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values())
{
if (memory.syncingState != null)
{
switch (memory.syncingState)
{
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null)
{
switch (memory.sendingState)
{
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null)
{
switch (memory.pushingState)
{
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
}
}
if (memory.processingState != null)
{
switch (memory.processingState)
{
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null)
{
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null)
{
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null)
{
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null)
{
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
}
else
{
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0)
{
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active)
{
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
@Override
public synchronized void sendPendingMessagesStarted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void sendPendingMessagesCompleted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
@Override
public synchronized void sendPendingMessagesFailed(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
@Override
public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total)
{
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
@Override
public synchronized void pendingCommandsProcessing(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void pendingCommandsFinished(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
@Override
public synchronized void pendingCommandStarted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
@Override
public synchronized void pendingCommandCompleted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
private void actOnMessages(Message[] messages, MessageActor actor)
{
Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>();
for (Message message : messages)
{
Folder folder = message.getFolder();
Account account = folder.getAccount();
Map<Folder, List<Message>> folderMap = accountMap.get(account);
if (folderMap == null)
{
folderMap = new HashMap<Folder, List<Message>>();
accountMap.put(account, folderMap);
}
List<Message> messageList = folderMap.get(folder);
if (messageList == null)
{
messageList = new LinkedList<Message>();
folderMap.put(folder, messageList);
}
messageList.add(message);
}
for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet())
{
Account account = entry.getKey();
//account.refresh(Preferences.getPreferences(K9.app));
Map<Folder, List<Message>> folderMap = entry.getValue();
for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet())
{
Folder folder = folderEntry.getKey();
List<Message> messageList = folderEntry.getValue();
actor.act(account, folder, messageList);
}
}
}
interface MessageActor
{
public void act(final Account account, final Folder folder, final List<Message> messages);
}
} |
package net.somethingdreadful.MAL.tasks;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.MALManager;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.Theme;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.BaseModels.Forum;
import net.somethingdreadful.MAL.api.MALApi;
import java.util.ArrayList;
import retrofit.RetrofitError;
public class ForumNetworkTask extends AsyncTask<String, Void, ArrayList<Forum>> {
private final ForumNetworkTaskListener callback;
private final ForumJob type;
private final int id;
private final Activity activity;
public ForumNetworkTask(ForumNetworkTaskListener callback, Activity activity, ForumJob type, int id) {
this.callback = callback;
this.type = type;
this.id = id;
this.activity = activity;
}
@Override
protected ArrayList<Forum> doInBackground(String... params) {
ArrayList<Forum> result = new ArrayList<>();
MALManager mManager = new MALManager(activity);
if (!AccountService.isMAL() && MALApi.isNetworkAvailable(activity))
mManager.verifyAuthentication();
try {
switch (type) {
case MENU: // list with all categories
result = mManager.getForumCategories();
break;
case CATEGORY: // list with all topics of a certain category
result = mManager.getCategoryTopics(id, Integer.parseInt(params[0]));
break;
case SUBCATEGORY:
result = mManager.getSubCategory(id, Integer.parseInt(params[0]));
break;
case TOPIC: // list with all comments of users
result = mManager.getTopic(id, Integer.parseInt(params[0]));
break;
case SEARCH:
result = mManager.search(params[0]);
break;
case ADDCOMMENT:
result = mManager.addComment(id, params[0]) ? new ArrayList<Forum>() : null;
if (result != null)
result = mManager.getTopic(id, Integer.parseInt(params[1]));
break;
case UPDATECOMMENT:
result = mManager.updateComment(id, params[0]) ? new ArrayList<Forum>() : null;
break;
/*
case DISCUSSION:
if (params[1].equals(MALApi.ListType.ANIME.toString()))
result = mManager.getDiscussion(id, Integer.parseInt(params[0]), MALApi.ListType.ANIME);
else
result = mManager.getDiscussion(id, Integer.parseInt(params[0]), MALApi.ListType.MANGA);
break;
case TOPICS:
result = mManager.getTopics(id, Integer.parseInt(params[0]));
break;
case POSTS:
result = mManager.getPosts(id, Integer.parseInt(params[0]));
break;
case ADDTOPIC:
result.setList(mManager.addTopic(id, params[0], params[1]) ? new ArrayList<Forum>() : null);
break;
case ADDCOMMENT:
result.setList(mManager.addComment(id, params[0]) ? new ArrayList<Forum>() : null);
break;
case UPDATECOMMENT:
result.setList(mManager.updateComment(id, params[0]) ? new ArrayList<Forum>() : null);
break;*/
}
} catch (RetrofitError re) {
if (re.getResponse() != null && activity != null) {
switch (re.getResponse().getStatus()) {
case 400: // Bad Request
Theme.Snackbar(activity, R.string.toast_error_api);
break;
case 401: // Unauthorized
Crashlytics.log(Log.ERROR, "MALX", "ForumNetworkTask.doInBackground(1): User is not logged in");
Theme.Snackbar(activity, R.string.toast_info_password);
break;
case 404: // Not Found
Theme.Snackbar(activity, R.string.toast_error_Records);
break;
case 500: // Internal Server Error
Crashlytics.log(Log.ERROR, "MALX", "ForumNetworkTask.doInBackground(2): Internal server error, API bug?");
Crashlytics.logException(re);
Theme.Snackbar(activity, R.string.toast_error_api);
break;
case 503: // Service Unavailable
case 504: // Gateway Timeout
Crashlytics.log(Log.ERROR, "MALX", "ForumNetworkTask.doInBackground(3): " + String.format("%s-task unknown API error on id %s: %s", type.toString(), id, re.getMessage()));
Theme.Snackbar(activity, R.string.toast_error_maintenance);
break;
default:
Theme.Snackbar(activity, R.string.toast_error_Records);
break;
}
Crashlytics.log(Log.ERROR, "MALX", "ForumNetworkTask.doInBackground(4): " + String.format("%s-task unknown API error on id %s: %s", type.toString(), id, re.getMessage()));
} else {
Crashlytics.log(Log.ERROR, "MALX", "ForumNetworkTask.doInBackground(5): " + String.format("%s-task unknown API error on id %s: %s", type.toString(), id, re.getMessage()));
Theme.Snackbar(activity, R.string.toast_error_maintenance);
}
} catch (Exception e) {
Theme.logTaskCrash(this.getClass().getSimpleName(), "doInBackground(6): " + String.format("%s-task unknown API error on id %s", type.toString(), id), e);
}
return result;
}
@Override
protected void onPostExecute(ArrayList<Forum> result) {
if (callback != null)
callback.onForumNetworkTaskFinished(result, type);
}
public interface ForumNetworkTaskListener {
void onForumNetworkTaskFinished(ArrayList<Forum> result, ForumJob task);
}
} |
package com.proofpoint.jetty;
import com.proofpoint.configuration.Config;
public class JettyConfig
{
@Config("jetty.ip")
public String getServerIp()
{
return null;
}
@Config("jetty.http.port")
int getHttpPort()
{
return 8080;
}
@Config("jetty.https.enabled")
boolean isHttpsEnabled()
{
return false;
}
@Config("jetty.https.port")
int getHttpsPort()
{
return 8443;
}
@Config("jetty.https.keystore.path")
String getKeystorePath()
{
return null;
}
@Config("jetty.https.keystore.password")
String getKeystorePassword()
{
return null;
}
@Config("jetty.log.path")
String getLogPath()
{
return "var/log/jetty.log";
}
@Config("jetty.threads.max")
int getMaxThreads()
{
return 200;
}
@Config("jetty.threads.min")
int getMinThreads()
{
return 2;
}
@Config("jetty.threads.max-idle-time-ms")
int getThreadMaxIdleTime()
{
return 60000;
}
@Config("jetty.log.retain-days")
int getLogRetainDays()
{
return 90;
}
@Config("jetty.auth.users-file")
String getUserAuthPath()
{
return null;
}
} |
import java.io.File;
import org.jmxdatamart.common.DBException;
import java.sql.SQLException;
import java.util.ArrayList;
public class Main {
/**
* Command line main method. Loads all hypersql files in the directory passed in args
* according to the configuration in the .ini file also passed in args.
* @param args command line arguments
*/
public static void main(String[] args) throws SQLException, DBException {
if (args.length!=3){
printHelp();
}
else{
if (lookForHelp(args)){
printHelp();
}
else{
Integer dFormat = lookForDataFormat(args);
if (dFormat == -1){
printHelp();
}
else{
String configFile = getConfig(args);
ArrayList<File> dbFiles = new ArrayList<File>();
if (dFormat == 0){
//db files are csv directories
dbFiles = getCSVDirList(args);
for(File dbfile : dbFiles){
System.out.println(dbfile.getPath());
}
}
if (dFormat == 1){
// db files are HyperSQL files
dbFiles = getDbFileList(args);
for(File dbfile : dbFiles){
String dbName = dbfile.getPath().substring(0,dbfile.getPath().length()-7);
System.out.println(dbfile.getPath().substring(0,dbfile.getPath().length()-7));
DB2DB d2d = new DB2DB();
LoaderSetting s = d2d.readProperties(configFile);
LoaderSetting.DBInfo fileInfo = s.getSource();
fileInfo.setDatabaseName(dbName);
fileInfo.setJdbcUrl("jdbc:hsqldb:file:" + dbName);
s.setSource(fileInfo);
d2d.loadSetting(s);
d2d.copySchema();
d2d.importData();
d2d.disConnect();
}
}
}
}
}
}
/**
* Prints to System.out the Loader syntax for the command line.
*/
public static void printHelp(){
System.out.println("Loader Syntax:");
System.out.println("Loader -h | h | ? | help , brings up this display");
System.out.println("Loader config.ini \\dbfiledirpath dataformat");
System.out.println(" Loader looks for files/dirs in dbfiledirpath");
System.out.println(" dataformat - (csv | CSV | hsql | HSQL)");
System.out.println("Example: Loader loaderConfig.ini C:\\Extracted");
}
/**
* Iterates through the command line arguments looking for .ini file name/path
* @param argArray command line arguments
* @return String file name
*/
private static String getConfig(String[] argArray){
String extension;
for(int i = 0; i<argArray.length; i++){
extension = argArray[i].substring(argArray[i].length()-3);
if (extension.equals("ini")){
return argArray[i];
}
}
return "";
}
/**
* Iterates through the command line arguments looking for -h | h | ? | help
* @param argArray command line arguments
* @return Boolean True if found in argArray
*/
private static Boolean lookForHelp(String[] argArray){
for(int i = 0; i < argArray.length; i++){
if (argArray[i].equals("-h") | argArray[i].equals("h") | argArray[i].equals("?") | argArray[i].equals("help")){
return true;
}
}
return false;
}
/**
*
* @param argArray
* @return Integer 0 if data format is HyperSQL, 1 if CSV directories
*/
private static Integer lookForDataFormat(String[] argArray){
// dataFormat should be replaced in the future with an enum of supported
// datatypes, searching through args could also be cleaned up.
Integer dataFormat = -1;
for(int i = 0; i < argArray.length; i++){
if (argArray[i].equals("csv") | argArray[i].equals("CSV")){
dataFormat = 0;
}
if (argArray[i].equals("hsql") | argArray[i].equals("HQSL")){
dataFormat = 1;
}
}
return dataFormat;
}
/**
* Iterates through the command line arguments looking for a directory
* The method then iterates through all files in that directory looking for .script files
* @param argArray command line arguments
* @return ArrayList<File> list of hypersql db files
*/
private static ArrayList<File> getDbFileList(String[] argArray) {
ArrayList<File> dbList = new ArrayList<File>();
for (int i = 0; i < argArray.length; i++) {
//find db directory argument
File folder = new File(argArray[i]);
if (folder.isDirectory()) {
File[] listOfFiles = folder.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
//find db files files in the directory
if (listOfFiles[j].isFile() && listOfFiles[j].getName().endsWith(".script")) {
if (!dbList.contains(listOfFiles[j])) {
dbList.add(listOfFiles[j]);
}
}
}
}
}
return dbList;
}
/**
* Iterates through the command line arguments looking for directory
* The method then iterates through all files/directories in that directory looking
* for directories that start with "Extractor"
* @param argArray
* @return ArrayList<File> list of CSV directories
*/
private static ArrayList<File> getCSVDirList(String[] argArray) {
ArrayList<File> dbList = new ArrayList<File>();
for (int i = 0; i < argArray.length; i++) {
//find db directory argument
File folder = new File(argArray[i]);
if (folder.isDirectory()) {
File[] listOfFiles = folder.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
//find db files files in the directory
if (listOfFiles[j].isDirectory() && listOfFiles[j].getName().startsWith("Extractor")) {
if (!dbList.contains(listOfFiles[j])) {
dbList.add(listOfFiles[j]);
}
}
}
}
}
return dbList;
}
}
//public class Main {
// public static void main(String[] args) throws SQLException, DBException {
// if (args.length!=1){
// System.err.println("Must have one argument");
// //System.exit(0);
// //read file ...
// String arg1 = "jmx-loader/src/main/java/org/jmxdatamart/Loader/loaderconfig.ini";
// DB2DB d2d = new DB2DB();
// LoaderSetting s =d2d.readProperties(arg1);
// d2d.loadSetting(s);
// d2d.copySchema();
// d2d.importData();
// d2d.disConnect();
// System.out.println("done"); |
package org.jasig.portal.security.provider;
/**
* A store for basic account information; username, passwords, etc.
* Note: this interface is particular to the reference security provider
* and is not part of the core portal interfaces.
*
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @version $Revision$
*/
public interface IAccountStore {
/**
* Obtain account information for a given username
*
* @param username a <code>String</code> value
* @return a <code>String[]</code> array containing (in the order given):
* md5 password, first name, last name.
* @exception Exception if an error occurs
*/
public String[] getUserAccountInformation(String username) throws Exception;
} |
package com.intuit.karate.cli;
import com.intuit.karate.FileUtils;
import com.intuit.karate.Resource;
import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import com.intuit.karate.RunnerOptions;
import com.intuit.karate.StringUtils;
import com.intuit.karate.core.Engine;
import com.intuit.karate.core.Feature;
import com.intuit.karate.core.FeatureParser;
import com.intuit.karate.core.FeatureResult;
import com.intuit.karate.core.Scenario;
import com.intuit.karate.core.ScenarioResult;
import com.intuit.karate.core.Tags;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author pthomas3
*/
public class Main {
private static final Pattern COMMAND_NAME = Pattern.compile("--name (.+?\\$)");
public static void main(String[] args) {
String command;
if (args.length > 0) {
command = StringUtils.join(args, ' ');
} else {
command = System.getProperty("sun.java.command");
}
System.out.println("command: " + command);
boolean isIntellij = command.contains("org.jetbrains");
RunnerOptions options = RunnerOptions.parseCommandLine(command);
String targetDir = FileUtils.getBuildDir() + File.separator + "surefire-reports";
runParallel(options, targetDir, isIntellij);
// runNormal(options, targetDir, isIntellij);
}
private static void runNormal(RunnerOptions options, String targetDir, boolean isIntellij) {
String tagSelector = Tags.fromKarateOptionsTags(options.getTags());
ClassLoader cl = Thread.currentThread().getContextClassLoader();
List<Resource> resources = FileUtils.scanForFeatureFiles(options.getFeatures(), cl);
for (Resource resource : resources) {
Feature feature = FeatureParser.parse(resource);
feature.setCallName(options.getName());
feature.setCallLine(resource.getLine());
FeatureResult result = Engine.executeFeatureSync(null, feature, tagSelector, null);
if (isIntellij) {
log(result);
}
Engine.saveResultHtml(targetDir, result, null);
}
}
private static void runParallel(RunnerOptions ro, String targetDir, boolean isIntellij) {
CliExecutionHook hook = new CliExecutionHook(targetDir, isIntellij);
Runner.path(ro.getFeatures())
.tags(ro.getTags()).scenarioName(ro.getName())
.hook(hook).parallel(ro.getThreads());
}
public static StringUtils.Pair parseCommandLine(String commandLine, String cwd) {
Matcher matcher = COMMAND_NAME.matcher(commandLine);
String name;
if (matcher.find()) {
name = matcher.group(1);
commandLine = matcher.replaceFirst("");
} else {
name = null;
}
List<String> args = Arrays.asList(commandLine.split("\\s+"));
Iterator<String> iterator = args.iterator();
String path = null;
while (iterator.hasNext()) {
String arg = iterator.next();
if (arg.equals("--plugin") || arg.equals("--glue")) {
iterator.next();
}
if (arg.startsWith("--") || arg.startsWith("com.") || arg.startsWith("cucumber.") || arg.startsWith("org.")) {
// do nothing
} else {
path = arg;
}
}
if (path == null) {
return null;
}
if (cwd == null) {
cwd = new File("").getAbsoluteFile().getPath();
}
cwd = cwd.replace('\\', '/'); // fix for windows
path = path.substring(cwd.length() + 1);
if (path.startsWith(FileUtils.SRC_TEST_JAVA)) {
path = FileUtils.CLASSPATH_COLON + path.substring(FileUtils.SRC_TEST_JAVA.length() + 1);
} else if (path.startsWith(FileUtils.SRC_TEST_RESOURCES)) {
path = FileUtils.CLASSPATH_COLON + path.substring(FileUtils.SRC_TEST_RESOURCES.length() + 1);
}
return StringUtils.pair(path, name);
}
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
private static final String TEAMCITY_PREFIX = "##teamcity";
private static final String TEMPLATE_TEST_STARTED = TEAMCITY_PREFIX + "[testStarted timestamp = '%s' locationHint = '%s' captureStandardOutput = 'true' name = '%s']";
private static final String TEMPLATE_TEST_FAILED = TEAMCITY_PREFIX + "[testFailed timestamp = '%s' details = '%s' message = '%s' name = '%s' %s]";
private static final String TEMPLATE_SCENARIO_FAILED = TEAMCITY_PREFIX + "[customProgressStatus timestamp='%s' type='testFailed']";
private static final String TEMPLATE_TEST_PENDING = TEAMCITY_PREFIX + "[testIgnored name = '%s' message = 'Skipped step' timestamp = '%s']";
private static final String TEMPLATE_TEST_FINISHED = TEAMCITY_PREFIX + "[testFinished timestamp = '%s' duration = '%s' name = '%s']";
private static final String TEMPLATE_ENTER_THE_MATRIX = TEAMCITY_PREFIX + "[enteredTheMatrix timestamp = '%s']";
private static final String TEMPLATE_TEST_SUITE_STARTED = TEAMCITY_PREFIX + "[testSuiteStarted timestamp = '%s' locationHint = 'file://%s' name = '%s']";
private static final String TEMPLATE_TEST_SUITE_FINISHED = TEAMCITY_PREFIX + "[testSuiteFinished timestamp = '%s' name = '%s']";
private static final String TEMPLATE_SCENARIO_COUNTING_STARTED = TEAMCITY_PREFIX + "[customProgressStatus testsCategory = 'Scenarios' count = '%s' timestamp = '%s']";
private static final String TEMPLATE_SCENARIO_COUNTING_FINISHED = TEAMCITY_PREFIX + "[customProgressStatus testsCategory = '' count = '0' timestamp = '%s']";
private static final String TEMPLATE_SCENARIO_STARTED = TEAMCITY_PREFIX + "[customProgressStatus type = 'testStarted' timestamp = '%s']";
private static final String TEMPLATE_SCENARIO_FINISHED = TEAMCITY_PREFIX + "[customProgressStatus type = 'testFinished' timestamp = '%s']";
private static String escape(String source) {
if (source == null) {
return "";
}
return source.replace("|", "||").replace("\n", "|n").replace("\r", "|r").replace("'", "|'").replace("[", "|[").replace("]", "|]");
}
private static String getCurrentTime() {
return DATE_FORMAT.format(new Date());
}
private static void log(String s) {
System.out.println(s);
}
private static StringUtils.Pair details(Throwable error) {
String fullMessage = error.getMessage().replace("\r", "").replace("\t", " ");
String[] messageInfo = fullMessage.split("\n", 2);
if (messageInfo.length == 2) {
return StringUtils.pair(messageInfo[0].trim(), messageInfo[1].trim());
} else {
return StringUtils.pair(fullMessage, "");
}
}
public static void log(FeatureResult fr) {
Feature f = fr.getFeature();
String uri = fr.getDisplayUri();
String featureName = Feature.KEYWORD + ": " + escape(f.getName());
log(String.format(TEMPLATE_ENTER_THE_MATRIX, getCurrentTime()));
log(String.format(TEMPLATE_SCENARIO_COUNTING_STARTED, 0, getCurrentTime()));
log(String.format(TEMPLATE_TEST_SUITE_STARTED, getCurrentTime(), uri + ":" + f.getLine(), featureName));
for (ScenarioResult sr : fr.getScenarioResults()) {
Scenario s = sr.getScenario();
String scenarioName = s.getKeyword() + ": " + escape(s.getName());
log(String.format(TEMPLATE_SCENARIO_STARTED, getCurrentTime()));
log(String.format(TEMPLATE_TEST_STARTED, getCurrentTime(), uri + ":" + s.getLine(), scenarioName));
if (sr.isFailed()) {
StringUtils.Pair error = details(sr.getError());
log(String.format(TEMPLATE_TEST_FAILED, getCurrentTime(), escape(error.right), escape(error.left), scenarioName, ""));
}
log(String.format(TEMPLATE_TEST_FINISHED, getCurrentTime(), sr.getDurationNanos() / 1000000, scenarioName));
}
log(String.format(TEMPLATE_TEST_SUITE_FINISHED, getCurrentTime(), featureName));
log(String.format(TEMPLATE_SCENARIO_COUNTING_FINISHED, getCurrentTime()));
}
} |
package com.googlecode.totallylazy.records.xml;
import com.googlecode.totallylazy.Callable1;
import com.googlecode.totallylazy.LazyException;
import com.googlecode.totallylazy.Pair;
import com.googlecode.totallylazy.Sequence;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import static com.googlecode.totallylazy.Runnables.VOID;
public class Xml {
public static String selectContents(final Node node, final String expression) {
return contents(selectNodes(node, expression));
}
public static Sequence<Node> selectNodes(final Node node, final String expression) {
try {
return sequence((NodeList) xpath().evaluate(expression, node, XPathConstants.NODESET));
} catch (XPathExpressionException e) {
throw new LazyException(e);
}
}
public static Node selectNode(final Node node, final String expression){
return selectNodes(node, expression).head();
}
public static Sequence<Element> selectElements(final Node node, final String expression){
return selectNodes(node, expression).safeCast(Element.class);
}
public static Element selectElement(final Node node, final String expression){
return selectElements(node, expression).head();
}
public static XPath xpath() {
return XPathFactory.newInstance().newXPath();
}
public static Sequence<Node> sequence(final NodeList nodes) {
return new Sequence<Node>() {
public Iterator<Node> iterator() {
return new NodeIterator(nodes);
}
};
}
public static String contents(Sequence<Node> nodes) {
return nodes.map(contents()).toString("");
}
public static Callable1<Element, Void> removeAttribute(final String name) {
return new Callable1<Element, Void>() {
public Void call(Element element) throws Exception {
element.removeAttribute(name);
return VOID;
}
};
}
public static Callable1<? super Node, String> contents() {
return new Callable1<Node, String>() {
public String call(Node node) throws Exception {
return contents(node);
}
};
}
public static String contents(Node node) throws Exception {
if (node instanceof Attr) {
return contents((Attr) node);
}
if (node instanceof CharacterData) {
return contents((CharacterData) node);
}
if (node instanceof Element) {
return contents((Element) node);
}
throw new UnsupportedOperationException("Unknown node type " + node.getClass());
}
public static String contents(CharacterData characterData) {
return characterData.getData();
}
public static String contents(Attr attr) {
return attr.getValue();
}
public static String contents(Element element) throws Exception {
return sequence(element.getChildNodes()).map(new Callable1<Node, String>() {
public String call(Node node) throws Exception {
if (node instanceof Element) {
return asString((Element) node);
}
return contents(node);
}
}).toString("");
}
public static String asString(Element element) throws Exception {
Transformer transformer = transformer();
StringWriter writer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(element), new StreamResult(writer));
return writer.toString();
}
public static Transformer transformer(Pair<String, Object>... attributes) throws TransformerConfigurationException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
for (Pair<String, Object> attribute : attributes) {
transformerFactory.setAttribute(attribute.first(), attribute.second());
}
return transformerFactory.newTransformer();
}
public static Document document(String xml) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(ignoreEntities());
return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
} catch (Exception e) {
throw new LazyException(e);
}
}
private static EntityResolver ignoreEntities() {
return new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
};
}
public static Sequence<Node> remove(final Node root, final String expression) {
return remove(selectNodes(root, expression));
}
public static Sequence<Node> remove(final Sequence<Node> nodes) {
return nodes.map(remove()).realise();
}
private static Callable1<Node, Node> remove() {
return new Callable1<Node, Node>() {
public Node call(Node node) throws Exception {
return node.getParentNode().removeChild(node);
}
};
}
public static String format(final Node node) throws Exception {
return format(node, Pair.<String, Object>pair("indent-number", 4));
}
public static String format(final Node node, final Pair<String, Object>... attributes) throws Exception {
Transformer transformer = transformer(attributes);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();
}
} |
package edu.oswego.tiltandtumble.data;
import java.util.ArrayList;
import java.util.HashMap;
import com.badlogic.gdx.file.FileHandle;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.BufferedOutputStream;
import java.lang.ClassNotFoundException;
public class HighScores implements Serializable{
// TODO: implement this
ArrayList<Integer> scores;
public HighScore(){
if(Gdx.file.local("Score.dat").exist()){
try{
HighScore temp = this.loadFromFile();
scores = temp.scores;
}
catch(IOException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
else{
scores = new ArrayList<Interger>();
}
}
public void compareAndSave(int currentScore){
if(scores.size() < 10){
int j = 0;
for(; j < scores.size(); j++){
if(currentScore > scores.get(j)){
scores.add(j, new Integer(currrentScore));
j = 11;
}
}
if(j != 11){
scores.add(scores.size(), new Integer(currentScore));
}
}
else{
if(currentScore > scores.get(0)){
scores.add(0, new Integer(currentScore));
scores.remove(10);
}
else{
for(int i = 1; i < 10; i++){
if(currentScore < scores.get(i-1) && currentScore > scores.get(i)){
scores.add(i, Integer(currentScore));
scores.remove(10);
}
}
}
}
}
public void saveToFile() throws IOException{
FileHandle file = Gdx.files.local("Scores.dat");
OutputStream out= null;
file.writeBytes(serialize(this), false);
if(out != null){
out.close();
}
}
public HighScore loadFromFile()throws IOException, ClassNotFoundException{
FileHandle file = Gdx.files.local("Scores.dat");
return (HighScore) deserialize(file.readBytes());
}
private byte[] serialize(Object o)throws IOException{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream(bOut);
oOut.writeObject(o);
return bOut.toByteArray();
}
}
private Object deserialize(byte[] b)throws IOException, ClassNotFoundException{
ByteArrayInputStream bIn = new ByteArrayInputStream(b);
ObjectInputStream oIn = new ObjectInputStream(bIn);
return oIn.readObject();
}
} |
package br.ufam.sportag.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import br.ufam.sportag.R;
import br.ufam.sportag.asynctask.HttpWebRequest;
import br.ufam.sportag.dialog.EventInviteDialog;
import br.ufam.sportag.model.Evento;
import br.ufam.sportag.model.Usuario;
import br.ufam.sportag.util.Util;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class EventActivity extends Activity {
// private String eventTitle;
private GoogleMap map;
private LatLng eventLocation;
private Evento evento;
private Usuario usuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
getActionBar().setDisplayHomeAsUpEnabled(true);
usuario = (Usuario) getIntent().getExtras().getSerializable("usuario");
evento = (Evento) getIntent().getExtras().getSerializable("evento");
Log.i("Evento Recebido", evento.getNome());
initJoinDetail();
addEventDetails();
}
private void initJoinDetail() {
// estado do switch
final Switch switchJoin = (Switch) findViewById(R.id.switch_join);
HashMap<String, Object> args = new HashMap<String, Object>();
args.put("type", "usuario_evento_confirmado");
args.put("usuario_id", usuario.getId_foursquare());
args.put("evento_id", evento.getId());
String isAttendantUrl = Util.searchUrl + Util.dictionaryToString(args);
HttpWebRequest isAttendantRequest = new HttpWebRequest(this,
isAttendantUrl) {
@Override
public void onSuccess(String paramString) {
JSONArray arrayObj;
try {
arrayObj = new JSONArray(paramString);
if (!arrayObj.toString().equals("[]")) {
switchJoin.setChecked(true);
}
setarSwitchListener(switchJoin);
} catch (JSONException jsonExcep)
{
Log.e("Erro", "JSON", jsonExcep);
};
}
};
isAttendantRequest.execute();
}
private void setarSwitchListener(final Switch switchJoin) {
switchJoin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
saveJoin(switchJoin);
} else {
cancelJoin(switchJoin);
}
}
});
}
protected void saveJoin(Switch switchJoin) {
HashMap<String, Object> args = new HashMap<String, Object>();
args.put("type", "usuario_evento_confirmado");
args.put("usuario_id", usuario.getId_foursquare());
args.put("evento_id", evento.getId());
String saveJoinUrl = Util.addUrl + Util.dictionaryToString(args);
HttpWebRequest saveJoinRequest = new HttpWebRequest(this, saveJoinUrl) {
@Override
public void onSuccess(String paramString) {
Toast.makeText(getApplicationContext(),
"Participação confirmada!", Toast.LENGTH_SHORT).show();
}
};
saveJoinRequest.execute();
}
protected void cancelJoin(Switch switchJoin) {
HashMap<String, Object> args = new HashMap<String, Object>();
args.put("type", "usuario_evento_confirmado");
args.put("usuario_id", usuario.getId_foursquare());
args.put("evento_id", evento.getId());
String saveJoinUrl = Util.deleteUrl + Util.dictionaryToString(args);
HttpWebRequest cancelJoinRequest = new HttpWebRequest(this, saveJoinUrl) {
@Override
public void onSuccess(String paramString) {
Toast.makeText(getApplicationContext(),
"Participação cancelada", Toast.LENGTH_SHORT).show();
}
};
cancelJoinRequest.execute();
}
private void addEventDetails() {
// Popula a tela de eventos com os dados recebidos na intent
TextView tvEventName = (TextView) findViewById(R.id.tv_eventName);
TextView tvEventPrivacy = (TextView) findViewById(R.id.tv_eventPrivacy);
TextView tvEventAddress = (TextView) findViewById(R.id.tv_eventAddress);
TextView tvEventDate = (TextView) findViewById(R.id.tv_eventDate);
map = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map_event)).getMap();
String dataHora = (String) DateFormat.format("yyyy-MM-dd kk:mm:ss",
evento.getDataHora());
int visibilidade = evento.isVisivel() ? 1 : 0;
String nomeEvento = evento.getNome(), nomeLocal = evento
.getLocalizacaoEvento().getNomeLocal();
double latit = evento.getLocalizacaoEvento().getLatitude();
double longit = evento.getLocalizacaoEvento().getLongitude();
tvEventName.setText(nomeEvento);
tvEventPrivacy.setText(visibilidade == 1 ? "Público" : "Privado");
tvEventAddress.setText(nomeLocal);
tvEventDate.setText(dataHora);
eventLocation = new LatLng(latit, longit);
map.addMarker(new MarkerOptions().position(eventLocation).icon(
BitmapDescriptorFactory.fromResource(R.drawable.icone_futebol)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(eventLocation, 14));
// Adiciona imagens dos participantes no grid
// addAttendantsToGrid();
}
private void addAttendantsToGrid() {
HashMap<String, Object> args = new HashMap<String, Object>();
args.put("type", "usuario_evento_confirmado");
args.put("evento_id", evento.getId());
String attendantsUrl = Util.searchUrl + Util.dictionaryToString(args);
HttpWebRequest attendantsRequest = new HttpWebRequest(this,
attendantsUrl) {
@Override
public void onSuccess(String paramString) {
ArrayList<Usuario> listaUsuarios = new ArrayList<Usuario>();
parsingUsuarios(listaUsuarios, paramString);
GridLayout grid = (GridLayout) findViewById(R.id.grid_attendants);
for (Usuario usuario : listaUsuarios) {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new LayoutParams(32, 32));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
imageView.setImageBitmap(usuario.getAvatar());
grid.addView(imageView);
}
}
};
attendantsRequest.execute();
}
private void parsingUsuarios(final ArrayList<Usuario> listaUsuarios,
String jsonString) {
JSONArray arrayObj;
try {
arrayObj = new JSONArray(jsonString);
for (int i = 0; i < arrayObj.length(); i++) {
final JSONObject eventoJSONObj = arrayObj.getJSONObject(i);
Usuario usuario = new Usuario();
usuario.setId_foursquare(eventoJSONObj
.getInt("usuario.id_foursquare"));
usuario.setNome(eventoJSONObj.getString("usuario.nome"));
usuario.setFotoPrefix(eventoJSONObj
.getString("usuario.fotoPrefix"));
usuario.setFotoSuffix(eventoJSONObj
.getString("usuario.fotoSuffix"));
Bitmap avatar = Util.loadBitmap(usuario.getFotoPrefix()
+ "36x36" + usuario.getFotoSuffix());
usuario.setAvatar(avatar);
listaUsuarios.add(usuario);
}
} catch (JSONException e) {
Log.e("Erro", "JSON", e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.event, menu);
return true;
}
public void callEventDiscussionActivity(View view) {
Intent intent = new Intent(getApplicationContext(),
EventDiscussionActivity.class);
intent.putExtras(getIntent().getExtras());
startActivity(intent);
}
public void callEventInvitationDialog(View view) {
// Chama a dialog de amigos que podem ser convidados para o evento
EventInviteDialog inviteDialog = new EventInviteDialog();
inviteDialog.show(getFragmentManager(), "event_invite");
}
} |
package com.karateca.jstoolbox.joiner;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.karateca.jstoolbox.MyAction;
/**
* @author Andres Dominguez.
*/
public class JoinerAction extends MyAction {
private static final String VAR_DECLARATION = "^\\s*var.*";
private static final String MULTI_LINE_STRING = ".+\\+\\s*$";
private static final String MULTI_LINE_STRING_SECOND_LINE = "^\\s*'.+";
private Document document;
private Editor editor;
private Project project;
public void actionPerformed(AnActionEvent actionEvent) {
editor = actionEvent.getData(PlatformDataKeys.EDITOR);
if (editor == null) {
return;
}
project = getEventProject(actionEvent);
document = editor.getDocument();
LineRange lineRange = getSelectedLineRange();
int firstSelectedLine = lineRange.getStart();
String firstLine = getLocForLineNumber(firstSelectedLine);
String nextLine = getLocForLineNumber(firstSelectedLine + 1);
// Is the caret in a multi line string ('foo' +) and the next line is a
// string?
if (firstLine.matches(MULTI_LINE_STRING) &&
nextLine.matches(MULTI_LINE_STRING_SECOND_LINE)) {
joinMultiLineString(lineRange);
return;
}
// Is it a variable declaration?
if (firstLine.endsWith(";") && nextLine.matches(VAR_DECLARATION)) {
joinCurrentVariableDeclaration(firstLine);
}
}
private void joinMultiLineString(LineRange lineRange) {
// Join either one line with the next or multiple lines.
int endLine = Math.max(lineRange.getEnd(), lineRange.getStart() + 1);
joinStringGivenLineRange(lineRange.getStart(), endLine);
}
private void joinCurrentVariableDeclaration(final String currentLine) {
final String nextLine = getNextLine();
int lineNumber = getLineNumberAtCaret();
final TextRange currentLineTextRange = getTextRange(lineNumber);
final TextRange nextLineTextRange = getTextRange(lineNumber + 1);
runWriteActionInsideCommand(new Runnable() {
@Override
public void run() {
// Replace var from next line.
String newLine = nextLine.replaceFirst("var", " ");
document.replaceString(nextLineTextRange.getStartOffset(),
nextLineTextRange.getEndOffset(), newLine);
// Replace ; from current line.
newLine = currentLine.replaceAll(";$", ",");
document.replaceString(currentLineTextRange.getStartOffset(),
currentLineTextRange.getEndOffset(), newLine);
}
});
}
private LineRange getSelectedLineRange() {
SelectionModel selectionModel = editor.getSelectionModel();
VisualPosition startPosition = selectionModel.getSelectionStartPosition();
VisualPosition endPosition = selectionModel.getSelectionEndPosition();
if (startPosition == null || endPosition == null) {
return null;
}
int startLine = startPosition.getLine();
int endLine = endPosition.getLine();
return new LineRange(Math.min(startLine, endLine), Math.max(startLine, endLine));
}
private void joinStringGivenLineRange(int startLine, int endLine) {
int startOffset = getTextRange(startLine).getStartOffset();
int endOffset = getTextRange(endLine).getEndOffset();
String textForRange = getTextForRange(new TextRange(startOffset, endOffset));
String s = textForRange.replaceAll("'\\s*\\+\\s*'", "");
replaceString(s, startOffset, endOffset);
}
private void replaceString(final String replacementText, final int start, final int end) {
runWriteActionInsideCommand(new Runnable() {
@Override
public void run() {
document.replaceString(start, end, replacementText);
}
});
}
private String getLocForLineNumber(int lineNumber) {
return getTextForRange(getTextRange(lineNumber));
}
private String getNextLine() {
int lineNumber = getLineNumberAtCaret();
return getLocForLineNumber(lineNumber + 1);
}
private int getLineNumberAtCaret() {
int offset = editor.getCaretModel().getOffset();
return document.getLineNumber(offset);
}
private String getTextForRange(TextRange range) {
return document.getText(range);
}
/**
* Get the text range for a line of code.
*
* @param lineNumber The line number.
* @return The text range for the line.
*/
private TextRange getTextRange(int lineNumber) {
int lineStart = document.getLineStartOffset(lineNumber);
int lineEnd = document.getLineEndOffset(lineNumber);
return new TextRange(lineStart, lineEnd);
}
/**
* Run a write operation within a command.
*
* @param action The action to run.
*/
private void runWriteActionInsideCommand(final Runnable action) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(action);
}
}, "Join", null);
}
} |
package com.mapotempo.fleet.core;
import com.couchbase.lite.AsyncTask;
import com.couchbase.lite.Attachment;
import com.couchbase.lite.Context;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DatabaseOptions;
import com.couchbase.lite.Document;
import com.couchbase.lite.LiveQuery;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.SavedRevision;
import com.couchbase.lite.TransactionalTask;
import com.couchbase.lite.UnsavedRevision;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.replicator.RemoteRequestResponseException;
import com.couchbase.lite.replicator.Replication;
import com.couchbase.lite.support.FileDirUtils;
import com.mapotempo.fleet.core.exception.CoreException;
import com.mapotempo.fleet.utils.HashHelper;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* DatabaseHandler.
*/
public class DatabaseHandler {
private boolean mReleaseStatus = false;
private boolean mConnexionStatus = true;
private Context mContext;
private Manager mManager;
public Database mDatabase;
private String mDbname;
private URL url = null;
private String mUser;
private String mPassword;
private Replication mPusher, mPuller;
private String mSyncGatewayUrl;
public interface OnCatchLoginError {
void CatchLoginError();
}
private OnCatchLoginError mOnCatchLoginError;
public DatabaseHandler(String user, String password, Context context, String syncGatewayUrl, OnCatchLoginError onCatchLoginError) throws CoreException {
mContext = context;
mOnCatchLoginError = onCatchLoginError;
// FIXME
mUser = user;
mPassword = password;
mSyncGatewayUrl = syncGatewayUrl;
try {
mManager = new Manager(mContext, Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
throw new CoreException("Error : Manager can't be created");
}
mDbname = databaseNameGenerator(mUser, mSyncGatewayUrl);
try {
DatabaseOptions passwordDatabaseOption = new DatabaseOptions();
passwordDatabaseOption.setEncryptionKey(mPassword);
passwordDatabaseOption.setCreate(true);
mDatabase = mManager.openDatabase(mDbname.toLowerCase(), passwordDatabaseOption);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
throw new CoreException("Error : Can't open bdd");
}
}
// CONNEXION
public void initConnexion() throws CoreException {
try {
url = new URL(mSyncGatewayUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
throw new CoreException("Error : Invalide url connexion");
}
// Pusher and Puller sync
mPusher = mDatabase.createPushReplication(url);
mPusher.setContinuous(true); // Runs forever in the background
mPusher.addChangeListener(new Replication.ChangeListener() {
@Override
public void changed(Replication.ChangeEvent changeEvent) {
System.out.println("pusher changed listener " + changeEvent.getStatus());
Replication.ReplicationStatus a = changeEvent.getStatus();
if (changeEvent.getError() != null) {
System.out.println("
System.out.println("changeEvent.toString() >>>>>>>>> " + changeEvent.toString());
System.out.println("changeEvent.getError() >>>>>>>>> " + changeEvent.getError());
if (changeEvent.getError() instanceof RemoteRequestResponseException) {
RemoteRequestResponseException ex = (RemoteRequestResponseException) changeEvent.getError();
System.out.println("HTTP Error: " + ex.getCode() + ": " + ex.getMessage());
System.out.println(" " + ex.getUserInfo());
System.out.println(" hash code " + ex.hashCode());
if (new Integer(403).equals(ex.getCode())) {
System.out.println("403 !!");
mOnCatchLoginError.CatchLoginError();
}
}
System.out.println("
}
}
});
mPuller = mDatabase.createPullReplication(url);
mPuller.setContinuous(true); // Runs forever in the background
mPuller.addChangeListener(new Replication.ChangeListener() {
@Override
public void changed(Replication.ChangeEvent changeEvent) {
Replication.ReplicationStatus a = changeEvent.getStatus();
System.out.println("puller changed listener " + changeEvent.getStatus());
System.out.println("> *************");
if (changeEvent.getError() != null) {
System.out.println(changeEvent.toString());
if (changeEvent.getError() instanceof RemoteRequestResponseException) {
RemoteRequestResponseException ex = (RemoteRequestResponseException) changeEvent.getError();
System.out.println("HTTP Error: " + ex.getCode() + ": " + ex.getMessage());
System.out.println(" " + ex.getUserInfo());
System.out.println(" hash code " + ex.hashCode());
if (new Integer(401).equals(ex.getCode())) {
System.out.println("401 !!");
mOnCatchLoginError.CatchLoginError();
}
}
}
System.out.println("< *************");
}
});
// USER AUTH
Authenticator authenticator = AuthenticatorFactory.createBasicAuthenticator(mUser, mPassword);
mPusher.setAuthenticator(authenticator);
mPuller.setAuthenticator(authenticator);
// Start synchronisation
mPusher.start();
mPuller.start();
onlineStatus(mConnexionStatus);
startConflictLiveQuery();
}
// FIXME replace goOnline/goOffline => start/stop
public void onlineStatus(boolean status) {
mConnexionStatus = status;
if (status) {
mPusher.start();
mPuller.start();
} else {
mPusher.stop();
mPuller.stop();
}
}
public boolean isOnline() {
return mConnexionStatus;
}
public void printAllData() {
try {
// Let's find the documents that have conflicts so we can resolve them:
Query query = mDatabase.createAllDocumentsQuery();
query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
List<Object> res = new ArrayList<Object>();
QueryEnumerator result = query.run();
for (Iterator<QueryRow> it = result; it.hasNext(); ) {
QueryRow row = it.next();
String docId = row.getDocumentId();
Document doc = mDatabase.getDocument(docId);
System.out.println("
System.out.println("id : " + doc.getId());
for (SavedRevision savedRevision : doc.getConflictingRevisions())
System.out.println(" - conflict : " + savedRevision.getProperties().get("_rev"));
System.out.println(" - " + doc.getProperties().toString());
}
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
return;
}
public void restartPuller() {
mPuller.restart();
}
public void setPublicChannel() {
List<String> channels = mPuller.getChannels();
channels.add("!");
mPuller.setChannels(channels);
}
public void setUserChannel(String userName) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("user:" + userName);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void setCompanyChannel(String companyId) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("company:" + companyId);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void setMissionChannel(String userName, String date) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("mission:" + userName + ":" + date);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void setMissionStatusTypeChannel(String company_id) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("mission_status_type:" + company_id);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void setMissionStatusActionChannel(String company_id) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("mission_status_action:" + company_id);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void setCurrentLocationChannel(String user) throws CoreException {
if (mPuller != null) {
List<String> channels = mPuller.getChannels();
channels.add("user_current_location" + ":" + user);
mPuller.setChannels(channels);
} else {
throw new CoreException("Warning : Connexion need to be configure with setConnexionParam method before channel setting");
}
}
public void release(boolean delete_db) {
if (mReleaseStatus)
return;
if (mPusher != null) {
mPusher.stop();
mPusher = null;
}
if (mPuller != null) {
mPuller.stop();
mPuller = null;
}
//
// ## FIXME Trick
// ## Ce 'trick' permet d'effectuer la fermeture de la base
// ## dans un autre thread. En effet la fermeture d'une base
//
//
//
//
//
mDatabase.runAsync(new AsyncTask() {
@Override
public void run(Database database) {
mDatabase.close();
}
});
if (delete_db) {
File databaseDirectory = mManager.getDirectory();
if (databaseDirectory != null) {
File databaseFile = new File(databaseDirectory, mDbname + ".cblite2"); // Or ".cblite"...
if (databaseFile.exists()) {
FileDirUtils.deleteRecursive(databaseFile);
}
}
}
// # FIXME Trick
//
mDatabase = null;
mManager.close();
mManager = null;
mReleaseStatus = true;
}
private String databaseNameGenerator(String userName, String url) {
try {
// Database name must be unique for a username and specific url.
return "database_" + userName + HashHelper.sha256(url).substring(0, 10);
} catch (CoreException e) {
throw new RuntimeException("Error during databaseNameGenerator");
}
}
private void startConflictLiveQuery() {
System.out.println(">>>>>>>>>>>>>>>>>> startConflictLiveQuery");
LiveQuery conflictsLiveQuery = mDatabase.createAllDocumentsQuery().toLiveQuery();
conflictsLiveQuery.setAllDocsMode(Query.AllDocsMode.ONLY_CONFLICTS);
conflictsLiveQuery.addChangeListener(new LiveQuery.ChangeListener() {
@Override
public void changed(LiveQuery.ChangeEvent event) {
resolveConflicts(event.getRows());
}
});
conflictsLiveQuery.start();
}
private void resolveConflicts(QueryEnumerator rows) {
for (QueryRow row : rows) {
List<SavedRevision> revs = row.getConflictingRevisions();
if (revs.size() > 1) {
SavedRevision defaultWinning = revs.get(0);
Map<String, Object> props = defaultWinning.getUserProperties();
Attachment image = defaultWinning.getAttachment("image");
resolveConflicts(revs, props, image);
}
}
}
private void resolveConflicts(final List<SavedRevision> revs, final Map<String, Object> desiredProps, final Attachment desiredImage) {
mDatabase.runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
int i = 0;
for (SavedRevision rev : revs) {
UnsavedRevision newRev = rev.createRevision(); // Create new revision
if (i == 0) { // That's the current/winning revision
newRev.setUserProperties(desiredProps);
if (desiredImage != null) {
try {
newRev.setAttachment("image", "image/jpg", desiredImage.getContent());
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
} else { // That's a conflicting revision, delete it
newRev.setIsDeletion(true);
}
try {
newRev.save(true); // Persist the new revision
} catch (CouchbaseLiteException e) {
e.printStackTrace();
return false;
}
i++;
}
return true;
}
});
}
} |
package SW9.controllers;
import SW9.HUPPAAL;
import SW9.abstractions.Query;
import SW9.abstractions.QueryState;
import SW9.backend.BackendException;
import SW9.backend.UPPAALDriver;
import SW9.presentations.QueryPresentation;
import SW9.utility.helpers.DropShadowHelper;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXRippler;
import com.sun.javaws.exceptions.InvalidArgumentException;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
public class QueryPaneController implements Initializable {
public Label toolbarTitle;
public JFXButton addQueryButton;
public AnchorPane toolbar;
public JFXRippler runAllQueriesButton;
public JFXRippler clearAllQueriesButton;
public VBox queriesList;
public StackPane root;
public ScrollPane scrollPane;
private Map<Query, QueryPresentation> queryPresentationMap = new HashMap<>();
@Override
public void initialize(final URL location, final ResourceBundle resources) {
// We need to register these event manually this way because JFXButton overrides onPressed and onRelease to handle rippler effect
addQueryButton.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> addQueryButtonPressed());
addQueryButton.addEventHandler(MouseEvent.MOUSE_RELEASED, event -> addQueryButtonReleased());
HUPPAAL.getProject().getQueries().addListener(new ListChangeListener<Query>() {
@Override
public void onChanged(final Change<? extends Query> c) {
while (c.next()) {
for (final Query removeQuery : c.getRemoved()) {
queriesList.getChildren().remove(queryPresentationMap.get(removeQuery));
queryPresentationMap.remove(removeQuery);
}
for (final Query newQuery : c.getAddedSubList()) {
final QueryPresentation newQueryPresentation = new QueryPresentation(newQuery);
queryPresentationMap.put(newQuery, newQueryPresentation);
queriesList.getChildren().add(newQueryPresentation);
}
}
}
});
for (final Query newQuery : HUPPAAL.getProject().getQueries()) {
queriesList.getChildren().add(new QueryPresentation(newQuery));
}
}
@FXML
private void addQueryButtonClicked() {
HUPPAAL.getProject().getQueries().add(new Query("", "", QueryState.UNKNOWN));
}
@FXML
private void addQueryButtonPressed() {
addQueryButton.setEffect(DropShadowHelper.generateElevationShadow(12));
}
@FXML
private void addQueryButtonReleased() {
addQueryButton.setEffect(DropShadowHelper.generateElevationShadow(6));
}
@FXML
private void runAllQueriesButtonClicked() {
HUPPAAL.getProject().getQueries().forEach(query -> {
// Reset the status of the query
query.setQueryState(QueryState.UNKNOWN);
query.setQueryState(QueryState.RUNNING);
try {
UPPAALDriver.buildHUPPAALDocument();
UPPAALDriver.verify(query.getQuery(),
aBoolean -> {
if (aBoolean) {
query.setQueryState(QueryState.SUCCESSFUL);
} else {
query.setQueryState(QueryState.ERROR);
}
},
e -> {
query.setQueryState(QueryState.SYNTAX_ERROR);
}
).start();
} catch (InvalidArgumentException | BackendException e) {
e.printStackTrace();
}
});
}
@FXML
private void clearAllQueriesButtonClicked() {
HUPPAAL.getProject().getQueries().forEach(query -> query.setQueryState(QueryState.UNKNOWN));
}
} |
package nodash.test;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import org.apache.commons.codec.binary.Base64;
import sun.security.rsa.RSAPublicKeyImpl;
import nodash.core.NoCore;
import nodash.core.NoRegister;
import nodash.exceptions.NoDashSessionBadUUIDException;
import nodash.exceptions.NoSessionConfirmedException;
import nodash.exceptions.NoSessionExpiredException;
import nodash.exceptions.NoUserAlreadyOnlineException;
import nodash.exceptions.NoUserNotValidException;
import nodash.models.NoSession.NoState;
public class NoCoreTest {
private static final String[] CHANGE = new String[] {
"first-string",
"second-string",
"third-string",
"forth-string",
"fifth-string",
"sixth-string",
"seventh-string",
"eighth-string",
"ninth-string",
"tenth-string"
};
private static Iterator<String> CHANGES = Arrays.asList(CHANGE).iterator();
private static final String PASSWORD = "password";
private static final String BAD_PASSWORD = "bad-password";
private static final Logger logger = Logger.getLogger("NoCoreTest");
private static boolean silent = false;
private static boolean printStackTraces = false;
private static Object passoverData;
public static void setPrintStackTraces(boolean toggle) {
printStackTraces = toggle;
}
public static void setSilence(boolean toggle) {
silent = toggle;
}
private static class TestTicker {
private int run;
private int passed;
public void test(boolean result) {
run++;
if (result) {
passed++;
}
}
public boolean passed() {
return run == passed;
}
public int getRun() {
return run;
}
public int getPassed() {
return passed;
}
public String getResultMessage() {
return "Passed " + getPassed() + " out of " + getRun() + " tests.";
}
public void logResultMessage() {
if (passed()) {
printIf(getResultMessage());
} else {
logger.severe(getResultMessage());
}
}
}
private static void printIf(Exception e) {
if (printStackTraces) {
e.printStackTrace();
}
}
private static void printIf(String s) {
if (!silent) {
logger.info(s);
}
}
private static void checkSetup() {
if (!NoCore.isReady()) {
throw new NoTestNotReadyException("NoCore is not ready to test.");
}
}
private static byte[] modifyByteArray(byte[] array) {
if (array.length > 0) {
if (array[0] == 'A') {
array[0] = 'B';
} else {
array[0] = 'A';
}
}
return array;
}
private static byte[] copy(byte[] array) {
return Arrays.copyOf(array, array.length);
}
/*
* BEGIN Registration Methods
*/
public static boolean testRegistrationFailureBadCookie() {
printIf("Testing registration failure with a bad cookie.");
checkSetup();
NoUserTest user = new NoUserTest(CHANGE[0]);
NoRegister register = NoCore.register(user, PASSWORD.toCharArray());
byte[] cookie = modifyByteArray(register.cookie);
try {
NoCore.confirm(cookie, PASSWORD.toCharArray(), register.data);
logger.severe("Registration with bad cookie throws no errors.");
} catch (NoDashSessionBadUUIDException e) {
printIf("NoDashSessionBadUUIDException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoDashSessionBadUUIDException, was " + e.getClass().getSimpleName());
printIf(e);
}
return false;
}
public static boolean testRegistrationFailureBadData() {
printIf("Testing registration failure with a bad data stream.");
checkSetup();
NoUserTest user = new NoUserTest(CHANGE[0]);
NoRegister register = NoCore.register(user, PASSWORD.toCharArray());
byte[] data = modifyByteArray(register.data);
try {
NoCore.confirm(register.cookie, PASSWORD.toCharArray(), data);
logger.severe("Registration with bad d throws no errors.");
} catch (NoUserNotValidException e) {
printIf("NoUserNotValidException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName());
printIf(e);
}
return false;
}
public static boolean testRegistrationFailureBadPassword() {
printIf("Testing registration failure with a bad password.");
checkSetup();
NoUserTest user = new NoUserTest(CHANGE[0]);
NoRegister register = NoCore.register(user, PASSWORD.toCharArray());
try {
NoCore.confirm(register.cookie, BAD_PASSWORD.toCharArray(), register.data);
logger.severe("Registration with bad d throws no errors.");
} catch (NoUserNotValidException e) {
printIf("NoUserNotValidException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName());
printIf(e);
}
return false;
}
public static boolean testRegistrationFailure() {
printIf("Testing registration failure.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testRegistrationFailureBadCookie());
ticker.test(testRegistrationFailureBadData());
ticker.test(testRegistrationFailureBadPassword());
ticker.logResultMessage();
return ticker.passed();
}
public static boolean testRegistrationSuccess() {
printIf("Testing successful registration.");
checkSetup();
NoUserTest user = new NoUserTest(CHANGE[0]);
NoRegister register = NoCore.register(user, PASSWORD.toCharArray());
try {
NoCore.confirm(register.cookie, PASSWORD.toCharArray(), copy(register.data));
} catch (Exception e) {
logger.severe("Error thrown on confirm, of type " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("Registration completed without errors. Attempting login to confirm.");
byte[] cookie;
try {
cookie = NoCore.login(register.data, PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown on login, of type " + e.getClass().getSimpleName());
printIf(e);
return false;
}
NoUserTest accessed;
try {
accessed = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown on getUser, of type " + e.getClass().getSimpleName());
printIf(e);
return false;
}
if (!accessed.getPublicExponent().equals(user.getPublicExponent())) {
logger.severe("Received user object from getUser has a different Public Exponent to the registered user.");
return false;
}
printIf("Successfully registered, logged in and retrieved user information.");
return true;
}
public static boolean testRegistration() {
printIf("Testing registration paths.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testRegistrationFailure());
ticker.test(testRegistrationSuccess());
ticker.logResultMessage();
return ticker.passed();
}
/*
* END Registration Methods
*
* BEGIN Login methods
*/
private static byte[] registerAndGetBytes() {
printIf("Registering...");
NoUserTest user = new NoUserTest(CHANGES.next());
printIf("Generated user, changeableString: " + user.getChangableString());
NoRegister register = NoCore.register(user, PASSWORD.toCharArray());
byte[] userFile = copy(register.data);
try {
NoCore.confirm(register.cookie, PASSWORD.toCharArray(), register.data);
} catch (Exception e) {
logger.severe("Error encountered while trying to register, of type " + e.getClass().getSimpleName());
printIf(e);
throw new NoTestNotReadyException("Failed to set up user file.");
}
return userFile;
}
public static boolean testLoginFailBadPassword(byte[] data) {
printIf("Testing login with bad password.");
checkSetup();
byte[] cookie = null;
try {
cookie = NoCore.login(copy(data), BAD_PASSWORD.toCharArray());
logger.severe("Cookie (" + Base64.encodeBase64(cookie) + ") returned, even with bad password.");
} catch (NoUserNotValidException e) {
printIf("NoUserNotValidException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName());
printIf(e);
} finally {
NoCore.shred(cookie);
}
return false;
}
public static boolean testLoginFailBadData(byte[] data) {
printIf("Testing login with bad data.");
checkSetup();
byte[] dataCopy = copy(data);
dataCopy = modifyByteArray(dataCopy);
byte[] cookie = null;
try {
cookie = NoCore.login(dataCopy, PASSWORD.toCharArray());
logger.severe("Cookie (" + Base64.encodeBase64(cookie) + ") returned, even with bad data.");
} catch (NoUserNotValidException e) {
printIf("NoUserNotValidException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName());
printIf(e);
} finally {
NoCore.shred(cookie);
}
return false;
}
public static boolean testLoginFailMultipleSessions(byte[] data) {
printIf("Testing that multiple sessions throw an error.");
checkSetup();
byte[] cookie;
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
printIf("Received cookie (" + new String(cookie) + ")");
} catch (Exception e) {
logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
byte[] secondCookie = null;
try {
secondCookie = NoCore.login(copy(data), PASSWORD.toCharArray());
logger.severe("Cookie (" + new String(secondCookie) + ") returned, even with concurrent session.");
} catch (NoUserAlreadyOnlineException e) {
printIf("NoUserAlreadyOnlineException thrown, passed.");
return true;
} catch (Exception e) {
logger.severe("Wrong error thrown, should have been NoUserAlreadyOnlineException, was " + e.getClass().getSimpleName());
printIf(e);
} finally {
NoCore.shred(secondCookie);
NoCore.shred(cookie);
}
return false;
}
public static boolean testLoginFail() {
return testLoginFail(registerAndGetBytes());
}
public static boolean testLoginFail(byte[] data) {
printIf("Testing login failure methods.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testLoginFailBadPassword(data));
ticker.test(testLoginFailBadData(data));
ticker.test(testLoginFailMultipleSessions(data));
ticker.logResultMessage();
return ticker.passed();
}
public static boolean testLoginSuccess(byte[] data) {
printIf("Testing successful login and user/state retrieval.");
checkSetup();
byte[] cookie = null;
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
try {
NoState state = NoCore.getSessionState(cookie);
if (state != NoState.IDLE) {
logger.severe("Returned state is not IDLE, instead '" + state.toString() + "'");
return false;
}
} catch (Exception e) {
logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
NoUserTest user = null;
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("User login successful, changableString: " + user.getChangableString());
NoCore.shred(cookie);
return true;
}
public static boolean testLogin() {
return testLogin(registerAndGetBytes());
}
public static boolean testLogin(byte[] data) {
printIf("Testing all login methods.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testLoginFail(data));
ticker.test(testLoginSuccess(data));
ticker.logResultMessage();
return ticker.passed();
}
/*
* END Login methods
* BEGIN Login-Logout methods
*/
public static boolean testLoginModifyLogout(byte[] data) {
printIf("Testing login, change changableString, save-logout.");
checkSetup();
byte[] cookie = null;
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("Cookie recieved.");
NoUserTest user;
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("User object received.");
String original = user.getChangableString();
user.setChangableString(CHANGES.next());
NoState stateModified;
try {
stateModified = NoCore.getSessionState(cookie);
} catch (Exception e) {
logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (stateModified != NoState.MODIFIED) {
logger.severe("State not MODIFIED.");
NoCore.shred(cookie);
return false;
}
printIf("State is MODIFIED.");
byte[] newData;
try {
newData = NoCore.requestSave(cookie, PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown, should have returned new byte array, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
printIf("New data stream received.");
NoState stateAwaiting;
try {
stateAwaiting = NoCore.getSessionState(cookie);
} catch (Exception e) {
logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (stateAwaiting != NoState.AWAITING_CONFIRMATION) {
logger.severe("State not AWAITING_CONFIRMATION.");
NoCore.shred(cookie);
return false;
}
printIf("State is AWAITING_CONFIRMATION.");
try {
NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(newData));
} catch (Exception e) {
logger.severe("Error thrown, should have confirmed, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
printIf("Confirm raised no errors.");
passoverData = copy(newData);
data = copy(newData);
try {
NoCore.getSessionState(cookie);
logger.severe("Get session state threw no errors after confirmation.");
return false;
} catch (NoSessionConfirmedException e) {
printIf("NoSessionConfirmed exception thrown.");
} catch (Exception e) {
logger.severe("Error thrown, should have been NoSessionConfirmedException, was " + e.getClass().getSimpleName());
printIf(e);
return false;
} finally {
user = null;
}
// Log in again to check changes
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("Cookie recieved for second login.");
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown on second login, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
printIf("User object received on second login.");
if (!user.getChangableString().equals(original)) {
printIf("Changable string has changed and saved.");
NoCore.shred(cookie);
return true;
} else {
logger.severe("Changable string has not changed.");
NoCore.shred(cookie);
return false;
}
}
public static boolean testActionInfluenceLifecycle(byte[] data) {
printIf("Testing an action-influence cycle between two users.");
checkSetup();
// First, log in, get the user Public Address and save the current name, log out
PublicKey address;
String currentString;
byte[] cookie = null;
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
NoUserTest user = (NoUserTest) NoCore.getUser(cookie);
address = user.getRSAPublicKey();
currentString = user.getChangableString();
} catch (Exception e) {
logger.severe("Error thrown on address-getting login, gotten address and string, was " + e.getClass().getSimpleName());
printIf(e);
return false;
} finally {
NoCore.shred(cookie);
}
printIf("Got public address.");
// Create a second user
byte[] secondUserData = registerAndGetBytes();
byte[] secondUserCookie;
try {
secondUserCookie = NoCore.login(copy(secondUserData), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown on second user login, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
NoUserTest user;
try {
user = (NoUserTest) NoCore.getUser(secondUserCookie);
} catch (Exception e) {
logger.severe("Error thrown on second user login, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
// Create outgoing action
NoActionTest action = new NoActionTest(address, CHANGES.next());
user.addAction(action);
printIf("Action added to second user.");
// Save-confirm user
try {
secondUserData = NoCore.requestSave(secondUserCookie, PASSWORD.toCharArray());
NoCore.confirm(secondUserCookie, PASSWORD.toCharArray(), copy(secondUserData));
} catch (Exception e) {
logger.severe("Error thrown on second user confirm, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(secondUserCookie);
return false;
}
printIf("Logged out of second user.");
// Log in as first user, should get changes
printIf("Logging into first user again.");
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown on first user, second login, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
NoState state;
try {
state = NoCore.getSessionState(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, second login, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (state != NoState.MODIFIED) {
logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString());
return false;
}
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, second login, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (user.getChangableString().equals(currentString)) {
logger.severe("User information has not changed (still " + user.getChangableString() + ").");
return false;
}
printIf("User string changed on first return login, (" + currentString + " to " + user.getChangableString() + ")!");
// Test that the influence resets accordingly on hotpull
NoCore.shred(cookie);
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown on first user, third login, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
try {
state = NoCore.getSessionState(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, third login, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (state != NoState.MODIFIED) {
logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString());
return false;
}
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, third login, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (user.getChangableString().equals(currentString)) {
logger.severe("User information has not changed (still " + user.getChangableString() + ").");
return false;
}
printIf("User string changed on second return login, (" + currentString + " to " + user.getChangableString() + ")!");
// Save-confirm
try {
data = NoCore.requestSave(cookie, PASSWORD.toCharArray());
NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(data));
passoverData = copy(data);
} catch (Exception e) {
logger.severe("Error thrown on first user, save-confirm, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
// Final login, check that data has changed AND state is IDLE
try {
cookie = NoCore.login(copy(data), PASSWORD.toCharArray());
} catch (Exception e) {
logger.severe("Error thrown on first user, final login, should have returned cookie, was " + e.getClass().getSimpleName());
printIf(e);
return false;
}
try {
state = NoCore.getSessionState(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, final login, should have returned state, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (state != NoState.IDLE) {
logger.severe("Was expecting state to be IDLE, instead was " + state.toString());
return false;
}
try {
user = (NoUserTest) NoCore.getUser(cookie);
} catch (Exception e) {
logger.severe("Error thrown on first user, final login, should have returned user, was " + e.getClass().getSimpleName());
printIf(e);
NoCore.shred(cookie);
return false;
}
if (user.getChangableString().equals(currentString)) {
logger.severe("User information has not changed (still " + user.getChangableString() + ").");
return false;
}
printIf("User string changed on final login (" + currentString + " to " + user.getChangableString() + "), while IDLE!");
return true;
}
public static boolean testLifecycle(byte[] data) {
printIf("Running life-cycle tests.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testLoginModifyLogout(data));
if (passoverData != null && passoverData.getClass().equals(byte[].class)) {
data = copy((byte[])passoverData);
passoverData = null;
}
ticker.test(testActionInfluenceLifecycle(data));
if (passoverData != null && passoverData.getClass().equals(byte[].class)) {
data = copy((byte[])passoverData);
passoverData = null;
}
ticker.logResultMessage();
return ticker.passed();
}
/*
* END Login-Logout methods
*/
public static boolean testAll() {
logger.info("Running all tests.");
checkSetup();
TestTicker ticker = new TestTicker();
ticker.test(testRegistration());
final byte[] data = registerAndGetBytes();
ticker.test(testLogin(data));
ticker.test(testLifecycle(data));
ticker.logResultMessage();
return ticker.passed();
}
public static void run() {
if (testAll()) {
logger.info("All tests passed.");
}
}
public static void main(String[] args) {
setSilence(false);
setPrintStackTraces(true);
if (!NoCore.isReady()) {
NoCore.setup();
}
run();
}
} |
package org.voovan.test.tools.cache;
import junit.framework.TestCase;
import org.voovan.tools.collection.RedisZSet;
import java.util.HashMap;
import java.util.Map;
public class RedisZSetUnit extends TestCase {
private RedisZSet redisSortedSet;
@Override
protected void setUp() throws Exception {
super.setUp();
redisSortedSet = new RedisZSet("127.0.0.1", 6379, 2000, 100, "ZSet", null);
}
public void testAdd(){
Object value = redisSortedSet.add(11d, "heffff");
System.out.println(value);
assertEquals(1, redisSortedSet.size());
}
public void testAddAll(){
Map<String, Double> testMap = new HashMap<String, Double>();
testMap.put("aaa", new Double(12));
testMap.put("bbb", new Double(13));
testMap.put("ccc", new Double(14));
Object value = redisSortedSet.addAll(testMap);
System.out.println(value);
assertEquals(4, redisSortedSet.size());
}
public void testIncrease(){
Object value = redisSortedSet.increase("heffff", 11d);
System.out.println(value);
assertEquals(22D, value);
}
public void testScoreRanageCount(){
Object value = redisSortedSet.scoreRangeCount(12, 14);
System.out.println(value);
assertEquals(4, redisSortedSet.size());
}
public void testValueRanageCount(){
Object value = redisSortedSet.valueRangeCount("[a", "[c");
System.out.println(value);
assertEquals(1, redisSortedSet.size());
}
public void testRangeByIndex(){
Object value = redisSortedSet.getRangeByIndex(0,1);
System.out.println(value);
value = redisSortedSet.getRevRangeByIndex(0,1);
System.out.println(value);
}
public void testRangeByValue(){
Object value = redisSortedSet.getRrangeByValue("[a", "+");
System.out.println(value);
value = redisSortedSet.getRevRangeByValue("+", "[a");
System.out.println(value);
value = redisSortedSet.getRangeByValue("[a", "+", 2, 1);
System.out.println(value);
value = redisSortedSet.getRevRangeByValue("+", "[a", 2, 1);
System.out.println(value);
}
public void testRangeByScore(){
Object value = redisSortedSet.getRangeByScore(12, 14);
System.out.println(value);
value = redisSortedSet.getRevRangeByScore(14, 12);
System.out.println(value);
value = redisSortedSet.getRangeByScore(12, 14, 1, 1);
System.out.println(value);
value = redisSortedSet.getRevRangeByScore(14, 12, 1, 1);
System.out.println(value);
}
public void testIndexOf(){
Object value = redisSortedSet.indexOf("bbb");
System.out.println(value);
value = redisSortedSet.revIndexOf("bbb");
System.out.println(value);
}
public void testRemove(){
Object value = redisSortedSet.remove("bbb");
System.out.println(value);
value = redisSortedSet.removeRangeByValue("[aaa", "[ccc");
System.out.println(value);
value = redisSortedSet.removeRangeByIndex(1,1);
System.out.println(value);
value = redisSortedSet.removeRangeByScore(13, 15);
System.out.println(value);
}
public void testScore(){
Object value = redisSortedSet.getScore("heffff");
System.out.println(value);
}
public void testByScoreAndReplace(){
// redisSortedSet.add(111, "bbb");
// redisSortedSet.add(111, "aaa");
Object value = redisSortedSet.getRevByScore(111);
System.out.println(value);
redisSortedSet.replace(111, value, "aaa" + System.currentTimeMillis());
value = redisSortedSet.getRevByScore(111);
System.out.println(value);
}
public void testScan(){
Object value = redisSortedSet.scan("99", "*", 1);
System.out.println(value);
}
} |
package StevenDimDoors.mod_pocketDim;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MathHelper;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import StevenDimDoors.mod_pocketDim.util.WeightedContainer;
/*
* Registers a category of loot chests for Dimensional Doors in Forge.
*/
public class DDLoot {
private static final String[] SPECIAL_SKULL_OWNERS = new String[] { "stevenrs11", "kamikazekiwi3", "Jaitsu", "XCompWiz", "skyboy026", "Wylker" };
private static final double MIN_ITEM_DAMAGE = 0.3;
private static final double MAX_ITEM_DAMAGE = 0.9;
private static final int ITEM_ENCHANTMENT_CHANCE = 50;
private static final int MAX_ITEM_ENCHANTMENT_CHANCE = 100;
private static final int SPECIAL_SKULL_CHANCE = 20;
private static final int MAX_SPECIAL_SKULL_CHANCE = 100;
public static final String DIMENSIONAL_DUNGEON_CHEST = "dimensionalDungeonChest";
public static ChestGenHooks DungeonChestInfo = null;
private static final int CHEST_SIZE = 5;
private DDLoot() { }
public static void registerInfo(DDProperties properties)
{
// Register the dimensional dungeon chest with ChestGenHooks. This isn't necessary, but allows
// other mods to add their own loot to our chests if they know our loot category, without having
// to interface with our code.
DungeonChestInfo = ChestGenHooks.getInfo(DIMENSIONAL_DUNGEON_CHEST);
DungeonChestInfo.setMin(CHEST_SIZE);
DungeonChestInfo.setMax(CHEST_SIZE);
ArrayList<WeightedRandomChestContent> items = new ArrayList<WeightedRandomChestContent>();
addContent(true, items, Item.ingotIron.itemID, 160, 1, 3);
addContent(true, items, Item.coal.itemID, 120, 1, 3);
addContent(true, items, Item.netherQuartz.itemID, 120, 1, 3);
addContent(true, items, Item.enchantedBook.itemID, 100);
addContent(true, items, Item.ingotGold.itemID, 80, 1, 3);
addContent(true, items, Item.diamond.itemID, 40, 1, 2);
addContent(true, items, Item.emerald.itemID, 20, 1, 2);
addContent(true, items, Item.appleGold.itemID, 10);
addContent(properties.FabricOfRealityLootEnabled, items, mod_pocketDim.blockDimWall.blockID, 20, 16, 64);
addContent(properties.WorldThreadLootEnabled, items, mod_pocketDim.itemWorldThread.itemID, 80, 2, 8);
// Add all the items to our dungeon chest
addItemsToContainer(DungeonChestInfo, items);
}
private static void addContent(boolean include, ArrayList<WeightedRandomChestContent> items,
int itemID, int weight)
{
if (include)
items.add(new WeightedRandomChestContent(itemID, 0, 1, 1, weight));
}
private static void addContent(boolean include, ArrayList<WeightedRandomChestContent> items,
int itemID, int weight, int minAmount, int maxAmount)
{
if (include)
items.add(new WeightedRandomChestContent(itemID, 0, minAmount, maxAmount, weight));
}
private static void addItemsToContainer(ChestGenHooks container, ArrayList<WeightedRandomChestContent> items)
{
for (WeightedRandomChestContent item : items)
{
container.addItem(item);
}
}
private static void fillChest(ArrayList<ItemStack> stacks, IInventory inventory, Random random)
{
// This custom chest-filling function avoids overwriting item stacks
// The prime number below is used for choosing chest slots in a seemingly-random pattern. Its value
// was selected specifically to achieve a spread-out distribution for chests with up to 104 slots.
// Choosing a prime number ensures that our increments are relatively-prime to the chest size, which
// means we'll cover all the slots before repeating any. This is mathematically guaranteed.
final int primeOffset = 239333;
int size = inventory.getSizeInventory();
for (ItemStack item : stacks)
{
int limit = size;
int index = random.nextInt(size);
while (limit > 0 && inventory.getStackInSlot(index) != null)
{
limit
index = (index + primeOffset) % size;
}
inventory.setInventorySlotContents(index, item);
}
}
public static void generateChestContents(ChestGenHooks chestInfo, IInventory inventory, Random random)
{
// This is a custom version of net.minecraft.util.WeightedRandomChestContent.generateChestContents()
// It's designed to avoid the following bugs in MC 1.5:
// 1. If multiple enchanted books appear, then they will have the same enchantment
// 2. The randomized filling algorithm will sometimes overwrite item stacks with other stacks
int count = chestInfo.getCount(random);
WeightedRandomChestContent[] content = chestInfo.getItems(random);
ArrayList<ItemStack> allStacks = new ArrayList<ItemStack>();
for (int k = 0; k < count; k++)
{
WeightedRandomChestContent selection = (WeightedRandomChestContent)WeightedRandom.getRandomItem(random, content);
// Call getChestGenBase() to make sure we generate a different enchantment for books.
// Don't just use a condition to check if the item is an instance of ItemEnchantedBook because
// we don't know if other mods might add items that also need to be regenerated.
selection = selection.theItemId.getItem().getChestGenBase(chestInfo, random, selection);
ItemStack[] stacks = ChestGenHooks.generateStacks(random, selection.theItemId, selection.theMinimumChanceToGenerateItem, selection.theMaximumChanceToGenerateItem);
for (int h = 0; h < stacks.length; h++)
{
allStacks.add(stacks[h]);
}
}
fillChest(allStacks, inventory, random);
}
public static void fillGraveChest(IInventory inventory, Random random, DDProperties properties)
{
// This function fills "grave chests", which are chests for dungeons that
// look like a player died in the area and his remains were gathered in
// a chest. Doing this properly requires fine control of loot generation,
// so we use our own function rather than Minecraft's functions.
int k;
int count;
ArrayList<ItemStack> stacks = new ArrayList<ItemStack>();
ArrayList<WeightedContainer<Item>> selection = new ArrayList<WeightedContainer<Item>>();
// Insert bones and rotten flesh
// Make stacks of single items to spread them out
count = MathHelper.getRandomIntegerInRange(random, 2, 5);
for (k = 0; k < count; k++)
{
stacks.add( new ItemStack(Item.bone, 1) );
}
count = MathHelper.getRandomIntegerInRange(random, 2, 4);
for (k = 0; k < count; k++)
{
stacks.add( new ItemStack(Item.rottenFlesh, 1) );
}
// Insert tools
// 30% chance of adding a pickaxe
if (random.nextInt(100) < 30)
{
addModifiedTool(Item.pickaxeIron, stacks, random);
}
// 30% chance of adding a bow and some arrows
if (random.nextInt(100) < 30)
{
addModifiedBow(stacks, random);
stacks.add( new ItemStack(Item.arrow, MathHelper.getRandomIntegerInRange(random, 8, 32)) );
}
// 10% chance of adding a Rift Blade (no enchants)
if (properties.RiftBladeLootEnabled && random.nextInt(100) < 10)
{
stacks.add( new ItemStack(mod_pocketDim.itemRiftBlade, 1) );
}
else
{
// 20% of adding an iron sword, 10% of adding a stone sword
addModifiedSword( getRandomItem(Item.swordIron, Item.swordStone, null, 20, 10, random) , stacks, random);
}
// Insert equipment
// For each piece, 25% of an iron piece, 10% of a chainmail piece
addModifiedEquipment( getRandomItem(Item.helmetIron, Item.helmetChain, null, 25, 10, random) , stacks, random);
addModifiedEquipment( getRandomItem(Item.plateIron, Item.plateChain, null, 25, 10, random) , stacks, random);
addModifiedEquipment( getRandomItem(Item.legsIron, Item.legsChain, null, 25, 10, random) , stacks, random);
addModifiedEquipment( getRandomItem(Item.bootsIron, Item.bootsChain, null, 25, 10, random) , stacks, random);
// Insert other random stuff
// 40% chance for a name tag, 35% chance for a glass bottle
// 30% chance for an ender pearl, 5% chance for record 11
// 30% chance for a ghast tear
addItemWithChance(stacks, random, 40, Item.nameTag, 1);
addItemWithChance(stacks, random, 35, Item.glassBottle, 1);
addItemWithChance(stacks, random, 30, Item.enderPearl, 1);
addItemWithChance(stacks, random, 30, Item.ghastTear, 1);
addItemWithChance(stacks, random, 5, Item.record11, 1);
// Finally, there is a 5% chance of adding a player head
if (random.nextInt(100) < 5)
{
addGraveSkull(stacks, random);
}
fillChest(stacks, inventory, random);
}
private static void addModifiedEquipment(Item item, ArrayList<ItemStack> stacks, Random random)
{
if (item == null)
return;
stacks.add( getModifiedItem(item, random, new Enchantment[] { Enchantment.blastProtection, Enchantment.fireProtection, Enchantment.protection, Enchantment.projectileProtection }) );
}
private static void addModifiedSword(Item item, ArrayList<ItemStack> stacks, Random random)
{
if (item == null)
return;
stacks.add( getModifiedItem(item, random, new Enchantment[] { Enchantment.fireAspect, Enchantment.knockback, Enchantment.sharpness }) );
}
private static void addModifiedTool(Item tool, ArrayList<ItemStack> stacks, Random random)
{
if (tool == null)
return;
stacks.add( getModifiedItem(tool, random, new Enchantment[] { Enchantment.efficiency, Enchantment.unbreaking }) );
}
private static void addModifiedBow(ArrayList<ItemStack> stacks, Random random)
{
stacks.add( getModifiedItem(Item.bow, random, new Enchantment[] { Enchantment.flame, Enchantment.power, Enchantment.punch }) );
}
private static ItemStack getModifiedItem(Item item, Random random, Enchantment[] enchantments)
{
ItemStack result = applyRandomDamage(item, random);
if (enchantments.length > 0 && random.nextInt(MAX_ITEM_ENCHANTMENT_CHANCE) < ITEM_ENCHANTMENT_CHANCE)
{
result.addEnchantment(enchantments[ random.nextInt(enchantments.length) ], 1);
}
return result;
}
private static Item getRandomItem(Item a, Item b, Item c, int weightA, int weightB, Random random)
{
int roll = random.nextInt(100);
if (roll < weightA)
return a;
if (roll < weightA + weightB)
return b;
return c;
}
private static void addItemWithChance(ArrayList<ItemStack> stacks, Random random, int chance, Item item, int count)
{
if (random.nextInt(100) < chance)
{
stacks.add(new ItemStack(item, count));
}
}
private static ItemStack applyRandomDamage(Item item, Random random)
{
int damage = (int) (item.getMaxDamage() * MathHelper.getRandomDoubleInRange(random, MIN_ITEM_DAMAGE, MAX_ITEM_DAMAGE));
return new ItemStack(item, 1, damage);
}
private static void addGraveSkull(ArrayList<ItemStack> stacks, Random random)
{
final int PLAYER_SKULL_METADATA = 3;
DeathTracker deathTracker = mod_pocketDim.deathTracker;
String skullOwner;
if (deathTracker.isEmpty() || (random.nextInt(MAX_SPECIAL_SKULL_CHANCE) < SPECIAL_SKULL_CHANCE))
{
skullOwner = SPECIAL_SKULL_OWNERS[ random.nextInt(SPECIAL_SKULL_OWNERS.length) ];
}
else
{
skullOwner = deathTracker.getRandomUsername(random);
}
ItemStack skull = new ItemStack(Item.skull, 1, PLAYER_SKULL_METADATA);
skull.stackTagCompound = new NBTTagCompound();
skull.stackTagCompound.setString("SkullOwner", skullOwner);
stacks.add(skull);
}
} |
package com.example.moodly;
import android.test.ActivityInstrumentationTestCase2;
import java.util.ArrayList;
public class MoodTest extends ActivityInstrumentationTestCase2{
public MoodTest() {
super(MoodHolder.class);
}
public void testAddMood(){
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
String owner = "Harambe";
String trigger = "Banana";
String reasonText = "Ate a banana";
mood.setOwner(owner);
mood.setEmotion(emotion);
mood.setTrigger(trigger);
mood.setReasonText(reasonText);
moodList.add(mood);
assertTrue(moodList.contains(mood));
}
public void testChooseEmotionalState() {
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
mood.setEmotion(emotion);
moodList.add(mood);
assertEquals(moodList.get(0).getEmotion(),emotion);
}
public void testAddTextReason() {
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String textReason = "Happy";
mood.setReasonText(textReason);
moodList.add(mood);
assertEquals(moodList.get(0).getReasonText(),textReason);
}
public void testAddLocation() {
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String location = "Cincinnatti";
mood.setLocation(location);
moodList.add(mood);
assertEquals(moodList.get(0).getLocation(),location);
}
public void testViewMoodDetails(){
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
String owner = "Harambe";
String trigger = "Banana";
String reasonText = "Ate a banana";
mood.setOwner(owner);
mood.setEmotion(emotion);
mood.setTrigger(trigger);
mood.setReasonText(reasonText);
moodList.add(mood);
assertEquals(emotion,moodList.get(0).getEmotion());
assertEquals(trigger,moodList.get(0).getTrigger());
assertEquals(reasonText,moodList.get(0).getReasonText());
}
public void testEditMood() {
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
String owner = "Harambe";
String trigger = "Banana";
String reasonText = "Ate a banana";
mood.setOwner(owner);
mood.setEmotion(emotion);
mood.setTrigger(trigger);
mood.setReasonText(reasonText);
moodList.add(mood);
String newTrigger = "a kid";
moodList.get(0).setTrigger(newTrigger);
assertEquals(emotion,moodList.get(0).getEmotion());
assertEquals(newTrigger,moodList.get(0).getTrigger());
assertEquals(reasonText,moodList.get(0).getReasonText());
}
public void testDeleteMood(){
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
String owner = "Harambe";
String trigger = "Banana";
String reasonText = "Ate a banana";
mood.setOwner(owner);
mood.setEmotion(emotion);
mood.setTrigger(trigger);
mood.setReasonText(reasonText);
moodList.add(mood);
moodList.remove(mood);
assertFalse(moodList.contains(mood));
}
public void testRegister() {}
public void testFilter() {
ArrayList<Mood> moodList = new ArrayList<>();
Mood mood = new Mood();
String emotion = "Happy";
mood.setEmotion(emotion);
moodList.add(mood);
Mood anotherMood = new Mood();
String newEmotion = "Sad";
anotherMood.setEmotion(newEmotion);
moodList.add(anotherMood);
//Add stuff here
}
} |
/**
* Isaac Wismer
*/
/**
* TODO: Fix Help Menu Optimize
*
*/
package nutrientcalculator;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author isaac
*/
public class GUI extends javax.swing.JFrame {
/**
* Creates new form GUI
*/
public GUI() {
initComponents();
//make windows appear in the middle of the screen
setLocationRelativeTo(null);
frameRecepieEntry.setLocationRelativeTo(null);
frameAbout.setLocationRelativeTo(null);
frameDirections.setLocationRelativeTo(null);
frameHelp.setLocationRelativeTo(null);
frameTitle.setLocationRelativeTo(null);
lblLoad.setVisible(false);
framePrint.setLocationRelativeTo(null);
}
//static variables
static double portionAmount;
static boolean update;
static Recipe recipe = new Recipe();
static DefaultComboBoxModel model = new DefaultComboBoxModel();
ArrayList<Ingredient> ingList = new ArrayList<>(0);
//non static variables
Ingredient selected;
int numIngredients, editSelection = 0;
boolean edit = false, dontShow = false;
ArrayList<Object[]> matches = new ArrayList<>(0);
ArrayList<Ingredient> matchesIngr;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
frameRecepieEntry = new javax.swing.JFrame();
jScrollPane2 = new javax.swing.JScrollPane();
listResults = new javax.swing.JList();
tfName = new javax.swing.JTextField();
cmbFraction = new javax.swing.JComboBox();
cmbUnit = new javax.swing.JComboBox();
btnOK1 = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
btnSearch2 = new javax.swing.JButton();
btnUseSelected = new javax.swing.JButton();
btnHelp1 = new javax.swing.JButton();
spQuantity = new javax.swing.JSpinner();
frameAbout = new javax.swing.JDialog();
btnCloseAbout = new javax.swing.JButton();
jScrollPane4 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
frameDirections = new javax.swing.JFrame();
jScrollPane1 = new javax.swing.JScrollPane();
taDirections = new javax.swing.JTextArea();
btnOK3 = new javax.swing.JButton();
frameHelp = new javax.swing.JFrame();
cmbHelp = new javax.swing.JComboBox();
jScrollPane5 = new javax.swing.JScrollPane();
taHelp = new javax.swing.JTextArea();
frameTitle = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
tfTitle = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
taInstructions = new javax.swing.JTextArea();
btnOK4 = new javax.swing.JButton();
btnCancel2 = new javax.swing.JButton();
fcSave = new javax.swing.JFileChooser();
jPopupMenu1 = new javax.swing.JPopupMenu();
fcPrinter = new javax.swing.JFileChooser();
framePrint = new javax.swing.JFrame();
scrollPane = new javax.swing.JScrollPane();
output = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
menuSave = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
MenuPrint = new javax.swing.JMenu();
menuHelp = new javax.swing.JMenu();
menuAbout = new javax.swing.JMenu();
btnRemove = new javax.swing.JButton();
btnCalculate = new javax.swing.JButton();
btnAdd = new javax.swing.JButton();
btnHelp2 = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnTitle = new javax.swing.JButton();
jLayeredPane1 = new javax.swing.JLayeredPane();
lblLoad = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
listRecipe = new javax.swing.JList();
jMenuBar2 = new javax.swing.JMenuBar();
menuSave1 = new javax.swing.JMenu();
menuOpen1 = new javax.swing.JMenu();
menuHelp1 = new javax.swing.JMenu();
menuAbout1 = new javax.swing.JMenu();
frameRecepieEntry.setTitle("Enter Ingredient");
frameRecepieEntry.setMinimumSize(new java.awt.Dimension(1000, 510));
listResults.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listResults.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
listResultsValueChanged(evt);
}
});
jScrollPane2.setViewportView(listResults);
tfName.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
tfNameKeyPressed(evt);
}
});
cmbFraction.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1/4 Teaspoon", "1/2 Teaspoon", "1 Teaspoon", "1 Tablespoon", "1/4 Cup", "1/3 Cup", "1/2 Cup", "1 Cup" }));
cmbFraction.setEnabled(false);
cmbUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Metric Cooking Measures", "mL", "g" }));
cmbUnit.setEnabled(false);
cmbUnit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbUnitActionPerformed(evt);
}
});
btnOK1.setText("OK");
btnOK1.setEnabled(false);
btnOK1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOK1ActionPerformed(evt);
}
});
btnBack.setText("Back");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnSearch2.setText("Search");
btnSearch2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSearch2ActionPerformed(evt);
}
});
btnUseSelected.setText("Use Selected Food");
btnUseSelected.setEnabled(false);
btnUseSelected.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUseSelectedActionPerformed(evt);
}
});
btnHelp1.setText("Help");
btnHelp1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHelp1ActionPerformed(evt);
}
});
spQuantity.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
javax.swing.GroupLayout frameRecepieEntryLayout = new javax.swing.GroupLayout(frameRecepieEntry.getContentPane());
frameRecepieEntry.getContentPane().setLayout(frameRecepieEntryLayout);
frameRecepieEntryLayout.setHorizontalGroup(
frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameRecepieEntryLayout.createSequentialGroup()
.addContainerGap()
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameRecepieEntryLayout.createSequentialGroup()
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameRecepieEntryLayout.createSequentialGroup()
.addComponent(btnSearch2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnUseSelected, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(frameRecepieEntryLayout.createSequentialGroup()
.addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(6, 6, 6)
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameRecepieEntryLayout.createSequentialGroup()
.addComponent(btnHelp1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnOK1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(frameRecepieEntryLayout.createSequentialGroup()
.addComponent(cmbFraction, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbUnit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap())
);
frameRecepieEntryLayout.setVerticalGroup(
frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameRecepieEntryLayout.createSequentialGroup()
.addContainerGap()
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spQuantity))
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbFraction)
.addComponent(cmbUnit)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(frameRecepieEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnOK1, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(btnBack, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(btnSearch2, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(btnUseSelected, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(btnHelp1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE)
.addContainerGap())
);
frameAbout.setTitle("About");
frameAbout.setMinimumSize(new java.awt.Dimension(404, 260));
frameAbout.setName("About"); // NOI18N
frameAbout.setResizable(false);
btnCloseAbout.setText("Close");
btnCloseAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseAboutActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(240, 240, 240));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Lucida Console", 0, 12)); // NOI18N
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jTextArea1.setText("Recipe Nutrient Analysis\nv1.2.1\nJuly 12 2015\nBy Isaac Wismer\n\nThis program uses the Canadian Nutrient File 2010\nFor more information visit:\nhttp:
jTextArea1.setWrapStyleWord(true);
jTextArea1.setAutoscrolls(false);
jTextArea1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollPane4.setViewportView(jTextArea1);
javax.swing.GroupLayout frameAboutLayout = new javax.swing.GroupLayout(frameAbout.getContentPane());
frameAbout.getContentPane().setLayout(frameAboutLayout);
frameAboutLayout.setHorizontalGroup(
frameAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameAboutLayout.createSequentialGroup()
.addGroup(frameAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameAboutLayout.createSequentialGroup()
.addGap(331, 331, 331)
.addComponent(btnCloseAbout))
.addGroup(frameAboutLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
frameAboutLayout.setVerticalGroup(
frameAboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameAboutLayout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCloseAbout)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
frameDirections.setTitle("Directions");
frameDirections.setMinimumSize(new java.awt.Dimension(600, 475));
frameDirections.setResizable(false);
taDirections.setColumns(20);
taDirections.setRows(5);
jScrollPane1.setViewportView(taDirections);
btnOK3.setText("OK");
btnOK3.setToolTipText("");
btnOK3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOK3ActionPerformed(evt);
}
});
javax.swing.GroupLayout frameDirectionsLayout = new javax.swing.GroupLayout(frameDirections.getContentPane());
frameDirections.getContentPane().setLayout(frameDirectionsLayout);
frameDirectionsLayout.setHorizontalGroup(
frameDirectionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameDirectionsLayout.createSequentialGroup()
.addContainerGap()
.addGroup(frameDirectionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameDirectionsLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnOK3)))
.addContainerGap())
);
frameDirectionsLayout.setVerticalGroup(
frameDirectionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameDirectionsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnOK3)
.addContainerGap(42, Short.MAX_VALUE))
);
frameHelp.setMinimumSize(new java.awt.Dimension(800, 500));
frameHelp.setResizable(false);
cmbHelp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Output Window", "Recipe Ingredient List", "Ingredient List", "Save/Open" }));
cmbHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbHelpActionPerformed(evt);
}
});
taHelp.setEditable(false);
taHelp.setColumns(20);
taHelp.setRows(5);
jScrollPane5.setViewportView(taHelp);
javax.swing.GroupLayout frameHelpLayout = new javax.swing.GroupLayout(frameHelp.getContentPane());
frameHelp.getContentPane().setLayout(frameHelpLayout);
frameHelpLayout.setHorizontalGroup(
frameHelpLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameHelpLayout.createSequentialGroup()
.addContainerGap()
.addGroup(frameHelpLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 771, Short.MAX_VALUE)
.addGroup(frameHelpLayout.createSequentialGroup()
.addComponent(cmbHelp, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
frameHelpLayout.setVerticalGroup(
frameHelpLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameHelpLayout.createSequentialGroup()
.addContainerGap()
.addComponent(cmbHelp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
.addContainerGap())
);
frameTitle.setMinimumSize(new java.awt.Dimension(623, 502));
jLabel1.setText("Title");
jLabel3.setText("Insructions/Description");
taInstructions.setColumns(20);
taInstructions.setRows(5);
jScrollPane6.setViewportView(taInstructions);
btnOK4.setText("OK");
btnOK4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOK4ActionPerformed(evt);
}
});
btnCancel2.setText("Cancel");
btnCancel2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancel2ActionPerformed(evt);
}
});
javax.swing.GroupLayout frameTitleLayout = new javax.swing.GroupLayout(frameTitle.getContentPane());
frameTitle.getContentPane().setLayout(frameTitleLayout);
frameTitleLayout.setHorizontalGroup(
frameTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameTitleLayout.createSequentialGroup()
.addContainerGap()
.addGroup(frameTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
.addComponent(tfTitle)
.addGroup(frameTitleLayout.createSequentialGroup()
.addGroup(frameTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameTitleLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnCancel2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnOK4, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
frameTitleLayout.setVerticalGroup(
frameTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(frameTitleLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(frameTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnOK4)
.addComponent(btnCancel2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
fcSave.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
fcSave.setDialogTitle("");
fcSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fcSaveActionPerformed(evt);
}
});
framePrint.setTitle("Output");
framePrint.setMinimumSize(new java.awt.Dimension(926, 673));
output.setColumns(20);
output.setFont(new java.awt.Font("Monospaced", 0, 15)); // NOI18N
output.setRows(5);
scrollPane.setViewportView(output);
menuSave.setText("Save");
jMenuItem1.setText("Save Recipe");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
menuSave.add(jMenuItem1);
jMenuItem2.setText("Save Output");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
menuSave.add(jMenuItem2);
jMenuBar1.add(menuSave);
MenuPrint.setText("Print");
MenuPrint.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
MenuPrintMouseClicked(evt);
}
});
jMenuBar1.add(MenuPrint);
menuHelp.setText("Help");
menuHelp.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuHelpMouseClicked(evt);
}
});
jMenuBar1.add(menuHelp);
menuAbout.setText("About");
menuAbout.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuAboutMouseClicked(evt);
}
});
jMenuBar1.add(menuAbout);
framePrint.setJMenuBar(jMenuBar1);
javax.swing.GroupLayout framePrintLayout = new javax.swing.GroupLayout(framePrint.getContentPane());
framePrint.getContentPane().setLayout(framePrintLayout);
framePrintLayout.setHorizontalGroup(
framePrintLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(framePrintLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE)
.addContainerGap())
);
framePrintLayout.setVerticalGroup(
framePrintLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, framePrintLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Canadian Nutrient File Search");
setIconImages(null);
btnRemove.setText("Remove Selected");
btnRemove.setEnabled(false);
btnRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveActionPerformed(evt);
}
});
btnCalculate.setText("Get Nutrition Facts");
btnCalculate.setEnabled(false);
btnCalculate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCalculateActionPerformed(evt);
}
});
btnAdd.setText("Add Food Item");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnHelp2.setText("Help");
btnHelp2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHelp2ActionPerformed(evt);
}
});
btnEdit.setText("Edit Food Item");
btnEdit.setEnabled(false);
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
btnTitle.setText("Add/Edit Title/Instructions");
btnTitle.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTitleActionPerformed(evt);
}
});
lblLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nutrientcalculator/data/loader.gif"))); // NOI18N
lblLoad.setText("Calculating Nutrients...");
lblLoad.setToolTipText("");
lblLoad.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lblLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
listRecipe.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
listRecipeValueChanged(evt);
}
});
jScrollPane3.setViewportView(listRecipe);
javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
jLayeredPane1.setLayout(jLayeredPane1Layout);
jLayeredPane1Layout.setHorizontalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3)
.addContainerGap())
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(384, 384, 384)
.addComponent(lblLoad)
.addContainerGap(384, Short.MAX_VALUE)))
);
jLayeredPane1Layout.setVerticalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(174, 174, 174)
.addComponent(lblLoad)
.addContainerGap(175, Short.MAX_VALUE)))
);
jLayeredPane1.setLayer(lblLoad, javax.swing.JLayeredPane.POPUP_LAYER);
jLayeredPane1.setLayer(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);
menuSave1.setText("Save");
menuSave1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuSave1MouseClicked(evt);
}
});
jMenuBar2.add(menuSave1);
menuOpen1.setText("Open");
menuOpen1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuOpen1MouseClicked(evt);
}
});
jMenuBar2.add(menuOpen1);
menuHelp1.setText("Help");
menuHelp1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuHelp1MouseClicked(evt);
}
});
jMenuBar2.add(menuHelp1);
menuAbout1.setText("About");
menuAbout1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuAbout1MouseClicked(evt);
}
});
jMenuBar2.add(menuAbout1);
setJMenuBar(jMenuBar2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHelp2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnEdit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnAdd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCalculate))
.addComponent(jLayeredPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdd)
.addComponent(btnHelp2)
.addComponent(btnRemove)
.addComponent(btnCalculate)
.addComponent(btnEdit)
.addComponent(btnTitle)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSearch2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearch2ActionPerformed
ingredientLookUp();
}//GEN-LAST:event_btnSearch2ActionPerformed
private void btnUseSelectedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUseSelectedActionPerformed
useSelected();
}//GEN-LAST:event_btnUseSelectedActionPerformed
private void cmbUnitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbUnitActionPerformed
//change what is showing depending on what unit is selected
if (cmbUnit.getSelectedItem() == "Metric Cooking Measures") {
cmbFraction.setModel(model);
cmbFraction.setEnabled(true);
} else if (cmbUnit.getSelectedItem() == "Other") {
DefaultComboBoxModel model2 = new DefaultComboBoxModel();
if (edit) {
for (int i = 0; i < selected.getMeasures().size(); i++) {
model2.addElement(selected.getSingleMeasureIndex(i).getName());
}
} else {
model2 = Database.measures(selected.getID());
}
cmbFraction.setModel(model2);
cmbFraction.setEnabled(true);
} else {
cmbFraction.setEnabled(false);
}
}//GEN-LAST:event_cmbUnitActionPerformed
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//reset the add ingredient window
DefaultListModel empty = new DefaultListModel();
tfName.setText(null);
listResults.setModel(empty);
cmbUnit.setSelectedIndex(0);
cmbFraction.setEnabled(false);
cmbUnit.setEnabled(false);
spQuantity.setEnabled(false);
frameRecepieEntry.setVisible(true);
btnOK1.setEnabled(false);
edit = false;
}//GEN-LAST:event_btnAddActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
frameRecepieEntry.setVisible(false);
}//GEN-LAST:event_btnBackActionPerformed
private void tfNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfNameKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
ingredientLookUp();
}
}//GEN-LAST:event_tfNameKeyPressed
private void btnOK1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOK1ActionPerformed
int temp;
String ingredient = "";
if (cmbUnit.getSelectedItem() == "Metric Cooking Measures") {
//add the correct fraction to the begining of the ingredient name
if ((int) spQuantity.getValue() > 1) {
temp = Integer.parseInt(cmbFraction.getSelectedItem().toString().substring(0, 1)) * (int) spQuantity.getValue();
if (cmbFraction.getSelectedIndex() != 2 && cmbFraction.getSelectedIndex() != 3 && cmbFraction.getSelectedIndex() != 7) {//not full measures eg 1 cup
if (temp / Integer.parseInt(cmbFraction.getSelectedItem().toString().substring(2, 3)) >= 1) {
if (temp % Double.parseDouble(cmbFraction.getSelectedItem().toString().substring(2, 3)) == 0) {
ingredient = temp / Integer.parseInt(cmbFraction.getSelectedItem().toString().substring(2, 3)) + cmbFraction.getSelectedItem().toString().substring(3);
if (temp / Integer.parseInt(cmbFraction.getSelectedItem().toString().substring(2, 3)) > 1) {
ingredient += "s";
}
ingredient += " " + tfName.getText();
} else {
ingredient += (int) Math.floor(temp / Double.parseDouble(cmbFraction.getSelectedItem().toString().substring(2, 3)));
temp -= Double.parseDouble(cmbFraction.getSelectedItem().toString().substring(2, 3));
double temp2 = (double) temp / Double.parseDouble(cmbFraction.getSelectedItem().toString().substring(2, 3));
temp2 -= Math.floor(temp2);//leftovers
if (temp2 == 0.25) {
ingredient += " 1/4";
} else if (temp2 == 0.5) {
ingredient += " 1/2";
} else if (temp2 == 0.75) {
ingredient += " 3/4";
} else if ((temp2 + "").substring(2, 3).equals("3")) {
ingredient += " 1/3";
} else {
ingredient += " 2/3";
}
ingredient += cmbFraction.getSelectedItem().toString().substring(3) + "s" + " " + tfName.getText();
}
} else {
ingredient = temp + cmbFraction.getSelectedItem().toString().substring(1) + "s" + " " + tfName.getText();
}
} else {
ingredient = temp + cmbFraction.getSelectedItem().toString().substring(1) + "s" + " " + tfName.getText();
}
} else {
ingredient = cmbFraction.getSelectedItem() + " " + tfName.getText();
}
} else if (cmbUnit.getSelectedItem() == "g") {
if ((int) spQuantity.getValue() < 1000) {
ingredient = spQuantity.getValue() + "g " + tfName.getText();
} else {
ingredient = (Double.parseDouble(spQuantity.getValue().toString()) / 1000.0) + "Kg " + tfName.getText();
}
} else if (cmbUnit.getSelectedItem() == "Other") {
String str = "";
int i;
for (i = 0; i < cmbFraction.getSelectedItem().toString().length(); i++) {//get the numbers from the front of the other name
if (cmbFraction.getSelectedItem().toString().charAt(i) >= 48
&& cmbFraction.getSelectedItem().toString().charAt(i) <= 57) {
str += cmbFraction.getSelectedItem().toString().charAt(i);
} else {
break;
}
}
int num = Integer.parseInt(str);
int num2 = num * (int) spQuantity.getValue();
ingredient = num2 + cmbFraction.getSelectedItem().toString().substring(i) + " " + tfName.getText();
} else {
if ((int) spQuantity.getValue() < 1000) {
ingredient = spQuantity.getValue() + "mL " + tfName.getText();
} else {
ingredient = (Double.parseDouble(spQuantity.getValue().toString()) / 1000.0) + "L " + tfName.getText();
}
}
//add the information the ingredient object
selected.setFormattedName(ingredient);
listRecipe.setModel(recipe.getList());
selected.setQuantity((int) spQuantity.getValue());
selected.setFractionNum(cmbFraction.getSelectedIndex());
if (!cmbUnit.getSelectedItem().equals("g")) {
selected.setFractionName(cmbFraction.getSelectedItem().toString());
} else {
selected.setFractionName(selected.getQuantity() + "g");
}
selected.setUnit(cmbUnit.getSelectedItem().toString());
selected.setUnitNum(cmbUnit.getSelectedIndex());
frameRecepieEntry.setVisible(false);
btnCalculate.setEnabled(true);
if (edit) {//if its an edit change the list of ingredients to reflect the changes
recipe.getList().removeElementAt(editSelection + 1);
recipe.getList().insertElementAt(ingredient, editSelection + 1);
//ingredients.setElementAt(ingredient, editSelection + 1);
recipe.setSingleIngredient(editSelection + 1, selected);
} else {//otherwise jsut add a new ingredient
recipe.setSingleIngredient(recipe.getIngredients().size() - 1, selected);
recipe.getList().addElement(ingredient);
}
edit = false;
}//GEN-LAST:event_btnOK1ActionPerformed
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
for (int j = listRecipe.getSelectedIndices().length - 1; j >= 0; j
recipe.remove(listRecipe.getSelectedIndices()[j]);
recipe.getList().removeElementAt(listRecipe.getSelectedIndices()[j]);
}
}//GEN-LAST:event_btnRemoveActionPerformed
private void listResultsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listResultsValueChanged
btnUseSelected.setEnabled(true);
if (!(listResults.getSelectedIndex() >= 0)) {
btnUseSelected.setEnabled(false);
}
}//GEN-LAST:event_listResultsValueChanged
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalculateActionPerformed
if (recipe.getInstructions().equals("")) {
int instruction = JOptionPane.showConfirmDialog(null, "Would you like to add instructions to your recipe?");
if (instruction == JOptionPane.YES_OPTION) {
frameDirections.setVisible(true);
} else {
printOutput();
}
} else {
printOutput();
}
}//GEN-LAST:event_btnCalculateActionPerformed
private void btnCloseAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseAboutActionPerformed
frameAbout.setVisible(false);
}//GEN-LAST:event_btnCloseAboutActionPerformed
private void btnOK3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOK3ActionPerformed
frameDirections.setVisible(false);
recipe.setInstructions(recipe.getInstructions() + "\n" + taDirections.getText());
printOutput();
}//GEN-LAST:event_btnOK3ActionPerformed
private void cmbHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbHelpActionPerformed
help();
}//GEN-LAST:event_cmbHelpActionPerformed
private void btnHelp1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHelp1ActionPerformed
help();
}//GEN-LAST:event_btnHelp1ActionPerformed
private void btnHelp2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHelp2ActionPerformed
help();
}//GEN-LAST:event_btnHelp2ActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
editSelection = listRecipe.getSelectedIndex();
edit = true;
useSelected();
tfName.setText(recipe.getSingleIngredientIndex(editSelection).getName());
spQuantity.setValue(recipe.getSingleIngredientIndex(editSelection).getQuantity());
cmbUnit.setSelectedIndex(recipe.getSingleIngredientIndex(editSelection).getUnitNum());
cmbFraction.setSelectedIndex(recipe.getSingleIngredientIndex(editSelection).getFractionNum());
frameRecepieEntry.setVisible(true);
}//GEN-LAST:event_btnEditActionPerformed
private void btnTitleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTitleActionPerformed
tfTitle.setText(recipe.getTitle());
taInstructions.setText(recipe.getInstructions());
frameTitle.setVisible(true);
}//GEN-LAST:event_btnTitleActionPerformed
private void btnOK4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOK4ActionPerformed
recipe.setInstructions(taInstructions.getText());
recipe.setTitle(tfTitle.getText());
frameTitle.setVisible(false);
}//GEN-LAST:event_btnOK4ActionPerformed
private void btnCancel2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancel2ActionPerformed
frameTitle.setVisible(false);
}//GEN-LAST:event_btnCancel2ActionPerformed
private void fcSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fcSaveActionPerformed
try {
if (fcSave.getDialogType() == JFileChooser.SAVE_DIALOG) {
Database.save(fcSave.getSelectedFile());
} else {
recipe.setList(new DefaultComboBoxModel());
recipe = new Recipe();
Database.open(fcSave.getSelectedFile());
}
} catch (NullPointerException | FileNotFoundException e) {
System.out.println("Didn't Select File Error: " + e.toString());
}
}//GEN-LAST:event_fcSaveActionPerformed
private void menuSave1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuSave1MouseClicked
save();
}//GEN-LAST:event_menuSave1MouseClicked
private void menuHelp1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuHelp1MouseClicked
help();
}//GEN-LAST:event_menuHelp1MouseClicked
private void menuAbout1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuAbout1MouseClicked
frameAbout.setVisible(true);
}//GEN-LAST:event_menuAbout1MouseClicked
private void menuOpen1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuOpen1MouseClicked
open();
}//GEN-LAST:event_menuOpen1MouseClicked
private void listRecipeValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listRecipeValueChanged
btnRemove.setEnabled(true);
btnEdit.setEnabled(true);
btnCalculate.setEnabled(true);
editSelection = listRecipe.getSelectedIndex();
if (!(listRecipe.getSelectedIndex() >= 0)) {
btnRemove.setEnabled(false);
btnCalculate.setEnabled(false);
btnEdit.setEnabled(false);
}
if (!recipe.getIngredients().isEmpty()) {
btnCalculate.setEnabled(true);
}
}//GEN-LAST:event_listRecipeValueChanged
private void menuAboutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuAboutMouseClicked
frameAbout.setVisible(true);
}//GEN-LAST:event_menuAboutMouseClicked
private void menuHelpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuHelpMouseClicked
help();
}//GEN-LAST:event_menuHelpMouseClicked
private void MenuPrintMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MenuPrintMouseClicked
//Print
}//GEN-LAST:event_MenuPrintMouseClicked
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
print();
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
save();
}//GEN-LAST:event_jMenuItem1ActionPerformed
/**
* This method searches using the string provided by the user THIS HAS BEEN
* FIXED
*/
public void ingredientLookUp() {
DefaultListModel matchesList = new DefaultListModel();
matchesIngr = new ArrayList<>();
//check that the search string isn't too short
if (tfName.getText().length() < 2) {
matchesList.addElement("Invalid Keyword (Too short?)");
listResults.setEnabled(false);
} else {
//search for matches
matchesIngr = Database.search(tfName.getText().toUpperCase());
if (matchesIngr.isEmpty()) {
matchesList.addElement("Nothing Found");
listResults.setEnabled(false);
} else {
//add the matches to the list model
for (int i = 0; i < matchesIngr.size(); i++) {
matchesList.addElement(matchesIngr.get(i).getName());
}
listResults.setEnabled(true);
}
}
//display model
listResults.setModel(matchesList);
}//fixed
/**
* This method gives the user options on how they want their data displayed
*/
public void printOutput() {
update = true;
String data = "";
boolean cancel = false;
//label print option
int label = JOptionPane.showConfirmDialog(null, "Would you like to print your recipe as a label?");
if (label == JOptionPane.YES_OPTION) {
boolean valid = false;
int servings = 1;
//makes sure that the input is valid and wont give errors
while (!valid) {
try {
recipe.setServings(Integer.parseInt(JOptionPane.showInputDialog("Please enter the number of servings that this recipe makes")));
valid = true;
} catch (HeadlessException | NumberFormatException e) {
valid = false;
System.out.println("Error: " + e.toString());
}
if (servings < 1) {
valid = false;
}
if (!valid) {
JOptionPane.showMessageDialog(cmbUnit, "That is not a valid input. Please try again");
}
}
valid = false;
String servingNameEng = "",
servingNameFre = "";
//makes sure that the names are not too long (so thatthey fit in the label
while (!valid) {
servingNameEng = JOptionPane.showInputDialog("Please enter the English name/value of the serving eg. 1 Cookie or 30g");
servingNameFre = JOptionPane.showInputDialog("Please enter the French name/value of the serving eg. 1 Biscuit or 30g");
if (servingNameEng.length() + servingNameFre.length() > 30 || servingNameEng.equals("") || servingNameFre.equals("")) {
JOptionPane.showMessageDialog(null, "That is not a valid name (Too Long/null). Please try again.");
} else {
valid = true;
recipe.setServingEng(servingNameEng);
recipe.setServingFre(servingNameFre);
}
}
//show load image
lblLoad.setVisible(true);
revalidate();
update(getGraphics());
Loading.start();
//get the output
data = Database.recipe(recipe, true);
} else if (label == JOptionPane.NO_OPTION) {
//show loading image
lblLoad.setVisible(true);
revalidate();
update(getGraphics());
Loading.start();
//get the output
data = Database.recipe(recipe, false);
} else {
cancel = true;
}
update = false;
lblLoad.setVisible(false);
if (!cancel) {
//set the output visible
output.setText(data);
framePrint.setVisible(true);
}
}
/**
* This method shows the help menu
*/
public void help() {
boolean visible = frameHelp.isVisible();
//show help
frameHelp.setVisible(true);
//open the selected category
int category = cmbHelp.getSelectedIndex();
String helpOutput = "";
try {
InputStream is = getClass().getResourceAsStream("data\\help.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean eof = false, read = false;
while (!eof) {
String line = br.readLine();
if (line == null) {
eof = true;
} else {
if (line.equals(category + "")) {
read = true;
} else if (line.equals((category + 1) + "")) {
read = false;
} else if (read) {
helpOutput += line + "\n";
}
}
}
} catch (IOException ex) {
System.out.println("Error: " + ex.toString());
}
taHelp.setText(helpOutput);
}
/**
* this method opens the save dialog
*/
public void save() {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Recipe Files", "xml");
fcSave.setFileFilter(filter);
fcSave.showSaveDialog(this);
}
/**
* This method opens a recipe file
*/
public void open() {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Recipe Files", "xml");
fcSave.setFileFilter(filter);
fcSave.showOpenDialog(this);
// if (!recipe.isEmpty()) {
// listRecipe.setModel(ingredients);
// setVisible(false);
// btnCalculate.setEnabled(true);
// numIngredients = ingredients.size();
lblLoad.setVisible(false);
}
/* This method prints the output of the recipe to a text file
*
*/
public void print() {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fcPrinter.setFileFilter(filter);
fcPrinter.showSaveDialog(frameAbout);
if (fcPrinter.getSelectedFile() != null) {
PrintWriter writer;
try {
writer = new PrintWriter(fcPrinter.getSelectedFile());
writer.print(output.getText());
writer.close();
} catch (FileNotFoundException ex) {
System.out.println("Error:" + ex.toString());
}
}
}
public void useSelected() {
DefaultComboBoxModel units = new DefaultComboBoxModel();
units.addElement("Metric Cooking Measures");
units.addElement("mL");
units.addElement("g");
units.addElement("Other");
if (!edit) {
selected = matchesIngr.get(listResults.getSelectedIndex());
recipe.addIngredient(selected);
} else {
selected = recipe.getSingleIngredientIndex(editSelection);
}
if (!Database.checkMeasuresML(selected.getID())) {
units.removeElementAt(0);
units.removeElementAt(0);
cmbFraction.setEnabled(false);
}
if (selected.getMeasures().isEmpty()) {
JOptionPane.showMessageDialog(frameRecepieEntry, "Error: No measures available.\nCannot use ingredient; Please choose another.\nBlame the person who made the database.", "Error: No Measures", WIDTH);
} else {
if (!edit) {
selected = recipe.getSingleIngredientIndex(recipe.getIngredients().size() - 1);
} else {
while (selected.getSingleMeasureIndex(selected.getMeasures().size() - 1).getName().equals("")) { //prevents empty measures in the list
selected.getMeasures().remove(selected.getMeasures().size() - 1);
}
}
cmbFraction.setEnabled(true);
cmbUnit.setEnabled(true);
spQuantity.setEnabled(true);
cmbUnit.setModel(units);
cmbFraction.setModel(model);
tfName.setText(selected.getName());
spQuantity.setValue(1);
btnOK1.setEnabled(true);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
model.addElement("1/4 Teaspoon");
model.addElement("1/2 Teaspoon");
model.addElement("1 Teaspoon");
model.addElement("1 Tablespoon");
model.addElement("1/4 Cup");
model.addElement("1/3 Cup");
model.addElement("1/2 Cup");
model.addElement("1 Cup");
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public static javax.swing.JMenu MenuPrint;
public static javax.swing.JButton btnAdd;
public static javax.swing.JButton btnBack;
public static javax.swing.JButton btnCalculate;
public static javax.swing.JButton btnCancel2;
public static javax.swing.JButton btnCloseAbout;
public static javax.swing.JButton btnEdit;
public static javax.swing.JButton btnHelp1;
public static javax.swing.JButton btnHelp2;
public static javax.swing.JButton btnOK1;
public static javax.swing.JButton btnOK3;
public static javax.swing.JButton btnOK4;
public static javax.swing.JButton btnRemove;
public static javax.swing.JButton btnSearch2;
public static javax.swing.JButton btnTitle;
public static javax.swing.JButton btnUseSelected;
public static javax.swing.JComboBox cmbFraction;
public static javax.swing.JComboBox cmbHelp;
public static javax.swing.JComboBox cmbUnit;
public static javax.swing.JFileChooser fcPrinter;
public static javax.swing.JFileChooser fcSave;
public static javax.swing.JDialog frameAbout;
public static javax.swing.JFrame frameDirections;
public static javax.swing.JFrame frameHelp;
public static javax.swing.JFrame framePrint;
public static javax.swing.JFrame frameRecepieEntry;
public static javax.swing.JFrame frameTitle;
public static javax.swing.JLabel jLabel1;
public static javax.swing.JLabel jLabel3;
public static javax.swing.JLayeredPane jLayeredPane1;
public static javax.swing.JMenuBar jMenuBar1;
public static javax.swing.JMenuBar jMenuBar2;
public static javax.swing.JMenuItem jMenuItem1;
public static javax.swing.JMenuItem jMenuItem2;
public static javax.swing.JPopupMenu jPopupMenu1;
public static javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JScrollPane jScrollPane2;
public static javax.swing.JScrollPane jScrollPane3;
public static javax.swing.JScrollPane jScrollPane4;
public static javax.swing.JScrollPane jScrollPane5;
public static javax.swing.JScrollPane jScrollPane6;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JLabel lblLoad;
public static javax.swing.JList listRecipe;
public static javax.swing.JList listResults;
public static javax.swing.JMenu menuAbout;
public static javax.swing.JMenu menuAbout1;
public static javax.swing.JMenu menuHelp;
public static javax.swing.JMenu menuHelp1;
public static javax.swing.JMenu menuOpen1;
public static javax.swing.JMenu menuSave;
public static javax.swing.JMenu menuSave1;
public static javax.swing.JTextArea output;
public static javax.swing.JScrollPane scrollPane;
public static javax.swing.JSpinner spQuantity;
public static javax.swing.JTextArea taDirections;
public static javax.swing.JTextArea taHelp;
public static javax.swing.JTextArea taInstructions;
public static javax.swing.JTextField tfName;
public static javax.swing.JTextField tfTitle;
// End of variables declaration//GEN-END:variables
} |
package com.jediterm.terminal.display;
import com.jediterm.terminal.*;
import com.jediterm.terminal.emulator.charset.CharacterSet;
import com.jediterm.terminal.emulator.charset.GraphicSet;
import com.jediterm.terminal.emulator.charset.GraphicSetState;
import com.jediterm.terminal.emulator.mouse.*;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;
/**
* Terminal that reflects obtained commands and text at {@link TerminalDisplay}(handles change of cursor position, screen size etc)
* and {@link BackBuffer}(stores printed text)
*
* @author traff
*/
public class JediTerminal implements Terminal, TerminalMouseListener {
private static final Logger LOG = Logger.getLogger(JediTerminal.class.getName());
private static final int MIN_WIDTH = 5;
private int myScrollRegionTop;
private int myScrollRegionBottom;
volatile private int myCursorX = 0;
volatile private int myCursorY = 1;
private int myTerminalWidth = 80;
private int myTerminalHeight = 24;
private final TerminalDisplay myDisplay;
private final BackBuffer myBackBuffer;
private final StyleState myStyleState;
private StoredCursor myStoredCursor = null;
private final EnumSet<TerminalMode> myModes = EnumSet.noneOf(TerminalMode.class);
private final TerminalKeyEncoder myTerminalKeyEncoder = new TerminalKeyEncoder();
private final Tabulator myTabulator;
private final GraphicSetState myGraphicSetState;
private MouseFormat myMouseFormat = MouseFormat.MOUSE_FORMAT_XTERM;
private TerminalOutputStream myTerminalOutput = null;
private MouseMode myMouseMode = MouseMode.MOUSE_REPORTING_NONE;
public JediTerminal(final TerminalDisplay display, final BackBuffer buf, final StyleState initialStyleState) {
myDisplay = display;
myBackBuffer = buf;
myStyleState = initialStyleState;
myTerminalWidth = display.getColumnCount();
myTerminalHeight = display.getRowCount();
myScrollRegionTop = 1;
myScrollRegionBottom = myTerminalHeight;
myTabulator = new DefaultTabulator(myTerminalWidth);
myGraphicSetState = new GraphicSetState();
reset();
}
@Override
public void setModeEnabled(TerminalMode mode, boolean enabled) {
if (enabled) {
myModes.add(mode);
}
else {
myModes.remove(mode);
}
mode.setEnabled(this, enabled);
}
@Override
public void disconnected() {
myDisplay.setCursorVisible(false);
}
private void wrapLines() {
if (myCursorX >= myTerminalWidth) {
myCursorX = 0;
if (isAutoWrap()) {
myCursorY += 1;
}
}
}
private void finishText() {
myDisplay.setCursor(myCursorX, myCursorY);
scrollY();
}
@Override
public void writeCharacters(String string) {
writeCharacters(decode(string).toCharArray(), 0, string.length());
}
private void writeCharacters(final char[] chosenBuffer, final int start,
final int length) {
myBackBuffer.lock();
try {
wrapLines();
scrollY();
if (length != 0) {
myBackBuffer.writeBytes(myCursorX, myCursorY, chosenBuffer, start, length);
}
myCursorX += length;
finishText();
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void writeDoubleByte(final char[] bytesOfChar) throws UnsupportedEncodingException {
writeString(new String(bytesOfChar, 0, 2));
}
public void writeString(String string) {
doWriteString(decode(string));
}
private String decode(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
result.append(myGraphicSetState.map(c));
}
return result.toString();
}
private void doWriteString(String string) {
myBackBuffer.lock();
try {
wrapLines();
scrollY();
myBackBuffer.writeString(myCursorX, myCursorY, string);
myCursorX += string.length();
finishText();
}
finally {
myBackBuffer.unlock();
}
}
public void writeUnwrappedString(String string) {
int length = string.length();
int off = 0;
while (off < length) {
int amountInLine = Math.min(distanceToLineEnd(), length - off);
writeString(string.substring(off, off + amountInLine));
wrapLines();
scrollY();
off += amountInLine;
}
}
public void scrollY() {
myBackBuffer.lock();
try {
if (myCursorY > myScrollRegionBottom) {
final int dy = myScrollRegionBottom - myCursorY;
myCursorY = myScrollRegionBottom;
scrollArea(myScrollRegionTop, scrollingRegionSize(), dy);
myDisplay.setCursor(myCursorX, myCursorY);
}
if (myCursorY < myScrollRegionTop) {
myCursorY = myScrollRegionTop;
}
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void newLine() {
myCursorY += 1;
scrollY();
if (isAutoNewLine()) {
carriageReturn();
}
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void mapCharsetToGL(int num) {
myGraphicSetState.setGL(num);
}
@Override
public void mapCharsetToGR(int num) {
myGraphicSetState.setGR(num);
}
@Override
public void designateCharacterSet(int tableNumber, char charset) {
GraphicSet gs = myGraphicSetState.getGraphicSet(tableNumber);
myGraphicSetState.designateGraphicSet(gs, charset);
}
@Override
public void singleShiftSelect(int num) {
myGraphicSetState.overrideGL(num);
}
@Override
public void setAnsiConformanceLevel(int level) {
if (level == 1 || level == 2) {
myGraphicSetState.designateGraphicSet(0, CharacterSet.ASCII); //ASCII designated as G0
myGraphicSetState
.designateGraphicSet(1, CharacterSet.DEC_SUPPLEMENTAL); //TODO: not DEC supplemental, but ISO Latin-1 supplemental designated as G1
mapCharsetToGL(0);
mapCharsetToGR(1);
}
else if (level == 3) {
designateCharacterSet(0, 'B'); //ASCII designated as G0
mapCharsetToGL(0);
}
else {
throw new IllegalArgumentException();
}
}
@Override
public void setWindowTitle(String name) {
myDisplay.setWindowTitle(name);
}
@Override
public void backspace() {
myCursorX -= 1;
if (myCursorX < 0) {
myCursorY -= 1;
myCursorX = myTerminalWidth - 1;
}
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void carriageReturn() {
myCursorX = 0;
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void horizontalTab() {
myCursorX = myTabulator.nextTab(myCursorX);
if (myCursorX >= myTerminalWidth) {
myCursorX = 0;
myCursorY += 1;
}
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void eraseInDisplay(final int arg) {
myBackBuffer.lock();
try {
int beginY;
int endY;
switch (arg) {
case 0:
// Initial line
if (myCursorX < myTerminalWidth) {
myBackBuffer.eraseCharacters(myCursorX, myTerminalWidth, myCursorY - 1);
}
// Rest
beginY = myCursorY;
endY = myTerminalHeight;
break;
case 1:
// initial line
myBackBuffer.eraseCharacters(0, myCursorX + 1, myCursorY - 1);
beginY = 0;
endY = myCursorY - 1;
break;
case 2:
beginY = 0;
endY = myTerminalHeight;
break;
default:
LOG.error("Unsupported erase in display mode:" + arg);
beginY = 1;
endY = 1;
break;
}
// Rest of lines
if (beginY != endY) {
clearLines(beginY, endY);
}
}
finally {
myBackBuffer.unlock();
}
}
public void clearLines(final int beginY, final int endY) {
myBackBuffer.lock();
try {
myBackBuffer.clearLines(beginY, endY);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void clearScreen() {
clearLines(0, myTerminalHeight);
}
@Override
public void setCursorVisible(boolean visible) {
myDisplay.setCursorVisible(visible);
}
@Override
public void useAlternateBuffer(boolean enabled) {
myBackBuffer.useAlternateBuffer(enabled);
myDisplay.setScrollingEnabled(!enabled);
}
@Override
public byte[] getCodeForKey(int key) {
return myTerminalKeyEncoder.getCode(key);
}
@Override
public void setApplicationArrowKeys(boolean enabled) {
if (enabled) {
myTerminalKeyEncoder.arrowKeysApplicationSequences();
}
else {
myTerminalKeyEncoder.arrowKeysAnsiCursorSequences();
}
}
@Override
public void setApplicationKeypad(boolean enabled) {
if (enabled) {
myTerminalKeyEncoder.keypadApplicationSequences();
}
else {
myTerminalKeyEncoder.normalKeypad();
}
}
public void eraseInLine(int arg) {
myBackBuffer.lock();
try {
switch (arg) {
case 0:
if (myCursorX < myTerminalWidth) {
myBackBuffer.eraseCharacters(myCursorX, myTerminalWidth, myCursorY - 1);
}
break;
case 1:
final int extent = Math.min(myCursorX + 1, myTerminalWidth);
myBackBuffer.eraseCharacters(0, extent, myCursorY - 1);
break;
case 2:
myBackBuffer.eraseCharacters(0, myTerminalWidth, myCursorY - 1);
break;
default:
LOG.error("Unsupported erase in line mode:" + arg);
break;
}
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void deleteCharacters(int count) {
myBackBuffer.lock();
try {
final int extent = Math.min(count, myTerminalWidth - myCursorX);
myBackBuffer.deleteCharacters(myCursorX, myCursorY - 1, extent);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void insertBlankCharacters(int count) {
myBackBuffer.lock();
try {
final int extent = Math.min(count, myTerminalWidth - myCursorX);
myBackBuffer.insertBlankCharacters(myCursorX, myCursorY - 1, extent);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void eraseCharacters(int count) {
//Clear the next n characters on the cursor's line, including the cursor's
//position.
myBackBuffer.lock();
try {
final int extent = Math.min(count, myTerminalWidth - myCursorX);
myBackBuffer.eraseCharacters(myCursorX, myCursorX + extent, myCursorY - 1);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void clearTabStopAtCursor() {
myTabulator.clearTabStop(myCursorX);
}
@Override
public void clearAllTabStops() {
myTabulator.clearAllTabStops();
}
@Override
public void setTabStopAtCursor() {
myTabulator.setTabStop(myCursorX);
}
@Override
public void insertLines(int count) {
myBackBuffer.lock();
try {
myBackBuffer.insertLines(myCursorY - 1, count, myScrollRegionBottom);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void deleteLines(int count) {
myBackBuffer.lock();
try {
myBackBuffer.deleteLines(myCursorY - 1, count, myScrollRegionBottom);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void setBlinkingCursor(boolean enabled) {
myDisplay.setBlinkingCursor(enabled);
}
@Override
public void cursorUp(final int countY) {
myBackBuffer.lock();
try {
myCursorY -= countY;
myCursorY = Math.max(myCursorY, scrollingRegionTop());
myDisplay.setCursor(myCursorX, myCursorY);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void cursorDown(final int dY) {
myBackBuffer.lock();
try {
myCursorY += dY;
myCursorY = Math.min(myCursorY, scrollingRegionBottom());
myDisplay.setCursor(myCursorX, myCursorY);
}
finally {
myBackBuffer.unlock();
}
}
@Override
public void index() {
//Moves the cursor down one line in the
//same column. If the cursor is at the
//bottom margin, the page scrolls up
myBackBuffer.lock();
try {
if (myCursorY == myScrollRegionBottom) {
scrollArea(myScrollRegionTop, scrollingRegionSize(), -1);
}
else {
myCursorY += 1;
myDisplay.setCursor(myCursorX, myCursorY);
}
}
finally {
myBackBuffer.unlock();
}
}
private void scrollArea(int scrollRegionTop, int scrollRegionSize, int dy) {
myDisplay.scrollArea(scrollRegionTop, scrollRegionSize, dy);
myBackBuffer.scrollArea(scrollRegionTop, dy, scrollRegionTop + scrollRegionSize - 1);
}
@Override
public void nextLine() {
myBackBuffer.lock();
try {
myCursorX = 0;
if (myCursorY == myScrollRegionBottom) {
scrollArea(myScrollRegionTop, scrollingRegionSize(), -1);
}
else {
myCursorY += 1;
}
myDisplay.setCursor(myCursorX, myCursorY);
}
finally {
myBackBuffer.unlock();
}
}
private int scrollingRegionSize() {
return myScrollRegionBottom - myScrollRegionTop + 1;
}
@Override
public void reverseIndex() {
//Moves the cursor up one line in the same
//column. If the cursor is at the top margin,
//the page scrolls down.
myBackBuffer.lock();
try {
if (myCursorY == myScrollRegionTop) {
scrollArea(myScrollRegionTop - 1, scrollingRegionSize(), 1);
}
else {
myCursorY -= 1;
myDisplay.setCursor(myCursorX, myCursorY);
}
}
finally {
myBackBuffer.unlock();
}
}
private int scrollingRegionTop() {
return isOriginMode() ? myScrollRegionTop : 1;
}
private int scrollingRegionBottom() {
return isOriginMode() ? myScrollRegionBottom : myTerminalHeight;
}
@Override
public void cursorForward(final int dX) {
myCursorX += dX;
myCursorX = Math.min(myCursorX, myTerminalWidth - 1);
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void cursorBackward(final int dX) {
myCursorX -= dX;
myCursorX = Math.max(myCursorX, 0);
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void cursorHorizontalAbsolute(int x) {
cursorPosition(x, myCursorY);
}
@Override
public void linePositionAbsolute(int y) {
myCursorY = y;
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void cursorPosition(int x, int y) {
myCursorX = x - 1;
if (isOriginMode()) {
myCursorY = y + scrollingRegionTop() - 1;
}
else {
myCursorY = y;
}
if (myCursorY > scrollingRegionBottom()) {
myCursorY = scrollingRegionBottom();
}
myDisplay.setCursor(myCursorX, myCursorY);
}
@Override
public void setScrollingRegion(int top, int bottom) {
if (top > bottom) {
LOG.error("Top margin of scroll region can't be greater then bottom: " + top + ">" + bottom);
}
myScrollRegionTop = Math.max(1, top);
myScrollRegionBottom = Math.min(myTerminalHeight, bottom);
//DECSTBM moves the cursor to column 1, line 1 of the page
cursorPosition(1, 1);
}
@Override
public void resetScrollRegions() {
setScrollingRegion(1, myTerminalHeight);
}
@Override
public void characterAttributes(final TextStyle textStyle) {
myStyleState.setCurrent(textStyle);
}
@Override
public void beep() {
myDisplay.beep();
}
@Override
public int distanceToLineEnd() {
return myTerminalWidth - myCursorX;
}
@Override
public void saveCursor() {
myStoredCursor = createCursorState();
}
private StoredCursor createCursorState() {
return new StoredCursor(myCursorX, myCursorY, myStyleState.getCurrent().clone(),
isAutoWrap(), isOriginMode(), myGraphicSetState);
}
@Override
public void restoreCursor() {
if (myStoredCursor != null) {
restoreCursor(myStoredCursor);
}
else { //If nothing was saved by DECSC
setModeEnabled(TerminalMode.OriginMode, false); //Resets origin mode (DECOM)
cursorPosition(1, 1); //Moves the cursor to the home position (upper left of screen).
myStyleState.reset(); //Turns all character attributes off (normal setting).
myGraphicSetState.resetState();
//myGraphicSetState.designateGraphicSet(0, CharacterSet.ASCII);//Maps the ASCII character set into GL
//mapCharsetToGL(0);
//myGraphicSetState.designateGraphicSet(1, CharacterSet.DEC_SUPPLEMENTAL);
//mapCharsetToGR(1); //and the DEC Supplemental Graphic set into GR
}
myDisplay.setCursor(myCursorX, myCursorY);
}
public void restoreCursor(@NotNull StoredCursor storedCursor) {
myCursorX = storedCursor.getCursorX();
myCursorY = storedCursor.getCursorY();
myStyleState.setCurrent(storedCursor.getTextStyle().clone());
setModeEnabled(TerminalMode.AutoWrap, storedCursor.isAutoWrap());
setModeEnabled(TerminalMode.OriginMode, storedCursor.isOriginMode());
CharacterSet[] designations = storedCursor.getDesignations();
for (int i = 0; i < designations.length; i++) {
myGraphicSetState.designateGraphicSet(i, designations[i]);
}
myGraphicSetState.setGL(storedCursor.getGLMapping());
myGraphicSetState.setGR(storedCursor.getGRMapping());
if (storedCursor.getGLOverride() >= 0) {
myGraphicSetState.overrideGL(storedCursor.getGLOverride());
}
}
@Override
public void reset() {
myGraphicSetState.resetState();
myStyleState.reset();
myBackBuffer.clearAll();
initModes();
initMouseModes();
cursorPosition(1, 1);
}
private void initMouseModes() {
myMouseMode = MouseMode.MOUSE_REPORTING_NONE;
myMouseFormat = MouseFormat.MOUSE_FORMAT_XTERM;
}
private void initModes() {
myModes.clear();
setModeEnabled(TerminalMode.AutoNewLine, true);
setModeEnabled(TerminalMode.AutoWrap, true);
}
public boolean isAutoNewLine() {
return myModes.contains(TerminalMode.AutoNewLine);
}
public boolean isOriginMode() {
return myModes.contains(TerminalMode.OriginMode);
}
public boolean isAutoWrap() {
return myModes.contains(TerminalMode.AutoWrap);
}
private static int createButtonCode(MouseEvent event) {
if ((event.getButton()) == MouseEvent.BUTTON1) {
return MouseButtonCodes.LEFT;
}
else if (event.getButton() == MouseEvent.BUTTON3) {
return MouseButtonCodes.NONE; //we dont handle right mouse button as it used for the context menu invocation
}
else {
return MouseButtonCodes.RIGHT;
}
}
private byte[] mouseReport(int button, int x, int y) {
StringBuilder sb = new StringBuilder();
switch (myMouseFormat) {
case MOUSE_FORMAT_XTERM_EXT:
sb.append(String.format("\033[M%c%c%c",
(char)(32 + button),
(char)(32 + x),
(char)(32 + y)));
break;
case MOUSE_FORMAT_URXVT:
sb.append(String.format("\033[%d;%d;%dM", 32 + button, x, y));
break;
case MOUSE_FORMAT_SGR:
if ((button & MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG) != 0) {
// for mouse release event
sb.append(String.format("\033[<%d;%d;%dm",
button ^ MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG,
x,
y));
}
else {
// for mouse press/motion event
sb.append(String.format("\033[<%d;%d;%dM", button, x, y));
}
break;
case MOUSE_FORMAT_XTERM:
default:
sb.append(String.format("\033[M%c%c%c", (char)(32 + button), (char)(32 + x), (char)(32 + y)));
break;
}
return sb.toString().getBytes(Charset.forName("UTF-8"));
}
private boolean shouldSendMouseData() {
return myTerminalOutput != null &&
(myMouseMode == MouseMode.MOUSE_REPORTING_NORMAL || myMouseMode == MouseMode.MOUSE_REPORTING_ALL_MOTION ||
myMouseMode == MouseMode.MOUSE_REPORTING_BUTTON_MOTION);
}
@Override
public void mousePressed(int x, int y, MouseEvent event) {
if (shouldSendMouseData()) {
int cb = createButtonCode(event);
if (cb != MouseButtonCodes.NONE) {
if (createButtonCode(event) == MouseButtonCodes.SCROLLDOWN || createButtonCode(event) == MouseButtonCodes.SCROLLUP) {
// convert x11 scroll button number to terminal button code
int offset = MouseButtonCodes.SCROLLDOWN;
cb -= offset;
cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SCROLL_FLAG;
}
cb = applyModifierKeys(event, cb);
myTerminalOutput.sendBytes(mouseReport(cb, x + 1, y + 1));
}
}
}
@Override
public void mouseReleased(int x, int y, MouseEvent event) {
if (shouldSendMouseData()) {
int cb = createButtonCode(event);
if (cb != MouseButtonCodes.NONE) {
if (myMouseFormat == MouseFormat.MOUSE_FORMAT_SGR) {
// for SGR 1006 mode
cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG;
}
else {
// for 1000/1005/1015 mode
cb = MouseButtonCodes.RELEASE;
}
cb = applyModifierKeys(event, cb);
myTerminalOutput.sendBytes(mouseReport(cb, x + 1, y + 1));
}
}
}
private static int applyModifierKeys(MouseEvent event, int cb) {
if (event.isControlDown()) {
cb |= MouseButtonModifierFlags.MOUSE_BUTTON_CTRL_FLAG;
}
if (event.isShiftDown()) {
cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SHIFT_FLAG;
}
if ((event.getModifiersEx() & InputEvent.META_MASK) != 0) {
cb |= MouseButtonModifierFlags.MOUSE_BUTTON_META_FLAG;
}
return cb;
}
public void setTerminalOutput(TerminalOutputStream terminalOutput) {
myTerminalOutput = terminalOutput;
}
@Override
public void setMouseMode(@NotNull MouseMode mode) {
myMouseMode = mode;
}
@Override
public void setMouseFormat(MouseFormat mouseFormat) {
myMouseFormat = mouseFormat;
}
public interface ResizeHandler {
void sizeUpdated(int termWidth, int termHeight, int cursorY);
}
public Dimension resize(final Dimension pendingResize, final RequestOrigin origin) {
final int oldHeight = myTerminalHeight;
if (pendingResize.width <= MIN_WIDTH) {
pendingResize.setSize(MIN_WIDTH, pendingResize.height);
}
final Dimension pixelSize = myDisplay.requestResize(pendingResize, origin, myCursorY, new ResizeHandler() {
@Override
public void sizeUpdated(int termWidth, int termHeight, int cursorY) {
myTerminalWidth = termWidth;
myTerminalHeight = termHeight;
myCursorY = cursorY;
myTabulator.resize(myTerminalWidth);
}
});
myScrollRegionBottom += myTerminalHeight - oldHeight;
return pixelSize;
}
@Override
public void fillScreen(final char c) {
myBackBuffer.lock();
try {
final char[] chars = new char[myTerminalWidth];
Arrays.fill(chars, c);
final String str = new String(chars);
for (int row = 1; row <= myTerminalHeight; row++) {
myBackBuffer.writeString(0, row, str);
}
}
finally {
myBackBuffer.unlock();
}
}
@Override
public int getTerminalHeight() {
return myTerminalHeight;
}
@Override
public int getCursorX() {
return myCursorX;
}
@Override
public int getCursorY() {
return myCursorY;
}
@Override
public StyleState getStyleState() {
return myStyleState;
}
private static class DefaultTabulator implements Tabulator {
private static final int TAB_LENGTH = 8;
private final SortedSet<Integer> myTabStops;
private int myWidth;
private int myTabLength;
public DefaultTabulator(int width) {
this(width, TAB_LENGTH);
}
public DefaultTabulator(int width, int tabLength) {
myTabStops = new TreeSet<Integer>();
myWidth = width;
myTabLength = tabLength;
initTabStops(width, tabLength);
}
private void initTabStops(int columns, int tabLength) {
for (int i = tabLength; i < columns; i += tabLength) {
myTabStops.add(i);
}
}
public void resize(int columns) {
if (columns > myWidth) {
for (int i = myTabLength * (myWidth / myTabLength); i < columns; i += myTabLength) {
if (i >= myWidth) {
myTabStops.add(i);
}
}
}
else {
Iterator<Integer> it = myTabStops.iterator();
while (it.hasNext()) {
int i = it.next();
if (i > columns) {
it.remove();
}
}
}
myWidth = columns;
}
@Override
public void clearTabStop(int position) {
myTabStops.remove(Integer.valueOf(position));
}
@Override
public void clearAllTabStops() {
myTabStops.clear();
}
@Override
public int getNextTabWidth(int position) {
return nextTab(position) - position;
}
@Override
public int getPreviousTabWidth(int position) {
return position - previousTab(position);
}
@Override
public int nextTab(int position) {
int tabStop = Integer.MAX_VALUE;
// Search for the first tab stop after the given position...
SortedSet<Integer> tailSet = myTabStops.tailSet(position + 1);
if (!tailSet.isEmpty()) {
tabStop = tailSet.first();
}
// Don't go beyond the end of the line...
return Math.min(tabStop, (myWidth - 1));
}
@Override
public int previousTab(int position) {
int tabStop = 0;
// Search for the first tab stop before the given position...
SortedSet<Integer> headSet = myTabStops.headSet(Integer.valueOf(position));
if (!headSet.isEmpty()) {
tabStop = headSet.last();
}
// Don't go beyond the start of the line...
return Math.max(0, tabStop);
}
@Override
public void setTabStop(int position) {
myTabStops.add(Integer.valueOf(position));
}
}
} |
package acdsee.gui.components;
import acdsee.base.Directory;
import acdsee.base.Walkable;
import acdsee.base.ZipFile;
import acdsee.gui.components.thumbnail.ZipEntryThumbnail;
import acdsee.gui.components.thumbnail.FileThumbnail;
import acdsee.gui.components.thumbnail.AbstractThumbnail;
import acdsee.sorting.ui.SortMenu;
import java.awt.Color;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import org.apache.commons.io.FileUtils;
public class ThumbnailPane extends JScrollPane {
private static final Point UPPERLEFTCORNER = new Point(0, 0);
private static final int THUMB_MARGIN_LEFT = 10;
private static final int THUMB_MARGIN_RIGHT = 10;
private static final int THUMB_MARGIN_BOTTOM = 10;
private static final int THUMB_MARGIN_TOP = 10;
private static ThumbnailPane thumbnailPane;
private JPanel panel;
private PreviewPane previewpane;
private ExecutorService executorService;
private Walkable walkable;
private int thumbSize = 135;
private final PropertyChangeSupport pcs;
private MouseAdapter mouseListener;
public ExecutorService getExecutorService() {
return executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
public static final ThumbnailPane getThumbnailPane() {
if (thumbnailPane == null) {
thumbnailPane = new ThumbnailPane();
int thumbSize = thumbnailPane.getThumbSize();
thumbnailPane.getVerticalScrollBar().setBlockIncrement(thumbSize + THUMB_MARGIN_BOTTOM);
thumbnailPane.getVerticalScrollBar().setUnitIncrement(thumbSize + THUMB_MARGIN_BOTTOM);
thumbnailPane.getViewport().setMinimumSize(new Dimension(thumbSize + THUMB_MARGIN_LEFT + THUMB_MARGIN_RIGHT, thumbSize + THUMB_MARGIN_TOP + THUMB_MARGIN_BOTTOM));
}
return thumbnailPane;
}
/**
* Creates a new instance of ThumbnailPane
*/
public ThumbnailPane() {
super();
this.mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
getPanel().requestFocusInWindow();
final AbstractThumbnail proxy = (AbstractThumbnail)evt.getSource();
if (SwingUtilities.isLeftMouseButton(evt) && evt.getClickCount() > 1) {
if (proxy instanceof FileThumbnail) {
File f = ((FileThumbnail) proxy).getFile();
Walkable walkable = Walkable.getInstance(f);
setSource(walkable);
}
}
if (SwingUtilities.isRightMouseButton(evt)) {
JPopupMenu popup = new JPopupMenu();
// Desktop integration...
JMenu nativeCommands = new JMenu("Native Cmd");
if (proxy instanceof FileThumbnail && Desktop.isDesktopSupported()) {
final File selectedFile = ((FileThumbnail) proxy).getFile();
if (selectedFile.isFile()) {
JMenuItem nativeCmd = new JMenuItem("Open...");
nativeCmd.addActionListener((ActionEvent arg0) -> {
try {
Desktop.getDesktop().open(selectedFile);
} catch (IOException ex) {
Logger.getLogger(ThumbnailPane.class.getName()).log(Level.SEVERE, null, ex);
}
});
nativeCommands.add(nativeCmd);
nativeCmd = new JMenuItem("Edit...");
nativeCmd.addActionListener((ActionEvent arg0) -> {
try {
Desktop.getDesktop().edit(selectedFile);
} catch (IOException ex) {
Logger.getLogger(ThumbnailPane.class.getName()).log(Level.SEVERE, null, ex);
}
});
nativeCommands.add(nativeCmd);
}
popup.add(nativeCommands);
popup.addSeparator();
}
JMenuItem mi = new JMenuItem("Delete");
mi.addActionListener((ActionEvent arg0) -> {
final File selectedFile = ((FileThumbnail) proxy).getFile();
FileUtils.deleteQuietly(selectedFile);
getPanel().remove(proxy);
revalidate();
});
popup.add(mi);
mi = new JMenuItem("Refresh...");
mi.addActionListener((ActionEvent arg0) -> {
refresh();
});
popup.add(mi);
popup.show(proxy, evt.getX(), evt.getY());
}
try {
// statusbarLabelTotalObjects.setText("Total " + proxy.getFile().getParentFile().listFiles().length + " objects (" + FileHelper.getSizeInMegaByte(FileHelper.getFileOrDirectorySize(proxy.getFile().getParentFile())) + " MB)");
// statusbarLabelFileName.setText(proxy.getFile().getName());
// statusbarLabelFileIcon.setIcon(FileSystemView.getFileSystemView().getSystemIcon(proxy.getFile()));
// statusbarLabelImgProps.setText(proxy.getImageWidth() + "x" + proxy.getImageHeight() + "x" + proxy.getImageDepth());
if (evt.getClickCount() > 1) {
// Desktop.getDesktop().open(((FileThumbnail)proxy).getFile());
final JFrame w = new JFrame();
w.setExtendedState(JFrame.MAXIMIZED_BOTH);
w.setUndecorated(true);
w.setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
gd.setFullScreenWindow(w);
final Container parent = previewpane.getParent();
w.getContentPane().setBackground(Color.BLACK);
w.getContentPane().add(previewpane);
w.setVisible(true);
previewpane.setFocusable(true);
previewpane.requestFocusInWindow();
previewpane.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
int keyCode = evt.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE) {
try {
w.setVisible(false);
previewpane.removeKeyListener(this);
parent.add(previewpane);
w.dispose();
} catch (Exception ex) {
//TODO
}
}
}
});
}
if (proxy instanceof FileThumbnail) {
previewpane.setSource(/*proxy.loadOriginalImage()); */((FileThumbnail) proxy).getFile());
} else if (proxy instanceof ZipEntryThumbnail) {
previewpane.setSource(((ZipEntryThumbnail) proxy).getInputStream());
}
} catch (Exception e) {
System.out.println(e);
}
}
};
setBorder(null);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
setRequestFocusEnabled(true);
setAutoscrolls(true);
panel = new JPanel() {
private final Dimension MINSIZE = new Dimension(getThumbSize() + THUMB_MARGIN_LEFT + THUMB_MARGIN_RIGHT, getThumbSize() + THUMB_MARGIN_TOP + THUMB_MARGIN_BOTTOM);
@Override
public java.awt.Dimension getMinimumSize() {
return MINSIZE;
}
@Override
public java.awt.Dimension getPreferredSize() {
final java.awt.Insets insets = getInsets();
final int count = getComponentCount();
final int hgap = ((java.awt.FlowLayout) getLayout()).getHgap();
final int vgap = ((java.awt.FlowLayout) getLayout()).getVgap();
final int cols = getVisibleRect().width / (getThumbSize() + 10);
if (cols == 0) {
return getMinimumSize();
}
final java.awt.Dimension d = new java.awt.Dimension(
cols * (getThumbSize() + hgap) + hgap,
(count / cols) * (getThumbSize() + vgap) + vgap);
// Dont forget the frame's insets
d.width += insets.left + insets.right;
d.height += insets.top + insets.bottom;
return d;
}
};
panel.setBorder(null);
panel.setBackground(Color.WHITE);
SelectionContainer sc = new SelectionContainer(panel);
getViewport().add(sc);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, THUMB_MARGIN_RIGHT, THUMB_MARGIN_BOTTOM));
sc.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
FileThumbnail at = (FileThumbnail) evt.getSource();
setSource(Walkable.getInstance(at.getFile()));
} catch (Exception ex) {
//TODO
}
if (ThumbnailPane.this.isVisible()) {
ThumbnailPane.this.requestFocusInWindow();
}
}
@Override
public void mousePressed(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
final JPopupMenu sortPopupMenu = new JPopupMenu();
final SortMenu sort = new SortMenu(ThumbnailPane.this);
sort.setSortableContainer(panel);
sortPopupMenu.add(sort);
sortPopupMenu.show(panel, evt.getX(), evt.getY());
}
}
});
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent evt) {
if ((getThumbSize() + THUMB_MARGIN_LEFT + THUMB_MARGIN_RIGHT + getVerticalScrollBar().getWidth()) > getWidth()) {
setThumbSize(getWidth() - THUMB_MARGIN_LEFT - THUMB_MARGIN_RIGHT - getVerticalScrollBar().getWidth());
}
panel.invalidate();
panel.validate();
panel.repaint();
}
});
pcs = new PropertyChangeSupport(this);
}
public JPanel getPanel() {
return panel;
}
private void refresh() {
setSource(getSource());
}
public Walkable getSource() {
return this.walkable;
}
public void setSource(Walkable walkable) {
if (walkable!=null) {
this.walkable = walkable;
getViewport().setViewPosition(UPPERLEFTCORNER);
getPanel().removeAll();
getPanel().revalidate();
getPanel().repaint();
if (walkable instanceof ZipFile) {
walkable.getChildren().forEach(zipEntry -> {
AbstractThumbnail t = new ZipEntryThumbnail((ZipEntry)zipEntry, (java.util.zip.ZipFile)walkable.getSource(), executorService);
t.addMouseListener(mouseListener);
getVerticalScrollBar().addAdjustmentListener(t);
getPanel().add(t);
});
} else if (walkable instanceof Directory) {
walkable.getChildren().forEach(file -> {
AbstractThumbnail t = new FileThumbnail((File)file, executorService);
t.addMouseListener(mouseListener);
getVerticalScrollBar().addAdjustmentListener(t);
getPanel().add(t);
});
}
}
}
public void setPreviewpane(PreviewPane previewpane) {
this.previewpane = previewpane;
}
public int getThumbSize() {
return this.thumbSize;
}
public void setThumbSize(int thumbSize) {
this.thumbSize = thumbSize;
AbstractThumbnail.setThumbnailHeight(thumbSize);
AbstractThumbnail.setThumbnailWidth(thumbSize);
refresh();
}
} |
package eu.chargetime.ocpp;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles basic server logic: Holds a list of supported features. Keeps track of outgoing requests.
* Calls back when a confirmation is received.
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
public static final int INITIAL_SESSIONS_NUMBER = 1000;
private Map<UUID, ISession> sessions;
private Listener listener;
private final IFeatureRepository featureRepository;
private final IPromiseRepository promiseRepository;
/**
* Constructor. Handles the required injections.
*
* @param listener injected listener.
*/
public Server(
Listener listener,
IFeatureRepository featureRepository,
IPromiseRepository promiseRepository) {
this.listener = listener;
this.featureRepository = featureRepository;
this.promiseRepository = promiseRepository;
this.sessions = new ConcurrentHashMap<>(INITIAL_SESSIONS_NUMBER);
}
/**
* Start listening for clients.
*
* @param hostname Url or IP of the server as String.
* @param port the port number of the server.
* @param serverEvents Callback handler for server specific events.
*/
public void open(String hostname, int port, ServerEvents serverEvents) {
listener.open(
hostname,
port,
new ListenerEvents() {
@Override
public void authenticateSession(
SessionInformation information, String username, byte[] password)
throws AuthenticationException {
serverEvents.authenticateSession(information, username, password);
}
@Override
public void newSession(ISession session, SessionInformation information) {
session.accept(
new SessionEvents() {
@Override
public void handleConfirmation(String uniqueId, Confirmation confirmation) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get().complete(confirmation);
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for confirmation {}", confirmation);
}
}
@Override
public Confirmation handleRequest(Request request)
throws UnsupportedFeatureException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (featureOptional.isPresent()) {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
return featureOptional
.get()
.handleRequest(sessionIdOptional.get(), request);
} else {
logger.error(
"Unable to handle request ({}), the active session was not found for {}.",
request, session.getSessionId());
throw new IllegalStateException("Active session not found");
}
} else {
throw new UnsupportedFeatureException();
}
}
@Override
public boolean asyncCompleteRequest(String uniqueId, Confirmation confirmation) throws UnsupportedFeatureException, OccurenceConstraintException {
return session.completePendingPromise(uniqueId, confirmation);
}
@Override
public void handleError(
String uniqueId, String errorCode, String errorDescription, Object payload) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for error {}", errorDescription);
}
}
@Override
public void handleConnectionClosed() {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.lostSession(sessionIdOptional.get());
sessions.remove(sessionIdOptional.get());
} else {
logger.warn("Active session not found for {}", session.getSessionId());
}
}
@Override
public void handleConnectionOpened() {}
});
sessions.put(session.getSessionId(), session);
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.newSession(sessionIdOptional.get(), information);
logger.debug("Session created: {}", session.getSessionId());
} else {
throw new IllegalStateException("Failed to create a session");
}
}
});
}
private Optional<UUID> getSessionID(ISession session) {
if (!sessions.containsKey(session.getSessionId())) {
return Optional.empty();
}
return Optional.of(session.getSessionId());
}
/** Close all connections and stop listening for clients. */
public void close() {
listener.close();
}
/**
* Send a message to a client.
*
* @param sessionIndex Session index of the client.
* @param request Request for the client.
* @return Callback handler for when the client responds.
* @throws UnsupportedFeatureException Thrown if the feature isn't among the list of supported
* featured.
* @throws OccurenceConstraintException Thrown if the request isn't valid.
*/
public CompletableFuture<Confirmation> send(UUID sessionIndex, Request request)
throws UnsupportedFeatureException, OccurenceConstraintException, NotConnectedException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (!featureOptional.isPresent()) {
throw new UnsupportedFeatureException();
}
if (!request.validate()) {
throw new OccurenceConstraintException();
}
ISession session = sessions.get(sessionIndex);
if (session == null) {
logger.warn("Session not found by index: {}", sessionIndex);
// No session found means client disconnected and request should be cancelled
throw new NotConnectedException();
}
String id = session.storeRequest(request);
CompletableFuture<Confirmation> promise = promiseRepository.createPromise(id);
session.sendRequest(featureOptional.get().getAction(), request, id);
return promise;
}
/**
* Indicate completion of a pending request.
*
* @param sessionIndex Session index of the client.
* @param uniqueId the unique id used for the original {@link Request}.
* @param confirmation the {@link Confirmation} to the original {@link Request}.
* @return a boolean indicating if pending request was found.
* @throws NotConnectedException Thrown if session with passed sessionIndex is not found
*/
public boolean asyncCompleteRequest(UUID sessionIndex, String uniqueId, Confirmation confirmation) throws NotConnectedException, UnsupportedFeatureException, OccurenceConstraintException {
ISession session = sessions.get(sessionIndex);
if (session == null) {
logger.warn("Session not found by index: {}", sessionIndex);
// No session found means client disconnected and request should be cancelled
throw new NotConnectedException();
}
return session.completePendingPromise(uniqueId, confirmation);
}
public boolean isSessionOpen(UUID sessionIndex) {
return sessions.containsKey(sessionIndex);
}
/**
* Close connection to a client
*
* @param sessionIndex Session index of the client.
*/
public void closeSession(UUID sessionIndex) {
ISession session = sessions.get(sessionIndex);
if (session != null) {
session.close();
}
}
} |
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.template.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.util.*;
public class CmsXmlWpTemplateFile extends CmsXmlTemplateFile implements I_CmsLogChannels {
private Hashtable m_wpTags = new Hashtable();
/** Reference to the actual language file. */
private CmsXmlLanguageFile m_languageFile = null;
/**
* Default constructor.
*/
public CmsXmlWpTemplateFile() throws CmsException {
super();
registerMyTags();
}
/**
* Constructor for creating a new object containing the content
* of the given filename.
*
* @param cms A_CmsObject object for accessing system resources.
* @param filename Name of the body file that shoul be read.
*/
public CmsXmlWpTemplateFile(A_CmsObject cms, String filename) throws CmsException {
super();
registerMyTags();
init(cms, filename);
}
/**
* Constructor for creating a new object containing the content
* of the given filename.
*
* @param cms A_CmsObject object for accessing system resources.
* @param filename Name of the body file that shoul be read.
*/
public CmsXmlWpTemplateFile(A_CmsObject cms, CmsFile file) throws CmsException {
super();
registerMyTags();
init(cms, file);
}
/**
* Overridden init method of A_CmsXmlContent.
* This method is now extended to get an actual instance of the
* language file.
* @param cms A_CmsObject Object for accessing resources.
* @param file CmsFile object of the file to be loaded and parsed.
* @exception CmsException
*/
public void init(A_CmsObject cms, String filename) throws CmsException {
m_languageFile = new CmsXmlLanguageFile(cms);
super.init(cms, filename);
}
/**
* Overridden init method of A_CmsXmlContent.
* This method is now extended to get an actual instance of the
* language file.
* @param cms A_CmsObject Object for accessing resources.
* @param file CmsFile object of the file to be loaded and parsed.
* @exception CmsException
*/
public void init(A_CmsObject cms, CmsFile file) throws CmsException {
m_languageFile = new CmsXmlLanguageFile(cms);
super.init(cms, file);
}
/**
* Registers the special tags for processing with
* processNode().
*/
private void registerMyTags() {
registerTag("BUTTON", "com.opencms.workplace.CmsButton");
registerTag("BUTTONSEPARATOR", "com.opencms.workplace.CmsButtonSeparator");
registerTag("LABEL", "com.opencms.workplace.CmsLabel");
registerTag("INPUTFIELD", "com.opencms.workplace.CmsInput");
}
/**
* Special registerTag method for this content definition class.
* Any workplace XML tag will be registered with the superclass for handling with
* the method <code>handleAnyTag()</code> in this class.
* Then the tagname together with the name of the class for the template
* element (e.g. <code>CmsButton</code> or <code>CmsLabel</code>) will be put in an internal Hashtable.
* <P>
* Every workplace element class used by this method has to implement the interface
* <code>I_CmsWpElement</code>
*
* @param tagname XML tag to be registered as a special workplace tag.
* @param elementClassName Appropriate workplace element class name for this tag.
* @see com.opencms.workplace.I_CmsWpElement
*/
private void registerTag(String tagname, String elementClassName) {
super.registerTag(tagname, CmsXmlWpTemplateFile.class, "handleAnyTag", C_REGISTER_MAIN_RUN);
m_wpTags.put(tagname.toLowerCase(), elementClassName);
}
/**
* Gets the expected tagname for the XML documents of this content type
* @return Expected XML tagname.
*/
public String getXmlDocumentTagName() {
return "WORKPLACE";
}
/**
* Gets the actual instance of the language file.
* @return Language file.
*/
public CmsXmlLanguageFile getLanguageFile() {
return m_languageFile;
}
/**
* Gets the processed data of the <code><TEMPLATE></code> section of
* this workplace template file.
*
* @param callingObject reference to the calling object. Used to look up user methods while processing.
* @param parameters hashtable containing all user parameters.
* @return Processed template data.
* @exception CmsException
*/
public String getProcessedTemplateContent(Object callingObject, Hashtable parameters) throws CmsException {
return getProcessedDataValue("TEMPLATE", callingObject, parameters);
}
/**
* Handles any occurence of any special workplace XML tag like <code><BUTTON></code> or
* <code><LABEL></code>. Looks up the appropriate workplace element class for the current
* tag and calls the <code>handleSpecialWorkplaceTag()</code> method of this class.
* <P>
* Every workplace element class used by this method has to implement the interface
* <code>I_CmsWpElement</code>
*
* @param n XML element containing the current special workplace tag.
* @param callingObject reference to the calling object <em>(not used here)</em>.
* @param userObj hashtable containig all user parameters.
* @exception CmsException
* @see com.opencms.workplace.I_CmsWpElement
*/
public Object handleAnyTag(Element n, Object callingObject, Object userObj) throws CmsException {
Object result = null;
I_CmsWpElement workplaceObject = null;
String tagname = n.getTagName().toLowerCase();
String classname = null;
classname = (String)m_wpTags.get(tagname);
if(classname == null || "".equals(classname)) {
throwException("Don't know which class handles " + tagname + " tags.");
}
Object loadedClass = CmsTemplateClassManager.getClassInstance(m_cms, classname);
if(!(loadedClass instanceof I_CmsWpElement)) {
throwException("Loaded class " + classname + " is not implementing I_CmsWpElement");
}
workplaceObject = (I_CmsWpElement)loadedClass;
result = workplaceObject.handleSpecialWorkplaceTag(m_cms, n, (Hashtable)userObj, m_languageFile);
return result;
}
} |
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyjc.io;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import wyjc.attributes.WhileyDefine;
import wyjc.attributes.WhileyVersion;
import wybs.lang.Path;
import wybs.lang.SyntaxError;
import wyil.*;
import static wybs.lang.SyntaxError.*;
import wyil.util.*;
import wyil.lang.*;
import wyil.lang.Code.*;
import static wyil.lang.Block.*;
import wyjc.runtime.BigRational;
import wyjvm.attributes.Code.Handler;
import wyjvm.attributes.LineNumberTable;
import wyjvm.attributes.SourceFile;
import wyjvm.io.BinaryOutputStream;
import wyjvm.lang.*;
import wyjvm.lang.Modifier;
import static wyjvm.lang.JvmTypes.*;
/**
* The purpose of the class file builder is to construct a jvm class file from a
* given WhileyFile.
*
* @author David J. Pearce
*/
public class ClassFileBuilder {
protected int CLASS_VERSION = 49;
protected int WHILEY_MINOR_VERSION;
protected int WHILEY_MAJOR_VERSION;
protected String filename;
protected JvmType.Clazz owner;
public ClassFileBuilder(int whileyMajorVersion, int whileyMinorVersion) {
this.WHILEY_MINOR_VERSION = whileyMinorVersion;
this.WHILEY_MAJOR_VERSION = whileyMajorVersion;
}
public ClassFile build(WyilFile module) {
owner = new JvmType.Clazz(module.id().parent().toString().replace('.','/'),
module.id().last());
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_FINAL);
ClassFile cf = new ClassFile(49, owner, JAVA_LANG_OBJECT,
new ArrayList<JvmType.Clazz>(), modifiers);
this.filename = module.filename();
if(filename != null) {
cf.attributes().add(new SourceFile(filename));
}
boolean addMainLauncher = false;
for(WyilFile.ConstDef cd : module.constants()) {
// FIXME: this is an ugly hack for now
ArrayList<BytecodeAttribute> attrs = new ArrayList<BytecodeAttribute>();
for(Attribute a : cd.attributes()) {
if(a instanceof BytecodeAttribute) {
attrs.add((BytecodeAttribute)a);
}
}
WhileyDefine wd = new WhileyDefine(cd.name(),cd.constant(),attrs);
cf.attributes().add(wd);
}
for(WyilFile.TypeDef td : module.types()) {
// FIXME: this is an ugly hack for now
ArrayList<BytecodeAttribute> attrs = new ArrayList<BytecodeAttribute>();
for(Attribute a : td.attributes()) {
if(a instanceof BytecodeAttribute) {
attrs.add((BytecodeAttribute)a);
}
}
Type t = td.type();
WhileyDefine wd = new WhileyDefine(td.name(),t,attrs);
cf.attributes().add(wd);
}
HashMap<Constant,Integer> constants = new HashMap<Constant,Integer>();
for(WyilFile.Method method : module.methods()) {
if(method.name().equals("main")) {
addMainLauncher = true;
}
cf.methods().addAll(build(method, constants));
}
buildConstants(constants,cf);
if(addMainLauncher) {
cf.methods().add(buildMainLauncher(owner));
}
cf.attributes().add(
new WhileyVersion(WHILEY_MAJOR_VERSION, WHILEY_MINOR_VERSION));
return cf;
}
public void buildConstants(HashMap<Constant,Integer> constants, ClassFile cf) {
buildCoercions(constants,cf);
buildValues(constants,cf);
}
public void buildCoercions(HashMap<Constant,Integer> constants, ClassFile cf) {
HashSet<Constant> done = new HashSet<Constant>();
HashMap<Constant,Integer> original = constants;
// this could be a little more efficient I think!!
while(done.size() != constants.size()) {
// We have to clone the constants map, since it may be expanded as a
// result of buildCoercion(). This will occur if the coercion
// constructed requires a helper coercion that was not in the
// original constants map.
HashMap<Constant,Integer> nconstants = new HashMap<Constant,Integer>(constants);
for(Map.Entry<Constant,Integer> entry : constants.entrySet()) {
Constant e = entry.getKey();
if(!done.contains(e) && e instanceof Coercion) {
Coercion c = (Coercion) e;
buildCoercion(c.from,c.to,entry.getValue(),nconstants,cf);
}
done.add(e);
}
constants = nconstants;
}
original.putAll(constants);
}
public void buildValues(HashMap<Constant,Integer> constants, ClassFile cf) {
int nvalues = 0;
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
for(Map.Entry<Constant,Integer> entry : constants.entrySet()) {
Constant c = entry.getKey();
if(c instanceof ValueConst) {
nvalues++;
Value constant = ((ValueConst)c).value;
int index = entry.getValue();
// First, create the static final field that will hold this constant
String name = "constant$" + index;
ArrayList<Modifier> fmods = new ArrayList<Modifier>();
fmods.add(Modifier.ACC_PRIVATE);
fmods.add(Modifier.ACC_STATIC);
fmods.add(Modifier.ACC_FINAL);
JvmType type = convertType(constant.type());
ClassFile.Field field = new ClassFile.Field(name, type, fmods);
cf.fields().add(field);
// Now, create code to intialise this field
translate(constant,0,bytecodes);
bytecodes.add(new Bytecode.PutField(owner, name, type, Bytecode.STATIC));
}
}
if(nvalues > 0) {
// create static initialiser method, but only if we really need to.
bytecodes.add(new Bytecode.Return(null));
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ftype = new JvmType.Function(new JvmType.Void());
ClassFile.Method clinit = new ClassFile.Method("<clinit>", ftype, modifiers);
cf.methods().add(clinit);
// finally add code for staticinitialiser method
wyjvm.attributes.Code code = new wyjvm.attributes.Code(bytecodes,new ArrayList(),clinit);
clinit.attributes().add(code);
}
}
public ClassFile.Method buildMainLauncher(JvmType.Clazz owner) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ft1 = new JvmType.Function(T_VOID, new JvmType.Array(JAVA_LANG_STRING));
ClassFile.Method cm = new ClassFile.Method("main",ft1,modifiers);
JvmType.Array strArr = new JvmType.Array(JAVA_LANG_STRING);
ArrayList<Bytecode> codes = new ArrayList<Bytecode>();
ft1 = new JvmType.Function(WHILEYRECORD,new JvmType.Array(JAVA_LANG_STRING));
codes.add(new Bytecode.Load(0,strArr));
codes.add(new Bytecode.Invoke(WHILEYUTIL,"systemConsole",ft1,Bytecode.STATIC));
Type.Method wyft = Type.Method(Type.T_VOID, Type.T_VOID, WHILEY_SYSTEM_T);
JvmType.Function ft3 = convertFunType(wyft);
// The following is a little bit of hack. Basically we flush the stdout
// channel on exit
codes.add(new Bytecode.Invoke(owner, nameMangle("main",wyft), ft3, Bytecode.STATIC));
ft3 = new JvmType.Function(T_VOID);
codes.add(new Bytecode.Invoke(new JvmType.Clazz(
"whiley.io", "File$native"), "flush", ft3,
Bytecode.STATIC));
codes.add(new Bytecode.Return(null));
wyjvm.attributes.Code code = new wyjvm.attributes.Code(codes,
new ArrayList(), cm);
cm.attributes().add(code);
return cm;
}
public List<ClassFile.Method> build(WyilFile.Method method,
HashMap<Constant, Integer> constants) {
ArrayList<ClassFile.Method> methods = new ArrayList<ClassFile.Method>();
int num = 1;
for(WyilFile.Case c : method.cases()) {
if(method.isNative()) {
methods.add(buildNativeOrExport(c,method,constants));
} else {
if(method.isExport()) {
methods.add(buildNativeOrExport(c,method,constants));
}
methods.add(build(num++,c,method,constants));
}
}
return methods;
}
public ClassFile.Method build(int caseNum, WyilFile.Case mcase,
WyilFile.Method method, HashMap<Constant,Integer> constants) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
if(method.isPublic()) {
modifiers.add(Modifier.ACC_PUBLIC);
}
modifiers.add(Modifier.ACC_STATIC);
JvmType.Function ft = convertFunType(method.type());
String name = nameMangle(method.name(),method.type());
/* need to put this back somehow?
if(method.cases().size() > 1) {
name = name + "$" + caseNum;
}
*/
ClassFile.Method cm = new ClassFile.Method(name,ft,modifiers);
for(Attribute a : mcase.attributes()) {
if(a instanceof BytecodeAttribute) {
// FIXME: this is a hack
cm.attributes().add((BytecodeAttribute)a);
}
}
ArrayList<Handler> handlers = new ArrayList<Handler>();
ArrayList<LineNumberTable.Entry> lineNumbers = new ArrayList<LineNumberTable.Entry>();
ArrayList<Bytecode> codes;
codes = translate(mcase,constants,handlers,lineNumbers);
wyjvm.attributes.Code code = new wyjvm.attributes.Code(codes,handlers,cm);
if(!lineNumbers.isEmpty()) {
code.attributes().add(new LineNumberTable(lineNumbers));
}
cm.attributes().add(code);
return cm;
}
public ClassFile.Method buildNativeOrExport(WyilFile.Case mcase,
WyilFile.Method method, HashMap<Constant,Integer> constants) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
if(method.isPublic()) {
modifiers.add(Modifier.ACC_PUBLIC);
}
modifiers.add(Modifier.ACC_STATIC);
JvmType.Function ft = convertFunType(method.type());
String name = method.name();
if(method.isNative()) {
name = nameMangle(method.name(),method.type());
}
ClassFile.Method cm = new ClassFile.Method(name,ft,modifiers);
for(Attribute a : mcase.attributes()) {
if(a instanceof BytecodeAttribute) {
// FIXME: this is a hack
cm.attributes().add((BytecodeAttribute)a);
}
}
ArrayList<Handler> handlers = new ArrayList<Handler>();
ArrayList<Bytecode> codes;
codes = translateNativeOrExport(method);
wyjvm.attributes.Code code = new wyjvm.attributes.Code(codes,handlers,cm);
cm.attributes().add(code);
return cm;
}
public ArrayList<Bytecode> translateNativeOrExport(WyilFile.Method method) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
Type.FunctionOrMethodOrMessage ft = method.type();
int slot = 0;
// first, check to see if need to load receiver
if (ft instanceof Type.Message) {
Type.Message mt = (Type.Message) ft;
if (mt.receiver() != null) {
bytecodes.add(new Bytecode.Load(slot++, convertType(mt
.receiver())));
}
}
for (Type param : ft.params()) {
bytecodes.add(new Bytecode.Load(slot++, convertType(param)));
}
if (method.isNative()) {
JvmType.Clazz redirect = new JvmType.Clazz(owner.pkg(), owner
.components().get(0).first(), "native");
bytecodes.add(new Bytecode.Invoke(redirect, method.name(),
convertFunType(ft), Bytecode.STATIC));
} else {
JvmType.Clazz redirect = new JvmType.Clazz(owner.pkg(), owner
.components().get(0).first());
bytecodes.add(new Bytecode.Invoke(redirect, nameMangle(
method.name(), method.type()), convertFunType(ft),
Bytecode.STATIC));
}
if (ft.ret() == Type.T_VOID) {
bytecodes.add(new Bytecode.Return(null));
} else {
bytecodes.add(new Bytecode.Return(convertType(ft.ret())));
}
return bytecodes;
}
public ArrayList<Bytecode> translate(WyilFile.Case mcase,
HashMap<Constant, Integer> constants, ArrayList<Handler> handlers,
ArrayList<LineNumberTable.Entry> lineNumbers) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
translate(mcase.body(), mcase.body().numSlots(), constants, handlers,
lineNumbers, bytecodes);
return bytecodes;
}
public void translate(Block blk, int freeSlot,
HashMap<Constant, Integer> constants,
ArrayList<Handler> handlers,
ArrayList<LineNumberTable.Entry> lineNumbers,
ArrayList<Bytecode> bytecodes) {
ArrayList<UnresolvedHandler> unresolvedHandlers = new ArrayList<UnresolvedHandler>();
for (Entry s : blk) {
Attribute.Source loc = s.attribute(Attribute.Source.class);
if(loc != null) {
lineNumbers.add(new LineNumberTable.Entry(bytecodes.size(),loc.line));
}
freeSlot = translate(s, freeSlot, constants, unresolvedHandlers,
bytecodes);
}
if (unresolvedHandlers.size() > 0) {
HashMap<String, Integer> labels = new HashMap<String, Integer>();
for (int i = 0; i != bytecodes.size(); ++i) {
Bytecode b = bytecodes.get(i);
if (b instanceof Bytecode.Label) {
Bytecode.Label lab = (Bytecode.Label) b;
labels.put(lab.name, i);
}
}
for (UnresolvedHandler ur : unresolvedHandlers) {
int start = labels.get(ur.start);
int end = labels.get(ur.end);
Handler handler = new Handler(start, end, ur.target,
ur.exception);
handlers.add(handler);
}
}
// here, we need to resolve the handlers.
}
public int translate(Entry entry, int freeSlot,
HashMap<Constant, Integer> constants,
ArrayList<UnresolvedHandler> handlers, ArrayList<Bytecode> bytecodes) {
try {
Code code = entry.code;
if(code instanceof BinOp) {
translate((BinOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof Convert) {
translate((Convert)code,freeSlot,constants,bytecodes);
} else if(code instanceof Const) {
translate((Const) code, freeSlot, constants, bytecodes);
} else if(code instanceof Debug) {
translate((Debug)code,freeSlot,bytecodes);
} else if(code instanceof LoopEnd) {
translate((LoopEnd)code,freeSlot,bytecodes);
} else if(code instanceof Assert) {
translate((Assert)code,entry,freeSlot,bytecodes);
} else if(code instanceof FieldLoad) {
translate((FieldLoad)code,freeSlot,bytecodes);
} else if(code instanceof ForAll) {
freeSlot = translate((ForAll)code,freeSlot,bytecodes);
} else if(code instanceof Goto) {
translate((Goto)code,freeSlot,bytecodes);
} else if(code instanceof IfGoto) {
translateIfGoto((IfGoto) code, entry, freeSlot, bytecodes);
} else if(code instanceof IfType) {
translate((IfType) code, entry, freeSlot, constants, bytecodes);
} else if(code instanceof IndirectInvoke) {
translate((IndirectInvoke)code,freeSlot,bytecodes);
} else if(code instanceof IndirectSend) {
translate((IndirectSend)code,freeSlot,bytecodes);
} else if(code instanceof Invoke) {
translate((Invoke)code,freeSlot,bytecodes);
} else if(code instanceof Invert) {
translate((Invert)code,freeSlot,bytecodes);
} else if(code instanceof Label) {
translate((Label)code,freeSlot,bytecodes);
} else if(code instanceof ListOp) {
translate((ListOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof LengthOf) {
translate((LengthOf)code,entry,freeSlot,bytecodes);
} else if(code instanceof SubList) {
translate((SubList)code,entry,freeSlot,bytecodes);
} else if(code instanceof IndexOf) {
translate((IndexOf)code,freeSlot,bytecodes);
} else if(code instanceof Copy) {
translate((Copy)code,freeSlot,bytecodes);
} else if(code instanceof Loop) {
translate((Loop)code,freeSlot,bytecodes);
} else if(code instanceof Move) {
translate((Move)code,freeSlot,bytecodes);
} else if(code instanceof Update) {
translate((Update)code,freeSlot,bytecodes);
} else if(code instanceof NewDict) {
translate((NewDict)code,freeSlot,bytecodes);
} else if(code instanceof NewList) {
translate((NewList)code,freeSlot,bytecodes);
} else if(code instanceof NewRecord) {
translate((NewRecord)code,freeSlot,bytecodes);
} else if(code instanceof NewSet) {
translate((NewSet)code,freeSlot,bytecodes);
} else if(code instanceof NewTuple) {
translate((NewTuple)code,freeSlot,bytecodes);
} else if(code instanceof Negate) {
translate((Negate)code,freeSlot,bytecodes);
} else if(code instanceof Dereference) {
translate((Dereference)code,freeSlot,bytecodes);
} else if(code instanceof Return) {
translate((Return)code,freeSlot,bytecodes);
} else if(code instanceof Nop) {
// do nothing
} else if(code instanceof Send) {
translate((Send)code,freeSlot,bytecodes);
} else if(code instanceof SetOp) {
translate((SetOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof StringOp) {
translate((StringOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof SubString) {
translate((SubString)code,entry,freeSlot,bytecodes);
} else if(code instanceof Switch) {
translate((Switch)code,entry,freeSlot,bytecodes);
} else if(code instanceof TryCatch) {
translate((TryCatch)code,entry,freeSlot,handlers,constants,bytecodes);
} else if(code instanceof New) {
translate((New)code,freeSlot,bytecodes);
} else if(code instanceof Throw) {
translate((Throw)code,freeSlot,bytecodes);
} else if(code instanceof TupleLoad) {
translate((TupleLoad)code,freeSlot,bytecodes);
} else {
internalFailure("unknown wyil code encountered (" + code + ")", filename, entry);
}
} catch (SyntaxError ex) {
throw ex;
} catch (Exception ex) {
internalFailure(ex.getMessage(), filename, entry, ex);
}
return freeSlot;
}
public void translate(Code.Const c, int freeSlot,
HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
Value constant = c.constant;
JvmType jt = convertType(constant.type());
if (constant instanceof Value.Rational || constant instanceof Value.Bool
|| constant instanceof Value.Null || constant instanceof Value.Byte) {
translate(constant,freeSlot,bytecodes);
} else {
int id = ValueConst.get(constant,constants);
String name = "constant$" + id;
bytecodes.add(new Bytecode.GetField(owner, name, jt, Bytecode.STATIC));
// the following is necessary to prevent in-place updates of our
// constants!
addIncRefs(constant.type(),bytecodes);
}
bytecodes.add(new Bytecode.Store(c.target, jt));
}
public void translate(Code.Convert c, int freeSlot,
HashMap<Constant, Integer> constants, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type)));
addCoercion(c.type, c.result, freeSlot, constants, bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.result)));
}
public void translate(Code.Update code, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(code.target, convertType(code.type)));
translateUpdate(code.iterator(), code, bytecodes);
bytecodes.add(new Bytecode.Store(code.target,
convertType(code.afterType)));
}
public void translateUpdate(Iterator<Code.LVal> iterator, Code.Update code,
ArrayList<Bytecode> bytecodes) {
LVal lv = iterator.next();
if(lv instanceof ListLVal) {
ListLVal l = (ListLVal) lv;
if(iterator.hasNext()) {
// In this case, we're partially updating the element at a
// given position.
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.Load(l.indexOperand,BIG_INTEGER));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYLIST,BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "internal_get", ftype,
Bytecode.STATIC));
addReadConversion(l.type().element(),bytecodes);
translateUpdate(iterator,code,bytecodes);
bytecodes.add(new Bytecode.Load(l.indexOperand,BIG_INTEGER));
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.Load(l.indexOperand,BIG_INTEGER));
bytecodes.add(new Bytecode.Load(code.operand, convertType(l
.type().element())));
addWriteConversion(code.rhs(),bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,
WHILEYLIST,BIG_INTEGER,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "set", ftype,
Bytecode.STATIC));
} else if(lv instanceof StringLVal) {
StringLVal l = (StringLVal) lv;
// assert: level must be zero here
bytecodes.add(new Bytecode.Load(l.indexOperand, BIG_INTEGER));
bytecodes.add(new Bytecode.Load(code.operand, T_CHAR));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,
JAVA_LANG_STRING, BIG_INTEGER, T_CHAR);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "set", ftype,
Bytecode.STATIC));
} else if(lv instanceof DictLVal) {
DictLVal l = (DictLVal) lv;
JvmType keyType = convertType(l.type().key());
JvmType valueType = convertType(l.type().value());
if(iterator.hasNext()) {
// In this case, we're partially updating the element at a
// given position.
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.type().key(),bytecodes);
JvmType.Function ftype = new JvmType.Function(
JAVA_LANG_OBJECT, WHILEYMAP, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "internal_get", ftype,
Bytecode.STATIC));
addReadConversion(l.type().value(),bytecodes);
translateUpdate(iterator,code,bytecodes);
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.type().key(),bytecodes);
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.type().key(),bytecodes);
bytecodes.add(new Bytecode.Load(code.operand, valueType));
addWriteConversion(l.type().value(),bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYMAP,
WHILEYMAP,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.STATIC));
} else if(lv instanceof RecordLVal) {
RecordLVal l = (RecordLVal) lv;
Type.EffectiveRecord type = l.type();
if (iterator.hasNext()) {
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(l.field));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYRECORD, JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD, "internal_get",
ftype, Bytecode.STATIC));
addReadConversion(type.field(l.field), bytecodes);
translateUpdate(iterator, code, bytecodes);
bytecodes.add(new Bytecode.LoadConst(l.field));
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.LoadConst(l.field));
bytecodes.add(new Bytecode.Load(code.operand, convertType(type
.field(l.field))));
addWriteConversion(type.field(l.field), bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYRECORD,WHILEYRECORD,JAVA_LANG_STRING,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.STATIC));
} else {
ReferenceLVal l = (ReferenceLVal) lv;
bytecodes.add(new Bytecode.Dup(WHILEYPROCESS));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "state", ftype,
Bytecode.VIRTUAL));
addReadConversion(l.type().element(), bytecodes);
translateUpdate(iterator, code, bytecodes);
ftype = new JvmType.Function(WHILEYPROCESS, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "setState", ftype,
Bytecode.VIRTUAL));
}
}
public void translate(Code.Return c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if (c.type == Type.T_VOID) {
bytecodes.add(new Bytecode.Return(null));
} else {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand,jt));
bytecodes.add(new Bytecode.Return(jt));
}
}
public void translate(Code.Throw c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Dup(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Load(c.operand,convertType(c.type)));
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYEXCEPTION, "<init>", ftype,
Bytecode.SPECIAL));
bytecodes.add(new Bytecode.Throw());
}
public void translate(Code.TupleLoad c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYTUPLE, T_INT);
bytecodes.add(new Bytecode.Load(c.operand,convertType((Type) c.type)));
bytecodes.add(new Bytecode.LoadConst(c.index));
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "get", ftype,
Bytecode.STATIC));
addReadConversion(c.type.elements().get(c.index), bytecodes);
bytecodes.add(new Bytecode.Store(c.target,convertType(c.type
.element(c.index))));
}
public void translate(Code.Switch c, Block.Entry entry, int freeSlot,
ArrayList<Bytecode> bytecodes) {
ArrayList<Pair<Integer, String>> cases = new ArrayList();
boolean canUseSwitchBytecode = true;
for (Pair<Value, String> p : c.branches) {
// first, check whether the switch value is indeed an integer.
Value v = (Value) p.first();
if (!(v instanceof Value.Integer)) {
canUseSwitchBytecode = false;
break;
}
// second, check whether integer value can fit into a Java int
Value.Integer vi = (Value.Integer) v;
int iv = vi.value.intValue();
if (!BigInteger.valueOf(iv).equals(vi.value)) {
canUseSwitchBytecode = false;
break;
}
// ok, we're all good so far
cases.add(new Pair(iv, p.second()));
}
bytecodes.add(new Bytecode.Load(c.operand,convertType((Type) c.type)));
if (canUseSwitchBytecode) {
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER, "intValue", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Switch(c.defaultTarget, cases));
} else {
// ok, in this case we have to fall back to series of the if
// conditions. Not ideal.
for (Pair<Value, String> p : c.branches) {
Value value = p.first();
String target = p.second();
translate(value, freeSlot, bytecodes);
bytecodes
.add(new Bytecode.Load(c.operand, convertType(c.type)));
translateIfGoto(value.type(), Code.COp.EQ, target, entry,
freeSlot + 1, bytecodes);
}
bytecodes.add(new Bytecode.Goto(c.defaultTarget));
}
}
public void translate(Code.TryCatch c, Block.Entry entry, int freeSlot,
ArrayList<UnresolvedHandler> handlers,
HashMap<Constant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// this code works by redirecting *all* whiley exceptions into the
// trampoline block. The trampoline then pulls out the matching ones,
// and lets the remainder be rethrown.
String start = freshLabel();
String trampolineStart = freshLabel();
bytecodes.add(new Bytecode.Goto(start));
// trampoline goes here
bytecodes.add(new Bytecode.Label(trampolineStart));
bytecodes.add(new Bytecode.Dup(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Store(freeSlot, WHILEYEXCEPTION));
bytecodes.add(new Bytecode.GetField(WHILEYEXCEPTION, "value", JAVA_LANG_OBJECT, Bytecode.NONSTATIC));
ArrayList<String> bounces = new ArrayList<String>();
for (Pair<Type, String> handler : c.catches) {
String bounce = freshLabel();
bounces.add(bounce);
bytecodes.add(new Bytecode.Dup(JAVA_LANG_OBJECT));
translateTypeTest(bounce, Type.T_ANY, handler.first(),
bytecodes, constants);
}
// rethrow what doesn't match
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Load(freeSlot, WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Throw());
for(int i=0;i!=bounces.size();++i) {
String bounce = bounces.get(i);
Pair<Type,String> handler = c.catches.get(i);
bytecodes.add(new Bytecode.Label(bounce));
addReadConversion(handler.first(),bytecodes);
bytecodes.add(new Bytecode.Goto(handler.second()));
}
bytecodes.add(new Bytecode.Label(start));
UnresolvedHandler trampolineHandler = new UnresolvedHandler(start,
c.label, trampolineStart, WHILEYEXCEPTION);
handlers.add(trampolineHandler);
}
public void translateIfGoto(Code.IfGoto code, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(code.type);
bytecodes.add(new Bytecode.Load(code.leftOperand,jt));
bytecodes.add(new Bytecode.Load(code.rightOperand,jt));
translateIfGoto(code.type,code.op,code.target,stmt,freeSlot,bytecodes);
}
public void translateIfGoto(Type c_type, Code.COp cop, String target, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c_type);
if(c_type == Type.T_BOOL) {
// boolean is a special case, since it is not implemented as an
// object on the JVM stack. Therefore, we need to use the "if_cmp"
// bytecode, rather than calling .equals() and using "if" bytecode.
switch(cop) {
case EQ:
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.EQ, type, target));
break;
case NEQ:
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.NE, type, target));
break;
}
} else if(c_type == Type.T_CHAR || c_type == Type.T_BYTE) {
int op;
switch(cop) {
case EQ:
op = Bytecode.IfCmp.EQ;
break;
case NEQ:
op = Bytecode.IfCmp.NE;
break;
case LT:
op = Bytecode.IfCmp.LT;
break;
case LTEQ:
op = Bytecode.IfCmp.LE;
break;
case GT:
op = Bytecode.IfCmp.GT;
break;
case GTEQ:
op = Bytecode.IfCmp.GE;
break;
default:
internalFailure("unknown if condition encountered",filename,stmt);
return;
}
bytecodes.add(new Bytecode.IfCmp(op, T_BYTE,target));
} else {
// Non-primitive case. Just use the Object.equals() method, followed
// by "if" bytecode.
int op;
switch(cop) {
case EQ:
{
if(Type.isSubtype(c_type, Type.T_NULL)) {
// this indicates an interesting special case. The left
// handside of this equality can be null. Therefore, we
// cannot directly call "equals()" on this method, since
// this would cause a null pointer exception!
JvmType.Function ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "equals", ftype,
Bytecode.STATIC));
} else {
JvmType.Function ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "equals", ftype,
Bytecode.VIRTUAL));
}
op = Bytecode.If.NE;
break;
}
case NEQ:
{
if (Type.isSubtype(c_type, Type.T_NULL)) {
// this indicates an interesting special case. The left
// handside of this equality can be null. Therefore, we
// cannot directly call "equals()" on this method, since
// this would cause a null pointer exception!
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "equals",
ftype, Bytecode.STATIC));
} else {
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"equals", ftype, Bytecode.VIRTUAL));
}
op = Bytecode.If.EQ;
break;
}
case LT:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type, "compareTo", ftype,
Bytecode.VIRTUAL));
op = Bytecode.If.LT;
break;
}
case LTEQ:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.VIRTUAL));
op = Bytecode.If.LE;
break;
}
case GT:
{
JvmType.Function ftype = new JvmType.Function(T_INT, type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.VIRTUAL));
op = Bytecode.If.GT;
break;
}
case GTEQ:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.VIRTUAL));
op = Bytecode.If.GE;
break;
}
case SUBSETEQ:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,WHILEYSET,WHILEYSET);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "subsetEq", ftype,
Bytecode.STATIC));
op = Bytecode.If.NE;
break;
}
case SUBSET:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,WHILEYSET,WHILEYSET);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "subset", ftype,
Bytecode.STATIC));
op = Bytecode.If.NE;
break;
}
case ELEMOF:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "contains",
ftype, Bytecode.INTERFACE));
op = Bytecode.If.NE;
break;
}
default:
syntaxError("unknown if condition encountered",filename,stmt);
return;
}
// do the jump
bytecodes.add(new Bytecode.If(op, target));
}
}
public void translate(Code.IfType c, Entry stmt, int freeSlot,
HashMap<Constant,Integer> constants, ArrayList<Bytecode> bytecodes) {
// In this case, we're updating the type of a local variable. To
// make this work, we must update the JVM type of that slot as well
// using a checkcast.
String exitLabel = freshLabel();
String trueLabel = freshLabel();
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type)));
translateTypeTest(trueLabel, c.type, c.rightOperand, bytecodes, constants);
Type gdiff = Type.intersect(c.type,Type.Negation(c.rightOperand));
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type)));
// now, add checkcast
addReadConversion(gdiff,bytecodes);
bytecodes.add(new Bytecode.Store(c.leftOperand,convertType(gdiff)));
bytecodes.add(new Bytecode.Goto(exitLabel));
bytecodes.add(new Bytecode.Label(trueLabel));
Type glb = Type.intersect(c.type, c.rightOperand);
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type)));
// now, add checkcast
addReadConversion(glb,bytecodes);
bytecodes.add(new Bytecode.Store(c.leftOperand,convertType(glb)));
bytecodes.add(new Bytecode.Goto(c.target));
bytecodes.add(new Bytecode.Label(exitLabel));
}
// The purpose of this method is to translate a type test. We're testing to
// see whether what's on the top of the stack (the value) is a subtype of
// the type being tested.
protected void translateTypeTest(String trueTarget, Type src, Type test,
ArrayList<Bytecode> bytecodes, HashMap<Constant,Integer> constants) {
// First, try for the easy cases
if (test instanceof Type.Null) {
// Easy case
bytecodes.add(new Bytecode.If(Bytecode.If.NULL, trueTarget));
} else if(test instanceof Type.Bool) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_BOOLEAN));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
} else if(test instanceof Type.Char) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_CHARACTER));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
} else if(test instanceof Type.Int) {
bytecodes.add(new Bytecode.InstanceOf(BIG_INTEGER));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
} else if(test instanceof Type.Real) {
bytecodes.add(new Bytecode.InstanceOf(BIG_RATIONAL));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
} else if(test instanceof Type.Strung) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_STRING));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
} else {
// Fall-back to an external (recursive) check
Value constant = Value.V_TYPE(test);
int id = ValueConst.get(constant,constants);
String name = "constant$" + id;
bytecodes.add(new Bytecode.GetField(owner, name, WHILEYTYPE, Bytecode.STATIC));
JvmType.Function ftype = new JvmType.Function(T_BOOL,convertType(src),WHILEYTYPE);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "instanceOf",
ftype, Bytecode.STATIC));
bytecodes.add(new Bytecode.If(Bytecode.If.NE, trueTarget));
}
}
public void translate(Code.Loop c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Label(c.target + "$head"));
}
protected void translate(Code.LoopEnd end,
int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Goto(end.label + "$head"));
bytecodes.add(new Bytecode.Label(end.label));
}
public int translate(Code.ForAll c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
Type elementType = c.type.element();
bytecodes.add(new Bytecode.Load(c.sourceOperand, convertType((Type) c.type)));
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "iterator", ftype, Bytecode.STATIC));
ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Store(freeSlot, JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Label(c.target + "$head"));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(freeSlot, JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext", ftype,
Bytecode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.If.EQ, c.target));
bytecodes.add(new Bytecode.Load(freeSlot, JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next", ftype,
Bytecode.INTERFACE));
addReadConversion(elementType, bytecodes);
bytecodes.add(new Bytecode.Store(c.indexOperand, convertType(elementType)));
// we need to increase the freeSlot, since we've allocated one slot to
// hold the iterator.
return freeSlot + 1;
}
public void translate(Code.Goto c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Goto(c.target));
}
public void translate(Code.Label c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Label(c.label));
}
public void translate(Code.Debug c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Load(c.operand, JAVA_LANG_STRING));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "debug", ftype,
Bytecode.STATIC));
}
public void translate(Code.Assert c, Block.Entry entry, int freeSlot,
ArrayList<Bytecode> bytecodes) {
String lab = freshLabel();
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.leftOperand, jt));
bytecodes.add(new Bytecode.Load(c.rightOperand, jt));
translateIfGoto(c.type, c.op, lab, entry, freeSlot, bytecodes);
bytecodes.add(new Bytecode.New(JAVA_LANG_RUNTIMEEXCEPTION));
bytecodes.add(new Bytecode.Dup(JAVA_LANG_RUNTIMEEXCEPTION));
bytecodes.add(new Bytecode.LoadConst(c.msg));
JvmType.Function ftype = new JvmType.Function(T_VOID, JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_RUNTIMEEXCEPTION, "<init>",
ftype, Bytecode.SPECIAL));
bytecodes.add(new Bytecode.Throw());
bytecodes.add(new Bytecode.Label(lab));
}
public void translate(Code.Copy c, int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, jt));
addIncRefs(c.type,bytecodes);
bytecodes.add(new Bytecode.Store(c.target, jt));
}
public void translate(Code.Move c, int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, jt));
bytecodes.add(new Bytecode.Store(c.target, jt));
}
public void translate(Code.ListOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
switch(c.operation) {
case APPEND:
leftType = WHILEYLIST;
rightType = WHILEYLIST;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
case LEFT_APPEND:
leftType = WHILEYLIST;
rightType = JAVA_LANG_OBJECT;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
break;
case RIGHT_APPEND:
leftType = JAVA_LANG_OBJECT;
rightType = WHILEYLIST;
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
default:
internalFailure("unknown list operation",filename,stmt);
return;
}
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,leftType,rightType);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "append", ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
public void translate(Code.LengthOf c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, convertType((Type) c.type)));
JvmType.Clazz ctype = JAVA_LANG_OBJECT;
JvmType.Function ftype = new JvmType.Function(BIG_INTEGER, ctype);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "length", ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, BIG_INTEGER));
}
public void translate(Code.SubList c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operands[0], WHILEYLIST));
bytecodes.add(new Bytecode.Load(c.operands[1], BIG_INTEGER));
bytecodes.add(new Bytecode.Load(c.operands[2], BIG_INTEGER));
JvmType.Function ftype = new JvmType.Function(WHILEYLIST, WHILEYLIST,
BIG_INTEGER, BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "sublist", ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
public void translate(Code.IndexOf c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.leftOperand, WHILEYLIST));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.key())));
addWriteConversion(c.type.key(),bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "indexOf", ftype,
Bytecode.STATIC));
addReadConversion(c.type.value(), bytecodes);
bytecodes.add(new Bytecode.Store(c.target,
convertType(c.type.element())));
}
public void translate(Code.FieldLoad c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(c.field));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,WHILEYRECORD,JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"get",ftype,Bytecode.STATIC));
addReadConversion(c.fieldType(),bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.fieldType())));
}
public void translate(Code.BinOp c, Block.Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
JvmType.Function ftype = new JvmType.Function(type,type);
// first, load operands
switch(c.bop) {
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
case BITWISEAND:
case BITWISEOR:
case BITWISEXOR:
bytecodes.add(new Bytecode.Load(c.leftOperand, type));
bytecodes.add(new Bytecode.Load(c.rightOperand, type));
break;
case LEFTSHIFT:
case RIGHTSHIFT:
bytecodes.add(new Bytecode.Load(c.leftOperand, type));
bytecodes.add(new Bytecode.Load(c.rightOperand, BIG_INTEGER));
break;
case RANGE:
bytecodes.add(new Bytecode.Load(c.leftOperand, BIG_INTEGER));
bytecodes.add(new Bytecode.Load(c.rightOperand, BIG_INTEGER));
break;
}
// second, apply operation
switch(c.bop) {
case ADD:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "add", ftype,
Bytecode.VIRTUAL));
break;
case SUB:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "subtract", ftype,
Bytecode.VIRTUAL));
break;
case MUL:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "multiply", ftype,
Bytecode.VIRTUAL));
break;
case DIV:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "divide", ftype,
Bytecode.VIRTUAL));
break;
case REM:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"remainder", ftype, Bytecode.VIRTUAL));
break;
case RANGE:
ftype = new JvmType.Function(WHILEYLIST,BIG_INTEGER,BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"range", ftype, Bytecode.STATIC));
break;
case BITWISEAND:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.AND,T_INT));
break;
case BITWISEOR:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.OR,T_INT));
break;
case BITWISEXOR:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.XOR,T_INT));
break;
case LEFTSHIFT:
ftype = new JvmType.Function(type,type,BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"leftshift", ftype, Bytecode.STATIC));
break;
case RIGHTSHIFT:
ftype = new JvmType.Function(type,type,BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"rightshift", ftype, Bytecode.STATIC));
break;
default:
internalFailure("unknown binary expression encountered",filename,stmt);
}
bytecodes.add(new Bytecode.Store(c.target, type));
}
public void translate(Code.SetOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
// First, load operands
switch(c.operation) {
case UNION:
case DIFFERENCE:
case INTERSECTION:
leftType = WHILEYSET;
rightType = WHILEYSET;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
case LEFT_UNION:
case LEFT_DIFFERENCE:
case LEFT_INTERSECTION:
leftType = WHILEYSET;
rightType = JAVA_LANG_OBJECT;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
break;
case RIGHT_UNION:
case RIGHT_INTERSECTION:
leftType = JAVA_LANG_OBJECT;
rightType = WHILEYSET;
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
default:
internalFailure("Unknown set operation encountered: ",filename,stmt);
return; // dead-code
}
JvmType.Function ftype= new JvmType.Function(WHILEYSET,leftType,rightType);
// Second, select operation
String operation;
switch(c.operation) {
case UNION:
case LEFT_UNION:
case RIGHT_UNION:
operation = "union";
break;
case INTERSECTION:
case LEFT_INTERSECTION:
case RIGHT_INTERSECTION:
operation = "intersect";
break;
case DIFFERENCE:
case LEFT_DIFFERENCE:
operation = "difference";
break;
default:
internalFailure("Unknown set operation encountered: ",filename,stmt);
return; // dead-code
}
bytecodes.add(new Bytecode.Invoke(WHILEYSET, operation, ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYSET));
}
public void translate(Code.StringOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
switch(c.operation) {
case APPEND:
leftType = JAVA_LANG_STRING;
rightType = JAVA_LANG_STRING;
break;
case LEFT_APPEND:
leftType = JAVA_LANG_STRING;
rightType = T_CHAR;
break;
case RIGHT_APPEND:
leftType = T_CHAR;
rightType = JAVA_LANG_STRING;
break;
default:
internalFailure("Unknown string operation encountered: ",filename,stmt);
return; // dead-code
}
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,leftType,rightType);
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "append", ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, JAVA_LANG_STRING));
}
public void translate(Code.SubString c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operands[0], JAVA_LANG_STRING));
bytecodes.add(new Bytecode.Load(c.operands[1], BIG_INTEGER));
bytecodes.add(new Bytecode.Load(c.operands[2], BIG_INTEGER));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,JAVA_LANG_STRING,
BIG_INTEGER, BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "substring", ftype,
Bytecode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, JAVA_LANG_STRING));
}
public void translate(Code.Invert c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, type));
bytecodes.add(new Bytecode.LoadConst(-1));
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.XOR, T_INT));
bytecodes.add(new Bytecode.Store(c.target, type));
}
public void translate(Code.Negate c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
JvmType.Function ftype = new JvmType.Function(type);
bytecodes.add(new Bytecode.Load(c.operand, type));
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type, "negate",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Store(c.target, type));
}
public void translate(Code.New c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
bytecodes.add(new Bytecode.New(WHILEYPROCESS));
bytecodes.add(new Bytecode.Dup(WHILEYPROCESS));
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type.element())));
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(T_VOID);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "start", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Store(c.target, type));
}
public void translate(Code.Dereference c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Load(c.operand, type));
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "state", ftype,
Bytecode.VIRTUAL));
// finally, we need to cast the object we got back appropriately.
Type.Reference pt = (Type.Reference) c.type;
addReadConversion(pt.element(), bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.type.element())));
}
protected void translate(Code.NewList c, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYLIST));
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.LoadConst(c.operands.length));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(WHILEYLIST, WHILEYLIST, JAVA_LANG_OBJECT);
for (int i = 0; i != c.operands.length; ++i) {
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(c.type
.element())));
addWriteConversion(c.type.element(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "internal_add",
ftype, Bytecode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
protected void translate(Code.NewDict c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
construct(WHILEYMAP, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
JvmType keyType = convertType(c.type.key());
JvmType valueType = convertType(c.type.value());
for (int i = 0; i != c.operands.length; i=i+2) {
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Load(c.operands[i], keyType));
addWriteConversion(c.type.key(), bytecodes);
bytecodes.add(new Bytecode.Load(c.operands[i + 1],valueType));
addWriteConversion(c.type.value(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYMAP));
}
public void translate(Code.NewRecord code, int freeSlot,
ArrayList<Bytecode> bytecodes) {
construct(WHILEYRECORD, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
HashMap<String,Type> fields = code.type.fields();
ArrayList<String> keys = new ArrayList<String>(fields.keySet());
Collections.sort(keys);
for (int i = 0; i != code.operands.length; i++) {
int register = code.operands[i];
String key = keys.get(i);
Type fieldType = fields.get(key);
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
bytecodes.add(new Bytecode.Load(register, convertType(fieldType)));
addWriteConversion(fieldType,bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Store(code.target, WHILEYRECORD));
}
protected void translate(Code.NewSet c, int freeSlot, ArrayList<Bytecode> bytecodes) {
construct(WHILEYSET, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(WHILEYSET,
WHILEYSET,JAVA_LANG_OBJECT);
for(int i=0;i!=c.operands.length;++i) {
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(c.type
.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYSET,"internal_add",ftype,Bytecode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYSET));
}
protected void translate(Code.NewTuple c, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYTUPLE ));
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE ));
bytecodes.add(new Bytecode.LoadConst(c.operands.length));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE , "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(WHILEYTUPLE , WHILEYTUPLE , JAVA_LANG_OBJECT);
for (int i = 0; i != c.operands.length; ++i) {
Type elementType = c.type.elements().get(i);
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(elementType)));
addWriteConversion(elementType, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE , "internal_add",
ftype, Bytecode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYTUPLE));
}
public void translate(Code.Invoke c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
for (int i = 0; i != c.operands.length; ++i) {
int register = c.operands[i];
JvmType parameterType = convertType(c.type.params().get(i));
bytecodes.add(new Bytecode.Load(register, parameterType));
}
Path.ID mid = c.name.module();
String mangled = nameMangle(c.name.name(), c.type);
JvmType.Clazz owner = new JvmType.Clazz(mid.parent().toString()
.replace('/', '.'), mid.last());
JvmType.Function type = convertFunType(c.type);
bytecodes
.add(new Bytecode.Invoke(owner, mangled, type, Bytecode.STATIC));
// now, handle the case of an invoke which returns a value that should
// be discarded.
if(c.target != Code.NULL_REG){
bytecodes.add(new Bytecode.Store(c.target, convertType(c.type.ret())));
} else if(c.target == Code.NULL_REG && c.type.ret() != Type.T_VOID) {
bytecodes.add(new Bytecode.Pop(convertType(c.type.ret())));
}
}
public void translate(Code.IndirectInvoke c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
Type.FunctionOrMethodOrMessage ft = c.type;
JvmType.Array arrT = new JvmType.Array(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Load(c.operand,JAVA_LANG_REFLECT_METHOD));
bytecodes.add(new Bytecode.LoadConst(null));
bytecodes.add(new Bytecode.LoadConst(ft.params().size()));
bytecodes.add(new Bytecode.New(arrT));
for (int i = 0; i != c.operands.length; ++i) {
int register = c.operands[i];
Type pt = c.type.params().get(i);
JvmType jpt = convertType(pt);
bytecodes.add(new Bytecode.Dup(arrT));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.Load(register, jpt));
addWriteConversion(pt,bytecodes);
bytecodes.add(new Bytecode.ArrayStore(arrT));
}
JvmType.Clazz owner = new JvmType.Clazz("java.lang.reflect","Method");
JvmType.Function type = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,arrT);
bytecodes.add(new Bytecode.Invoke(owner, "invoke", type,
Bytecode.VIRTUAL));
// now, handle the case of an invoke which returns a value that should
// be discarded.
if (c.target != Code.NULL_REG) {
addReadConversion(ft.ret(),bytecodes);
bytecodes.add(new Bytecode.Store(c.target,
convertType(c.type.ret())));
} else if (c.target == Code.NULL_REG && c.type.ret() != Type.T_VOID) {
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
public void translate(Code.Send c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operands[0],convertType(c.type.receiver())));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_REFLECT_METHOD,
JAVA_LANG_STRING, JAVA_LANG_STRING);
bytecodes.add(new Bytecode.LoadConst(c.name.module().toString().replace('/','.')));
bytecodes
.add(new Bytecode.LoadConst(nameMangle(c.name.name(), c.type)));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "functionRef", ftype,
Bytecode.STATIC));
Type.Message ft = c.type;
JvmType.Array arrT = new JvmType.Array(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.LoadConst(ft.params().size()+1));
bytecodes.add(new Bytecode.New(arrT));
// first, peal parameters off stack in reverse order
List<Type> params = ft.params();
for(int i=1;i!=c.operands.length;++i) {
Type pt = params.get(i-1);
bytecodes.add(new Bytecode.Dup(arrT));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.Load(c.operands[i],convertType(pt)));
addWriteConversion(pt,bytecodes);
bytecodes.add(new Bytecode.ArrayStore(arrT));
}
// finally, setup the stack for the send
if (c.synchronous && c.target != Code.NULL_REG) {
ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "syncSend", ftype,
Bytecode.VIRTUAL));
addReadConversion(c.type.ret(), bytecodes);
bytecodes.add(new Bytecode.Store(c.target,
convertType(c.type.ret())));
} else if (c.synchronous) {
ftype = new JvmType.Function(T_VOID,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "vSyncSend", ftype,
Bytecode.VIRTUAL));
} else {
ftype = new JvmType.Function(T_VOID,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "asyncSend",
ftype, Bytecode.VIRTUAL));
}
}
public void translate(Code.IndirectSend c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
// The main issue here, is that we have all of the parameters + receiver
// on the stack. What we need to do is to put them into an array, so
// they can then be passed into Method.invoke()
// To make this work, what we'll do is use a temporary register to hold
// the array as we build it up.
Type.Message ft = c.type;
JvmType.Array arrT = new JvmType.Array(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.LoadConst(ft.params().size()+1));
bytecodes.add(new Bytecode.New(arrT));
bytecodes.add(new Bytecode.Store(freeSlot,arrT));
// first, peal parameters off stack in reverse order
List<Type> params = ft.params();
for(int i=params.size()-1;i>=0;--i) {
Type pt = params.get(i);
bytecodes.add(new Bytecode.Load(freeSlot,arrT));
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.LoadConst(i+1));
bytecodes.add(new Bytecode.Swap());
addWriteConversion(pt,bytecodes);
bytecodes.add(new Bytecode.ArrayStore(arrT));
}
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.Load(freeSlot, arrT));
if (c.synchronous && c.target >= 0) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "syncSend", ftype,
Bytecode.VIRTUAL));
addReadConversion(c.type.ret(), bytecodes);
} else if (c.synchronous) {
JvmType.Function ftype = new JvmType.Function(T_VOID,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "vSyncSend", ftype,
Bytecode.VIRTUAL));
} else {
JvmType.Function ftype = new JvmType.Function(T_VOID,
JAVA_LANG_REFLECT_METHOD, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(WHILEYPROCESS, "asyncSend",
ftype, Bytecode.VIRTUAL));
}
}
public void translate(Value v, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if(v instanceof Value.Null) {
translate((Value.Null)v,freeSlot,bytecodes);
} else if(v instanceof Value.Bool) {
translate((Value.Bool)v,freeSlot,bytecodes);
} else if(v instanceof Value.Byte) {
translate((Value.Byte)v,freeSlot,bytecodes);
} else if(v instanceof Value.Char) {
translate((Value.Char)v,freeSlot,bytecodes);
} else if(v instanceof Value.Integer) {
translate((Value.Integer)v,freeSlot,bytecodes);
} else if(v instanceof Value.Type) {
translate((Value.Type)v,freeSlot,bytecodes);
} else if(v instanceof Value.Rational) {
translate((Value.Rational)v,freeSlot,bytecodes);
} else if(v instanceof Value.Strung) {
translate((Value.Strung)v,freeSlot,bytecodes);
} else if(v instanceof Value.Set) {
translate((Value.Set)v,freeSlot,bytecodes);
} else if(v instanceof Value.List) {
translate((Value.List)v,freeSlot,bytecodes);
} else if(v instanceof Value.Record) {
translate((Value.Record)v,freeSlot,bytecodes);
} else if(v instanceof Value.Dictionary) {
translate((Value.Dictionary)v,freeSlot,bytecodes);
} else if(v instanceof Value.Tuple) {
translate((Value.Tuple)v,freeSlot,bytecodes);
} else if(v instanceof Value.FunctionOrMethodOrMessage) {
translate((Value.FunctionOrMethodOrMessage)v,freeSlot,bytecodes);
} else {
throw new IllegalArgumentException("unknown value encountered:" + v);
}
}
protected void translate(Value.Null e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(null));
}
protected void translate(Value.Bool e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if (e.value) {
bytecodes.add(new Bytecode.LoadConst(1));
} else {
bytecodes.add(new Bytecode.LoadConst(0));
}
}
protected void translate(Value.Type e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream bout = new BinaryOutputStream(jout);
Type.BinaryWriter writer = new Type.BinaryWriter(bout);
try {
writer.write(e.type);
writer.close();
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(),ex);
}
bytecodes.add(new Bytecode.LoadConst(jout.toString()));
JvmType.Function ftype = new JvmType.Function(WHILEYTYPE,
JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYTYPE, "valueOf", ftype,
Bytecode.STATIC));
}
protected void translate(Value.Byte e, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Value.Char e, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Value.Integer e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
BigInteger num = e.value;
if(num.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
bytecodes.add(new Bytecode.Conversion(T_INT,T_LONG));
JvmType.Function ftype = new JvmType.Function(BIG_INTEGER,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER, "valueOf", ftype,
Bytecode.STATIC));
} else if(num.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
JvmType.Function ftype = new JvmType.Function(BIG_INTEGER,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER, "valueOf", ftype,
Bytecode.STATIC));
} else {
// in this context, we need to use a byte array to construct the
// integer object.
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(BIG_INTEGER));
bytecodes.add(new Bytecode.Dup(BIG_INTEGER));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
JvmType.Function ftype = new JvmType.Function(T_VOID,bat);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER, "<init>", ftype,
Bytecode.SPECIAL));
}
}
protected void translate(Value.Rational e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
BigRational rat = e.value;
BigInteger den = rat.denominator();
BigInteger num = rat.numerator();
if(rat.isInteger()) {
// this
if(num.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,T_INT);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "valueOf", ftype,
Bytecode.STATIC));
} else if(num.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "valueOf", ftype,
Bytecode.STATIC));
} else {
// in this context, we need to use a byte array to construct the
// integer object.
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(BIG_RATIONAL));
bytecodes.add(new Bytecode.Dup(BIG_RATIONAL));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
JvmType.Function ftype = new JvmType.Function(T_VOID,bat);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "<init>", ftype,
Bytecode.SPECIAL));
}
} else if(num.bitLength() < 32 && den.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
bytecodes.add(new Bytecode.LoadConst(den.intValue()));
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,T_INT,T_INT);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "valueOf", ftype,
Bytecode.STATIC));
} else if(num.bitLength() < 64 && den.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
bytecodes.add(new Bytecode.LoadConst(den.longValue()));
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,T_LONG,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "valueOf", ftype,
Bytecode.STATIC));
} else {
// First, do numerator bytes
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(BIG_RATIONAL));
bytecodes.add(new Bytecode.Dup(BIG_RATIONAL));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
// Second, do denominator bytes
bytes = den.toByteArray();
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
// Finally, construct BigRational object
JvmType.Function ftype = new JvmType.Function(T_VOID,bat,bat);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL, "<init>", ftype,
Bytecode.SPECIAL));
}
}
protected void translate(Value.Strung e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Value.Set lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYSET));
bytecodes.add(new Bytecode.Dup(WHILEYSET));
JvmType.Function ftype = new JvmType.Function(T_VOID);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Value e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYSET));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Value.List lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYLIST));
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.LoadConst(lv.values.size()));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Value e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "add", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Value.Tuple lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYTUPLE));
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE));
bytecodes.add(new Bytecode.LoadConst(lv.values.size()));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "<init>", ftype,
Bytecode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Value e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "add", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Value.Record expr, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
construct(WHILEYRECORD, freeSlot, bytecodes);
for (Map.Entry<String, Value> e : expr.values.entrySet()) {
Type et = e.getValue().type();
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(e.getKey()));
translate(e.getValue(), freeSlot, bytecodes);
addWriteConversion(et, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD, "put", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
protected void translate(Value.Dictionary expr, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
construct(WHILEYMAP, freeSlot, bytecodes);
for (Map.Entry<Value, Value> e : expr.values.entrySet()) {
Type kt = e.getKey().type();
Type vt = e.getValue().type();
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
translate(e.getKey(), freeSlot, bytecodes);
addWriteConversion(kt, bytecodes);
translate(e.getValue(), freeSlot, bytecodes);
addWriteConversion(vt, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
protected void translate(Value.FunctionOrMethodOrMessage e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_REFLECT_METHOD,JAVA_LANG_STRING,JAVA_LANG_STRING);
NameID nid = e.name;
bytecodes.add(new Bytecode.LoadConst(nid.module().toString().replace('/','.')));
bytecodes.add(new Bytecode.LoadConst(nameMangle(nid.name(),e.type)));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "functionRef", ftype,Bytecode.STATIC));
}
protected void addCoercion(Type from, Type to, int freeSlot,
HashMap<Constant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// First, deal with coercions which require a change of representation
// when going into a union. For example, bool must => Boolean.
if (!(to instanceof Type.Bool) && from instanceof Type.Bool) {
// this is either going into a union type, or the any type
buildCoercion((Type.Bool) from, to, freeSlot, bytecodes);
} else if(from == Type.T_BYTE) {
buildCoercion((Type.Byte)from, to, freeSlot,bytecodes);
} else if(from == Type.T_CHAR) {
buildCoercion((Type.Char)from, to, freeSlot,bytecodes);
} else if (Type.intersect(from, to).equals(from)) {
// do nothing!
// (note, need to check this after primitive types to avoid risk of
// missing coercion to any)
} else if(from == Type.T_INT) {
buildCoercion((Type.Int)from, to, freeSlot,bytecodes);
} else if(from == Type.T_STRING && to instanceof Type.List) {
buildCoercion((Type.Strung)from, (Type.List) to, freeSlot,bytecodes);
} else {
// ok, it's a harder case so we use an explicit coercion function
int id = Coercion.get(from,to,constants);
String name = "coercion$" + id;
JvmType.Function ft = new JvmType.Function(convertType(to), convertType(from));
bytecodes.add(new Bytecode.Invoke(owner, name, ft, Bytecode.STATIC));
}
}
public void buildCoercion(Type.Bool fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BOOLEAN,T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,"valueOf",ftype,Bytecode.STATIC));
// done deal!
}
public void buildCoercion(Type.Byte fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BYTE,T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE,"valueOf",ftype,Bytecode.STATIC));
// done deal!
}
public void buildCoercion(Type.Int fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
Type glb = Type.intersect(Type.T_REAL, toType);
if(glb == Type.T_REAL) {
// coercion required!
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,BIG_INTEGER);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL,"valueOf",ftype,Bytecode.STATIC));
} else {
// must be => char
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER,"intValue",ftype,Bytecode.VIRTUAL));
}
}
public void buildCoercion(Type.Char fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
if(!Type.isSubtype(toType,fromType)) {
if(toType == Type.T_REAL) {
// coercion required!
JvmType.Function ftype = new JvmType.Function(BIG_RATIONAL,T_INT);
bytecodes.add(new Bytecode.Invoke(BIG_RATIONAL,"valueOf",ftype,Bytecode.STATIC));
} else {
bytecodes.add(new Bytecode.Conversion(T_INT, T_LONG));
JvmType.Function ftype = new JvmType.Function(BIG_INTEGER,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER,"valueOf",ftype,Bytecode.STATIC));
}
} else {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_CHARACTER,T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER,"valueOf",ftype,Bytecode.STATIC));
}
}
public void buildCoercion(Type.Strung fromType, Type.List toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,JAVA_LANG_STRING);
if(toType.element() == Type.T_CHAR) {
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"str2cl",ftype,Bytecode.STATIC));
} else {
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"str2il",ftype,Bytecode.STATIC));
}
}
/**
* The build coercion method constructs a static final private method which
* accepts a value of type "from", and coerces it into a value of type "to".
*
* @param to
* @param from
*
*/
protected void buildCoercion(Type from, Type to, int id,
HashMap<Constant, Integer> constants, ClassFile cf) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
int freeSlot = 1;
bytecodes.add(new Bytecode.Load(0,convertType(from)));
buildCoercion(from,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Return(convertType(to)));
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PRIVATE);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ftype = new JvmType.Function(convertType(to),convertType(from));
String name = "coercion$" + id;
ClassFile.Method method = new ClassFile.Method(name, ftype, modifiers);
cf.methods().add(method);
wyjvm.attributes.Code code = new wyjvm.attributes.Code(bytecodes,new ArrayList(),method);
method.attributes().add(code);
}
protected void buildCoercion(Type from, Type to, int freeSlot,
HashMap<Constant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// Second, case analysis on the various kinds of coercion
if(from instanceof Type.Tuple && to instanceof Type.Tuple) {
buildCoercion((Type.Tuple) from, (Type.Tuple) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Reference && to instanceof Type.Reference) {
// TODO
} else if(from instanceof Type.Set && to instanceof Type.Set) {
buildCoercion((Type.Set) from, (Type.Set) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Set && to instanceof Type.Dictionary) {
buildCoercion((Type.Set) from, (Type.Dictionary) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.Set) {
buildCoercion((Type.List) from, (Type.Set) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Dictionary && to instanceof Type.Dictionary) {
buildCoercion((Type.Dictionary) from, (Type.Dictionary) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.Dictionary) {
buildCoercion((Type.List) from, (Type.Dictionary) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.List) {
buildCoercion((Type.List) from, (Type.List) to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Record && from instanceof Type.Record) {
buildCoercion((Type.Record) from, (Type.Record) to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Function && from instanceof Type.Function) {
// TODO
} else if(from instanceof Type.Negation || to instanceof Type.Negation) {
// no need to do anything, since convertType on a negation returns java/lang/Object
} else if(from instanceof Type.Union) {
buildCoercion((Type.Union) from, to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Union) {
buildCoercion(from, (Type.Union) to, freeSlot, constants, bytecodes);
} else {
throw new RuntimeException("invalid coercion encountered: " + from + " => " + to);
}
}
protected void buildCoercion(Type.Tuple fromType, Type.Tuple toType,
int freeSlot, HashMap<Constant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
int oldSlot = freeSlot++;
int newSlot = freeSlot++;
bytecodes.add(new Bytecode.Store(oldSlot,WHILEYTUPLE));
construct(WHILEYTUPLE,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(newSlot,WHILEYTUPLE));
List<Type> from_elements = fromType.elements();
List<Type> to_elements = toType.elements();
for(int i=0;i!=to_elements.size();++i) {
Type from = from_elements.get(i);
Type to = to_elements.get(i);
bytecodes.add(new Bytecode.Load(newSlot,WHILEYTUPLE));
bytecodes.add(new Bytecode.Load(oldSlot,WHILEYTUPLE));
bytecodes.add(new Bytecode.LoadConst(i));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE,"get",ftype,Bytecode.VIRTUAL));
addReadConversion(from,bytecodes);
// now perform recursive conversion
addCoercion(from,to,freeSlot,constants,bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE,"add",ftype,Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
bytecodes.add(new Bytecode.Load(newSlot,WHILEYTUPLE));
}
protected void buildCoercion(Type.List fromType, Type.List toType,
int freeSlot, HashMap<Constant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYLIST,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYLIST));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.If.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYLIST));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "add",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYLIST));
}
protected void buildCoercion(Type.List fromType, Type.Dictionary toType,
int freeSlot, HashMap<Constant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int source = freeSlot++;
int target = freeSlot++;
bytecodes.add(new Bytecode.Store(source,JAVA_UTIL_LIST));
bytecodes.add(new Bytecode.LoadConst(0));
bytecodes.add(new Bytecode.Store(iter,T_INT));
construct(WHILEYMAP,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(target, WHILEYMAP));
bytecodes.add(new Bytecode.Label(loopLabel));
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Load(iter,JvmTypes.T_INT));
bytecodes.add(new Bytecode.Load(source,JAVA_UTIL_LIST));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_LIST, "size",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.GE, T_INT, exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,T_INT));
bytecodes.add(new Bytecode.Conversion(T_INT,T_LONG));
ftype = new JvmType.Function(BIG_INTEGER,T_LONG);
bytecodes.add(new Bytecode.Invoke(BIG_INTEGER, "valueOf",
ftype, Bytecode.STATIC));
bytecodes.add(new Bytecode.Load(source,WHILEYMAP));
bytecodes.add(new Bytecode.Load(iter,T_INT));
ftype = new JvmType.Function(JAVA_LANG_OBJECT,T_INT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_LIST, "get",
ftype, Bytecode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.value(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Iinc(iter,1));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
}
protected void buildCoercion(Type.Dictionary fromType, Type.Dictionary toType,
int freeSlot, HashMap<Constant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if (fromType.key() == Type.T_VOID || toType.key() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int source = freeSlot++;
int target = freeSlot++;
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Store(source, WHILEYMAP));
construct(WHILEYMAP,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(target, WHILEYMAP));
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_SET);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "keySet",
ftype, Bytecode.VIRTUAL));
ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_SET, "iterator",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.If.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.INTERFACE));
addReadConversion(fromType.key(),bytecodes);
bytecodes.add(new Bytecode.Dup(convertType(fromType.key())));
addCoercion(fromType.key(), toType.key(), freeSlot,
constants, bytecodes);
addWriteConversion(toType.key(),bytecodes);
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.Load(source,WHILEYMAP));
bytecodes.add(new Bytecode.Swap());
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "get",
ftype, Bytecode.VIRTUAL));
addReadConversion(fromType.value(),bytecodes);
addCoercion(fromType.value(), toType.value(), freeSlot,
constants, bytecodes);
addWriteConversion(toType.value(),bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
}
protected void buildCoercion(Type.Set fromType, Type.Dictionary toType,
int freeSlot, HashMap<Constant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if (fromType.element() != Type.T_VOID) {
throw new RuntimeException("invalid coercion encountered: "
+ fromType + " => " + toType);
}
bytecodes.add(new Bytecode.Pop(WHILEYSET));
construct(WHILEYMAP, freeSlot, bytecodes);
}
protected void buildCoercion(Type.List fromType, Type.Set toType,
int freeSlot, HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYSET,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYSET));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.If.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
}
protected void buildCoercion(Type.Set fromType, Type.Set toType,
int freeSlot, HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYSET,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYSET));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.If.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add",
ftype, Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
}
public void buildCoercion(Type.Record fromType, Type.Record toType,
int freeSlot, HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
int oldSlot = freeSlot++;
int newSlot = freeSlot++;
bytecodes.add(new Bytecode.Store(oldSlot,WHILEYRECORD));
construct(WHILEYRECORD,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(newSlot,WHILEYRECORD));
Map<String,Type> toFields = toType.fields();
Map<String,Type> fromFields = fromType.fields();
for(String key : toFields.keySet()) {
Type to = toFields.get(key);
Type from = fromFields.get(key);
bytecodes.add(new Bytecode.Load(newSlot,WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
bytecodes.add(new Bytecode.Load(oldSlot,WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"get",ftype,Bytecode.VIRTUAL));
// TODO: in cases when the read conversion is a no-op, we can do
// better here.
addReadConversion(from,bytecodes);
addCoercion(from,to,freeSlot,constants,bytecodes);
addWriteConversion(from,bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Load(newSlot,WHILEYRECORD));
}
public void buildCoercion(Type.Union from, Type to,
int freeSlot, HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
String exitLabel = freshLabel();
List<Type> bounds = new ArrayList<Type>(from.bounds());
ArrayList<String> labels = new ArrayList<String>();
// basically, we're building a big dispatch table. I think there's no
// question that this could be more efficient in some cases.
for(int i=0;i!=bounds.size();++i) {
Type bound = bounds.get(i);
if((i+1) == bounds.size()) {
addReadConversion(bound,bytecodes);
addCoercion(bound,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Goto(exitLabel));
} else {
String label = freshLabel();
labels.add(label);
bytecodes.add(new Bytecode.Dup(convertType(from)));
translateTypeTest(label,from,bound,bytecodes,constants);
}
}
for(int i=0;i<labels.size();++i) {
String label = labels.get(i);
Type bound = bounds.get(i);
bytecodes.add(new Bytecode.Label(label));
addReadConversion(bound,bytecodes);
addCoercion(bound,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Goto(exitLabel));
}
bytecodes.add(new Bytecode.Label(exitLabel));
}
public void buildCoercion(Type from, Type.Union to,
int freeSlot, HashMap<Constant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
Type.Union t2 = (Type.Union) to;
// First, check for identical type (i.e. no coercion necessary)
for (Type b : t2.bounds()) {
if (from.equals(b)) {
// nothing to do
return;
}
}
// Second, check for single non-coercive match
for (Type b : t2.bounds()) {
if (Type.isSubtype(b, from)) {
buildCoercion(from,b,freeSlot,constants,bytecodes);
return;
}
}
// Third, test for single coercive match
for (Type b : t2.bounds()) {
if (Type.isImplicitCoerciveSubtype(b, from)) {
buildCoercion(from,b,freeSlot,constants,bytecodes);
return;
}
}
// I don't think we should be able to get here!
}
/**
* The read conversion is necessary in situations where we're reading a
* value from a collection (e.g. WhileyList, WhileySet, etc) and then
* putting it on the stack. In such case, we need to convert boolean values
* from Boolean objects to bool primitives.
*/
public void addReadConversion(Type et, ArrayList<Bytecode> bytecodes) {
if(et instanceof Type.Bool) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_BOOLEAN));
JvmType.Function ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,
"booleanValue", ftype, Bytecode.VIRTUAL));
} else if(et instanceof Type.Byte) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_BYTE));
JvmType.Function ftype = new JvmType.Function(T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE,
"byteValue", ftype, Bytecode.VIRTUAL));
} else if(et instanceof Type.Char) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_CHARACTER));
JvmType.Function ftype = new JvmType.Function(T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER,
"charValue", ftype, Bytecode.VIRTUAL));
} else {
addCheckCast(convertType(et),bytecodes);
}
}
/**
* The write conversion is necessary in situations where we're write a value
* from the stack into a collection (e.g. WhileyList, WhileySet, etc). In
* such case, we need to convert boolean values from bool primitives to
* Boolean objects.
*/
public void addWriteConversion(Type et, ArrayList<Bytecode> bytecodes) {
if(et instanceof Type.Bool) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BOOLEAN,T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,
"valueOf", ftype, Bytecode.STATIC));
} else if(et instanceof Type.Byte) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BYTE,
T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE, "valueOf", ftype,
Bytecode.STATIC));
} else if(et instanceof Type.Char) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_CHARACTER,
T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER, "valueOf", ftype,
Bytecode.STATIC));
}
}
public void addCheckCast(JvmType type, ArrayList<Bytecode> bytecodes) {
// The following can happen in situations where a variable has type
// void. In principle, we could remove this as obvious dead-code, but
// for now I just avoid it.
if(type instanceof JvmType.Void) {
return;
} else if(!type.equals(JAVA_LANG_OBJECT)) {
// pointless to add a cast for object
bytecodes.add(new Bytecode.CheckCast(type));
}
}
/**
* Return true if this type is, or maybe reference counted.
*
* @param t
* @return
*/
public static boolean isRefCounted(Type t) {
if (t instanceof Type.Union) {
Type.Union n = (Type.Union) t;
for (Type b : n.bounds()) {
if (isRefCounted(b)) {
return true;
}
}
return false;
} else {
// FIXME: what about negations?
return t instanceof Type.Any || t instanceof Type.List
|| t instanceof Type.Tuple || t instanceof Type.Set
|| t instanceof Type.Dictionary || t instanceof Type.Record;
}
}
/**
* Add bytecodes for incrementing the reference count.
*
* @param type
* @param bytecodes
*/
public static void addIncRefs(Type type, ArrayList<Bytecode> bytecodes) {
if(isRefCounted(type)){
JvmType jtype = convertType(type);
JvmType.Function ftype = new JvmType.Function(jtype,jtype);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.STATIC));
}
}
public static void addIncRefs(Type.List type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,WHILEYLIST);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.STATIC));
}
public static void addIncRefs(Type.Record type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYRECORD,WHILEYRECORD);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.STATIC));
}
public static void addIncRefs(Type.Dictionary type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYMAP,WHILEYMAP);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.STATIC));
}
/**
* The construct method provides a generic way to construct a Java object.
*
* @param owner
* @param freeSlot
* @param bytecodes
* @param params
*/
public void construct(JvmType.Clazz owner, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(owner));
bytecodes.add(new Bytecode.Dup(owner));
ArrayList<JvmType> paramTypes = new ArrayList<JvmType>();
JvmType.Function ftype = new JvmType.Function(T_VOID,paramTypes);
bytecodes.add(new Bytecode.Invoke(owner, "<init>", ftype,
Bytecode.SPECIAL));
}
public final static Type.Reference WHILEY_SYSTEM_OUT_T = (Type.Reference) Type
.Reference(Type.T_ANY);
public final static Type WHILEY_SYSTEM_T = Type.Record(false,
new HashMap() {
{
put("out", WHILEY_SYSTEM_OUT_T);
put("args", Type.List(Type.T_STRING,false));
}
});
public final static JvmType.Clazz WHILEYUTIL = new JvmType.Clazz("wyjc.runtime","Util");
public final static JvmType.Clazz WHILEYLIST = new JvmType.Clazz("wyjc.runtime","List");
public final static JvmType.Clazz WHILEYSET = new JvmType.Clazz("wyjc.runtime","Set");
public final static JvmType.Clazz WHILEYTUPLE = new JvmType.Clazz("wyjc.runtime","Tuple");
public final static JvmType.Clazz WHILEYCOLLECTION = new JvmType.Clazz("wyjc.runtime","Collection");
public final static JvmType.Clazz WHILEYTYPE = new JvmType.Clazz("wyjc.runtime","Type");
public final static JvmType.Clazz WHILEYMAP = new JvmType.Clazz("wyjc.runtime","Dictionary");
public final static JvmType.Clazz WHILEYRECORD = new JvmType.Clazz("wyjc.runtime","Record");
public final static JvmType.Clazz WHILEYPROCESS = new JvmType.Clazz(
"wyjc.runtime", "Actor");
public final static JvmType.Clazz WHILEYEXCEPTION = new JvmType.Clazz("wyjc.runtime","Exception");
public final static JvmType.Clazz BIG_INTEGER = new JvmType.Clazz("java.math","BigInteger");
public final static JvmType.Clazz BIG_RATIONAL = new JvmType.Clazz("wyjc.runtime","BigRational");
private static final JvmType.Clazz JAVA_LANG_CHARACTER = new JvmType.Clazz("java.lang","Character");
private static final JvmType.Clazz JAVA_LANG_SYSTEM = new JvmType.Clazz("java.lang","System");
private static final JvmType.Array JAVA_LANG_OBJECT_ARRAY = new JvmType.Array(JAVA_LANG_OBJECT);
private static final JvmType.Clazz JAVA_UTIL_LIST = new JvmType.Clazz("java.util","List");
private static final JvmType.Clazz JAVA_UTIL_SET = new JvmType.Clazz("java.util","Set");
private static final JvmType.Clazz JAVA_LANG_REFLECT_METHOD = new JvmType.Clazz("java.lang.reflect","Method");
private static final JvmType.Clazz JAVA_IO_PRINTSTREAM = new JvmType.Clazz("java.io","PrintStream");
private static final JvmType.Clazz JAVA_LANG_RUNTIMEEXCEPTION = new JvmType.Clazz("java.lang","RuntimeException");
private static final JvmType.Clazz JAVA_LANG_ASSERTIONERROR = new JvmType.Clazz("java.lang","AssertionError");
private static final JvmType.Clazz JAVA_UTIL_COLLECTION = new JvmType.Clazz("java.util","Collection");
public JvmType.Function convertFunType(Type.FunctionOrMethodOrMessage ft) {
ArrayList<JvmType> paramTypes = new ArrayList<JvmType>();
if(ft instanceof Type.Message) {
Type.Message mt = (Type.Message)ft;
if(mt.receiver() != null) {
paramTypes.add(convertType(mt.receiver()));
}
}
for(Type pt : ft.params()) {
paramTypes.add(convertType(pt));
}
JvmType rt = convertType(ft.ret());
return new JvmType.Function(rt,paramTypes);
}
public static JvmType convertType(Type t) {
if(t == Type.T_VOID) {
return T_VOID;
} else if(t == Type.T_ANY) {
return JAVA_LANG_OBJECT;
} else if(t == Type.T_NULL) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Bool) {
return T_BOOL;
} else if(t instanceof Type.Byte) {
return T_BYTE;
} else if(t instanceof Type.Char) {
return T_CHAR;
} else if(t instanceof Type.Int) {
return BIG_INTEGER;
} else if(t instanceof Type.Real) {
return BIG_RATIONAL;
} else if(t instanceof Type.Meta) {
return WHILEYTYPE;
} else if(t instanceof Type.Strung) {
return JAVA_LANG_STRING;
} else if(t instanceof Type.EffectiveList) {
return WHILEYLIST;
} else if(t instanceof Type.EffectiveSet) {
return WHILEYSET;
} else if(t instanceof Type.EffectiveDictionary) {
return WHILEYMAP;
} else if(t instanceof Type.EffectiveRecord) {
return WHILEYRECORD;
} else if(t instanceof Type.EffectiveTuple) {
return WHILEYTUPLE;
} else if(t instanceof Type.Reference) {
return WHILEYPROCESS;
} else if(t instanceof Type.Negation) {
// can we do any better?
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Union) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Meta) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.FunctionOrMethodOrMessage) {
return JAVA_LANG_REFLECT_METHOD;
}else {
throw new RuntimeException("unknown type encountered: " + t);
}
}
protected int label = 0;
protected String freshLabel() {
return "cfblab" + label++;
}
public static String nameMangle(String name, Type.FunctionOrMethodOrMessage ft) {
try {
return name + "$" + typeMangle(ft);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static String typeMangle(Type.FunctionOrMethodOrMessage ft) throws IOException {
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream binout = new BinaryOutputStream(jout);
Type.BinaryWriter tm = new Type.BinaryWriter(binout);
tm.write(ft);
binout.close(); // force flush
return jout.toString();
}
/**
* A constant is some kind of auxillary functionality used in generated code, which can be reused at multiple sites. This includes value constants, and coercion functions.
* @author David J. Pearce
*
*/
public abstract static class Constant {}
public static final class ValueConst extends Constant {
public final Value value;
public ValueConst(Value v) {
value = v;
}
public boolean equals(Object o) {
if(o instanceof ValueConst) {
ValueConst vc = (ValueConst) o;
return value.equals(vc.value);
}
return false;
}
public int hashCode() {
return value.hashCode();
}
public static int get(Value value, HashMap<Constant,Integer> constants) {
ValueConst vc = new ValueConst(value);
Integer r = constants.get(vc);
if(r != null) {
return r;
} else {
int x = constants.size();
constants.put(vc, x);
return x;
}
}
}
public static final class Coercion extends Constant {
public final Type from;
public final Type to;
public Coercion(Type from, Type to) {
this.from = from;
this.to = to;
}
public boolean equals(Object o) {
if(o instanceof Coercion) {
Coercion c = (Coercion) o;
return from.equals(c.from) && to.equals(c.to);
}
return false;
}
public int hashCode() {
return from.hashCode() + to.hashCode();
}
public static int get(Type from, Type to, HashMap<Constant,Integer> constants) {
Coercion vc = new Coercion(from,to);
Integer r = constants.get(vc);
if(r != null) {
return r;
} else {
int x = constants.size();
constants.put(vc, x);
return x;
}
}
}
public static class UnresolvedHandler {
public String start;
public String end;
public String target;
public JvmType.Clazz exception;
public UnresolvedHandler(String start, String end, String target,
JvmType.Clazz exception) {
this.start = start;
this.end = end;
this.target = target;
this.exception = exception;
}
}
/*
public static void testMangle1(Type.Fun ft) throws IOException {
IdentifierOutputStream jout = new IdentifierOutputStream();
BinaryOutputStream binout = new BinaryOutputStream(jout);
Types.BinaryWriter tm = new Types.BinaryWriter(binout);
Type.build(tm,ft);
binout.close();
System.out.println("MANGLED: " + ft + " => " + jout.toString());
Type.Fun type = (Type.Fun) new Types.BinaryReader(
new BinaryInputStream(new IdentifierInputStream(
jout.toString()))).read();
System.out.println("UNMANGLED TO: " + type);
if(!type.equals(ft)) {
throw new RuntimeException("INVALID TYPE RECONSTRUCTED");
}
}
*/
} |
package cz.hobrasoft.pdfmu.sign;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CrlClient;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
import cz.hobrasoft.pdfmu.Operation;
import cz.hobrasoft.pdfmu.OperationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Collection;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* Adds a digital signature to a PDF document
*
* @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
*/
public class OperationSign implements Operation {
@Override
public String getCommandName() {
return "sign";
}
@Override
public Subparser configureSubparser(Subparser subparser) {
String help = "Digitally sign a PDF document";
String metavarIn = "IN.pdf";
String metavarOut = "OUT.pdf";
// Configure the subparser
subparser.help(help)
.description(help)
.defaultHelp(true)
.setDefault("command", OperationSign.class);
// Add arguments to the subparser
// Positional arguments are required by default
subparser.addArgument("in")
.help("input PDF document")
.metavar(metavarIn)
.type(Arguments.fileType().acceptSystemIn().verifyCanRead())
.required(true);
subparser.addArgument("-o", "--out")
.help(String.format("output PDF document (default: <%s>)", metavarIn))
.metavar(metavarOut)
.type(Arguments.fileType().verifyCanCreate())
.nargs("?");
subparser.addArgument("-f", "--force")
.help(String.format("overwrite %s if it exists", metavarOut))
.type(boolean.class)
.action(Arguments.storeTrue());
signatureParameters.addArguments(subparser);
return subparser;
}
// digitalsignatures20130304.pdf : Code sample 1.6
// Initialize the security provider
private static final BouncyCastleProvider provider = new BouncyCastleProvider();
static {
// We need to register the provider because it needs to be accessible by its name globally.
// {@link com.itextpdf.text.pdf.security.PrivateKeySignature#PrivateKeySignature(PrivateKey pk, String hashAlgorithm, String provider)}
// uses the provider name.
Security.addProvider(provider);
}
// Initialize the digest algorithm
private static final ExternalDigest externalDigest = new BouncyCastleDigest();
// `signatureParameters` is a member variable
// so that we can add the arguments to the parser in `configureSubparser`.
// We need an instance of {@link SignatureParameters} in `configureSubparser`
// because the interface `ArgsConfiguration` does not allow static methods.
private final SignatureParameters signatureParameters = new SignatureParameters();
@Override
public void execute(Namespace namespace) throws OperationException {
// Input file
File inFile = namespace.get("in");
assert inFile != null; // Required argument
System.err.println(String.format("Input PDF document: %s", inFile));
// Output file
File outFile = namespace.get("out");
if (outFile == null) {
System.err.println("--out option not specified; assuming in-place version change");
outFile = inFile;
}
System.err.println(String.format("Output PDF document: %s", outFile));
if (outFile.exists()) {
System.err.println("Output file already exists.");
if (!namespace.getBoolean("force")) {
throw new OperationException("Set --force flag to overwrite.");
}
}
boolean append = true;
// With `append == false`, adding a signature invalidates the previous signature.
// In order to make `append == false` work correctly, we would need to remove the previous signature.
// Initialize signature parameters
signatureParameters.setFromNamespace(namespace);
sign(inFile, outFile, append, signatureParameters);
}
// Open the PDF reader
private static void sign(File inFile,
File outFile,
boolean append,
SignatureParameters signatureParameters) throws OperationException {
assert inFile != null;
System.err.println(String.format("Input PDF document: %s", inFile));
// Open the input stream
FileInputStream inStream;
try {
inStream = new FileInputStream(inFile);
} catch (FileNotFoundException ex) {
throw new OperationException("Input file not found.", ex);
}
// Open the PDF reader
// PdfReader parses a PDF document.
PdfReader pdfReader;
try {
pdfReader = new PdfReader(inStream);
} catch (IOException ex) {
throw new OperationException("Could not open the input PDF document.", ex);
}
if (outFile == null) {
System.err.println("Output file not set. Commencing in-place operation.");
outFile = inFile;
}
sign(pdfReader, outFile, append, signatureParameters);
// Close the PDF reader
pdfReader.close();
// Close the input stream
try {
inStream.close();
} catch (IOException ex) {
throw new OperationException("Could not close the input file.", ex);
}
}
// Open the PDF stamper
private static void sign(PdfReader pdfReader,
File outFile,
boolean append,
SignatureParameters signatureParameters) throws OperationException {
assert outFile != null;
System.err.println(String.format("Output PDF document: %s", outFile));
// Open the output stream
FileOutputStream os;
try {
os = new FileOutputStream(outFile);
} catch (FileNotFoundException ex) {
throw new OperationException("Could not open the output file.", ex);
}
if (append) {
System.err.println("Appending signature.");
} else {
System.err.println("Replacing signature.");
}
PdfStamper stp;
try {
// digitalsignatures20130304.pdf : Code sample 2.17
// TODO?: Make sure version is high enough
stp = PdfStamper.createSignature(pdfReader, os, '\0', null, append);
} catch (DocumentException | IOException ex) {
throw new OperationException("Could not open the PDF stamper.", ex);
}
sign(stp, signatureParameters);
// Close the PDF stamper
try {
stp.close();
} catch (DocumentException | IOException ex) {
throw new OperationException("Could not close PDF stamper.", ex);
}
// Close the output stream
try {
os.close();
} catch (IOException ex) {
throw new OperationException("Could not close the output file.", ex);
}
}
// Initialize the signature appearance
private static void sign(PdfStamper stp,
SignatureParameters signatureParameters) throws OperationException {
assert signatureParameters != null;
// Unwrap the signature parameters
SignatureAppearanceParameters signatureAppearanceParameters = signatureParameters.appearance;
KeystoreParameters keystoreParameters = signatureParameters.keystore;
KeyParameters keyParameters = signatureParameters.key;
String digestAlgorithm = signatureParameters.digestAlgorithm;
MakeSignature.CryptoStandard sigtype = signatureParameters.sigtype;
// Initialize the signature appearance
PdfSignatureAppearance sap = signatureAppearanceParameters.getSignatureAppearance(stp);
assert sap != null; // `stp` must have been created using `PdfStamper.createSignature` static method
sign(sap, keystoreParameters, keyParameters, digestAlgorithm, sigtype);
}
// Initialize and load the keystore
private static void sign(PdfSignatureAppearance sap,
KeystoreParameters keystoreParameters,
KeyParameters keyParameters,
String digestAlgorithm,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert keystoreParameters != null;
// Initialize and load keystore
KeyStore ks = keystoreParameters.loadKeystore();
sign(sap, ks, keyParameters, digestAlgorithm, sigtype);
}
// Get the private key and the certificate chain from the keystore
private static void sign(PdfSignatureAppearance sap,
KeyStore ks,
KeyParameters keyParameters,
String digestAlgorithm,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert keyParameters != null;
// Fix the values, especially if they were not set at all
keyParameters.fix(ks);
PrivateKey pk = keyParameters.getPrivateKey(ks);
Certificate[] chain = keyParameters.getCertificateChain(ks);
sign(sap, pk, digestAlgorithm, chain, sigtype);
}
// Initialize the signature algorithm
private static void sign(PdfSignatureAppearance sap,
PrivateKey pk,
String digestAlgorithm,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert digestAlgorithm != null;
// Initialize the signature algorithm
System.err.println(String.format("Digest algorithm: %s", digestAlgorithm));
if (DigestAlgorithms.getAllowedDigests(digestAlgorithm) == null) {
throw new OperationException(String.format("The digest algorithm %s is not supported.", digestAlgorithm));
}
System.err.println(String.format("Signature security provider: %s", provider.getName()));
ExternalSignature externalSignature = new PrivateKeySignature(pk, digestAlgorithm, provider.getName());
sign(sap, externalSignature, chain, sigtype);
}
// Set the "external digest" algorithm
private static void sign(PdfSignatureAppearance sap,
ExternalSignature externalSignature,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
// Use the static BouncyCastleDigest instance
sign(sap, OperationSign.externalDigest, externalSignature, chain, sigtype);
}
// Sign the document
private static void sign(PdfSignatureAppearance sap,
ExternalDigest externalDigest,
ExternalSignature externalSignature,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
// TODO?: Set some of the following parameters more sensibly
// Certificate Revocation List
// digitalsignatures20130304.pdf : Section 3.2
Collection<CrlClient> crlList = null;
// Online Certificate Status Protocol
// digitalsignatures20130304.pdf : Section 3.2.4
OcspClient ocspClient = null;
// Time Stamp Authority
// digitalsignatures20130304.pdf : Section 3.3
TSAClient tsaClient = null;
// digitalsignatures20130304.pdf : Section 3.5
// The value of 0 means "try a generous educated guess".
// We need not change this unless we want to optimize the resulting PDF document size.
int estimatedSize = 0;
System.err.println(String.format("Cryptographic standard (signature format): %s", sigtype));
try {
MakeSignature.signDetached(sap, externalDigest, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
throw new OperationException("Could not sign the document.", ex);
} catch (NullPointerException ex) {
throw new OperationException("Could not sign the document. Invalid digest algorithm?", ex);
}
System.err.println("Document successfully signed.");
}
} |
package com.example.cesarsk.say_it;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.speech.tts.Voice;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import static android.content.Context.MODE_PRIVATE;
import static android.speech.tts.TextToSpeech.QUEUE_ADD;
import static com.example.cesarsk.say_it.MainActivity.FAVORITES_PREFS_KEY;
import static com.example.cesarsk.say_it.MainActivity.HISTORY_PREFS_KEY;
import static com.example.cesarsk.say_it.MainActivity.WordList;
import static com.example.cesarsk.say_it.MainActivity.tts;
import static com.example.cesarsk.say_it.MainActivity.voice_american_female;
import static com.example.cesarsk.say_it.MainActivity.voice_british_female;
public class Utility {
private static final String AUDIO_RECORDER_FOLDER = "Say it";
public static boolean delete_recordings() {
//TODO DELETE ALL FILES IN THE FOLDER EXCEPT FOR .NOMEDIA FILE
return true;
}
//Method used for BUG_REPORT and CONTACT_US Modules
public static void shareToMail(String[] email, String subject, Context context) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, email);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
//emailIntent.putExtra(Intent.EXTRA_TEXT, content);
emailIntent.setType("text/plain");
context.startActivity(emailIntent);
}
//Rate-Us Module
public static void rateUs(Context context){
Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
context.startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
context.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
}
//Gestione Preferences
public static void savePrefs(Context context, Set<String> set, String prefs_key)
{
SharedPreferences settings = context.getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putStringSet(prefs_key, set);
editor.apply();
}
public static void addFavs(Context context, String word)
{
Set<String> new_favs = new TreeSet<>();
loadFavs(context);
if(MainActivity.FAVORITES != null){
for (String element: MainActivity.FAVORITES) {
new_favs.add(element);
}
}
new_favs.add(word);
savePrefs(context, new_favs, MainActivity.FAVORITES_PREFS_KEY);
}
public static void addHist(Context context, String word)
{
Set<String> new_hist = new TreeSet<>();
loadHist(context);
if(MainActivity.HISTORY != null){
for (String element: MainActivity.HISTORY) {
new_hist.add(element);
}
}
new_hist.add(word);
savePrefs(context, new_hist, MainActivity.HISTORY_PREFS_KEY);
}
public static void loadFavs(Context context)
{
SharedPreferences sharedPreferences = context.getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
MainActivity.FAVORITES = sharedPreferences.getStringSet(FAVORITES_PREFS_KEY, new TreeSet<String>());
}
public static void loadHist(Context context)
{
SharedPreferences sharedPreferences = context.getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
MainActivity.HISTORY = sharedPreferences.getStringSet(HISTORY_PREFS_KEY, new TreeSet<String>());
}
public static void pronunciateWord(CharSequence word, float pitch, float speechRate, Voice accent)
{
//manual pronunciation of a word, never used.
tts.setPitch(pitch);
tts.setSpeechRate(speechRate);
tts.setVoice(accent);
tts.speak(word, QUEUE_ADD, null, null);
}
public static ArrayList<String> loadRecordings()
{
//load all recordings, needs to be used in order to build the HistoryFragment
ArrayList<String> recordings = new ArrayList<>();
String path = Environment.getExternalStorageDirectory().getPath()+"/"+AUDIO_RECORDER_FOLDER;
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
if(files[i].getName().equals(".nomedia"));
else recordings.add(files[i].getName().substring(0, files[i].getName().lastIndexOf(".")));
}
return recordings;
}
public static void loadDictionary(Activity activity) {
//loading wordslist from file.
BufferedReader line_reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(R.raw.wordlist)));
String line;
try {
while ((line = line_reader.readLine()) != null) {
WordList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.sort(WordList);
}
public static void deleteRecordings()
{
//delete all recordings
String path = Environment.getExternalStorageDirectory().getPath()+"/"+AUDIO_RECORDER_FOLDER;
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++)
{
if(files[i].getName().equals(".nomedia"));
else files[i].delete();
}
}
} |
package com.opengamma.engine.position;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.opengamma.engine.security.Security;
import com.opengamma.engine.security.SecurityKey;
import com.opengamma.util.CompareUtils;
/**
* A simple JavaBean-based implementation of {@link Position}.
*
* @author kirk
*/
public class PositionBean implements Position, Serializable, Cloneable {
private final BigDecimal _quantity;
private final SecurityKey _securityKey;
private Security _security;
public PositionBean(BigDecimal quantity, SecurityKey securityKey) {
_quantity = quantity;
_securityKey = securityKey;
_security = null;
}
public PositionBean(BigDecimal quantity, SecurityKey securityKey, Security security) {
_quantity = quantity;
_securityKey = securityKey;
_security = security;
}
@Override
public BigDecimal getQuantity() {
return _quantity;
}
@Override
public SecurityKey getSecurityKey() {
return _securityKey;
}
@Override
public Security getSecurity() {
return _security;
}
public void setSecurity(Security security) {
_security = security;
}
@Override
public PositionBean clone() {
try {
return (PositionBean)super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Yes, it is supported.");
}
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(!(obj instanceof PositionBean)) {
return false;
}
PositionBean other = (PositionBean) obj;
// Use comparison here to deal with scale issues with BigDecimal comparisons.
if(CompareUtils.compareWithNull(getQuantity(), other.getQuantity()) != 0) {
return false;
}
if(!ObjectUtils.equals(getSecurityKey(), other.getSecurityKey())) {
return false;
}
if(!ObjectUtils.equals(getSecurity(), other.getSecurity())) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 65;
hashCode += getQuantity().hashCode();
hashCode <<= 5;
hashCode += getSecurityKey().hashCode();
return hashCode;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
} |
package bpsm.edn.parser;
import java.util.HashMap;
import java.util.Map;
import bpsm.edn.model.Symbol;
import bpsm.edn.model.Tag;
import bpsm.edn.parser.handlers.InstantToDate;
import bpsm.edn.parser.handlers.UuidHandler;
public class ParserConfiguration {
BuilderFactory listFactory;
BuilderFactory vectorFactory;
BuilderFactory setFactory;
BuilderFactory mapFactory;
Map<Tag,TagHandler> tagHandlers;
private ParserConfiguration() {
listFactory = DEFAULT_LIST_FACTORY;
vectorFactory = DEFAULT_VECTOR_FACTORY;
setFactory = DEFAULT_SET_FACTORY;
mapFactory = DEFAULT_MAP_FACTORY;
Map<Tag,TagHandler> m = new HashMap<Tag,TagHandler>();
m.put(EDN_UUID, new UuidHandler());
m.put(EDN_INSTANT, new InstantToDate());
this.tagHandlers = m;
}
public static ParserConfiguration defaultConfiguration() {
return builder().build();
}
public static ParserConfigurationBuilder builder() {
return new ParserConfigurationBuilder(new ParserConfiguration());
}
public BuilderFactory getListFactory() {
return listFactory;
}
public BuilderFactory getVectorFactory() {
return vectorFactory;
}
public BuilderFactory getSetFactory() {
return setFactory;
}
public BuilderFactory getMapFactory() {
return mapFactory;
}
public Map<Tag, TagHandler> getTagHandlers() {
return tagHandlers;
}
public static final Tag EDN_UUID = new Tag(new Symbol(null, "uuid"));
public static final Tag EDN_INSTANT = new Tag(new Symbol(null, "inst"));
static final BuilderFactory DEFAULT_LIST_FACTORY = new DefaultListFactory();
static final BuilderFactory DEFAULT_VECTOR_FACTORY = new DefaultVectorFactory();
static final BuilderFactory DEFAULT_SET_FACTORY = new DefaultSetFactory();
static final BuilderFactory DEFAULT_MAP_FACTORY = new DefaultMapFactory();
} |
package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class ApsMetadataEntry {
private String id;
private String date;
private Map<String,String> title;
private List<Map<String,Object>> authors;
@SerializedName("abstract")
private Map<String,String> abstractText;
public static ApsMetadataEntry load(File file) throws FileNotFoundException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
return new Gson().fromJson(br, ApsMetadataEntry.class);
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
public String getId() {
return id;
}
public String getDate() {
return date;
}
public List<String> getNormalizedAuthors() {
List<String> nAuthors = new ArrayList<String>();
if (authors != null) {
for (Map<String,Object> m : authors) {
if (!m.containsKey("type") || !"Person".equals(m.get("type")) || !m.containsKey("firstname") ||
!m.containsKey("surname")) {
nAuthors.add(null);
continue;
}
String f = m.get("firstname").toString().toLowerCase();
String s = m.get("surname").toString().toLowerCase();
if (f.isEmpty() || s.isEmpty()) {
nAuthors.add(null);
continue;
}
nAuthors.add(f.substring(0, 1) + "." + s);
}
}
return nAuthors;
}
public String getNormalizedTitle() {
if (title == null || !title.containsKey("value")) return null;
String n = title.get("value");
if (n == null) return null;
if (title.containsKey("format") && title.get("format").startsWith("html")) {
n = preprocessHtml(n);
}
return MemeUtils.normalize(n);
}
public String getNormalizedAbstract() {
if (abstractText == null || !abstractText.containsKey("value")) return null;
String n = abstractText.get("value");
if (n == null) return null;
if (abstractText.containsKey("format") && abstractText.get("format").startsWith("html")) {
n = preprocessHtml(n);
}
return MemeUtils.normalize(n);
}
public String preprocessHtml(String htmlText) {
htmlText = htmlText.replaceAll("</?[a-z]+ ?.*?/?>", "");
return htmlText;
}
} |
package com.example.john.project1;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class Chapter2 extends AppCompatActivity {
@Override
protected void onDestroy() {
super.onDestroy();
Thread.currentThread().interrupt();
}
@Override
protected void onRestart() {
super.onRestart();
sv_code.scrollTo(0,0);
}
@Override
protected void onResume() {
super.onResume();
}
/**
* Dispatch onPause() to fragments.
*/
@Override
protected void onPause() {
super.onPause();
Thread.currentThread().interrupt();
}
@Override
protected void onStop() {
super.onStop();
}
ImageButton playbtn,stopbtn,pausebtn;
ImageView pointer,pic_class_chap2;
ScrollView sv_code;
LinearLayout layoutcode;
Thread scD400,scD800,scD1500;
Boolean checkScrolling=true;
String checkStateChap2="";
TextView num1,num2,sign,result,text_returnChap2,
resultChap2text,text_num1,text_num2,object,
text_plus,text_minus,text_multi,text_divide,class_chap2;
AnimatorSet amMovingNum,amMovingNum2,amMovingtextToResultBoxPlus,amMovingtextToResultBoxMinus,amMovingtextToResultBoxMulti,amMovingtextToResultBoxDivide;
ObjectAnimator objline1,objline2,objline3,objline17
,objline29,objline30,objline31,
objline32,objline18,objline3_1,objline5,objline35,objline5_1,objline6,objline7,
objline39,objline7_1,objline8,objline9,objline20,objline9_1,objline10,objline11,objline23,objline11_1,objline12;
int Delaytime=2000,count=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter2);
playbtn =(ImageButton)findViewById(R.id.playbtnChap2);
pausebtn =(ImageButton)findViewById(R.id.pausebtnChap2);
stopbtn =(ImageButton)findViewById(R.id.stopbtnChap2);
pointer =(ImageView)findViewById(R.id.pointer);
sv_code = (ScrollView)findViewById(R.id.sv_code);
layoutcode = (LinearLayout)findViewById(R.id.layout_code2);
num1 = (TextView)findViewById(R.id.num1_chap2);
num2 = (TextView)findViewById(R.id.num2_chap2);
sign = (TextView)findViewById(R.id.sign_chap2);
result = (TextView)findViewById(R.id.result_chap2);
text_returnChap2 = (TextView)findViewById(R.id.text_return_chap2);
resultChap2text =(TextView)findViewById(R.id.result_chap2_text);
object = (TextView)findViewById(R.id.object);
text_num1 = (TextView)findViewById(R.id.text_num1);
text_num2 = (TextView)findViewById(R.id.text_num2);
text_plus = (TextView)findViewById(R.id.text_plus);
text_minus = (TextView)findViewById(R.id.text_minus);
text_multi =(TextView)findViewById(R.id.text_multi);
text_divide =(TextView)findViewById(R.id.text_divide);
pic_class_chap2 =(ImageView)findViewById(R.id.pic_class_chap2);
class_chap2 = (TextView)findViewById(R.id.class_chap2);
sv_code.scrollTo(0,0);
prepare();
playbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Chapter2.this, "Start!", Toast.LENGTH_SHORT).show();
testPointerLine1();
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread.currentThread().interrupt();
recreate();
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count%2!=0)
{
callingPause();
count +=1;
}
else if(count%2==0)
{
callingResume();
count +=1;
}
}
});
}
//method CallingPuase
private void callingPause()
{
if(checkStateChap2.equals("line1"))
{
objline1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 1 Paused");
}
else if(checkStateChap2.equals("line2"))
{
objline2.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 2 Paused");
}
else if(checkStateChap2.equals("line3"))
{
objline3.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 3 Paused");
}
else if(checkStateChap2.equals("checkingnumbersmoving"))
{
amMovingNum.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","movingNums Paused");
}
else if(checkStateChap2.equals("line17"))
{
objline17.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 17 Paused");
}
else if(checkStateChap2.equals("line29"))
{
objline29.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 29 Paused");
}
else if(checkStateChap2.equals("line30"))
{
objline30.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 30 Paused");
}
else if(checkStateChap2.equals("line31"))
{
objline31.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 31 Paused");
}
else if(checkStateChap2.equals("line32"))
{
objline32.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 32 Paused");
}
else if(checkStateChap2.equals("line18"))
{
objline18.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 18 Paused");
}
else if(checkStateChap2.equals("line3_1"))
{
objline3_1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 3_1 Paused");
}
else if(checkStateChap2.equals("line5"))
{
objline5.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 5 Paused");
}
else if(checkStateChap2.equals("line35"))
{
objline35.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 35 Paused");
}
else if(checkStateChap2.equals("movingtextToResultBoxPlus"))
{
amMovingtextToResultBoxPlus.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationPlus Paused");
}
else if(checkStateChap2.equals("line5_1"))
{
objline5_1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 5_1 Paused");
}
else if(checkStateChap2.equals("line6"))
{
objline6.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 6 Paused");
}
else if(checkStateChap2.equals("line7"))
{
objline7.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 7 Paused");
}
else if(checkStateChap2.equals("line39"))
{
objline39.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 39 Paused");
}
else if(checkStateChap2.equals("movingtextToResultBoxMinus"))
{
amMovingtextToResultBoxMinus.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationMinus Paused");
}
else if(checkStateChap2.equals("line7_1"))
{
objline7_1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 7_1 Paused");
}
else if(checkStateChap2.equals("line8"))
{
objline8.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 8 Paused");
}
else if(checkStateChap2.equals("line9"))
{
objline9.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 9 Paused");
}
else if(checkStateChap2.equals("line20"))
{
objline20.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 20 Paused");
}
else if(checkStateChap2.equals("movingtextToResultBoxMultiply"))
{
amMovingtextToResultBoxMulti.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationMultiply Paused");
}
else if(checkStateChap2.equals("line9_1"))
{
objline9_1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 9_1 Paused");
}
else if(checkStateChap2.equals("line10"))
{
objline10.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 10 Paused");
}
else if(checkStateChap2.equals("line11"))
{
objline11.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 11 Paused");
}
else if(checkStateChap2.equals("line23"))
{
objline23.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 23 Paused");
}
else if(checkStateChap2.equals("movingtextToResultBoxDivide"))
{
amMovingtextToResultBoxDivide.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationDivide Paused");
}
else if(checkStateChap2.equals("line11_1"))
{
objline11_1.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 11_1 Paused");
}
else if(checkStateChap2.equals("line12"))
{
objline12.pause();
Toast.makeText(this, "Paused", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 12 Paused");
}
}
//method callingResume()
private void callingResume()
{
if(checkStateChap2.equals("line1"))
{
objline1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 1 resume");
}
else if(checkStateChap2.equals("line2"))
{
objline2.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 2 resume");
}
else if(checkStateChap2.equals("line3"))
{
objline3.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 3 resume");
}
else if(checkStateChap2.equals("checkingnumbersmoving"))
{
amMovingNum.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","movingNums resume");
}
else if(checkStateChap2.equals("line17"))
{
objline17.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 17 resume");
}
else if(checkStateChap2.equals("line29"))
{
objline29.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 29 resume");
}
else if(checkStateChap2.equals("line30"))
{
objline30.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 30 resume");
}
else if(checkStateChap2.equals("line31"))
{
objline31.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 31 resume");
}
else if(checkStateChap2.equals("line32"))
{
objline32.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 32 resume");
}
else if(checkStateChap2.equals("line18"))
{
objline18.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 18 resume");
}
else if(checkStateChap2.equals("line3_1"))
{
objline3_1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 3_1 resume");
}
else if(checkStateChap2.equals("line5"))
{
objline5.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 5 resume");
}
else if(checkStateChap2.equals("line35"))
{
objline35.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 35 resume");
}
else if(checkStateChap2.equals("movingtextToResultBoxPlus"))
{
amMovingtextToResultBoxPlus.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationPlus resume");
}
else if(checkStateChap2.equals("line5_1"))
{
objline5_1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 5_1 resume");
}
else if(checkStateChap2.equals("line6"))
{
objline6.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 6 resume");
}
else if(checkStateChap2.equals("line7"))
{
objline7.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 7 resume");
}
else if(checkStateChap2.equals("line39"))
{
objline39.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 39 resume");
}
else if(checkStateChap2.equals("movingtextToResultBoxMinus"))
{
amMovingtextToResultBoxMinus.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationMinus resume");
}
else if(checkStateChap2.equals("line7_1"))
{
objline7_1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 7_1 resume");
}
else if(checkStateChap2.equals("line8"))
{
objline8.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 8 resume");
}
else if(checkStateChap2.equals("line9"))
{
objline9.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 9 resume");
}
else if(checkStateChap2.equals("line20"))
{
objline20.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 20 resume");
}
else if(checkStateChap2.equals("movingtextToResultBoxMultiply"))
{
amMovingtextToResultBoxMulti.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationMultiply resume");
}
else if(checkStateChap2.equals("line9_1"))
{
objline9_1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 9_1 resume");
}
else if(checkStateChap2.equals("line10"))
{
objline10.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 10 resume");
}
else if(checkStateChap2.equals("line11"))
{
objline11.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 11 resume");
}
else if(checkStateChap2.equals("line23"))
{
objline23.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 23 resume");
}
else if(checkStateChap2.equals("movingtextToResultBoxDivide"))
{
amMovingtextToResultBoxDivide.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","AnimationDivide resume");
}
else if(checkStateChap2.equals("line11_1"))
{
objline11_1.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 11_1 resume");
}
else if(checkStateChap2.equals("line12"))
{
objline12.resume();
Toast.makeText(this, "Resumed", Toast.LENGTH_SHORT).show();
Log.d("Animation","Line 12 resume");
}
}
//Method Prepare to hide all of objects
private void prepare()
{
sv_code.scrollTo(0,0);
pic_class_chap2.setVisibility(View.INVISIBLE);
text_returnChap2.setVisibility(View.INVISIBLE);
result.setVisibility(View.INVISIBLE);
num1.setVisibility(View.INVISIBLE);
num2.setVisibility(View.INVISIBLE);
sign.setVisibility(View.INVISIBLE);
object.setVisibility(View.INVISIBLE);
resultChap2text.setVisibility(View.INVISIBLE);
text_num1.setVisibility(View.INVISIBLE);
text_num2.setVisibility(View.INVISIBLE);
text_plus.setVisibility(View.INVISIBLE);
text_minus.setVisibility(View.INVISIBLE);
text_multi.setVisibility(View.INVISIBLE);
text_divide.setVisibility(View.INVISIBLE);
}
private void testPointerLine1()
{
checkStateChap2="line1";
checkStateChap2="line1";
objline1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,0);
objline1.setDuration(500);
objline1.start();
objline1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
pic_class_chap2.setVisibility(View.VISIBLE);
class_chap2.setVisibility(View.VISIBLE);
testPointerLine2();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line2
private void testPointerLine2()
{
checkStateChap2="line2";
objline2 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,60);
objline2.setDuration(3000);
objline2.start();
objline2.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine3();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private void testPointerLine3()
{
checkStateChap2="line3";
objline3 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,125);
objline3.setDuration(2000);
objline3.setInterpolator(new LinearInterpolator());
objline3.start();
objline3.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
pic_class_chap2.setImageResource(R.drawable.shape_circle_class);
object.setVisibility(View.VISIBLE);
num1.setVisibility(View.VISIBLE);
num2.setVisibility(View.VISIBLE);
checkingnumbersmoving();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//Checking number moving
private void checkingnumbersmoving()
{
checkStateChap2="checkingnumbersmoving";
ObjectAnimator objnum1_x = ObjectAnimator.ofFloat(num1,View.TRANSLATION_X,250);
ObjectAnimator objnum1_y = ObjectAnimator.ofFloat(num1,View.TRANSLATION_Y,-350);
amMovingNum = new AnimatorSet();
amMovingNum.setDuration(3000);
amMovingNum.setInterpolator(new LinearInterpolator());
amMovingNum.playTogether(objnum1_x,objnum1_y);
amMovingNum.start();
amMovingNum.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
text_num1.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
ObjectAnimator objnum2_x = ObjectAnimator.ofFloat(num2,View.TRANSLATION_X,-250);
ObjectAnimator objnum2_y = ObjectAnimator.ofFloat(num2,View.TRANSLATION_Y,-350);
amMovingNum2 = new AnimatorSet();
amMovingNum2.setDuration(3000);
amMovingNum2.setInterpolator(new LinearInterpolator());
amMovingNum2.playTogether(objnum2_x,objnum2_y);;
amMovingNum2.start();
amMovingNum2.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
text_num2.setVisibility(View.VISIBLE);
// scrolling down
testScrollingDown(2200);
testPointerLine17();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
//Line17
private void testPointerLine17()
{
checkStateChap2="line17";
objline17 = ObjectAnimator.ofFloat(pointer, View.TRANSLATION_Y,680);
objline17.setDuration(2000);
objline17.start();
objline17.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
num1.setText("0");
num2.setText("0");
testScrollingDown(1400);
testPointerLine29();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line29
private void testPointerLine29()
{
checkStateChap2="line29";
objline29 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,610);
objline29.setDuration(4000);
objline29.start();
objline29.setStartDelay(Delaytime);
objline29.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine30();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private void testPointerLine30()
{
checkStateChap2="line30";
objline30 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,670);
objline30.setDuration(3800);
objline30.start();
objline30.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine31();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line31
private void testPointerLine31()
{
checkStateChap2="line31";
objline31 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,730);
objline31.setDuration(3800);
objline31.start();
objline31.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
num1.setText("10");
testPointerLine32();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private void testPointerLine32()
{
checkStateChap2="line32";
objline32 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,790);
objline32.setDuration(3800);
objline32.start();
objline32.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
num2.setText("5");
testScrollingUp(2000);
testPointeLine18();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line18
private void testPointeLine18()
{
checkStateChap2="line18";
objline18 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,550);
objline18.setDuration(7000);
objline18.start();
objline18.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testScrollingUp(2480);
testPointerLine3_1();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//Line3_1
private void testPointerLine3_1()
{
checkStateChap2="line3_1";
objline3_1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,125);
objline3_1.setDuration(4000);
objline3_1.start();
objline3_1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
Toast.makeText(Chapter2.this, "Line 3 again", Toast.LENGTH_SHORT).show();
testPointerLine5();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line5
private void testPointerLine5()
{
checkStateChap2="line5";
objline5 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,240);
objline5.setDuration(4000);
objline5.start();
objline5.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
result.setText("");
result.setVisibility(View.VISIBLE);
resultChap2text.setVisibility(View.VISIBLE);
testScrollingDown(1000);
testPointerLine35();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line35
private void testPointerLine35()
{
checkStateChap2="line35";
objline35 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,570);
objline35.setDuration(9000);
objline35.start();
objline35.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
sign.setText("+");
sign.setVisibility(View.VISIBLE);
text_returnChap2.setVisibility(View.VISIBLE);
movingtextToResultBoxPlus();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//movingtextToResult method
private void movingtextToResultBoxPlus()
{
checkStateChap2="movingtextToResultBoxPlus";
ObjectAnimator objGoX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,-500);
objGoX.setDuration(1000);
ObjectAnimator objGoY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,-450);
objGoY.setDuration(1000);
//Hidding
ObjectAnimator objHide = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,0f);
ObjectAnimator objReturnX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,0);
objReturnX.setDuration(50);
ObjectAnimator objReturnY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,0);
objReturnY.setDuration(50);
//Showing
ObjectAnimator objShow = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,1f);
amMovingtextToResultBoxPlus = new AnimatorSet();
amMovingtextToResultBoxPlus.playSequentially(objGoX,objGoY,objHide,objReturnX,objReturnY,objShow);
checkStateChap2="amMovingtextToResultBoxPlus";
amMovingtextToResultBoxPlus.start();
amMovingtextToResultBoxPlus.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
testScrollingUp(2480);
testPointerLine5_1();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
//Line5_1
private void testPointerLine5_1()
{
checkStateChap2="line5_1";
objline5_1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,240);
objline5_1.setDuration(9000);
objline5_1.start();
objline5_1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine6();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line 6
private void testPointerLine6()
{
checkStateChap2="line6";
objline6 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,300);
objline6.setDuration(4000);
objline6.start();
objline6.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
result.setText("15");
text_plus.setVisibility(View.VISIBLE);
testPointerLine7();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line7
private void testPointerLine7()
{
checkStateChap2="line7";
objline7 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,365);
objline7.setDuration(4000);
objline7.start();
objline7.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testScrollingDown(1000);
testPointerLine39();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line39
private void testPointerLine39()
{
checkStateChap2="line39";
objline39 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,810);
objline39.setDuration(9000);
text_returnChap2.setText("5");
sign.setText("-");
objline39.start();
objline39.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
movingtextToResultBoxMinus();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//Minus animation
private void movingtextToResultBoxMinus()
{
checkStateChap2="movingtextToResultBoxMinus";
ObjectAnimator objGoX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,-500);
objGoX.setDuration(1000);
ObjectAnimator objGoY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,-450);
objGoY.setDuration(1000);
//Hidding
ObjectAnimator objHide = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,0f);
ObjectAnimator objReturnX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,0);
objReturnX.setDuration(50);
ObjectAnimator objReturnY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,0);
objReturnY.setDuration(50);
//Showing
ObjectAnimator objShow = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,1f);
amMovingtextToResultBoxMinus = new AnimatorSet();
amMovingtextToResultBoxMinus.playSequentially(objGoX,objGoY,objHide,objReturnX,objReturnY,objShow);
amMovingtextToResultBoxMinus.start();
amMovingtextToResultBoxMinus.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
testScrollingUp(2480);
testPointerLine7_1();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
//Line7_1
private void testPointerLine7_1()
{
checkStateChap2="line7_1";
objline7_1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y, 365);
objline7_1.setDuration(9000);
objline7_1.start();
objline7_1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine8();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line8
private void testPointerLine8()
{
checkStateChap2="line8";
objline8 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,420);
objline8.setDuration(4000);
objline8.start();
objline8.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
result.setText("5");
text_minus.setVisibility(View.VISIBLE);
testPointerLine9();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line9
private void testPointerLine9()
{
checkStateChap2="line9";
objline9 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,485);
objline9.setDuration(4000);
objline9.start();
objline9.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testScrollingDown(1700);
testPointerLine20();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line20
private void testPointerLine20()
{
checkStateChap2="line20";
sign.setText("*");
objline20 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,360);
objline20.setDuration(4000);
objline20.start();
objline20.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
text_returnChap2.setText("50");
movingtextToResultBoxMutiply();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//multiply animation
private void movingtextToResultBoxMutiply()
{
checkStateChap2="movingtextToResultBoxMultiply";
ObjectAnimator objGoX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,-500);
objGoX.setDuration(1000);
ObjectAnimator objGoY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,-450);
objGoY.setDuration(1000);
//Hidding
ObjectAnimator objHide = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,0f);
ObjectAnimator objReturnX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,0);
objReturnX.setDuration(50);
ObjectAnimator objReturnY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,0);
objReturnY.setDuration(50);
//Showing
ObjectAnimator objShow = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,1f);
amMovingtextToResultBoxMulti = new AnimatorSet();
amMovingtextToResultBoxMulti.playSequentially(objGoX,objGoY,objHide,objReturnX,objReturnY,objShow);
amMovingtextToResultBoxMulti.start();
amMovingtextToResultBoxMulti.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
testScrollingUp(2480);
testPointerLine9_1();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
//line9_1
private void testPointerLine9_1()
{
checkStateChap2="line9_1";
objline9_1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,485);
objline9_1.setDuration(4000);
objline9_1.start();
objline9_1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine10();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line10
private void testPointerLine10()
{
checkStateChap2="line10";
objline10 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,540);
objline10.setDuration(4000);
objline10.start();
objline10.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
result.setText("50");
text_multi.setVisibility(View.VISIBLE);
testPointerLine11();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line11
private void testPointerLine11()
{
checkStateChap2="line11";
objline11 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,600);
objline11.setDuration(4000);
objline11.start();
objline11.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testScrollingDown(1700);
testPointerLine23();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line23
private void testPointerLine23()
{
checkStateChap2="line23";
sign.setText("/");
text_returnChap2.setText("2");
objline23 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,550);
objline23.setDuration(4000);
objline23.start();
objline23.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
movingtextToResultBoxDivide();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//divide animation
private void movingtextToResultBoxDivide()
{
checkStateChap2="movingtextToResultBoxDivide";
ObjectAnimator objGoX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,-500);
objGoX.setDuration(1000);
ObjectAnimator objGoY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,-450);
objGoY.setDuration(1000);
//Hidding
ObjectAnimator objHide = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,0f);
ObjectAnimator objReturnX = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_X,0);
objReturnX.setDuration(50);
ObjectAnimator objReturnY = ObjectAnimator.ofFloat(text_returnChap2,View.TRANSLATION_Y,0);
objReturnY.setDuration(50);
//Showing
ObjectAnimator objShow = ObjectAnimator.ofFloat(text_returnChap2,View.ALPHA,1f);
amMovingtextToResultBoxDivide = new AnimatorSet();
amMovingtextToResultBoxDivide.playSequentially(objGoX,objGoY,objHide,objReturnX,objReturnY,objShow);
amMovingtextToResultBoxDivide.start();
amMovingtextToResultBoxDivide.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
testScrollingUp(2480);
testPointerLine11_1();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
//line11_1
private void testPointerLine11_1()
{
checkStateChap2="line11_1";
objline11_1 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,600);
objline11_1.setDuration(4000);
objline11_1.start();
objline11_1.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
testPointerLine12();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//line12
private void testPointerLine12()
{
checkStateChap2="line12";
objline12 = ObjectAnimator.ofFloat(pointer,View.TRANSLATION_Y,660);
objline12.setDuration(4000);
objline12.start();
objline12.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
result.setText("2");
text_divide.setVisibility(View.VISIBLE);
Toast.makeText(Chapter2.this, "Finish", Toast.LENGTH_SHORT).show();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
//Scrolling up
private void testScrollingUp(final int a)
{
new Thread(new Runnable() {
@Override
public void run()
{
//Checking what 'CheckingControl' is ?
if(checkScrolling)
{
//CheckControl is 'false' then Creates runOnUIThread's method.
checkScrolling = false;
//Looping when 'CheckControl' is false.
while(!checkScrolling)
{
try
{
//Creating runOnUiThread for scrolling down the code.
runOnUiThread(new Runnable() {
@Override
public void run() {
//Scrolling down the code every 1 px.
sv_code.scrollBy(0,-1);
//If reachs the bottom line of code then stops it.
if(sv_code.getScrollY()==layoutcode.getHeight()-a)
{
//Changing 'checkControl' to 'true' for exit while loop.
checkScrolling=true;
}
}
});
//Slowing speed of scroll down.
Thread.sleep(5);
}
//To handle ThreadException by handler 'InteruptException'.
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//If 'checkControl' is not 'true' then makes it 'true'.
else
{
checkScrolling =true;
}
}
}//This statement for starting the new thread execution.
).start();
}
//SCrolling down
private void testScrollingDown(final int a)
{
new Thread(new Runnable() {
@Override
public void run()
{
//Checking what 'CheckingControl' is ?
if(checkScrolling)
{
//CheckControl is 'false' then Creates runOnUIThread's method.
checkScrolling = false;
//Looping when 'CheckControl' is false.
while(!checkScrolling)
{
try
{
//Creating runOnUiThread for scrolling down the code.
runOnUiThread(new Runnable() {
@Override
public void run() {
//Scrolling down the code every 1 px.
sv_code.scrollBy(0,1);
//If reachs the bottom line of code then stops it.
if(sv_code.getScrollY()==layoutcode.getBottom()-a)
{
//Changing 'checkControl' to 'true' for exit while loop.
checkScrolling=true;
}
}
});
//Slowing speed of scroll down.
Thread.sleep(5);
}
//To handle ThreadException by handler 'InteruptException'.
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//If 'checkControl' is not 'true' then makes it 'true'.
else
{
checkScrolling =true;
}
}
}//This statement for starting the new thread execution.
).start();
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this,List_chapter.class);
sv_code.scrollTo(0,0);
startActivity(intent);
finish();
}
} |
package railo.commons.pdf;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import railo.commons.io.IOUtil;
import railo.commons.io.SystemUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.HTMLEntities;
import railo.commons.lang.StringUtil;
import railo.commons.net.HTTPUtil;
import railo.runtime.Info;
import railo.runtime.PageContext;
import railo.runtime.config.ConfigWeb;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.functions.system.ContractPath;
import railo.runtime.functions.system.GetDirectoryFromPath;
import railo.runtime.op.Caster;
import railo.runtime.text.xml.XMLCaster;
import railo.runtime.text.xml.XMLUtil;
import railo.runtime.type.List;
import railo.runtime.type.scope.CGIImpl;
import railo.runtime.util.URLResolver;
public final class PDFDocument {
// PageType
public static final Dimension PAGETYPE_ISOB5 = new Dimension(501, 709);
public static final Dimension PAGETYPE_ISOB4 = new Dimension(709, 1002);
public static final Dimension PAGETYPE_ISOB3 = new Dimension(1002, 1418);
public static final Dimension PAGETYPE_ISOB2 = new Dimension(1418, 2004);
public static final Dimension PAGETYPE_ISOB1 = new Dimension(2004, 2836);
public static final Dimension PAGETYPE_ISOB0 = new Dimension(2836, 4008);
public static final Dimension PAGETYPE_HALFLETTER = new Dimension(396, 612);
public static final Dimension PAGETYPE_LETTER = new Dimension(612, 792);
public static final Dimension PAGETYPE_TABLOID = new Dimension(792, 1224);
public static final Dimension PAGETYPE_LEDGER = new Dimension(1224, 792);
public static final Dimension PAGETYPE_NOTE = new Dimension(540, 720);
public static final Dimension PAGETYPE_LEGAL = new Dimension(612, 1008);
public static final Dimension PAGETYPE_A10 = new Dimension(74, 105);
public static final Dimension PAGETYPE_A9 = new Dimension(105, 148);
public static final Dimension PAGETYPE_A8 = new Dimension(148, 210);
public static final Dimension PAGETYPE_A7 = new Dimension(210, 297);
public static final Dimension PAGETYPE_A6 = new Dimension(297, 421);
public static final Dimension PAGETYPE_A5 = new Dimension(421, 595);
public static final Dimension PAGETYPE_A4 = new Dimension(595, 842);
public static final Dimension PAGETYPE_A3 = new Dimension(842, 1190);
public static final Dimension PAGETYPE_A2 = new Dimension(1190, 1684);
public static final Dimension PAGETYPE_A1 = new Dimension(1684, 2384);
public static final Dimension PAGETYPE_A0 = new Dimension(2384, 3370);
public static final Dimension PAGETYPE_B4=new Dimension(708,1000);
public static final Dimension PAGETYPE_B5=new Dimension(499,708);
public static final Dimension PAGETYPE_B4_JIS=new Dimension(728,1031);
public static final Dimension PAGETYPE_B5_JIS=new Dimension(516,728);
public static final Dimension PAGETYPE_CUSTOM=new Dimension(1,1);
// encryption
public static final int ENC_NONE=0;
public static final int ENC_40BIT=1;
public static final int ENC_128BIT=2;
// fontembed
public static final int FONT_EMBED_NO=0;
public static final int FONT_EMBED_YES=1;
public static final int FONT_EMBED_SELECCTIVE=FONT_EMBED_YES;
// unit
public static final double UNIT_FACTOR_CM=85d/3d;// =28.333333333333333333333333333333333333333333;
public static final double UNIT_FACTOR_IN=UNIT_FACTOR_CM*2.54;
public static final double UNIT_FACTOR_POINT=1;
// margin init
private static final int MARGIN_INIT=36;
// mimetype
private static final int MIMETYPE_TEXT_HTML = 0;
private static final int MIMETYPE_TEXT = 1;
private static final int MIMETYPE_IMAGE = 2;
private static final int MIMETYPE_APPLICATION = 3;
private static final int MIMETYPE_OTHER = -1;
private static final String USER_AGENT = "Railo "+Info.getVersionAsString()+" "+Info.getStateAsString();
private double margintop=-1;
private double marginbottom=-1;
private double marginleft=-1;
private double marginright=-1;
private int mimetype=MIMETYPE_TEXT_HTML;
private String strMimetype=null;
private String strCharset=null;
private boolean backgroundvisible;
private boolean fontembed=true;
private PDFPageMark header;
private PDFPageMark footer;
private String proxyserver;
private int proxyport=80;
private String proxyuser=null;
private String proxypassword="";
private String src=null;
private Resource srcfile=null;
private String body;
//private boolean isEvaluation;
private String name;
private String authUser;
private String authPassword;
private String userAgent=USER_AGENT;
private boolean localUrl;
private boolean bookmark;
private boolean htmlBookmark;
public PDFDocument(){
//this.isEvaluation=isEvaluation;
}
public void setHeader(PDFPageMark header) {
this.header=header;
}
public void setFooter(PDFPageMark footer) {
this.footer=footer;
}
/**
* @param marginbottom the marginbottom to set
*/
public void setMarginbottom(double marginbottom) {
this.marginbottom = marginbottom;
}
/**
* @param marginleft the marginleft to set
*/
public void setMarginleft(double marginleft) {
this.marginleft = marginleft;
}
/**
* @param marginright the marginright to set
*/
public void setMarginright(double marginright) {
this.marginright = marginright;
}
/**
* @param margintop the margintop to set
*/
public void setMargintop(double margintop) {
this.margintop = margintop;
}
/**
* @param mimetype the mimetype to set
*/
public void setMimetype(String strMimetype) {
strMimetype = strMimetype.toLowerCase().trim();
this.strMimetype=strMimetype;
// mimetype
if(strMimetype.startsWith("text/html")) mimetype=MIMETYPE_TEXT_HTML;
else if(strMimetype.startsWith("text/")) mimetype=MIMETYPE_TEXT;
else if(strMimetype.startsWith("image/")) mimetype=MIMETYPE_IMAGE;
else if(strMimetype.startsWith("application/")) mimetype=MIMETYPE_APPLICATION;
else mimetype=MIMETYPE_OTHER;
// charset
String[] arr = List.listToStringArray(strMimetype, ';');
if(arr.length>=2) {
this.strMimetype=arr[0].trim();
for(int i=1;i<arr.length;i++) {
String[] item = List.listToStringArray(arr[i], '=');
if(item.length==1) {
strCharset=item[0].trim();
break;
}
else if(item.length==2 && item[0].trim().equals("charset")) {
strCharset=item[1].trim();
break;
}
}
}
}
/** set the value proxyserver
* Host name or IP address of a proxy server.
* @param proxyserver value to set
**/
public void setProxyserver(String proxyserver) {
this.proxyserver=proxyserver;
}
/** set the value proxyport
* The port number on the proxy server from which the object is requested. Default is 80. When
* used with resolveURL, the URLs of retrieved documents that specify a port number are automatically
* resolved to preserve links in the retrieved document.
* @param proxyport value to set
**/
public void setProxyport(int proxyport) {
this.proxyport=proxyport;
}
/** set the value username
* When required by a proxy server, a valid username.
* @param proxyuser value to set
**/
public void setProxyuser(String proxyuser) {
this.proxyuser=proxyuser;
}
/** set the value password
* When required by a proxy server, a valid password.
* @param proxypassword value to set
**/
public void setProxypassword(String proxypassword) {
this.proxypassword=proxypassword;
}
/**
* @param src
* @throws PDFException
*/
public void setSrc(String src) throws PDFException {
if(srcfile!=null) throw new PDFException("You cannot specify both the src and srcfile attributes");
this.src = src;
}
/**
* @param srcfile the srcfile to set
* @throws PDFException
*/
public void setSrcfile(Resource srcfile) throws PDFException {
if(src!=null) throw new PDFException("You cannot specify both the src and srcfile attributes");
this.srcfile=srcfile;
}
public void setBody(String body) {
this.body=body;
}
public byte[] render(Dimension dimension,double unitFactor, PageContext pc,boolean generateOutlines) throws PageException, IOException {
ConfigWeb config = pc.getConfig();
PDF pd4ml = new PDF(config);
pd4ml.generateOutlines(generateOutlines);
pd4ml.enableTableBreaks(true);
pd4ml.interpolateImages(true);
// DO NOT ENABLE pd4ml.adjustHtmlWidth();
//check size
int mTop = toPoint(margintop,unitFactor);
int mLeft = toPoint(marginleft,unitFactor);
int mBottom=toPoint(marginbottom,unitFactor);
int mRight=toPoint(marginright,unitFactor);
if((mLeft+mRight)>dimension.getWidth())
throw new ExpressionException("current document width ("+Caster.toString(dimension.getWidth())+" point) is smaller that specified horizontal margin ("+Caster.toString(mLeft+mRight)+" point).",
"1 in = "+Math.round(1*UNIT_FACTOR_IN)+" point and 1 cm = "+Math.round(1*UNIT_FACTOR_CM)+" point");
if((mTop+mBottom)>dimension.getHeight())
throw new ExpressionException("current document height ("+Caster.toString(dimension.getHeight())+" point) is smaller that specified vertical margin ("+Caster.toString(mTop+mBottom)+" point).",
"1 in = "+Math.round(1*UNIT_FACTOR_IN)+" point and 1 cm = "+Math.round(1*UNIT_FACTOR_CM)+" point");
// Size
pd4ml.setPageInsets(new Insets(mTop,mLeft,mBottom,mRight));
pd4ml.setPageSize(dimension);
// header
if(header!=null) pd4ml.setPageHeader(header);
// footer
if(footer!=null) pd4ml.setPageFooter(footer);
// content
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try {
content(pd4ml,pc,baos);
}
finally {
IOUtil.closeEL(baos);
}
return baos.toByteArray();
}
private void content(PDF pd4ml, PageContext pc, OutputStream os) throws PageException, IOException {
ConfigWeb config = pc.getConfig();
pd4ml.useTTF("java:fonts", fontembed);
// body
if(!StringUtil.isEmpty(body,true)) {
// optimize html
URL base = getBase(pc);
try {
body=beautifyHTML(new InputSource(new StringReader(body)),base);
}catch (Throwable t) {}
pd4ml.render(body, os,base);
}
// srcfile
else if(srcfile!=null) {
if(StringUtil.isEmpty(strCharset))strCharset=pc.getConfig().getResourceCharset();
// mimetype
if(StringUtil.isEmpty(strMimetype)) {
String mt = ResourceUtil.getMymeType(srcfile,null);
if(mt!=null) setMimetype(mt);
}
InputStream is = srcfile.getInputStream();
try {
URL base = new URL("file://"+srcfile);
if(!localUrl){
//PageContext pc = Thread LocalPageContext.get();
if(pc!=null) {
String abs = srcfile.getAbsolutePath();
String contract = ContractPath.call(pc, abs);
if(!abs.equals(contract)) {
base=HTTPUtil.toURL(CGIImpl.getDomain(pc.getHttpServletRequest())+contract);
}
}
}
//URL base = localUrl?new URL("file://"+srcfile):getBase();
render(pd4ml, is,os,base);
}
catch (Throwable t) {}
finally {
IOUtil.closeEL(is);
}
}
// src
else if(src!=null) {
if(StringUtil.isEmpty(strCharset))strCharset="iso-8859-1";
URL url = HTTPUtil.toURL(src);
// set Proxy
if(StringUtil.isEmpty(proxyserver) && config.isProxyEnableFor(url.getHost())) {
proxyserver=config.getProxyServer();
proxyport=config.getProxyPort();
proxyuser=config.getProxyUsername();
proxypassword=config.getProxyPassword();
}
HttpMethod method = HTTPUtil.invoke(url, authUser, authPassword, -1, null, userAgent,
proxyserver,
proxyport,
proxyuser,
proxypassword,null);
// mimetype
if(StringUtil.isEmpty(strMimetype)) {
Header[] headers = method.getResponseHeaders();
for(int i=0;i<headers.length;i++) {
if(headers[i].getName().equalsIgnoreCase("Content-type") && !StringUtil.isEmpty(headers[i].getValue())) {
setMimetype(headers[i].getValue());
break;
}
}
}
InputStream is =
new ByteArrayInputStream(method.getResponseBody());
//method.getResponseBodyAsStream();
try {
render(pd4ml, is, os,url);
}
finally {
IOUtil.closeEL(is);
}
}
else {
pd4ml.render("<html><body> </body></html>", os,null);
}
}
private static String beautifyHTML(InputSource is,URL base) throws ExpressionException, SAXException, IOException {
Document xml = XMLUtil.parse(is,null,true);
patchPD4MLProblems(xml);
if(base!=null)URLResolver.getInstance().transform(xml, base);
String html = XMLCaster.toHTML(xml);
return html;
}
private static void patchPD4MLProblems(Document xml) {
Element b = XMLUtil.getChildWithName("body", xml.getDocumentElement());
if(!b.hasChildNodes()){
b.appendChild(xml.createTextNode(" "));
}
}
private static URL getBase(PageContext pc) throws MalformedURLException {
//PageContext pc = Thread LocalPageContext.get();
if(pc==null)return null;
String userAgent = pc.getHttpServletRequest().getHeader("User-Agent");
// bug in pd4ml-> html badse definition create a call
if(!StringUtil.isEmpty(userAgent) && userAgent.startsWith("Java"))return null;
return HTTPUtil.toURL(GetDirectoryFromPath.call(pc,CGIImpl.getCurrentURL(pc.getHttpServletRequest())));
}
private void render(PDF pd4ml, InputStream is,OutputStream os, URL base) throws IOException, PageException {
try {
// text/html
if(mimetype==MIMETYPE_TEXT_HTML) {
body="";
try {
InputSource input = new InputSource(IOUtil.getReader(is,strCharset));
body=beautifyHTML(input,base);
}
catch (Throwable t) {}
//else if(body==null)body =IOUtil.toString(is,strCharset);
pd4ml.render(body, os,base);
}
// text
else if(mimetype==MIMETYPE_TEXT) {
body =IOUtil.toString(is,strCharset);
body="<html><body><pre>"+HTMLEntities.escapeHTML(body)+"</pre></body></html>";
pd4ml.render(body, os,null);
}
// image
else if(mimetype==MIMETYPE_IMAGE) {
Resource tmpDir= SystemUtil.getTempDirectory();
Resource tmp = tmpDir.getRealResource(this+"-"+Math.random());
IOUtil.copy(is, tmp,true);
body="<html><body><img src=\"file://"+tmp+"\"></body></html>";
try {
pd4ml.render(body, os,null);
}
finally {
tmp.delete();
}
}
// Application
else if(mimetype==MIMETYPE_APPLICATION && "application/pdf".equals(strMimetype)) {
IOUtil.copy(is, os,true,true);
}
else pd4ml.render(new InputStreamReader(is), os);
}
finally {
IOUtil.closeEL(is,os);
}
}
public static int toPoint(double value,double unitFactor) {
if(value<0) return MARGIN_INIT;
return (int)Math.round(value*unitFactor);
//return r;
}
public PDFPageMark getHeader() {
return header;
}
public PDFPageMark getFooter() {
return footer;
}
public void setFontembed(int fontembed) {
this.fontembed=fontembed!=FONT_EMBED_NO;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the authUser
*/
public String getAuthUser() {
return authUser;
}
/**
* @param authUser the authUser to set
*/
public void setAuthUser(String authUser) {
this.authUser = authUser;
}
/**
* @return the authPassword
*/
public String getAuthPassword() {
return authPassword;
}
/**
* @param authPassword the authPassword to set
*/
public void setAuthPassword(String authPassword) {
this.authPassword = authPassword;
}
/**
* @return the userAgent
*/
public String getUserAgent() {
return userAgent;
}
/**
* @param userAgent the userAgent to set
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
/**
* @return the proxyserver
*/
public String getProxyserver() {
return proxyserver;
}
/**
* @return the proxyport
*/
public int getProxyport() {
return proxyport;
}
/**
* @return the proxyuser
*/
public String getProxyuser() {
return proxyuser;
}
/**
* @return the proxypassword
*/
public String getProxypassword() {
return proxypassword;
}
public boolean hasProxy() {
return !StringUtil.isEmpty(proxyserver);
}
/**
* @return the localUrl
*/
public boolean getLocalUrl() {
return localUrl;
}
/**
* @param localUrl the localUrl to set
*/
public void setLocalUrl(boolean localUrl) {
this.localUrl = localUrl;
}
/**
* @return the bookmark
*/
public boolean getBookmark() {
return bookmark;
}
/**
* @param bookmark the bookmark to set
*/
public void setBookmark(boolean bookmark) {
this.bookmark = bookmark;
}
/**
* @return the htmlBookmark
*/
public boolean getHtmlBookmark() {
return htmlBookmark;
}
/**
* @param htmlBookmark the htmlBookmark to set
*/
public void setHtmlBookmark(boolean htmlBookmark) {
this.htmlBookmark = htmlBookmark;
}
} |
package com.udpwork.ssdb;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Response{
public String status;
public List<byte[]> raw;
/**
* Indicates items' order
*/
public List<byte[]> keys = new ArrayList<byte[]>();
/**
* key-value results
*/
public Map<byte[], byte[]> items = new LinkedHashMap<byte[], byte[]>();
public Response(List<byte[]> raw){
this.raw = raw;
if(raw.size() > 0){
status = new String(raw.get(0));
}
}
public Object exception() throws Exception{
if(raw.size() >= 2){
throw new Exception(new String(raw.get(1)));
}else{
throw new Exception("");
}
}
public boolean ok(){
return status.equals("ok");
}
public boolean not_found(){
return status.equals("not_found");
}
public void buildMap(){
for(int i=1; i<raw.size(); i+=2){
byte[] k = raw.get(i);
byte[] v = raw.get(i+1);
keys.add(k);
items.put(k, v);
}
}
public void print(){
System.out.println(String.format("%-15s %s", "key", "value"));
System.out.println("
for (byte[] bs : keys) {
System.out.print(String.format("%-15s", MemoryStream.repr(bs)));
System.out.print(": ");
System.out.print(MemoryStream.repr(items.get(bs)));
System.out.println();
}
}
} |
package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class CalculateHistory {
@Parameter(description = "chronologically-sorted-input-file", required = true)
private List<String> parameters = new ArrayList<String>();
private File inputFile;
@Parameter(names = "-w", description = "Window size", required = true)
private int windowSize;
@Parameter(names = "-s", description = "Step size", required = true)
private int stepSize;
private int stepsPerWindow;
@Parameter(names = "-t", description = "File with terms", required = true)
private File termsFile;
@Parameter(names = "-tcol", description = "Index or name of column to read terms (if term file is in CSV format)")
private String termCol = "TERM";
@Parameter(names = "-c", description = "Only use first c terms")
private int termCount = -1;
@Parameter(names = "-m", description = "Metrics to use (comma separated): 'ms' = meme score, " +
"'ps' = propagation score, 'st' = sticking factor, 'sp' = sparking factor, 'af' = absolute frequency")
private String metrics = "ms";
@Parameter(names = "-n", description = "Set n parameter")
private int n = 1;
@Parameter(names = "-v", description = "Write detailed log")
private boolean verbose = false;
private File logFile;
public static final void main(String[] args) {
CalculateHistory obj = new CalculateHistory();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
if (obj.parameters.size() != 1) {
System.err.println("ERROR: Exactly one main argument is needed");
jc.usage();
System.exit(1);
}
if (obj.stepSize <= 0 || obj.windowSize <= obj.stepSize) {
System.err.println("ERROR: Step size has to be positive and smaller than window size");
jc.usage();
System.exit(1);
}
if (obj.windowSize % obj.stepSize != 0) {
System.err.println("ERROR: Window size must be a multiple of step size");
jc.usage();
System.exit(1);
}
obj.inputFile = new File(obj.parameters.get(0));
obj.run();
}
private MemeScorer[] ms;
private List<String> terms;
private List<CsvListWriter> csvWriters;
public void run() {
init();
try {
readTerms();
processAndWriteData();
} catch (Throwable th) {
log(th);
System.exit(1);
}
log("Finished");
}
private void init() {
logFile = new File(MemeUtils.getLogDir(), getOutputFileName(metrics) + ".log");
log("==========");
stepsPerWindow = windowSize / stepSize;
ms = new MemeScorer[stepsPerWindow];
ms[0] = new MemeScorer(MemeScorer.GIVEN_TERMLIST_MODE);
for (int i = 1 ; i < stepsPerWindow ; i++) {
ms[i] = new MemeScorer(ms[0], MemeScorer.GIVEN_TERMLIST_MODE);
}
terms = new ArrayList<String>();
csvWriters = new ArrayList<CsvListWriter>();
}
private void readTerms() throws IOException {
log("Reading terms from " + termsFile + " ...");
if (termsFile.toString().endsWith(".csv")) {
readTermsCsv();
} else {
readTermsTxt();
}
log("Number of terms: " + terms.size());
}
private void readTermsTxt() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(termsFile));
String line;
while ((line = reader.readLine()) != null) {
String term = MemeUtils.normalize(line);
ms[0].addTerm(term);
terms.add(term);
if (termCount >= 0 && terms.size() >= termCount) {
break;
}
}
reader.close();
}
private void readTermsCsv() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(termsFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
List<String> header = csvReader.read();
int col;
if (termCol.matches("[0-9]+")) {
col = Integer.parseInt(termCol);
} else {
col = header.indexOf(termCol);
}
List<String> line;
while ((line = csvReader.read()) != null) {
String term = MemeUtils.normalize(line.get(col));
ms[0].addTerm(term);
terms.add(term);
if (termCount >= 0 && terms.size() >= termCount) {
break;
}
}
csvReader.close();
}
private void processAndWriteData() throws IOException {
log("Processing data from " + inputFile + " and writing result to output files...");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
for (String metric : metrics.split(",")) {
File outputFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName(metric) + ".csv");
BufferedWriter w = new BufferedWriter(new FileWriter(outputFile));
csvWriters.add(new CsvListWriter(w, MemeUtils.getCsvPreference()));
}
List<String> outputHeader = new ArrayList<String>();
outputHeader.add("DATE");
for (String term : terms) outputHeader.add(term);
for (CsvListWriter csvWriter : csvWriters) {
csvWriter.write(outputHeader);
}
int entryCount = 0;
int bin = 0;
String inputLine;
while ((inputLine = reader.readLine()) != null) {
logProgress(entryCount);
DataEntry d = new DataEntry(inputLine);
ms[bin].recordTerms(d);
entryCount++;
bin = (entryCount % windowSize) / stepSize;
if (entryCount % stepSize == 0) {
// Current bin is full
if (entryCount >= windowSize) {
// All bins are full
writeLine(d.getDate());
}
logDetail("Start new bin " + bin + " (at entry " + entryCount + ")");
ms[bin].clear();
}
}
log(((entryCount - windowSize) / stepSize + 1) + " output entries written");
log((entryCount % stepSize) + " final input entries ignored");
reader.close();
for (CsvListWriter csvWriter : csvWriters) {
csvWriter.close();
}
}
private void writeLine(String date) throws IOException {
List<List<String>> outputLines = new ArrayList<List<String>>();
String[] metricsArray = metrics.split(",");
for (int i = 0 ; i < metricsArray.length ; i++) {
List<String> outputLine = new ArrayList<String>();
outputLine.add(date);
outputLines.add(outputLine);
}
List<String> outputLine = new ArrayList<String>();
outputLine.add(date);
for (String term : terms) {
int mmVal = 0, mVal = 0, xmVal = 0, xVal = 0, fVal = 0;
for (MemeScorer m : ms) {
mmVal += m.getMM(term);
mVal += m.getM(term);
xmVal += m.getXM(term);
xVal += m.getX(term);
fVal += m.getF(term);
}
double[] v = MemeScorer.calculateMemeScoreValues(mmVal, mVal, xmVal, xVal, fVal, n);
for (int i = 0 ; i < metricsArray.length ; i++) {
String metric = metricsArray[i];
if (metric.equals("st")) {
outputLines.get(i).add(v[0] + "");
} else if (metric.equals("sp")) {
outputLines.get(i).add(v[1] + "");
} else if (metric.equals("ps")) {
outputLines.get(i).add(v[2] + "");
} else if (metric.equals("ms")) {
outputLines.get(i).add(v[3] + "");
} else if (metric.equals("af")) {
outputLines.get(i).add(fVal + "");
}
}
}
for (int i = 0 ; i < metricsArray.length ; i++) {
csvWriters.get(i).write(outputLines.get(i));
}
}
private String getOutputFileName(String metric) {
String basename = inputFile.getName().replaceAll("\\..*$", "");
basename = basename.replace("-chronologic", "");
String filename = "hi-" + metric + "-" + basename + "-n" + n + "-w" + windowSize + "-s" + stepSize;
return filename;
}
private void logProgress(int p) {
if (p % 100000 == 0) log(p + "...");
}
private void log(Object obj) {
MemeUtils.log(logFile, obj);
}
private void logDetail(Object obj) {
if (verbose) log(obj);
}
} |
package com.conveyal.gtfs.model;
import com.conveyal.gtfs.GTFSFeed;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class Route extends Entity { // implements Entity.Factory<Route>
private static final long serialVersionUID = -819444896818029068L;
//Used for converting extended route types to simple route types
public static final Map<Integer, Integer> EXTENTED_ROUTE_TYPE_MAPPING = new HashMap<>();
static {
EXTENTED_ROUTE_TYPE_MAPPING.put(100, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(101, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(102, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(103, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(105, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(106, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(107, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(108, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(109, 2);
EXTENTED_ROUTE_TYPE_MAPPING.put(200, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(201, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(202, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(204, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(208, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(400, 1);
EXTENTED_ROUTE_TYPE_MAPPING.put(401, 1);
EXTENTED_ROUTE_TYPE_MAPPING.put(402, 1);
EXTENTED_ROUTE_TYPE_MAPPING.put(405, 1);
EXTENTED_ROUTE_TYPE_MAPPING.put(700, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(701, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(702, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(704, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(715, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(717, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(800, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(900, 0);
EXTENTED_ROUTE_TYPE_MAPPING.put(1000, 4);
EXTENTED_ROUTE_TYPE_MAPPING.put(1300, 6);
EXTENTED_ROUTE_TYPE_MAPPING.put(1400, 7);
EXTENTED_ROUTE_TYPE_MAPPING.put(1501, 3);
EXTENTED_ROUTE_TYPE_MAPPING.put(1700, 3);
}
public String route_id;
public String agency_id;
public String route_short_name;
public String route_long_name;
public String route_desc;
public int route_type;
public URL route_url;
public String route_color;
public String route_text_color;
public URL route_branding_url;
public String feed_id;
public static class Loader extends Entity.Loader<Route> {
public Loader(GTFSFeed feed) {
super(feed, "routes");
}
@Override
protected boolean isRequired() {
return true;
}
@Override
public void loadOneRow() throws IOException {
Route r = new Route();
r.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index
r.route_id = getStringField("route_id", true);
Agency agency = getRefField("agency_id", false, feed.agency);
// if there is only one agency, associate with it automatically
if (agency == null && feed.agency.size() == 1) {
agency = feed.agency.values().iterator().next();
}
// If we still haven't got an agency, it's because we have a bad reference, or because there is no agency
if (agency != null) {
r.agency_id = agency.agency_id;
}
r.route_short_name = getStringField("route_short_name", false); // one or the other required, needs a special validator
r.route_long_name = getStringField("route_long_name", false);
r.route_desc = getStringField("route_desc", false);
r.route_type = getIntField("route_type", true, 0, 7, 0, EXTENTED_ROUTE_TYPE_MAPPING);
r.route_url = getUrlField("route_url", false);
r.route_color = getStringField("route_color", false);
r.route_text_color = getStringField("route_text_color", false);
r.route_branding_url = getUrlField("route_branding_url", false);
r.feed = feed;
r.feed_id = feed.feedId;
feed.routes.put(r.route_id, r);
}
}
} |
package com.swabunga.spell.event;
import java.util.*;
import java.io.*;
/** This class tokenizes a input file.
* <p>
* Any takers to do this efficiently?? Doesnt need to replace any words to start with
* . I need this to get an idea of how quick the spell checker is.
*/
public class FileWordTokenizer implements WordTokenizer {
public FileWordTokenizer(File inputFile) {
}
public boolean hasMoreWords() {
return false;
}
public int getCurrentWordPosition() {
return 0;
}
/** Returns the current end word position in the text
*
*/
public int getCurrentWordEnd() {
return 0;
}
public String nextWord() {
return null;
}
public int getCurrentWordCount() {
return 0;
}
/** Replaces the current word token*/
public void replaceWord(String newWord) {
}
/** Returns the current text that is being tokenized (includes any changes
* that have been made)
*/
public String getContext() {
return null;
}
/** returns true iif the current word is at the start of a sentance*/
public boolean isNewSentance() {
return false;
}
} |
package ee.ria.DigiDoc.android;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.os.StrictMode;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
import com.google.common.collect.ImmutableList;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Date;
import java.util.Map;
import javax.inject.Provider;
import javax.inject.Singleton;
import dagger.Binds;
import dagger.BindsInstance;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
import dagger.multibindings.ClassKey;
import dagger.multibindings.IntoMap;
import ee.ria.DigiDoc.BuildConfig;
import ee.ria.DigiDoc.R;
import ee.ria.DigiDoc.android.crypto.create.CryptoCreateViewModel;
import ee.ria.DigiDoc.android.eid.EIDHomeViewModel;
import ee.ria.DigiDoc.android.main.diagnostics.DiagnosticsView;
import ee.ria.DigiDoc.android.main.diagnostics.DiagnosticsViewModel;
import ee.ria.DigiDoc.android.main.diagnostics.source.DiagnosticsDataSource;
import ee.ria.DigiDoc.android.main.diagnostics.source.FileSystemDiagnosticsDataSource;
import ee.ria.DigiDoc.android.main.home.HomeViewModel;
import ee.ria.DigiDoc.android.main.settings.SettingsDataStore;
import ee.ria.DigiDoc.android.signature.create.SignatureCreateViewModel;
import ee.ria.DigiDoc.android.signature.data.SignatureContainerDataSource;
import ee.ria.DigiDoc.android.signature.data.source.FileSystemSignatureContainerDataSource;
import ee.ria.DigiDoc.android.signature.list.SignatureListViewModel;
import ee.ria.DigiDoc.android.signature.update.SignatureUpdateViewModel;
import ee.ria.DigiDoc.android.utils.Formatter;
import ee.ria.DigiDoc.android.utils.LocaleService;
import ee.ria.DigiDoc.android.utils.TSLUtil;
import ee.ria.DigiDoc.android.utils.navigator.Navigator;
import ee.ria.DigiDoc.android.utils.navigator.conductor.ConductorNavigator;
import ee.ria.DigiDoc.configuration.ConfigurationConstants;
import ee.ria.DigiDoc.configuration.ConfigurationManager;
import ee.ria.DigiDoc.configuration.ConfigurationManagerService;
import ee.ria.DigiDoc.configuration.ConfigurationProperties;
import ee.ria.DigiDoc.configuration.ConfigurationProvider;
import ee.ria.DigiDoc.configuration.loader.CachedConfigurationHandler;
import ee.ria.DigiDoc.configuration.util.FileUtils;
import ee.ria.DigiDoc.configuration.util.UserAgentUtil;
import ee.ria.DigiDoc.crypto.RecipientRepository;
import ee.ria.DigiDoc.sign.SignLib;
import ee.ria.DigiDoc.smartcardreader.SmartCardReaderManager;
import ee.ria.DigiDoc.smartcardreader.acs.AcsSmartCardReader;
import ee.ria.DigiDoc.smartcardreader.identiv.IdentivSmartCardReader;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import timber.log.Timber;
public class Application extends android.app.Application {
private static ConfigurationProvider configurationProvider;
@Override
public void onCreate() {
setupAppLogging();
setupTSLFiles();
setupStrictMode();
super.onCreate();
setupBouncyCastle();
setupTimber();
setupConfiguration();
setupRxJava();
setupDagger();
}
// Copy every TSL file from APKs assets into cache if non-existent
private void setupTSLFiles() {
String destination = getCacheDir().toString() + "/schema";
String assetsPath = "tslFiles";
String[] tslFiles = null;
try {
tslFiles = getAssets().list(assetsPath);
} catch (IOException e) {
Timber.e(e, "Failed to get folder list: %s", assetsPath);
}
if (tslFiles != null && tslFiles.length > 0) {
FileUtils.createDirectoryIfNotExist(destination);
for (String fileName : tslFiles) {
if (shouldCopyTSL(assetsPath, fileName, destination)) {
copyTSLFromAssets(assetsPath, fileName, destination);
removeExistingETag(destination + File.separator + fileName);
}
}
}
}
private boolean shouldCopyTSL(String sourcePath, String fileName, String destionationDir) {
if (!FileUtils.fileExists(destionationDir + File.separator + fileName)) {
return true;
} else {
try (
InputStream assetsTSLInputStream = getAssets().open(sourcePath + File.separator + fileName);
InputStream cachedTSLInputStream = new FileInputStream(destionationDir + File.separator + fileName)
) {
Integer assetsTslVersion = TSLUtil.readSequenceNumber(assetsTSLInputStream);
Integer cachedTslVersion = TSLUtil.readSequenceNumber(cachedTSLInputStream);
return assetsTslVersion != null && assetsTslVersion > cachedTslVersion;
} catch (Exception e) {
String message = "Error comparing sequence number between assets and cached TSLs";
Timber.e(e, message);
return false;
}
}
}
private void copyTSLFromAssets(String sourcePath, String fileName, String destionationDir) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(sourcePath + File.separator + fileName),
StandardCharsets.UTF_8))) {
FileUtils.writeToFile(reader, destionationDir, fileName);
} catch (IOException ex) {
Timber.e(ex, "Failed to copy file: %s from assets", fileName);
}
}
private void removeExistingETag(String filePath) {
String eTagPath = filePath + ".etag";
FileUtils.removeFile(eTagPath);
}
// StrictMode
private void setupStrictMode() {
if (BuildConfig.DEBUG) {
StrictMode.enableDefaults();
}
}
// BouncyCastle Security provider
private void setupBouncyCastle() {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
Security.addProvider(new BouncyCastleProvider());
}
// Timber
private void setupTimber() {
if (isLoggingEnabled() || BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
Timber.plant(new FileLoggingTree(getApplicationContext()));
}
// TODO error reporting
}
// Container configuration
private void setupSignLib() {
SignLib.init(this, getString(R.string.main_settings_tsa_url_key), getConfigurationProvider(), UserAgentUtil.getUserAgent(getApplicationContext()), isLoggingEnabled());
}
private void setupRxJava() {
RxJavaPlugins.setErrorHandler(throwable -> Timber.e(throwable, "RxJava error handler"));
}
private void setupConfiguration() {
CachedConfigurationHandler cachedConfHandler = new CachedConfigurationHandler(getCacheDir());
ConfigurationProperties confProperties = new ConfigurationProperties(getAssets());
ConfigurationManager confManager = new ConfigurationManager(this, confProperties, cachedConfHandler, UserAgentUtil.getUserAgent(getApplicationContext()));
// Initially load cached configuration (if it exists and default configuration is not newer) in a blocking (synchronous)
// manner. If default conf is newer then load default conf (case where application was updated and cache was not removed,
// then in new packaged APK the default might be newer than the previously cached conf).
// Initial conf is load synchronously so there would be no state where asynchronous central configuration loading timed
// out or not ready yet and application features not working due to missing configuration.
if (cachedConfHandler.doesCachedConfigurationExist() && !isDefaultConfNewerThanCachedConf(confProperties, cachedConfHandler)) {
configurationProvider = confManager.forceLoadCachedConfiguration();
} else {
configurationProvider = confManager.forceLoadDefaultConfiguration();
}
Bundle bundle = new Bundle();
bundle.putParcelable(ConfigurationConstants.CONFIGURATION_PROVIDER, configurationProvider);
ConfigurationProviderReceiver confProviderReceiver = new ConfigurationProviderReceiver(new Handler());
confProviderReceiver.send(ConfigurationManagerService.NEW_CONFIGURATION_LOADED, bundle);
// Load configuration again in asynchronous manner, from central if needed or cache if present.
initAsyncConfigurationLoad(new ConfigurationProviderReceiver(new Handler()), false);
}
private boolean isDefaultConfNewerThanCachedConf(ConfigurationProperties confProperties, CachedConfigurationHandler cachedConfHandler) {
int defaultConfVersion = confProperties.getConfigurationVersionSerial();
Integer cachedConfVersion = cachedConfHandler.getConfigurationVersionSerial();
return cachedConfVersion == null || defaultConfVersion > cachedConfVersion;
}
// Following configuration updating should be asynchronous
public void updateConfiguration(DiagnosticsView diagnosticsView) {
ConfigurationProviderReceiver confProviderReceiver = new ConfigurationProviderReceiver(new Handler());
confProviderReceiver.setDiagnosticView(diagnosticsView);
initAsyncConfigurationLoad(confProviderReceiver, true);
}
private void initAsyncConfigurationLoad(ConfigurationProviderReceiver confProviderReceiver, boolean forceLoadCentral) {
Intent intent = new Intent(this, ConfigurationManagerService.class);
intent.putExtra(ConfigurationConstants.CONFIGURATION_RESULT_RECEIVER, confProviderReceiver);
intent.putExtra(ConfigurationConstants.FORCE_LOAD_CENTRAL_CONFIGURATION, forceLoadCentral);
Date configurationUpdateDate = configurationProvider.getConfigurationUpdateDate();
if (configurationUpdateDate != null) {
intent.putExtra(ConfigurationConstants.LAST_CONFIGURATION_UPDATE, configurationUpdateDate.getTime());
}
ConfigurationManagerService.enqueueWork(this, intent);
}
public ConfigurationProvider getConfigurationProvider() {
return configurationProvider;
}
private void setupAppLogging() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (!sharedPreferences.contains(getString(R.string.main_diagnostics_logging_key))) {
sharedPreferences.edit().putBoolean(getString(R.string.main_diagnostics_logging_key), false)
.commit();
}
if (!sharedPreferences.contains(getString(R.string.main_diagnostics_logging_running_key))) {
sharedPreferences.edit().putBoolean(getString(R.string.main_diagnostics_logging_running_key), false)
.commit();
}
boolean isDiagnosticsLoggingEnabled = sharedPreferences.getBoolean(getString(R.string.main_diagnostics_logging_key), false);
boolean isDiagnosticsLoggingRunning = sharedPreferences.getBoolean(getString(R.string.main_diagnostics_logging_running_key), false);
if (isDiagnosticsLoggingEnabled && isDiagnosticsLoggingRunning) {
isDiagnosticsLoggingEnabled = false;
isDiagnosticsLoggingRunning = false;
} else if (isDiagnosticsLoggingEnabled) {
isDiagnosticsLoggingRunning = true;
}
sharedPreferences.edit()
.putBoolean(getString(R.string.main_diagnostics_logging_key), isDiagnosticsLoggingEnabled)
.putBoolean(getString(R.string.main_diagnostics_logging_running_key), isDiagnosticsLoggingRunning)
.commit();
}
private boolean isLoggingEnabled() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isDiagnosticsLoggingEnabled = sharedPreferences.getBoolean(getString(R.string.main_diagnostics_logging_key), false);
boolean isDiagnosticsLoggingRunning = sharedPreferences.getBoolean(getString(R.string.main_diagnostics_logging_running_key), false);
return isDiagnosticsLoggingEnabled && isDiagnosticsLoggingRunning;
}
public class ConfigurationProviderReceiver extends ResultReceiver {
private DiagnosticsView diagnosticsView;
ConfigurationProviderReceiver(Handler handler) {
super(handler);
}
void setDiagnosticView(DiagnosticsView diagnosticView) {
this.diagnosticsView = diagnosticView;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
configurationProvider = resultData.getParcelable(ConfigurationConstants.CONFIGURATION_PROVIDER);
if (resultCode == ConfigurationManagerService.NEW_CONFIGURATION_LOADED) {
setupSignLib();
}
if (diagnosticsView != null) {
diagnosticsView.updateViewData(configurationProvider, resultCode);
}
}
}
// Dagger
private ApplicationComponent component;
private void setupDagger() {
component = DaggerApplication_ApplicationComponent.builder()
.application(this)
.build();
}
public static ApplicationComponent component(Context context) {
return ((Application) context.getApplicationContext()).component;
}
@Singleton
@Component(modules = {
AndroidModule.class,
ApplicationModule.class,
SmartCardModule.class,
CryptoLibModule.class
})
public interface ApplicationComponent {
Navigator navigator();
Formatter formatter();
Activity.RootScreenFactory rootScreenFactory();
LocaleService localeService();
SettingsDataStore settingsDataStore();
@Component.Builder
interface Builder {
@BindsInstance Builder application(android.app.Application application);
ApplicationComponent build();
}
}
@Module
static abstract class AndroidModule {
@Provides
static UsbManager usbManager(android.app.Application application) {
return (UsbManager) application.getSystemService(Context.USB_SERVICE);
}
@Provides
static ContentResolver contentResolver(android.app.Application application) {
return application.getContentResolver();
}
}
@Module
static abstract class ApplicationModule {
@Provides @Singleton
static Navigator navigator(Activity.RootScreenFactory rootScreenFactory,
ViewModelProvider.Factory viewModelFactory) {
return new ConductorNavigator(rootScreenFactory, viewModelFactory);
}
@Provides @Singleton
static ViewModelProvider.Factory viewModelFactory(
Map<Class<?>, Provider<ViewModel>> viewModelProviders) {
return new ViewModelFactory(viewModelProviders);
}
@SuppressWarnings("unused")
@Binds abstract SignatureContainerDataSource signatureContainerDataSource(
FileSystemSignatureContainerDataSource fileSystemSignatureContainerDataSource);
@SuppressWarnings("unused")
@Binds abstract DiagnosticsDataSource diagnosticsDataSource(
FileSystemDiagnosticsDataSource fileSystemDiagnosticsDataSource);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(HomeViewModel.class)
abstract ViewModel mainHomeViewModel(HomeViewModel homeViewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(SignatureListViewModel.class)
abstract ViewModel signatureListViewModel(SignatureListViewModel viewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(SignatureCreateViewModel.class)
abstract ViewModel signatureCreateViewModel(SignatureCreateViewModel viewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(DiagnosticsViewModel.class)
abstract ViewModel diagnosticsViewModel(DiagnosticsViewModel viewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(SignatureUpdateViewModel.class)
abstract ViewModel signatureUpdateModel(SignatureUpdateViewModel viewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(CryptoCreateViewModel.class)
abstract ViewModel cryptoCreateViewModel(CryptoCreateViewModel viewModel);
@SuppressWarnings("unused")
@Binds @IntoMap @ClassKey(EIDHomeViewModel.class)
abstract ViewModel eidHomeViewModel(EIDHomeViewModel viewModel);
}
@Module
static abstract class SmartCardModule {
@Provides @Singleton
static SmartCardReaderManager smartCardReaderManager(
android.app.Application application, UsbManager usbManager,
AcsSmartCardReader acsSmartCardReader,
IdentivSmartCardReader identivSmartCardReader) {
return new SmartCardReaderManager(application, usbManager,
ImmutableList.of(acsSmartCardReader, identivSmartCardReader));
}
@Provides @Singleton
static AcsSmartCardReader acsSmartCardReader(UsbManager usbManager) {
return new AcsSmartCardReader(usbManager);
}
@Provides @Singleton
static IdentivSmartCardReader identivSmartCardReader(android.app.Application application,
UsbManager usbManager) {
return new IdentivSmartCardReader(application, usbManager);
}
}
@Module
static abstract class CryptoLibModule {
@Provides @Singleton
static RecipientRepository recipientRepository() {
return new RecipientRepository(configurationProvider.getLdapPersonUrl(), configurationProvider.getLdapCorpUrl());
}
}
static final class ViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<?>, Provider<ViewModel>> viewModelProviders;
ViewModelFactory(Map<Class<?>, Provider<ViewModel>> viewModelProviders) {
this.viewModelProviders = viewModelProviders;
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) viewModelProviders.get(modelClass).get();
}
}
} |
package org.opencb.opencga.storage.mongodb.variant;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.opencb.biodata.models.variant.annotation.*;
import org.opencb.datastore.core.ComplexTypeConverter;
import java.util.*;
public class DBObjectToVariantAnnotationConverter implements ComplexTypeConverter<VariantAnnotation, DBObject> {
public final static String CONSEQUENCE_TYPE_FIELD = "ct";
public static final String GENE_NAME_FIELD = "gn";
public static final String ENSEMBL_GENE_ID_FIELD = "ensg";
public static final String ENSEMBL_TRANSCRIPT_ID_FIELD = "enst";
public static final String RELATIVE_POS_FIELD = "relPos";
public static final String CODON_FIELD = "codon";
public static final String STRAND_FIELD = "strand";
public static final String BIOTYPE_FIELD = "bt";
public static final String C_DNA_POSITION_FIELD = "cDnaPos";
public static final String CDS_POSITION_FIELD = "cdsPos";
public static final String AA_POSITION_FIELD = "aaPos";
public static final String AA_CHANGE_FIELD = "aaChange";
public static final String SO_ACCESSION_FIELD = "so";
public static final String XREFS_FIELD = "xrefs";
public final static String XREF_ID_FIELD = "id";
public final static String XREF_SOURCE_FIELD = "src";
public static final String PROTEIN_SUBSTITUTION_SCORE_FIELD = "ps_score";
public static final String CONSERVED_REGION_SCORE_FIELD = "cr_score";
public final static String SCORE_SCORE_FIELD = "sc";
public final static String SCORE_SOURCE_FIELD = "src";
public final static String SCORE_DESCRIPTION_FIELD = "desc";
private final ObjectMapper jsonObjectMapper;
public DBObjectToVariantAnnotationConverter() {
jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Override
public VariantAnnotation convertToDataModelType(DBObject object) {
VariantAnnotation va = new VariantAnnotation();
//ConsequenceType
List<ConsequenceType> consequenceTypes = new LinkedList<>();
Object cts = object.get(CONSEQUENCE_TYPE_FIELD);
if(cts != null && cts instanceof BasicDBList) {
for (Object o : ((BasicDBList) cts)) {
if(o instanceof DBObject) {
DBObject ct = (DBObject) o;
//SO accession name
List<String> soAccessionNames = new LinkedList<>();
if(ct.containsField(SO_ACCESSION_FIELD)) {
if (ct.get(SO_ACCESSION_FIELD) instanceof List) {
List<Integer> list = (List) ct.get(SO_ACCESSION_FIELD);
for (Integer so : list) {
soAccessionNames.add(ConsequenceTypeMappings.accessionToTerm.get(so));
}
} else {
soAccessionNames.add(ConsequenceTypeMappings.accessionToTerm.get(ct.get(SO_ACCESSION_FIELD)));
}
}
//ProteinSubstitutionScores
List<Score> proteinSubstitutionScores = new LinkedList<>();
if(ct.containsField(PROTEIN_SUBSTITUTION_SCORE_FIELD)) {
List<DBObject> list = (List) ct.get(PROTEIN_SUBSTITUTION_SCORE_FIELD);
for (DBObject dbObject : list) {
proteinSubstitutionScores.add(new Score(
getDefault(dbObject, SCORE_SCORE_FIELD, 0.0),
getDefault(dbObject, SCORE_SOURCE_FIELD, ""),
getDefault(dbObject, SCORE_DESCRIPTION_FIELD, "")
));
}
}
consequenceTypes.add(new ConsequenceType(
getDefault(ct, GENE_NAME_FIELD, "") /*.toString()*/,
getDefault(ct, ENSEMBL_GENE_ID_FIELD, "") /*.toString()*/,
getDefault(ct, ENSEMBL_TRANSCRIPT_ID_FIELD, "") /*.toString()*/,
getDefault(ct, STRAND_FIELD, "") /*.toString()*/,
getDefault(ct, BIOTYPE_FIELD, "") /*.toString()*/,
getDefault(ct, C_DNA_POSITION_FIELD, 0),
getDefault(ct, CDS_POSITION_FIELD, 0),
getDefault(ct, AA_POSITION_FIELD, 0),
getDefault(ct, AA_CHANGE_FIELD, "") /*.toString() */,
getDefault(ct, CODON_FIELD, "") /*.toString() */,
proteinSubstitutionScores,
soAccessionNames));
}
}
}
va.setConsequenceTypes(consequenceTypes);
//Conserved Region Scores
List<Score> conservedRegionScores = new LinkedList<>();
if(object.containsField(CONSERVED_REGION_SCORE_FIELD)) {
List<DBObject> list = (List) object.get(CONSERVED_REGION_SCORE_FIELD);
for (DBObject dbObject : list) {
conservedRegionScores.add(new Score(
getDefault(dbObject, SCORE_SCORE_FIELD, 0.0),
getDefault(dbObject, SCORE_SOURCE_FIELD, ""),
getDefault(dbObject, SCORE_DESCRIPTION_FIELD, "")
));
}
}
va.setConservedRegionScores(conservedRegionScores);
//XREfs
List<Xref> xrefs = new LinkedList<>();
Object xrs = object.get(XREFS_FIELD);
if(xrs != null && xrs instanceof BasicDBList) {
for (Object o : (BasicDBList) xrs) {
if(o instanceof DBObject) {
DBObject xref = (DBObject) o;
xrefs.add(new Xref(
(String) xref.get(XREF_ID_FIELD),
(String) xref.get(XREF_SOURCE_FIELD))
);
}
}
}
va.setXrefs(xrefs);
return va;
}
@Override
public DBObject convertToStorageType(VariantAnnotation object) {
DBObject dbObject = new BasicDBObject();
Set<DBObject> xrefs = new HashSet<>();
List<DBObject> cts = new LinkedList<>();
if (object.getId() != null && !object.getId().isEmpty()) {
xrefs.add(convertXrefToStorage(object.getId(), "dbSNP"));
}
//ConsequenceType
if (object.getConsequenceTypes() != null) {
List<ConsequenceType> consequenceTypes = object.getConsequenceTypes();
for (ConsequenceType consequenceType : consequenceTypes) {
DBObject ct = new BasicDBObject();
putNotNull(ct, GENE_NAME_FIELD, consequenceType.getGeneName());
putNotNull(ct, ENSEMBL_GENE_ID_FIELD, consequenceType.getEnsemblGeneId());
putNotNull(ct, ENSEMBL_TRANSCRIPT_ID_FIELD, consequenceType.getEnsemblTranscriptId());
putNotNull(ct, RELATIVE_POS_FIELD, consequenceType.getRelativePosition());
putNotNull(ct, CODON_FIELD, consequenceType.getCodon());
putNotNull(ct, STRAND_FIELD, consequenceType.getStrand());
putNotNull(ct, BIOTYPE_FIELD, consequenceType.getBiotype());
putNotNull(ct, C_DNA_POSITION_FIELD, consequenceType.getcDnaPosition());
putNotNull(ct, CDS_POSITION_FIELD, consequenceType.getCdsPosition());
putNotNull(ct, AA_POSITION_FIELD, consequenceType.getAaPosition());
putNotNull(ct, AA_CHANGE_FIELD, consequenceType.getAaChange());
if (consequenceType.getSoTerms() != null) {
List<Integer> soAccession = new LinkedList<>();
for (ConsequenceType.ConsequenceTypeEntry entry : consequenceType.getSoTerms()) {
soAccession.add(ConsequenceTypeMappings.termToAccession.get(entry.getSoName()));
}
putNotNull(ct, SO_ACCESSION_FIELD, soAccession);
}
//Protein substitution region score
if (consequenceType.getProteinSubstitutionScores() != null) {
List<DBObject> proteinSubstitutionScores = new LinkedList<>();
for (Score score : consequenceType.getProteinSubstitutionScores()) {
if (score != null) {
proteinSubstitutionScores.add(convertScoreToStorage(score));
}
}
putNotNull(ct, PROTEIN_SUBSTITUTION_SCORE_FIELD, proteinSubstitutionScores);
}
cts.add(ct);
if (consequenceType.getGeneName() != null) {
xrefs.add(convertXrefToStorage(consequenceType.getGeneName(), "HGNC"));
}
if (consequenceType.getEnsemblGeneId() != null) {
xrefs.add(convertXrefToStorage(consequenceType.getEnsemblGeneId(), "ensemblGene"));
}
if (consequenceType.getEnsemblTranscriptId() != null) {
xrefs.add(convertXrefToStorage(consequenceType.getEnsemblTranscriptId(), "ensemblTranscript"));
}
}
putNotNull(dbObject, CONSEQUENCE_TYPE_FIELD, cts);
}
//Conserved region score
if (object.getConservedRegionScores() != null) {
List<DBObject> conservedRegionScores = new LinkedList<>();
for (Score score : object.getConservedRegionScores()) {
if (score != null) {
conservedRegionScores.add(convertScoreToStorage(score));
}
}
putNotNull(dbObject, CONSERVED_REGION_SCORE_FIELD, conservedRegionScores);
}
//XREFs
if(object.getXrefs() != null) {
for (Xref xref : object.getXrefs()) {
xrefs.add(convertXrefToStorage(xref.getId(), xref.getSrc()));
}
}
putNotNull(dbObject, XREFS_FIELD, xrefs);
return dbObject;
}
private DBObject convertScoreToStorage(Score score) {
DBObject dbObject = new BasicDBObject(SCORE_SCORE_FIELD, score.getScore());
putNotNull(dbObject, SCORE_SOURCE_FIELD, score.getSource());
putNotNull(dbObject, SCORE_DESCRIPTION_FIELD, score.getDescription());
return dbObject;
}
private DBObject convertXrefToStorage(String id, String source) {
DBObject dbObject = new BasicDBObject(XREF_ID_FIELD, id);
dbObject.put(XREF_SOURCE_FIELD, source);
return dbObject;
}
//Utils
private void putNotNull(DBObject dbObject, String key, Object obj) {
if(obj != null) {
dbObject.put(key, obj);
}
}
private void putNotNull(DBObject dbObject, String key, Collection obj) {
if(obj != null && !obj.isEmpty()) {
dbObject.put(key, obj);
}
}
private void putNotNull(DBObject dbObject, String key, String obj) {
if(obj != null && !obj.isEmpty()) {
dbObject.put(key, obj);
}
}
private void putNotNull(DBObject dbObject, String key, Integer obj) {
if(obj != null && obj != 0) {
dbObject.put(key, obj);
}
}
private String getDefault(DBObject object, String key, String defaultValue) {
Object o = object.get(key);
if (o != null ) {
return o.toString();
} else {
return defaultValue;
}
}
private int getDefault(DBObject object, String key, int defaultValue) {
Object o = object.get(key);
if (o != null ) {
if (o instanceof Integer) {
return (Integer) o;
} else {
try {
return Integer.parseInt(o.toString());
} catch (Exception e) {
return defaultValue;
}
}
} else {
return defaultValue;
}
}
private double getDefault(DBObject object, String key, double defaultValue) {
Object o = object.get(key);
if (o != null ) {
if (o instanceof Double) {
return (Double) o;
} else {
try {
return Double.parseDouble(o.toString());
} catch (Exception e) {
return defaultValue;
}
}
} else {
return defaultValue;
}
}
} |
package io.tetrapod.core.utils;
import io.netty.buffer.*;
import io.netty.handler.codec.base64.*;
import io.tetrapod.core.serialize.datasources.ByteBufDataSource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Helper class used to authenticate messages. Works by taking a message (an array of ints) and computing an HMAC using a shared secret. The
* token is then a subset(input vals) + HMAC. Upon decoding the subset of input vals are recovered, combined with any values known through
* other means, and the HMAC is recomputed and checked for validity.
* <p>
* Note that the actual data encoded and decoded in the token is up to the caller.
*/
public class AuthToken {
private static final long NOT_THAT_LONG_AGO = 1395443029600L;
private static Mac MAC = null;
/**
* Sets the shared secret. Needs to be called before this class is used. Returns false if there is an error which would typically be Java
* not having strong crypto available.
*/
public static boolean setSecret(byte[] secret) {
try {
// append NTLA so updating it will invalidate old tokens
byte[] ntla = Long.toHexString(NOT_THAT_LONG_AGO).getBytes();
byte[] key = Arrays.copyOf(secret, secret.length + ntla.length);
System.arraycopy(ntla, 0, key, secret.length, ntla.length);
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac macCoder = Mac.getInstance("HmacSHA1");
macCoder.init(signingKey);
synchronized (AuthToken.class) {
MAC = macCoder;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes a auth token with all passed in values also present in the auth token.
*
* @param values the values which form the basis of the token
* @return the base64 encoded token
*/
public static String encode(int[] values) {
return encode(values, values.length);
}
/**
* Encodes a auth token. The numInToken parameter is a bandwidth micro-optimization. Say for example we wanted to make an auth token with
* one value being the entityId. We *could* encode the true value for the entity id in the token, but since it is already present in the
* header we could leave it out of the token and supply it at decode time.
*
* @param values the values which form the basis of the token
* @param numInToken the number of values which will need to be encoded inside the token
* @return the base64 encoded token
*/
public static String encode(int[] values, int numInToken) {
ByteBuf buf = Unpooled.buffer();
try {
ByteBufDataSource bds = new ByteBufDataSource(buf);
for (int i = 0; i < values.length; i++) {
bds.writeVarInt(values[i]);
}
byte[] mac;
synchronized (AuthToken.class) {
MAC.update(buf.array(), buf.arrayOffset(), buf.writerIndex());
mac = MAC.doFinal();
}
buf.resetWriterIndex();
for (int i = 0; i < numInToken; i++) {
bds.writeVarInt(values[i]);
}
String plainText = Base64.encode(buf, Base64Dialect.URL_SAFE).toString(Charset.forName("UTF-8"));
ByteBuf macBuf = Unpooled.wrappedBuffer(mac);
try {
String macText = Base64.encode(macBuf, Base64Dialect.URL_SAFE).toString(Charset.forName("UTF-8"));
return plainText + macText;
} finally {
macBuf.release();
}
} catch (IOException e) {
} finally {
buf.release();
}
return null;
}
/**
* Decodes an auth token. If there is at least one value in the token it assumes the first value is a timeout value and checks it versus
* the current time.
*
* @param values the values of the token, the first numInToken elements get filled in from the token
* @param numInToken the number of values to pull out from the token
* @param token the base64 encoded token
* @param timedOut true if there is at least one value and the first value is less than the current time
* @return true if it decodes successfully, and as a side effect fills in values with any values which were encoded in token
*/
public static boolean decode(int[] values, int numInToken, String token) {
ByteBuf tokenBuf = null;
try {
tokenBuf = Base64.decode(Unpooled.wrappedBuffer(token.getBytes()), Base64Dialect.URL_SAFE);
ByteBufDataSource bds = new ByteBufDataSource(tokenBuf);
for (int i = 0; i < numInToken; i++) {
values[i] = bds.readVarInt();
}
String encoded = encode(values, numInToken);
return encoded.equals(token);
} catch (Exception e) {} finally {
if (tokenBuf != null) {
tokenBuf.release();
}
}
return false;
}
/**
* Return the number of minutes since NOT_THAT_LONG_AGO
*/
public static int timeNowInMinutes() {
long delta = System.currentTimeMillis() - NOT_THAT_LONG_AGO;
return (int) (delta / 60000);
}
// encode/decode wrappers for known auth token types
public static String encodeUserToken(int accountId, int entityId, int properties, int timeoutInMinutes) {
int timeout = AuthToken.timeNowInMinutes() + timeoutInMinutes;
int[] vals = { timeout, properties, accountId, entityId };
return AuthToken.encode(vals, 2);
}
public static String encodeAuthToken1(int accountId, int val1, int timeoutInMinutes) {
int timeout = AuthToken.timeNowInMinutes() + timeoutInMinutes;
int[] vals = { timeout, val1, accountId };
return AuthToken.encode(vals);
}
public static String encodeAuthToken2(int accountId, int val1, int val2, int timeoutInMinutes) {
int timeout = AuthToken.timeNowInMinutes() + timeoutInMinutes;
int[] vals = { timeout, val1, val2, accountId };
return AuthToken.encode(vals);
}
public static String encodeAuthToken3(int accountId, int val1, int val2, int val3, int timeoutInMinutes) {
int timeout = AuthToken.timeNowInMinutes() + timeoutInMinutes;
int[] vals = { timeout, val1, val2, val3, accountId };
return AuthToken.encode(vals);
}
public static Decoded decodeUserToken(String token, int accountId, int entityId) {
int[] vals = { 0, 0, accountId, entityId };
if (!decode(vals, 2, token)) {
return null;
}
Decoded d = new Decoded();
d.accountId = accountId;
d.miscValues = new int[] { vals[1] };
d.timeLeft = vals[0] - timeNowInMinutes();
return d;
}
public static Decoded decodeAuthToken1(String token) {
int[] vals = new int[3];
if (!decode(vals, 3, token)) {
return null;
}
Decoded d = new Decoded();
d.accountId = vals[2];
d.miscValues = new int[] { vals[1] };
d.timeLeft = vals[0] - timeNowInMinutes();
return d;
}
public static Decoded decodeAuthToken2(String token) {
int[] vals = new int[4];
if (!decode(vals, 4, token)) {
return null;
}
Decoded d = new Decoded();
d.accountId = vals[3];
d.miscValues = new int[] { vals[1], vals[2] };
d.timeLeft = vals[0] - timeNowInMinutes();
return d;
}
public static Decoded decodeAuthToken3(String token) {
int[] vals = new int[5];
if (!decode(vals, 5, token)) {
return null;
}
Decoded d = new Decoded();
d.accountId = vals[4];
d.miscValues = new int[] { vals[1], vals[2], vals[3] };
d.timeLeft = vals[0] - timeNowInMinutes();
return d;
}
public static class Decoded {
public int accountId;
public int timeLeft;
public int[] miscValues;
}
} |
package com.aol.cyclops2.types.anyM;
import static com.aol.cyclops2.internal.Utils.firstOrNull;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Stream;
import com.aol.cyclops2.types.*;
import cyclops.collections.DequeX;
import cyclops.collections.QueueX;
import cyclops.collections.SetX;
import cyclops.collections.immutable.*;
import cyclops.monads.WitnessType;
import org.jooq.lambda.tuple.Tuple2;
import org.jooq.lambda.tuple.Tuple3;
import org.jooq.lambda.tuple.Tuple4;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import cyclops.function.Monoid;
import cyclops.monads.AnyM;
import cyclops.stream.ReactiveSeq;
import cyclops.control.Trampoline;
import cyclops.control.Xor;
import cyclops.collections.ListX;
import com.aol.cyclops2.types.extensability.FunctionalAdapter;
import cyclops.function.Predicates;
import cyclops.function.Fn4;
import cyclops.function.Fn3;
/**
* Wrapper around 'Any' non-scalar 'M'onad
*
* @author johnmcclean
*
* @param <T> Data types of elements managed by wrapped non-scalar Monad.
*/
public interface AnyMSeq<W extends WitnessType<W>,T> extends AnyM<W,T>, FoldableTraversable<T>, Publisher<T> {
default <R> AnyMSeq<W,R> flatMapI(Function<? super T, ? extends Iterable<? extends R>> fn){
return this.flatMap(fn.andThen(i->unitIterator(i.iterator())));
}
default <R> AnyMSeq<W,R> flatMapP(Function<? super T, ? extends Publisher<? extends R>> fn){
return this.flatMap(fn.andThen(i->unitIterator(ReactiveSeq.fromPublisher(i).iterator())));
}
default <R> AnyMSeq<W,R> flatMapS(Function<? super T, ? extends Stream<? extends R>> fn){
return this.flatMap(fn.andThen(i->unitIterator(i.iterator())));
}
/**
* Perform a four level nested internal iteration over this monad and the
* supplied monads
*
*
* @param monad1
* Nested Monad to iterate over
* @param monad2
* Nested Monad to iterate over
* @param monad3
* Nested Monad to iterate over
* @param yieldingFunction
* Function with pointers to the current element from both
* Monad that generates the new elements
* @return AnyMSeq with elements generated via nested iteration
*/
default <R1, R2, R3,R> AnyMSeq<W,R> forEach4(final Function<? super T, ? extends AnyM<W,R1>> monad1,
final BiFunction<? super T,? super R1, ? extends AnyM<W,R2>> monad2,
final Fn3<? super T, ? super R1, ? super R2, ? extends AnyM<W,R3>> monad3,
final Fn4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction){
return this.flatMapA(in -> {
AnyM<W,R1> a = monad1.apply(in);
return a.flatMapA(ina -> {
AnyM<W,R2> b = monad2.apply(in, ina);
return b.flatMapA(inb -> {
AnyM<W,R3> c = monad3.apply(in, ina,inb);
return c.map(in2 -> yieldingFunction.apply(in, ina, inb, in2));
});
});
});
}
/**
* Perform a four level nested internal iteration over this monad and the
* supplied monads
*
*
* @param monad1
* Nested Monad to iterate over
* @param monad2
* Nested Monad to iterate over
* @param monad3
* Nested Monad to iterate over
* @param filterFunction
* Filter to apply over elements before passing non-filtered
* values to the yielding function
* @param yieldingFunction
* Function with pointers to the current element from both
* Streams that generates the new elements
* @return ReactiveSeq with elements generated via nested iteration
*/
default <R1, R2, R3,R> AnyMSeq<W,R> forEach4(final Function<? super T, ? extends AnyM<W,R1>> monad1,
final BiFunction<? super T,? super R1, ? extends AnyM<W,R2>> monad2,
final Fn3<? super T, ? super R1, ? super R2, ? extends AnyM<W,R3>> monad3,
final Fn4<? super T, ? super R1, ? super R2, ? super R3, Boolean> filterFunction,
final Fn4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction){
return this.flatMapA(in -> {
AnyM<W,R1> a = monad1.apply(in);
return a.flatMapA(ina -> {
AnyM<W,R2> b = monad2.apply(in, ina);
return b.flatMapA(inb -> {
AnyM<W,R3> c = monad3.apply(in, ina,inb);
return c.filter(in2 -> filterFunction.apply(in, ina, inb, in2))
.map(in2 -> yieldingFunction.apply(in, ina, inb, in2));
});
});
});
}
/**
* Perform a two level nested internal iteration over this Stream and the supplied monad (allowing null handling, exception handling
* etc to be injected, for example)
*
* <pre>
* {@code
* AnyM.fromArray(1,2,3)
.forEachAnyM2(a->AnyM.fromIntStream(IntStream.range(10,13)),
(a,b)->a+b);
*
* //AnyM[11,14,12,15,13,16]
* }
* </pre>
*
*
* @param monad Nested Monad to iterate over
* @param yieldingFunction Function with pointers to the current element from both Streams that generates the new elements
* @return FutureStream with elements generated via nested iteration
*/
default <R1, R> AnyMSeq<W,R> forEach2(Function<? super T, ? extends AnyM<W,R1>> monad,
BiFunction<? super T,? super R1, ? extends R> yieldingFunction){
return this.flatMapA(in-> {
AnyM<W,R1> b = monad.apply(in);
return b.map(in2->yieldingFunction.apply(in, in2));
});
}
/**
* Perform a two level nested internal iteration over this Stream and the supplied monad (allowing null handling, exception handling
* etc to be injected, for example)
*
* <pre>
* {@code
* AnyM.fromArray(1,2,3)
.forEach2(a->AnyM.fromIntStream(IntStream.range(10,13)),
(a,b)-> a<3 && b>10,
(a,b)->a+b);
*
* //AnyM[14,15]
* }
* </pre>
* @param monad Nested Monad to iterate over
* @param filterFunction Filter to apply over elements before passing non-filtered values to the yielding function
* @param yieldingFunction Function with pointers to the current element from both monads that generates the new elements
* @return
*/
default <R1, R> AnyMSeq<W,R> forEach2(Function<? super T, ? extends AnyM<W,R1>> monad,
BiFunction<? super T,? super R1, Boolean> filterFunction,
BiFunction<? super T, ? super R1, ? extends R> yieldingFunction){
return this.flatMapA(in-> {
AnyM<W,R1> b = monad.apply(in);
return b.filter(in2-> filterFunction.apply(in,in2))
.map(in2->yieldingFunction.apply(in, in2));
});
}
/**
* Perform a three level nested internal iteration over this Stream and the supplied streams
*<pre>
* {@code
* AnyM.fromArray(1,2)
.forEach3(a->AnyM.fromIntStream(IntStream.range(10,13)),
(a,b)->AnyM.fromArray(""+(a+b),"hello world"),
(a,b,c)->AnyM.fromArray(""+(a+b),"hello world"),
(a,b,c,d)->c+":"a+":"+b);
*
*
* }
* </pre>
* @param monad1 Nested monad to flatMap over
* @param monad2 Nested monad to flatMap over
* @param filterFunction Filter to apply over elements before passing non-filtered values to the yielding function
* @param yieldingFunction Function with pointers to the current element from both monads that generates the new elements
* @return AnyM with elements generated via nested iteration
*/
default <R1, R2, R> AnyMSeq<W,R> forEach3(Function<? super T, ? extends AnyM<W,R1>> monad1,
BiFunction<? super T, ? super R1, ? extends AnyM<W,R2>> monad2,
Fn3<? super T,? super R1, ? super R2, Boolean> filterFunction,
Fn3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction){
return this.flatMapA(in -> {
AnyM<W,R1> a = monad1.apply(in);
return a.flatMapA(ina -> {
AnyM<W,R2> b = monad2.apply(in, ina);
return b.filter(in2 -> filterFunction.apply(in, ina, in2))
.map(in2 -> yieldingFunction.apply(in, ina, in2));
});
});
}
/**
* Perform a three level nested internal iteration over this AnyM and the supplied monads
*<pre>
* {@code
* AnyM.fromArray(1,2,3)
.forEach3(a->AnyM.fromStream(IntStream.range(10,13)),
(a,b)->AnyM.fromArray(""+(a+b),"hello world"),
(a,b,c)-> c!=3,
(a,b,c)->c+":"a+":"+b);
*
* //AnyM[11:1:2,hello world:1:2,14:1:4,hello world:1:4,12:1:2,hello world:1:2,15:1:5,hello world:1:5]
* }
* </pre>
*
* @param monad1 Nested Stream to iterate over
* @param monad2 Nested Stream to iterate over
* @param yieldingFunction Function with pointers to the current element from both Monads that generates the new elements
* @return AnyM with elements generated via nested iteration
*/
default <R1, R2, R> AnyMSeq<W,R> forEach3(Function<? super T, ? extends AnyM<W,R1>> monad1,
BiFunction<? super T, ? super R1, ? extends AnyM<W,R2>> monad2,
Fn3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction){
return this.flatMapA(in -> {
AnyM<W,R1> a = monad1.apply(in);
return a.flatMapA(ina -> {
AnyM<W,R2> b = monad2.apply(in, ina);
return b.map(in2 -> yieldingFunction.apply(in, ina, in2));
});
});
}
/**
* Equivalence test, returns true if this Monad is equivalent to the supplied monad
* e.g.
* <pre>
* {code
* Stream.of(1) and Arrays.asList(1) are equivalent
* }
* </pre>
*
*
* @param t Monad to compare to
* @return true if equivalent
*/
default boolean eqv(final AnyMSeq<?,T> t) {
return Predicates.eqvIterable(t)
.test(this);
}
/* (non-Javadoc)
* @see cyclops2.monads.AnyM#collect(java.util.reactiveStream.Collector)
*/
@Override
default <R, A> R collect(final Collector<? super T, A, R> collector) {
return stream().collect(collector);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#traversable()
*/
@Override
default Traversable<T> traversable() {
final Object o = unwrap();
if (o instanceof Traversable) {
return (Traversable) o;
}
return stream();
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#limit(long)
*/
@Override
default AnyMSeq<W,T> limit(final long num) {
return fromIterable(FoldableTraversable.super.limit(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#limitWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> limitWhile(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.limitWhile(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#limitUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> limitUntil(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.limitUntil(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#limitLast(int)
*/
@Override
default AnyMSeq<W,T> limitLast(final int num) {
return fromIterable(FoldableTraversable.super.limitLast(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#onEmpty(java.lang.Object)
*/
@Override
default AnyMSeq<W,T> onEmpty(final T value) {
return fromIterable(FoldableTraversable.super.onEmpty(value));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#onEmptyGet(java.util.function.Supplier)
*/
@Override
default AnyMSeq<W,T> onEmptyGet(final Supplier<? extends T> supplier) {
return fromIterable(FoldableTraversable.super.onEmptyGet(supplier));
}
FunctionalAdapter<W> adapter();
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#onEmptyThrow(java.util.function.Supplier)
*/
@Override
default <X extends Throwable> AnyMSeq<W,T> onEmptyThrow(final Supplier<? extends X> supplier) {
return fromIterable(FoldableTraversable.super.onEmptyThrow(supplier));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#subscribeAll(org.reactivestreams.Subscriber)
*/
@Override
default void subscribe(final Subscriber<? super T> sub) {
if (unwrap() instanceof Publisher) {
((Publisher) unwrap()).subscribe(sub);
} else {
this.stream()
.subscribe(sub);
}
}
/**
* @return The first value of this monad
*/
default Value<T> toFirstValue() {
return () -> firstOrNull(toListX());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Transformable#cast(java.lang.Class)
*/
@Override
default <U> AnyMSeq<W,U> cast(final Class<? extends U> type) {
return (AnyMSeq<W,U>) FoldableTraversable.super.cast(type);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Transformable#trampoline(java.util.function.Function)
*/
@Override
default <R> AnyMSeq<W,R> trampoline(final Function<? super T, ? extends Trampoline<? extends R>> mapper) {
return (AnyMSeq<W,R>) FoldableTraversable.super.trampoline(mapper);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#cycle(int)
*/
@Override
default AnyMSeq<W,T> cycle(final long times) {
return fromIterable(FoldableTraversable.super.cycle(times));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#cycle(cyclops2.function.Monoid, int)
*/
@Override
default AnyMSeq<W,T> cycle(final Monoid<T> m, final long times) {
return fromIterable(FoldableTraversable.super.cycle(m, times));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#cycleWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> cycleWhile(final Predicate<? super T> predicate) {
return fromIterable(FoldableTraversable.super.cycleWhile(predicate));
}
@Override
default Xor<AnyMValue<W,T>, AnyMSeq<W,T>> matchable() {
return Xor.primary(this);
}
@Override
default <T> AnyMSeq<W,T> fromIterable(Iterable<T> t){
if(t instanceof AnyMSeq) {
AnyMSeq check =(AnyMSeq) t;
if(check.adapter() == this.adapter())
return check;
}
return (AnyMSeq<W,T>)adapter().unitIterable(t);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#cycleUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> cycleUntil(final Predicate<? super T> predicate) {
return fromIterable(FoldableTraversable.super.cycleUntil(predicate));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip(java.lang.Iterable, java.util.function.BiFunction)
*/
@Override
default <U, R> AnyMSeq<W,R> zip(final Iterable<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) {
return fromIterable(FoldableTraversable.super.zip(other, zipper));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip(java.util.reactiveStream.Stream, java.util.function.BiFunction)
*/
@Override
default <U, R> AnyMSeq<W,R> zipS(final Stream<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) {
return fromIterable(FoldableTraversable.super.zipS(other, zipper));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip(java.util.reactiveStream.Stream)
*/
@Override
default <U> AnyMSeq<W,Tuple2<T, U>> zipS(final Stream<? extends U> other) {
return fromIterable(FoldableTraversable.super.zipS(other));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip(java.lang.Iterable)
*/
@Override
default <U> AnyMSeq<W,Tuple2<T, U>> zip(final Iterable<? extends U> other) {
return fromIterable(FoldableTraversable.super.zip(other));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip3(java.util.reactiveStream.Stream, java.util.reactiveStream.Stream)
*/
@Override
default <S, U> AnyMSeq<W,Tuple3<T, S, U>> zip3(final Iterable<? extends S> second, final Iterable<? extends U> third) {
return fromIterable(FoldableTraversable.super.zip3(second, third));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zip4(java.util.reactiveStream.Stream, java.util.reactiveStream.Stream, java.util.reactiveStream.Stream)
*/
@Override
default <T2, T3, T4> AnyMSeq<W,Tuple4<T, T2, T3, T4>> zip4(final Iterable<? extends T2> second, final Iterable<? extends T3> third,
final Iterable<? extends T4> fourth) {
return fromIterable(FoldableTraversable.super.zip4(second, third, fourth));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#zipWithIndex()
*/
@Override
default AnyMSeq<W,Tuple2<T, Long>> zipWithIndex() {
return fromIterable(FoldableTraversable.super.zipWithIndex());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#sliding(int)
*/
@Override
default AnyMSeq<W,PVectorX<T>> sliding(final int windowSize) {
return fromIterable(FoldableTraversable.super.sliding(windowSize));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#sliding(int, int)
*/
@Override
default AnyMSeq<W,PVectorX<T>> sliding(final int windowSize, final int increment) {
return fromIterable(FoldableTraversable.super.sliding(windowSize, increment));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#grouped(int, java.util.function.Supplier)
*/
@Override
default <C extends Collection<? super T>> AnyMSeq<W,C> grouped(final int size, final Supplier<C> supplier) {
return fromIterable(FoldableTraversable.super.grouped(size, supplier));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#groupedUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,ListX<T>> groupedUntil(final Predicate<? super T> predicate) {
return fromIterable(FoldableTraversable.super.groupedUntil(predicate));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#groupedStatefullyUntil(java.util.function.BiPredicate)
*/
@Override
default AnyMSeq<W,ListX<T>> groupedStatefullyUntil(final BiPredicate<ListX<? super T>, ? super T> predicate) {
return fromIterable(FoldableTraversable.super.groupedStatefullyUntil(predicate));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#combine(java.util.function.BiPredicate, java.util.function.BinaryOperator)
*/
@Override
default AnyMSeq<W,T> combine(final BiPredicate<? super T, ? super T> predicate, final BinaryOperator<T> op) {
return fromIterable(FoldableTraversable.super.combine(predicate, op));
}
@Override
default AnyMSeq<W,T> combine(final Monoid<T> op, final BiPredicate<? super T, ? super T> predicate) {
return (AnyMSeq<W,T>)FoldableTraversable.super.combine(op,predicate);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#groupedWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,ListX<T>> groupedWhile(final Predicate<? super T> predicate) {
return fromIterable(FoldableTraversable.super.groupedWhile(predicate));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#groupedWhile(java.util.function.Predicate, java.util.function.Supplier)
*/
@Override
default <C extends Collection<? super T>> AnyMSeq<W,C> groupedWhile(final Predicate<? super T> predicate, final Supplier<C> factory) {
return fromIterable(FoldableTraversable.super.groupedWhile(predicate, factory));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#groupedUntil(java.util.function.Predicate, java.util.function.Supplier)
*/
@Override
default <C extends Collection<? super T>> AnyMSeq<W,C> groupedUntil(final Predicate<? super T> predicate, final Supplier<C> factory) {
return fromIterable(FoldableTraversable.super.groupedUntil(predicate, factory));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#grouped(int)
*/
@Override
default AnyMSeq<W,ListX<T>> grouped(final int groupSize) {
return fromIterable(FoldableTraversable.super.grouped(groupSize));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#grouped(java.util.function.Function, java.util.reactiveStream.Collector)
*/
@Override
default <K, A, D> AnyMSeq<W,Tuple2<K, D>> grouped(final Function<? super T, ? extends K> classifier, final Collector<? super T, A, D> downstream) {
return fromIterable(FoldableTraversable.super.grouped(classifier, downstream));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#grouped(java.util.function.Function)
*/
@Override
default <K> AnyMSeq<W,Tuple2<K, ReactiveSeq<T>>> grouped(final Function<? super T, ? extends K> classifier) {
return fromIterable(FoldableTraversable.super.grouped(classifier));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#takeWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> takeWhile(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.takeWhile(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#dropWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> dropWhile(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.dropWhile(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#takeUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> takeUntil(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.takeUntil(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#dropUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> dropUntil(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.dropUntil(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#dropRight(int)
*/
@Override
default AnyMSeq<W,T> dropRight(final int num) {
return fromIterable(FoldableTraversable.super.dropRight(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#takeRight(int)
*/
@Override
default AnyMSeq<W,T> takeRight(final int num) {
return fromIterable(FoldableTraversable.super.takeRight(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#reverse()
*/
@Override
default AnyMSeq<W,T> reverse() {
return fromIterable(FoldableTraversable.super.reverse());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#shuffle()
*/
@Override
default AnyMSeq<W,T> shuffle() {
return fromIterable(FoldableTraversable.super.shuffle());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#shuffle(java.util.Random)
*/
@Override
default AnyMSeq<W,T> shuffle(final Random random) {
return fromIterable(FoldableTraversable.super.shuffle(random));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#distinct()
*/
@Override
default AnyMSeq<W,T> distinct() {
return fromIterable(FoldableTraversable.super.distinct());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#scanLeft(cyclops2.function.Monoid)
*/
@Override
default AnyMSeq<W,T> scanLeft(final Monoid<T> monoid) {
return fromIterable(FoldableTraversable.super.scanLeft(monoid));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#scanLeft(java.lang.Object, java.util.function.BiFunction)
*/
@Override
default <U> AnyMSeq<W,U> scanLeft(final U seed, final BiFunction<? super U, ? super T, ? extends U> function) {
return fromIterable(FoldableTraversable.super.scanLeft(seed, function));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#scanRight(cyclops2.function.Monoid)
*/
@Override
default AnyMSeq<W,T> scanRight(final Monoid<T> monoid) {
return fromIterable(FoldableTraversable.super.scanRight(monoid));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#scanRight(java.lang.Object, java.util.function.BiFunction)
*/
@Override
default <U> AnyMSeq<W,U> scanRight(final U identity, final BiFunction<? super T, ? super U, ? extends U> combiner) {
return fromIterable(FoldableTraversable.super.scanRight(identity, combiner));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#sorted()
*/
@Override
default AnyMSeq<W,T> sorted() {
return fromIterable(FoldableTraversable.super.sorted());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#sorted(java.util.Comparator)
*/
@Override
default AnyMSeq<W,T> sorted(final Comparator<? super T> c) {
return fromIterable(FoldableTraversable.super.sorted(c));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#skip(long)
*/
@Override
default AnyMSeq<W,T> skip(final long num) {
return fromIterable(FoldableTraversable.super.skip(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#skipWhile(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> skipWhile(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.skipWhile(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#skipUntil(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> skipUntil(final Predicate<? super T> p) {
return fromIterable(FoldableTraversable.super.skipUntil(p));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#intersperse(java.lang.Object)
*/
@Override
default AnyMSeq<W,T> intersperse(final T value) {
return fromIterable(FoldableTraversable.super.intersperse(value));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#skipLast(int)
*/
@Override
default AnyMSeq<W,T> skipLast(final int num) {
return fromIterable(FoldableTraversable.super.skipLast(num));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#slice(long, long)
*/
@Override
default AnyMSeq<W,T> slice(final long from, final long to) {
return fromIterable(FoldableTraversable.super.slice(from, to));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Traversable#sorted(java.util.function.Function)
*/
@Override
default <U extends Comparable<? super U>> AnyMSeq<W,T> sorted(final Function<? super T, ? extends U> function) {
return fromIterable(FoldableTraversable.super.sorted(function));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.ExtendedTraversable#permutations()
*/
@Override
default AnyMSeq<W,ReactiveSeq<T>> permutations() {
return fromIterable(FoldableTraversable.super.permutations());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.ExtendedTraversable#combinations(int)
*/
@Override
default AnyMSeq<W,ReactiveSeq<T>> combinations(final int size) {
return fromIterable(FoldableTraversable.super.combinations(size));
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.ExtendedTraversable#combinations()
*/
@Override
default AnyMSeq<W,ReactiveSeq<T>> combinations() {
return fromIterable(FoldableTraversable.super.combinations());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Filters#ofType(java.lang.Class)
*/
@Override
default <U> AnyMSeq<W,U> ofType(final Class<? extends U> type) {
return (AnyMSeq<W,U>) FoldableTraversable.super.ofType(type);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.Filters#filterNot(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> filterNot(final Predicate<? super T> fn) {
return (AnyMSeq<W,T>) FoldableTraversable.super.filterNot(fn);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.IterableFunctor#unitIterable(java.util.Iterator)
*/
@Override
default <U> AnyMSeq<W,U> unitIterator(Iterator<U> U){
return (AnyMSeq<W,U>)adapter().unitIterable(()->U);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.EmptyUnit#emptyUnit()
*/
@Override
default <T> AnyMSeq<W,T> emptyUnit(){
return (AnyMSeq<W,T> )empty();
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#filter(java.util.function.Predicate)
*/
@Override
default AnyMSeq<W,T> filter(Predicate<? super T> p){
return (AnyMSeq<W,T>)AnyM.super.filter(p);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#map(java.util.function.Function)
*/
@Override
default <R> AnyMSeq<W,R> map(Function<? super T, ? extends R> fn){
return (AnyMSeq<W,R>)AnyM.super.map(fn);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.reactiveStream.reactive.ReactiveStreamsTerminalOperations#forEach(long, java.util.function.Consumer)
*/
@Override
default <X extends Throwable> Subscription forEach(final long numberOfElements, final Consumer<? super T> consumer) {
return this.stream()
.forEach(numberOfElements, consumer);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.reactiveStream.reactive.ReactiveStreamsTerminalOperations#forEach(long, java.util.function.Consumer, java.util.function.Consumer)
*/
@Override
default <X extends Throwable> Subscription forEach(final long numberOfElements, final Consumer<? super T> consumer,
final Consumer<? super Throwable> consumerError) {
return this.stream()
.forEach(numberOfElements, consumer, consumerError);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.reactiveStream.reactive.ReactiveStreamsTerminalOperations#forEach(long, java.util.function.Consumer, java.util.function.Consumer, java.lang.Runnable)
*/
@Override
default <X extends Throwable> Subscription forEach(final long numberOfElements, final Consumer<? super T> consumer,
final Consumer<? super Throwable> consumerError, final Runnable onComplete) {
return this.stream()
.forEach(numberOfElements, consumer, consumerError, onComplete);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.reactiveStream.reactive.ReactiveStreamsTerminalOperations#forEach(java.util.function.Consumer, java.util.function.Consumer)
*/
@Override
default <X extends Throwable> void forEach(final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError) {
this.stream()
.forEach(consumerElement, consumerError);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.types.reactiveStream.reactive.ReactiveStreamsTerminalOperations#forEach(java.util.function.Consumer, java.util.function.Consumer, java.lang.Runnable)
*/
@Override
default <X extends Throwable> void forEach(final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError,
final Runnable onComplete) {
this.stream()
.forEach(consumerElement, consumerError, onComplete);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#peek(java.util.function.Consumer)
*/
@Override
default AnyMSeq<W,T> peek(final Consumer<? super T> c) {
return map(i -> {
c.accept(i);
return i;
});
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#flatten()
*/
static <W extends WitnessType<W>,T1> AnyMSeq<W,T1> flatten(AnyMSeq<W,AnyMSeq<W,T1>> nested){
return nested.flatMap(Function.identity());
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#aggregate(com.aol.cyclops2.monad.AnyM)
*/
@Override
default AnyMSeq<W,List<T>> aggregate(AnyM<W,T> next){
return (AnyMSeq<W,List<T>>)AnyM.super.aggregate(next);
}
@Override
default <R> AnyMSeq<W,R> flatMapA(Function<? super T, ? extends AnyM<W,? extends R>> fn){
return (AnyMSeq<W,R>)AnyM.super.flatMapA(fn);
}
@Override
default <R> AnyMSeq<W,R> retry(final Function<? super T, ? extends R> fn) {
return (AnyMSeq<W,R>)AnyM.super.retry(fn);
}
@Override
default <R> AnyMSeq<W,R> retry(final Function<? super T, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) {
return (AnyMSeq<W,R>)AnyM.super.retry(fn);
}
@Override
default AnyMSeq<W,T> prependS(Stream<? extends T> stream) {
return (AnyMSeq<W,T>)FoldableTraversable.super.prependS(stream);
}
@Override
default AnyMSeq<W,T> append(T... values) {
return (AnyMSeq<W,T>)FoldableTraversable.super.append(values);
}
@Override
default AnyMSeq<W,T> append(T value) {
return (AnyMSeq<W,T>)FoldableTraversable.super.append(value);
}
@Override
default AnyMSeq<W,T> prepend(T value) {
return (AnyMSeq<W,T>)FoldableTraversable.super.prepend(value);
}
@Override
default AnyMSeq<W,T> prepend(T... values) {
return (AnyMSeq<W,T>)FoldableTraversable.super.prepend(values);
}
@Override
default AnyMSeq<W,T> insertAt(int pos, T... values) {
return (AnyMSeq<W,T>)FoldableTraversable.super.insertAt(pos,values);
}
@Override
default AnyMSeq<W,T> deleteBetween(int start, int end) {
return (AnyMSeq<W,T>)FoldableTraversable.super.deleteBetween(start,end);
}
@Override
default AnyMSeq<W,T> insertAtS(int pos, Stream<T> stream) {
return (AnyMSeq<W,T>)FoldableTraversable.super.insertAtS(pos,stream);
}
@Override
default AnyMSeq<W,T> recover(final Function<? super Throwable, ? extends T> fn) {
return (AnyMSeq<W,T>)FoldableTraversable.super.recover(fn);
}
@Override
default <EX extends Throwable> AnyMSeq<W,T> recover(Class<EX> exceptionClass, final Function<? super EX, ? extends T> fn) {
return (AnyMSeq<W,T>)FoldableTraversable.super.recover(exceptionClass,fn);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#unit(java.lang.Object)
*/
@Override
default <T> AnyMSeq<W,T> unit(T value){
return (AnyMSeq<W,T>)AnyM.super.unit(value);
}
/* (non-Javadoc)
* @see com.aol.cyclops2.monad.AnyM#empty()
*/
@Override
default <T> AnyMSeq<W,T> empty(){
return (AnyMSeq<W,T>)AnyM.super.empty();
}
default <R> AnyMSeq<W,R> flatMap(Function<? super T, ? extends AnyM<W,? extends R>> fn){
return flatMapA(fn);
}
@Override
ReactiveSeq<T> stream();
@Override
default DequeX<T> toDequeX() {
return FoldableTraversable.super.toDequeX().materialize();
}
@Override
default QueueX<T> toQueueX() {
return FoldableTraversable.super.toQueueX().materialize();
}
@Override
default SetX<T> toSetX() {
return FoldableTraversable.super.toSetX().materialize();
}
@Override
default ListX<T> toListX() {
return FoldableTraversable.super.toListX().materialize();
}
@Override
default PStackX<T> toPStackX() {
return FoldableTraversable.super.toPStackX().materialize();
}
@Override
default PVectorX<T> toPVectorX() {
return FoldableTraversable.super.toPVectorX().materialize();
}
@Override
default PQueueX<T> toPQueueX() {
return FoldableTraversable.super.toPQueueX().materialize();
}
@Override
default PBagX<T> toPBagX() {
return FoldableTraversable.super.toPBagX().materialize();
}
@Override
default PSetX<T> toPSetX() {
return FoldableTraversable.super.toPSetX().materialize();
}
@Override
default POrderedSetX<T> toPOrderedSetX() {
return FoldableTraversable.super.toPOrderedSetX().materialize();
}
} |
package jp.ddo.masm11.cplayer;
import android.support.v7.app.AppCompatActivity;
import android.app.Service;
import android.os.IBinder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.media.MediaPlayer;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.widget.Button;
import android.widget.TextView;
import android.widget.SeekBar;
import android.content.Intent;
import android.content.Context;
import android.content.ServiceConnection;
import android.content.ComponentName;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private class PlayerServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
svc = (PlayerService.PlayerServiceBinder) service;
svc.setOnStatusChangedListener(new PlayerService.OnStatusChangedListener() {
public void onStatusChanged(PlayerService.CurrentStatus status) {
Log.d("path=%s, topDir=%s, position=%d.",
status.path, status.topDir, status.position);
updateTrackInfo(status);
}
});
updateTrackInfo(svc.getCurrentStatus());
}
@Override
public void onServiceDisconnected(ComponentName name) {
svc = null;
}
}
private PlayerService.PlayerServiceBinder svc;
private ServiceConnection conn;
private File rootDir;
private String curPath;
private String curTopDir;
private int curPos; // msec
private int maxPos; // msec
private boolean seeking;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.init(getExternalCacheDir());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
Log.d("rootDir=%s", rootDir.getAbsolutePath());
rootDir.mkdirs();
curTopDir = rootDir.getAbsolutePath();
if (PlayContext.all().size() == 0) {
PlayContext ctxt = new PlayContext();
ctxt.name = (String) getResources().getText(R.string.default_context);
ctxt.topDir = rootDir.getAbsolutePath();
ctxt.save();
}
Config config = Config.findByKey("context_id");
if (config == null) {
config = new Config();
config.key = "context_id";
config.value = PlayContext.all().get(0).getId().toString();
config.save();
}
TextView textView;
textView = (TextView) findViewById(R.id.context_name);
assert textView != null;
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ContextActivity.class);
startActivity(i);
}
});
View layout = findViewById(R.id.playing_info);
assert layout != null;
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ExplorerActivity.class);
PlayContext ctxt = PlayContext.all().get(0);
i.putExtra("CONTEXT_ID", ctxt.getId());
startActivity(i);
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.playing_pos);
assert seekBar != null;
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
if (svc != null)
svc.seek(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
seeking = true;
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
seeking = false;
}
});
// started service
// fixme: service ...
Intent intent = new Intent(this, PlayerService.class);
startService(intent);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, PlayerService.class);
conn = new PlayerServiceConnection();
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
@Override
protected void onResume() {
PlayContext ctxt = PlayContext.find(Long.parseLong(Config.findByKey("context_id").value));
TextView textView = (TextView) findViewById(R.id.context_name);
assert textView != null;
if (ctxt != null)
textView.setText(ctxt.name);
super.onResume();
}
@Override
protected void onStop() {
unbindService(conn);
super.onStop();
}
private void updateTrackInfo(PlayerService.CurrentStatus status) {
if (!strEq(curPath, status.path)) {
curPath = status.path;
PathView pathView = (PathView) findViewById(R.id.playing_filename);
assert pathView != null;
pathView.setRootDir(rootDir.getAbsolutePath());
pathView.setPath(curPath);
MediaMetadataRetriever retr = new MediaMetadataRetriever();
CharSequence title = null, artist = null;
String duration = null;
try {
retr.setDataSource(curPath);
title = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
artist = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
duration = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
} catch (Exception e) {
Log.i(e, "exception");
}
retr.release();
if (title == null)
title = getResources().getText(R.string.unknown_title);
if (artist == null)
artist = getResources().getText(R.string.unknown_artist);
TextView textView;
textView = (TextView) findViewById(R.id.playing_title);
assert textView != null;
textView.setText(title);
textView = (TextView) findViewById(R.id.playing_artist);
assert textView != null;
textView.setText(artist);
if (duration != null)
maxPos = Integer.parseInt(duration);
else
maxPos = 0;
SeekBar seekBar = (SeekBar) findViewById(R.id.playing_pos);
assert seekBar != null;
seekBar.setMax(maxPos);
int sec = maxPos / 1000;
String maxTime = String.format("%d:%02d", sec / 60, sec % 60);
textView = (TextView) findViewById(R.id.playing_maxtime);
assert textView != null;
textView.setText(maxTime);
}
if (!strEq(curTopDir, status.topDir)) {
curTopDir = status.topDir;
PathView pathView = (PathView) findViewById(R.id.playing_filename);
assert pathView != null;
pathView.setTopDir(curTopDir);
}
if (curPos != status.position) {
curPos = status.position;
SeekBar seekBar = (SeekBar) findViewById(R.id.playing_pos);
assert seekBar != null;
seekBar.setProgress(curPos);
int sec = curPos / 1000;
String curTime = String.format("%d:%02d", sec / 60, sec % 60);
TextView textView = (TextView) findViewById(R.id.playing_curtime);
assert textView != null;
textView.setText(curTime);
}
}
private boolean strEq(String s1, String s2) {
if (s1 == s2)
return true;
if (s1 == null && s2 != null)
return false;
if (s1 != null && s2 == null)
return false;
return s1.equals(s2);
}
} |
package org.redisson;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.Test;
import io.netty.channel.nio.NioEventLoopGroup;
import org.redisson.RedisRunner.RedisProcess;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
public class RedissonRedLockTest {
@Test
public void testLockLeasetime() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
RLock lock1 = client1.getLock("lock1");
RLock lock2 = client1.getLock("lock2");
RLock lock3 = client2.getLock("lock3");
RLock lock4 = client2.getLock("lock4");
RLock lock5 = client2.getLock("lock5");
RLock lock6 = client2.getLock("lock6");
RLock lock7 = client2.getLock("lock7");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3, lock4, lock5, lock6, lock7);
ExecutorService executor = Executors.newFixedThreadPool(10);
AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < 10; i++) {
executor.submit(() -> {
for (int j = 0; j < 5; j++) {
try {
lock.lock(2, TimeUnit.SECONDS);
int nextValue = counter.get() + 1;
Thread.sleep(1000);
counter.set(nextValue);
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
executor.shutdown();
assertThat(executor.awaitTermination(2, TimeUnit.MINUTES)).isTrue();
assertThat(counter.get()).isEqualTo(50);
assertThat(redis1.stop()).isEqualTo(0);
assertThat(redis2.stop()).isEqualTo(0);
}
@Test
public void testTryLockLeasetime() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
RLock lock1 = client1.getLock("lock1");
RLock lock2 = client1.getLock("lock2");
RLock lock3 = client2.getLock("lock3");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
ExecutorService executor = Executors.newFixedThreadPool(10);
AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < 10; i++) {
executor.submit(() -> {
for (int j = 0; j < 5; j++) {
try {
if (lock.tryLock(4, 2, TimeUnit.SECONDS)) {
int nextValue = counter.get() + 1;
Thread.sleep(1000);
counter.set(nextValue);
lock.unlock();
} else {
j
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
executor.shutdown();
assertThat(executor.awaitTermination(2, TimeUnit.MINUTES)).isTrue();
assertThat(counter.get()).isEqualTo(50);
assertThat(redis1.stop()).isEqualTo(0);
assertThat(redis2.stop()).isEqualTo(0);
}
@Test
public void testLockFailed() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
RLock lock1 = client1.getLock("lock1");
RLock lock2 = client1.getLock("lock2");
RLock lock3 = client2.getLock("lock3");
Thread t1 = new Thread() {
public void run() {
lock2.lock();
lock3.lock();
};
};
t1.start();
t1.join();
Thread t = new Thread() {
public void run() {
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
};
};
t.start();
t.join(1000);
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
Assert.assertFalse(lock.tryLock());
assertThat(redis1.stop()).isEqualTo(0);
assertThat(redis2.stop()).isEqualTo(0);
}
@Test
public void testLockSuccess() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
RLock lock1 = client1.getLock("lock1");
RLock lock2 = client1.getLock("lock2");
RLock lock3 = client2.getLock("lock3");
Thread t1 = new Thread() {
public void run() {
lock3.lock();
};
};
t1.start();
t1.join();
Thread t = new Thread() {
public void run() {
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
lock.unlock();
};
};
t.start();
t.join(1000);
lock3.delete();
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
lock.unlock();
assertThat(redis1.stop()).isEqualTo(0);
assertThat(redis2.stop()).isEqualTo(0);
}
@Test
public void testConnectionFailed() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
RLock lock1 = client1.getLock("lock1");
RLock lock2 = client1.getLock("lock2");
assertThat(redis2.stop()).isEqualTo(0);
RLock lock3 = client2.getLock("lock3");
Thread t = new Thread() {
public void run() {
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
lock.unlock();
};
};
t.start();
t.join(1000);
RedissonMultiLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
lock.unlock();
assertThat(redis1.stop()).isEqualTo(0);
}
// @Test
public void testMultiThreads() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
Config config1 = new Config();
config1.useSingleServer().setAddress(redis1.getRedisServerAddressAndPort());
RedissonClient client = Redisson.create(config1);
RLock lock1 = client.getLock("lock1");
RLock lock2 = client.getLock("lock2");
RLock lock3 = client.getLock("lock3");
Thread t = new Thread() {
public void run() {
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
lock.unlock();
};
};
t.start();
t.join(1000);
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
lock.unlock();
assertThat(redis1.stop()).isEqualTo(0);
}
// @Test
public void test() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedisProcess redis3 = redisTestMultilockInstance();
NioEventLoopGroup group = new NioEventLoopGroup();
RedissonClient client1 = createClient(group, redis1.getRedisServerAddressAndPort());
RedissonClient client2 = createClient(group, redis2.getRedisServerAddressAndPort());
RedissonClient client3 = createClient(group, redis3.getRedisServerAddressAndPort());
final RLock lock1 = client1.getLock("lock1");
final RLock lock2 = client2.getLock("lock2");
final RLock lock3 = client3.getLock("lock3");
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
final AtomicBoolean executed = new AtomicBoolean();
Thread t = new Thread() {
@Override
public void run() {
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
assertThat(lock.tryLock()).isFalse();
assertThat(lock.tryLock()).isFalse();
executed.set(true);
}
};
t.start();
t.join();
await().atMost(5, TimeUnit.SECONDS).until(() -> assertThat(executed.get()).isTrue());
lock.unlock();
assertThat(redis1.stop()).isEqualTo(0);
assertThat(redis2.stop()).isEqualTo(0);
assertThat(redis3.stop()).isEqualTo(0);
}
private RedissonClient createClient(String host) {
return createClient(null, host);
}
private RedissonClient createClient(NioEventLoopGroup group, String host) {
Config config1 = new Config();
config1.useSingleServer().setAddress(host);
config1.setEventLoopGroup(group);
RedissonClient client1 = Redisson.create(config1);
client1.getKeys().flushdb();
return client1;
}
private RedisProcess redisTestMultilockInstance() throws IOException, InterruptedException {
return new RedisRunner()
.nosave()
.randomDir()
.randomPort()
.run();
}
} |
package com.bwfcwalshy.flarebot;
import com.bwfcwalshy.flarebot.music.MusicManager;
import com.google.gson.JsonParseException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.MissingPermissionsException;
import sx.blah.discord.util.RequestBuffer;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.List;
public class VideoThread extends Thread {
// Keep this instance across all threads. Efficiency bitch!
private static MusicManager manager;
private String searchTerm;
private IUser user;
private IChannel channel;
private boolean isUrl = false;
private boolean isShortened = false;
public VideoThread(String term, IUser user, IChannel channel) {
this.searchTerm = term;
this.user = user;
this.channel = channel;
if (manager == null) manager = FlareBot.getInstance().getMusicManager();
start();
}
public VideoThread(String termOrUrl, IUser user, IChannel channel, boolean url, boolean shortened) {
this.searchTerm = termOrUrl;
this.user = user;
this.channel = channel;
this.isUrl = url;
this.isShortened = shortened;
if (manager == null) manager = FlareBot.getInstance().getMusicManager();
start();
}
// Making sure these stay across all threads.
private static final String SEARCH_URL = "https:
private static final String YOUTUBE_URL = "https:
private static final String WATCH_URL = "https:
private static final String EXTENSION = ".mp3";
@Override
public void run() {
long a = System.currentTimeMillis();
// TODO: Severely clean this up!!!
// ^ EDIT BY Arsen: A space goes there..
try {
IMessage message;
String videoName;
String link;
String videoId;
if (!searchTerm.matches("https?://(www\\.)?youtube.com/playlist\\?list=([0-9A-z+-]*)")) {
if (isUrl) {
message = MessageUtils.sendMessage(channel, "Getting video from URL.");
if (isShortened) {
searchTerm = YOUTUBE_URL + searchTerm.replaceFirst("http(s)?://youtu\\.be", "");
}
Document doc = Jsoup.connect(searchTerm).get();
videoId = searchTerm.replaceFirst("http(s)?://(www\\.)?youtube\\.com/watch\\?v=", "");
// Playlist
if (videoId.contains("&list")) videoId = videoId.substring(0, videoId.indexOf("&list"));
videoName = MessageUtils.escapeFile(doc.title().replace(" - YouTube", ""));
link = WATCH_URL + videoId;
} else {
message = MessageUtils.sendMessage(channel, "Searching YouTube for '" + searchTerm + "'");
Document doc = Jsoup.connect(SEARCH_URL + URLEncoder.encode(searchTerm, "UTF-8")).get();
int i = 0;
Element videoElement = doc.getElementsByClass("yt-lockup-title").get(i);
boolean hasAd = true;
while (hasAd) {
for (Element e : videoElement.children()) {
if (e.toString().contains("href=\"https://googleads")) {
videoElement = doc.getElementsByClass("yt-lockup-title").get(++i);
break;
}
}
hasAd = false;
}
link = videoElement.select("a").first().attr("href");
Document doc2 = Jsoup.connect((link.startsWith("http") ? "" : YOUTUBE_URL) + link).get();
videoName = MessageUtils.escapeFile(doc2.title().substring(0, doc2.title().length() - 10));
// I check the index of 2 chars so I need to add 2
videoId = link.substring(link.indexOf("v=") + 2);
link = YOUTUBE_URL + link;
}
File video = new File("cached" + File.separator + videoId + EXTENSION);
// if (video.exists()) {
// manager.addSong(channel.getGuild().getID(), videoFile + EXTENSION);
// RequestBuffer.request(() -> {
// try {
// message.edit(user.mention() + " added: **" + videoName + "** to the playlist!");
// FlareBot.LOGGER.error("Could not edit own message!", e);
if (!video.exists()) {
RequestBuffer.request(() -> {
try {
message.edit("Downloading video!");
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Could not edit own message!", e);
}
});
ProcessBuilder builder = new ProcessBuilder("youtube-dl", "-o",
"cached" + File.separator + "%(id)s.%(ext)s",
"--extract-audio", "--audio-format"
, "mp3", link);
FlareBot.LOGGER.debug("Downloading");
builder.redirectErrorStream(true);
Process process = builder.start();
processInput(process);
process.waitFor();
if (process.exitValue() != 0) {
RequestBuffer.request(() -> {
try {
message.edit("Could not download **" + videoName + "**!");
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Could not edit own message!", e);
}
});
return;
}
}
if (manager.addSong(channel.getGuild().getID(), video.getName(), videoName)) {
RequestBuffer.request(() -> {
try {
message.edit(user.mention() + " added: **" + videoName + "** to the playlist!");
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Could not edit own message!", e);
}
});
} else RequestBuffer.request(() -> {
try {
message.edit("Failed to add **" + videoName + "**!");
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Could not edit own message!", e);
}
});
} else {
message = MessageUtils.sendMessage(channel, "Getting playlist from URL.");
ProcessBuilder builder = new ProcessBuilder("youtube-dl", "-i", "-4", "--dump-single-json", "--flat-playlist", searchTerm);
searchTerm = searchTerm.replaceFirst("https?://(www\\.)?youtube.com/playlist\\?list=", "");
Process process = builder.start();
Playlist playlist;
try {
playlist = FlareBot.GSON.fromJson(new InputStreamReader(process.getInputStream()), Playlist.class);
} catch (JsonParseException e) {
RequestBuffer.request(() -> {
try {
message.edit("Could not parse the playlist!");
} catch (MissingPermissionsException | DiscordException e1) {
FlareBot.LOGGER.error("Edit own message!", e1);
}
});
FlareBot.LOGGER.error("Could not parse playlist!", e);
return;
}
RequestBuffer.request(() -> {
try {
message.edit("Downloading **" + playlist.title + "**");
} catch (MissingPermissionsException | DiscordException e1) {
FlareBot.LOGGER.error("Edit own message!", e1);
}
});
int i = 0;
for (Playlist.PlaylistEntry e : playlist.entries) {
if(e != null){
if (!new File("cached" + File.separator + e.id + EXTENSION).exists()) {
ProcessBuilder entryDownload = new ProcessBuilder("youtube-dl", "-o",
"cached" + File.separator + "%(id)s.%(ext)s",
"--extract-audio", "--audio-format"
, "mp3", WATCH_URL + e.id);
FlareBot.LOGGER.debug("Downloading");
entryDownload.redirectErrorStream(true);
Process downloadProcess = entryDownload.start();
processInput(downloadProcess);
downloadProcess.waitFor();
if(downloadProcess.exitValue() != 0)
continue;
}
FlareBot.getInstance().getMusicManager().addSong(message.getChannel().getGuild().getID(), e.id + EXTENSION, e.title);
}
if(++i % 10 == 0){
int finalI = i;
RequestBuffer.request(() -> {
try {
message.edit(user + "Added **" + finalI + "** out of **" + playlist.entries.size() + "** songs to the queue");
} catch (MissingPermissionsException | DiscordException e1) {
FlareBot.LOGGER.error("Could not edit own message!", e1);
}
});
}
}
RequestBuffer.request(() -> {
try {
message.edit(user + " Added the playlist **" + playlist.title + "** to the queue");
} catch (MissingPermissionsException | DiscordException e1) {
FlareBot.LOGGER.error("Could not edit own message!", e1);
}
});
}
} catch (IOException | InterruptedException e) {
FlareBot.LOGGER.error(e.getMessage(), e);
}
long b = System.currentTimeMillis();
FlareBot.LOGGER.debug("Process took " + (b - a) + " milliseconds");
}
private void processInput(Process downloadProcess) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(downloadProcess.getInputStream()))) {
while (downloadProcess.isAlive()) {
String line;
if ((line = reader.readLine()) != null) {
FlareBot.LOGGER.info("[YT-DL] " + line);
}
}
}
}
private class Playlist {
public List<PlaylistEntry> entries;
public class PlaylistEntry {
public String id;
public String title;
}
public String title;
}
} |
package com.catalyst.sonar.score.log;
import static org.mockito.Mockito.mock;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* The Logger class is used for printing useful information in the console of a
* CI engine (like Hudson/Jenkins), and for general debugging.
*
* @author JDunn
*
*/
public class Logger {
public static final char BORDER1 = '*';
public static final char BORDER2 = '>';
public static final char BORDER3 = ':';
public static final char BORDER4 = '-';
public static final char[] BORDER = { BORDER1, BORDER2, BORDER3, BORDER4 };
public static final char TAB = '\t';
public static final int BORDER_LENGTH = 70;
public static final int TAB_LENGTH = 4;
public static final String START = "Start ";
public static final String END = "End ";
public static final int MAX_LENGTH = 50;
public static final Logger LOG = new Logger();
private int extraTabs = 0;
private static final PrintStream offStream = mock(PrintStream.class);
private PrintStream currentStream;
private PrintStream onStream;
private List<String> stack;
private boolean offForMethod;
/**
* The no-args constructor sets the currentStream and onStream to
* {@code System.out} and instantiates the {@code List<String> stack} as an
* {@link ArrayList} {@code <String>}.
*/
public Logger() {
this(System.out);
}
/**
* Constructs a Logger and sets its currentStream and onStream to
* {@code onStream} and instantiates the {@code List<String> stack} as an
* {@link ArrayList} {@code <String>}.
*
* @param onStream
*/
public Logger(PrintStream onStream) {
this.onStream = onStream;
this.currentStream = this.onStream;
this.stack = new ArrayList<String>();
offForMethod = false;
}
/**
* Prints a tab for every method name in the stack List, and then prints the
* object.
*
* @param x
* @return this
*/
public Logger log(Object x) {
currentStream.println(tab() + x);
return this;
}
/**
* Logs an Exception.
*
* @param e
* @return
*/
public Logger log(Exception e) {
final boolean wasOff = !isOn();
onIf(wasOff);
log(e.toString());
addTab(1);
log(Arrays.asList(e.getStackTrace()));
return offIf(wasOff);
}
/**
* Prints a tab for every method name in the stack List, and then logs each
* object in Collection x on its own line.
*
* @param x
* @return this
*/
public Logger log(@SuppressWarnings("rawtypes") Collection x) {
String listDelimiter = ", ";
// characters left in line now
int before = MAX_LENGTH;
// characters that will be left in line after Object o is printed
int after = before;
int index = 0;
for (Object o : x) {
index++;
if (index == x.size()) {
listDelimiter = ".";
}
String objStr = o.toString() + listDelimiter;
after = before - objStr.length();
if (before == MAX_LENGTH) {
currentStream.print(tab() + objStr);
} else if (after >= 0) {
currentStream.print("" + objStr);
} else {
currentStream.println();
currentStream.print(tab() + objStr);
before = MAX_LENGTH - objStr.length();
continue;
}
before = after;
}
currentStream.println();
return this;
}
/**
* Prints the same as {@link Logger.log(Object x)} but adding an emphasis
* String.
*
* @param x
* @return
*/
public Logger logEmf(Object x) {
currentStream.println(tab() + "!!! " + x);
return log(x);
}
/**
* Prints the same as {@link Logger.log(Object x)} but adding an emphasis
* String.
*
* @param x
* @return
*/
public Logger warn(Object x) {
Object objectToPrint = x;
if (x instanceof String[]) {
objectToPrint = Arrays.toString((String[]) x);
}
currentStream.println(tab() + "WARNING! " + objectToPrint);
return this;
}
/**
* Prints the methodName with a border, and then adds the methodName to the
* stack.
*
* @param methodName
* @return
*/
public Logger beginMethod(final String methodName) {
String message = border(TAB_LENGTH) + START + methodName;
borderMessage(message);
stack.add(methodName);
return this;
}
/**
* Logs the beginning of a method only if logIf is true; if not, the Logger
* is turned off until endMethod() is called.
*
* @param methodName
* @param logIf
* @return
*/
public Logger beginMethod(final String methodName, boolean logIf) {
if (!logIf) {
off();
this.offForMethod = true;
}
return beginMethod(methodName);
}
/**
* Removes the last methodName from the stack and prints it with a border.
*
* @return
*/
public Logger endMethod() {
try {
final String methodName = stack.remove(stack.size() - 1);
String message = border(TAB_LENGTH) + END + methodName;
return borderMessage(message).onIf(offForMethod);
} catch (ArrayIndexOutOfBoundsException methodLoggingOutOfSync) {
final boolean wasOff = !isOn();
onIf(wasOff);
return LOG.log("METHOD LOGGING OUT OF SYNC!!!")
.log(methodLoggingOutOfSync).offIf(wasOff);
}
}
/**
* Logs "Returning " + the object.
*
* @param o
* @return
*/
public Logger returning(Object o) {
return log("Returning " + o);
}
/**
* prints a message with a "border". The characters used in the Border will
* be based on the stack size.
*
* @param message
* @return
*/
private Logger borderMessage(String message) {
currentStream.println(tab()
+ message
+ border(BORDER_LENGTH - (TAB_LENGTH * stack.size())
- message.length()));
return this;
}
/**
* Returns a String to be used as a border.
*
* @param x
* @return
*/
private String border(final int x) {
StringBuilder border = new StringBuilder();
int index = stack.size();
index = (index >= BORDER.length) ? BORDER.length - 1 : index;
for (int y = 0; y < x; y++) {
border.append(BORDER[index]);
}
return border.toString();
}
/**
* Returns a String consisting of the appropriate number of tabs based on
* the size of the stack List.
*
* @return
*/
private String tab() {
String tabs = "";
for (int i = 0; i < stack.size() + extraTabs; i++) {
tabs += '\t';
}
return tabs;
}
/**
* @return the currentStream
*/
public PrintStream getStream() {
return currentStream;
}
/**
* @param stream
* the currentStream to set
* @param stream
* @return this
*/
public Logger setStream(PrintStream stream) {
this.currentStream = stream;
return this;
}
/**
* Gets the onStream -- that is, the {@link PrintStream} when this Logger is
* turned on.
*
* @return the onStream
*/
public PrintStream getOnStream() {
return onStream;
}
/**
* Gets the onStream -- that is, the {@link PrintStream} when this Logger is
* turned on.
*
* @param onStream
* the onStream to set
*/
public void setOnStream(PrintStream onStream) {
this.onStream = onStream;
}
/**
* Adds the specified number of tabs to the indentation of what is being
* logged.
*
* @param amount
* @return
*/
public Logger addTab(int amount) {
extraTabs += amount;
return this;
}
/**
* Removes the specified number of tabs from the indentation of what is
* being logged.
*
* @param amount
* @return
*/
public Logger removeTab(int amount) {
extraTabs -= amount;
return this;
}
/**
* Turns on this Logger by setting {@code this.currentStream} to
* {@code this.onStream}.
*
* @return
*/
private Logger on() {
return setStream(onStream);
}
/**
* Turns off this Logger by setting {@code this.currentStream} to
* {@code this.offStream}.
*
* @return
*/
private Logger off() {
return setStream(offStream);
}
/**
* Turns this Logger off if the boolean argument offIf is true.
*
* @param offIf
* @return
*/
private Logger offIf(boolean offIf) {
return (offIf) ? off() : this;
}
private boolean isOn() {
return currentStream == onStream;
}
/**
* Turns this Logger on if the boolean argument onIf is true.
*
* @param onIf
* @return
*/
private Logger onIf(boolean onIf) {
return (onIf) ? on() : this;
}
} |
package org.zoneproject.extractor.plugin.extractarticlescontent;
import de.l3s.boilerpipe.BoilerpipeProcessingException;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zoneproject.extractor.utils.Item;
import org.zoneproject.extractor.utils.Prop;
import org.zoneproject.extractor.utils.VirtuosoDatabase;
public class DownloadThread extends Thread {
private Item item;
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(App.class);
public DownloadThread(Item item) {
this.item = item;
}
public void run() {
run(0);
}
public void run(int restartLevel) {
if(restartLevel > 5) {
logger.warn("annotation process imposible for "+item.getUri());
return;
}
if(restartLevel>0)
try {Thread.currentThread().sleep(5000);} catch (InterruptedException ex1) {}
try {
logger.info("Add ExtractArticlesContent for item: "+item);
URL url = new URL(item.getUri());
String content= ArticleExtractor.INSTANCE.getText(url).replace("\u00A0", " ").trim();
String title = item.getTitle().trim();
if(item.getDescription() != null){
String description = item.getDescription().trim().substring(0,Math.min(item.getDescription().trim().length(),20));
if(content.contains(description)){
content = content.substring(content.indexOf(description));
}
}
if(content.contains(title)){
content = content.substring(content.indexOf(title)+title.length());
}
content = content.replace("\n", "<br/>");
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(App.PLUGIN_RESULT_URI,content));
} catch (BoilerpipeProcessingException ex) {
logger.warn("annotation process because of download error for "+item.getUri());
run(restartLevel+1);
} catch (MalformedURLException ex) {
logger.warn("annotation process because of malformed Uri for "+item.getUri());
} catch (java.io.IOException ex) {
logger.warn("annotation process because of download error for "+item.getUri());
run(restartLevel+1);
}catch (com.hp.hpl.jena.shared.JenaException ex){
logger.warn("annotation process because of virtuoso partial error "+item.getUri());
run(restartLevel+1);
}
}
} |
package thomas.jonathan.notey;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.CursorIndexOutOfBoundsException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.speech.RecognizerIntent;
import android.support.v4.app.NotificationCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.vending.billing.IInAppBillingService;
import com.easyandroidanimations.library.ScaleInAnimation;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import thomas.jonathan.notey.util.IabHelper;
import thomas.jonathan.notey.util.IabResult;
import thomas.jonathan.notey.util.Inventory;
import thomas.jonathan.notey.util.Purchase;
public class MainActivity extends Activity implements OnClickListener {
public static final int CURRENT_ANDROID_VERSION = Build.VERSION.SDK_INT;
public static boolean justTurnedPro = false;
public static boolean spinnerChanged = false;
private static final int REQUEST_CODE = 1234;
public static final int SHORTCUT_NOTIF_ID = 314150413; //pi and bday
private final String TAG = "Notey_MainActivity";
private List<Integer> imageIconList;
private NotificationManager nm;
private ImageButton ib1, ib2, ib3, ib4, ib5, send_btn, menu_btn, alarm_btn;
private EditText et, et_title;
private Spinner spinner;
private PopupMenu mPopupMenu;
private int imageButtonNumber = 1, spinnerLocation = 0, id = (int) (Math.random() * 10000), priority;
private boolean pref_expand;
private boolean pref_swipe;
private boolean impossible_to_delete = false;
private boolean pref_enter;
private boolean pref_share_action;
private boolean settings_activity_flag;
private boolean about_activity_flag;
private boolean editIntentFlag = false;
private boolean noteTextBoxHasFocus = false;
private String clickNotif;
private String noteTitle;
private String alarm_time = "";
private int repeat_time = 0;
private NoteyNote notey;
public MySQLiteHelper db = new MySQLiteHelper(this);
private RelativeLayout layout_bottom;
private PendingIntent alarmPendingIntent;
private static List<String> pref_icons;
private List<String> spinnerPositionList;
private static Context appContext;
public static final SimpleDateFormat format_short_date = new SimpleDateFormat("MMM dd"), format_short_time = new SimpleDateFormat("hh:mm a");
/* in app billing variables */
public static IabHelper mHelper;
public static IInAppBillingService mService;
public static ServiceConnection mServiceConn;
public static final String SKU_PRO_VERSION = "thomas.jonathan.notey.pro";
public static final String SKU_TIP_VERSION = "thomas.jonathan.notey.tip";
public static boolean proVersionEnabled = false;
public static String payload = Integer.toString((int) (Math.random() * 1000000));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_dialog);
getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
notey = new NoteyNote(); //create a new Notey object
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
appContext = getApplicationContext();
doInAppBillingStuff();
initializeSettings();
initializeGUI();
setLayout();
//menu popup
mPopupMenu = new PopupMenu(this, menu_btn);
setUpMenu();
checkForAppUpdate(); // restore notifications after app update
checkForAnyIntents(); //checking for intents of edit button clicks or received shares
//button click listener. for Enter key and Menu key
et.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button, then check the prefs for what to do (either new line or send).
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
pref_enter = sp.getBoolean("pref_enter", true);
// enter to send, or new line
if (pref_enter)
send_btn.performClick();
else et.append("\n");
return true;
}
//if hardware menu button, activate the menu button at the top of the app.
else if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_MENU)) {
menu_btn.performClick();
}
return false;
}
});
//focus change listeners for the note and title text boxes. these are for determining where the text will go when using the mic button
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
noteTextBoxHasFocus = true;
}
}
});
et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
noteTextBoxHasFocus = false;
}
}
});
//spinner listener. changes the row of five icons based on what spinner item is selected.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
if (editIntentFlag) {
spinner.setSelection(spinnerLocation);
position = spinnerLocation;
editIntentFlag = false;
} else spinnerLocation = position;
String s = pref_icons.get(position);
//the text the user sees is different than the icon names
if (s.equals("smile")) s = "mood";
if (s.equals("heart")) s = "favorite";
if (s.equals("note")) s = "note_add";
ib1.setImageResource(getResources().getIdentifier("ic_" + s + "_white_36dp", "drawable", getPackageName()));
ib2.setImageResource(getResources().getIdentifier("ic_" + s + "_yellow_36dp", "drawable", getPackageName()));
ib3.setImageResource(getResources().getIdentifier("ic_" + s + "_blue_36dp", "drawable", getPackageName()));
ib4.setImageResource(getResources().getIdentifier("ic_" + s + "_green_36dp", "drawable", getPackageName()));
ib5.setImageResource(getResources().getIdentifier("ic_" + s + "_red_36dp", "drawable", getPackageName()));
new ScaleInAnimation(ib1).setDuration(250).animate();
new ScaleInAnimation(ib2).setDuration(250).animate();
new ScaleInAnimation(ib3).setDuration(250).animate();
new ScaleInAnimation(ib4).setDuration(250).animate();
new ScaleInAnimation(ib5).setDuration(250).animate();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// do nothing
}
});
}
//adapter for spinner. allows custom icons to be placed.
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, parent);
}
public View getCustomView(int position, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.spinner, parent, false);
ImageView icon = (ImageView) row.findViewById(R.id.imageView1);
icon.setImageResource(imageIconList.get(position));
new ScaleInAnimation(icon).setDuration(250).animate();
return row;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public void onClick(View v) {
//if one of the five icons are clicked, highlight them and un-highlight the previous selection.
if (v.getId() == R.id.imageButton1) {
imageButtonNumber = 1;
ib1.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (v.getId() == R.id.imageButton2) {
imageButtonNumber = 2;
ib2.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (v.getId() == R.id.imageButton3) {
imageButtonNumber = 3;
ib3.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (v.getId() == R.id.imageButton4) {
imageButtonNumber = 4;
ib4.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (v.getId() == R.id.imageButton5) {
imageButtonNumber = 5;
ib5.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
} else if (v.getId() == R.id.menuButton) {
mPopupMenu.show();
} else if (v.getId() == R.id.alarm_btn) {
Intent i = new Intent(this, AlarmActivity.class);
i.putExtra("alarm_id", id);
// if alarm is set, pass the alarm time to the next activity. if no repeat, check for regular alarm
if (repeat_time != 0) {
i.putExtra("repeat_set_time", repeat_time);
i.putExtra("alarmPendingIntent", alarmPendingIntent);
if (alarm_time != null && !alarm_time.equals(""))
i.putExtra("alarm_set_time", alarm_time);
} else if (alarm_time != null && !alarm_time.equals("")) {
i.putExtra("alarm_set_time", alarm_time);
i.putExtra("alarmPendingIntent", alarmPendingIntent);
}
startActivityForResult(i, id);
settings_activity_flag = false;
about_activity_flag = false;
}
// else if the send button is pressed
else if (v.getId() == R.id.btn) {
//check if user has made it not possible to remove notifications.
// (this is a fail-safe in case they got out of the settings menu by pressing the 'home' key or some other way)
if ((!clickNotif.equals("remove") && !clickNotif.equals("info")) && !pref_swipe && !pref_expand) {
Toast.makeText(getApplicationContext(), getString(R.string.impossibleToDeleteAtSend), Toast.LENGTH_SHORT).show();
impossible_to_delete = true;
} else impossible_to_delete = false;
//if empty, go ahead with voice input
if (et.getText().toString().equals("") && et_title.getText().toString().equals("")) {
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_voice_input), Toast.LENGTH_SHORT).show();
} else {
startVoiceRecognitionActivity();
}
}
// if alarm time is empty, set the boolean to true, otherwise check if alarm time is greater than current time. if it is, dont set notificatin.
boolean alarmTimeIsGreaterThanCurrentTime;
alarmTimeIsGreaterThanCurrentTime = alarm_time == null || alarm_time.equals("") || Long.valueOf(alarm_time) > System.currentTimeMillis();
//if either textbox has text AND it is possible to delete notifs AND (if current time is less than alarm time OR there is a repeating alarm), then set the alarm, continue and create notification
if ((!et.getText().toString().equals("") || !et_title.getText().toString().equals("")) && !impossible_to_delete && (alarmTimeIsGreaterThanCurrentTime || repeat_time != 0)) {
String s = pref_icons.get(spinnerLocation);
if (s.equals("smile")) s = "mood";
if (s.equals("heart")) s = "favorite";
if (s.equals("note")) s = "note_add";
int d;
if (imageButtonNumber == 2)
d = getResources().getIdentifier("ic_" + s + "_yellow_36dp", "drawable", getPackageName());
else if (imageButtonNumber == 3)
d = getResources().getIdentifier("ic_" + s + "_blue_36dp", "drawable", getPackageName());
else if (imageButtonNumber == 4)
d = getResources().getIdentifier("ic_" + s + "_green_36dp", "drawable", getPackageName());
else if (imageButtonNumber == 5)
d = getResources().getIdentifier("ic_" + s + "_red_36dp", "drawable", getPackageName());
else
d = getResources().getIdentifier("ic_" + s + "_white_36dp", "drawable", getPackageName());
String note = et.getText().toString(); //get the text
//set title text
String tickerText; //if title is there, set ticker to title. otherwise set it to the note
if (!et_title.getText().toString().equals("")) {
noteTitle = et_title.getText().toString();
tickerText = noteTitle;
} else {
noteTitle = getString(R.string.app_name);
tickerText = note;
}
//set the notey object
notey.setId(id);
notey.setNote(note);
notey.setIcon(d);
notey.setImgBtnNum(imageButtonNumber);
notey.setSpinnerLoc(spinnerLocation);
notey.setTitle(noteTitle);
notey.setIconName(getResources().getResourceEntryName(d));
//add alarm to db and set it
String noteForNotification = note; // use a temp string to add the alarm info to the notification
if (alarm_time != null && !alarm_time.equals("")) { //if alarm time is valid, and if we are not in and editIntent
notey.setAlarm(alarm_time); // add to db
// add the alarm date/time to the notification
Date date = new Date(Long.valueOf(alarm_time));
noteForNotification += "\n" + getString(R.string.alarm) + ": " + format_short_date.format(date) + ", " + format_short_time.format(date);
// intent for alarm service to launch
Intent myIntent = new Intent(this, AlarmService.class);
Bundle bundle = new Bundle();
bundle.putInt("alarmID", id);
myIntent.putExtras(bundle);
//set alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmPendingIntent = PendingIntent.getService(this, id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(alarmPendingIntent); // cancel any alarm that might already exist
//set repeating alarm or set regular alarm
if (repeat_time != 0) {
//if alarm_time is old, set alarm_time to currTime+repeat_time to avoid alarm going off directly after user creates note
if (!alarmTimeIsGreaterThanCurrentTime) {
alarm_time = Long.toString((System.currentTimeMillis() + (long) (repeat_time * 1000 * 60)));
}
// check the sharedPrefs for the check box to wake up the device
if (PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getBoolean("wake" + Integer.toString(id), true))
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Long.valueOf(alarm_time), repeat_time * 1000 * 60, alarmPendingIntent);
else
alarmManager.setRepeating(AlarmManager.RTC, Long.valueOf(alarm_time), repeat_time * 1000 * 60, alarmPendingIntent);
} else { //set regualar alarm
// check the sharedPrefs for the check box to wake up the device
if (PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getBoolean("wake" + Integer.toString(id), true))
alarmManager.set(AlarmManager.RTC_WAKEUP, Long.valueOf(alarm_time), alarmPendingIntent);
else
alarmManager.set(AlarmManager.RTC, Long.valueOf(alarm_time), alarmPendingIntent);
}
}
//does notey exist in database? if yes-update. if no-add new notey.
if (db.checkIfExist(id)) db.updateNotey(notey);
else db.addNotey(notey);
//intents for expandable notifications
PendingIntent piDismiss = createOnDismissedIntent(this, id);
PendingIntent piEdit = createEditIntent();
PendingIntent piShare = createShareIntent(note);
// set expandable notification buttons
Bitmap bm;
//big white icons are un-seeable on lollipop, have a null LargeIcon if that's the case
if (CURRENT_ANDROID_VERSION >= 21 && notey.getIconName().contains("white_36dp")) {
bm = null;
} else bm = BitmapFactory.decodeResource(getResources(), d);
//build the notification!
Notification n;
if (pref_expand && pref_share_action && CURRENT_ANDROID_VERSION >= 16) { //jelly bean and above with expandable notifs settings allowed && share action button is enabled
n = new NotificationCompat.Builder(this)
.setContentTitle(noteTitle)
.setContentText(note)
.setTicker(tickerText)
.setSmallIcon(d)
.setLargeIcon(bm)
.setStyle(new NotificationCompat.BigTextStyle().bigText(noteForNotification))
.setDeleteIntent(piDismiss)
.setOngoing(!pref_swipe)
.setContentIntent(onNotifClickPI(clickNotif, note, noteTitle))
.setAutoCancel(false)
.setPriority(priority)
.addAction(R.drawable.ic_edit_white_24dp,
getString(R.string.edit), piEdit) //edit button on notification
.addAction(R.drawable.ic_share_white_24dp,
getString(R.string.share), piShare) // share button
.addAction(R.drawable.ic_delete_white_24dp,
getString(R.string.remove), piDismiss) //remove button
.build();
}
// same as above, but without share action button
else if (pref_expand && !pref_share_action && CURRENT_ANDROID_VERSION >= 16) {
n = new NotificationCompat.Builder(this)
.setContentTitle(noteTitle)
.setContentText(note)
.setTicker(tickerText)
.setSmallIcon(d)
.setLargeIcon(bm)
.setStyle(new NotificationCompat.BigTextStyle().bigText(noteForNotification))
.setDeleteIntent(piDismiss)
.setOngoing(!pref_swipe)
.setContentIntent(onNotifClickPI(clickNotif, note, noteTitle))
.setAutoCancel(false)
.setPriority(priority)
.addAction(R.drawable.ic_edit_white_24dp,
getString(R.string.edit), piEdit) //edit button on notification
.addAction(R.drawable.ic_delete_white_24dp,
getString(R.string.remove), piDismiss) //remove button
.build();
} else if (!pref_expand && CURRENT_ANDROID_VERSION >= 16) { //not expandable, but still able to set priority
n = new NotificationCompat.Builder(this)
.setContentTitle(noteTitle)
.setContentText(note)
.setTicker(tickerText)
.setSmallIcon(d)
.setDeleteIntent(piDismiss)
.setOngoing(!pref_swipe)
.setContentIntent(onNotifClickPI(clickNotif, note, noteTitle))
.setAutoCancel(false)
.setPriority(priority)
.build();
} else { //if api < 16. they cannot have expandable notifs or any type of priority
n = new NotificationCompat.Builder(this)
.setContentTitle(noteTitle)
.setContentText(note)
.setTicker(tickerText)
.setSmallIcon(d)
.setAutoCancel(false)
.setContentIntent(onNotifClickPI(clickNotif, note, noteTitle))
.setDeleteIntent(piDismiss)
.setOngoing(!pref_swipe)
.build();
}
nm.notify(id, n);
db.close();
finish();
}
// alarm time has past, show toast
else if (!alarmTimeIsGreaterThanCurrentTime) {
Toast.makeText(getApplicationContext(), getString(R.string.alarm_not_set), Toast.LENGTH_SHORT).show();
}
}
}
private void setLayout() {
//show keyboard at start
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
et.setText("");
//keep layout where it belongs on screen
layout_bottom = (RelativeLayout) findViewById(R.id.layout_bottom); //row containing the text box
RelativeLayout.LayoutParams parms = (RelativeLayout.LayoutParams) layout_bottom.getLayoutParams();
parms.addRule(RelativeLayout.BELOW, R.id.tableRow1);
final int spinnerHeight = spinner.getLayoutParams().height;
layout_bottom.getLayoutParams().height = spinnerHeight + (int) convertDpToPixel(10, this); //get spinner height + 10dp
et.getLayoutParams().height = spinnerHeight; //set the row's height to that of the spinner's + 10dp
/* resizing the window when more/less text is added */
final RelativeLayout relativeLayoutCopy = layout_bottom;
final EditText editTextCopy = et;
//when text is added or deleted, count the num lines of text there are and adjust the size of the textbox accordingly.
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (et.getText().toString().equals("") && et_title.getText().toString().equals("")) { //if both note and title are blank, set to mic
new ScaleInAnimation(send_btn).setDuration(250).animate();
send_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_mic_grey600_36dp));
}
if (et.getLineCount() > 1) {
et.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
layout_bottom.getLayoutParams().height = et.getLayoutParams().height;
} else {
et.setLayoutParams(editTextCopy.getLayoutParams());
layout_bottom.setLayoutParams(relativeLayoutCopy.getLayoutParams());
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { /*do nothing*/ }
public void onTextChanged(CharSequence s, int start, int before, int count) {
//only animate the mic switching to the send button when the text starts at 0 (no text)
if (before == 0 && start == 0) {
if (!send_btn.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ic_send_grey600_36dp).getConstantState())) { //switch it to the send icon if not already
new ScaleInAnimation(send_btn).setDuration(250).animate();
send_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_send_grey600_36dp));
}
}
}
});
// title text change listener to switch icon
et_title.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (et_title.getText().toString().equals("") && et.getText().toString().equals("")) {
new ScaleInAnimation(send_btn).setDuration(250).animate();
send_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_mic_grey600_36dp));
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { /*do nothing*/ }
public void onTextChanged(CharSequence s, int start, int before, int count) {
//only animate the mic switching to the send button when the text starts at 0 (no text)
if (before == 0 && start == 0) {
if (!send_btn.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ic_send_grey600_36dp).getConstantState())) {
new ScaleInAnimation(send_btn).setDuration(250).animate();
send_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_send_grey600_36dp));
}
}
}
});
}
private void checkForAnyIntents() {
Intent i = this.getIntent();
String action = i.getAction();
String type = i.getType();
noteTitle = getString(R.string.app_name); // setting the note title before the intents, that way if there are no intents it is already set
if (action == null) action = "";
//edit notification intent. set the gui to the notey wanting to be edited
try {
if (i.hasExtra("editNotificationID")) {
MySQLiteHelper db = new MySQLiteHelper(this);
editIntentFlag = true;
int editID = i.getExtras().getInt("editNotificationID");
NoteyNote nTemp = db.getNotey(editID);
int editBtn = i.getExtras().getInt("editButton");
String editAlarm = i.getExtras().getString("editAlarm");
boolean doAlarmActivity = i.getExtras().getBoolean("doEditAlarmActivity", false);
PendingIntent editAlarmPI = (PendingIntent) i.getExtras().get("editAlarmPendingIntent");
id = editID;
et.setText(nTemp.getNote());
et.setSelection(et.getText().length());
spinnerLocation = nTemp.getSpinnerLoc();
imageButtonNumber = nTemp.getImgBtnNum();
noteTitle = nTemp.getTitle();
if (!noteTitle.equals(getString(R.string.app_name))) //if title is not Notey, then display it
et_title.setText(noteTitle);
et_title.setSelection(et_title.getText().length());
alarm_time = editAlarm;
repeat_time = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getInt("repeat" + Integer.toString(id), 0);
alarmPendingIntent = editAlarmPI;
// switch alarm button icon to show an alarm is set
if ((alarm_time != null && !alarm_time.equals("")) || repeat_time != 0) {
new ScaleInAnimation(alarm_btn).setDuration(250).animate();
alarm_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_alarm_on_grey600_36dp));
}
spinner.setSelection(spinnerLocation);
setImageButtonsBasedOffSpinnerSelection();
setWhichImageButtonIsSelected(editBtn);
//resize window for amount of text
et.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
layout_bottom.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
//if the alarm text was pressed on the info screen, doAlarmActivity is set to true. if it is true, then go straight into the alarm activity to edit the alarm
if (doAlarmActivity) {
alarm_btn.performClick();
}
} else if ((Intent.ACTION_SEND.equals(action) || action.equals("com.google.android.gm.action.AUTO_SEND")) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(i); // Handle text being sent
//resize window for amount of text
et.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
et.getLayoutParams().width = RelativeLayout.LayoutParams.WRAP_CONTENT;
layout_bottom.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
}
}
} catch (CursorIndexOutOfBoundsException e) { //catches if the user deletes a note from the notfication tray while the info screen is active. then presses something on the info screen such as the alarm.
e.printStackTrace();
}
}
private void setWhichImageButtonIsSelected(int loc) {
if (loc == 1) {
imageButtonNumber = 1;
ib1.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (loc == 2) {
imageButtonNumber = 2;
ib2.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (loc == 3) {
imageButtonNumber = 3;
ib3.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (loc == 4) {
imageButtonNumber = 4;
ib4.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
} else if (loc == 5) {
imageButtonNumber = 5;
ib5.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib1.setBackgroundColor(Color.TRANSPARENT);
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
}
}
private void checkForAppUpdate() {
int versionCode = -1;
try { //get current version num
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
versionCode = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int userVersion = sharedPref.getInt("VERSION_CODE", -1);
//checks the current version code with the one stored in shared prefs to determine if app has been updated
if (versionCode != userVersion) {
//if on before v2.0.4 and not first install, change the on click notifcation setting to the info screen
if (userVersion <= 14 && userVersion != -1) {
addIconNamesToDB();
sharedPref.edit().putString("clickNotif", "info").apply();
}
//remove proVersionEnabled sharedPref if coming from v2.2
if(userVersion == 41){
sharedPref.edit().remove("proVersionEnabled").apply();
}
//always restore notifications
Intent localIntent = new Intent(this, NotificationBootService.class);
localIntent.putExtra("action", "boot");
startService(localIntent);
}
//update version code in shared prefs
sharedPref.edit().putInt("VERSION_CODE", versionCode).apply();
}
public void initializeGUI() {
setUpSpinner();
//setup the five icons
ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib3 = (ImageButton) findViewById(R.id.imageButton3);
ib4 = (ImageButton) findViewById(R.id.imageButton4);
ib5 = (ImageButton) findViewById(R.id.imageButton5);
send_btn = (ImageButton) findViewById(R.id.btn); //send button
menu_btn = (ImageButton) findViewById(R.id.menuButton);
alarm_btn = (ImageButton) findViewById(R.id.alarm_btn);
nm.cancel(id);
id++;
//set the click listener
ib1.setOnClickListener(this);
ib2.setOnClickListener(this);
ib3.setOnClickListener(this);
ib4.setOnClickListener(this);
ib5.setOnClickListener(this);
send_btn.setOnClickListener(this);
menu_btn.setOnClickListener(this);
alarm_btn.setOnClickListener(this);
ib1.setBackgroundColor(getResources().getColor(R.color.grey_600));
ib2.setBackgroundColor(Color.TRANSPARENT);
ib3.setBackgroundColor(Color.TRANSPARENT);
ib4.setBackgroundColor(Color.TRANSPARENT);
ib5.setBackgroundColor(Color.TRANSPARENT);
impossible_to_delete = false; //set setting for unable to delete notifications to false, will be checked before pressing send
//set textviews and change font
TextView mainTitle = (TextView) findViewById(R.id.mainTitle);
et = (EditText) findViewById(R.id.editText1);
et_title = (EditText) findViewById(R.id.editText_title);
Typeface font = Typeface.createFromAsset(getAssets(), "ROBOTO-LIGHT.TTF");
et.setTypeface(font);
et_title.setTypeface(font);
mainTitle.setTypeface(font);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void initializeSettings() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (CURRENT_ANDROID_VERSION >= 16) {
pref_expand = sharedPreferences.getBoolean("pref_expand", true);
pref_swipe = sharedPreferences.getBoolean("pref_swipe", false);
String pref_priority = sharedPreferences.getString("pref_priority", "normal");
switch (pref_priority) {
case "high":
priority = Notification.PRIORITY_MAX;
break;
case "low":
priority = Notification.PRIORITY_LOW;
break;
case "minimum":
priority = Notification.PRIORITY_MIN;
break;
}
} else { //ics can't have expandable notifs, so set swipe to true as default
pref_expand = false;
pref_swipe = sharedPreferences.getBoolean("pref_swipe", true);
}
clickNotif = sharedPreferences.getString("clickNotif", "info"); //notification click action
pref_share_action = sharedPreferences.getBoolean("pref_share_action", true);
// Create new note shortcut in the notification tray
boolean pref_shortcut = sharedPreferences.getBoolean("pref_shortcut", false);
if (pref_shortcut) {
buildShortcutNotification();
} else {
nm.cancel(SHORTCUT_NOTIF_ID);
}
Set<String> selections = sharedPreferences.getStringSet("pref_icon_picker", null);
//if no icons are selected, automatically select the default five. otherwise, get their selection
if (selections == null || selections.size() == 0) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("pref_icon_picker", new HashSet<>(Arrays.asList(getResources().getStringArray(R.array.default_icons))));
editor.apply();
pref_icons = Arrays.asList(getResources().getStringArray(R.array.default_icons));
} else pref_icons = Arrays.asList(selections.toArray(new String[selections.size()]));
Collections.sort(pref_icons);
//just make check first in the list
if (pref_icons.size() > 1 && pref_icons.get(1).equals("check")) {
Collections.swap(pref_icons, 1, 0);
}
}
private void setUpSpinner() {
setUpIcons();
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(new MyAdapter(this, R.layout.spinner, spinnerPositionList.toArray(new String[spinnerPositionList.size()])));
}
private void setUpIcons() {
imageIconList = new ArrayList<>();
spinnerPositionList = new ArrayList<>();
for (int i = 0; i < pref_icons.size(); i++) {
imageIconList.add(convertStringToIcon(pref_icons.get(i)));
spinnerPositionList.add(Integer.toString(i));
}
}
//turns name like edit into ic_edit_grey600_36dp
private int convertStringToIcon(String s) {
int ic;
if (s.equals("smile")) s = "mood";
if (s.equals("heart")) s = "favorite";
if (s.equals("note")) s = "note_add";
s = "ic_" + s + "_grey600_36dp";
ic = getResources().getIdentifier(s, "drawable", getPackageName());
return ic;
}
private PendingIntent createOnDismissedIntent(Context context, int notificationId) {
//we want to signal the NotificationDismiss receiver for removing notifications
Intent intent = new Intent(context, NotificationDismiss.class);
intent.putExtra("NotificationID", notificationId);
intent.putExtra("alarmPendingIntent", alarmPendingIntent);
return PendingIntent.getBroadcast(context.getApplicationContext(), notificationId, intent, 0);
}
private PendingIntent createEditIntent() {
Intent editIntent = new Intent(this, MainActivity.class);
editIntent.putExtra("editNotificationID", id);
editIntent.putExtra("editButton", imageButtonNumber);
editIntent.putExtra("editAlarm", alarm_time);
editIntent.putExtra("editRepeat", repeat_time);
editIntent.putExtra("editAlarmPendingIntent", alarmPendingIntent);
return PendingIntent.getActivity(getApplicationContext(), id, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent createInfoScreenIntent(String note, String title) {
Intent infoIntent = new Intent(this, InfoScreenActivity.class);
infoIntent.putExtra("infoNotificationID", id);
infoIntent.putExtra("infoNote", note);
infoIntent.putExtra("infoLoc", spinnerLocation);
infoIntent.putExtra("infoButton", imageButtonNumber);
infoIntent.putExtra("infoTitle", title);
infoIntent.putExtra("infoAlarm", alarm_time);
infoIntent.putExtra("infoRepeat", repeat_time);
infoIntent.putExtra("infoAlarmPendingIntent", alarmPendingIntent);
return PendingIntent.getActivity(getApplicationContext(), id, infoIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent createShareIntent(String note) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, note);
sendIntent.setType("text/plain");
return PendingIntent.getActivity(this, id, sendIntent, 0);
}
private PendingIntent onNotifClickPI(String clickNotif, String note, String title) {
switch (clickNotif) {
case "info":
return createInfoScreenIntent(note, title);
case "edit":
return createEditIntent();
case "remove":
return createOnDismissedIntent(this, id);
case "shortcut":
return PendingIntent.getActivity(getApplicationContext(), SHORTCUT_NOTIF_ID, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
default:
return null;
}
}
private void setImageButtonsBasedOffSpinnerSelection() {
String s = pref_icons.get(spinnerLocation);
if (s.equals("smile")) s = "mood";
if (s.equals("heart")) s = "favorite";
if (s.equals("note")) s = "note_add";
ib1.setImageResource(getResources().getIdentifier("ic_" + s + "_white_36dp", "drawable", getPackageName()));
ib2.setImageResource(getResources().getIdentifier("ic_" + s + "_yellow_36dp", "drawable", getPackageName()));
ib3.setImageResource(getResources().getIdentifier("ic_" + s + "_blue_36dp", "drawable", getPackageName()));
ib4.setImageResource(getResources().getIdentifier("ic_" + s + "_green_36dp", "drawable", getPackageName()));
ib5.setImageResource(getResources().getIdentifier("ic_" + s + "_red_36dp", "drawable", getPackageName()));
}
void handleSendText(Intent intent) { //for intents from other apps who want to share text to notey
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update ui to reflect text being shared
et.setText(sharedText);
et.setSelection(et.getText().length());
noteTitle = intent.getStringExtra(Intent.EXTRA_SUBJECT);
}
}
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
return dp * (metrics.densityDpi / 160f);
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speak_now));
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult(" + requestCode + ", " + resultCode + ", " + data + ")");
super.onActivityResult(requestCode, resultCode, data);
// Handles the results from the voice recognition activity.
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
// get the voice input and put it into the text field
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!results.isEmpty()) {
String input = results.get(0);
// put the spoken words into the note textbox or the title textbox
if (noteTextBoxHasFocus) {
et.setText(input);
et.setSelection(et.getText().length());
} else {
et_title.setText(input);
et_title.setSelection(et.getText().length());
}
}
}
// gets the set alarm time (in milliseconds)
if (requestCode == id && resultCode == RESULT_OK) {
alarm_time = data.getExtras().getString("alarm_time", "");
repeat_time = data.getExtras().getInt("repeat_time", 0);
// switch alarm button icon to show an alarm is set. also show toast
if ((alarm_time != null && !alarm_time.equals("")) || repeat_time != 0) {
new ScaleInAnimation(alarm_btn).setDuration(250).animate();
alarm_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_alarm_on_grey600_36dp));
Date date = new Date(Long.valueOf(alarm_time));
Toast.makeText(getApplicationContext(), getString(R.string.alarm_set_for) + " " +
format_short_date.format(date) + ", " + format_short_time.format(date), Toast.LENGTH_LONG).show();
} else {
new ScaleInAnimation(alarm_btn).setDuration(250).animate();
alarm_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_alarm_add_grey600_36dp));
}
}
//IAB stuff
if (mHelper == null) return;
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
setUpMenu();
} else {
Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
private void setUpMenu() {
MenuInflater menuInflater = mPopupMenu.getMenuInflater();
mPopupMenu.getMenu().clear(); //clear the menu so list items aren't duplicated
//if not a pro user, show the updgrade menu option
if (!proVersionEnabled) {
menuInflater.inflate(R.menu.menu, mPopupMenu.getMenu());
} else menuInflater.inflate(R.menu.menu_pro, mPopupMenu.getMenu());
mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
settings_activity_flag = true; //flag so mainActivity UI does get reset after settings is called
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
break;
case R.id.go_pro:
try {
doInAppBillingStuff();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), getString(R.string.play_store_fail), Toast.LENGTH_SHORT).show();
}
MaterialDialog md = new MaterialDialog.Builder(MainActivity.this)
.title(getResources().getString(R.string.go_pro))
.customView(R.layout.webview_dialog_layout, false)
.positiveText(getResources().getString(R.string.tip))
.negativeText(getResources().getString(R.string.pro))
.neutralText(getResources().getString(R.string.no_thanks))
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
Log.i(TAG, "Upgrade button clicked; launching purchase flow for PRO + TIP upgrade.");
try {
mHelper.launchPurchaseFlow(MainActivity.this, SKU_TIP_VERSION, 10001, mPurchaseFinishedListener, payload);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), getString(R.string.play_store_fail), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
Log.i(TAG, "Upgrade button clicked; launching purchase flow for PRO upgrade.");
try {
mHelper.launchPurchaseFlow(MainActivity.this, SKU_PRO_VERSION, 10001, mPurchaseFinishedListener, payload);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), getString(R.string.play_store_fail), Toast.LENGTH_SHORT).show();
}
}
})
.build();
WebView webView = (WebView) md.getCustomView().findViewById(R.id.pro_features_webview);
webView.loadUrl("file:///android_asset/ProFeatures.html");
md.show();
break;
case R.id.about:
about_activity_flag = true;
Intent i = new Intent(MainActivity.this, About.class);
startActivity(i);
break;
default:
return true;
}
return true;
}
});
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void buildShortcutNotification() {
Notification n = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.quick_note))
.setSmallIcon(R.drawable.ic_launcher_dashclock)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_new_note))
.setOngoing(true)
.setContentIntent(onNotifClickPI("shortcut", "", ""))
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_MIN)
.build();
nm.notify(SHORTCUT_NOTIF_ID, n);
}
/* changes were made from v2.0.3 to v2.0.4. this fudged up the icon numbers. a new column in the
* database was created called 'iconName' to prevent this issue from happening again.
* This converts to old icon's ints to the new ints and writes their proper name to the database.
*/
private void addIconNamesToDB() {
List<NoteyNote> allNoteys = null;
try {
allNoteys = db.getAllNoteys();
} catch (RuntimeException e) {
e.printStackTrace();
}
int newIconInt;
String newIconName;
if (allNoteys != null) {
for (NoteyNote n : allNoteys) {
if (n.getIcon() >= 2130837510 && n.getIcon() <= 2130837512) {
newIconInt = n.getIcon() - 6;
newIconName = getResources().getResourceEntryName(newIconInt);
n.setIconName(newIconName);
} else if (n.getIcon() >= 2130837513 && n.getIcon() <= 2130837519) {
newIconInt = n.getIcon() - 5;
newIconName = getResources().getResourceEntryName(newIconInt);
n.setIconName(newIconName);
} else if (n.getIcon() >= 2130837520 && n.getIcon() <= 2130837522) {
newIconInt = n.getIcon() - 3;
newIconName = getResources().getResourceEntryName(newIconInt);
n.setIconName(newIconName);
} else if (n.getIcon() >= 2130837523 && n.getIcon() <= 2130837528) {
newIconInt = n.getIcon() - 2;
newIconName = getResources().getResourceEntryName(newIconInt);
n.setIconName(newIconName);
} else if (n.getIcon() >= 2130837530 && n.getIcon() <= 2130837547) {
newIconInt = n.getIcon() + 2;
newIconName = getResources().getResourceEntryName(newIconInt);
n.setIconName(newIconName);
} else
n.setIconName(getResources().getResourceEntryName(R.drawable.ic_check_white_36dp)); //else default to white check
db.updateNotey(n);
}
}
}
private void doInAppBillingStuff() {
// get public key which was generated from my Dev Play Account. This is split up for security reasons.
String row3 = "kjbLj5687y153Ra3s64Mq+2ZZnWqEjY8PhDwEN2WNKhntBfBaRcGVD2FNpkcMeZdkv524e9O0VqJJCCLhyg9kil3Nx+h+pnbvtID5lwRIAbyPYbOn2xLXt";
String row1 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApuEWdJzuPhdnu28kyd+8/GwNCjTXfMXfBST5+LgFYaljmb0ah7Op8gULgOeLGo1OeK4oLfKAWw";
String row4 = "LLB*AqB/w*8uNGl$F6$jI5*fYWl8eO2aF3*zKQI**DAQAB";
String row2 = "sfeDLPklID/xCkAsWVPAGfdiTsyIU83zxRMJc2jYUxcIbzUotWslQxaKVSaH35pcN+PqrG3eMOShTCHN9VxqMkn3Zr+g8HkiXOKMVduCgDFrWEtv8Xiqk1";
row4 = row4.replace("*", "");
String base64EncodedPublicKey = row1 + row2 + row3 + row4.replace("$", "");
Log.d(TAG, "Creating IAB helper.");
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(true);
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
return;
}
if (mHelper == null) {
return;
}
Log.d(TAG, "Setup successful. Querying inventory.");
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mQueryFinishedListener);
}
});
}
// Listener that's called when we finish querying the items and subscriptions we own
IabHelper.QueryInventoryFinishedListener mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
Log.d(TAG, "Query inventory finished.");
if (mHelper == null || result.isFailure()) {
return;
}
Log.d(TAG, "Query inventory was successful.");
Purchase proVersion = inv.getPurchase(SKU_PRO_VERSION);
Purchase tipVersion = inv.getPurchase(SKU_TIP_VERSION);
if ((proVersion != null && verifyDeveloperPayload(proVersion)) || (tipVersion != null && verifyDeveloperPayload(tipVersion))) {
proVersionEnabled = true;
setUpProGUI();
setUpMenu();
setUpSpinner();
}
Log.d(TAG, "User is " + (proVersionEnabled ? "PREMIUM" : "NOT PREMIUM"));
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
// Callback for when a purchase is finished
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: " + info);
if (mHelper == null) return;
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
} else mHelper.queryInventoryAsync(mQueryFinishedListener);
if (!verifyDeveloperPayload(info)) {
Log.d(TAG, "Error purchasing. Authenticity verification failed.");
return;
}
Log.d(TAG, "Purchase successful.");
if (info.getSku().equals(SKU_PRO_VERSION)) {
Log.d(TAG, "Purchasing premium upgrade. Congratulating user.");
Toast.makeText(getApplicationContext(), getString(R.string.thank_you_for_pro), Toast.LENGTH_SHORT).show();
proVersionEnabled = true;
setUpProGUI();
setUpSpinner();
} else if (info.getSku().equals(SKU_TIP_VERSION)) {
Log.d(TAG, "Purchasing premium upgrade. Congratulating user.");
Toast.makeText(getApplicationContext(), getString(R.string.thank_you_for_contribution), Toast.LENGTH_SHORT).show();
proVersionEnabled = true;
setUpProGUI();
setUpSpinner();
}
}
};
public static void setUpProGUI() {
//make all the icons enabled initially
pref_icons = Arrays.asList(appContext.getResources().getStringArray(R.array.icon_picker_values));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(appContext).edit();
editor.putStringSet("pref_icon_picker", new HashSet<>(Arrays.asList(appContext.getResources().getStringArray(R.array.icon_picker_values))));
editor.apply();
//when upgrading to pro, adding more icons to the spinner alters the spinner location's number. this is to fix that
MySQLiteHelper db = new MySQLiteHelper(appContext);
List<NoteyNote> allNoteys = db.getAllNoteys();
for (NoteyNote n : allNoteys) {
if (n.getSpinnerLoc() == 1) { //change edit icon. no changing check, that stays first
n.setSpinnerLoc(2);
db.updateNotey(n);
} else if (n.getSpinnerLoc() == 2) { //change warning sign
n.setSpinnerLoc(7);
db.updateNotey(n);
} else if (n.getSpinnerLoc() == 3) { //change star
n.setSpinnerLoc(8);
db.updateNotey(n);
} else if (n.getSpinnerLoc() == 4) { //change flame
n.setSpinnerLoc(9);
db.updateNotey(n);
}
}
}
boolean verifyDeveloperPayload(Purchase p) {
payload = p.getDeveloperPayload();
return true;
}
@Override
protected void onResume() {
super.onResume();
// if settings activity was called, reset the ui
if (settings_activity_flag) {
initializeSettings();
if (spinnerChanged) { //if the spinner was altered then refresh it
setUpSpinner();
spinnerChanged = false;
}
settings_activity_flag = false;
}
if (about_activity_flag) { // if about activity was called, check to see if the user had typed in the secret code and are now Pro. if yes, set up everything like a normal pro purchase.
initializeSettings();
if (justTurnedPro) {
setUpMenu();
setUpSpinner();
justTurnedPro = false;
}
about_activity_flag = false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
//unbind from the In-app Billing service when done with the activity
Log.d(TAG, "Destroying helper.");
if (mHelper != null) mHelper.dispose();
mHelper = null;
if (mService != null) {
unbindService(mServiceConn);
}
}
} |
package com.catalyst.sonar.score.log;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
/**
* The Logger class is used for printing useful information in the console of a
* CI engine (like Hudson/Jenkins), and for general debugging.
*
* @author JDunn
*
*/
public class Logger {
public static final char BORDER1 = '*';
public static final char BORDER2 = '>';
public static final char BORDER3 = ':';
public static final char BORDER4 = '-';
public static final char[] BORDER = { BORDER1, BORDER2, BORDER3, BORDER4 };
public static final char TAB = '\t';
public static final int BORDER_LENGTH = 70;
public static final int TAB_LENGTH = 4;
public static final String START = "Start ";
public static final String END = "End ";
public static final Logger LOG = new Logger();
private PrintStream stream;
private List<String> stack;
/**
* The no-args constructor sets the stream to {@code System.out} and
* instantiates the {@code List<String> stack} as an {@link ArrayList}.
* {@code String}.
*/
public Logger() {
this.setStream(System.out);
this.stack = new ArrayList<String>();
}
/**
* Prints a tab for every method name in the stack List, and then prints the
* object.
*
* @param x
* @return this
*/
public Logger log(Object x) {
stream.println(tab() + x);
return this;
}
/**
* Prints the same as {@link Logger.log(Object x)} but adding an emphasis
* String.
*
* @param x
* @return
*/
public Logger logEmf(Object x) {
stream.println(tab() + "!!! " + x);
return log(x);
}
/**
* Prints the methodName with a border, and then adds the methodName to the
* stack.
*
* @param methodName
* @return
*/
public Logger beginMethod(final String methodName) {
String message = border(TAB_LENGTH) + START + methodName;
borderMessage(message);
stack.add(methodName);
return this;
}
/**
* Removes the last methodName from the stack and prints it with a border.
*
* @return
*/
public Logger endMethod() {
final String methodName = stack.remove(stack.size() - 1);
String message = border(TAB_LENGTH) + END + methodName;
return borderMessage(message);
}
private Logger borderMessage(String message) {
stream.println(tab()
+ message
+ border(BORDER_LENGTH - (TAB_LENGTH * stack.size())
- message.length()));
return this;
}
/**
* Returns a String to be used as a border.
*
* @param x
* @return
*/
private String border(final int x) {
StringBuilder border = new StringBuilder();
for (int y = 0; y < x; y++) {
border.append(BORDER[stack.size()]);
}
return border.toString();
}
/**
* Returns a String consisting of the appropriate number of tabs based on
* the size of the stack List.
*
* @return
*/
private String tab() {
String tabs = "";
for (int i = 0; i < stack.size(); i++) {
tabs += '\t';
}
return tabs;
}
/**
* @return the stream
*/
public PrintStream getStream() {
return stream;
}
/**
* @param stream
* the stream to set
* @param stream
* @return this
*/
public Logger setStream(PrintStream stream) {
this.stream = stream;
return this;
}
} |
package org.csstudio.alarm.beast.annunciator.ui;
import org.csstudio.alarm.beast.annunciator.model.AnnunciationMessage;
import org.csstudio.apputil.ringbuffer.RingBuffer;
import org.eclipse.jface.viewers.ILazyContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
/** (Lazy) Table content provider for input of type
* <code>RingBuffer<AnnunciationMessage></code>
* @author Kay Kasemir
*/
public class MessageRingBufferContentProvider implements ILazyContentProvider
{
private TableViewer viewer;
/** List of recent Messages.
* Synchronize on access.
*/
private RingBuffer<AnnunciationMessage> messages;
@SuppressWarnings("unchecked")
public void inputChanged(final Viewer viewer, final Object old, final Object input)
{
this.viewer = (TableViewer) viewer;
messages = (RingBuffer<AnnunciationMessage>) input;
if (viewer == null)
return;
if (messages == null)
this.viewer.setItemCount(0);
else
{
final int N;
synchronized (messages)
{
N = messages.size();
}
this.viewer.setItemCount(N);
}
}
public void updateElement(final int index)
{
// Show elements in reverse order; index 0 is last message
final AnnunciationMessage message;
synchronized (messages)
{
final int N = messages.size();
// Ignore update in case message count changed
if (index >= N)
return;
message = messages.get(N-1-index);
}
viewer.replace(message, index);
}
public void dispose()
{
// NOP
}
} |
package com.neverwinterdp.vm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import com.beust.jcommander.DynamicParameter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import com.neverwinterdp.registry.RegistryConfig;
import com.neverwinterdp.util.text.StringUtil;
public class VMConfig {
public enum ClusterEnvironment {
YARN, YARN_MINICLUSTER, JVM;
public static ClusterEnvironment fromString(String code) {
for(ClusterEnvironment output : ClusterEnvironment.values()) {
if(output.toString().equalsIgnoreCase(code)) return output;
}
return null;
}
}
@Parameter(names = "--description", description = "Description")
private String description;
@Parameter(names = "--name", description = "The registry partition or table")
private String name;
@Parameter(names = "--role", description = "The VM roles")
private List<String> roles = new ArrayList<String>();
@Parameter(names = "--cpu-cores", description = "The request number of cpu cores")
private int requestCpuCores = 1;
@Parameter(names = "--memory", description = "The request amount of memory in MB")
private int requestMemory = 256;
@Parameter(names = "--app-home", description = "App Home")
private String appHome;
@Parameter(names = "--app-data-dir", description = "App Data Dir")
private String appDataDir = "build/vm";
@Parameter(names = "--log4j-config-url", description = "Log4j Config Url")
private String log4jConfigUrl = "classpath:vm-log4j.properties";
@DynamicParameter(names = "--vm-resource:", description = "The resources for the vm")
private Map<String, String> vmResources = new LinkedHashMap<String, String>();
@ParametersDelegate
private RegistryConfig registryConfig = new RegistryConfig();
@Parameter(
names = "--self-registration",
description = "Self create the registation entry in the registry, for master node")
private boolean selfRegistration = false;
@Parameter(names = "--vm-application", description = "The vm application class")
private String vmApplication;
@DynamicParameter(names = "--prop:", description = "The application configuration properties")
private Map<String, String> properties = new HashMap<String, String>();
@DynamicParameter(names = "--hadoop:", description = "The application configuration properties")
private HadoopProperties hadoopProperties = new HadoopProperties();
@Parameter(names = "--environment", description = "Environement YARN, YARN_MINICLUSTER, JVM")
private ClusterEnvironment clusterEnvironment = ClusterEnvironment.JVM;
public VMConfig() {}
public VMConfig(String[] args) {
new JCommander(this, args);
}
public String getName() { return name; }
public VMConfig setName(String name) {
this.name = name;
return this;
}
public List<String> getRoles() { return roles; }
public VMConfig setRoles(List<String> roles) {
this.roles = roles;
return this;
}
public VMConfig addRoles(String ... role) {
if(roles == null) roles = StringUtil.toList(role);
else StringUtil.addList(roles, role);
return this;
}
public int getRequestCpuCores() { return requestCpuCores; }
public VMConfig setRequestCpuCores(int requestCpuCores) {
this.requestCpuCores = requestCpuCores;
return this;
}
public int getRequestMemory() { return requestMemory; }
public VMConfig setRequestMemory(int requestMemory) {
this.requestMemory = requestMemory;
return this;
}
public String getAppHome() { return appHome; }
public void setAppHome(String appHome) { this.appHome = appHome; }
public String getAppDataDir() { return appDataDir; }
public void setAppDataDir(String appDataDir) { this.appDataDir = appDataDir; }
public String getLog4jConfigUrl() { return log4jConfigUrl; }
public void setLog4jConfigUrl(String url) {
if(url == null || url.length() == 0) return;
log4jConfigUrl = url;
}
public Map<String, String> getVmResources() { return vmResources; }
public void setVmResources(Map<String, String> vmResources) { this.vmResources = vmResources; }
public void addVMResource(String name, String resource) {
vmResources.put(name, resource);
}
public RegistryConfig getRegistryConfig() { return registryConfig;}
public VMConfig setRegistryConfig(RegistryConfig registryConfig) {
this.registryConfig = registryConfig;
return this;
}
public boolean isSelfRegistration() { return selfRegistration; }
public VMConfig setSelfRegistration(boolean selfRegistration) {
this.selfRegistration = selfRegistration;
return this;
}
public String getVmApplication() { return vmApplication;}
public VMConfig setVmApplication(String vmApplication) {
this.vmApplication = vmApplication;
return this;
}
public Map<String, String> getProperties() { return properties;}
public VMConfig setProperties(Map<String, String> appProperties) {
this.properties = appProperties;
return this;
}
public VMConfig addProperty(String name, String value) {
properties.put(name, value);
return this;
}
public String getProperty(String name) { return properties.get(name); }
public String getProperty(String name, String defaultValue) {
String value = properties.get(name);
if(value == null) return defaultValue;
return value ;
}
public int getPropertyAsInt(String name, int defaultVal) {
String val = properties.get(name);
return val == null ? defaultVal : Integer.parseInt(val);
}
public VMConfig addProperty(String name, int value) {
return addProperty(name, Integer.toString(value));
}
public long getPropertyAsLong(String name, long defaultVal) {
String val = properties.get(name);
return val == null ? defaultVal : Long.parseLong(val);
}
public VMConfig addProperty(String name, long value) {
return addProperty(name, Long.toString(value));
}
public boolean getPropertyAsBoolean(String name, boolean defaultVal) {
String val = properties.get(name);
return val == null ? defaultVal : Boolean.parseBoolean(val);
}
public VMConfig addProperty(String name, boolean value) {
return addProperty(name, Boolean.toString(value));
}
public HadoopProperties getHadoopProperties() { return hadoopProperties; }
public VMConfig setHadoopProperties(HadoopProperties hadoopProperties) {
this.hadoopProperties = hadoopProperties;
return this;
}
public VMConfig addHadoopProperty(String name, String value) {
hadoopProperties.put(name, value);
return this;
}
public VMConfig addHadoopProperty(Map<String, String> conf) {
Iterator<Map.Entry<String, String>> i = conf.entrySet().iterator();
while(i.hasNext()) {
Map.Entry<String, String> entry = i.next();
String key = entry.getKey();
String value = conf.get(key);
if(value.length() == 0) continue;
else if(value.indexOf(' ') > 0) continue;
hadoopProperties.put(key, value);
}
return this;
}
public void overrideHadoopConfiguration(Configuration aconf) {
hadoopProperties.overrideConfiguration(aconf);
}
public String getDescription() { return description; }
public VMConfig setDescription(String description) {
this.description = description;
return this;
}
public ClusterEnvironment getClusterEnvironment() { return this.clusterEnvironment; }
public VMConfig setClusterEnvironment(ClusterEnvironment env) {
this.clusterEnvironment = env;
return this;
}
public String buildCommand() {
StringBuilder b = new StringBuilder() ;
b.append("java ").append(" -Xmx" + requestMemory + "m ").append(VM.class.getName()) ;
addParameters(b);
System.out.println("Command: " + b.toString());
return b.toString() ;
}
private void addParameters(StringBuilder b) {
if(name != null) {
b.append(" --name ").append(name) ;
}
if(roles != null && roles.size() > 0) {
b.append(" --role ");
for(String role : roles) {
b.append(role).append(" ");
}
}
b.append(" --cpu-cores ").append(requestCpuCores) ;
b.append(" --memory ").append(requestMemory) ;
if(appHome != null) {
b.append(" --app-home ").append(appHome) ;
}
for(Map.Entry<String, String> entry : vmResources.entrySet()) {
b.append(" --vm-resource:").append(entry.getKey()).append("=").append(entry.getValue()) ;
}
b.append(" --vm-application ").append(vmApplication);
if(selfRegistration) {
b.append(" --self-registration ") ;
}
b.append(" --registry-connect ").append(registryConfig.getConnect()) ;
b.append(" --registry-db-domain ").append(registryConfig.getDbDomain()) ;
b.append(" --registry-implementation ").append(registryConfig.getRegistryImplementation()) ;
b.append(" --environment ").append(clusterEnvironment) ;
b.append(" --log4j-config-url ").append(log4jConfigUrl) ;
for(Map.Entry<String, String> entry : properties.entrySet()) {
b.append(" --prop:").append(entry.getKey()).append("=").append(entry.getValue()) ;
}
for(Map.Entry<String, String> entry : hadoopProperties.entrySet()) {
b.append(" --hadoop:").append(entry.getKey()).append("=").append(entry.getValue()) ;
}
}
static public void overrideHadoopConfiguration(Map<String, String> props, Configuration aconf) {
HadoopProperties hprops = new HadoopProperties() ;
hprops.putAll(props);
hprops.overrideConfiguration(aconf);
}
} |
package com.celements.navigation;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.SpaceReference;
import com.celements.navigation.cmd.MultilingualMenuNameCommand;
import com.celements.navigation.filter.INavFilter;
import com.celements.navigation.filter.InternalRightsFilter;
import com.celements.navigation.presentation.IPresentationTypeRole;
import com.celements.navigation.service.ITreeNodeService;
import com.celements.pagetype.PageTypeReference;
import com.celements.pagetype.service.IPageTypeResolverRole;
import com.celements.pagetype.service.PageTypeResolverService;
import com.celements.web.plugin.cmd.PageLayoutCommand;
import com.celements.web.service.IWebUtilsService;
import com.celements.web.utils.IWebUtils;
import com.celements.web.utils.WebUtils;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiMessageTool;
public class Navigation implements INavigation {
public static final int DEFAULT_MAX_LEVEL = 100;
/**
* @deprecated since 2.18.0 instead use NavigationClasses.NAVIGATION_CONFIG_CLASS_DOC
*/
@Deprecated
public static final String NAVIGATION_CONFIG_CLASS_DOC = NavigationClasses.NAVIGATION_CONFIG_CLASS_DOC;
/**
* @deprecated since 2.18.0 instead use NavigationClasses.NAVIGATION_CONFIG_CLASS_SPACE
*/
@Deprecated
public static final String NAVIGATION_CONFIG_CLASS_SPACE = NavigationClasses.NAVIGATION_CONFIG_CLASS_SPACE;
/**
* @deprecated since 2.18.0 instead use NavigationClasses.NAVIGATION_CONFIG_CLASS
*/
@Deprecated
public static final String NAVIGATION_CONFIG_CLASS = NavigationClasses.NAVIGATION_CONFIG_CLASS;
private INavigationBuilder navBuilder;
public static final String LIST_LAYOUT_TYPE = "list";
private static final String _PAGE_MENU_DATA_TYPE = "pageMenu";
public static final String MENU_TYPE_MENUITEM = "menuitem";
private final static Logger LOGGER = LoggerFactory.getLogger(Navigation.class);
private static final String _NAVIGATION_COUNTER_KEY = NavigationApi.class.getCanonicalName()
+ "_NavigationCounter";
private static final String _LANGUAGE_MENU_DATA_TYPE = "languages";
public PageLayoutCommand pageLayoutCmd = new PageLayoutCommand();
String uniqueName;
IWebUtils utils;
private boolean navigationEnabled;
String configName;
int fromHierarchyLevel;
int toHierarchyLevel;
String menuPart;
SpaceReference nodeSpaceRef;
private int showInactiveToLevel;
private int offset = 0;
private int nrOfItemsPerPage = -1;
private String cmCssClass;
private String mainUlCssClasses;
private String emptyDictKeySuffix;
private String dataType;
private String navInclude = null;
private IPresentationTypeRole presentationType = null;
private boolean _showAll;
private boolean _hasLink;
private INavFilter<BaseObject> navFilter;
private MultilingualMenuNameCommand menuNameCmd;
private String navLanguage;
public ITreeNodeService injected_TreeNodeService;
public IWebUtilsService injected_WebUtilsService;
public PageTypeResolverService injected_PageTypeResolverService;
public Navigation(String navUniqueId) {
this.menuNameCmd = new MultilingualMenuNameCommand();
this.uniqueName = navUniqueId;
this.navigationEnabled = true;
this.fromHierarchyLevel = 1;
this.toHierarchyLevel = DEFAULT_MAX_LEVEL;
this.menuPart = "";
this.dataType = _PAGE_MENU_DATA_TYPE;
this._showAll = false;
this._hasLink = true;
try {
setLayoutType(LIST_LAYOUT_TYPE);
} catch (UnknownLayoutTypeException exp) {
LOGGER.error("Native List Layout Type not available!", exp);
throw new IllegalStateException("Native List Layout Type not available!", exp);
}
this.nodeSpaceRef = null;
this.mainUlCssClasses = "";
this.cmCssClass = "";
utils = WebUtils.getInstance();
}
/**
* @deprecated since 2.18.0 instead use getNavigationConfigClassRef of NavigationClasses
*/
@Deprecated
public static DocumentReference getNavigationConfigClassReference(String wikiName) {
return new DocumentReference(wikiName, NAVIGATION_CONFIG_CLASS_SPACE,
NAVIGATION_CONFIG_CLASS_DOC);
}
public String getLayoutType() {
return navBuilder.getLayoutTypeName();
}
public void setLayoutType(String layoutType) throws UnknownLayoutTypeException {
// TODO implement a component role
if (LIST_LAYOUT_TYPE.equals(layoutType)) {
this.navBuilder = new ListBuilder(uniqueName);
} else {
throw new UnknownLayoutTypeException(layoutType);
}
}
public IPresentationTypeRole getPresentationType() {
if (presentationType == null) {
return Utils.getComponent(IPresentationTypeRole.class);
} else {
return presentationType;
}
}
public void setPresentationType(IPresentationTypeRole presentationType) {
this.presentationType = presentationType;
}
@Override
public void setPresentationType(String presentationTypeHint) {
if (presentationTypeHint != null) {
try {
LOGGER.info("setPresentationType to [" + presentationTypeHint + "].");
setPresentationType(Utils.getComponent(IWebUtilsService.class).lookup(
IPresentationTypeRole.class, presentationTypeHint));
} catch (ComponentLookupException failedToLoadException) {
LOGGER.error("setPresentationType failed to load IPresentationTypeRole for hint ["
+ presentationTypeHint + "].", failedToLoadException);
this.presentationType = null;
}
} else {
this.presentationType = null;
}
}
/**
* setFromHierarchyLevel
*
* @param fromHierarchyLevel
* starting (including) at Hierarchy Level 1 = mainMenu , 0 = spaceMenu
* (including all first mainMenuItems of all Spaces)
*/
@Override
public void setFromHierarchyLevel(int fromHierarchyLevel) {
if (fromHierarchyLevel > 0) {
this.fromHierarchyLevel = fromHierarchyLevel;
}
}
/**
* setToHierarchyLevel
*
* @param toHierarchyLevel
* ending (including) with Hierarchy Level
*/
@Override
public void setToHierarchyLevel(int toHierarchyLevel) {
this.toHierarchyLevel = toHierarchyLevel;
}
@Override
public void setMenuPart(String menuPart) {
this.menuPart = menuPart;
}
/**
* @param menuSpace
* (default: $doc.web)
* @deprecated since 2.24.0 instead use setNodeSpace
*/
@Override
@Deprecated
public void setMenuSpace(String menuSpace) {
if ((menuSpace != null) && (!"".equals(menuSpace))) {
setNodeSpace(getWebUtilsService().resolveSpaceReference(menuSpace));
} else {
setNodeSpace(null);
}
}
@Override
public void setNodeSpace(SpaceReference newNodeSpaceRef) {
this.nodeSpaceRef = newNodeSpaceRef;
}
/**
* @deprecated since 2.24.0 use includeNavigation() instead.
*/
@Override
@Deprecated
public String includeNavigation(XWikiContext context) {
return includeNavigation();
}
@Override
public String includeNavigation() {
if (fromHierarchyLevel > 0) {
DocumentReference parentRef = getWebUtilsService().getParentForLevel(fromHierarchyLevel);
if ((fromHierarchyLevel == 1) || (parentRef != null)) {
return includeNavigation(parentRef);
}
return "";
} else {
throw new IllegalArgumentException("fromHierarchyLevel [" + fromHierarchyLevel
+ "] must be greater than zero");
}
}
@Override
public String includeNavigation(DocumentReference parentRef) {
LOGGER.debug("includeNavigation: navigationEnabled [" + navigationEnabled + "].");
if (navInclude == null) {
if (navigationEnabled) {
StringBuilder outStream = new StringBuilder();
if (_PAGE_MENU_DATA_TYPE.equals(dataType)) {
try {
addNavigationForParent(outStream, parentRef, getNumLevels());
} catch (XWikiException e) {
LOGGER.error("addNavigationForParent failed for [" + parentRef + "].", e);
}
} else if (_LANGUAGE_MENU_DATA_TYPE.equals(dataType)) {
navBuilder.useStream(outStream);
generateLanguageMenu(navBuilder, getContext());
}
navInclude = outStream.toString();
} else {
navInclude = "";
}
}
return navInclude;
}
/**
* @deprecated since 2.24.0 instead use getNodeSpaceRef()
*/
@Override
@Deprecated
public String getMenuSpace(XWikiContext context) {
return getWebUtilsService().getRefLocalSerializer().serialize(getNodeSpaceRef());
}
@Override
public SpaceReference getNodeSpaceRef() {
if (nodeSpaceRef == null) {
SpaceReference currentSpaceRef = getContext().getDoc().getDocumentReference().getLastSpaceReference();
if (fromHierarchyLevel == 1) {
if (isEmptyMainMenu(currentSpaceRef) && getWebUtilsService().hasParentSpace(
currentSpaceRef.getName())) {
// is main Menu and no mainMenuItem found ; user has edit rights
nodeSpaceRef = getWebUtilsService().resolveSpaceReference(
getWebUtilsService().getParentSpace(currentSpaceRef.getName()));
}
}
if (nodeSpaceRef == null) {
nodeSpaceRef = currentSpaceRef;
}
}
SpaceReference theNodeSpaceRef = nodeSpaceRef;
return theNodeSpaceRef;
}
@Override
public boolean isEmptyMainMenu() {
return isEmptyMainMenu(getNodeSpaceRef());
}
public boolean isEmptyMainMenu(SpaceReference spaceRef) {
getNavFilter().setMenuPart(getMenuPartForLevel(1));
return getTreeNodeService().getSubNodesForParent(spaceRef, getNavFilter()).size() == 0;
}
@Override
public boolean isEmpty() {
getNavFilter().setMenuPart(getMenuPartForLevel(fromHierarchyLevel));
EntityReference parentRef = getWebUtilsService().getParentForLevel(fromHierarchyLevel);
LOGGER.debug("isEmpty: parentRef [" + parentRef + "] for level [" + fromHierarchyLevel + "]");
if (parentRef == null) {
LOGGER.info("isEmpty: no subnode for level [" + fromHierarchyLevel + "] found.");
return true;
}
List<TreeNode> subNodeList = getTreeNodeService().getSubNodesForParent(parentRef,
getNavFilter());
LOGGER.info("isEmpty: subNodeList size [" + subNodeList.size() + "] for parentRef [" + parentRef
+ "] -> [" + subNodeList.isEmpty() + "].");
return subNodeList.isEmpty();
}
INavFilter<BaseObject> getNavFilter() {
if (navFilter == null) {
navFilter = new InternalRightsFilter();
}
return navFilter;
}
@Override
public void setNavFilter(INavFilter<BaseObject> navFilter) {
this.navFilter = navFilter;
}
private int getNumLevels() {
return (toHierarchyLevel - fromHierarchyLevel) + 1;
}
void addNavigationForParent(StringBuilder outStream, EntityReference parentRef, int numMoreLevels)
throws XWikiException {
LOGGER.debug("addNavigationForParent: parent [" + parentRef + "] numMoreLevels ["
+ numMoreLevels + "].");
if (numMoreLevels > 0) {
String parent = "";
if (parentRef != null) {
parent = getWebUtilsService().getRefLocalSerializer().serialize(parentRef);
}
List<TreeNode> currentMenuItems = getCurrentMenuItems(numMoreLevels, parent);
if (currentMenuItems.size() > 0) {
outStream.append("<ul " + addUniqueContainerId(parent) + " " + getMainUlCSSClasses() + ">");
boolean isFirstItem = true;
int numItem = 0;
if (this.getOffset() > 0) {
numItem = this.getOffset();
}
for (TreeNode treeNode : currentMenuItems) {
numItem = numItem + 1;
DocumentReference nodeRef = treeNode.getDocumentReference();
boolean isLastItem = (currentMenuItems.lastIndexOf(treeNode) == (currentMenuItems.size()
- 1));
writeMenuItemWithSubmenu(outStream, parent, numMoreLevels, nodeRef, isFirstItem,
isLastItem, numItem);
isFirstItem = false;
}
outStream.append("</ul>");
} else if ((getCurrentLevel(numMoreLevels) == 1) && hasedit()) {
LOGGER.trace("addNavigationForParent: empty navigation hint for parent [" + parentRef
+ "] numMoreLevels [" + numMoreLevels + "], currentLevel [" + getCurrentLevel(
numMoreLevels) + "].");
// is main Menu and no mainMenuItem found ; user has edit rights
outStream.append("<ul class=\"cel_nav_empty\">");
openMenuItemOut(outStream, null, true, true, false, 1);
outStream.append("<span " + addUniqueElementId(null) + " " + addCssClasses(null, true, true,
true, false, 1) + ">" + getWebUtilsService().getAdminMessageTool().get(
getEmptyDictKey()) + "</span>");
closeMenuItemOut(outStream);
outStream.append("</ul>");
} else {
LOGGER.debug("addNavigationForParent: empty output for parent [" + parentRef
+ "] numMoreLevels [" + numMoreLevels + "], currentLevel [" + getCurrentLevel(
numMoreLevels) + "], hasEdit [" + hasedit() + "].");
}
}
}
List<TreeNode> getCurrentMenuItems(int numMoreLevels, String parent) {
getNavFilter().setMenuPart(getMenuPartForLevel(getCurrentLevel(numMoreLevels)));
List<TreeNode> currentMenuItems = getTreeNodeService().getSubNodesForParent(parent,
getMenuSpace(getContext()), getNavFilter());
int endIdx = currentMenuItems.size();
if (((offset > 0) || (nrOfItemsPerPage > 0)) && (offset < endIdx)) {
if (nrOfItemsPerPage > 0) {
endIdx = Math.min(endIdx, offset + nrOfItemsPerPage);
}
currentMenuItems = currentMenuItems.subList(offset, endIdx);
} else if (offset >= endIdx) {
currentMenuItems = Collections.emptyList();
}
return currentMenuItems;
}
@Override
public String getEmptyDictKey() {
return getPresentationType().getEmptyDictionaryKey() + getEmptyDictKeySuffix();
}
@Override
public void setEmptyDictKeySuffix(String emptyDictKeySuffix) {
this.emptyDictKeySuffix = emptyDictKeySuffix;
}
private String getEmptyDictKeySuffix() {
if (emptyDictKeySuffix != null) {
return emptyDictKeySuffix;
}
return "";
}
private int getCurrentLevel(int numMoreLevels) {
return (getNumLevels() - numMoreLevels) + 1;
}
/**
* menuPart is only valid for the first level of a menu block.
*
* @param currentLevel
* @return
*/
String getMenuPartForLevel(int currentLevel) {
if (currentLevel == 1) {
return menuPart;
} else {
return "";
}
}
String getMainUlCSSClasses() {
if (!"".equals(mainUlCssClasses.trim())) {
return " class=\"" + mainUlCssClasses.trim() + "\" ";
} else {
return "";
}
}
@Override
public void addUlCSSClass(String cssClass) {
if (!(" " + mainUlCssClasses + " ").contains(" " + cssClass + " ")) {
mainUlCssClasses = mainUlCssClasses.trim() + " " + cssClass;
}
}
private boolean hasedit() throws XWikiException {
return getContext().getWiki().getRightService().hasAccessLevel("edit", getContext().getUser(),
getContext().getDoc().getFullName(), getContext());
}
private void writeMenuItemWithSubmenu(StringBuilder outStream, String parent, int numMoreLevels,
DocumentReference docRef, boolean isFirstItem, boolean isLastItem, int numItem)
throws XWikiException {
boolean showSubmenu = showSubmenuForMenuItem(docRef, getCurrentLevel(numMoreLevels),
getContext());
String fullName = getWebUtilsService().getRefLocalSerializer().serialize(docRef);
boolean isLeaf = isLeaf(fullName, getContext());
openMenuItemOut(outStream, docRef, isFirstItem, isLastItem, isLeaf, numItem);
writeMenuItemContent(outStream, isFirstItem, isLastItem, docRef, isLeaf, numItem);
if (showSubmenu) {
addNavigationForParent(outStream, docRef, numMoreLevels - 1);
}
closeMenuItemOut(outStream);
}
void writeMenuItemContent(StringBuilder outStream, boolean isFirstItem, boolean isLastItem,
DocumentReference docRef, boolean isLeaf, int numItem) throws XWikiException {
getPresentationType().writeNodeContent(outStream, isFirstItem, isLastItem, docRef, isLeaf,
numItem, this);
}
private boolean isLeaf(String fullName, XWikiContext context) {
List<TreeNode> currentMenuItems = getTreeNodeService().getSubNodesForParent(fullName,
getMenuSpace(context), getNavFilter());
boolean isLeaf = (currentMenuItems.size() <= 0);
return isLeaf;
}
@Override
public String getNavLanguage() {
if (this.navLanguage != null) {
return this.navLanguage;
}
return getContext().getLanguage();
}
@Override
public boolean useImagesForNavigation() {
return getContext().getWiki().getSpacePreferenceAsInt("use_navigation_images", 0,
getContext()) > 0;
}
private void closeMenuItemOut(StringBuilder outStream) {
outStream.append("<!-- IE6 --></li>");
}
void openMenuItemOut(StringBuilder outStream, DocumentReference docRef, boolean isFirstItem,
boolean isLastItem, boolean isLeaf, int numItem) {
outStream.append("<li" + addCssClasses(docRef, false, isFirstItem, isLastItem, isLeaf, numItem)
+ ">");
}
@Override
public String addCssClasses(DocumentReference docRef, boolean withCM, boolean isFirstItem,
boolean isLastItem, boolean isLeaf, int numItem) {
String cssClasses = getCssClasses(docRef, withCM, isFirstItem, isLastItem, isLeaf, numItem);
if (!"".equals(cssClasses.trim())) {
return " class=\"" + cssClasses + "\"";
}
return "";
}
@Override
public String addUniqueElementId(DocumentReference docRef) {
return "id=\"" + getUniqueId(docRef) + "\"";
}
private String addUniqueContainerId(String parent) {
return "id=\"C" + getUniqueId(parent) + "\"";
}
@Override
public String getUniqueId(DocumentReference docRef) {
String fullName = null;
if (docRef != null) {
fullName = getWebUtilsService().getRefLocalSerializer().serialize(docRef);
}
return getUniqueId(fullName);
}
@Override
public String getUniqueId(String fullName) {
String theMenuSpace = getMenuSpace(getContext());
if ((fullName != null) && !"".equals(fullName)) {
return uniqueName + ":" + theMenuSpace + ":" + fullName;
} else {
return uniqueName + ":" + theMenuSpace + ":" + menuPart + ":";
}
}
boolean showSubmenuForMenuItem(DocumentReference docRef, int currentLevel, XWikiContext context) {
return (isShowAll() || isBelowShowAllHierarchy(currentLevel) || isActiveMenuItem(docRef));
}
private boolean isBelowShowAllHierarchy(int currentLevel) {
return (currentLevel < showInactiveToLevel);
}
String getCssClasses(DocumentReference docRef, boolean withCM, boolean isFirstItem,
boolean isLastItem, boolean isLeaf, int numItem) {
String cssClass = "";
if (withCM) {
cssClass += getCMcssClass();
}
if (isFirstItem) {
cssClass += " first";
}
if (isLastItem) {
cssClass += " last";
}
if ((numItem % 2) == 0) {
cssClass += " cel_nav_even";
} else {
cssClass += " cel_nav_odd";
}
cssClass += " cel_nav_item" + numItem;
if (isLeaf) {
cssClass += " cel_nav_isLeaf";
} else {
cssClass += " cel_nav_hasChildren";
}
if (docRef != null) {
cssClass += " cel_nav_nodeSpace_" + docRef.getLastSpaceReference().getName();
cssClass += " cel_nav_nodeName_" + docRef.getName();
if (docRef.equals(getContext().getDoc().getDocumentReference())) {
cssClass += " currentPage";
}
cssClass += " " + getPageTypeConfigName(docRef);
String pageLayoutName = getPageLayoutName(docRef);
if (!"".equals(pageLayoutName)) {
cssClass += " " + pageLayoutName;
}
if (isActiveMenuItem(docRef)) {
cssClass += " active";
}
if (isRestrictedRights(docRef)) {
cssClass += " cel_nav_restricted_rights";
}
}
return cssClass.trim();
}
boolean isRestrictedRights(DocumentReference docRef) {
try {
String docFN = getWebUtilsService().getRefLocalSerializer().serialize(docRef);
XWikiRightService rightService = getContext().getWiki().getRightService();
boolean isRestricted = !rightService.hasAccessLevel("view", "XWiki.XWikiGuest", docFN,
getContext());
LOGGER.debug("isRestrictedRights for [" + docFN + "] returns [" + isRestricted
+ "] using rights service [" + rightService.getClass().getName() + "].");
return isRestricted;
} catch (XWikiException exp) {
LOGGER.error("Failed to check isRestrictedRights for [" + docRef + "].", exp);
}
return false;
}
String getPageLayoutName(DocumentReference docRef) {
SpaceReference pageLayoutRef = getPresentationType().getPageLayoutForDoc(docRef);
if (pageLayoutRef == null) {
pageLayoutRef = pageLayoutCmd.getPageLayoutForDoc(docRef);
}
if (pageLayoutRef != null) {
return "layout_" + pageLayoutRef.getName();
}
return "";
}
String getPageTypeConfigName(DocumentReference docRef) {
PageTypeReference pageTypeRef = getPageTypeResolverService().getPageTypeRefForDocWithDefault(
docRef);
String getPageTypeConfigName = pageTypeRef.getConfigName();
return getPageTypeConfigName;
}
boolean isActiveMenuItem(DocumentReference docRef) {
DocumentReference currentDocRef = getContext().getDoc().getDocumentReference();
List<DocumentReference> docParentList = getWebUtilsService().getDocumentParentsList(
currentDocRef, true);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("isActiveMenuItem: for [" + docRef + "] with [" + docParentList.size()
+ "] parents [" + Arrays.deepToString(docParentList.toArray(new DocumentReference[0]))
+ "].");
}
return (docRef != null) && (docParentList.contains(docRef) || docRef.equals(currentDocRef));
}
@Override
public String getMenuLink(DocumentReference docRef) {
String docURL = getContext().getWiki().getURL(docRef, "view", getContext());
// FIX for bug in xwiki url-factory 2.7.2
if ("".equals(docURL)) {
docURL = "/";
}
return docURL;
}
public static INavigation createNavigation(XWikiContext context) {
return new Navigation(Navigation.newNavIdForContext(context));
}
static String newNavIdForContext(XWikiContext context) {
Long navCounter = getNavCounterFromContext(context) + 1;
context.put(_NAVIGATION_COUNTER_KEY, navCounter);
return "N" + navCounter;
}
private static Long getNavCounterFromContext(XWikiContext context) {
if (!context.containsKey(_NAVIGATION_COUNTER_KEY)) {
return new Long(0);
}
java.lang.Object navCounterObj = context.get(_NAVIGATION_COUNTER_KEY);
if (navCounterObj instanceof Long) {
return (Long) navCounterObj + 1;
} else {
throw new IllegalArgumentException("Long object in context expected but got "
+ navCounterObj.getClass());
}
}
@Override
public int getMenuItemPos(String fullName, XWikiContext context) {
return WebUtils.getInstance().getMenuItemPos(fullName, menuPart, context);
}
@Override
public int getActiveMenuItemPos(int menuLevel, XWikiContext context) {
return WebUtils.getInstance().getActiveMenuItemPos(menuLevel, menuPart, context);
}
@Override
public List<com.xpn.xwiki.api.Object> getMenuItemsForHierarchyLevel(int menuLevel,
XWikiContext context) {
return WebUtils.getInstance().getMenuItemsForHierarchyLevel(menuLevel, menuPart, context);
}
@Override
public String getPrevMenuItemFullName(String fullName, XWikiContext context) {
BaseObject prevMenuItem = null;
try {
prevMenuItem = WebUtils.getInstance().getPrevMenuItem(fullName, context);
} catch (XWikiException exp) {
LOGGER.error("getPrevMenuItemFullName failed.", exp);
}
if (prevMenuItem != null) {
return prevMenuItem.getName();
} else {
return "";
}
}
@Override
public String getNextMenuItemFullName(String fullName, XWikiContext context) {
BaseObject nextMenuItem = null;
try {
nextMenuItem = WebUtils.getInstance().getNextMenuItem(fullName, context);
} catch (XWikiException exp) {
LOGGER.error("getNextMenuItemFullName failed.", exp);
}
if (nextMenuItem != null) {
return nextMenuItem.getName();
} else {
return "";
}
}
@Override
public boolean isNavigationEnabled() {
return navigationEnabled;
}
/**
* Look for a Celements2.NavigationConfigClass object on the WebPreferences,
* XWiki.XWikiPreferences or skin_doc in this order an take the first place where any
* Celements2.NavigationConfigClass object was found. If NO object for the given
* menu_element_name (configName) at the selected place is found. This navigation should
* be set to disabled and includeNavigation must return an empty string.
*/
@Override
public void loadConfigByName(String configName, XWikiContext context) {
XWikiDocument doc = context.getDoc();
try {
BaseObject prefObj = utils.getConfigDocByInheritance(doc, NAVIGATION_CONFIG_CLASS,
context).getObject(NAVIGATION_CONFIG_CLASS, "menu_element_name", configName, false);
loadConfigFromObject(prefObj);
} catch (XWikiException exp) {
LOGGER.error("loadConfigByName failed.", exp);
}
}
@Override
public void loadConfigFromObject(BaseObject prefObj) {
if (prefObj != null) {
configName = prefObj.getStringValue("menu_element_name");
LOGGER.debug("loadConfigFromObject: configName [" + configName + "] from doc ["
+ prefObj.getName() + "].");
fromHierarchyLevel = prefObj.getIntValue("from_hierarchy_level", 1);
toHierarchyLevel = prefObj.getIntValue("to_hierarchy_level", DEFAULT_MAX_LEVEL);
showInactiveToLevel = prefObj.getIntValue("show_inactive_to_level", 0);
menuPart = prefObj.getStringValue("menu_part");
setMenuSpace(prefObj.getStringValue("menu_space"));
if (!"".equals(prefObj.getStringValue("data_type")) && (prefObj.getStringValue(
"data_type") != null)) {
dataType = prefObj.getStringValue("data_type");
}
if (!"".equals(prefObj.getStringValue("layout_type")) && (prefObj.getStringValue(
"layout_type") != null)) {
try {
setLayoutType(prefObj.getStringValue("layout_type"));
} catch (UnknownLayoutTypeException exp) {
LOGGER.error("loadConfigFromObject failed on setLayoutType.", exp);
}
}
int itemsPerPage = prefObj.getIntValue(INavigationClassConfig.ITEMS_PER_PAGE);
if (itemsPerPage > 0) {
nrOfItemsPerPage = itemsPerPage;
}
String presentationTypeStr = prefObj.getStringValue(
NavigationClasses.PRESENTATION_TYPE_FIELD);
if (!"".equals(presentationTypeStr)) {
setPresentationType(presentationTypeStr);
}
setCMcssClass(prefObj.getStringValue("cm_css_class"));
// setMenuTypeByTypeName(prefObj.getStringValue("menu_type"));
} else {
navigationEnabled = false;
}
}
private void generateLanguageMenu(INavigationBuilder navBuilder, XWikiContext context) {
List<String> langs = getWebUtilsService().getAllowedLanguages();
mainUlCssClasses += " language";
navBuilder.openLevel(mainUlCssClasses);
for (String language : langs) {
navBuilder.openMenuItemOut();
boolean isLastItem = (langs.lastIndexOf(language) == (langs.size() - 1));
navBuilder.appendMenuItemLink(language, "?language=" + language, getLanguageName(language,
context), language.equals(getNavLanguage()), isLastItem, cmCssClass);
navBuilder.closeMenuItemOut();
}
navBuilder.closeLevel();
}
private String getLanguageName(String lang, XWikiContext context) {
XWikiMessageTool msg = context.getMessageTool();
String space = context.getDoc().getDocumentReference().getLastSpaceReference().getName();
if (!msg.get("nav_cel_" + space + "_" + lang + "_" + lang).equals("nav_cel_" + space + "_"
+ lang + "_" + lang)) {
return msg.get("nav_cel_" + space + "_" + lang + "_" + lang);
} else if (!msg.get("nav_cel_" + lang + "_" + lang).equals("nav_cel_" + lang + "_" + lang)) {
return msg.get("nav_cel_" + lang + "_" + lang);
} else {
return msg.get("cel_" + lang + "_" + lang);
}
}
@Override
public void setCMcssClass(String cmCssClass) {
this.cmCssClass = cmCssClass;
}
@Override
public String getCMcssClass() {
if ((cmCssClass == null) || "".equals(cmCssClass)) {
return getPresentationType().getDefaultCssClass();
} else {
return cmCssClass;
}
}
/**
* for Tests only !!!
**/
public void testInjectUtils(IWebUtils utils) {
this.utils = utils;
}
/**
* for Tests only !!!
**/
public INavigationBuilder getNavBuilder() {
return navBuilder;
}
@Override
public void setShowAll(boolean showAll) {
this._showAll = showAll;
}
boolean isShowAll() {
return this._showAll;
}
@Override
public void setShowInactiveToLevel(int showInactiveToLevel) {
this.showInactiveToLevel = showInactiveToLevel;
}
@Override
public void setHasLink(boolean hasLink) {
this._hasLink = hasLink;
}
@Override
public boolean hasLink() {
return this._hasLink;
}
@Override
public MultilingualMenuNameCommand getMenuNameCmd() {
return menuNameCmd;
}
@Override
public void setLanguage(String language) {
this.navLanguage = language;
}
public void inject_menuNameCmd(MultilingualMenuNameCommand menuNameCmd) {
this.menuNameCmd = menuNameCmd;
}
private IWebUtilsService getWebUtilsService() {
if (injected_WebUtilsService != null) {
return injected_WebUtilsService;
}
return Utils.getComponent(IWebUtilsService.class);
}
private XWikiContext getContext() {
return (XWikiContext) getExecution().getContext().getProperty("xwikicontext");
}
private Execution getExecution() {
return Utils.getComponent(Execution.class);
}
private ITreeNodeService getTreeNodeService() {
if (injected_TreeNodeService != null) {
return injected_TreeNodeService;
}
return Utils.getComponent(ITreeNodeService.class);
}
IPageTypeResolverRole getPageTypeResolverService() {
if (injected_PageTypeResolverService != null) {
return injected_PageTypeResolverService;
}
return Utils.getComponent(IPageTypeResolverRole.class);
}
@Override
public void setOffset(int offset) {
if (offset >= 0) {
this.offset = offset;
} else {
this.offset = 0;
}
}
@Override
public int getOffset() {
return this.offset;
}
@Override
public void setNumberOfItem(int nrOfItem) {
if (nrOfItem > 0) {
this.nrOfItemsPerPage = nrOfItem;
} else {
this.nrOfItemsPerPage = -1;
}
}
@Override
public int getNumberOfItem() {
return this.nrOfItemsPerPage;
}
@Deprecated
@Override
public int getEffectiveNumberOfItems() {
Tidy tidy = new Tidy();
tidy.setXHTML(true);
ByteArrayInputStream includeIn = new ByteArrayInputStream(includeNavigation().getBytes());
Document dom = tidy.parseDOM(includeIn, null);
NodeList uls = dom.getElementsByTagName("ul");
int elems = 0;
if (uls.getLength() > 0) {
elems = uls.item(0).getChildNodes().getLength();
}
return elems;
}
void inject_navInclude(String navInclude) {
this.navInclude = navInclude;
}
@Override
public boolean hasMore() {
DocumentReference parentRef = getWebUtilsService().getParentForLevel(fromHierarchyLevel);
String parent = "";
if (parentRef != null) {
parent = getWebUtilsService().getRefLocalSerializer().serialize(parentRef);
}
List<TreeNode> currentMenuItems = getCurrentMenuItems(fromHierarchyLevel, parent);
LOGGER.debug("hasMore: parentRef [" + parentRef + "] currentMenuItems.size() ["
+ currentMenuItems.size() + "] offset [" + offset + "]" + " nrOfItemsPerPage ["
+ nrOfItemsPerPage + "] fromHierarchyLevel [" + fromHierarchyLevel + "] parent [" + parent
+ "]");
return currentMenuItems.size() > 0;
}
} |
package org.commcare.dalvik.activities;
import java.math.BigInteger;
import java.security.MessageDigest;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.ManagedUi;
import org.commcare.android.framework.UiElement;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.notifications.MessageTag;
import org.commcare.android.models.notifications.NotificationMessage;
import org.commcare.android.models.notifications.NotificationMessageFactory;
import org.commcare.android.models.notifications.NotificationMessageFactory.StockMessages;
import org.commcare.android.tasks.DataPullTask;
import org.commcare.android.tasks.ManageKeyRecordListener;
import org.commcare.android.tasks.ManageKeyRecordTask;
import org.commcare.android.tasks.templates.HttpCalloutTask.HttpCalloutOutcomes;
import org.commcare.android.util.DemoUserUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.view.ViewUtil;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.dialogs.CustomProgressDialog;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author ctsims
*/
@ManagedUi(R.layout.screen_login)
public class LoginActivity extends CommCareActivity<LoginActivity> {
private static final String TAG = LoginActivity.class.getSimpleName();
public final static int MENU_DEMO = Menu.FIRST;
public final static String NOTIFICATION_MESSAGE_LOGIN = "login_message";
public static final String ALREADY_LOGGED_IN = "la_loggedin";
@UiElement(value=R.id.login_button, locale="login.button")
Button login;
@UiElement(value = R.id.screen_login_bad_password, locale = "login.bad.password")
TextView errorBox;
@UiElement(R.id.edit_username)
EditText username;
@UiElement(R.id.edit_password)
EditText password;
@UiElement(R.id.screen_login_banner_pane)
View banner;
@UiElement(R.id.str_version)
TextView versionDisplay;
@UiElement(R.id.login_button)
Button loginButton;
public static final int TASK_KEY_EXCHANGE = 1;
SqlStorage<UserKeyRecord> storage;
private int editTextColor;
private View.OnKeyListener l;
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
setStyleDefault();
}
};
public void setStyleDefault() {
LoginBoxesStatus.Normal.setStatus(this);
username.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_user_neutral50), null, null, null);
password.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_lock_neutral50), null, null, null);
loginButton.setBackgroundColor(getResources().getColor(R.color.cc_brand_color));
loginButton.setTextColor(getResources().getColor(R.color.cc_neutral_bg));
}
public enum LoginBoxesStatus {
Normal(R.color.login_edit_text_color),
Error(R.color.login_edit_text_color_error);
private final int colorAttr;
LoginBoxesStatus(int colorAttr){
this.colorAttr = colorAttr;
}
public int getColor(Context ctx){
int color = ctx.getResources().getColor(colorAttr);
if (BuildConfig.DEBUG) {
Log.d("LoginBoxesStatus", "Color for status " + this.toString() + " is: " + color);
}
return color;
}
public void setStatus(LoginActivity lact){
lact.setLoginBoxesColor(this.getColor(lact));
}
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
username.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
LoginBoxesStatus.Normal.setStatus(this);
final SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
//Only on the initial creation
if(savedInstanceState == null) {
String lastUser = prefs.getString(CommCarePreferences.LAST_LOGGED_IN_USER, null);
if(lastUser != null) {
username.setText(lastUser);
password.requestFocus();
}
}
login.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
errorBox.setVisibility(View.GONE);
ViewUtil.hideVirtualKeyboard(LoginActivity.this);
//Try logging in locally
if(tryLocalLogin(false)) {
return;
}
startOta();
}
});
username.addTextChangedListener(textWatcher);
password.addTextChangedListener(textWatcher);
versionDisplay.setText(CommCareApplication._().getCurrentVersionString());
username.setHint(Localization.get("login.username"));
password.setHint(Localization.get("login.password"));
final View activityRootView = findViewById(R.id.screen_login_main);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
/*
* (non-Javadoc)
* @see android.view.ViewTreeObserver.OnGlobalLayoutListener#onGlobalLayout()
*/
@Override
public void onGlobalLayout() {
int hideAll = LoginActivity.this.getResources().getInteger(R.integer.login_screen_hide_all_cuttoff);
int hideBanner = LoginActivity.this.getResources().getInteger(R.integer.login_screen_hide_banner_cuttoff);
int height = activityRootView.getHeight();
if(height < hideAll) {
versionDisplay.setVisibility(View.GONE);
banner.setVisibility(View.GONE);
} else if(height < hideBanner) {
banner.setVisibility(View.GONE);
} else {
// Override default CommCare banner if requested
String customBannerURI = prefs.getString(CommCarePreferences.BRAND_BANNER_LOGIN, "");
if (!"".equals(customBannerURI)) {
Bitmap bitmap = ViewUtil.inflateDisplayImage(LoginActivity.this, customBannerURI);
if (bitmap != null) {
ImageView bannerView = (ImageView) banner.findViewById(R.id.screen_login_top_banner);
bannerView.setImageBitmap(bitmap);
}
}
banner.setVisibility(View.VISIBLE);
}
}
});
}
public String getActivityTitle() {
//TODO: "Login"?
return null;
}
private void startOta() {
// We should go digest auth this user on the server and see whether to
// pull them down.
SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
// TODO Auto-generated method stub
// TODO: we don't actually always want to do this. We need to have an
// alternate route where we log in locally and sync (with unsent form
// submissions) more centrally.
DataPullTask<LoginActivity> dataPuller =
new DataPullTask<LoginActivity>(getUsername(), password.getText().toString(),
prefs.getString("ota-restore-url", LoginActivity.this.getString(R.string.ota_restore_url)),
prefs.getString("key_server", LoginActivity.this.getString(R.string.key_server)),
LoginActivity.this) {
@Override
protected void deliverResult( LoginActivity receiver, Integer result) {
if (result == null) {
// The task crashed unexpectedly
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
return;
}
switch(result) {
case DataPullTask.AUTH_FAILED:
receiver.raiseLoginMessage(StockMessages.Auth_BadCredentials, false);
break;
case DataPullTask.BAD_DATA:
receiver.raiseLoginMessage(StockMessages.Remote_BadRestore, true);
break;
case DataPullTask.DOWNLOAD_SUCCESS:
if(!tryLocalLogin(true)) {
receiver.raiseLoginMessage(StockMessages.Auth_CredentialMismatch, true);
} else {
break;
}
case DataPullTask.UNREACHABLE_HOST:
receiver.raiseLoginMessage(StockMessages.Remote_NoNetwork, true);
break;
case DataPullTask.CONNECTION_TIMEOUT:
receiver.raiseLoginMessage(StockMessages.Remote_Timeout, true);
break;
case DataPullTask.SERVER_ERROR:
receiver.raiseLoginMessage(StockMessages.Remote_ServerError, true);
break;
case DataPullTask.UNKNOWN_FAILURE:
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
break;
}
}
/*
* (non-Javadoc)
* @see org.commcare.android.tasks.templates.CommCareTask#deliverUpdate(java.lang.Object, java.lang.Object[])
*/
@Override
protected void deliverUpdate(LoginActivity receiver, Integer... update) {
if(update[0] == DataPullTask.PROGRESS_STARTED) {
receiver.updateProgress(Localization.get("sync.progress.purge"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_CLEANED) {
receiver.updateProgress(Localization.get("sync.progress.authing"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_AUTHED) {
receiver.updateProgress(Localization.get("sync.progress.downloading"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_DOWNLOADING) {
receiver.updateProgress(Localization.get("sync.process.downloading.progress", new String[] {String.valueOf(update[1])}), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_PROCESSING) {
receiver.updateProgress(Localization.get("sync.process.processing", new String[] {String.valueOf(update[1]), String.valueOf(update[2])}), DataPullTask.DATA_PULL_TASK_ID);
receiver.updateProgressBar(update[1], update[2], DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_RECOVERY_NEEDED) {
receiver.updateProgress(Localization.get("sync.recover.needed"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_RECOVERY_STARTED) {
receiver.updateProgress(Localization.get("sync.recover.started"), DataPullTask.DATA_PULL_TASK_ID);
}
}
/*
* (non-Javadoc)
* @see org.commcare.android.tasks.templates.CommCareTask#deliverError(java.lang.Object, java.lang.Exception)
*/
@Override
protected void deliverError( LoginActivity receiver, Exception e) {
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
}
};
dataPuller.connect(this);
dataPuller.execute();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
try {
//TODO: there is a weird circumstance where we're logging in somewhere else and this gets locked.
if(CommCareApplication._().getSession().isActive() && CommCareApplication._().getSession().getLoggedInUser() != null) {
Intent i = new Intent();
i.putExtra(ALREADY_LOGGED_IN, true);
setResult(RESULT_OK, i);
CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN);
finish();
return;
}
}catch(SessionUnavailableException sue) {
//Nothing, we're logging in here anyway
}
refreshView();
}
private void refreshView() {
}
private String getUsername() {
return username.getText().toString().toLowerCase().trim();
}
private boolean tryLocalLogin(final boolean warnMultipleAccounts) {
//TODO: check username/password for emptiness
return tryLocalLogin(getUsername(), password.getText().toString(), warnMultipleAccounts);
}
private boolean tryLocalLogin(final String username, String password,
final boolean warnMultipleAccounts) {
try{
// TODO: We don't actually even use this anymore other than for hte
// local login count, which seems super silly.
UserKeyRecord matchingRecord = null;
int count = 0;
for(UserKeyRecord record : storage()) {
if(!record.getUsername().equals(username)) {
continue;
}
count++;
String hash = record.getPasswordHash();
if(hash.contains("$")) {
String alg = "sha1";
String salt = hash.split("\\$")[1];
String check = hash.split("\\$")[2];
MessageDigest md = MessageDigest.getInstance("SHA-1");
BigInteger number = new BigInteger(1, md.digest((salt+password).getBytes()));
String hashed = number.toString(16);
while (hashed.length() < check.length()) {
hashed = "0" + hashed;
}
if (hash.equals(alg + "$" + salt + "$" + hashed)) {
matchingRecord = record;
}
}
}
final boolean triggerTooManyUsers = count > 1 && warnMultipleAccounts;
ManageKeyRecordTask<LoginActivity> task =
new ManageKeyRecordTask<LoginActivity>(this, TASK_KEY_EXCHANGE,
username, password,
CommCareApplication._().getCurrentApp(),
new ManageKeyRecordListener<LoginActivity>() {
@Override
public void keysLoginComplete(LoginActivity r) {
if(triggerTooManyUsers) {
// We've successfully pulled down new user data.
// Should see if the user already has a sandbox and let
// them know that their old data doesn't transition
r.raiseMessage(NotificationMessageFactory.message(StockMessages.Auth_RemoteCredentialsChanged), true);
Logger.log(AndroidLogger.TYPE_USER, "User " + username + " has logged in for the first time with a new password. They may have unsent data in their other sandbox");
}
r.done();
}
@Override
public void keysReadyForSync(LoginActivity r) {
// TODO: we only wanna do this on the _first_ try. Not
// subsequent ones (IE: On return from startOta)
r.startOta();
}
@Override
public void keysDoneOther(LoginActivity r, HttpCalloutOutcomes outcome) {
switch(outcome) {
case AuthFailed:
Logger.log(AndroidLogger.TYPE_USER, "auth failed");
r.raiseLoginMessage(StockMessages.Auth_BadCredentials, false);
break;
case BadResponse:
Logger.log(AndroidLogger.TYPE_USER, "bad response");
r.raiseLoginMessage(StockMessages.Remote_BadRestore, true);
break;
case NetworkFailure:
Logger.log(AndroidLogger.TYPE_USER, "bad network");
r.raiseLoginMessage(StockMessages.Remote_NoNetwork, false);
break;
case NetworkFailureBadPassword:
Logger.log(AndroidLogger.TYPE_USER, "bad network");
r.raiseLoginMessage(StockMessages.Remote_NoNetwork_BadPass, true);
break;
case BadCertificate:
Logger.log(AndroidLogger.TYPE_USER, "bad certificate");
r.raiseLoginMessage(StockMessages.BadSSLCertificate, false);
break;
case UnkownError:
Logger.log(AndroidLogger.TYPE_USER, "unknown");
r.raiseLoginMessage(StockMessages.Restore_Unknown, true);
break;
default:
return;
}
}
}) {
@Override
protected void deliverUpdate(LoginActivity receiver, String... update) {
receiver.updateProgress(update[0], TASK_KEY_EXCHANGE);
}
};
task.connect(this);
task.execute();
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
private void done() {
Intent i = new Intent();
setResult(RESULT_OK, i);
CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN);
finish();
}
private SqlStorage<UserKeyRecord> storage() throws SessionUnavailableException{
if(storage == null) {
storage= CommCareApplication._().getAppStorage(UserKeyRecord.class);
}
return storage;
}
public void finished(int status) {
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_DEMO, 0, Localization.get("login.menu.demo")).setIcon(android.R.drawable.ic_menu_preferences);
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean otherResult = super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case MENU_DEMO:
//Make sure we have a demo user
DemoUserUtil.checkOrCreateDemoUser(this, CommCareApplication._().getCurrentApp());
//Now try to log in as the demo user
tryLocalLogin(DemoUserUtil.DEMO_USER, DemoUserUtil.DEMO_USER, false);
return true;
default:
return otherResult;
}
}
private void raiseLoginMessage(MessageTag messageTag, boolean showTop) {
NotificationMessage message = NotificationMessageFactory.message(messageTag,
NOTIFICATION_MESSAGE_LOGIN);
raiseMessage(message, showTop);
}
private void raiseMessage(NotificationMessage message, boolean showTop) {
String toastText = message.getTitle();
if (showTop) {
CommCareApplication._().reportNotificationMessage(message);
toastText = Localization.get("notification.for.details.wrapper",
new String[] {toastText});
}
//either way
LoginBoxesStatus.Error.setStatus(this);
username.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_user_attnneg), null, null, null);
password.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_lock_attnneg), null, null, null);
loginButton.setBackgroundColor(getResources().getColor(R.color.cc_attention_negative_bg));
loginButton.setTextColor(getResources().getColor(R.color.cc_attention_negative_text));
errorBox.setVisibility(View.VISIBLE);
errorBox.setText(toastText);
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
}
/**
* Sets the login boxes (user/pass) to the given color.
* @param color Color code
*/
private void setLoginBoxesColor(int color) {
username.setTextColor(color);
password.setTextColor(color);
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#generateProgressDialog(int)
*
* Implementation of generateProgressDialog() for DialogController -- other methods
* handled entirely in CommCareActivity
*/
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
CustomProgressDialog dialog;
switch (taskId) {
case TASK_KEY_EXCHANGE:
dialog = CustomProgressDialog.newInstance(Localization.get("key.manage.title"),
Localization.get("key.manage.start"), taskId);
break;
case DataPullTask.DATA_PULL_TASK_ID:
dialog = CustomProgressDialog.newInstance(Localization.get("sync.progress.title"),
Localization.get("sync.progress.starting"), taskId);
dialog.addCancelButton();
dialog.addProgressBar();
break;
default:
Log.w(TAG, "taskId passed to generateProgressDialog does not match "
+ "any valid possibilities in LoginActivity");
return null;
}
return dialog;
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#isBackEnabled()
*/
@Override
public boolean isBackEnabled() {
return false;
}
} |
package com.coremedia.iso.boxes;
import com.coremedia.iso.BoxParser;
import com.coremedia.iso.IsoBufferWrapper;
import com.coremedia.iso.IsoFile;
import com.coremedia.iso.IsoOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
/**
* A basic ISO box. No full box.
*/
public abstract class AbstractBox implements Box {
public long offset;
private List<WriteListener> writeListeners = null;
/**
* Adds a Listener that will be called right before writing the box.
*
* @param writeListener the new Listener.
*/
public void addWriteListener(WriteListener writeListener) {
if (writeListeners == null) {
writeListeners = new LinkedList<WriteListener>();
}
writeListeners.add(writeListener);
}
public long getSize() {
return getContentSize() + getHeaderSize() + getDeadBytes().length;
}
protected long getHeaderSize() {
return 4 + // size
4 + // type
(getContentSize() >= 4294967296L ? 8 : 0) +
(Arrays.equals(getType(), IsoFile.fourCCtoBytes(UserBox.TYPE)) ? 16 : 0);
}
/**
* Gets the box's content size without header size.
*
* @return Gets the box's content size in bytes
*/
protected abstract long getContentSize();
private byte[] type;
private byte[] userType;
private ContainerBox parent;
protected AbstractBox(byte[] type) {
this.type = type;
}
public byte[] getType() {
return type;
}
public byte[] getUserType() {
return userType;
}
public void setUserType(byte[] userType) {
this.userType = userType;
}
public ContainerBox getParent() {
return parent;
}
public long getOffset() {
return offset;
}
public void setParent(ContainerBox parent) {
this.parent = parent;
}
public IsoFile getIsoFile() {
return parent.getIsoFile();
}
/**
* Pareses the given IsoBufferWrapper and returns the remaining bytes.
*
* @param in the (part of the) iso file to parse
* @param size expected size of the box
* @param boxParser creates inner boxes
* @param lastMovieFragmentBox latest of previously found moof boxes
* @throws IOException in case of an I/O error.
*/
public abstract void parse(IsoBufferWrapper in, long size, BoxParser boxParser, Box lastMovieFragmentBox) throws IOException;
/**
* Returns the human readable name of the box.
*
* @return a display string
*/
public abstract String getDisplayName();
ByteBuffer[] deadBytes = new ByteBuffer[]{};
public ByteBuffer[] getDeadBytes() {
return deadBytes;
}
public void setDeadBytes(ByteBuffer[] newDeadBytes) {
deadBytes = newDeadBytes;
}
public byte[] getHeader() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IsoOutputStream ios = new IsoOutputStream(baos, false);
if (isSmallBox()) {
ios.writeUInt32((int) this.getSize());
ios.write(getType());
} else {
ios.writeUInt32(1);
ios.write(getType());
ios.writeUInt64(getSize());
}
if (Arrays.equals(getType(), IsoFile.fourCCtoBytes(UserBox.TYPE))) {
ios.write(userType);
}
assert baos.size() == getHeaderSize();
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private boolean isSmallBox() {
return this.getSize() < 4294967296L;
}
public void getBox(IsoOutputStream os) throws IOException {
long sp = os.getStreamPosition();
if (writeListeners != null) {
for (WriteListener writeListener : writeListeners) {
writeListener.beforeWrite(sp);
}
}
os.write(getHeader());
getContent(os);
for (ByteBuffer buffer : deadBytes) {
buffer.rewind();
byte[] bufAsAr = new byte[buffer.limit()];
buffer.get(bufAsAr);
os.write(bufAsAr);
}
long writtenBytes = os.getStreamPosition() - sp;
String uuid;
if (getUserType() != null && getUserType().length == 16) {
ByteBuffer b = ByteBuffer.wrap(getUserType());
b.order(ByteOrder.BIG_ENDIAN);
uuid = new UUID(b.getLong(), b.getLong()).toString();
} else {
uuid = "
}
assert writtenBytes == getSize() : " getHeader + getContent + getDeadBytes (" + writtenBytes + ") of "
+ IsoFile.bytesToFourCC(getType()) + " userType: " + uuid
+ " doesn't match getSize (" + getSize() + ")";
}
/**
* Writes the box's content into the given <code>IsoOutputStream</code>. This MUST NOT include
* any header bytes.
*
* @param os the box's content-sink.
* @throws IOException in case of an exception in the underlying <code>OutputStream</code>.
*/
protected abstract void getContent(IsoOutputStream os) throws IOException;
public static int utf8StringLengthInBytes(String utf8) {
try {
if (utf8 != null) {
return utf8.getBytes("UTF-8").length;
} else {
return 0;
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException();
}
}
public long calculateOffset() {
//todo: doesn't work for fragmented files as it doesn't take mdats into account (as they are not in the parent structure)
long offsetFromParentBoxStart = parent.getNumOfBytesToFirstChild();
Box[] boxes = parent.getBoxes();
for (Box box : boxes) {
if (box.equals(this)) {
return parent.calculateOffset() + offsetFromParentBoxStart;
}
offsetFromParentBoxStart += box.getSize();
}
throw new InternalError("this box is not in the list of its parent's children");
}
} |
package br.com.dbsoft.tmp;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import org.junit.After;
import org.junit.Before;
import br.com.dbsoft.core.DBSSDK;
import br.com.dbsoft.error.DBSIOException;
import br.com.dbsoft.io.DBSDAO;
import br.com.dbsoft.util.DBSDate;
import br.com.dbsoft.util.DBSIO;
import br.com.dbsoft.util.DBSNumber;
import br.com.dbsoft.util.DBSString;
public class TrocaNomes {
// String url = "jdbc:mysql://ifeed.com.br:3306/ifeed?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
// String url = "jdbc:mysql://ifeed.com.br:3306/dbsfnd?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
// String url="jdbc:mysql://localhost:3306/dbsfnd?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
String url="jdbc:mysql://localhost:3306/ifeed?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
// String url="jdbc:mysql://192.168.0.106:3306/dbsfnd?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
// String url="jdbc:mysql://192.168.0.106:3306/ifeed?zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true";
// String url="jdbc:oracle:thin:@192.168.0.20:1521:xe";
String user="usuario";
String password="senha";
Connection wConexao;
@Before
public void setup() throws Exception {
Class.forName(DBSSDK.JDBC_DRIVER.MYSQL);
Class.forName(DBSSDK.JDBC_DRIVER.ORACLE);
wConexao = DriverManager.getConnection(url, user, password);
wConexao.setAutoCommit(false);
}
@After
public void tearDown() throws Exception {
wConexao.close();
}
// @Test
public void testaUpdate() throws DBSIOException{
@SuppressWarnings("rawtypes")
DBSDAO xDAO = new DBSDAO(wConexao, "SEG_GRUPO");
xDAO.open("SELECT * FROM SEG_GRUPO WHERE GRUPO_ID=2");
// xDAO.setValue("GRUPO_ID", 2);
// xDAO.setValue("GRUPO", DBSDate.getNowTime().toString());
xDAO.setValue("GRUPO_ID", null);
xDAO.setValue("GRUPO", "ttt");
xDAO.setExecuteOnlyChangedValues(false);
xDAO.executeInsert();
DBSIO.endTrans(wConexao, true);
}
// @Test
public void trocaAtivoTipo(){
try {
@SuppressWarnings("rawtypes")
DBSDAO xDAO = new DBSDAO(wConexao, "GR_COTACAO");
Double xDouble = DBSNumber.toDouble(200D);
BigDecimal xBigDecimal = DBSNumber.toBigDecimal("1000");
Integer xInteger = DBSNumber.toInteger("1");
Date xData = DBSDate.toDate(19,9,2014);
xDAO.open("Select * from GR_COTACAO WHERE DATA = " + DBSIO.toSQLDate(wConexao, xData));
if (xDAO.getRowsCount()==1){
xDAO.moveFirstRow();
// xDouble = xDAO.getValue("ABERTURA");
// xDouble = xDAO.<Double>getValueX("ABERTURA");
System.out.println(xDouble);
}
// xDAO.moveBeforeFirstRow();
// while(xDAO.moveNextRow()){
// System.out.println(xDAO.getValue("DATA"));
// }else{
xDAO.setValue("DATA", xData);
xDAO.setValue("POSID_ID", 2);
xDAO.setValue("ABERTURA", xInteger);
xDAO.setValue("media", xDouble);
xDAO.setValue("FECHAMENTO", xBigDecimal);
xDAO.setValue("MINIMA", null);
xDAO.setValue("MAXIMA", "6");
xDAO.setValue("AJUSTE", 7);
xDAO.setValue("DELTA", 8D);
xDAO.setValue("VOLUME", "123.456");
xDAO.setValue("NEGOCIOS", "78,9");
xDAO.setValue("REPETIDA", true);
// xDAO.executeInsert();
xDAO.executeMerge();
DBSIO.endTrans(wConexao, true);
xDAO.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void trocaProdutoTipo(){
try {
@SuppressWarnings("rawtypes")
DBSDAO xDAO = new DBSDAO(wConexao, "GR_PRODUTO_TIPO");
xDAO.open("Select * from GR_PRODUTO_TIPO");
xDAO.moveBeforeFirstRow();
while(xDAO.moveNextRow()){
System.out.println(xDAO.getValue("Produto_Tipo"));
xDAO.setValue("Produto_Tipo", DBSString.corretorOrtografico(DBSString.toProper((String) xDAO.getValue("Produto_Tipo"))));
// if (xDAO.getValue("Complemento")!=null){
// xDAO.setValue("Complemento", DBSString.toProper((String) xDAO.getValue("Complemento")));
// if (xDAO.getValue("Endereco")!=null){
// xDAO.setValue("Endereco", DBSString.corretorOrtografico(DBSString.toProper((String) xDAO.getValue("Endereco"))));
xDAO.executeUpdate();
//System.out.println(xDAO.getValue("Cidade"));
}
DBSIO.endTrans(wConexao, true);
xDAO.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test
public void readLoop2(){
try {
@SuppressWarnings("rawtypes")
DBSDAO xDAO = new DBSDAO(wConexao);
xDAO.open("Select * from Cor_Estado");
xDAO.moveBeforeFirstRow();
while(xDAO.moveNextRow()){
System.out.println(xDAO.getValue("Estado"));
//xDAO.setValue("Estado", DBSString.toProper((String) xDAO.getValue("Estado")));
//xDAO.executeUpdate();
//System.out.println(xDAO.getValue("Cidade"));
}
DBSIO.endTrans(wConexao, true);
xDAO.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test
public void troca_nomes_centrus() throws DBSIOException {
DBSDAO<Object> xDAO = new DBSDAO<Object>(wConexao, "PESSOA");
System.out.println(Runtime.getRuntime().maxMemory() + "====================================") ;
xDAO.open("Select * from pessoa order by cd_centrus");
String xNomeProprioAnterior = "CORRETORA";
String xSobrenomeAnterior = "";
String xSiglaAnterior = "CORRETORA";
String xNomeProprioAtual = "CORRETORA";
String xSobrenomeAtual="";
String xSiglaAtual="";
String xNovoNome;
String xNovaSigla;
xDAO.moveBeforeFirstRow();
while(xDAO.moveNextRow()){
if (!DBSString.toArray(xDAO.getValue("no_pessoa").toString(), " ").get(0).equals(xNomeProprioAtual)){
xNomeProprioAnterior = xNomeProprioAtual;
xSobrenomeAnterior = xSobrenomeAtual;
xSiglaAnterior = xSiglaAtual;
}
xNomeProprioAtual = DBSString.toArray(xDAO.getValue("no_pessoa").toString(), " ").get(0);
if (DBSString.toArray(xDAO.getValue("no_pessoa").toString(), " ").size()>1){
xSobrenomeAtual = DBSString.toArray(xDAO.getValue("no_pessoa").toString(), " ").get(1);
}
xNovoNome = DBSString.changeStr(xDAO.getValue("no_pessoa").toString(), xNomeProprioAtual, xNomeProprioAnterior);
xNovoNome = DBSString.changeStr(xNovoNome, xSobrenomeAtual, xSobrenomeAnterior);
System.out.println("OLD:" + xDAO.getValue("no_pessoa"));
xDAO.setValue("no_pessoa", DBSString.getSubString(xNovoNome, 1, 50));
System.out.println("NEW:" + xDAO.getValue("no_pessoa"));
if(xDAO.getValue("sg_pessoa")!=null){
xSiglaAtual = DBSString.toArray(xDAO.getValue("sg_pessoa").toString(), " ").get(0);
xNovaSigla = DBSString.changeStr(xDAO.getValue("sg_pessoa").toString(), xSiglaAtual, xSiglaAnterior);
xDAO.setValue("sg_pessoa", DBSString.getSubString(xNovaSigla,1,15));
}
xDAO.executeUpdate();
}
//assertTrue("TESTE ESPERAVA NOTNULL",xDAO.executeMerge()>0);
DBSIO.endTrans(wConexao, true);
xDAO.close();
System.out.println("FIM====================================");
}
// @Test
public void troca_nomes_centrus_usuario() throws DBSIOException {
DBSDAO<Object> xDAO = new DBSDAO<Object>(wConexao, "AC_USUARIO");
System.out.println(Runtime.getRuntime().maxMemory() + "====================================") ;
xDAO.open("Select * from AC_USUARIO");
String xNomeDaColuna = "COMPLETO";
String xNomeProprioAnterior = "LUIZ";
String xSobrenomeAnterior = "";
String xNomeProprioAtual = "CORRETORA";
String xSobrenomeAtual="";
String xNovoNome;
xDAO.moveBeforeFirstRow();
while(xDAO.moveNextRow()){
if (!DBSString.toArray(xDAO.getValue(xNomeDaColuna).toString(), " ").get(0).equals(xNomeProprioAtual)){
xNomeProprioAnterior = xNomeProprioAtual;
xSobrenomeAnterior = xSobrenomeAtual;
}
xNomeProprioAtual = DBSString.toArray(xDAO.getValue(xNomeDaColuna).toString(), " ").get(0);
if (DBSString.toArray(xDAO.getValue(xNomeDaColuna).toString(), " ").size()>1){
xSobrenomeAtual = DBSString.toArray(xDAO.getValue(xNomeDaColuna).toString(), " ").get(1);
}
xNovoNome = DBSString.changeStr(xDAO.getValue(xNomeDaColuna).toString(), xNomeProprioAtual, xNomeProprioAnterior);
xNovoNome = DBSString.changeStr(xNovoNome, xSobrenomeAtual, xSobrenomeAnterior);
System.out.println("OLD:" + xDAO.getValue(xNomeDaColuna));
xDAO.setValue(xNomeDaColuna, DBSString.getSubString(xNovoNome, 1, 50));
System.out.println("NEW:" + xDAO.getValue(xNomeDaColuna));
xDAO.executeUpdate();
}
//assertTrue("TESTE ESPERAVA NOTNULL",xDAO.executeMerge()>0);
DBSIO.endTrans(wConexao, true);
xDAO.close();
System.out.println("FIM====================================");
}
} |
package com.picea.memor4j;
import junit.framework.TestCase;
public class TestPeAtom extends TestCase {
public void testBasic() {
assertTrue(false);
}
} |
/**
* Created at Aug 3, 2010, 10:06:41 PM
*/
package com.dmurph.mvc.monitor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import com.dmurph.mvc.IGlobalEventMonitor;
import com.dmurph.mvc.MVCEvent;
/**
* This is an event monitor gui, for displaying all {@link MVCEvent}s that
* are dispatched. This makes it easy to debug your program and find out what is
* dispatched when.
* @author Daniel Murphy
*/
public class EventMonitor extends JFrame implements IGlobalEventMonitor {
private static final long serialVersionUID = 1L;
public static final int DEFAULT_NUM_MESSAGES_LOGGED = 500;
public static final int LOG_ALL_MESSAGES = Integer.MAX_VALUE;
private JTable table = new JTable();
private JButton enableDisable = new JButton();
private JLabel info = new JLabel();
private final EventTableModel model;
private final IGlobalEventMonitor delegate;
private final EventMonitorType type;
private boolean enabled = true;
private int numEvents = 0;
private int numSilentEvents = 0;
/**
* Creates a simple event monitor.
*/
public EventMonitor(){
this(EventMonitorType.BEFORE_DISPATCH, null, DEFAULT_NUM_MESSAGES_LOGGED);
}
public EventMonitor(int argMaxLogEntries){
this(EventMonitorType.BEFORE_DISPATCH, null, argMaxLogEntries);
}
public EventMonitor(IGlobalEventMonitor argDelegate){
this(EventMonitorType.BEFORE_DISPATCH, argDelegate, DEFAULT_NUM_MESSAGES_LOGGED);
}
public EventMonitor(EventMonitorType argType){
this(argType, null, DEFAULT_NUM_MESSAGES_LOGGED);
}
/**
* @param argType the type of event monitor this will be.
* @param argDelegate the delegate to forward calls to. Can be null.
*/
public EventMonitor(EventMonitorType argType, IGlobalEventMonitor argDelegate){
this(argType, argDelegate, DEFAULT_NUM_MESSAGES_LOGGED);
}
/**
* @param argType the type of event monitor this will be.
* @param argDelegate the delegate to forward calls to. Can be null.
* @param argMaxMessages the maximum messages to keep. Use {@link #LOG_ALL_MESSAGES}
* to try to log all messages.
*/
public EventMonitor(EventMonitorType argType, IGlobalEventMonitor argDelegate, int argMaxMessages){
super("JMVC Event Monitor");
setSize(400, 400);
delegate = argDelegate;
type = argType;
if(argMaxMessages < 0){
throw new IllegalArgumentException("Number cannot be negative");
}
model = new EventTableModel(argMaxMessages);
initializeComponents();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent argE) {
setEnabled(false);
}
});
}
/**
* @return the delegate
*/
public IGlobalEventMonitor getDelegate() {
return delegate;
}
private void initializeComponents() {
setLayout(new BorderLayout());
add(new JScrollPane(table), "Center");
table.setFillsViewportHeight(true);
table.setModel(model);
Box box = Box.createHorizontalBox();
box.add(Box.createRigidArea(new Dimension(10, 10)));
box.add(info);
box.add(Box.createHorizontalGlue());
enableDisable.setText("Disable");
box.add(enableDisable);
add(box, "South");
enableDisable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent argE) {
if(enabled){
setEnabled(false);
}else{
setEnabled(true);
}
}
});
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param argEnabled the enabled to set
*/
public void setEnabled(boolean argEnabled) {
enabled = argEnabled;
if(enabled){
enableDisable.setText("Disable");
}else{
enableDisable.setText("Enable");
}
}
/**
* @see com.dmurph.mvc.IGlobalEventMonitor#afterDispatch(com.dmurph.mvc.MVCEvent)
*/
public void afterDispatch(MVCEvent argEvent) {
if(delegate != null){
delegate.afterDispatch(argEvent);
}
if(enabled && type == EventMonitorType.AFTER_DISPATCH){
numEvents++;
updateInfo();
model.logEvent(argEvent, EventType.LISTENERS);
}
}
/**
* @see com.dmurph.mvc.IGlobalEventMonitor#beforeDispatch(com.dmurph.mvc.MVCEvent)
*/
public void beforeDispatch(MVCEvent argEvent) {
if(delegate != null){
delegate.beforeDispatch(argEvent);
}
if(enabled && type == EventMonitorType.BEFORE_DISPATCH){
numEvents++;
updateInfo();
model.logEvent(argEvent, EventType.LISTENERS);
}
}
/**
* @see com.dmurph.mvc.IGlobalEventMonitor#noListeners(com.dmurph.mvc.MVCEvent)
*/
public void noListeners(MVCEvent argEvent) {
if(delegate != null){
delegate.noListeners(argEvent);
}
if(enabled){
numEvents++;
numSilentEvents++;
updateInfo();
model.logEvent(argEvent, EventType.NO_LISTENERS);
}
}
private void updateInfo(){
info.setText(numEvents+" total events, "+numSilentEvents+" never recieved.");
}
protected static enum EventType{
LISTENERS, NO_LISTENERS
}
// public static void main(String[] args) {
// EventMonitor monitor = new EventMonitor(EventMonitorType.BEFORE_DISPATCH, MVC.getGlobalEventMonitor());
// MVC.setGlobalEventMonitor(monitor);
// monitor.setVisible(true);
// MVCEvent event = new MVCEvent("HI");
// event.dispatch();
// event = new MVCEvent("HI");
// event.dispatch();event = new MVCEvent("HI2");
// event.dispatch();event = new MVCEvent("HI2");
// event.dispatch();event = new MVCEvent("HI2");
// event.dispatch();
} |
package io.tracee.contextlogger.integrationtest;
import io.tracee.contextlogger.builder.TraceeContextLogger;
import io.tracee.contextlogger.profile.Profile;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Integration test to check behavior for custom context data providers and wrapper that have no no args constructor.
*/
public class MissingConstructorIntegrationTest {
@Test
public void should_handle_missing_no_args_constructor_gently() {
// should not break because of the missing no args constructor => type will be deserialized instead
String result = TraceeContextLogger.create().config().enforceProfile(Profile.ENHANCED).apply().build().createJson(TestBrokenImplicitContentDataProviderWithoutDefaultConstructor.class);
MatcherAssert.assertThat(result, Matchers.startsWith("{\"java.lang.Class\""));
}
@Test
public void should_wrap_with_external_wrappers_correctly_using_enhanced_profile() {
// should not default deserialization mechanism, because context data provider wrapper can't be created.
String result = TraceeContextLogger.create().config().enforceProfile(Profile.ENHANCED).apply().build().createJson(new BrokenCustomContextDataWrapperWithMissingNoargsConstructor());
MatcherAssert.assertThat(result, Matchers.startsWith("{\"io.tracee.contextlogger.integrationtest.BrokenCustomContextDataWrapperWithMissingNoargsConstructor\""));
}
} |
package ee.risk.util;
import junit.framework.TestCase;
import java.util.Calendar;
/**
* This test ensures that DateMangler works correctly
*
* @author The Ranger
*/
public class TestDateMangler extends TestCase {
private Calendar date;
private Calendar maxDate;
private Calendar minDate;
private DateMangler dateMangler;
@Override
public void setUp() {
date = Calendar.getInstance();
date.set(Calendar.YEAR, 2015);
date.set(Calendar.MONTH, 5);
date.set(Calendar.DAY_OF_MONTH, 2);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 40);
maxDate = Calendar.getInstance();
maxDate.setTime(date.getTime());
maxDate.set(Calendar.HOUR_OF_DAY, 23);
maxDate.set(Calendar.MINUTE, 59);
maxDate.set(Calendar.SECOND, 59);
maxDate.set(Calendar.MILLISECOND, 999);
minDate = date;
minDate.set(Calendar.HOUR_OF_DAY, 0);
minDate.set(Calendar.MINUTE, 0);
minDate.set(Calendar.SECOND, 0);
minDate.set(Calendar.MILLISECOND, 0);
dateMangler = new DateMangler(date.getTime());
dateMangler.setTimeZone("Europe/Tallinn");
}
public void testMinDate() {
assertEquals("Unexpected minimum date value", minDate.getTime(), dateMangler.getBeginningOfDay());
}
public void testMaxDate() {
assertEquals("Unexpected maximum date value", maxDate.getTime(), dateMangler.getEndOfDay());
}
public void testStringDay() {
assertEquals("Unexpected day received", "02", dateMangler.getDay());
}
public void testStringMonth() {
assertEquals("Unexpected month received", "06", dateMangler.getMonth());
}
public void testStringYear() {
assertEquals("Unexpected year received", "2015", dateMangler.getYear());
}
public void testNumericTriplet() {
DateMangler dateMangler = new DateMangler(2, 6, 2015);
assertEquals("Unexpected day received", "02", dateMangler.getDay());
assertEquals("Unexpected month received", "06", dateMangler.getMonth());
assertEquals("Unexpected year received","2015", dateMangler.getYear());
}
public void testTomorrow() {
DateMangler today = new DateMangler(30, 6, 2015);
DateMangler tomorrow = today.getTomorrow();
assertEquals("Unexpected day received", "01", tomorrow.getDay());
assertEquals("Unexpected month received","07", tomorrow.getMonth());
}
public void testYesterday() {
DateMangler today = new DateMangler(1, 6, 2015);
DateMangler yesterday = today.getYesterday();
assertEquals("Unexpected day received", "31", yesterday.getDay());
assertEquals("Unexpected month received", "05", yesterday.getMonth());
}
} |
package com.docusign.esign.client;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.docusign.esign.client.auth.Authentication;
import com.docusign.esign.client.auth.HttpBasicAuth;
import com.docusign.esign.client.auth.ApiKeyAuth;
import com.docusign.esign.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T11:06:30.816-07:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "https:
private boolean debugging = false;
private int connectionTimeout = 0;
private Client httpClient;
private ObjectMapper objectMapper;
private Map<String, Authentication> authentications;
private int statusCode;
private Map<String, List<String>> responseHeaders;
private DateFormat dateFormat;
public ApiClient() {
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.registerModule(new JodaModule());
objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());
dateFormat = ApiClient.buildDefaultDateFormat();
// Set default User-Agent.
setUserAgent("Swagger-Codegen/2.0.1/java");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
rebuildHttpClient();
}
public static DateFormat buildDefaultDateFormat() {
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone.
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
/**
* Build the Client used to make HTTP requests with the latest settings,
* i.e. objectMapper and debugging.
* TODO: better to use the Builder Pattern?
*/
public ApiClient rebuildHttpClient() {
// Add the JSON serialization support to Jersey
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
if (debugging) {
client.addFilter(new LoggingFilter());
}
this.httpClient = client;
return this;
}
/**
* Returns the current object mapper used for JSON serialization/deserialization.
* <p>
* Note: If you make changes to the object mapper, remember to set it back via
* <code>setObjectMapper</code> in order to trigger HTTP client rebuilding.
* </p>
*/
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public ApiClient setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
// Need to rebuild the Client as it depends on object mapper.
rebuildHttpClient();
return this;
}
public Client getHttpClient() {
return httpClient;
}
public ApiClient setHttpClient(Client httpClient) {
this.httpClient = httpClient;
return this;
}
public String getBasePath() {
return basePath;
}
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Gets the status code of the previous request
*/
public int getStatusCode() {
return statusCode;
}
/**
* Gets the response headers of the previous request
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
*/
public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param key The header's key
* @param value The header's value
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
*/
public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging;
// Need to rebuild the Client as it depends on the value of debugging.
rebuildHttpClient();
return this;
}
/**
* Connect timeout (in milliseconds).
*/
public int getConnectTimeout() {
return connectionTimeout;
}
/**
* Set the connect timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link Integer#MAX_VALUE}.
*/
public ApiClient setConnectTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
httpClient.setConnectTimeout(connectionTimeout);
return this;
}
/**
* Get the date format used to parse/format date parameters.
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// Also set the date format for model (de)serialization with Date properties.
this.objectMapper.setDateFormat((DateFormat) dateFormat.clone());
// Need to rebuild the Client as objectMapper changes.
rebuildHttpClient();
return this;
}
/**
* Parse the given string into Date object.
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/*
Format to {@code Pair} objects.
*/
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
public boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*/
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));
}
for (String key : defaultHeaderMap.keySet()) {
if (!headerParams.containsKey(key)) {
builder = builder.header(key, defaultHeaderMap.get(key));
}
}
// Add DocuSign Tracking Header
builder = builder.header("X-DocuSign-SDK", "Java");
ClientResponse response = null;
if ("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
} else if ("POST".equals(method)) {
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PUT".equals(method)) {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PATCH".equals(method)) {
response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams));
}
else {
throw new ApiException(500, "unknown method type " + method);
}
return response;
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
} else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if (returnType == null)
return null;
else
return response.getEntity(returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = response.getEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
response.getHeaders(),
respBody);
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
}
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
.append("=")
.append(URLEncoder.encode(valueStr, "utf8"));
formParamBuilder.append("&");
} catch (UnsupportedEncodingException e) {
// move on to next
}
}
String encodedFormParams = formParamBuilder.toString();
if (encodedFormParams.endsWith("&")) {
encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1);
}
return encodedFormParams;
}
} |
//$HeadURL$
package org.deegree.feature.persistence;
import static org.deegree.commons.jdbc.ConnectionManager.addConnection;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import org.deegree.commons.config.AbstractResourceManager;
import org.deegree.commons.config.DeegreeWorkspace;
import org.deegree.commons.config.DefaultResourceManagerMetadata;
import org.deegree.commons.config.ResourceManager;
import org.deegree.commons.config.ResourceManagerMetadata;
import org.deegree.commons.config.ResourceInitException;
import org.deegree.commons.jdbc.ConnectionManager;
import org.deegree.commons.utils.ProxyUtils;
import org.deegree.commons.utils.TempFileManager;
import org.deegree.filter.function.FunctionManager;
import org.slf4j.Logger;
/**
* Entry point for creating and retrieving {@link FeatureStore} providers and instances.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class FeatureStoreManager extends AbstractResourceManager<FeatureStore> {
private static final Logger LOG = getLogger( FeatureStoreManager.class );
private FeatureStoreManagerMetadata metadata;
@Override
public void startup( DeegreeWorkspace workspace )
throws ResourceInitException {
metadata = new FeatureStoreManagerMetadata( workspace );
// ConnectionManager mgr = workspace.getSubsystemManager(ConnectionManager.class );
// lockdb stuff
String lockDb = new File( TempFileManager.getBaseDir(), "lockdb" ).getAbsolutePath();
LOG.info( "Using '" + lockDb + "' for h2 lock database." );
try {
Class.forName( "org.h2.Driver" );
} catch ( ClassNotFoundException e ) {
LOG.error( "Unable to load h2 driver class." );
}
// TODO: mgr.
addConnection( "LOCK_DB", "jdbc:h2:" + lockDb, "SA", "", 0, 10 );
// stores startup
super.startup( workspace );
}
@SuppressWarnings("unchecked")
public Class<? extends ResourceManager>[] getDependencies() {
return new Class[] { ProxyUtils.class, ConnectionManager.class, FunctionManager.class };
}
static class FeatureStoreManagerMetadata extends DefaultResourceManagerMetadata<FeatureStore> {
FeatureStoreManagerMetadata( DeegreeWorkspace workspace ) {
super( "feature stores", "datasources/feature/", FeatureStoreProvider.class, workspace );
}
}
@Override
public ResourceManagerMetadata<FeatureStore> getMetadata() {
return metadata;
}
@Override
public void shutdown() {
workspace.getSubsystemManager( ConnectionManager.class ).deactivate( "LOCK_DB" );
}
} |
package com.dumbster.smtp.utils;
import com.dumbster.smtp.exceptions.SmtpException;
import com.google.common.collect.Lists;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;
public class EmailSender {
private static final String DEFAULT_CHARSET = "UTF-8";
private String charset = DEFAULT_CHARSET;
private String encoding;
private List<String> additionalHeaderLines = Lists.newArrayList();
private final String smtpHostname;
private final int smtpPort;
private String username;
private String password;
public EmailSender(String smtpHostname, int smtpPort) {
this.smtpHostname = smtpHostname;
this.smtpPort = smtpPort;
}
public void sendEmail(String from, String to, String subject, String body) {
sendEmail(from, new String[]{to}, subject, body);
}
public void sendEmail(String from, MimeMessage... mimeMessages) throws MessagingException {
Session session = newSmtpSession(from);
Transport transport = session.getTransport("smtp");
transport.connect(smtpHostname, smtpPort, username, password);
for(MimeMessage message : mimeMessages) {
if(encoding != null) {
message.setHeader("Content-Transfer-Encoding", encoding);
}
message.setFrom(new InternetAddress(from));
for(String headerLine : additionalHeaderLines) {
message.addHeaderLine(headerLine);
}
transport.sendMessage(message, message.getAllRecipients());
}
transport.close();
}
public void sendEmail(String from, String[] to, String subject, String body) {
Session session = newSmtpSession(from);
try {
MimeMessage message = new MimeMessage(session);
message.setHeader("Content-Type", "text/plain; charset=" + charset + "; format=flowed");
message.setHeader("X-Accept-Language", "pt-br, pt");
List<InternetAddress> recipients = Lists.newArrayList();
for (String email : to) {
recipients.add(new InternetAddress(email, email));
}
message.addRecipients(Message.RecipientType.TO, recipients.toArray(new InternetAddress[recipients.size()]));
message.setSubject(subject);
message.setText(body);
sendEmail(from, message);
} catch (Exception ex) {
throw new SmtpException(ex);
}
}
public Session newSmtpSession(String from) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", smtpHostname);
properties.setProperty("mail.smtp.port", Integer.toString(smtpPort));
properties.put("mail.mime.charset", charset);
properties.put("mail.from", from);
return Session.getDefaultInstance(properties);
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setCharset(String charset) {
this.charset = charset;
}
public void addHeaderLine(String headerLine) {
additionalHeaderLines.add(headerLine);
}
public void addHeader(String headerKey, String headerValue) {
addHeaderLine(headerKey + ": " + headerValue);
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
} |
package org.dominokit.domino.apt.client.processors.module.client.presenters;
import com.squareup.javapoet.*;
import org.dominokit.domino.api.client.annotations.StartupTask;
import org.dominokit.domino.api.client.annotations.presenter.*;
import org.dominokit.domino.api.client.events.BaseRoutingAggregator;
import org.dominokit.domino.api.client.events.DefaultEventAggregator;
import org.dominokit.domino.api.client.startup.BaseRoutingStartupTask;
import org.dominokit.domino.apt.client.processors.module.client.presenters.model.DependsOnModel;
import org.dominokit.domino.apt.client.processors.module.client.presenters.model.EventsGroup;
import org.dominokit.domino.apt.commons.AbstractSourceBuilder;
import org.dominokit.domino.apt.commons.DominoTypeBuilder;
import org.dominokit.domino.history.DominoHistory;
import org.dominokit.domino.history.TokenFilter;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.*;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Objects.nonNull;
public class HistoryStartupTaskSourceWriter extends AbstractSourceBuilder {
private final String token;
private final Element presenterElement;
protected HistoryStartupTaskSourceWriter(String token, Element presenterElement, ProcessingEnvironment processingEnv) {
super(processingEnv);
this.token = token;
this.presenterElement = presenterElement;
}
@Override
public List<TypeSpec.Builder> asTypeBuilder() {
String taskClassName = presenterElement.getSimpleName() + "HistoryListenerTask";
TypeSpec.Builder taskType = DominoTypeBuilder.classBuilder(taskClassName, PresenterProcessor.class);
taskType.addAnnotation(StartupTask.class)
.superclass(TypeName.get(BaseRoutingStartupTask.class))
.addMethod(MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addCode(getSuperCall(taskType))
.build());
taskType
.addMethod(getFilterTokenMethod())
.addMethod(getStartupFilterTokenMethod())
.addMethod(onStateReadyMethod());
if (presenterElement.getAnnotation(AutoRoute.class).routeOnce()) {
taskType.addMethod(routOnceMethod());
}
if (!presenterElement.getAnnotation(AutoRoute.class).reRouteActivated()) {
taskType.addMethod(reRouteActivatedMethod());
}
return Collections.singletonList(taskType);
}
private MethodSpec routOnceMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder("isRoutingOnce")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(TypeName.BOOLEAN)
.addStatement("return true");
return method.build();
}
private MethodSpec reRouteActivatedMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder("isReRouteActivated")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(TypeName.BOOLEAN)
.addStatement("return false");
return method.build();
}
private MethodSpec getStartupFilterTokenMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder("getStartupTokenFilter")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(TokenFilter.class);
Optional<String> tokenFilterMethodName = getTokenFilterMethodName(presenterElement, StartupTokenFilter.class);
if (tokenFilterMethodName.isPresent()) {
method.addStatement("return $T." + tokenFilterMethodName.get() + "(\"" + token + "\")", TypeName.get(presenterElement.asType()));
} else {
method.addStatement("return $T." + (token.trim().isEmpty() ? "any()" : "startsWithPathFilter(\"" + token + "\")"), TypeName.get(TokenFilter.class));
}
return method.build();
}
private MethodSpec getFilterTokenMethod() {
MethodSpec.Builder method = MethodSpec.methodBuilder("getTokenFilter")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(TokenFilter.class);
Optional<String> tokenFilterMethodName = getTokenFilterMethodName(presenterElement, RoutingTokenFilter.class);
if (tokenFilterMethodName.isPresent()) {
method.addStatement("return $T." + tokenFilterMethodName.get() + "(\"" + token + "\")", TypeName.get(presenterElement.asType()));
} else {
method.addStatement("return $T." + (token.trim().isEmpty() ? "any()" : "endsWithPathFilter(\"" + token + "\")"), TypeName.get(TokenFilter.class));
}
return method.build();
}
private CodeBlock getSuperCall(TypeSpec.Builder taskType) {
DependsOnModel dependsOnModel = getDependsOnModel();
CodeBlock.Builder codeBlock = CodeBlock.builder();
if (dependsOnModel.getEventsGroups().isEmpty()) {
codeBlock.addStatement("super($T.asList(new $T()))", TypeName.get(Arrays.class), TypeName.get(DefaultEventAggregator.class));
} else {
String superCall = "super($T.asList(" + dependsOnModel.getEventsGroups()
.stream()
.map(eventsGroup -> "new " + "EventsAggregator_" + dependsOnModel.getEventsGroups().indexOf(eventsGroup) + "()")
.collect(Collectors.joining(",")) + "))";
codeBlock.addStatement(superCall, TypeName.get(Arrays.class));
dependsOnModel.getEventsGroups()
.forEach(eventsGroup -> {
TypeSpec.Builder innerAggregator = TypeSpec.classBuilder("EventsAggregator_" + dependsOnModel.getEventsGroups().indexOf(eventsGroup));
innerAggregator
.addModifiers(Modifier.PRIVATE)
.addModifiers(Modifier.STATIC)
.superclass(BaseRoutingAggregator.class)
.addMethod(MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addStatement("super(Arrays.asList(" + eventsGroup.getClassList()
.stream()
.map(typeMirror -> "$T.class")
.collect(Collectors.joining(","))
+ "))", eventsGroup.getClassList().toArray())
.build());
taskType.addType(innerAggregator.build());
});
}
return codeBlock.build();
}
private MethodSpec onStateReadyMethod() {
MethodSpec.Builder onStateReadyBuilder = MethodSpec.methodBuilder("onStateReady")
.addAnnotation(Override.class)
.returns(TypeName.VOID)
.addModifiers(Modifier.PROTECTED)
.addParameter(TypeName.get(DominoHistory.State.class), "state");
CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow(" new $T().onPresenterReady(presenter ->", ClassName.bestGuess(makeRequestClassName()));
codeBlock.addStatement("bindPresenter(presenter)");
List<Element> routingState = processorUtil.getAnnotatedFields(presenterElement.asType(), RoutingState.class);
List<Element> pathParameters = processorUtil.getAnnotatedFields(presenterElement.asType(), PathParameter.class);
List<Element> fragmentParameters = processorUtil.getAnnotatedFields(presenterElement.asType(), FragmentParameter.class);
List<Element> queryParameters = processorUtil.getAnnotatedFields(presenterElement.asType(), QueryParameter.class);
if (!routingState.isEmpty() || !pathParameters.isEmpty() || !fragmentParameters.isEmpty() || !queryParameters.isEmpty()) {
codeBlock.addStatement("presenter.setState(state)");
}
String[] revealConditionMethods = revealConditionMethods();
if (revealConditionMethods.length > 0) {
String methodsCondition = Arrays.stream(revealConditionMethods)
.map(method -> "presenter.$L()")
.collect(Collectors.joining(" && "));
codeBlock.beginControlFlow("if(" + methodsCondition + ")", revealConditionMethods);
}
List<Element> onRoutingMethods = processorUtil.getAnnotatedMethods(presenterElement.asType(), OnRouting.class);
onRoutingMethods.forEach(element -> codeBlock.addStatement("presenter.$L()", element.getSimpleName().toString()));
if (nonNull(presenterElement.getAnnotation(AutoReveal.class))) {
codeBlock.beginControlFlow("if(!presenter.isActivated())");
codeBlock.addStatement("presenter.reveal()");
codeBlock.endControlFlow();
}
if (revealConditionMethods.length > 0) {
codeBlock.endControlFlow();
}
codeBlock.endControlFlow(").send()");
onStateReadyBuilder.addCode(codeBlock.build());
return onStateReadyBuilder.build();
}
private DependsOnModel getDependsOnModel() {
return getDependsOnModel((TypeElement) types.asElement(presenterElement.asType()));
}
private DependsOnModel getDependsOnModel(TypeElement element) {
DependsOnModel dependsOnModel = new DependsOnModel();
TypeMirror superclass = element.getSuperclass();
if (superclass.getKind().equals(TypeKind.NONE)) {
return dependsOnModel;
}
if (nonNull(element.getAnnotation(DependsOn.class))) {
List<? extends AnnotationMirror> annotations = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotations) {
if (types.isSameType(annotationMirror.getAnnotationType(), elements.getTypeElement(DependsOn.class.getName()).asType())) {
Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror.getElementValues();
elementValues.values()
.stream()
.findFirst()
.ifPresent(annotationValue -> {
List<AnnotationMirror> eventsGroupsAnnotations = (List<AnnotationMirror>) annotationValue.getValue();
eventsGroupsAnnotations.stream()
.forEach(eventGroupAnnotationMirror -> {
Collection<? extends AnnotationValue> values = eventGroupAnnotationMirror.getElementValues()
.values();
AnnotationValue groupValue = values.stream().findFirst().get();
List<AnnotationValue> eventTypes = (List<AnnotationValue>) groupValue.getValue();
Iterator<? extends AnnotationValue> iterator = eventTypes.iterator();
List<TypeMirror> eventTypesMirrors = new ArrayList<>();
while (iterator.hasNext()) {
AnnotationValue next = iterator.next();
eventTypesMirrors.add((TypeMirror) next.getValue());
}
if (!eventTypesMirrors.isEmpty()) {
dependsOnModel.addEventGroup(new EventsGroup(eventTypesMirrors));
}
});
});
}
}
return dependsOnModel;
} else {
return getDependsOnModel((TypeElement) types.asElement(element.getSuperclass()));
}
}
private String[] revealConditionMethods() {
List<Element> revealConditionMethods = processorUtil.getAnnotatedMethods(presenterElement.asType(), RevealCondition.class);
if (nonNull(revealConditionMethods) && !revealConditionMethods.isEmpty()) {
String[] methods = new String[revealConditionMethods.size()];
revealConditionMethods.stream().map(element -> element.getSimpleName().toString())
.collect(Collectors.toList())
.toArray(methods);
return methods;
}
return new String[]{};
}
public Optional<String> getTokenFilterMethodName(Element targetElement, Class<? extends Annotation> annotation) {
Optional<String> method = targetElement.getEnclosedElements()
.stream()
.filter(e -> e.getKind().equals(ElementKind.METHOD) && e.getModifiers().contains(Modifier.STATIC) && nonNull(e.getAnnotation(annotation)))
.map(element -> element.getSimpleName().toString())
.findFirst();
TypeMirror superclass = ((TypeElement) targetElement).getSuperclass();
if (superclass.getKind().equals(TypeKind.NONE)) {
return method;
} else {
return method.isPresent() ? method : getTokenFilterMethodName(types.asElement(superclass), annotation);
}
}
private String makeRequestClassName() {
return elements.getPackageOf(presenterElement)
.getQualifiedName().toString()
+ "."
+ presenterElement.getSimpleName().toString()
+ "Command";
}
} |
package com.jme3.gde.core.assets;
import com.jme3.asset.AssetKey;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileAlreadyLockedException;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
/**
*
* @author normenhansen
*/
@SuppressWarnings("unchecked")
public class AssetData extends Properties {
private AssetDataObject file;
private String extension = "jmpdata";
public AssetData(AssetDataObject file) {
this.file = file;
}
public AssetData(AssetDataObject file, String extension) {
this.file = file;
this.extension = extension;
}
public AssetKey<?> getAssetKey() {
return file.getAssetKey();
}
public void setAssetKey(AssetKey key){
file.setAssetKeyData(key);
}
public void setModified(boolean modified){
file.setModified(modified);
}
public void setSaveCookie(SaveCookie cookie){
file.setSaveCookie(cookie);
}
public Object loadAsset() {
return file.loadAsset();
}
public void saveAsset() throws IOException {
file.saveAsset();
}
public void closeAsset(){
file.closeAsset();
}
public List<FileObject> getAssetList(){
return file.getAssetList();
}
public List<AssetKey> getAssetKeyList(){
return file.getAssetKeyList();
}
public List<AssetKey> getFailedList() {
return file.getFailedList();
}
@Override
public synchronized String getProperty(String key) {
return super.getProperty(key);
}
@Override
public synchronized String getProperty(String key, String defaultValue) {
// loadProperties();
return super.getProperty(key, defaultValue);
}
@Override
public synchronized Object setProperty(String key, String value) {
Object obj= super.setProperty(key, value);
// try {
// saveProperties();
// } catch (FileAlreadyLockedException ex) {
// Exceptions.printStackTrace(ex);
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
return obj;
}
public void loadProperties() {
clear();
FileObject myFile = FileUtil.findBrother(file.getPrimaryFile(), extension);
if (myFile == null) {
return;
}
InputStream in = null;
try {
in = myFile.getInputStream();
try {
load(in);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} catch (FileNotFoundException ex) {
Exceptions.printStackTrace(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
}
public void saveProperties() throws FileAlreadyLockedException, IOException {
OutputStream out = null;
FileLock lock = null;
try {
FileObject pFile = file.getPrimaryFile();
FileObject myFile = FileUtil.findBrother(pFile, extension);
if (myFile == null) {
myFile = FileUtil.createData(pFile.getParent(), pFile.getName() + "." + extension);
}
lock = myFile.lock();
out = myFile.getOutputStream(lock);
store(out, "");
} finally {
if (out != null) {
out.close();
}
if (lock != null) {
lock.releaseLock();
}
}
}
public void setExtension(String extension) {
this.extension = extension;
}
} |
package org.trello4j;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.junit.Test;
import org.trello4j.model.Action;
import org.trello4j.model.Card;
import org.trello4j.model.Checklist;
import org.trello4j.model.Member;
import static java.lang.String.format;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author Johan Mynhardt
*/
public class CardServiceTest {
private static final String API_KEY = "23ec668887f03d4c71c7f74fb0ae30a4";
private static final String API_TOKEN = "cfb1df98cbde193b3181e02a8bca9871eaeb8aed0659391f887631055b0b774d";
@Test
public void testCreateCard() {
// GIVEN
String listId = "4f82ed4f1903bae43e66f5fd";
String name = "Trello4J CardService: Add Card using POST";
String description = "Something awesome happened :)";
Map<String, Object> map = new HashMap<String, Object>();
map.put("desc", description);
// WHEN
Card card = new TrelloImpl(API_KEY, API_TOKEN).createCard(listId, name, map);
// THEN
assertNotNull(card);
assertThat(card.getName(), equalTo(name));
assertThat(card.getDesc(), equalTo(description));
}
@Test
public void testCommentOnCard() {
// GIVEN
String idCard = "50429779e215b4e45d7aef24";
String commentText = "Comment text from JUnit test.";
// WHEN
Action action = new TrelloImpl(API_KEY, API_TOKEN).commentOnCard(idCard, commentText);
//THEN
assertNotNull(action);
assertThat(action.getType(), equalTo(Action.TYPE.COMMENT_CARD));
assertThat(action.getData().getText(), equalTo(commentText));
assertThat(action.getData().getCard().getId(), equalTo(idCard));
}
@Test
public void testAttachFileToCard() throws IOException {
// GIVEN
String idCard = "50429779e215b4e45d7aef24";
String fileContents = "foo bar text in file\n";
File file = File.createTempFile("trello_attach_test",".junit");
if (!file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(fileContents);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
fail(e.toString());
}
}
long size = file.length();
String fileName = file.getName();
// WHEN
List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, file, null, null, null);
file.deleteOnExit();
//THEN
assertNotNull(attachments);
Card.Attachment attachment = attachments.get(attachments.size()-1);
assertThat(attachment.getName(), equalTo(fileName));
assertThat(attachment.getBytes(), equalTo("" + size));
}
@Test
public void testAttachFileFromUrl() throws IOException {
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
URL url = new URL("https://trello.com/images/reco/Taco_idle.png");
//WHEN
List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, null, url, "Taco", null);
//THEN
assertNotNull(attachments);
Card.Attachment attachment = attachments.get(attachments.size()-1);
assertNotNull(attachment);
assertThat(attachment.getName(), equalTo("Taco"));
assertTrue(attachment.getUrl().startsWith("http"));
assertTrue(attachment.getUrl().endsWith("Taco_idle.png"));
}
@Test
public void testAddChecklistToCard() throws IOException {
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
//WHEN
Checklist checklist = new TrelloImpl(API_KEY, API_TOKEN).addChecklist(idCard, null, null, null);
//THEN
assertNotNull(checklist);
assertThat(checklist.getName(), equalTo("Checklist"));
assertThat(checklist.getCheckItems().size(), equalTo(0));
}
@Test
public void testAddLabelToCard() throws IOException {
//TODO: prepare for test by removing all labels when the delete method becomes available.
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
//WHEN
List<Card.Label> labels = new TrelloImpl(API_KEY, API_TOKEN).addLabel(idCard, "blue");
//THEN
assertNotNull(labels);
assertThat(labels.get(labels.size() - 1).getColor(), equalTo("blue"));
}
@Test
public void testAddMemberToCard() throws IOException {
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
Trello trello = new TrelloImpl(API_KEY, API_TOKEN);
Member boardUser = trello.getMember("userj");
//PREPARE CARD
List<Member> cardMembers = trello.getMembersByCard(idCard);
if (!cardMembers.isEmpty()) {
for (Member member : cardMembers){
deleteMembersFromCard(idCard, member.getId(), API_KEY, API_TOKEN);
}
}
//WHEN
List<Member> membersAfterAdd = trello.addMember(idCard, boardUser.getId());
//THEN
assertNotNull(membersAfterAdd);
assertThat(membersAfterAdd.size(), equalTo(1));
Member resultMember = membersAfterAdd.get(0);
assertThat(resultMember.getId(), equalTo(boardUser.getId()));
}
@Test
public void addMemberVote() throws IOException {
Trello trello = new TrelloImpl(API_KEY, API_TOKEN);
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
Member boardUser = trello.getMember("userj");
assertNotNull(boardUser);
//CLEANUP
List<Member> votedMembers = trello.getMemberVotesOnCard(idCard);
if (votedMembers != null && !votedMembers.isEmpty()) {
for (Member member : votedMembers) {
trello.deleteVoteFromCard(idCard, member.getId());
}
}
//WHEN
boolean voted = new TrelloImpl(API_KEY, API_TOKEN).voteOnCard(idCard, boardUser.getId());
//THEN
assertTrue(voted);
}
@Test
public void deleteMemberFromCard() throws IOException {
Trello trello = new TrelloImpl(API_KEY, API_TOKEN);
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
Member member = trello.getMember("userj");
//PREPARATION
List<Member> members = trello.getMembersByCard(idCard);
boolean needToAddMember = true;
for (Member cardMember : members) {
if (cardMember.getId().equals(member.getId())) needToAddMember = false;
}
if (needToAddMember) trello.addMember(idCard, member.getId());
//WHEN
boolean removedMemberFromCard = trello.deleteMemberFromCard(idCard, member.getId());
//THEN
assertTrue(removedMemberFromCard);
}
@Test
public void testDeleteMemberVoteFromCard() throws IOException {
Trello trello = new TrelloImpl(API_KEY, API_TOKEN);
//GIVEN
String idCard = "50429779e215b4e45d7aef24";
Member boardUser = trello.getMember("userj");
assertNotNull(boardUser);
boolean addedVote = trello.voteOnCard(idCard, boardUser.getId());
assertTrue(addedVote);
//WHEN
boolean removedFromCard = trello.deleteVoteFromCard(idCard, boardUser.getId());
//THEN
assertTrue(removedFromCard);
}
private void deleteMembersFromCard(String cardId, String memberId, String key, String token) {
Object[] params = new Object[]{
cardId, memberId, key, token
};
try {
HttpsURLConnection urlConnection = (HttpsURLConnection) new URL(
format("https://api.trello.com/1/cards/%s/members/%s?key=%s&token=%s", params)
).openConnection();
urlConnection.setRequestMethod("DELETE");
System.out.println(format("Removing member %s from card %s: HTTP Response: %s/%s",
memberId, cardId, urlConnection.getResponseMessage(), urlConnection.getResponseCode()));
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package com.punchthrough.bean.sdk;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.content.Context;
import com.punchthrough.bean.sdk.internal.ble.GattClient;
import com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile.SerialListener;
import com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
import java.util.List;
public class BeanTest {
GattClient.ConnectionListener testListener;
List<Runnable> handlerRunnables = new ArrayList<>();
// Mocks
Context mockContext;
BluetoothDevice mockDevice;
Handler mockHandler;
GattClient mockGattClient;
GattSerialTransportProfile mockGattSerialTransportProfile;
// Class under test
Bean bean;
@Before
public void setup() {
// Instantiate mocks
mockContext = mock(Context.class);
mockDevice = mock(BluetoothDevice.class);
mockHandler = mock(Handler.class);
mockGattClient = mock(GattClient.class);
mockGattSerialTransportProfile = mock(GattSerialTransportProfile.class);
// Customize some behavior
when(mockGattClient.getSerialProfile()).thenReturn(mockGattSerialTransportProfile);
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
testListener = (GattClient.ConnectionListener) args[0];
return null;
}
}).when(mockGattClient).setListener(any(GattClient.ConnectionListener.class));
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
handlerRunnables.add((Runnable) args[0]);
return null;
}
}).when(mockHandler).post(any(Runnable.class));
// Instantiate class under test
bean = new Bean(mockDevice, mockGattClient, mockHandler);
}
@Test
public void testBeanConnection() {
BeanListener mockListener = mock(BeanListener.class);
bean.connect(mockContext, mockListener);
testListener.onConnected();
for (Runnable r : handlerRunnables) {
r.run();
}
verify(mockListener).onConnected();
}
} |
package seedu.task.testutil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import com.google.common.io.Files;
import guitests.guihandles.TaskCardHandle;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import junit.framework.AssertionFailedError;
import seedu.task.TestApp;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.commons.util.FileUtil;
import seedu.task.commons.util.XmlUtil;
import seedu.task.model.TaskManager;
import seedu.task.model.tag.Tag;
import seedu.task.model.tag.UniqueTagList;
import seedu.task.model.task.TaskName;
import seedu.task.model.task.TaskStatus;
import seedu.task.model.task.TaskTime;
import seedu.task.model.task.Task;
import seedu.task.model.task.TaskDate;
import seedu.task.model.task.ReadOnlyTask;
import seedu.task.storage.XmlSerializableTaskManager;
/**
* A utility class for test cases.
*/
public class TestUtil {
public static final String LS = System.lineSeparator();
/**
* Folder used for temp files created during testing. Ignored by Git.
*/
public static final String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/");
public static final Task[] SAMPLE_TASK_DATA = getSampleTaskData();
public static final Tag[] SAMPLE_TAG_DATA = getSampleTagData();
public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) {
try {
executable.run();
} catch (Throwable actualException) {
if (actualException.getClass().isAssignableFrom(expected)) {
return;
}
String message = String.format("Expected thrown: %s, actual: %s", expected.getName(),
actualException.getClass().getName());
throw new AssertionFailedError(message);
}
throw new AssertionFailedError(
String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName()));
}
private static Task[] getSampleTaskData() {
try {
// CHECKSTYLE.OFF: LineLength
return new Task[] { new Task(new TaskName("Buy cookies"), new TaskDate("200217"), new TaskTime("0800"),
new TaskTime("1000"), new String("Look out for grand lucky draws."), new TaskStatus("Ongoing"),
new UniqueTagList()) };
// CHECKSTYLE.ON: LineLength
} catch (IllegalValueException e) {
assert false;
// not possible
return null;
}
}
private static Tag[] getSampleTagData() {
try {
return new Tag[] { new Tag("relatives"), new Tag("friends") };
} catch (IllegalValueException e) {
assert false;
return null;
// not possible
}
}
public static List<Task> generateSampleTaskData() {
return Arrays.asList(SAMPLE_TASK_DATA);
}
/**
* Appends the file name to the sandbox folder path. Creates the sandbox
* folder if it doesn't exist.
* @param fileName
* @return
*/
public static String getFilePathInSandboxFolder(String fileName) {
try {
FileUtil.createDirs(new File(SANDBOX_FOLDER));
} catch (IOException e) {
throw new RuntimeException(e);
}
return SANDBOX_FOLDER + fileName;
}
public static void createDataFileWithSampleData(String filePath) {
createDataFileWithData(generateSampleStorageTaskManager(), filePath);
}
public static <T> void createDataFileWithData(T data, String filePath) {
try {
File saveFileForTesting = new File(filePath);
FileUtil.createIfMissing(saveFileForTesting);
XmlUtil.saveDataToFile(saveFileForTesting, data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String... s) {
createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING);
}
public static XmlSerializableTaskManager generateSampleStorageTaskManager() {
return new XmlSerializableTaskManager(new TaskManager());
}
/**
* Tweaks the {@code keyCodeCombination} to resolve the
* {@code KeyCode.SHORTCUT} to their respective platform-specific keycodes
*/
public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) {
List<KeyCode> keys = new ArrayList<>();
if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.ALT);
}
if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.SHIFT);
}
if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.META);
}
if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.CONTROL);
}
keys.add(keyCodeCombination.getCode());
return keys.toArray(new KeyCode[] {});
}
public static boolean isHeadlessEnvironment() {
String headlessProperty = System.getProperty("testfx.headless");
return headlessProperty != null && headlessProperty.equals("true");
}
public static void captureScreenShot(String fileName) {
File file = GuiTest.captureScreenshot();
try {
Files.copy(file, new File(fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String descOnFail(Object... comparedObjects) {
return "Comparison failed \n"
+ Arrays.asList(comparedObjects).stream().map(Object::toString).collect(Collectors.joining("\n"));
}
public static void setFinalStatic(Field field, Object newValue)
throws NoSuchFieldException, IllegalAccessException {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
// ~Modifier.FINAL is used to remove the final modifier from field so
// that its value is no longer
// final and can be changed
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void initRuntime() throws TimeoutException {
FxToolkit.registerPrimaryStage();
FxToolkit.hideStage();
}
public static void tearDownRuntime() throws Exception {
FxToolkit.cleanupStages();
}
/**
* Gets private method of a class Invoke the method using
* method.invoke(objectInstance, params...)
*
* Caveat: only find method declared in the current Class, not inherited
* from supertypes
*/
public static Method getPrivateMethod(Class<?> objectClass, String methodName) throws NoSuchMethodException {
Method method = objectClass.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
}
public static void renameFile(File file, String newFileName) {
try {
Files.copy(file, new File(newFileName));
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Gets mid point of a node relative to the screen.
* @param node
* @return
*/
public static Point2D getScreenMidPoint(Node node) {
double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x, y);
}
/**
* Gets mid point of a node relative to its scene.
*
* @param node
* @return
*/
public static Point2D getSceneMidPoint(Node node) {
double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x, y);
}
/**
* Gets the bound of the node relative to the parent scene.
*
* @param node
* @return
*/
public static Bounds getScenePos(Node node) {
return node.localToScene(node.getBoundsInLocal());
}
public static Bounds getScreenPos(Node node) {
return node.localToScreen(node.getBoundsInLocal());
}
public static double getSceneMaxX(Scene scene) {
return scene.getX() + scene.getWidth();
}
public static double getSceneMaxY(Scene scene) {
return scene.getX() + scene.getHeight();
}
public static Object getLastElement(List<?> list) {
return list.get(list.size() - 1);
}
/**
* Removes a subset from the list of tasks.
*
* @param tasks
* The list of tasks
* @param tasksToRemove
* The subset of tasks.
* @return The modified tasks after removal of the subset from tasks.
*/
public static TestTask[] removetasksFromList(final TestTask[] tasks, TestTask... tasksToRemove) {
List<TestTask> listOftasks = asList(tasks);
listOftasks.removeAll(asList(tasksToRemove));
return listOftasks.toArray(new TestTask[listOftasks.size()]);
}
/**
* Returns a copy of the list with the task at specified index removed.
*
* @param list
* original list to copy from
* @param targetIndexInOneIndexedFormat
* e.g. index 1 if the first element is to be removed
*/
public static TestTask[] removeTaskFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) {
return removetasksFromList(list, list[targetIndexInOneIndexedFormat - 1]);
}
/**
* Replaces tasks[i] with a task.
*
* @param tasks
* The array of tasks.
* @param task
* The replacement task
* @param index
* The index of the task to be replaced.
* @return
*/
public static TestTask[] replaceTaskFromList(TestTask[] tasks, TestTask task, int index) {
tasks[index] = task;
return tasks;
}
/**
* Appends tasks to the array of tasks.
*
* @param tasks
* A array of tasks.
* @param tasksToAdd
* The tasks that are to be appended behind the original array.
* @return The modified array of tasks.
*/
public static TestTask[] addTasksToList(final TestTask[] tasks, TestTask... tasksToAdd) {
List<TestTask> listOfTasks = asList(tasks);
listOfTasks.addAll(asList(tasksToAdd));
return listOfTasks.toArray(new TestTask[listOfTasks.size()]);
}
private static <T> List<T> asList(T[] objs) {
List<T> list = new ArrayList<>();
for (T obj : objs) {
list.add(obj);
}
return list;
}
public static boolean compareCardAndTask(TaskCardHandle card, ReadOnlyTask task) {
return card.isSameTask(task);
}
public static Tag[] getTagList(String tags) {
if ("".equals(tags)) {
return new Tag[] {};
}
final String[] split = tags.split(", ");
final List<Tag> collect = Arrays.asList(split).stream().map(e -> {
try {
return new Tag(e.replaceFirst("Tag: ", ""));
} catch (IllegalValueException e1) {
// not possible
assert false;
return null;
}
}).collect(Collectors.toList());
return collect.toArray(new Tag[split.length]);
}
} |
package com.github.bednar.test;
import javax.annotation.Nonnull;
import javax.servlet.ServletContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.LifecycleUtils;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.util.WebUtils;
import org.mockito.Mockito;
public final class SecurityInit
{
private static final SecurityInit instance = new SecurityInit();
private SecurityInit()
{
}
/**
* @return singleton instance {@code SecurityInit}
*/
@Nonnull
public static SecurityInit build()
{
return instance;
}
/**
* @param jetty with {@link ServletContext}
*
* @see #bindSecurityManager(javax.servlet.ServletContext)
*/
@Nonnull
public SecurityInit bindSecurityManager(@Nonnull final EmbeddedJetty jetty)
{
return bindSecurityManager(jetty.getServletContext());
}
/**
* Bind {@link org.apache.shiro.web.mgt.WebSecurityManager} to actual {@link Thread}.
*
* @param context Servlet Context
*
* @return this
*/
@Nonnull
public SecurityInit bindSecurityManager(@Nonnull final ServletContext context)
{
SecurityManager securityManager = WebUtils
.getRequiredWebEnvironment(context).getWebSecurityManager();
SecurityUtils.setSecurityManager(securityManager);
return this;
}
/**
* Unbind and destroy {@link SecurityManager} binded on actual {@link Thread}.
*
* @return this
*/
@Nonnull
public SecurityInit unBindSecurityManager()
{
SecurityManager securityManager = SecurityUtils.getSecurityManager();
LifecycleUtils.destroy(securityManager);
SecurityUtils.setSecurityManager(null);
return this;
}
/**
* Create authenticated {@link Subject}
*
* @param principal username
*
* @return this
*/
@Nonnull
public SecurityInit buildSubject(@Nonnull final String principal)
{
Subject subject = Mockito.mock(Subject.class);
Mockito.when(subject.isAuthenticated()).thenReturn(true);
Mockito.when(subject.getPrincipal()).thenReturn(principal);
ThreadContext.bind(subject);
return this;
}
/**
* Logout actual {@link Subject}
*
* @return this
*/
@Nonnull
public SecurityInit destroySubject()
{
Subject subject = SecurityUtils.getSubject();
subject.logout();
ThreadContext.bind(subject);
return this;
}
} |
package unit.ui;
import kernel.Kernel;
import kernel.views.CommPortReporter;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.springframework.context.annotation.*;
import ui.UserInterfaceConfiguration;
import java.util.ArrayList;
import java.util.List;
/**
* Responsible for producing mock beans for the dependencies for this
* application
*/
@Configuration
@Import(UserInterfaceConfiguration.class)
@Lazy
public class TestingConfiguration {
/**
* A stub representing {@link kernel.Kernel}
*/
private volatile Kernel mockKernel;
/**
* The context in which mock beans are to be created
*/
private volatile Mockery mockingContext;
/**
* @return The context in which mockery is to take place
*/
@Bean
@Scope("singleton")
public Mockery mockingContext(){
if(mockingContext == null) {
mockingContext = new SynchronizedJUnit4Mockery();
}
return mockingContext;
}
/**
* @return A list containing data of serial ports
*/
@Bean
public static List<String> testData(){
List<String> testData = new ArrayList<>();
testData.add("/dev/ttyUSB0");
return testData;
}
/**
* @return A mock reporter for returning serial port names
*/
@Bean
@Scope("singleton")
public CommPortReporter portReporter(){
return mockingContext().mock(CommPortReporter.class);
}
/**
* @return A mock kernel
*/
@Bean
@Scope("singleton")
public Kernel kernel(){
mockKernel = mockingContext().mock(Kernel.class);
mockingContext().checking(new ExpectationsForKernel());
return mockKernel;
}
/**
* The mockery that is to be used. This is an extension of the
* traditional {@link JUnit4Mockery}, but with a {@link Synchroniser} to
* manage access to mock objects across threads
*/
private class SynchronizedJUnit4Mockery extends JUnit4Mockery {
/**
* Creates the mockery
*/
public SynchronizedJUnit4Mockery(){
setThreadingPolicy(new Synchroniser());
}
}
/**
* Defines the default allowed behaviour out of the stubbed-out
* {@link kernel.Kernel}.
*/
private class ExpectationsForKernel extends Expectations {
/**
* Set up the required behaviours
*/
public ExpectationsForKernel(){
expectationsForPortReporter();
expectationsForSerialPortNames();
}
/**
* Defines allowed behaviour for {@link Kernel#getCommPortReporter()}
*/
private void expectationsForPortReporter(){
allowing(mockKernel).getCommPortReporter();
}
/**
* Defines allowed behaviour for
* {@link CommPortReporter#getSerialPortNames()}
*/
private void expectationsForSerialPortNames(){
allowing(portReporter()).getSerialPortNames();
will(returnValue(testData()));
}
}
} |
package com.github.davidmoten.rtree;
import static com.google.common.base.Optional.of;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import rx.Subscriber;
import rx.functions.Func1;
import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.geometry.ListPair;
import com.github.davidmoten.rtree.geometry.Rectangle;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
final class NonLeaf<T, S extends Geometry> implements Node<T, S> {
private final List<? extends Node<T, S>> children;
private final Rectangle mbr;
private final Context context;
NonLeaf(List<? extends Node<T, S>> children, Context context) {
Preconditions.checkArgument(!children.isEmpty());
this.context = context;
this.children = children;
this.mbr = Util.mbr(children);
}
@Override
public Geometry geometry() {
return mbr;
}
@Override
public void search(Func1<? super Geometry, Boolean> criterion,
Subscriber<? super Entry<T, S>> subscriber) {
if (!criterion.call(this.geometry().mbr()))
return;
for (final Node<T, S> child : children) {
if (subscriber.isUnsubscribed())
return;
else
child.search(criterion, subscriber);
}
}
@Override
public int count() {
return children.size();
}
List<? extends Node<T, S>> children() {
return children;
}
@Override
public List<Node<T, S>> add(Entry<? extends T, ? extends S> entry) {
final Node<T, S> child = context.selector().select(entry.geometry().mbr(), children);
List<Node<T, S>> list = child.add(entry);
List<? extends Node<T, S>> children2 = Util.replace(children, child, list);
if (children2.size() <= context.maxChildren())
return Collections.singletonList((Node<T, S>) new NonLeaf<T, S>(children2, context));
else {
ListPair<? extends Node<T, S>> pair = context.splitter().split(children2,
context.minChildren());
return makeNonLeaves(pair);
}
}
private List<Node<T, S>> makeNonLeaves(ListPair<? extends Node<T, S>> pair) {
List<Node<T, S>> list = new ArrayList<Node<T, S>>();
list.add(new NonLeaf<T, S>(pair.group1().list(), context));
list.add(new NonLeaf<T, S>(pair.group2().list(), context));
return list;
}
@Override
public NodeAndEntries<T, S> delete(Entry<? extends T, ? extends S> entry, boolean all) {
// the result of performing a delete of the given entry from this node
// will be that zero or more entries will be needed to be added back to
// the root of the tree (because num entries of their node fell below
// minChildren),
// zero or more children will need to be removed from this node,
// zero or more nodes to be added as children to this node(because
// entries have been deleted from them and they still have enough
// members to be active)
List<Entry<T, S>> addTheseEntries = new ArrayList<Entry<T, S>>();
List<Node<T, S>> removeTheseNodes = new ArrayList<Node<T, S>>();
List<Node<T, S>> addTheseNodes = new ArrayList<Node<T, S>>();
int countDeleted = 0;
for (final Node<T, S> child : children) {
if (entry.geometry().intersects(child.geometry().mbr())) {
final NodeAndEntries<T, S> result = child.delete(entry, all);
if (result.node().isPresent()) {
if (result.node().get() != child) {
// deletion occurred and child is above minChildren so
// we update it
addTheseNodes.add(result.node().get());
removeTheseNodes.add(child);
addTheseEntries.addAll(result.entriesToAdd());
countDeleted += result.countDeleted();
if (!all)
break;
}
// else nothing was deleted from that child
} else {
// deletion occurred and brought child below minChildren
// so we redistribute its entries
removeTheseNodes.add(child);
addTheseEntries.addAll(result.entriesToAdd());
countDeleted += result.countDeleted();
if (!all)
break;
}
}
}
if (removeTheseNodes.isEmpty())
return new NodeAndEntries<T, S>(of(this), Collections.<Entry<T, S>> emptyList(), 0);
else {
List<Node<T, S>> nodes = Util.remove(children, removeTheseNodes);
nodes.addAll(addTheseNodes);
if (nodes.size() == 0)
return new NodeAndEntries<T, S>(Optional.<Node<T, S>> absent(), addTheseEntries,
countDeleted);
else {
NonLeaf<T, S> node = new NonLeaf<T, S>(nodes, context);
return new NodeAndEntries<T, S>(of(node), addTheseEntries, countDeleted);
}
}
}
} |
package org.apache.lucene.index;
import junit.framework.TestCase;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.search.DefaultSimilarity;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* Test that norms info is preserved during index life - including
* separate norms, addDocument, addIndexes, optimize.
*/
public class TestNorms extends TestCase {
private class SimilarityOne extends DefaultSimilarity {
public float lengthNorm(String fieldName, int numTerms) {
return 1;
}
}
private static final int NUM_FIELDS = 10;
private Similarity similarityOne;
private Analyzer anlzr;
private int numDocNorms;
private ArrayList norms;
private ArrayList modifiedNorms;
private float lastNorm = 0;
private float normDelta = (float) 0.001;
public TestNorms(String s) {
super(s);
}
protected void setUp() throws IOException {
similarityOne = new SimilarityOne();
anlzr = new StandardAnalyzer();
}
protected void tearDown() throws IOException {
}
/**
* Test that norms values are preserved as the index is maintained.
* Including separate norms.
* Including merging indexes with seprate norms.
* Including optimize.
*/
public void testNorms() throws IOException {
// tmp dir
String tempDir = System.getProperty("java.io.tmpdir");
if (tempDir == null) {
throw new IOException("java.io.tmpdir undefined, cannot run test");
}
// test with a single index: index1
File indexDir1 = new File(tempDir, "lucenetestindex1");
Directory dir1 = FSDirectory.getDirectory(indexDir1);
norms = new ArrayList();
modifiedNorms = new ArrayList();
createIndex(dir1);
doTestNorms(dir1);
// test with a single index: index2
ArrayList norms1 = norms;
ArrayList modifiedNorms1 = modifiedNorms;
int numDocNorms1 = numDocNorms;
norms = new ArrayList();
modifiedNorms = new ArrayList();
numDocNorms = 0;
File indexDir2 = new File(tempDir, "lucenetestindex2");
Directory dir2 = FSDirectory.getDirectory(indexDir2);
createIndex(dir2);
doTestNorms(dir2);
// add index1 and index2 to a third index: index3
File indexDir3 = new File(tempDir, "lucenetestindex3");
Directory dir3 = FSDirectory.getDirectory(indexDir3);
createIndex(dir3);
IndexWriter iw = new IndexWriter(dir3,anlzr,false);
iw.setMaxBufferedDocs(5);
iw.setMergeFactor(3);
iw.addIndexes(new Directory[]{dir1,dir2});
iw.close();
norms1.addAll(norms);
norms = norms1;
modifiedNorms1.addAll(modifiedNorms);
modifiedNorms = modifiedNorms1;
numDocNorms += numDocNorms1;
// test with index3
verifyIndex(dir3);
doTestNorms(dir3);
// now with optimize
iw = new IndexWriter(dir3,anlzr,false);
iw.setMaxBufferedDocs(5);
iw.setMergeFactor(3);
iw.optimize();
iw.close();
verifyIndex(dir3);
dir1.close();
dir2.close();
dir3.close();
}
private void doTestNorms(Directory dir) throws IOException {
for (int i=0; i<5; i++) {
addDocs(dir,12,true);
verifyIndex(dir);
modifyNormsForF1(dir);
verifyIndex(dir);
addDocs(dir,12,false);
verifyIndex(dir);
modifyNormsForF1(dir);
verifyIndex(dir);
}
}
private void createIndex(Directory dir) throws IOException {
IndexWriter iw = new IndexWriter(dir,anlzr,true);
iw.setMaxBufferedDocs(5);
iw.setMergeFactor(3);
iw.setSimilarity(similarityOne);
iw.setUseCompoundFile(true);
iw.close();
}
private void modifyNormsForF1(Directory dir) throws IOException {
IndexReader ir = IndexReader.open(dir);
int n = ir.maxDoc();
for (int i = 0; i < n; i+=3) { // modify for every third doc
int k = (i*3) % modifiedNorms.size();
float origNorm = ((Float)modifiedNorms.get(i)).floatValue();
float newNorm = ((Float)modifiedNorms.get(k)).floatValue();
//System.out.println("Modifying: for "+i+" from "+origNorm+" to "+newNorm);
//System.out.println(" and: for "+k+" from "+newNorm+" to "+origNorm);
modifiedNorms.set(i, new Float(newNorm));
modifiedNorms.set(k, new Float(origNorm));
ir.setNorm(i, "f"+1, newNorm);
ir.setNorm(k, "f"+1, origNorm);
}
ir.close();
}
private void verifyIndex(Directory dir) throws IOException {
IndexReader ir = IndexReader.open(dir);
for (int i = 0; i < NUM_FIELDS; i++) {
String field = "f"+i;
byte b[] = ir.norms(field);
assertEquals("number of norms mismatches",numDocNorms,b.length);
ArrayList storedNorms = (i==1 ? modifiedNorms : norms);
for (int j = 0; j < b.length; j++) {
float norm = Similarity.decodeNorm(b[j]);
float norm1 = ((Float)storedNorms.get(j)).floatValue();
assertEquals("stored norm value of "+field+" for doc "+j+" is "+norm+" - a mismatch!", norm, norm1, 0.000001);
}
}
}
private void addDocs(Directory dir, int ndocs, boolean compound) throws IOException {
IndexWriter iw = new IndexWriter(dir,anlzr,false);
iw.setMaxBufferedDocs(5);
iw.setMergeFactor(3);
iw.setSimilarity(similarityOne);
iw.setUseCompoundFile(compound);
for (int i = 0; i < ndocs; i++) {
iw.addDocument(newDoc());
}
iw.close();
}
// create the next document
private Document newDoc() {
Document d = new Document();
float boost = nextNorm();
for (int i = 0; i < 10; i++) {
Field f = new Field("f"+i,"v"+i,Store.NO,Index.UN_TOKENIZED);
f.setBoost(boost);
d.add(f);
}
return d;
}
// return unique norm values that are unchanged by encoding/decoding
private float nextNorm() {
float norm = lastNorm + normDelta;
do {
float norm1 = Similarity.decodeNorm(Similarity.encodeNorm(norm));
if (norm1 > lastNorm) {
//System.out.println(norm1+" > "+lastNorm);
norm = norm1;
break;
}
norm += normDelta;
} while (true);
norms.add(numDocNorms, new Float(norm));
modifiedNorms.add(numDocNorms, new Float(norm));
//System.out.println("creating norm("+numDocNorms+"): "+norm);
numDocNorms ++;
lastNorm = (norm>10 ? 0 : norm); //there's a limit to how many distinct values can be stored in a ingle byte
return norm;
}
} |
package com.graph.db.output;
import static com.graph.db.util.Constants.COLON;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.graph.db.file.annotation.domain.Exac;
import com.graph.db.file.annotation.domain.GeneticVariant;
import com.graph.db.file.annotation.domain.TranscriptConsequence;
import com.graph.db.util.Constants;
import com.graph.db.util.FileUtil;
public class HeaderGenerator {
public void generateHeaders(String outputFolder, Set<OutputFileType> set) {
for (OutputFileType outputFileType : set) {
String joinedHeaders = StringUtils.join(outputFileType.getHeader(), Constants.COMMA);
joinedHeaders = relabelIdColumns(outputFileType, joinedHeaders);
joinedHeaders = relabelNonStringTypes(joinedHeaders);
FileUtil.writeOutCsvHeader(outputFolder, outputFileType.getFileTag(), Arrays.asList(joinedHeaders));
}
}
private String relabelIdColumns(OutputFileType outputFileType, String joinedHeaders) {
switch(outputFileType) {
case GENETIC_VARIANT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "variant_id", "variantId:ID(GeneticVariant)");
break;
case GENE_TO_GENETIC_VARIANT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "left", ":START_ID(Gene)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "right", ":END_ID(GeneticVariant)");
break;
case GENE_TO_TERM:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "gene_id", ":START_ID(Gene)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "HPO-ID", ":END_ID(Term)");
break;
case TRANSCRIPT_VARIANT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "hgvsc", "hgvsc:ID(TranscriptVariant)");
break;
case GENETIC_VARIANT_TO_TRANSCRIPT_VARIANT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "variant_id", ":START_ID(GeneticVariant)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "hgvsc", ":END_ID(TranscriptVariant)");
break;
case TRANSCRIPT_TO_TRANSCRIPT_VARIANT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "transcript_id", ":START_ID(Transcript)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "hgvsc", ":END_ID(TranscriptVariant)");
break;
case CONSEQUENCE_TERM:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "this", "consequenceTerm:ID(ConsequenceTerm)");
break;
case TRANSCRIPT_VARIANT_TO_CONSEQUENCE_TERM:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "left", ":START_ID(TranscriptVariant)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "right", ":END_ID(ConsequenceTerm)");
break;
case GENE:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "gene_id", "gene_id:ID(Gene)");
break;
case TRANSCRIPT:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "transcript_id", "transcript_id:ID(Transcript)");
break;
case TRANSCRIPT_TO_GENE:
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "transcript_id", ":START_ID(Transcript)");
joinedHeaders = StringUtils.replaceOnce(joinedHeaders, "gene_id", ":END_ID(Gene)");
break;
default:
throw new IllegalStateException("Unknown outputFileType: " + outputFileType);
}
return joinedHeaders;
}
private String relabelNonStringTypes(String joinedHeaders) {
Map<String, String> nameToGraphType = createMapFromJavaTypeToGraphType();
for (Entry<String, String> entry : nameToGraphType.entrySet()) {
joinedHeaders = StringUtils.replace(joinedHeaders, entry.getKey(), entry.getValue());
}
return joinedHeaders;
}
private Map<String, String> createMapFromJavaTypeToGraphType() {
Map<String, String> nameToGraphType = new HashMap<>();
for (Class<?> c : Arrays.asList(GeneticVariant.class, Exac.class, TranscriptConsequence.class)) {
for (Field field : c.getDeclaredFields()) {
String name = field.getName();
switch (field.getType().getName()) {
case "java.lang.Integer":
nameToGraphType.put(name, name + COLON + "int");
break;
case "java.lang.Double":
nameToGraphType.put(name, name + COLON + "double");
break;
case "java.lang.Boolean":
nameToGraphType.put(name, name + COLON + "boolean");
break;
}
}
}
return nameToGraphType;
}
} |
package com.hankcs.hanlp.seg.CRF;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.algoritm.Viterbi;
import com.hankcs.hanlp.collection.trie.bintrie.BinTrie;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.dictionary.CoreDictionary;
import com.hankcs.hanlp.dictionary.CoreDictionaryTransformMatrixDictionary;
import com.hankcs.hanlp.dictionary.other.CharTable;
import com.hankcs.hanlp.model.CRFSegmentModel;
import com.hankcs.hanlp.model.crf.CRFModel;
import com.hankcs.hanlp.model.crf.FeatureFunction;
import com.hankcs.hanlp.model.crf.Table;
import com.hankcs.hanlp.seg.CharacterBasedGenerativeModelSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.seg.common.Vertex;
import com.hankcs.hanlp.utility.CharacterHelper;
import com.hankcs.hanlp.utility.GlobalObjectPool;
import java.util.*;
import static com.hankcs.hanlp.utility.Predefine.logger;
/**
* CRF
*
* @author hankcs
*/
public class CRFSegment extends CharacterBasedGenerativeModelSegment
{
private CRFModel crfModel;
public CRFSegment(CRFSegmentModel crfModel)
{
this.crfModel = crfModel;
}
public CRFSegment(String modelPath)
{
crfModel = GlobalObjectPool.get(modelPath);
if (crfModel != null)
{
return;
}
logger.info("CRF " + modelPath);
long start = System.currentTimeMillis();
crfModel = CRFModel.loadTxt(modelPath, new CRFSegmentModel(new BinTrie<FeatureFunction>()));
if (crfModel == null)
{
String error = "CRF " + modelPath + " " + (System.currentTimeMillis() - start) + " ms";
logger.severe(error);
throw new IllegalArgumentException(error);
}
else
logger.info("CRF " + modelPath + " " + (System.currentTimeMillis() - start) + " ms");
GlobalObjectPool.put(modelPath, crfModel);
}
public CRFSegment()
{
this(HanLP.Config.CRFSegmentModelPath);
}
@Override
protected List<Term> segSentence(char[] sentence)
{
if (sentence.length == 0) return Collections.emptyList();
char[] sentenceConverted = CharTable.convert(sentence);
Table table = new Table();
table.v = atomSegmentToTable(sentenceConverted);
crfModel.tag(table);
List<Term> termList = new LinkedList<Term>();
if (HanLP.Config.DEBUG)
{
System.out.println("CRF");
System.out.println(table);
}
int offset = 0;
OUTER:
for (int i = 0; i < table.v.length; offset += table.v[i][1].length(), ++i)
{
String[] line = table.v[i];
switch (line[2].charAt(0))
{
case 'B':
{
int begin = offset;
while (table.v[i][2].charAt(0) != 'E')
{
offset += table.v[i][1].length();
++i;
if (i == table.v.length)
{
break;
}
}
if (i == table.v.length)
{
termList.add(new Term(new String(sentence, begin, offset - begin), null));
break OUTER;
}
else
termList.add(new Term(new String(sentence, begin, offset - begin + table.v[i][1].length()), null));
}
break;
default:
{
termList.add(new Term(new String(sentence, offset, table.v[i][1].length()), null));
}
break;
}
}
if (config.speechTagging)
{
List<Vertex> vertexList = toVertexList(termList, true);
Viterbi.compute(vertexList, CoreDictionaryTransformMatrixDictionary.transformMatrixDictionary);
int i = 0;
for (Term term : termList)
{
if (term.nature != null) term.nature = vertexList.get(i + 1).guessNature();
++i;
}
}
if (config.useCustomDictionary)
{
List<Vertex> vertexList = toVertexList(termList, false);
combineByCustomDictionary(vertexList);
termList = toTermList(vertexList, config.offset);
}
return termList;
}
private static List<Vertex> toVertexList(List<Term> termList, boolean appendStart)
{
ArrayList<Vertex> vertexList = new ArrayList<Vertex>(termList.size() + 1);
if (appendStart) vertexList.add(Vertex.B);
for (Term term : termList)
{
CoreDictionary.Attribute attribute = CoreDictionary.get(term.word);
if (attribute == null)
{
if (term.word.trim().length() == 0) attribute = new CoreDictionary.Attribute(Nature.x);
else attribute = new CoreDictionary.Attribute(Nature.nz);
}
else term.nature = attribute.nature[0];
Vertex vertex = new Vertex(term.word, attribute);
vertexList.add(vertex);
}
return vertexList;
}
/**
*
*
* @param vertexList
* @param offsetEnabled offset
* @return
*/
protected static List<Term> toTermList(List<Vertex> vertexList, boolean offsetEnabled)
{
assert vertexList != null;
int length = vertexList.size();
List<Term> resultList = new ArrayList<Term>(length);
Iterator<Vertex> iterator = vertexList.iterator();
if (offsetEnabled)
{
int offset = 0;
for (int i = 0; i < length; ++i)
{
Vertex vertex = iterator.next();
Term term = convert(vertex);
term.offset = offset;
offset += term.length();
resultList.add(term);
}
}
else
{
for (int i = 0; i < length; ++i)
{
Vertex vertex = iterator.next();
Term term = convert(vertex);
resultList.add(term);
}
}
return resultList;
}
/**
* term
*
* @param vertex
* @return
*/
private static Term convert(Vertex vertex)
{
return new Term(vertex.realWord, vertex.guessNature());
}
public static List<String> atomSegment(char[] sentence)
{
List<String> atomList = new ArrayList<String>(sentence.length);
final int maxLen = sentence.length - 1;
final StringBuilder sbAtom = new StringBuilder();
out:
for (int i = 0; i < sentence.length; i++)
{
if (sentence[i] >= '0' && sentence[i] <= '9')
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
break;
}
char c = sentence[++i];
while (c == '.' || c == '%' || (c >= '0' && c <= '9'))
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
break out;
}
c = sentence[++i];
}
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
--i;
}
else if (CharacterHelper.isEnglishLetter(sentence[i]))
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
break;
}
char c = sentence[++i];
while (CharacterHelper.isEnglishLetter(c))
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
break out;
}
c = sentence[++i];
}
atomList.add(sbAtom.toString());
sbAtom.setLength(0);
--i;
}
else
{
atomList.add(String.valueOf(sentence[i]));
}
}
return atomList;
}
public static String[][] atomSegmentToTable(char[] sentence)
{
String table[][] = new String[sentence.length][3];
int size = 0;
final int maxLen = sentence.length - 1;
final StringBuilder sbAtom = new StringBuilder();
out:
for (int i = 0; i < sentence.length; i++)
{
if (sentence[i] >= '0' && sentence[i] <= '9')
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
table[size][0] = "M";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
break;
}
char c = sentence[++i];
while (c == '.' || c == '%' || (c >= '0' && c <= '9'))
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
table[size][0] = "M";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
break out;
}
c = sentence[++i];
}
table[size][0] = "M";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
--i;
}
else if (CharacterHelper.isEnglishLetter(sentence[i]) || sentence[i] == ' ')
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
table[size][0] = "W";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
break;
}
char c = sentence[++i];
while (CharacterHelper.isEnglishLetter(c) || c == ' ')
{
sbAtom.append(sentence[i]);
if (i == maxLen)
{
table[size][0] = "W";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
break out;
}
c = sentence[++i];
}
table[size][0] = "W";
table[size][1] = sbAtom.toString();
++size;
sbAtom.setLength(0);
--i;
}
else
{
table[size][0] = table[size][1] = String.valueOf(sentence[i]);
++size;
}
}
return resizeArray(table, size);
}
/**
*
*
* @param array
* @param size
* @return
*/
private static String[][] resizeArray(String[][] array, int size)
{
String[][] nArray = new String[size][];
System.arraycopy(array, 0, nArray, 0, size);
return nArray;
}
@Override
public Segment enableNumberQuantifierRecognize(boolean enable)
{
throw new UnsupportedOperationException("");
// enablePartOfSpeechTagging(enable);
// return super.enableNumberQuantifierRecognize(enable);
}
} |
package io.rsocket.loadbalance;
import io.rsocket.Availability;
import io.rsocket.loadbalance.stat.Ewma;
import io.rsocket.loadbalance.stat.FrugalQuantile;
import io.rsocket.loadbalance.stat.Median;
import io.rsocket.loadbalance.stat.Quantile;
import io.rsocket.util.Clock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
public class Stats implements Availability {
private static final double DEFAULT_LOWER_QUANTILE = 0.5;
private static final double DEFAULT_HIGHER_QUANTILE = 0.8;
private static final int INACTIVITY_FACTOR = 500;
private static final long DEFAULT_INITIAL_INTER_ARRIVAL_TIME =
Clock.unit().convert(1L, TimeUnit.SECONDS);
private static final double STARTUP_PENALTY = Long.MAX_VALUE >> 12;
private final Quantile lowerQuantile;
private final Quantile higherQuantile;
private final Ewma errorPercentage;
private final Median median;
private final Ewma interArrivalTime;
private final long tau;
private final long inactivityFactor;
private long errorStamp; // last we got an error
private long stamp; // last timestamp we sent a request
private long stamp0; // last timestamp we sent a request or receive a response
private long duration; // instantaneous cumulative duration
private double availability = 1.0;
private volatile int pending; // instantaneous rate
private volatile long pendingStreams; // number of active streams
private static final AtomicLongFieldUpdater<Stats> PENDING_STREAMS =
AtomicLongFieldUpdater.newUpdater(Stats.class, "pendingStreams");
private Stats() {
this(
new FrugalQuantile(DEFAULT_LOWER_QUANTILE),
new FrugalQuantile(DEFAULT_HIGHER_QUANTILE),
INACTIVITY_FACTOR);
}
private Stats(Quantile lowerQuantile, Quantile higherQuantile, long inactivityFactor) {
this.lowerQuantile = lowerQuantile;
this.higherQuantile = higherQuantile;
this.inactivityFactor = inactivityFactor;
long now = Clock.now();
this.stamp = now;
this.errorStamp = now;
this.stamp0 = now;
this.duration = 0L;
this.pending = 0;
this.median = new Median();
this.interArrivalTime = new Ewma(1, TimeUnit.MINUTES, DEFAULT_INITIAL_INTER_ARRIVAL_TIME);
this.errorPercentage = new Ewma(5, TimeUnit.SECONDS, 1.0);
this.tau = Clock.unit().convert((long) (5 / Math.log(2)), TimeUnit.SECONDS);
}
public double errorPercentage() {
return errorPercentage.value();
}
public double medianLatency() {
return median.estimation();
}
public double lowerQuantileLatency() {
return lowerQuantile.estimation();
}
public double higherQuantileLatency() {
return higherQuantile.estimation();
}
public double interArrivalTime() {
return interArrivalTime.value();
}
public int pending() {
return pending;
}
public long lastTimeUsedMillis() {
return stamp0;
}
@Override
public double availability() {
if (Clock.now() - stamp > tau) {
recordError(1.0);
}
return availability * errorPercentage.value();
}
public synchronized double predictedLatency() {
long now = Clock.now();
long elapsed = Math.max(now - stamp, 1L);
double weight;
double prediction = median.estimation();
if (prediction == 0.0) {
if (pending == 0) {
weight = 0.0; // first request
} else {
// subsequent requests while we don't have any history
weight = STARTUP_PENALTY + pending;
}
} else if (pending == 0 && elapsed > inactivityFactor * interArrivalTime.value()) {
// if we did't see any data for a while, we decay the prediction by inserting
// artificial 0.0 into the median
median.insert(0.0);
weight = median.estimation();
} else {
double predicted = prediction * pending;
double instant = instantaneous(now);
if (predicted < instant) { // NB: (0.0 < 0.0) == false
weight = instant / pending; // NB: pending never equal 0 here
} else {
// we are under the predictions
weight = prediction;
}
}
return weight;
}
synchronized long instantaneous(long now) {
return duration + (now - stamp0) * pending;
}
public void startStream() {
PENDING_STREAMS.incrementAndGet(this);
}
public void stopStream() {
PENDING_STREAMS.decrementAndGet(this);
}
public synchronized long startRequest() {
long now = Clock.now();
interArrivalTime.insert(now - stamp);
duration += Math.max(0, now - stamp0) * pending;
pending += 1;
stamp = now;
stamp0 = now;
return now;
}
public synchronized long stopRequest(long timestamp) {
long now = Clock.now();
duration += Math.max(0, now - stamp0) * pending - (now - timestamp);
pending -= 1;
stamp0 = now;
return now;
}
public synchronized void record(double roundTripTime) {
median.insert(roundTripTime);
lowerQuantile.insert(roundTripTime);
higherQuantile.insert(roundTripTime);
}
public synchronized void recordError(double value) {
errorPercentage.insert(value);
errorStamp = Clock.now();
}
public void setAvailability(double availability) {
this.availability = availability;
}
@Override
public String toString() {
return "Stats{"
+ "lowerQuantile="
+ lowerQuantile.estimation()
+ ", higherQuantile="
+ higherQuantile.estimation()
+ ", inactivityFactor="
+ inactivityFactor
+ ", tau="
+ tau
+ ", errorPercentage="
+ errorPercentage.value()
+ ", pending="
+ pending
+ ", errorStamp="
+ errorStamp
+ ", stamp="
+ stamp
+ ", stamp0="
+ stamp0
+ ", duration="
+ duration
+ ", median="
+ median.estimation()
+ ", interArrivalTime="
+ interArrivalTime.value()
+ ", pendingStreams="
+ pendingStreams
+ ", availability="
+ availability
+ '}';
}
private static final class NoOpsStats extends Stats {
static final Stats INSTANCE = new NoOpsStats();
private NoOpsStats() {}
@Override
public double errorPercentage() {
return 0.0d;
}
@Override
public double medianLatency() {
return 0.0d;
}
@Override
public double lowerQuantileLatency() {
return 0.0d;
}
@Override
public double higherQuantileLatency() {
return 0.0d;
}
@Override
public double interArrivalTime() {
return 0;
}
@Override
public int pending() {
return 0;
}
@Override
public long lastTimeUsedMillis() {
return 0;
}
@Override
public double availability() {
return 1.0d;
}
@Override
public double predictedLatency() {
return 0.0d;
}
@Override
long instantaneous(long now) {
return 0;
}
@Override
public void startStream() {}
@Override
public void stopStream() {}
@Override
public long startRequest() {
return 0;
}
@Override
public long stopRequest(long timestamp) {
return 0;
}
@Override
public void record(double roundTripTime) {}
@Override
public void recordError(double value) {}
@Override
public String toString() {
return "NoOpsStats{}";
}
}
public static Stats noOps() {
return NoOpsStats.INSTANCE;
}
public static Stats create() {
return new Stats();
}
public static Stats create(
Quantile lowerQuantile, Quantile higherQuantile, long inactivityFactor) {
return new Stats(lowerQuantile, higherQuantile, inactivityFactor);
}
} |
package com.herb.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
private static Logger logger = LogManager.getLogger(LoginController.class);
@RequestMapping("/login")
private String login(){
logger.info("start to login");
return "home";
}
} |
package org.objectweb.proactive.ic2d.jmxmonitoring.figure.listener;
import java.util.Iterator;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.ZoomInAction;
import org.eclipse.gef.ui.actions.ZoomOutAction;
import org.eclipse.jface.action.IAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.KillVMAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.RefreshJVMAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.StopMonitoringAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.data.RuntimeObject;
import org.objectweb.proactive.ic2d.jmxmonitoring.dnd.DragAndDrop;
import org.objectweb.proactive.ic2d.jmxmonitoring.extpoint.IActionExtPoint;
import org.objectweb.proactive.ic2d.jmxmonitoring.view.MonitoringView;
public class JVMListener implements MouseListener, MouseMotionListener {
private ActionRegistry registry;
private RuntimeObject jvm;
private DragAndDrop dnd;
public JVMListener(RuntimeObject jvm, MonitoringView monitoringView) {
this.registry = monitoringView.getGraphicalViewer().getActionRegistry();
this.dnd = monitoringView.getDragAndDrop();
this.jvm = jvm;
}
public void mouseDoubleClicked(MouseEvent me) { /* Do nothing */
}
public void mousePressed(MouseEvent me) {
if (me.button == 1) {
dnd.reset();
// for(Iterator<IAction> action = (Iterator<IAction>) registry.getActions() ; action.hasNext() ;) {
// IAction act = action.next();
// if (act instanceof IActionExtPoint) {
// IActionExtPoint extensionAction = (IActionExtPoint) act;
// extensionAction.setActiveSelect(this.jvm);
} else if (me.button == 3) {
final Iterator it = registry.getActions();
while (it.hasNext()) {
final IAction act = (IAction) it.next();
final Class<?> actionClass = act.getClass();
if (actionClass == RefreshJVMAction.class) {
RefreshJVMAction refreshJVMAction = (RefreshJVMAction) act;
refreshJVMAction.setJVM(jvm);
refreshJVMAction.setEnabled(true);
} else if (actionClass == StopMonitoringAction.class) {
StopMonitoringAction stopMonitoringAction = (StopMonitoringAction) act;
stopMonitoringAction.setObject(jvm);
stopMonitoringAction.setEnabled(true);
} else if (actionClass == KillVMAction.class) {
KillVMAction killVMAction = (KillVMAction) act;
killVMAction.setVM(jvm);
killVMAction.setEnabled(true);
} else if (act instanceof IActionExtPoint) {
((IActionExtPoint) act).setAbstractDataObject(this.jvm);
} else if (act instanceof ZoomOutAction ||
act instanceof ZoomInAction) {
act.setEnabled(true);
} else {
act.setEnabled(false);
}
}
}
}
public void mouseReleased(MouseEvent me) {
dnd.reset();
}
public void mouseEntered(MouseEvent me) {
if (dnd.getSource() != null) {
dnd.refresh(null);
}
}
public void mouseExited(MouseEvent me) {
if (dnd.getSource() != null) {
dnd.refresh(null);
}
}
public void mouseDragged(MouseEvent me) { /* Do nothing */
}
public void mouseHover(MouseEvent me) { /* Do nothing */
}
public void mouseMoved(MouseEvent me) { /* Do nothing */
}
} |
package org.innovateuk.ifs.application.feedback.viewmodel;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class InterviewFeedbackViewModelTest {
@Test
public void testConstruct() {
InterviewFeedbackViewModel leadWithResponse = new InterviewFeedbackViewModel("response", "feedback", true, true, false);
assertThat(leadWithResponse.getResponseBannerText(), is(equalTo(InterviewFeedbackViewModel.LEAD_WITH_RESPONSE_BANNER)));
assertThat(leadWithResponse.hasResponse(), is(true));
assertThat(leadWithResponse.hasFeedback(), is(true));
assertThat(leadWithResponse.isResponseSectionEnabled(), is(true));
InterviewFeedbackViewModel leadWithoutResponse = new InterviewFeedbackViewModel(null, "feedback", true, true, false);
assertThat(leadWithoutResponse.getNoResponseBannerText(), is(equalTo(InterviewFeedbackViewModel.LEAD_WITHOUT_RESPONSE_BANNER)));
assertThat(leadWithoutResponse.hasResponse(), is(false));
assertThat(leadWithoutResponse.isResponseSectionEnabled(), is(false));
InterviewFeedbackViewModel collabWithResponse = new InterviewFeedbackViewModel("response", "feedback", false, false, false);
assertThat(collabWithResponse.getResponseBannerText(), is(equalTo(InterviewFeedbackViewModel.COLLAB_WITH_RESPONSE_BANNER)));
InterviewFeedbackViewModel collabWithoutResponse = new InterviewFeedbackViewModel(null, "feedback", false, false, false);
assertThat(collabWithoutResponse.getNoResponseBannerText(), is(equalTo(InterviewFeedbackViewModel.COLLAB_WITHOUT_RESPONSE_BANNER)));
InterviewFeedbackViewModel assessorWithResponse = new InterviewFeedbackViewModel("response", "feedback", false, true, true);
assertThat(assessorWithResponse.getResponseBannerText(), is(equalTo(InterviewFeedbackViewModel.ASSESSOR_WITH_RESPONSE_BANNER)));
}
} |
package org.safehaus.subutai.impl.manager.dao;
import java.util.List;
import org.safehaus.subutai.api.dbmanager.DbManager;
import org.safehaus.subutai.api.manager.helper.Environment;
public class EnvironmentDAO {
DbManager dbManager;
private String source = "ENV";
public EnvironmentDAO( final DbManager dbManager ) {
this.dbManager = dbManager;
}
public List<Environment> getEnvironments() {
List<Environment> environments = dbManager.getEnvironmentInfo( source, Environment.class );
return environments;
}
public Environment getEnvironment( final String environmentName ) {
Environment environment = dbManager.getEnvironmentInfo( source, environmentName, Environment.class );
return environment;
}
public boolean saveEnvironment( final Environment environment ) {
dbManager.saveEnvironmentInfo( source, environment.getName(), environment );
return true;
}
} |
package org.opendaylight.controller.md.sal.dom.store.impl;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.Map.Entry;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
import org.opendaylight.controller.md.sal.dom.spi.RegistrationTreeSnapshot;
import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.Builder;
import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.SimpleEventFactory;
import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
import org.opendaylight.yangtools.util.concurrent.NotificationManager;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Resolve Data Change Events based on modifications and listeners
*
* Computes data change events for all affected registered listeners in data
* tree.
*/
@Beta
public final class ResolveDataChangeEventsTask {
private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
private final DataTreeCandidate candidate;
private final ListenerTree listenerRoot;
private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
this.candidate = Preconditions.checkNotNull(candidate);
this.listenerRoot = Preconditions.checkNotNull(listenerTree);
}
/**
* Resolves and submits notification tasks to the specified manager.
*/
public synchronized void resolve(final NotificationManager<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> manager) {
try (final RegistrationTreeSnapshot<DataChangeListenerRegistration<?>> w = listenerRoot.takeSnapshot()) {
// Defensive: reset internal state
collectedEvents = ArrayListMultimap.create();
// Run through the tree
final ResolveDataChangeState s = ResolveDataChangeState.initial(candidate.getRootPath(), w.getRootNode());
resolveAnyChangeEvent(s, candidate.getRootNode());
/*
* Convert to tasks, but be mindful of multiple values -- those indicate multiple
* wildcard matches, which need to be merged.
*/
for (Entry<DataChangeListenerRegistration<?>, Collection<DOMImmutableDataChangeEvent>> e : collectedEvents.asMap().entrySet()) {
final Collection<DOMImmutableDataChangeEvent> col = e.getValue();
final DOMImmutableDataChangeEvent event;
if (col.size() != 1) {
final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
for (DOMImmutableDataChangeEvent i : col) {
b.merge(i);
}
event = b.build();
LOG.trace("Merged events {} into event {}", col, event);
} else {
event = col.iterator().next();
}
manager.submitNotification(e.getKey(), event);
}
}
}
/**
* Resolves data change event for supplied node
*
* @param path
* Path to current node in tree
* @param listeners
* Collection of Listener registration nodes interested in
* subtree
* @param modification
* Modification of current node
* @param before
* - Original (before) state of current node
* @param after
* - After state of current node
* @return True if the subtree changed, false otherwise
*/
private boolean resolveAnyChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode node) {
final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
final ModificationType type = node.getModificationType();
if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
state.getPath(), type);
return false;
}
// no before and after state is present
switch (type) {
case SUBTREE_MODIFIED:
return resolveSubtreeChangeEvent(state, node);
case WRITE:
Preconditions.checkArgument(maybeAfter.isPresent(),
"Modification at {} has type {} but no after-data", state.getPath(), type);
if (!maybeBefore.isPresent()) {
@SuppressWarnings({ "unchecked", "rawtypes" })
final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
return true;
}
return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
case DELETE:
Preconditions.checkArgument(maybeBefore.isPresent(),
"Modification at {} has type {} but no before-data", state.getPath(), type);
@SuppressWarnings({ "unchecked", "rawtypes" })
final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
return true;
case UNMODIFIED:
return false;
}
throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
}
private boolean resolveReplacedEvent(final ResolveDataChangeState state,
final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
/*
* Node is a container (contains a child) and we have interested
* listeners registered for it, that means we need to do
* resolution of changes on children level and can not
* shortcut resolution.
*/
LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData, afterData);
@SuppressWarnings("unchecked")
NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) beforeData;
@SuppressWarnings("unchecked")
NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) afterData;
return resolveNodeContainerReplaced(state, beforeCont, afterCont);
}
// Node is a Leaf type (does not contain child nodes)
// so normal equals method is sufficient for determining change.
if (beforeData.equals(afterData)) {
LOG.trace("Skipping equal leaf {}", state.getPath());
return false;
}
LOG.trace("Resolving leaf replace event for {} , before {}, after {}", state.getPath(), beforeData, afterData);
DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE).addUpdated(state.getPath(), beforeData, afterData).build();
state.addEvent(event);
state.collectEvents(beforeData, afterData, collectedEvents);
return true;
}
private boolean resolveNodeContainerReplaced(final ResolveDataChangeState state,
final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont,
final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont) {
if (!state.needsProcessing()) {
LOG.trace("Not processing replaced container {}", state.getPath());
return true;
}
// We look at all children from before and compare it with after state.
boolean childChanged = false;
for (NormalizedNode<PathArgument, ?> beforeChild : beforeCont.getValue()) {
final PathArgument childId = beforeChild.getIdentifier();
if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
childChanged = true;
}
}
for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
final PathArgument childId = afterChild.getIdentifier();
/*
* We have already iterated of the before-children, so have already
* emitted modify/delete events. This means the child has been
* created.
*/
if (!beforeCont.getChild(childId).isPresent()) {
resolveSameEventRecursivelly(state.child(childId), afterChild, DOMImmutableDataChangeEvent.getCreateEventFactory());
childChanged = true;
}
}
if (childChanged) {
DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
.addUpdated(state.getPath(), beforeCont, afterCont).build();
state.addEvent(event);
}
state.collectEvents(beforeCont, afterCont, collectedEvents);
return childChanged;
}
private boolean resolveNodeContainerChildUpdated(final ResolveDataChangeState state,
final NormalizedNode<PathArgument, ?> before, final Optional<NormalizedNode<PathArgument, ?>> after) {
if (after.isPresent()) {
// REPLACE or SUBTREE Modified
return resolveReplacedEvent(state, before, after.get());
}
// AFTER state is not present - child was deleted.
resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
return true;
}
private void resolveSameEventRecursivelly(final ResolveDataChangeState state,
final NormalizedNode<PathArgument, ?> node, final SimpleEventFactory eventFactory) {
if (!state.needsProcessing()) {
LOG.trace("Skipping child {}", state.getPath());
return;
}
// We have listeners for this node or it's children, so we will try
// to do additional processing
if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
LOG.trace("Resolving subtree recursive event for {}, type {}", state.getPath(), eventFactory);
// Node has children, so we will try to resolve it's children
// changes.
@SuppressWarnings("unchecked")
NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> container = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) node;
for (NormalizedNode<PathArgument, ?> child : container.getValue()) {
final PathArgument childId = child.getIdentifier();
LOG.trace("Resolving event for child {}", childId);
resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
}
}
final DOMImmutableDataChangeEvent event = eventFactory.create(state.getPath(), node);
LOG.trace("Adding event {} at path {}", event, state.getPath());
state.addEvent(event);
state.collectEvents(event.getOriginalSubtree(), event.getUpdatedSubtree(), collectedEvents);
}
private boolean resolveSubtreeChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode modification) {
final Optional<NormalizedNode<?, ?>> maybeBefore = modification.getDataBefore();
final Optional<NormalizedNode<?, ?>> maybeAfter = modification.getDataAfter();
Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s", state.getPath());
Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s", state.getPath());
if (!state.needsProcessing()) {
LOG.trace("Not processing modified subtree {}", state.getPath());
return true;
}
DataChangeScope scope = null;
for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
switch (childMod.getModificationType()) {
case WRITE:
case DELETE:
if (resolveAnyChangeEvent(childState, childMod)) {
scope = DataChangeScope.ONE;
}
break;
case SUBTREE_MODIFIED:
if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
scope = DataChangeScope.SUBTREE;
}
break;
case UNMODIFIED:
// no-op
break;
}
}
final NormalizedNode<?, ?> before = maybeBefore.get();
final NormalizedNode<?, ?> after = maybeAfter.get();
if (scope != null) {
DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope).addUpdated(state.getPath(), before, after).build();
state.addEvent(one);
}
state.collectEvents(before, after, collectedEvents);
return scope != null;
}
public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
return new ResolveDataChangeEventsTask(candidate, listenerTree);
}
} |
package com.jwm.j3dfw.controller;
import com.jwm.j3dfw.geometry.Geometry;
import com.jwm.j3dfw.production.Camera;
public class Controller {
private Geometry geo;
public Controller(Geometry g) {
geo = g;
}
public void leftMouseDown() {
}
public void rightMouseDown() {
}
public void leftMouseUp() {
}
public void rightMouseUp() {
}
public void keyPress(int keyCode) {
// 67 = c
if (keyCode == 67) {
}
}
public void setMousePosition(double xPos, double percent) {
}
public void mouseWheelMoved(int wheelRotation) {
Camera cam = geo.getCamera();
if (cam == null) {
return;
}
cam.setZoom(wheelRotation);
}
public void cmdMouseWheelMoved(int wheelMoved) {
Camera cam = geo.getCamera();
if (cam == null) {
return;
}
double angleChange = wheelMoved;
cam.incrementAngle(angleChange);
}
public void shiftMouseWheelMoved(int wheelMoved) {
Camera cam = geo.getCamera();
if (cam == null) {
return;
}
double angleChange = wheelMoved;
cam.incrementVerticalAngle(angleChange);
}
} |
package com.s3auth.relay;
import com.s3auth.hosts.Host;
import com.s3auth.hosts.Resource;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.CharEncoding;
/**
* Single HTTP processing thread.
*
* <p>It's a wrapper around {@link Host}, that adds HTTP Basic Auth mechanism
* to a normal HTTP request processing. The class is instantiated in
* {@link HttpThread}.
*
* <p>The class is immutable and thread-safe.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 0.0.1
* @see HttpThread
*/
final class SecuredHost implements Host {
/**
* Authorization header pattern.
*/
private static final Pattern AUTH_PATTERN =
Pattern.compile("Basic ([a-zA-Z0-9/]+=*)");
/**
* Original host.
*/
private final transient Host host;
/**
* Http request to process.
*/
private final transient HttpRequest request;
/**
* Public ctor.
* @param hst Original host
* @param rqst The request
*/
public SecuredHost(@NotNull final Host hst,
@NotNull final HttpRequest rqst) {
this.host = hst;
this.request = rqst;
}
/**
* {@inheritDoc}
*/
@Override
public Resource fetch(@NotNull final URI uri) throws IOException {
Resource res;
if (this.isHidden(uri)) {
res = this.secured(uri);
} else {
res = this.host.fetch(uri);
}
return res;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHidden(@NotNull final URI uri) throws IOException {
return this.host.isHidden(uri);
}
/**
* {@inheritDoc}
*/
@Override
public boolean authorized(@NotNull final String user,
@NotNull final String password) throws IOException {
return this.host.authorized(user, password);
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
this.host.close();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return this.host.toString();
}
/**
* Fetch this URI in a secure way.
* @param uri The URI to fetch
* @return Fetched resource
* @throws IOException If some IO problem inside
*/
private Resource secured(final URI uri) throws IOException {
if (!this.request.headers().containsKey(HttpHeaders.AUTHORIZATION)) {
throw new HttpException(
new HttpResponse()
.withStatus(HttpURLConnection.HTTP_UNAUTHORIZED)
.withHeader(
HttpHeaders.WWW_AUTHENTICATE,
"Basic realm=\"s3auth\""
)
);
}
final Matcher matcher = SecuredHost.AUTH_PATTERN.matcher(
this.request.headers().get(HttpHeaders.AUTHORIZATION)
.iterator().next()
);
if (!matcher.matches()) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
"'%s' header is in wrong format",
HttpHeaders.AUTHORIZATION
)
);
}
String[] parts;
try {
parts = URLDecoder.decode(
new String(
Base64.decodeBase64(matcher.group(1)),
CharEncoding.UTF_8
),
CharEncoding.UTF_8
).split(":", 2);
} catch (java.io.UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
if (parts.length != 2) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
"should be two parts in Basic auth header"
);
}
if (!this.authorized(parts[0], parts[1])) {
throw new HttpException(
new HttpResponse()
.withStatus(HttpURLConnection.HTTP_UNAUTHORIZED)
.withHeader(
HttpHeaders.WWW_AUTHENTICATE,
"Basic realm=\"try again\""
)
.withBody(this.host.toString())
);
}
return this.host.fetch(uri);
}
} |
package com.kodcu.service.ui;
import com.kodcu.component.MenuItemBuilt;
import com.kodcu.controller.ApplicationController;
import com.kodcu.other.Current;
import com.kodcu.service.*;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseButton;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
@Component
public class WebviewService {
@Autowired
private ApplicationController controller;
@Autowired
private PathResolverService pathResolver;
@Autowired
private ThreadService threadService;
@Autowired
private ParserService parserService;
@Autowired
private MarkdownService markdownService;
@Autowired
private Current current;
@Autowired
private DocumentService documentService;
public WebView createWebView() {
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load(String.format("http://localhost:%d/editor.html", controller.getPort()));
webView.setContextMenuEnabled(false);
ContextMenu menu = new ContextMenu();
MenuItem copy = MenuItemBuilt.item("Copy").onclick(event1 -> {
controller.cutCopy(current.currentEditorSelection());
});
MenuItem paste = MenuItemBuilt.item("Paste").onclick(e -> {
controller.paste(false);
});
MenuItem pasteRaw = MenuItemBuilt.item("Paste raw").onclick(e -> {
current.insertEditorValue(controller.pasteRaw());
});
MenuItem convert = MenuItemBuilt.item("Markdown to Asciidoc").onclick(e -> {
markdownService.convertToAsciidoc(current.currentEditorValue(), content -> {
threadService.runActionLater(() -> {
documentService.newDoc(content);
});
});
});
webView.setOnMouseClicked(event -> {
if (menu.getItems().size() == 0) {
menu.getItems().addAll(copy, paste, pasteRaw, convert);
}
if (menu.isShowing()) {
menu.hide();
}
if (event.getButton() == MouseButton.SECONDARY) {
boolean asciidoc = current.currentTab().isAsciidoc();
convert.setVisible(asciidoc);
menu.show(webView, event.getScreenX(), event.getScreenY());
}
});
webView.setOnDragDropped(event -> {
Dragboard dragboard = event.getDragboard();
boolean success = false;
if (dragboard.hasFiles()) {
List<File> dragboardFiles = dragboard.getFiles();
if (dragboardFiles.size() == 1) {
Path path = dragboardFiles.get(0).toPath();
if (Files.isDirectory(path)) {
Iterator<File> files = FileUtils.iterateFilesAndDirs(path.toFile(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
StringBuffer buffer = new StringBuffer();
buffer.append("[tree,file=\"\"]");
buffer.append("\n
buffer.append("#" + path.getFileName().toString());
while (files.hasNext()) {
File next = files.next();
Path relativize = path.relativize(next.toPath());
Path path1 = relativize.getName(0);
if ("".equals(path1.toString()) || pathResolver.isHidden(path1))
continue;
String hash = String.join("", Collections.nCopies(relativize.getNameCount() + 1, "
buffer.append("\n");
buffer.append(hash);
buffer.append(relativize.getFileName().toString());
}
buffer.append("\n
current.insertEditorValue(buffer.toString());
success = true;
}
}
Optional<String> block = parserService.toImageBlock(dragboardFiles);
if (block.isPresent()) {
current.insertEditorValue(block.get());
success = true;
} else {
block = parserService.toIncludeBlock(dragboardFiles);
if (block.isPresent()) {
current.insertEditorValue(block.get());
success = true;
}
}
}
if (dragboard.hasHtml() && !success) {
Optional<String> block = parserService.toWebImageBlock(dragboard.getHtml());
if (block.isPresent()) {
current.insertEditorValue(block.get());
success = true;
}
}
if (dragboard.hasString() && !success) {
current.insertEditorValue(dragboard.getString());
success = true;
}
event.setDropCompleted(success);
event.consume();
});
return webView;
}
} |
package org.apereo.cas.adaptors.redis.services;
import org.apereo.cas.category.RedisCategory;
import org.apereo.cas.config.RedisServiceRegistryConfiguration;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.AbstractServiceRegistryTests;
import org.apereo.cas.services.RegexRegisteredService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ServiceRegistry;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.junit.ConditionalIgnore;
import org.apereo.cas.util.junit.RunningContinuousIntegrationCondition;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.test.context.TestPropertySource;
import java.util.Collection;
/**
* Unit test for {@link RedisServiceRegistry} class.
*
* @author Misagh Moayyed
* @since 4.0.0
*/
@RunWith(Parameterized.class)
@SpringBootTest(classes = {RedisServiceRegistryConfiguration.class, RefreshAutoConfiguration.class})
@EnableScheduling
@TestPropertySource(properties = {"cas.serviceRegistry.redis.host=localhost", "cas.serviceRegistry.redis.port=6379"})
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Category(RedisCategory.class)
@ConditionalIgnore(condition = RunningContinuousIntegrationCondition.class, port = 6379)
public class RedisServerServiceRegistryTests extends AbstractServiceRegistryTests {
@Autowired
@Qualifier("redisServiceRegistry")
private ServiceRegistry dao;
public RedisServerServiceRegistryTests(final Class<? extends RegisteredService> registeredServiceClass) {
super(registeredServiceClass);
}
@Parameterized.Parameters
public static Collection<Object> getTestParameters() {
return CollectionUtils.wrapList(RegexRegisteredService.class, OAuthRegisteredService.class, SamlRegisteredService.class);
}
@Override
public ServiceRegistry getNewServiceRegistry() {
return this.dao;
}
} |
package com.shaubert.imagepickersample;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import com.bumptech.glide.*;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.target.Target;
import com.shaubert.ui.imagepicker.ImagePickerConfig;
import com.shaubert.ui.imagepicker.glide.GlideImageLoader;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
setup();
}
private void setup() {
GlideImageLoader imageLoader = new GlideImageLoader(this) {
@Override
protected void loadBitmapWithGlide(Uri uri, Target<Bitmap> target) {
Glide.with(App.this)
.load(uri)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.animate(android.R.anim.fade_in)
.into(target);
}
@Override
protected void loadDrawableWithGlide(Context context, Uri uri, Target<GlideDrawable> target) {
Glide.with(context)
.load(uri)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.animate(android.R.anim.fade_in)
.into(target);
}
};
ImagePickerConfig.setup()
.imageLoader(imageLoader)
.apply();
}
} |
// $Id: Membership.java,v 1.6 2004/09/21 15:38:21 belaban Exp $
package org.jgroups;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Collections;
import java.util.Vector;
import java.util.LinkedList;
/**
* Class to keep track of Addresses.
* The member ship object holds a vector of Address object that are in the same membership
* Each unique address can only exist once, ie, doing Membership.add(existing_address) will be ignored
*/
public class Membership implements Cloneable {
/* private vector to hold all the addresses */
private LinkedList members;
protected static final Log log=LogFactory.getLog(Membership.class);
/**
* Public constructor
* Creates a member ship object with zero members
*/
public Membership() {
// 11 is the optimized value for vector growth
members=new LinkedList();
}
/**
* Creates a member ship object with the initial members.
* The Address references are copied out of the vector, so that the
* vector passed in as parameters is not the same reference as the vector
* that the membership class is using
*
* @param initial_members - a list of members that belong to this membership
*/
public Membership(Vector initial_members) {
if(initial_members != null)
members=new LinkedList(initial_members);
}
/**
* returns a copy (clone) of the members in this membership.
* the vector returned is immutable in reference to this object.
* ie, modifying the vector that is being returned in this method
* will not modify this membership object.
*
* @return a list of members,
*/
public Vector getMembers() {
/*clone so that this objects members can not be manipulated from the outside*/
synchronized(members) {
return new Vector(members);
}
}
/**
* Adds a new member to this membership.
* If the member already exist (Address.equals(Object) returns true then the member will
* not be added to the membership
*/
public void add(Address new_member) {
synchronized(members) {
if(new_member != null && !members.contains(new_member)) {
members.add(new_member);
}
}
}
/**
* Adds a list of members to this membership
*
* @param v - a vector containing Address objects
* @throws ClassCastException if v contains objects that don't implement the Address interface
* @see #add
*/
public void add(Vector v) {
if(v != null) {
for(int i=0; i < v.size(); i++) {
add((Address)v.elementAt(i));
}
}
}
/**
* removes an member from the membership.
* If this member doesn't exist, no action will be performed on the existing membership
*
* @param old_member - the member to be removed
*/
public void remove(Address old_member) {
if(old_member != null) {
synchronized(members) {
members.remove(old_member);
}
}
}
/**
* removes all the members contained in v from this membership
*
* @param v - a vector containing all the members to be removed
*/
public void remove(Vector v) {
if(v != null) {
synchronized(members) {
members.removeAll(v);
}
}
}
/**
* removes all the members from this membership
*/
public void clear() {
synchronized(members) {
members.clear();
}
}
/**
* Clear the membership and adds all members of v
* This method will clear out all the old members of this membership by
* invoking the <code>Clear</code> method.
* Then it will add all the all members provided in the vector v
*
* @param v - a vector containing all the members this membership will contain
*/
public void set(Vector v) {
clear();
if(v != null) {
add(v);
}
}
/**
* Clear the membership and adds all members of v
* This method will clear out all the old members of this membership by
* invoking the <code>Clear</code> method.
* Then it will add all the all members provided in the vector v
*
* @param m - a membership containing all the members this membership will contain
*/
public void set(Membership m) {
clear();
if(m != null) {
add(m.getMembers());
}
}
/**
* merges membership with the new members and removes suspects
* The Merge method will remove all the suspects and add in the new members.
* It will do it in the order
* 1. Remove suspects
* 2. Add new members
* the order is very important to notice.
*
* @param new_mems - a vector containing a list of members (Address) to be added to this membership
* @param suspects - a vector containing a list of members (Address) to be removed from this membership
*/
public void merge(Vector new_mems, Vector suspects) {
remove(suspects);
add(new_mems);
}
/**
* Returns true if the provided member belongs to this membership
*
* @param member
* @return true if the member belongs to this membership
*/
public boolean contains(Address member) {
if(member == null) return false;
synchronized(members) {
return members.contains(member);
}
}
/* Simple inefficient bubble sort, but not used very often (only when merging) */
public void sort() {
synchronized(members) {
Collections.sort(members);
}
}
/**
* returns a copy of this membership
*
* @return an exact copy of this membership
*/
public Membership copy() {
return ((Membership)clone());
}
/**
* @return a clone of this object. The list of members is copied to a new
* container
*/
public Object clone() {
Membership m;
try {
m=(Membership)super.clone();
}
catch(CloneNotSupportedException e) {
m=new Membership();
}
synchronized(members) {
m.members=(LinkedList)members.clone();
}
return (m);
}
/**
* Returns the number of addresses in this membership
*
* @return the number of addresses in this membership
*/
public int size() {
synchronized(members) {
return members.size();
}
}
/**
* Returns the component at the specified index
*
* @param index - 0..size()-1
* @throws ArrayIndexOutOfBoundsException - if the index is negative or not less than the current size of this Membership object.
* @see java.util.Vector#elementAt
*/
public Object elementAt(int index) {
synchronized(members) {
return members.get(index);
}
}
public String toString() {
synchronized(members) {
return members.toString();
}
}
} |
package com.monitorjbl.xlsx;
import com.monitorjbl.xlsx.exceptions.MissingSheetException;
import com.monitorjbl.xlsx.exceptions.OpenException;
import com.monitorjbl.xlsx.exceptions.ReadException;
import com.monitorjbl.xlsx.sst.BufferedStringsTable;
import com.monitorjbl.xlsx.impl.StreamingSheetReader;
import com.monitorjbl.xlsx.impl.StreamingWorkbook;
import com.monitorjbl.xlsx.impl.StreamingWorkbookReader;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.util.Iterator;
import java.util.Objects;
import static com.monitorjbl.xlsx.XmlUtils.document;
import static com.monitorjbl.xlsx.XmlUtils.searchForNodeList;
/**
* Streaming Excel workbook implementation. Most advanced features of POI are not supported.
* Use this only if your application can handle iterating through an entire workbook, row by
* row.
*/
public class StreamingReader implements Iterable<Row>, AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(StreamingReader.class);
private File tmp;
private final StreamingWorkbookReader workbook;
public StreamingReader(StreamingWorkbookReader workbook) {
this.workbook = workbook;
}
/**
* Returns a new streaming iterator to loop through rows. This iterator is not
* guaranteed to have all rows in memory, and any particular iteration may
* trigger a load from disk to read in new data.
*
* @return the streaming iterator
* @deprecated StreamingReader is equivalent to the POI Workbook object rather
* than the Sheet object. This method will be removed in a future release.
*/
@Override
public Iterator<Row> iterator() {
return workbook.first().iterator();
}
/**
* Closes the streaming resource, attempting to clean up any temporary files created.
*
* @throws com.monitorjbl.xlsx.exceptions.CloseException if there is an issue closing the stream
*/
@Override
public void close() {
try {
workbook.close();
} finally {
if(tmp != null) {
log.debug("Deleting tmp file [" + tmp.getAbsolutePath() + "]");
tmp.delete();
}
}
}
static File writeInputStreamToFile(InputStream is, int bufferSize) throws IOException {
File f = Files.createTempFile("tmp-", ".xlsx").toFile();
try(FileOutputStream fos = new FileOutputStream(f)) {
int read;
byte[] bytes = new byte[bufferSize];
while((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
is.close();
fos.close();
return f;
}
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private int rowCacheSize = 10;
private int bufferSize = 1024;
private int sheetIndex = 0;
private int sstCacheSize = -1;
private String sheetName;
private String password;
public int getRowCacheSize() {
return rowCacheSize;
}
public int getBufferSize() {
return bufferSize;
}
/**
* @return The sheet index
* @deprecated This method will be removed in a future release.
*/
public int getSheetIndex() {
return sheetIndex;
}
/**
* @return The sheet name
* @deprecated This method will be removed in a future release.
*/
public String getSheetName() {
return sheetName;
}
/**
* @return The password to use to unlock this workbook
*/
public String getPassword() {
return password;
}
/**
* @return The size of the shared string table cache. If less than 0, no
* cache will be used and the entire table will be loaded into memory.
*/
public int getSstCacheSize() {
return sstCacheSize;
}
/**
* The number of rows to keep in memory at any given point.
* <p>
* Defaults to 10
* </p>
*
* @param rowCacheSize number of rows
* @return reference to current {@code Builder}
*/
public Builder rowCacheSize(int rowCacheSize) {
this.rowCacheSize = rowCacheSize;
return this;
}
/**
* The number of bytes to read into memory from the input
* resource.
* <p>
* Defaults to 1024
* </p>
*
* @param bufferSize buffer size in bytes
* @return reference to current {@code Builder}
*/
public Builder bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
/**
* Which sheet to open. There can only be one sheet open
* for a single instance of {@code StreamingReader}. If
* more sheets need to be read, a new instance must be
* created.
* <p>
* Defaults to 0
* </p>
*
* @param sheetIndex index of sheet
* @return reference to current {@code Builder}
* @deprecated This method will be removed in a future release. Use {@link StreamingWorkbook#getSheetAt(int)} instead.
*/
public Builder sheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
return this;
}
/**
* Which sheet to open. There can only be one sheet open
* for a single instance of {@code StreamingReader}. If
* more sheets need to be read, a new instance must be
* created.
*
* @param sheetName name of sheet
* @return reference to current {@code Builder}
* @deprecated This method will be removed in a future release. Use {@link StreamingWorkbook#getSheet(String)} instead.
*/
public Builder sheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
/**
* For password protected files specify password to open file.
* If the password is incorrect a {@code ReadException} is thrown on
* {@code read}.
* <p>NULL indicates that no password should be used, this is the
* default value.</p>
*
* @param password to use when opening file
* @return reference to current {@code Builder}
*/
public Builder password(String password) {
this.password = password;
return this;
}
/**
* <h1>!!! This option is experimental !!!</h1>
*
* Set the size of the Shared Strings Table cache. This option exists to accommodate
* extremely large workbooks with millions of unique strings. Normally the SST is entirely
* loaded into memory, but with large workbooks with high cardinality (i.e., very few
* duplicate values) the SST may not fit entirely into memory.
* <p>
* By default, the entire SST *will* be loaded into memory. Setting a value greater than
* 0 for this option will only cache up to this many entries in memory. <strong>However</strong>,
* enabling this option at all will have some noticeable performance degredation as you are
* trading memory for disk space.
*
* @param sstCacheSize size of SST cache
* @return reference to current {@code Builder}
*/
public Builder sstCacheSize(int sstCacheSize) {
this.sstCacheSize = sstCacheSize;
return this;
}
/**
* Reads a given {@code InputStream} and returns a new
* instance of {@code Workbook}. Due to Apache POI
* limitations, a temporary file must be written in order
* to create a streaming iterator. This process will use
* the same buffer size as specified in {@link #bufferSize(int)}.
*
* @param is input stream to read in
* @return A {@link Workbook} that can be read from
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the stream
*/
public Workbook open(InputStream is) {
StreamingWorkbookReader workbook = new StreamingWorkbookReader(this);
workbook.init(is);
return new StreamingWorkbook(workbook);
}
/**
* Reads a given {@code File} and returns a new instance
* of {@code Workbook}.
*
* @param file file to read in
* @return built streaming reader instance
* @throws com.monitorjbl.xlsx.exceptions.OpenException if there is an issue opening the file
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the file
*/
public Workbook open(File file) {
StreamingWorkbookReader workbook = new StreamingWorkbookReader(this);
workbook.init(file);
return new StreamingWorkbook(workbook);
}
/**
* Reads a given {@code InputStream} and returns a new
* instance of {@code StreamingReader}. Due to Apache POI
* limitations, a temporary file must be written in order
* to create a streaming iterator. This process will use
* the same buffer size as specified in {@link #bufferSize(int)}.
*
* @param is input stream to read in
* @return built streaming reader instance
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the stream
* @deprecated This method will be removed in a future release. Use {@link Builder#open(InputStream)} instead
*/
public StreamingReader read(InputStream is) {
File f = null;
try {
f = writeInputStreamToFile(is, bufferSize);
log.debug("Created temp file [" + f.getAbsolutePath() + "]");
StreamingReader r = read(f);
r.tmp = f;
return r;
} catch(IOException e) {
throw new ReadException("Unable to read input stream", e);
} catch(RuntimeException e) {
f.delete();
throw e;
}
}
/**
* Reads a given {@code File} and returns a new instance
* of {@code StreamingReader}.
*
* @param f file to read in
* @return built streaming reader instance
* @throws com.monitorjbl.xlsx.exceptions.OpenException if there is an issue opening the file
* @throws com.monitorjbl.xlsx.exceptions.ReadException if there is an issue reading the file
* @deprecated This method will be removed in a future release. Use {@link Builder#open(File)} instead
*/
public StreamingReader read(File f) {
try {
OPCPackage pkg;
if(password != null) {
POIFSFileSystem poifs = new POIFSFileSystem(f);
EncryptionInfo info = new EncryptionInfo(poifs);
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword(password);
pkg = OPCPackage.open(d.getDataStream(poifs));
} else {
pkg = OPCPackage.open(f);
}
boolean use1904Dates = false;
XSSFReader reader = new XSSFReader(pkg);
SharedStringsTable sst;
File sstCache = null;
if(sstCacheSize > 0) {
sstCache = Files.createTempFile("", "").toFile();
log.debug("Created sst cache file [" + sstCache.getAbsolutePath() + "]");
sst = BufferedStringsTable.getSharedStringsTable(sstCache, sstCacheSize, pkg);
} else {
sst = reader.getSharedStringsTable();
}
StylesTable styles = reader.getStylesTable();
NodeList workbookPr = searchForNodeList(document(reader.getWorkbookData()), "/workbook/workbookPr");
if (workbookPr.getLength() == 1) {
final Node date1904 = workbookPr.item(0).getAttributes().getNamedItem("date1904");
if (date1904 != null) {
use1904Dates = ("1".equals(date1904.getTextContent()));
}
}
InputStream sheet = findSheet(reader);
if(sheet == null) {
throw new MissingSheetException("Unable to find sheet at index [" + sheetIndex + "]");
}
XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(sheet);
return new StreamingReader(new StreamingWorkbookReader(sst, sstCache, pkg, new StreamingSheetReader(sst, styles, parser, use1904Dates, rowCacheSize),
this));
} catch(IOException e) {
throw new OpenException("Failed to open file", e);
} catch(OpenXML4JException | XMLStreamException e) {
throw new ReadException("Unable to read workbook", e);
} catch(GeneralSecurityException e) {
throw new ReadException("Unable to read workbook - Decryption failed", e);
}
}
/**
* @deprecated This will be removed when the transition to the 1.x API is complete
*/
private InputStream findSheet(XSSFReader reader) throws IOException, InvalidFormatException {
int index = sheetIndex;
if(sheetName != null) {
index = -1;
//This file is separate from the worksheet data, and should be fairly small
NodeList nl = searchForNodeList(document(reader.getWorkbookData()), "/workbook/sheets/sheet");
for(int i = 0; i < nl.getLength(); i++) {
if(Objects.equals(nl.item(i).getAttributes().getNamedItem("name").getTextContent(), sheetName)) {
index = i;
}
}
if(index < 0) {
return null;
}
}
Iterator<InputStream> iter = reader.getSheetsData();
InputStream sheet = null;
int i = 0;
while(iter.hasNext()) {
InputStream is = iter.next();
if(i++ == index) {
sheet = is;
log.debug("Found sheet at index [" + sheetIndex + "]");
break;
}
}
return sheet;
}
}
} |
// $Id: Queue.java,v 1.11 2003/09/26 14:06:14 belaban Exp $
package org.jgroups.util;
import org.jgroups.TimeoutException;
import org.jgroups.log.Trace;
import java.util.Vector;
/**
* Elements are added at the tail and removed from the head. Class is thread-safe in that
* 1 producer and 1 consumer may add/remove elements concurrently. The class is not
* explicitely designed for multiple producers or consumers. Implemented as a linked
* list, so that removal of an element at the head does not cause a right-shift of the
* remaining elements (as in a Vector-based implementation).
* @author Bela Ban
*/
public class Queue {
/*head and the tail of the list so that we can easily add and remove objects*/
Element head=null, tail=null;
/*flag to determine the state of the queue*/
boolean closed=false;
/*current size of the queue*/
int size=0;
/* Lock object for synchronization. Is notified when element is added */
Object add_mutex=new Object();
/** Lock object for syncing on removes. It is notified when an object is removed */
// Object remove_mutex=new Object();
/*the number of end markers that have been added*/
int num_markers=0;
/**
* if the queue closes during the runtime
* an endMarker object is added to the end of the queue to indicate that
* the queue will close automatically when the end marker is encountered
* This allows for a "soft" close.
* @see Queue#close
*/
private static final Object endMarker=new Object();
/**
* the class Element indicates an object in the queue.
* This element allows for the linked list algorithm by always holding a
* reference to the next element in the list.
* if Element.next is null, then this element is the tail of the list.
*/
class Element {
/*the actual value stored in the queue*/
Object obj=null;
/*pointer to the next item in the (queue) linked list*/
Element next=null;
/**
* creates an Element object holding its value
* @param o - the object to be stored in the queue position
*/
Element(Object o) {
obj=o;
}
/**
* prints out the value of the object
*/
public String toString() {
return obj != null? obj.toString() : "null";
}
}
/**
* creates an empty queue
*/
public Queue() {
}
/**
* Returns the first element. Returns null if no elements are available.
*/
public Object getFirst() {
return head != null? head.obj : null;
}
/**
* Returns the last element. Returns null if no elements are available.
*/
public Object getLast() {
return tail != null? tail.obj : null;
}
/**
* returns true if the Queue has been closed
* however, this method will return false if the queue has been closed
* using the close(true) method and the last element has yet not been received.
* @return true if the queue has been closed
*/
public boolean closed() {
return closed;
}
/**
* adds an object to the tail of this queue
* If the queue has been closed with close(true) no exception will be
* thrown if the queue has not been flushed yet.
* @param obj - the object to be added to the queue
* @exception QueueClosedException exception if closed() returns true
*/
public void add(Object obj) throws QueueClosedException {
if(obj == null) {
Trace.error("Queue.add()", "argument must not be null");
return;
}
if(closed)
throw new QueueClosedException();
if(this.num_markers > 0)
throw new QueueClosedException("Queue.add(): queue has been closed. You can not add more elements. " +
"Waiting for removal of remaining elements.");
/*lock the queue from other threads*/
synchronized(add_mutex) {
/*create a new linked list element*/
Element el=new Element(obj);
/*check the first element*/
if(head == null) {
/*the object added is the first element*/
/*set the head to be this object*/
head=el;
/*set the tail to be this object*/
tail=head;
/*set the size to be one, since the queue was empty*/
size=1;
}
else {
/*add the object to the end of the linked list*/
tail.next=el;
/*set the tail to point to the last element*/
tail=el;
/*increase the size*/
size++;
}
/*wake up all the threads that are waiting for the lock to be released*/
add_mutex.notifyAll();
}
}
/**
* Adds a new object to the head of the queue
* basically (obj.equals(queue.remove(queue.add(obj)))) returns true
* If the queue has been closed with close(true) no exception will be
* thrown if the queue has not been flushed yet.
* @param obj - the object to be added to the queue
* @exception QueueClosedException exception if closed() returns true
*
*/
public void addAtHead(Object obj) throws QueueClosedException {
if(obj == null) {
Trace.error("Queue.addAtHead()", "argument must not be null");
return;
}
if(closed)
throw new QueueClosedException();
if(this.num_markers > 0)
throw new QueueClosedException("Queue.addAtHead(): queue has been closed. You can not add more elements. " +
"Waiting for removal of remaining elements.");
/*lock the queue from other threads*/
synchronized(add_mutex) {
Element el=new Element(obj);
/*check the head element in the list*/
if(head == null) {
/*this is the first object, we could have done add(obj) here*/
head=el;
tail=head;
size=1;
}
else {
/*set the head element to be the child of this one*/
el.next=head;
/*set the head to point to the recently added object*/
head=el;
/*increase the size*/
size++;
}
/*wake up all the threads that are waiting for the lock to be released*/
add_mutex.notifyAll();
}
}
/**
* Removes 1 element from head or <B>blocks</B>
* until next element has been added or until queue has been closed
* @return the first element to be taken of the queue
*/
public Object remove() throws QueueClosedException {
/*initialize the return value*/
Object retval=null;
/*lock the queue*/
synchronized(add_mutex) {
/*wait as long as the queue is empty. return when an element is present or queue is closed*/
while(size == 0) {
if(closed)
throw new QueueClosedException();
try {
add_mutex.wait();
}
catch(IllegalMonitorStateException ex) {
throw ex;
}
catch(InterruptedException ex) {
}
}
if(closed)
throw new QueueClosedException();
/*remove the head from the queue, if we make it to this point, retval should not be null !*/
retval=removeInternal();
if(retval == null)
Trace.error("Queue.remove()", "element was null, should never be the case");
}
/*
* we ran into an Endmarker, which means that the queue was closed before
* through close(true)
*/
if(retval == endMarker) {
close(false); // mark queue as closed
throw new QueueClosedException();
}
/*return the object*/
return retval;
}
/**
* Removes 1 element from the head.
* If the queue is empty the operation will wait for timeout ms.
* if no object is added during the timeout time, a Timout exception is thrown
* @param timeout - the number of milli seconds this operation will wait before it times out
* @return the first object in the queue
*/
public Object remove(long timeout) throws QueueClosedException, TimeoutException {
Object retval=null;
/*lock the queue*/
synchronized(add_mutex) {
/*if the queue size is zero, we want to wait until a new object is added*/
if(size == 0) {
if(closed)
throw new QueueClosedException();
try {
/*release the add_mutex lock and wait no more than timeout ms*/
add_mutex.wait(timeout);
}
catch(IllegalMonitorStateException ex) {
throw ex;
}
catch(IllegalArgumentException ex2) {
throw ex2;
}
catch(InterruptedException ex) {
}
}
/*we either timed out, or got notified by the add_mutex lock object*/
/*check to see if the object closed*/
if(closed)
throw new QueueClosedException();
/*get the next value*/
retval=removeInternal();
/*null result means we timed out*/
if(retval == null) throw new TimeoutException();
/*if we reached an end marker we are going to close the queue*/
if(retval == endMarker) {
close(false);
throw new QueueClosedException();
}
/*at this point we actually did receive a value from the queue, return it*/
return retval;
}
}
/**
* removes a specific object from the queue.
* the object is matched up using the Object.equals method.
* @param obj the actual object to be removed from the queue
*/
public void removeElement(Object obj) throws QueueClosedException {
Element el, tmp_el;
if(obj == null) {
Trace.error("Queue.removeElement()", "argument must not be null");
return;
}
/*lock the queue*/
synchronized(add_mutex) {
el=head;
/*the queue is empty*/
if(el == null) return;
/*check to see if the head element is the one to be removed*/
if(el.obj.equals(obj)) {
/*the head element matched we will remove it*/
head=el.next;
el.next=null;
/*check if we only had one object left
*at this time the queue becomes empty
*this will set the tail=head=null
*/
if(size == 1)
tail=head; // null
decrementSize();
// if(size == 0) {
// synchronized(remove_mutex) {
// remove_mutex.notifyAll();
return;
}
/*look through the other elements*/
while(el.next != null) {
if(el.next.obj.equals(obj)) {
tmp_el=el.next;
if(tmp_el == tail) // if it is the last element, move tail one to the left (bela Sept 20 2002)
tail=el;
el.next=el.next.next; // point to the el past the next one. can be null.
tmp_el.next=null;
decrementSize();
// if(size == 0) {
// synchronized(remove_mutex) {
// remove_mutex.notifyAll();
break;
}
el=el.next;
}
}
}
/**
* returns the first object on the queue, without removing it.
* If the queue is empty this object blocks until the first queue object has
* been added
* @return the first object on the queue
*/
public Object peek() throws QueueClosedException {
Object retval=null;
synchronized(add_mutex) {
while(size == 0) {
if(closed)
throw new QueueClosedException();
try {
add_mutex.wait();
}
catch(IllegalMonitorStateException ex) {
throw ex;
}
catch(InterruptedException ex) {
}
}
if(closed)
throw new QueueClosedException();
retval=(head != null)? head.obj : null;
// @remove:
if(retval == null) {
// print some diagnostics
Trace.error("Queue.peek()", "retval is null: head=" + head + ", tail=" + tail + ", size()=" + size() +
", num_markers=" + num_markers + ", closed()=" + closed());
}
}
if(retval == endMarker) {
close(false); // mark queue as closed
throw new QueueClosedException();
}
return retval;
}
/**
* returns the first object on the queue, without removing it.
* If the queue is empty this object blocks until the first queue object has
* been added or the operation times out
* @param timeout how long in milli seconds will this operation wait for an object to be added to the queue
* before it times out
* @return the first object on the queue
*/
public Object peek(long timeout) throws QueueClosedException, TimeoutException {
Object retval=null;
synchronized(add_mutex) {
if(size == 0) {
if(closed)
throw new QueueClosedException();
try {
add_mutex.wait(timeout);
}
catch(IllegalMonitorStateException ex) {
throw ex;
}
catch(IllegalArgumentException ex2) {
throw ex2;
}
catch(InterruptedException ex) {
}
}
if(closed)
throw new QueueClosedException();
retval=head != null? head.obj : null;
if(retval == null) throw new TimeoutException();
if(retval == endMarker) {
close(false);
throw new QueueClosedException();
}
return retval;
}
}
/**
Marks the queues as closed. When an <code>add</code> or <code>remove</code> operation is
attempted on a closed queue, an exception is thrown.
@param flush_entries When true, a end-of-entries marker is added to the end of the queue.
Entries may be added and removed, but when the end-of-entries marker
is encountered, the queue is marked as closed. This allows to flush
pending messages before closing the queue.
*/
public void close(boolean flush_entries) {
if(flush_entries) {
try {
add(endMarker); // add an end-of-entries marker to the end of the queue
num_markers++;
}
catch(QueueClosedException closed) {
}
return;
}
synchronized(add_mutex) {
closed=true;
add_mutex.notifyAll();
}
// synchronized(remove_mutex) {
// remove_mutex.notifyAll();
}
/**
* resets the queue.
* This operation removes all the objects in the queue and marks the queue open
*/
public void reset() {
num_markers=0;
if(!closed)
close(false);
synchronized(add_mutex) {
size=0;
head=null;
tail=null;
closed=false;
add_mutex.notifyAll();
}
// synchronized(remove_mutex) {
// remove_mutex.notifyAll();
}
/**
* returns the number of objects that are currently in the queue
*/
public int size() {
return size - num_markers;
}
/**
* prints the size of the queue
*/
public String toString() {
return "Queue (" + size() + ") messages";
}
/**
* Dumps internal state @remove
*/
public String debug() {
return toString() + ", head=" + head + ", tail=" + tail + ", closed()=" + closed() + ", contents=" + getContents();
}
/**
* returns a vector with all the objects currently in the queue
*/
public Vector getContents() {
Vector retval=new Vector();
Element el;
synchronized(add_mutex) {
el=head;
while(el != null) {
retval.addElement(el.obj);
el=el.next;
}
}
return retval;
}
/**
* Blocks until the queue has no elements left. If the queue is empty, the call will return
* immediately
* @param timeout Call returns if timeout has elapsed (number of milliseconds). 0 means to wait forever
* @throws QueueClosedException Thrown if queue has been closed
* @throws TimeoutException Thrown if timeout has elapsed
*/
/*public void waitUntilEmpty(long timeout) throws QueueClosedException, TimeoutException {
long time_to_wait=timeout;
synchronized(remove_mutex) {
if(timeout == 0) {
while(size > 0 && closed == false) {
try {
remove_mutex.wait(0);
}
catch(InterruptedException e) {
;
}
}
}
else {
long start_time=System.currentTimeMillis();
while(time_to_wait > 0 && size > 0 && closed == false) {
try {
remove_mutex.wait(time_to_wait);
}
catch(InterruptedException ex) {
}
time_to_wait-=(System.currentTimeMillis() - start_time);
}
if(size > 0)
throw new TimeoutException("queue has " + size + " elements");
}
if(closed)
throw new QueueClosedException();
}
}
*/
/**
* Removes the first element. Returns null if no elements in queue.
* Always called with add_mutex locked (we don't have to lock add_mutex ourselves)
*/
private Object removeInternal() {
Element retval;
/*if the head is null, the queue is empty*/
if(head == null)
return null;
retval=head; // head must be non-null now
head=head.next;
if(head == null)
tail=null;
decrementSize();
// if(size == 0) {
// synchronized(remove_mutex) {
// remove_mutex.notifyAll();
if(head != null && head.obj == endMarker) {
closed=true;
}
retval.next=null;
return retval.obj;
}
void decrementSize() {
size
if(size < 0)
size=0;
}
} |
package org.openhab.persistence.influxdb.internal;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Pong;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.openhab.core.items.GroupItem;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.library.items.ColorItem;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.DateTimeItem;
import org.openhab.core.library.items.DimmerItem;
import org.openhab.core.library.items.LocationItem;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.PointType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.persistence.FilterCriteria;
import org.openhab.core.persistence.FilterCriteria.Ordering;
import org.openhab.core.persistence.HistoricItem;
import org.openhab.core.persistence.PersistenceService;
import org.openhab.core.persistence.QueryablePersistenceService;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit.RetrofitError;
public class InfluxDBPersistenceService implements QueryablePersistenceService {
private static final String DEFAULT_URL = "http://127.0.0.1:8086";
private static final String DEFAULT_DB = "openhab";
private static final String DEFAULT_USER = "openhab";
private static final String DEFAULT_RETENTION_POLICY = "autogen";
private static final String DIGITAL_VALUE_OFF = "0";
private static final String DIGITAL_VALUE_ON = "1";
private static final String VALUE_COLUMN_NAME = "value";
private static final String VALUE_COLUMN_STRING_NAME = "value-string";
private static final String VALUE_COLUMN_INTEGER_NAME = "value-integer";
private static final String VALUE_COLUMN_DOUBLE_NAME = "value-double";
private static final String TYPE_COLUMN_NAME = "type-name";
private static final String ITEM_NAME_TAG = "item-name";
private ItemRegistry itemRegistry;
private InfluxDB influxDB;
private static final Logger logger = LoggerFactory.getLogger(InfluxDBPersistenceService.class);
private static final String TIME_COLUMN_NAME = "time";
private static final TimeUnit timeUnit = TimeUnit.MILLISECONDS;
private String dbName;
private String url;
private String user;
private String password;
private String retentionPolicy;
private String measurementName;
private boolean isProperlyConfigured;
private boolean connected;
public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
public void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
public void activate(final BundleContext bundleContext, final Map<String, Object> config) {
logger.debug("influxdb persistence service activated");
disconnect();
password = (String) config.get("password");
if (isBlank(password)) {
isProperlyConfigured = false;
logger.error("influxdb:password",
"The password is missing. To specify a password configure the password parameter in openhab.cfg.");
return;
}
url = (String) config.get("url");
if (isBlank(url)) {
url = DEFAULT_URL;
logger.debug("using default url {}", DEFAULT_URL);
}
user = (String) config.get("user");
if (isBlank(user)) {
user = DEFAULT_USER;
logger.debug("using default user {}", DEFAULT_USER);
}
dbName = (String) config.get("db");
if (isBlank(dbName)) {
dbName = DEFAULT_DB;
logger.debug("using default db name {}", DEFAULT_DB);
}
retentionPolicy = (String) config.get("retentionPolicy");
if (isBlank(retentionPolicy)) {
retentionPolicy = DEFAULT_RETENTION_POLICY;
logger.debug("using default retentionPolicy {}", DEFAULT_RETENTION_POLICY);
}
measurementName = (String) config.get("measurement");
if (isBlank(measurementName)) {
logger.debug("Using default storage schema");
} else {
logger.debug("Putting all values in central measurement");
}
isProperlyConfigured = true;
connect();
// check connection; errors will only be logged, hoping the connection will work at a later
// time.
if (!checkConnection()) {
logger.error("database connection does not work for now, will retry to use the database.");
}
}
public void deactivate() {
logger.debug("influxdb persistence service deactivated");
disconnect();
}
private void connect() {
if (influxDB == null) {
// reuse an existing InfluxDB object because concerning the database it has no state
// connection
influxDB = InfluxDBFactory.connect(url, user, password);
influxDB.enableBatch(200, 100, timeUnit);
}
connected = true;
}
private boolean checkConnection() {
boolean dbStatus = false;
if (!connected) {
logger.error("checkConnection: database is not connected");
dbStatus = false;
} else {
try {
Pong pong = influxDB.ping();
String version = pong.getVersion();
// may be check for version >= 0.9
if (version != null && !version.contains("unknown")) {
dbStatus = true;
logger.debug("database status is OK, version is {}", version);
} else {
logger.error("database ping error, version is: \"{}\" response time was \"{}\"", version,
pong.getResponseTime());
dbStatus = false;
}
} catch (RuntimeException e) {
dbStatus = false;
logger.error("database connection failed", e);
handleDatabaseException(e);
}
}
return dbStatus;
}
private void disconnect() {
influxDB = null;
connected = false;
}
private boolean isConnected() {
return connected;
}
@Override
public String getName() {
return "influxdb";
}
@Override
public void store(Item item) {
store(item, null);
}
/**
* {@inheritDoc}
*/
@Override
public void store(Item item, String alias) {
if (item.getState() instanceof UnDefType) {
return;
}
if (!isProperlyConfigured) {
logger.warn("Configuration for influxdb not yet loaded or broken.");
return;
}
if (!isConnected()) {
logger.warn("InfluxDB is not yet connected");
return;
}
String realName = item.getName();
String name = (alias != null) ? alias : realName;
State state = null;
if (item.getAcceptedCommandTypes().contains(HSBType.class)) {
state = item.getStateAs(HSBType.class);
logger.trace("Tried to get item as {}, state is {}", HSBType.class, state.toString());
} else if (item.getAcceptedDataTypes().contains(PercentType.class)) {
state = item.getStateAs(PercentType.class);
logger.trace("Tried to get item as {}, state is {}", PercentType.class, state.toString());
} else {
// All other items should return the best format by default
state = item.getState();
logger.trace("Tried to get item from item class {}, state is {}", item.getClass(), state.toString());
}
Point point;
if (isBlank(measurementName)) {
Object value = stateToObject(state);
logger.trace("storing {} in influxdb value {}, {}", name, value, item);
point = Point.measurement(name).field(VALUE_COLUMN_NAME, value).time(System.currentTimeMillis(), timeUnit)
.build();
} else {
point = stateToPoint(item);
logger.trace("storing point {}", point);
}
try {
influxDB.write(dbName, retentionPolicy, point);
} catch (RuntimeException e) {
logger.error("storing failed with exception for item: {}", name);
handleDatabaseException(e);
}
}
private void handleDatabaseException(Exception e) {
if (e instanceof RetrofitError) {
// e.g. raised if influxdb is not running
logger.error("database connection error {}", e.getMessage());
} else if (e instanceof RuntimeException) {
// e.g. raised by authentication errors
logger.error("database error: {}", e.getMessage());
}
}
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
logger.debug("got a query");
if (!isProperlyConfigured) {
logger.warn("Configuration for influxdb not yet loaded or broken.");
return Collections.emptyList();
}
if (!isConnected()) {
logger.warn("InfluxDB is not yet connected");
return Collections.emptyList();
}
List<HistoricItem> historicItems = new ArrayList<HistoricItem>();
StringBuffer query;
if (!isBlank(measurementName)) {
query = getSingleMeasurementQuery(filter);
} else {
query = getMultiMeasurementQuery(filter);
}
logger.trace(
"Filter: itemname: {}, ordering: {}, state: {}, operator: {}, getBeginDate: {}, getEndDate: {}, getPageSize: {}, getPageNumber: {}",
filter.getItemName(), filter.getOrdering().toString(), filter.getState(), filter.getOperator(),
filter.getBeginDate(), filter.getEndDate(), filter.getPageSize(), filter.getPageNumber());
if ((!isBlank(measurementName) || filter.getState() != null && filter.getOperator() != null)
|| filter.getBeginDate() != null || filter.getEndDate() != null) {
query.append(" and ");
boolean foundState = false;
boolean foundBeginDate = false;
if (filter.getState() != null && filter.getOperator() != null) {
String value = stateToString(filter.getState());
if (value != null) {
foundState = true;
query.append(VALUE_COLUMN_NAME);
query.append(" ");
query.append(filter.getOperator().toString());
query.append(" ");
query.append(value);
}
}
if (filter.getBeginDate() != null) {
foundBeginDate = true;
if (foundState) {
query.append(" and");
}
query.append(" ");
query.append(TIME_COLUMN_NAME);
query.append(" > ");
query.append(getTimeFilter(filter.getBeginDate()));
query.append(" ");
}
if (filter.getEndDate() != null) {
if (foundState || foundBeginDate) {
query.append(" and");
}
query.append(" ");
query.append(TIME_COLUMN_NAME);
query.append(" < ");
query.append(getTimeFilter(filter.getEndDate()));
query.append(" ");
}
}
if (filter.getOrdering() == Ordering.DESCENDING) {
query.append(String.format(" ORDER BY %s DESC", TIME_COLUMN_NAME));
logger.debug("descending ordering ");
}
int limit = (filter.getPageNumber() + 1) * filter.getPageSize();
query.append(" limit " + limit);
logger.trace("appending limit {}", limit);
int totalEntriesAffected = ((filter.getPageNumber() + 1) * filter.getPageSize());
int startEntryNum = totalEntriesAffected
- (totalEntriesAffected - (filter.getPageSize() * filter.getPageNumber()));
logger.trace("startEntryNum {}", startEntryNum);
logger.debug("query string: {}", query.toString());
Query influxdbQuery = new Query(query.toString(), dbName);
List<Result> results = Collections.emptyList();
results = influxDB.query(influxdbQuery, timeUnit).getResults();
for (Result result : results) {
List<Series> seriess = result.getSeries();
if (result.getError() != null) {
logger.error(result.getError());
continue;
}
if (seriess == null) {
logger.debug("query returned no series");
} else {
for (Series series : seriess) {
logger.trace("series {}", series.toString());
// TODO: get name
String historicItemName = filter.getItemName();
List<List<Object>> valuess = series.getValues();
if (valuess == null) {
logger.debug("query returned no values");
} else {
List<String> columns = series.getColumns();
logger.trace("columns {}", columns);
Integer timestampColumn = null;
Integer valueColumn = null;
for (int i = 0; i < columns.size(); i++) {
String columnName = columns.get(i);
if (columnName.equals(TIME_COLUMN_NAME)) {
logger.debug("Time: {}", columnName);
timestampColumn = i;
} else if (columnName.equals(VALUE_COLUMN_NAME)) {
valueColumn = i;
} else if (columnName.equals(TYPE_COLUMN_NAME)) {
logger.debug("Type: {}", columnName);
String column_name = valuess.get(0).get(i).toString();
logger.debug("Type-name: {}", column_name);
for (int a = 0; a < columns.size(); a++) {
String columTypeName = columns.get(a);
if (columTypeName.equals(column_name)) {
valueColumn = a;
logger.debug("Type-Index: {}", a);
break;
}
}
}
}
if (valueColumn == null || timestampColumn == null) {
throw new RuntimeException("missing column");
}
for (int i = 0; i < valuess.size(); i++) {
Double rawTime = (Double) valuess.get(i).get(timestampColumn);
Date time = new Date(rawTime.longValue());
State value = objectToState(valuess.get(i).get(valueColumn), historicItemName);
logger.debug("adding historic item {}: time {} value {}", historicItemName, time, value);
historicItems.add(new InfluxdbItem(historicItemName, value, time));
}
}
}
}
}
return historicItems;
}
private StringBuffer getSingleMeasurementQuery(FilterCriteria filter) {
StringBuffer query = new StringBuffer();
query.append("select ").append("*").append(" from \"").append(retentionPolicy).append("\".\"")
.append(measurementName).append("\" ");
if (filter.getItemName() != null) {
query.append("where \"").append(ITEM_NAME_TAG).append("\" = '").append(filter.getItemName()).append("' ");
}
return query;
}
private StringBuffer getMultiMeasurementQuery(FilterCriteria filter) {
StringBuffer query = new StringBuffer();
query.append("select ").append(VALUE_COLUMN_NAME).append(' ').append("from \"").append(retentionPolicy)
.append("\".");
if (filter.getItemName() != null) {
query.append('"').append(filter.getItemName()).append('"');
} else {
query.append("/.*/");
}
return query;
}
private String getTimeFilter(Date time) {
// for some reason we need to query using 'seconds' only
// passing milli seconds causes no results to be returned
long milliSeconds = time.getTime();
long seconds = milliSeconds / 1000;
return seconds + "s";
}
/**
* This method returns an integer if possible if not a double is returned. This is an optimization
* for influxdb because integers have less overhead.
*
* @param value the BigDecimal to be converted
* @return A double if possible else a double is returned.
*/
private Object convertBigDecimalToNum(BigDecimal value) {
Object convertedValue;
if (value.scale() == 0) {
logger.trace("found no fractional part");
convertedValue = value.toBigInteger();
} else {
logger.trace("found fractional part");
convertedValue = value.doubleValue();
}
return convertedValue;
}
/**
* Converts {@link State} to objects fitting into influxdb values.
*
* @param state to be converted
* @return integer or double value for DecimalType, 0 or 1 for OnOffType and OpenClosedType,
* integer for DateTimeType, String for all others
*/
private Object stateToObject(State state) {
Object value;
if (state instanceof HSBType) {
value = ((HSBType) state).toString();
logger.debug("got HSBType value {}", value);
} else if (state instanceof PointType) {
value = point2String((PointType) state);
logger.debug("got PointType value {}", value);
} else if (state instanceof DecimalType) {
value = convertBigDecimalToNum(((DecimalType) state).toBigDecimal());
logger.debug("got DecimalType value {}", value);
} else if (state instanceof OnOffType) {
value = (OnOffType) state == OnOffType.ON ? 1 : 0;
logger.debug("got OnOffType value {}", value);
} else if (state instanceof OpenClosedType) {
value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0;
logger.debug("got OpenClosedType value {}", value);
} else if (state instanceof DateTimeType) {
value = ((DateTimeType) state).getCalendar().getTime().getTime();
logger.debug("got DateTimeType value {}", value);
} else {
value = state.toString();
logger.debug("got String value {}", value);
}
return value;
}
/**
* Converts {@link State} to a String suitable for influxdb queries.
*
* @param state to be converted
* @return {@link String} equivalent of the {@link State}
*/
private String stateToString(State state) {
String value;
if (state instanceof DecimalType) {
value = ((DecimalType) state).toBigDecimal().toString();
} else if (state instanceof PointType) {
value = point2String((PointType) state);
} else if (state instanceof OnOffType) {
value = ((OnOffType) state) == OnOffType.ON ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF;
} else if (state instanceof OpenClosedType) {
value = ((OpenClosedType) state) == OpenClosedType.OPEN ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF;
} else if (state instanceof HSBType) {
value = ((HSBType) state).toString();
} else if (state instanceof DateTimeType) {
value = String.valueOf(((DateTimeType) state).getCalendar().getTime().getTime());
} else {
value = state.toString();
}
return value;
}
/**
* Converts a value to a {@link State} which is suitable for the given {@link Item}. This is
* needed for querying a {@link HistoricState}.
*
* @param value to be converted to a {@link State}
* @param itemName name of the {@link Item} to get the {@link State} for
* @return the state of the item represented by the itemName parameter, else the string value of
* the Object parameter
*/
private State objectToState(Object value, String itemName) {
String valueStr = String.valueOf(value);
if (itemRegistry != null) {
try {
Item item = itemRegistry.getItem(itemName);
if (item instanceof GroupItem) {
item = ((GroupItem) item).getBaseItem();
}
if (item instanceof ColorItem) {
logger.debug("objectToState found a ColorItem {}", valueStr);
return new HSBType(valueStr);
} else if (item instanceof LocationItem) {
logger.debug("objectToState found a LocationItem");
return new PointType(valueStr);
} else if (item instanceof NumberItem) {
logger.debug("objectToState found a NumberItem");
return new DecimalType(valueStr);
} else if (item instanceof DimmerItem) {
logger.debug("objectToState found a DimmerItem");
return new PercentType(valueStr);
} else if (item instanceof SwitchItem) {
logger.debug("objectToState found a SwitchItem");
return string2DigitalValue(valueStr).equals(DIGITAL_VALUE_OFF) ? OnOffType.OFF : OnOffType.ON;
} else if (item instanceof ContactItem) {
logger.debug("objectToState found a ContactItem");
return (string2DigitalValue(valueStr).equals(DIGITAL_VALUE_OFF)) ? OpenClosedType.CLOSED
: OpenClosedType.OPEN;
} else if (item instanceof RollershutterItem) {
logger.debug("objectToState found a RollershutterItem");
return new PercentType(valueStr);
} else if (item instanceof DateTimeItem) {
logger.debug("objectToState found a DateItem");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new BigDecimal(valueStr).longValue());
return new DateTimeType(calendar);
} else {
logger.debug("objectToState found a other Item");
return new StringType(valueStr);
}
} catch (ItemNotFoundException e) {
logger.warn("Could not find item '{}' in registry", itemName);
}
}
// just return a StringType as a fallback
return new StringType(valueStr);
}
/**
* Maps a string value which expresses a {@link BigDecimal.ZERO } to DIGITAL_VALUE_OFF, all others
* to DIGITAL_VALUE_ON
*
* @param value to be mapped
* @return
*/
private String string2DigitalValue(String value) {
BigDecimal num = new BigDecimal(value);
if (num.compareTo(BigDecimal.ZERO) == 0) {
logger.trace("digitalvalue {}", DIGITAL_VALUE_OFF);
return DIGITAL_VALUE_OFF;
} else {
logger.trace("digitalvalue {}", DIGITAL_VALUE_ON);
return DIGITAL_VALUE_ON;
}
}
private String point2String(PointType point) {
StringBuffer buf = new StringBuffer();
buf.append(point.getLatitude().toString());
buf.append(",");
buf.append(point.getLongitude().toString());
if (point.getAltitude().equals(0)) {
buf.append(",");
buf.append(point.getAltitude().toString());
}
return buf.toString(); // latitude, longitude, altitude
}
private Point stateToPoint(Item item) {
Point point;
State state = item.getState();
if (state instanceof HSBType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, ((HSBType) state).toString())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got HSBType value {}", point);
} else if (state instanceof PointType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, point2String((PointType) state))
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got PointType value {}", point);
} else if (state instanceof DecimalType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_DOUBLE_NAME, ((DecimalType) state).doubleValue())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_DOUBLE_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got DecimalType value {}", point);
} else if (state instanceof OnOffType) {
int value = (OnOffType) state == OnOffType.ON ? 1 : 0;
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got OnOffType value {}", point);
} else if (state instanceof OpenClosedType) {
int value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0;
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got OpenClosedType value {}", point);
} else if (state instanceof DateTimeType) {
long value = ((DateTimeType) state).getCalendar().getTime().getTime();
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got DateTimeType value {}", point);
} else {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, state.toString())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got String value {}", point);
}
return point;
}
} |
package com.sajo.teamkerbell.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table
@EqualsAndHashCode(of = {"projectId"})
@Data
@NoArgsConstructor
@ToString(exclude = "users")
public class Project implements Serializable {
private static final long serialVersionUID = 7463383057597003838L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Integer projectId;
@NotNull
@Column
private String name;
@Column
private Integer leaderId;
@Column
private String minute;
@Column
private boolean finished = false;
@Column
private boolean deleted = false;
@Column
private LocalDate createdAt;
@Column
private LocalDate updatedAt;
@ManyToMany(mappedBy = "projects", fetch = FetchType.EAGER)
private List<User> users = new ArrayList<>();
@PrePersist
protected void onCreate() {
updatedAt = createdAt = LocalDate.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDate.now();
}
public Project(String name, Integer leaderId, String minute) {
this.name = name;
this.leaderId = leaderId;
this.minute = minute;
}
void addUser(User user) {
this.users.add(user);
}
void removeUser(User user) {
this.users.remove(user);
}
public void finished() {
this.finished = true;
}
public void deleted() {
this.deleted = true;
}
public void updateMinute(Minute minute) {
this.minute = minute != null ? minute.getContent() : " ";
}
} |
package dr.evomodel.substmodel;
import dr.evolution.datatype.TwoStateCovarion;
import dr.evomodelxml.substmodel.BinaryCovarionModelParser;
import dr.inference.model.Parameter;
/**
* @author Alexei Drummond
* <p/>
* a the rate of the slow rate class
* 1 the rate of the fast rate class
* p0 the equilibrium frequency of zero states
* p1 1 - p0, the equilibrium frequency of one states
* f0 the equilibrium frequency of slow rate class
* f1 1 - f0, the equilibrium frequency of fast rate class
* s the rate of switching
* <p/>
* then the (unnormalized) instantaneous rate matrix (unnormalized Q) should be
* <p/>
* [ . , a*p1 , s*f1 , 0 ]
* [ a*p0 , . , 0 , s*f1 ]
* [ s*f0 , 0 , . , p1 ]
* [ 0 , s*f0 , p0 , . ]
*/
public class BinaryCovarionModel extends AbstractCovarionModel {
/**
* @param dataType the data type
* @param frequencies the frequencies of the visible states
* @param hiddenFrequencies the frequencies of the hidden rates
* @param alphaParameter the rate of evolution in slow mode
* @param switchingParameter the rate of flipping between slow and fast modes
*/
public BinaryCovarionModel(TwoStateCovarion dataType,
Parameter frequencies,
Parameter hiddenFrequencies,
Parameter alphaParameter,
Parameter switchingParameter) {
super(BinaryCovarionModelParser.COVARION_MODEL, dataType, frequencies, hiddenFrequencies);
alpha = alphaParameter;
this.switchRate = switchingParameter;
this.frequencies = frequencies;
this.hiddenFrequencies = hiddenFrequencies;
addVariable(alpha);
addVariable(switchRate);
addVariable(frequencies);
addVariable(hiddenFrequencies);
setupUnnormalizedQMatrix();
}
protected void setupUnnormalizedQMatrix() {
double a = alpha.getParameterValue(0);
double s = switchRate.getParameterValue(0);
double f0 = hiddenFrequencies.getParameterValue(0);
double f1 = hiddenFrequencies.getParameterValue(1);
double p0 = frequencies.getParameterValue(0);
double p1 = frequencies.getParameterValue(1);
assert Math.abs(1.0 - f0 - f1) < 1e-8;
assert Math.abs(1.0 - p0 - p1) < 1e-8;
unnormalizedQ[0][1] = a * p1;
unnormalizedQ[0][2] = s * f1;
unnormalizedQ[0][3] = 0.0;
unnormalizedQ[1][0] = a * p0;
unnormalizedQ[1][2] = 0.0;
unnormalizedQ[1][3] = s * f1;
unnormalizedQ[2][0] = s * f0;
unnormalizedQ[2][1] = 0.0;
unnormalizedQ[2][3] = p1;
unnormalizedQ[3][0] = 0.0;
unnormalizedQ[3][1] = s * f0;
unnormalizedQ[3][2] = p0;
}
protected void frequenciesChanged() {
}
protected void ratesChanged() {
}
public String toString() {
return SubstitutionModelUtils.toString(unnormalizedQ, dataType, 2);
}
/**
* Normalize rate matrix to one expected substitution per unit time
*
* @param matrix the matrix to normalize to one expected substitution
* @param pi the equilibrium distribution of states
*/
void normalize(double[][] matrix, double[] pi) {
double subst = 0.0;
int dimension = pi.length;
for (int i = 0; i < dimension; i++) {
subst += -matrix[i][i] * pi[i];
}
// normalize, including switches
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
matrix[i][j] = matrix[i][j] / subst;
}
}
double switchingProportion = 0.0;
switchingProportion += matrix[0][2] * pi[2];
switchingProportion += matrix[2][0] * pi[0];
switchingProportion += matrix[1][3] * pi[3];
switchingProportion += matrix[3][1] * pi[1];
//System.out.println("switchingProportion=" + switchingProportion);
// normalize, removing switches
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion);
}
}
}
private Parameter alpha;
private Parameter switchRate;
private Parameter frequencies;
private Parameter hiddenFrequencies;
} |
package org.deviceconnect.profile;
/**
* Media Stream Recording Profile API .<br/>
* Media Stream Recording Profile API
*
* @author NTT DOCOMO, INC.
*/
public interface MediaStreamRecordingProfileConstants extends DConnectProfileConstants {
/**
* : {@value} .
*/
String PROFILE_NAME = "mediastream_recording";
/**
* : {@value} .
*/
String ATTRIBUTE_MEDIARECORDER = "mediarecorder";
/**
* : {@value} .
*/
String ATTRIBUTE_TAKE_PHOTO = "takephoto";
/**
* : {@value} .
*/
String ATTRIBUTE_RECORD = "record";
/**
* : {@value} .
*/
String ATTRIBUTE_PAUSE = "pause";
/**
* : {@value} .
*/
String ATTRIBUTE_RESUME = "resume";
/**
* : {@value} .
*/
String ATTRIBUTE_STOP = "stop";
/**
* : {@value} .
*/
String ATTRIBUTE_MUTETRACK = "mutetrack";
/**
* : {@value} .
*/
String ATTRIBUTE_UNMUTETRACK = "unmutetrack";
/**
* : {@value} .
*/
String ATTRIBUTE_OPTIONS = "options";
/**
* : {@value} .
*/
String ATTRIBUTE_ON_PHOTO = "onphoto";
/**
* : {@value} .
* @deprecated This parameter is deprecated.
*/
String ATTRIBUTE_ON_DATA_AVAILABLE = "ondataavailable";
/**
* : {@value}.
*/
String ATTRIBUTE_PREVIEW = "preview";
/**
* : {@value} .
*/
String ATTRIBUTE_ON_RECORDING_CHANGE = "onrecordingchange";
/**
* : {@value}.
*/
String PATH_PROFILE = PATH_ROOT + SEPARATOR + PROFILE_NAME;
/**
* : {@value} .
*/
String PATH_MEDIARECORDER = PATH_PROFILE + SEPARATOR + ATTRIBUTE_MEDIARECORDER;
/**
* : {@value} .
*/
String PATH_PHOTO = PATH_PROFILE + SEPARATOR + ATTRIBUTE_TAKE_PHOTO;
/**
* : {@value} .
*/
String PATH_RECORD = PATH_PROFILE + SEPARATOR + ATTRIBUTE_RECORD;
/**
* : {@value} .
*/
String PATH_PAUSE = PATH_PROFILE + SEPARATOR + ATTRIBUTE_PAUSE;
/**
* : {@value} .
*/
String PATH_RESUME = PATH_PROFILE + SEPARATOR + ATTRIBUTE_RESUME;
/**
* : {@value} .
*/
String PATH_STOP = PATH_PROFILE + SEPARATOR + ATTRIBUTE_STOP;
/**
* : {@value} .
*/
String PATH_MUTETRACK = PATH_PROFILE + SEPARATOR + ATTRIBUTE_MUTETRACK;
/**
* : {@value} .
*/
String PATH_UNMUTETRACK = PATH_PROFILE + SEPARATOR + ATTRIBUTE_UNMUTETRACK;
/**
* : {@value} .
*/
String PATH_OPTIONS = PATH_PROFILE + SEPARATOR + ATTRIBUTE_OPTIONS;
/**
* : {@value} .
*/
String PATH_ON_PHOTO = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_PHOTO;
/**
* : {@value} .
* @deprecated This parameter is deprecated.
*/
String PATH_ON_DATA_AVAILABLE = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_DATA_AVAILABLE;
/**
* : {@value} .
*/
String PATH_ON_RECORDING_CHANGE = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_RECORDING_CHANGE;
/**
* : {@value}.
*/
String PATH_PREVIEW = PATH_PROFILE + SEPARATOR + ATTRIBUTE_PREVIEW;
/**
* : {@value} .
*/
String PARAM_TARGET = "target";
/**
* : {@value} .
*/
String PARAM_RECORDERS = "recorders";
/**
* : {@value} .
*/
String PARAM_ID = "id";
/**
* : {@value} .
*/
String PARAM_NAME = "name";
/**
* : {@value} .
*/
String PARAM_STATE = "state";
/**
* : {@value} .
*/
String PARAM_IMAGE_WIDTH = "imageWidth";
/**
* : {@value} .
*/
String PARAM_IMAGE_HEIGHT = "imageHeight";
/**
* : {@value} .
*/
String PARAM_PREVIEW_WIDTH = "previewWidth";
/**
* : {@value} .
*/
String PARAM_PREVIEW_HEIGHT = "previewHeight";
/**
* : {@value} .
*/
String PARAM_PREVIEW_MAX_FRAME_RATE = "previewMaxFrameRate";
/**
* : {@value} .
*/
String PARAM_AUDIO = "audio";
/**
* : {@value} .
*/
String PARAM_CHANNELS = "channels";
/**
* : {@value} .
*/
String PARAM_SAMPLE_RATE = "sampleRate";
/**
* : {@value} .
*/
String PARAM_SAMPLE_SIZE = "sampleSize";
/**
* : {@value} .
*/
String PARAM_BLOCK_SIZE = "blockSize";
/**
* : {@value} .
*/
String PARAM_MIME_TYPE = "mimeType";
/**
* : {@value} .
*/
String PARAM_CONFIG = "config";
/**
* : {@value} .
*/
String PARAM_IMAGE_SIZES = "imageSizes";
/**
* : {@value} .
*/
String PARAM_PREVIEW_SIZES = "previewSizes";
/**
* : {@value} .
*/
String PARAM_WIDTH = "width";
/**
* : {@value} .
*/
String PARAM_HEIGHT = "height";
/**
* : {@value} .
*/
String PARAM_TIME_SLICE = "timeslice";
/**
* : {@value} .
*/
String PARAM_SETTINGS = "settings";
/**
* : {@value} .
*/
String PARAM_PHOTO = "photo";
/**
* : {@value} .
*/
String PARAM_MEDIA = "media";
/**
* : {@value} .
*/
String PARAM_STATUS = "status";
/**
* : {@value} .
*/
String PARAM_ERROR_MESSAGE = "errorMessage";
/**
* : {@value} .
*/
String PARAM_PATH = "path";
/**
* : {@value} .
* @deprecated
*/
String PARAM_MIN = "min";
/**
* : {@value} .
* @deprecated
*/
String PARAM_MAX = "max";
enum RecorderState {
UNKNOWN("Unknown"),
INACTIVE("inactive"),
RECORDING("recording"),
PAUSED("paused");
private String mValue;
/**
* .
*
* @param value
*/
private RecorderState(final String value) {
this.mValue = value;
}
/**
* .
*
* @return
*/
public String getValue() {
return mValue;
}
/**
* .
*
* @param value
* @return
*/
public static RecorderState getInstance(final String value) {
for (RecorderState state : values()) {
if (state.getValue().equals(value)) {
return state;
}
}
return UNKNOWN;
}
}
enum RecordingState {
UNKNOWN("Unknown"),
RECORDING("recording"),
STOP("stop"),
PAUSE("pause"),
RESUME("resume"),
MUTETRACK("mutetrack"),
UNMUTETRACK("unmutetrack"),
ERROR("error"),
WARNING("warning");
private String mValue;
/**
* .
*
* @param value
*/
private RecordingState(final String value) {
this.mValue = value;
}
/**
* .
*
* @return
*/
public String getValue() {
return mValue;
}
/**
* .
*
* @param value
* @return
*/
public static RecordingState getInstance(final String value) {
for (RecordingState state : values()) {
if (state.getValue().equals(value)) {
return state;
}
}
return UNKNOWN;
}
}
} |
package mil.emp3.api.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
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.net.URI;
import java.util.Deque;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtility
{
/**
* Private Constructor to avoid instantiation of the class
*/
private ZipUtility()
{
}
private final static int BUFFER = 2048;
/**
* Zips a file at a location and places the resulting zip file at the toLocation
* Example: zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
*
* @param directory the location of the file/folder that needs to be zipped
* @param zipfile the location where the file/folder will be zipped to
* @return true if the zipping was successful, false otherwise
*/
public static void zip(File directory, File zipfile) throws IOException
{
URI base = directory.toURI();
Deque<File> queue = new LinkedList<File>();
queue.push(directory);
try (OutputStream out = new FileOutputStream(zipfile);
ZipOutputStream zout = new ZipOutputStream(out);)
{
while (!queue.isEmpty())
{
directory = queue.pop();
for (File kid : directory.listFiles())
{
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory())
{
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
}
else
{
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
while (true)
{
int readCount = in.read(buffer);
if (readCount < 0)
{
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException
{
try (InputStream in = new FileInputStream(file))
{
copy(in, out);
}
}
} |
package com.scriptandscroll.adt;
import com.scriptandscroll.exceptions.InvalidValueException;
import java.util.ArrayList;
import java.util.List;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Serializer;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.HSuperColumn;
/**
*
* @author Courtney
*/
public class SuperColumn extends ColumnContainer implements Savable {
private String name;
private Serializer namese;
private Serializer supernamese;
private Serializer valuese;
public SuperColumn() {
supernamese = new StringSerializer();
namese = new StringSerializer();
valuese = new StringSerializer();
}
/**
* Create a super column with no sub-columns
* @param name the name of the super column
* @throws InvalidValueException if name is empty or null
*/
public SuperColumn(String name) {
this(name, new ArrayList<Column>());
}
public SuperColumn(HSuperColumn<String, String, String> col) {
this();
this.name = col.getName();
fromHectorList(col.getColumns());
}
public SuperColumn(String name, List<HColumn<String, String>> cols) {
this();
this.name = name;
fromHectorList(cols);
}
private void fromHectorList(List<HColumn<String, String>> cols) {
for (HColumn<String, String> c : cols) {
putColumn(new Column(c));
}
}
/**
* Create a super column with a list of sub columns
* @param name the name of the super column within the row
* @param columns a list of sub columns to add
* @throws InvalidValueException if name is empty or null
*/
public SuperColumn(String name, ArrayList<Column> columns) {
this();
if (name == null || name.isEmpty()) {
throw new InvalidValueException("The name of a column cannot be null or empty!");
}
this.name = name;
for (Column col : columns) {
putColumn(col);
}
}
/**
*
* @return Get the name of this Super column
*/
public String getName() {
return name;
}
/**
* The serializer to be used on sub column names
* @param s
*/
public final void setNameSerializer(Serializer s) {
namese = s;
}
/**
* Set the serializer for the super column names
* @param s
*/
public final void setSuperNameSerializer(Serializer s) {
supernamese = s;
}
/**
* The serializer to be used on the sub column's values
* @param s
*/
public final void setValueSerializer(Serializer s) {
valuese = s;
}
/**
* The serializer to be used on this column's name
*/
public Serializer getNameSerializer() {
return namese;
}
/**
* The serializer to be used on this column's value
*/
public Serializer getValueSerializer() {
return valuese;
}
/**
* get the serializer for the super column names
* @param s
*/
public final Serializer getSuperNameSerializer() {
return supernamese;
}
} |
package dr.evomodel.treelikelihood;
import dr.evolution.alignment.PatternList;
import dr.evolution.util.TaxonList;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.sitemodel.SiteModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.xml.*;
/**
* @author Andrew Rambaut
* @version $Id$
*/
public class ADNADamageModel extends TipPartialsModel {
public static final String ADNA_DAMAGE_MODEL = "aDNADamageModel";
public static final String BASE_DAMAGE_RATE = "baseDamageRate";
public static final String AGE_RATE_FACTOR = "ageRateFactor";
public static final String EXCLUDE = "exclude";
public static final String INCLUDE = "include";
public ADNADamageModel(TreeModel treeModel, TaxonList includeTaxa, TaxonList excludeTaxa, Parameter baseDamageRateParameter, Parameter ageRateFactorParameter) {
super(ADNA_DAMAGE_MODEL, treeModel, includeTaxa, excludeTaxa);
this.baseDamageRateParameter = baseDamageRateParameter;
this.ageRateFactorParameter = ageRateFactorParameter;
}
public double[] getTipPartials(int nodeIndex) {
if (updatePartials) {
double base = baseDamageRateParameter.getParameterValue(0);
double factor = ageRateFactorParameter.getParameterValue(0);
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
int[] states = this.states[i];
double[] partials = this.partials[i];
if (!excluded[i]) {
double age = treeModel.getNodeHeight(treeModel.getExternalNode(i));
double pUndamaged = (1.0 - base) * Math.exp(-factor * age);
int k = 0;
for (int j = 0; j < patternCount; j++) {
switch (states[j]) {
case 0: // is an A
partials[k] = pUndamaged;
partials[k + 1] = 0.0;
partials[k + 2] = 1.0 - pUndamaged;
partials[k + 3] = 0.0;
break;
case 1: // is an C
partials[k] = 0.0;
partials[k + 1] = pUndamaged;
partials[k + 2] = 0.0;
partials[k + 3] = 1.0 - pUndamaged;
break;
case 2: // is an G
partials[k] = 1.0 - pUndamaged;
partials[k + 1] = 0.0;
partials[k + 2] = pUndamaged;
partials[k + 3] = 0.0;
break;
case 3: // is an T
partials[k] = 0.0;
partials[k + 1] = 1.0 - pUndamaged;
partials[k + 2] = 0.0;
partials[k + 3] = pUndamaged;
break;
default: // is an ambiguity
partials[k] = 1.0;
partials[k + 1] = 1.0;
partials[k + 2] = 1.0;
partials[k + 3] = 1.0;
}
k += stateCount;
}
} else {
int k = 0;
for (int j = 0; j < patternCount; j++) {
switch (states[j]) {
case 0: // is an A
partials[k] = 1.0;
partials[k + 1] = 0.0;
partials[k + 2] = 0.0;
partials[k + 3] = 0.0;
break;
case 1: // is an C
partials[k] = 0.0;
partials[k + 1] = 1.0;
partials[k + 2] = 0.0;
partials[k + 3] = 0.0;
break;
case 2: // is an G
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 1.0;
partials[k + 3] = 0.0;
break;
case 3: // is an T
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 0.0;
partials[k + 3] = 1.0;
break;
default: // is an ambiguity
partials[k] = 1.0;
partials[k + 1] = 1.0;
partials[k + 2] = 1.0;
partials[k + 3] = 1.0;
}
k += stateCount;
}
}
}
updatePartials = false;
}
return partials[nodeIndex];
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return ADNA_DAMAGE_MODEL; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel)xo.getChild(TreeModel.class);
Parameter baseDamageRateParameter = (Parameter)xo.getSocketChild(BASE_DAMAGE_RATE);
Parameter ageRateFactorParameter = (Parameter)xo.getSocketChild(AGE_RATE_FACTOR);
TaxonList includeTaxa = null;
TaxonList excludeTaxa = null;
if (xo.hasSocket(INCLUDE)) {
includeTaxa = (TaxonList)xo.getSocketChild(INCLUDE);
}
if (xo.hasSocket(EXCLUDE)) {
excludeTaxa = (TaxonList)xo.getSocketChild(EXCLUDE);
}
ADNADamageModel aDNADamageModel = new ADNADamageModel(treeModel, includeTaxa, excludeTaxa, baseDamageRateParameter, ageRateFactorParameter);
System.out.println("Using aDNA damage model.");
return aDNADamageModel;
} |
package io.subutai.core.registration.impl;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.net.util.SubnetUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.subutai.common.command.CommandException;
import io.subutai.common.command.CommandResult;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.environment.Environment;
import io.subutai.common.environment.NodeGroup;
import io.subutai.common.environment.Topology;
import io.subutai.common.host.ContainerHostInfo;
import io.subutai.common.host.HostInterface;
import io.subutai.common.host.HostInterfaceModel;
import io.subutai.common.host.ResourceHostInfo;
import io.subutai.common.metric.QuotaAlertValue;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.ContainerSize;
import io.subutai.common.peer.Host;
import io.subutai.common.peer.HostNotFoundException;
import io.subutai.common.peer.LocalPeer;
import io.subutai.common.peer.Peer;
import io.subutai.common.peer.PeerException;
import io.subutai.common.peer.ResourceHost;
import io.subutai.common.util.P2PUtil;
import io.subutai.common.util.RestUtil;
import io.subutai.core.broker.api.Broker;
import io.subutai.core.broker.api.BrokerException;
import io.subutai.core.environment.api.EnvironmentManager;
import io.subutai.core.environment.api.exception.EnvironmentCreationException;
import io.subutai.core.hostregistry.api.HostListener;
import io.subutai.core.network.api.NetworkManager;
import io.subutai.core.network.api.NetworkManagerException;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.registration.api.RegistrationManager;
import io.subutai.core.registration.api.RegistrationStatus;
import io.subutai.core.registration.api.exception.NodeRegistrationException;
import io.subutai.core.registration.api.service.ContainerInfo;
import io.subutai.core.registration.api.service.ContainerToken;
import io.subutai.core.registration.api.service.RequestedHost;
import io.subutai.core.registration.impl.dao.ContainerInfoDataService;
import io.subutai.core.registration.impl.dao.ContainerTokenDataService;
import io.subutai.core.registration.impl.dao.RequestDataService;
import io.subutai.core.registration.impl.entity.ContainerInfoImpl;
import io.subutai.core.registration.impl.entity.ContainerTokenImpl;
import io.subutai.core.registration.impl.entity.RequestedHostImpl;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.core.security.api.crypto.EncryptionTool;
import io.subutai.core.security.api.crypto.KeyManager;
public class RegistrationManagerImpl implements RegistrationManager, HostListener
{
private static final Logger LOGGER = LoggerFactory.getLogger( RegistrationManagerImpl.class );
private SecurityManager securityManager;
private RequestDataService requestDataService;
private ContainerInfoDataService containerInfoDataService;
private ContainerTokenDataService containerTokenDataService;
private DaoManager daoManager;
private Broker broker;
private String domainName;
private PeerManager peerManager;
private EnvironmentManager environmentManager;
private NetworkManager networkManager;
public RegistrationManagerImpl( final SecurityManager securityManager, final DaoManager daoManager,
String domainName )
{
this.securityManager = securityManager;
this.daoManager = daoManager;
this.domainName = domainName;
}
public void init()
{
containerTokenDataService = new ContainerTokenDataService( daoManager );
requestDataService = new RequestDataService( daoManager );
containerInfoDataService = new ContainerInfoDataService( daoManager );
}
public NetworkManager getNetworkManager()
{
return networkManager;
}
public void setNetworkManager( final NetworkManager networkManager )
{
this.networkManager = networkManager;
}
public EnvironmentManager getEnvironmentManager()
{
return environmentManager;
}
public void setEnvironmentManager( final EnvironmentManager environmentManager )
{
this.environmentManager = environmentManager;
}
public PeerManager getPeerManager()
{
return peerManager;
}
public void setPeerManager( final PeerManager peerManager )
{
this.peerManager = peerManager;
}
public Broker getBroker()
{
return broker;
}
public void setBroker( final Broker broker )
{
this.broker = broker;
}
public RequestDataService getRequestDataService()
{
return requestDataService;
}
public void setRequestDataService( final RequestDataService requestDataService )
{
Preconditions.checkNotNull( requestDataService, "RequestDataService shouldn't be null." );
this.requestDataService = requestDataService;
}
@Override
public List<RequestedHost> getRequests()
{
List<RequestedHost> temp = Lists.newArrayList();
temp.addAll( requestDataService.getAll() );
return temp;
}
@Override
public RequestedHost getRequest( final String requestId )
{
return requestDataService.find( requestId );
}
@Override
public void queueRequest( final RequestedHost requestedHost ) throws NodeRegistrationException
{
if ( requestDataService.find( requestedHost.getId() ) != null )
{
LOGGER.info( "Already requested registration" );
}
else
{
RequestedHostImpl registrationRequest = new RequestedHostImpl( requestedHost );
registrationRequest.setStatus( RegistrationStatus.REQUESTED );
try
{
requestDataService.persist( registrationRequest );
}
catch ( Exception ex )
{
throw new NodeRegistrationException( "Failed adding resource host registration request to queue", ex );
}
}
}
@Override
public void rejectRequest( final String requestId )
{
RequestedHostImpl registrationRequest = requestDataService.find( requestId );
registrationRequest.setStatus( RegistrationStatus.REJECTED );
requestDataService.update( registrationRequest );
WebClient client = RestUtil.createWebClient( registrationRequest.getRestHook() );
EncryptionTool encryptionTool = securityManager.getEncryptionTool();
KeyManager keyManager = securityManager.getKeyManager();
String message = RegistrationStatus.REJECTED.name();
PGPPublicKey publicKey = keyManager.getPublicKey( registrationRequest.getId() );
byte[] encodedArray = encryptionTool.encrypt( message.getBytes(), publicKey, true );
String encoded = message;
try
{
encoded = new String( encodedArray, "UTF-8" );
}
catch ( Exception e )
{
LOGGER.error( "Error approving new connections request", e );
}
client.query( "Message", encoded ).delete();
}
private Set<String> getTunnelNetworks( final Set<Peer> peers )
{
Set<String> result = new HashSet<>();
for ( Peer peer : peers )
{
Set<HostInterfaceModel> r = null;
try
{
r = peer.getInterfaces().filterByIp( P2PUtil.P2P_INTERFACE_IP_PATTERN );
}
catch ( PeerException e )
{
e.printStackTrace();
}
Collection tunnels = CollectionUtils.collect( r, new Transformer()
{
@Override
public Object transform( final Object o )
{
HostInterface i = ( HostInterface ) o;
SubnetUtils u = new SubnetUtils( i.getIp(), P2PUtil.P2P_SUBNET_MASK );
return u.getInfo().getNetworkAddress();
}
} );
result.addAll( tunnels );
}
return result;
}
@Override
public void approveRequest( final String requestId )
{
RequestedHostImpl registrationRequest = requestDataService.find( requestId );
if ( registrationRequest == null || !RegistrationStatus.REQUESTED.equals( registrationRequest.getStatus() ) )
{
return;
}
registrationRequest.setStatus( RegistrationStatus.APPROVED );
requestDataService.update( registrationRequest );
//todo sign RH key with Peer Key
importHostPublicKey( registrationRequest.getId(), registrationRequest.getPublicKey() );
importHostSslCert( registrationRequest.getId(), registrationRequest.getCert() );
for ( final ContainerInfo containerInfo : registrationRequest.getHostInfos() )
{
if ( !"management".equals( containerInfo.getHostname() ) )
{
importHostPublicKey( containerInfo.getId(), containerInfo.getPublicKey() );
}
}
//TODO @Talas implement this method correctly asap. Temporarily disabling it
//processEnvironmentImport( registrationRequest );
}
private void importHostSslCert( String hostId, String cert )
{
try
{
broker.registerClientCertificate( hostId, cert );
}
catch ( BrokerException e )
{
LOGGER.error( "Error importing host SSL certificate", e );
}
}
private void importHostPublicKey( String hostId, String publicKey )
{
try
{
KeyManager keyManager = securityManager.getKeyManager();
keyManager.savePublicKeyRing( hostId, ( short ) 2, publicKey );
}
catch ( Exception ex )
{
LOGGER.error( "Error importing host public key", ex );
}
}
private Map<Integer, Map<String, Set<ContainerInfo>>> groupContainersByVlan( Set<ContainerInfo> containerInfoSet )
{
Map<Integer, Map<String, Set<ContainerInfo>>> groupedContainersByVlan = Maps.newHashMap();
for ( final ContainerInfo containerInfo : containerInfoSet )
{
//Group containers by environment relation
// and group into node groups.
Map<String, Set<ContainerInfo>> groupedContainers = groupedContainersByVlan.get( containerInfo.getVlan() );
if ( groupedContainers == null )
{
groupedContainers = Maps.newHashMap();
}
//Group by container infos by container name
Set<ContainerInfo> group = groupedContainers.get( containerInfo.getTemplateName() );
if ( group != null )
{
group.add( containerInfo );
}
else
{
group = Sets.newHashSet( containerInfo );
}
if ( containerInfo.getVlan() != null && containerInfo.getVlan() != 0 )
{
groupedContainers.put( containerInfo.getTemplateName(), group );
groupedContainersByVlan.put( containerInfo.getVlan(), groupedContainers );
}
}
return groupedContainersByVlan;
}
private void processEnvironmentImport( RequestedHostImpl registrationRequest )
{
Map<Integer, Map<String, Set<ContainerInfo>>> groupedContainersByVlan =
groupContainersByVlan( registrationRequest.getHostInfos() );
LocalPeer localPeer = peerManager.getLocalPeer();
for ( final Map.Entry<Integer, Map<String, Set<ContainerInfo>>> mapEntry : groupedContainersByVlan.entrySet() )
{
//TODO: check this run. Topology constructor changed
Topology topology = new Topology( "Imported-environment", 0, 0 );
Map<String, Set<ContainerInfo>> rawNodeGroup = mapEntry.getValue();
Map<NodeGroup, Set<ContainerHostInfo>> classification = Maps.newHashMap();
for ( final Map.Entry<String, Set<ContainerInfo>> entry : rawNodeGroup.entrySet() )
{
//place where to create node groups
String templateName = entry.getKey();
//TODO: please change this distribution
NodeGroup nodeGroup =
new NodeGroup( String.format( "%s_group", templateName ), templateName, ContainerSize.SMALL, 1,
1, localPeer.getId(), registrationRequest.getId() );
topology.addNodeGroupPlacement( localPeer.getId(), nodeGroup );
Set<ContainerHostInfo> converter = Sets.newHashSet();
converter.addAll( entry.getValue() );
classification.put( nodeGroup, converter );
}
//trigger environment import task
try
{
Environment environment = environmentManager
.importEnvironment( String.format( "environment_%d", mapEntry.getKey() ), topology,
classification, mapEntry.getKey() );
//Save container gateway from environment configuration to update container network configuration
// later when it will be available
SubnetUtils cidr;
try
{
cidr = new SubnetUtils( environment.getSubnetCidr() );
}
catch ( IllegalArgumentException e )
{
throw new RuntimeException( "Failed to parse subnet CIDR", e );
}
String gateway = cidr.getInfo().getLowAddress();
for ( final Set<ContainerHostInfo> infos : classification.values() )
{
//TODO: sign CH key with PEK (identified by LocalPeerId+environment.getId())
for ( final ContainerHostInfo hostInfo : infos )
{
ContainerInfoImpl containerInfo = containerInfoDataService.find( hostInfo.getId() );
containerInfo.setGateway( gateway );
containerInfo.setStatus( RegistrationStatus.APPROVED );
containerInfoDataService.update( containerInfo );
}
}
}
catch ( EnvironmentCreationException e )
{
LOGGER.error( "Error importing environment", e );
}
}
}
@Override
public void onHeartbeat( final ResourceHostInfo resourceHostInfo, Set<QuotaAlertValue> alerts )
{
RequestedHostImpl requestedHost = requestDataService.find( resourceHostInfo.getId() );
if ( requestedHost != null && requestedHost.getStatus() == RegistrationStatus.APPROVED )
{
LocalPeer localPeer = peerManager.getLocalPeer();
try
{
ResourceHost resourceHost = localPeer.getResourceHostById( resourceHostInfo.getId() );
Map<Integer, Set<ContainerHost>> containerHostList = Maps.newHashMap();
for ( final ContainerInfo containerInfo : requestedHost.getHostInfos() )
{
if ( RegistrationStatus.APPROVED.equals( containerInfo.getState() )
&& containerInfo.getVlan() != 0 )
{
ContainerInfoImpl containerInfoImpl = containerInfoDataService.find( containerInfo.getId() );
ContainerHost containerHost = resourceHost.getContainerHostById( containerInfo.getId() );
containerInfoImpl.setStatus( RegistrationStatus.REGISTERED );
containerInfoDataService.update( containerInfoImpl );
//we assume that newly imported environment has always default sshGroupId=1, hostsGroupId=1
//configure hosts on each group | group containers by ssh group
Set<ContainerHost> containers = containerHostList.get( containerInfoImpl.getVlan() );
if ( containers == null )
{
containers = Sets.newHashSet();
}
containers.add( containerHost );
}
}
for ( final Map.Entry<Integer, Set<ContainerHost>> entry : containerHostList.entrySet() )
{
configureHosts( entry.getValue() );
}
}
catch ( HostNotFoundException e )
{
//ignore
}
catch ( NetworkManagerException e )
{
LOGGER.error( "Error configuring container hosts", e );
}
}
}
private void configureHosts( final Set<ContainerHost> containerHosts ) throws NetworkManagerException
{
//assume that inside one host group the domain name must be the same for all containers
//so pick one container's domain name as the group domain name
networkManager.registerHosts( containerHosts, domainName );
networkManager.exchangeSshKeys( containerHosts, Sets.<String>newHashSet() );
}
@Override
public void removeRequest( final String requestId )
{
requestDataService.remove( requestId );
}
@Override
public void deployResourceHost( List<String> args ) throws NodeRegistrationException
{
Host managementHost = null;
CommandResult result;
try
{
managementHost = peerManager.getLocalPeer().getManagementHost();
Set<Peer> peers = Sets.newHashSet( managementHost.getPeer() );
Set<String> existingNetworks = getTunnelNetworks( peers );
String freeTunnelNetwork = P2PUtil.findFreeTunnelNetwork( existingNetworks );
args.add( "-I" );
freeTunnelNetwork = freeTunnelNetwork.substring( 0, freeTunnelNetwork.length() - 1 ) + (
Integer.valueOf( freeTunnelNetwork.substring( freeTunnelNetwork.length() - 1 ) ) + 1 );
args.add( freeTunnelNetwork );
int ipOctet = ( Integer.valueOf( freeTunnelNetwork.substring( freeTunnelNetwork.length() - 1 ) ) + 1 );
String ipRh = freeTunnelNetwork.substring( 0, freeTunnelNetwork.length() - 1 ) + ipOctet;
args.add( "-i" );
args.add( ipRh );
String communityName = P2PUtil.generateCommunityName( freeTunnelNetwork );
args.add( "-n" );
args.add( communityName );
String deviceName = P2PUtil.generateInterfaceName( freeTunnelNetwork );
args.add( "-d" );
args.add( deviceName );
String runUser = "root";
result = managementHost.execute(
new RequestBuilder( "/apps/subutai-mng/current/awsdeploy/awsdeploy" ).withCmdArgs( args )
.withRunAs( runUser )
.withTimeout( 600 ) );
if ( result.getExitCode() != 0 )
{
throw new NodeRegistrationException( result.getStdErr() );
}
}
catch ( HostNotFoundException | CommandException e )
{
e.printStackTrace();
}
}
@Override
public ContainerToken generateContainerTTLToken( final Long ttl )
{
ContainerTokenImpl token =
new ContainerTokenImpl( UUID.randomUUID().toString(), new Timestamp( System.currentTimeMillis() ),
ttl );
try
{
containerTokenDataService.persist( token );
}
catch ( Exception ex )
{
LOGGER.error( "Error persisting container token", ex );
}
return token;
}
@Override
public ContainerToken verifyToken( final String token, String containerHostId, String publicKey )
throws NodeRegistrationException
{
ContainerTokenImpl containerToken = containerTokenDataService.find( token );
if ( containerToken == null )
{
throw new NodeRegistrationException( "Couldn't verify container token" );
}
if ( containerToken.getDateCreated().getTime() + containerToken.getTtl() < System.currentTimeMillis() )
{
throw new NodeRegistrationException( "Container token expired" );
}
try
{
securityManager.getKeyManager().savePublicKeyRing( containerHostId, ( short ) 2, publicKey );
}
catch ( Exception ex )
{
throw new NodeRegistrationException( "Failed to store container pubkey", ex );
}
return containerToken;
}
} |
package com.stuartwarren.logit.fields;
import java.util.HashMap;
import com.stuartwarren.logit.utils.LogitLog;
import com.stuartwarren.logit.utils.ThreadLocalMap;
/**
* @author Stuart Warren
* @date 20 Oct 2013
*
*/
public class Field {
private static final Field field = new Field();
private Object tlm;
public IFieldName section;
public Field() {
try {
this.section = null;
tlm = new ThreadLocalMap();
} catch (Exception e) {
LogitLog.error("Error thrown initialising ExceptionField", e);
}
}
public static void put(String key, Object o) {
if (field != null) {
field.put0(key, o);
}
}
public static Object get(String key) {
if (field != null) {
return field.get0(key);
}
return null;
}
public static void remove(String key) {
if (field != null) {
field.remove0(key);
}
}
public static HashMap<String, Object> getContext() {
if (field != null) {
return field.getContext0();
} else {
return null;
}
}
public static void clear() {
if (field != null) {
field.clear0();
}
}
public String getSection() {
return this.section.toString();
}
@SuppressWarnings("unchecked")
protected void put0(String key, Object o) {
if (tlm == null) {
return;
} else {
HashMap<String, Object> ht = (HashMap<String, Object>) ((ThreadLocalMap) tlm).get();
if (ht == null) {
ht = new HashMap<String, Object>();
((ThreadLocalMap) tlm).set(ht);
}
HashMap<String, Object> h = (HashMap<String, Object>) get0(getSection());
if (h == null) {
h = new HashMap<String, Object>();
}
h.put(key, o);
ht.put(getSection(), h);
}
}
protected Object get0(String key) {
if (tlm == null) {
return null;
} else {
@SuppressWarnings("unchecked")
HashMap<String, Object> ht = (HashMap<String, Object>) ((ThreadLocalMap) tlm).get();
if (ht != null && key != null) {
return ht.get(key);
} else {
return null;
}
}
}
protected void remove0(String key) {
if (tlm != null) {
HashMap<?, ?> ht = (HashMap<?, ?>) ((ThreadLocalMap) tlm).get();
if (ht != null) {
ht.remove(key);
// clean up if this was the last key
if (ht.isEmpty()) {
clear0();
}
}
}
}
@SuppressWarnings("unchecked")
protected HashMap<String, Object> getContext0() {
if (tlm == null) {
return null;
} else {
return (HashMap<String, Object>) ((ThreadLocalMap) tlm).get();
}
}
protected void clear0() {
if (tlm != null) {
HashMap<?, ?> ht = (HashMap<?, ?>) ((ThreadLocalMap) tlm).get();
if (ht != null) {
ht.clear();
}
}
}
public static enum ROOT implements IFieldName {
/**
* MESSAGE - message
* Main log message.
*/
MESSAGE("message"),
/**
* TAGS - tags
* List of tags to assist filtering.
*/
TAGS("tags"),
/**
* USER - user
* Name of user running the process.
*/
USER("user"),
/**
* HOSTNAME - host_name
* Host the process is running on.
*/
HOSTNAME("host_name"),
/**
* LOCATION - location
* Location information of where in the code this log is.
*/
LOCATION("location"),
/**
* EXCEPTION - exception
* Exception details including full stacktrace.
*/
EXCEPTION("exception"),
/**
* THREAD - thread
* Details of current thread
*/
THREAD("thread"),
/**
* LOGGER - logger
* Details of current logger.
*/
LOGGER("logger"),
/**
* LEVEL - level
* Used to denote how severe the event is.
*/
LEVEL("level"),
/**
* MDC - mdc
* Mapped Diagnostic Context
*/
MDC("mdc"),
/**
* NDC - ndc
* Nested Diagnostic Context
*/
NDC("ndc")
;
private String text;
ROOT(String text) {
this.text = text;
}
public String toString() {
return this.text;
}
}
} |
package dr.inference.operators.hmc;
import dr.inference.hmc.ReversibleHMCProvider;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.Loggable;
import dr.inference.loggers.NumberColumn;
import dr.inference.operators.GibbsOperator;
import dr.inference.operators.SimpleMCMCOperator;
import dr.math.MathUtils;
import dr.math.matrixAlgebra.WrappedVector;
import java.util.Arrays;
public class NoUTurnOperator extends SimpleMCMCOperator implements GibbsOperator, Loggable {
class Options {
private double logProbErrorTol = 100.0;
private int findMax = 100;
private int maxHeight = 10;
}
private final Options options = new Options();
public NoUTurnOperator(ReversibleHMCProvider hmcProvider,
boolean adaptiveStepsize,
int adaptiveDelay,
double weight) {
this.hmcProvider = hmcProvider;
this.adaptiveStepsize = adaptiveStepsize;
this.adaptiveDelay = adaptiveDelay;
if (hmcProvider instanceof SplitHamiltonianMonteCarloOperator) {
this.splitHMCmultiplier = ((SplitHamiltonianMonteCarloOperator) hmcProvider).travelTimeMultipler;
this.splitHMCinner = ((SplitHamiltonianMonteCarloOperator) hmcProvider).inner;
this.splitHMCouter = ((SplitHamiltonianMonteCarloOperator) hmcProvider).outer;
}
setWeight(weight);
}
@Override
public String getOperatorName() {
return "No-U-Turn Operator";
}
@Override
public double doOperation() {
if (hmcProvider instanceof SplitHamiltonianMonteCarloOperator) {
updateRS();
if (splitHMCmultiplier.shouldGetMultiplier(getCount())){
((SplitHamiltonianMonteCarloOperator) hmcProvider).relativeScale = splitHMCmultiplier.getMultiplier();
}
}
final double[] initialPosition = hmcProvider.getInitialPosition();
if(updatePreconditioning){ //todo: should preconditioning, use a schedular
hmcProvider.providerUpdatePreconditioning();
}
if (stepSizeInformation == null) {
stepSizeInformation = findReasonableStepSize(initialPosition,
hmcProvider.getGradientProvider().getGradientLogDensity(), hmcProvider.getStepSize());
}
initializeNumEvents();
double[] position = takeOneStep(getCount() + 1, initialPosition);
hmcProvider.setParameter(position);
return 0;
}
private double[] takeOneStep(long m, double[] initialPosition) {
double[] endPosition = Arrays.copyOf(initialPosition, initialPosition.length);
final WrappedVector initialMomentum = hmcProvider.drawMomentum();
final double initialJointDensity = hmcProvider.getJointProbability(initialMomentum);
double logSliceU = Math.log(MathUtils.nextDouble()) + initialJointDensity;
TreeState trajectoryTree = new TreeState(initialPosition, initialMomentum.getBuffer(),
hmcProvider.getGradientProvider().getGradientLogDensity(), 1, true);
int height = 0;
while (trajectoryTree.flagContinue) {
double[] tmp = updateTrajectoryTree(trajectoryTree, height, logSliceU, initialJointDensity);
if (tmp != null) {
endPosition = tmp;
}
height++;
if (height > options.maxHeight) {
trajectoryTree.flagContinue = false;
}
}
if (adaptiveStepsize && getCount() > adaptiveDelay) {
stepSizeInformation.update(m, trajectoryTree.cumAcceptProb, trajectoryTree.numAcceptProbStates);
if (printStepsize) System.err.println("step size is " + stepSizeInformation.getStepSize());
}
return endPosition;
}
private double[] updateTrajectoryTree(TreeState trajectoryTree, int depth, double logSliceU,
double initialJointDensity) {
double[] endPosition = null;
final double uniform1 = MathUtils.nextDouble();
int direction = (uniform1 < 0.5) ? -1 : 1;
TreeState nextTrajectoryTree = buildTree(
trajectoryTree.getPosition(direction), trajectoryTree.getMomentum(direction),
trajectoryTree.getGradient(direction),
direction, logSliceU, depth, stepSizeInformation.getStepSize(), initialJointDensity);
if (nextTrajectoryTree.flagContinue) {
final double uniform = MathUtils.nextDouble();
final double acceptProb = (double) nextTrajectoryTree.numNodes / (double) trajectoryTree.numNodes;
if (uniform < acceptProb) {
endPosition = nextTrajectoryTree.getSample();
}
}
trajectoryTree.mergeNextTree(nextTrajectoryTree, direction);
return endPosition;
}
private TreeState buildTree(double[] position, double[] momentum, double[] gradient, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
if (height == 0) {
return buildBaseCase(position, momentum, gradient, direction, logSliceU, stepSize, initialJointDensity);
} else {
return buildRecursiveCase(position, momentum, gradient, direction, logSliceU, height, stepSize,
initialJointDensity);
}
}
private TreeState buildBaseCase(double[] inPosition, double[] inMomentum, double[] inGradient, int direction,
double logSliceU, double stepSize, double initialJointDensity) {
recordOneBaseCall();
// Make deep copy of position and momentum
WrappedVector position = new WrappedVector.Raw(Arrays.copyOf(inPosition, inPosition.length));
WrappedVector momentum = new WrappedVector.Raw(Arrays.copyOf(inMomentum, inMomentum.length));
WrappedVector gradient = new WrappedVector.Raw(Arrays.copyOf(inGradient, inGradient.length));
hmcProvider.setParameter(position.getBuffer());
// "one reversibleHMC integral
hmcProvider.reversiblePositionMomentumUpdate(position, momentum, gradient, direction, stepSize);
recordEvents();
double logJointProbAfter = hmcProvider.getJointProbability(momentum);
final int numNodes = (logSliceU <= logJointProbAfter ? 1 : 0);
final boolean flagContinue = (logSliceU < options.logProbErrorTol + logJointProbAfter);
// Values for dual-averaging
final double acceptProb = Math.min(1.0, Math.exp(logJointProbAfter - initialJointDensity));
final int numAcceptProbStates = 1;
hmcProvider.setParameter(inPosition);
return new TreeState(position.getBuffer(), momentum.getBuffer(), gradient.getBuffer(), numNodes, flagContinue
, acceptProb,
numAcceptProbStates);
}
private TreeState buildRecursiveCase(double[] inPosition, double[] inMomentum, double[] gradient, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
TreeState subtree = buildTree(inPosition, inMomentum, gradient, direction, logSliceU,
height - 1, // Recursion
stepSize, initialJointDensity);
if (subtree.flagContinue) {
TreeState nextSubtree = buildTree(subtree.getPosition(direction), subtree.getMomentum(direction),
subtree.getGradient(direction), direction,
logSliceU, height - 1, stepSizeInformation.getStepSize(), initialJointDensity);
subtree.mergeNextTree(nextSubtree, direction);
}
return subtree;
}
private static boolean computeStopCriterion(boolean flagContinue, TreeState state) {
return computeStopCriterion(flagContinue,
state.getPosition(1), state.getPosition(-1),
state.getMomentum(1), state.getMomentum(-1));
}
private StepSize findReasonableStepSize(double[] initialPosition, double[] initialGradient,
double forcedInitialStepSize) {
if (forcedInitialStepSize != 0) {
return new StepSize(forcedInitialStepSize);
} else {
double stepSize = 0.1;
WrappedVector momentum = hmcProvider.drawMomentum();
int count = 1;
int dim = initialPosition.length;
WrappedVector position = new WrappedVector.Raw(Arrays.copyOf(initialPosition, dim));
WrappedVector gradient = new WrappedVector.Raw(Arrays.copyOf(initialGradient, dim));
double probBefore = hmcProvider.getJointProbability(momentum);
hmcProvider.reversiblePositionMomentumUpdate(position, momentum, gradient, 1, stepSize);
double probAfter = hmcProvider.getJointProbability(momentum);
double a = ((probAfter - probBefore) > Math.log(0.5) ? 1 : -1);
double probRatio = Math.exp(probAfter - probBefore);
while (Math.pow(probRatio, a) > Math.pow(2, -a)) {
probBefore = probAfter;
hmcProvider.reversiblePositionMomentumUpdate(position, momentum, gradient, 1, stepSize);
probAfter = hmcProvider.getJointProbability(momentum);
probRatio = Math.exp(probAfter - probBefore);
stepSize = Math.pow(2, a) * stepSize;
count++;
if (count > options.findMax) {
throw new RuntimeException("Cannot find a reasonable step-size in " + options.findMax + " " +
"iterations");
}
}
hmcProvider.setParameter(initialPosition);
return new StepSize(stepSize);
}
}
private static boolean computeStopCriterion(boolean flagContinue,
double[] positionPlus, double[] positionMinus,
double[] momentumPlus, double[] momentumMinus) {
double[] positionDifference = subtractArray(positionPlus, positionMinus);
return flagContinue &&
getDotProduct(positionDifference, momentumMinus) >= 0 &&
getDotProduct(positionDifference, momentumPlus) >= 0;
}
private static double getDotProduct(double[] x, double[] y) {
assert (x.length == y.length);
final int dim = x.length;
double total = 0.0;
for (int i = 0; i < dim; i++) {
total += x[i] * y[i];
}
return total;
}
private static double[] subtractArray(double[] a, double[] b) {
assert (a.length == b.length);
final int dim = a.length;
double[] result = new double[dim];
for (int i = 0; i < dim; i++) {
result[i] = a[i] - b[i];
}
return result;
}
private class TreeState {
private TreeState(double[] position, double[] moment, double[] gradient,
int numNodes, boolean flagContinue) {
this(position, moment, gradient, numNodes, flagContinue, 0.0, 0);
}
private TreeState(double[] position, double[] moment, double[] gradient,
int numNodes, boolean flagContinue,
double cumAcceptProb, int numAcceptProbStates) {
this.position = new double[3][];
this.momentum = new double[3][];
this.gradient = new double[3][]; //todo: (for gradient) no need for 3 but 2? If changed to 2, getIndex should also be changed
for (int i = 0; i < 3; ++i) {
this.position[i] = position;
this.momentum[i] = moment;
this.gradient[i] = gradient;
}
// Recursion variables
this.numNodes = numNodes;
this.flagContinue = flagContinue;
// Dual-averaging variables
this.cumAcceptProb = cumAcceptProb;
this.numAcceptProbStates = numAcceptProbStates;
}
private double[] getPosition(int direction) {
return position[getIndex(direction)];
}
private double[] getMomentum(int direction) {
return momentum[getIndex(direction)];
}
private double[] getGradient(int direction) {
return gradient[getIndex(direction)];
}
private double[] getSample() {
/*
Returns a state chosen uniformly from the acceptable states along a hamiltonian dynamics trajectory tree.
The sample is updated recursively while building trees.
*/
return position[getIndex(0)];
}
private void setPosition(int direction, double[] position) {
this.position[getIndex(direction)] = position;
}
private void setMomentum(int direction, double[] momentum) {
this.momentum[getIndex(direction)] = momentum;
}
private void setGradient(int direction, double[] gradient) {
this.gradient[getIndex(direction)] = gradient;
}
private void setSample(double[] position) { setPosition(0, position); }
private int getIndex(int direction) { // valid directions: -1, 0, +1
assert (direction >= -1 && direction <= 1);
return direction + 1;
}
private void mergeNextTree(TreeState nextTree, int direction) {
setPosition(direction, nextTree.getPosition(direction));
setMomentum(direction, nextTree.getMomentum(direction));
setGradient(direction, nextTree.getGradient(direction));
updateSample(nextTree);
numNodes += nextTree.numNodes;
flagContinue = computeStopCriterion(nextTree.flagContinue, this);
cumAcceptProb += nextTree.cumAcceptProb;
numAcceptProbStates += nextTree.numAcceptProbStates;
}
private void updateSample(TreeState nextTree) {
double uniform = MathUtils.nextDouble();
if (nextTree.numNodes > 0
&& uniform < ((double) nextTree.numNodes / (double) (numNodes + nextTree.numNodes))) {
setSample(nextTree.getSample());
}
}
final private double[][] position;
final private double[][] momentum;
final private double[][] gradient;
private int numNodes;
private boolean flagContinue;
private double cumAcceptProb;
private int numAcceptProbStates;
}
private void initializeNumEvents(){
numBaseCalls = 0;
numBoundaryEvents = 0;
numGradientEvents = 0;
}
private void recordOneBaseCall(){
numBaseCalls++;
}
private void recordEvents(){
numGradientEvents += hmcProvider.getNumGradientEvent();
numBoundaryEvents += hmcProvider.getNumBoundaryEvent();
}
@Override
public LogColumn[] getColumns() {
LogColumn[] columns = new LogColumn[4];
columns[0] = new NumberColumn("base calls") {
@Override
public double getDoubleValue() {
return numBaseCalls;
}
};
columns[1] = new NumberColumn("step size") {
@Override
public double getDoubleValue() {
if(stepSizeInformation != null) return stepSizeInformation.getStepSize();
else return 0;
}
};
columns[2] = new NumberColumn("gradient events") {
@Override
public double getDoubleValue() {
return numGradientEvents;
}
};
columns[3] = new NumberColumn("boundary events") {
@Override
public double getDoubleValue() {
return numBoundaryEvents;
}
};
return columns;
}
private void updateRS() {
if (splitHMCmultiplier != null && splitHMCmultiplier.shouldUpdateSCM(getCount())) {
splitHMCmultiplier.updateSCM(splitHMCmultiplier.getInnerCov(), splitHMCinner.getInitialPosition(), getCount());
splitHMCmultiplier.updateSCM(splitHMCmultiplier.getOuterCov(), splitHMCouter.getInitialPosition(), getCount());
}
}
private ReversibleHMCProvider hmcProvider;
private StepSize stepSizeInformation;
private boolean adaptiveStepsize;
private int adaptiveDelay;
private int numBaseCalls;
private int numBoundaryEvents;
private int numGradientEvents;
private SplitHMCtravelTimeMultiplier splitHMCmultiplier = null;
private ReversibleHMCProvider splitHMCinner = null;
private ReversibleHMCProvider splitHMCouter = null;
private final boolean updatePreconditioning = false;
private final boolean printStepsize = false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.