answer
stringlengths
17
10.2M
package org.andengine.util.algorithm.hull; import org.andengine.opengl.util.VertexUtils; import org.andengine.util.math.MathConstants; import org.andengine.util.math.MathUtils; public class JarvisMarch implements IHullAlgorithm { // Constants // Fields // Constructors // Getter & Setter // Methods for/from SuperClass/Interfaces @Override public int computeHull(final float[] pVertices, final int pVertexCount, final int pVertexOffsetX, final int pVertexOffsetY, final int pVertexStride) { return this.jarvisMarch(pVertices, pVertexCount, pVertexOffsetX, pVertexOffsetY, pVertexStride); } // Methods private int jarvisMarch(final float[] pVertices, final int pVertexCount, final int pVertexOffsetX, final int pVertexOffsetY, final int pVertexStride) { /* Start at the lowest (y-axis) of all vertices. */ final int firstHullVertexIndex = HullUtils.indexOfLowestVertex(pVertices, pVertexCount, pVertexOffsetY, pVertexStride); final float firstHullVertexX = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, firstHullVertexIndex); final float firstHullVertexY = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, firstHullVertexIndex); int hullVertexCount = 0; int currentHullVertexIndex = firstHullVertexIndex; float currentHullVertexAngle = 0; /* 0 degrees. */ do { HullUtils.swap(pVertices, pVertexStride, hullVertexCount, currentHullVertexIndex); final float currentHullPointVertexX = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, hullVertexCount); final float currentHullPointVertexY = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, hullVertexCount); hullVertexCount++; /* Compute the angle between the current hull vertex and all remaining vertices. * Pick the smallest angle larger then the current angle. */ int nextHullVertexIndex = 0; float nextHullVertexAngle = MathConstants.PI_TWICE; /* 360 degrees. */ /* Start searching one behind the already found hull vertices. */ for(int j = hullVertexCount; j < pVertexCount; j++) { final float possibleNextHullVertexX = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, j); final float possibleNextHullVertexY = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, j); /* Ignore identical vertices. */ if(currentHullPointVertexX != possibleNextHullVertexX || currentHullPointVertexY != possibleNextHullVertexY) { final float dX = possibleNextHullVertexX - currentHullPointVertexX; final float dY = possibleNextHullVertexY - currentHullPointVertexY; float possibleNextHullVertexAngle = MathUtils.atan2(dY, dX); if(possibleNextHullVertexAngle < 0) { possibleNextHullVertexAngle += MathConstants.PI_TWICE; /* 360 degrees. */ } if((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { nextHullVertexIndex = j; nextHullVertexAngle = possibleNextHullVertexAngle; } } } /* Compare against first hull vertex. */ if(hullVertexCount > 1) { final float dX = firstHullVertexX - currentHullPointVertexX; final float dY = firstHullVertexY - currentHullPointVertexY; float possibleNextHullVertexAngle = MathUtils.atan2(dY, dX); if(possibleNextHullVertexAngle < 0) { possibleNextHullVertexAngle += MathConstants.PI_TWICE; /* 360 degrees. */ } if((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { break; } } currentHullVertexAngle = nextHullVertexAngle; currentHullVertexIndex = nextHullVertexIndex; } while(currentHullVertexIndex > 0); return hullVertexCount; } // Inner and Anonymous Classes }
package org.eclipse.emf.emfstore.client.ui.views.emfstorebrowser.views; import java.util.ArrayList; import org.eclipse.emf.emfstore.client.model.ServerInfo; import org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager; import org.eclipse.emf.emfstore.client.model.exceptions.CertificateStoreException; import org.eclipse.emf.emfstore.client.model.util.EMFStoreCommand; import org.eclipse.emf.emfstore.client.model.util.WorkspaceUtil; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; /** * The main page of the wizard. * * @author shterev */ public class NewRepositoryWizardPageOne extends WizardPage { private static final int DEFAULT_PORT = 8080; private Text name; private Text url; private Spinner port; private Combo cert; /** * Default constructor. */ public NewRepositoryWizardPageOne() { super("Main"); setTitle("Server Details"); setDescription("Select the details for the new repository"); } /** * {@inheritDoc} */ public void createControl(Composite parent) { NewRepositoryWizard wizard = (NewRepositoryWizard) getWizard(); ServerInfo serverInfo = wizard.getServerInfo(); GridData gd; Composite composite = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(); int ncol = 3; gl.numColumns = ncol; composite.setLayout(gl); // Server Name new Label(composite, SWT.NONE).setText("Name:"); name = new Text(composite, SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = ncol - 1; name.setLayoutData(gd); // Server URL new Label(composite, SWT.NONE).setText("URL:"); url = new Text(composite, SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = ncol - 1; url.setLayoutData(gd); // Server Port new Label(composite, SWT.NONE).setText("Port:"); port = new Spinner(composite, SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = ncol - 1; port.setLayoutData(gd); port.setValues(DEFAULT_PORT, 1, 999999, 0, 1, 10); setControl(composite); // Certificate new Label(composite, SWT.NONE).setText("Certificate:"); cert = new Combo(composite, SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = ncol - 2; cert.setLayoutData(gd); cert.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); initCombo(); // Choose Certificate, Opens Dialogue Button button = new Button(composite, SWT.NONE); button.setText("Edit"); button.addSelectionListener(new SelectionDialogListener()); gd = new GridData(GridData.HORIZONTAL_ALIGN_END); gd.horizontalSpan = 1; button.setLayoutData(gd); if (serverInfo.getUrl() != null) { name.setText(serverInfo.getName()); url.setText(serverInfo.getUrl()); port.setSelection(serverInfo.getPort()); if (serverInfo.getCertificateAlias() == null) { return; } try { if (KeyStoreManager.getInstance().contains(serverInfo.getCertificateAlias())) { for (int i = 0; i < cert.getItemCount(); i++) { if (cert.getItem(i).equals(serverInfo.getCertificateAlias())) { cert.select(i); break; } } } else { cert.setText(""); } } catch (CertificateStoreException e1) { cert.setText(""); } } } private void initCombo() { try { ArrayList<String> certificates = KeyStoreManager.getInstance().getCertificates(); String[] aliases = new String[certificates.size()]; for (int i = 0; i < certificates.size(); i++) { aliases[i] = certificates.get(i); } cert.setItems(aliases); NewRepositoryWizard wizard = (NewRepositoryWizard) getWizard(); ServerInfo serverInfo = wizard.getServerInfo(); String selectedCertificate = serverInfo.getCertificateAlias(); cert.select(certificates.indexOf(selectedCertificate)); } catch (CertificateStoreException e) { WorkspaceUtil.logException(e.getMessage(), e); } } /** * @return if the input on the current page is valid. */ @Override public boolean canFlipToNextPage() { if (getErrorMessage() != null) { return false; } if (isTextNonEmpty(name.getText()) && isTextNonEmpty(url.getText()) && isComboNotEmpty()) { saveDataToModel(); return true; } return false; } /** * Saves the uses choices from this page to the model. Called on exit of the * page */ private void saveDataToModel() { new EMFStoreCommand() { @Override protected void doRun() { NewRepositoryWizard wizard = (NewRepositoryWizard) getWizard(); ServerInfo serverInfo = wizard.getServerInfo(); serverInfo.setName(name.getText()); serverInfo.setUrl(url.getText()); serverInfo.setPort(port.getSelection()); serverInfo.setCertificateAlias(cert.getText()); } }.run(); } /** * Returns true if Text is not empty, i.e. not null/only space characters. * * @param t * @return boolean */ private static boolean isTextNonEmpty(String s) { if ((s != null) && (s.trim().length() > 0)) { return true; } return false; } private boolean isComboNotEmpty() { String s = cert.getItem(cert.getSelectionIndex()); return isTextNonEmpty(s); } /** * Listener for the selection dialog. * * @author pfeifferc */ class SelectionDialogListener implements SelectionListener { /** * @param e * selection event * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetDefaultSelected(SelectionEvent e) { // nothing to do } /** * @param e * selection event * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { CertificateSelectionDialog csd = new CertificateSelectionDialog(Display.getCurrent().getActiveShell(), new LabelProvider() { @Override public String getText(Object element) { if (element instanceof String) { return element.toString(); } else { return ""; } } }); ArrayList<String> certificates; try { certificates = KeyStoreManager.getInstance().getCertificates(); csd.setElements(certificates.toArray()); } catch (CertificateStoreException e1) { csd.setErrorMessage(e1.getMessage()); } csd.setBlockOnOpen(true); csd.setTitle("Certificate Selection Dialog"); csd.open(); if (csd.getReturnCode() == Window.OK) { initCombo(); for (int i = 0; i < cert.getItemCount(); i++) { String item = cert.getItem(i); if (item.equals(csd.getCertificateAlias())) { cert.select(i); break; } } } } } }
package se.thinkcode.wait; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; @Mojo(name = "wait", threadSafe = true, defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST) public class HttpWaitMojo extends AbstractMojo { @Parameter(defaultValue = "http://localhost") String url; @Parameter(defaultValue = "10000") int timeout; @Parameter Map<String, String> headers = Collections.emptyMap(); public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Waiting for " + url); long startTime = System.currentTimeMillis(); int responseCode = HttpURLConnection.HTTP_NOT_FOUND; try { long endTime = System.currentTimeMillis() + timeout; while (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { try { HttpURLConnection con; URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(timeout); for (String key : headers.keySet()) { String value = headers.get(key); con.setRequestProperty(key, value); } responseCode = con.getResponseCode(); con.disconnect(); } catch (MalformedURLException e) { throw new ConnectionException("Connection to " + url + " failed with the message: " + e.getMessage()); } catch (IOException e) { if (System.currentTimeMillis() > endTime) { throw new TimeoutException("Connection to " + url + " timed out"); } } Thread.sleep(100); } } catch (InterruptedException e) { getLog().error(e); } if (responseCode == HttpURLConnection.HTTP_OK) { long waitingTime = System.currentTimeMillis() - startTime; getLog().info("Waited for " + waitingTime + "ms for " + url); return; } throw new ConnectionException("Connection to " + url + " failed with response code " + responseCode); } }
package org.biojava.bio.seq.io; import java.util.Collections; import java.util.List; import java.util.ArrayList; import org.biojava.bio.BioException; import org.biojava.bio.seq.*; import org.biojava.bio.symbol.*; /** * <code>EmblLikeLocationParser</code> parses EMBL/Genbank style * locations. Supported location forms: * * <pre> * 123 * <123 or >123 * (123.567) * (123.567)..789 * 123..(567.789) * (123.345)..(567.789) * 123..456 * <123..567 or 123..>567 or <123..>567 * 123^567 * </pre> * * Specifically not supported are: * <pre> * AL123465:(123..567) * </pre> * * Use of 'order' rather than 'join' is not retained over a read/write * cycle. i.e. 'order' is converted to 'join' * * @author <a href="mailto:kdj@sanger.ac.uk">Keith James</a> * @author Greg Cox * @since 1.2 */ public class EmblLikeLocationParser { // For the LocationLexer inner classs private String location; private LocationLexer lexer; private int nextCharIndex; private Object thisToken; // Stores join/order/complement instructions private List instructStack = new ArrayList(); // joinType is a hack to store if a compound location is a join(...) or an // order(...) location. If this isn't sufficient for your needs, feel free // to fix it. If you do, please make sure the AbstractGenEmblFileFormer // class is still able to format join and order correctly private String joinType = null; // List of sublocations. Used for compound locations on the current // sequence private List subLocations = new ArrayList(); // List of subRegions. Used to store remote regions private List subRegions = new ArrayList(); // These hold working data for each (sub)location and are cleared // by calling the processCoords() function private String mRegionSeqID; private List startCoords = new ArrayList(); private List endCoords = new ArrayList(); private boolean isPointLoc = true; private boolean fuzzyCoord = false; private boolean unboundMin = false; private boolean unboundMax = false; private boolean isBetweenLocation = false; // Currently set per Feature; this is a deficiency in the current // parser. Features are assumed to be on the positive strand until // complemented. // No features have a strand type of UNKNOWN private StrandedFeature.Strand mStrandType = StrandedFeature.POSITIVE; EmblLikeLocationParser() { this.lexer = new LocationLexer(); } /** * <code>parseLocation</code> creates a <code>Location</code> from * the String and returns a stranded location. * * @param location a location <code>String</code>. * @param theTemplate the template to be filled with the parsed out location * information. * * @exception BioException if an error occurs. */ public Feature.Template parseLocation(String location, Feature.Template theTemplate) throws BioException { this.location = location; if ((countChar(location, '(')) != (countChar(location, ')'))) throw new BioException("Unbalanced parentheses in location: " + location); nextCharIndex = 0; instructStack.clear(); subLocations.clear(); subRegions.clear(); joinType = null; thisToken = lexer.getNextToken(); while (thisToken != null) { if (String.class.isInstance(thisToken)) { String toke = (String) thisToken; if (toke.equals("..")) { // This token indicates that this isn't a point isPointLoc = false; } else { instructStack.add(thisToken); } } else if (Integer.class.isInstance(thisToken)) { if (isPointLoc) startCoords.add(thisToken); else endCoords.add(thisToken); } else if (Character.class.isInstance(thisToken)) { char toke = ((Character) thisToken).charValue(); switch (toke) { case '(': break; case ':': processInstructs(); break; case '^': isBetweenLocation = true; break; case '<': unboundMin = true; break; case '>': unboundMax = true; break; case '.': // Catch range: (123.567) fuzzyCoord = true; break; case ',': processCoords(); break; case ')': // Catch the end of range: (123.567) if (fuzzyCoord) { fuzzyCoord = false; } else { processCoords(); processInstructs(); } break; default: throw new BioException("Unknown character '" + toke + "' within location: " + location); } } thisToken = lexer.getNextToken(); } processCoords(); // The location has been processed, and now the template gets filled if (subLocations.size() == 1) { theTemplate.location = (Location)subLocations.get(0); } else { // EMBL ordering is in reverse on the complementary strand // but LocationTools sorts them anyway theTemplate.location = LocationTools.union(subLocations); } if(theTemplate instanceof StrandedFeature.Template) { ((StrandedFeature.Template)theTemplate).strand = mStrandType; } if(subRegions.size() > subLocations.size()) { // This is a remote feature, so a new template has to be made RemoteFeature.Template newTemplate = new RemoteFeature.Template(theTemplate); newTemplate.regions = new ArrayList(subRegions); // FIXME: // I don't know how to create an appropriate resolver, so I'm leaving it // blank. No doubt this will break things. // -- Gcox newTemplate.resolver = null; theTemplate = newTemplate; } if(joinType != null) { try { theTemplate.annotation.setProperty("JoinType", joinType); } catch(org.biojava.utils.ChangeVetoException cve) { throw new org.biojava.bio.BioError(cve); } } return theTemplate; } /** * <code>processCoords</code> uses the coordinate data in the * start/endCoords Lists to create a Location and add to the * subLocations List. As this code will require further * modification to support fuzzy point locations, please keep any * changes well-commented. * * @exception BioException if an error occurs. */ private void processCoords() throws BioException { int outerMin, innerMin, innerMax, outerMax; Location createdLocation = null; // This is expected where two calls to processCoords() are // made sequentially e.g. where two levels of parens are // closed. The second call will have no data to process. if (startCoords.isEmpty() && endCoords.isEmpty()) return; // Range of form 5^6 or 5^7 if (isBetweenLocation) { // Create a ranged location, and wrap it in a between location int minCoord = ((Integer)startCoords.get(0)).intValue(); int maxCoord = ((Integer)startCoords.get(1)).intValue(); createdLocation = new BetweenLocation(new RangeLocation(minCoord, maxCoord)); } // Range of form: 123 else if (startCoords.size() == 1 && endCoords.isEmpty()) { innerMin = outerMin = ((Integer) startCoords.get(0)).intValue(); innerMax = outerMax = innerMin; // This looks like a point, but is actually a range which // lies entirely outside the current entry if (unboundMin || unboundMax) { createdLocation = new FuzzyPointLocation(unboundMin ? Integer.MIN_VALUE : innerMin, unboundMax ? Integer.MAX_VALUE : innerMax, FuzzyPointLocation.RESOLVE_AVERAGE); } else if (isPointLoc) { createdLocation = new PointLocation(innerMin); } else { // I'm really sorry about this exception message! This // should not happen throw new BioException("Internal error in location parsing; parser became confused: " + location); } } // Range of form: (123.567) else if (startCoords.size() == 2 && endCoords.isEmpty()) { innerMin = outerMin = ((Integer) startCoords.get(0)).intValue(); innerMax = outerMax = ((Integer) startCoords.get(1)).intValue(); createdLocation = new FuzzyPointLocation(innerMin, innerMax, FuzzyPointLocation.RESOLVE_AVERAGE); } // Range of form: 123..567 or <123..567 or 123..>567 or <123..>567 else if (startCoords.size() == 1 && endCoords.size() == 1) { innerMin = outerMin = ((Integer) startCoords.get(0)).intValue(); innerMax = outerMax = ((Integer) endCoords.get(0)).intValue(); if (unboundMin || unboundMax) { createdLocation = new FuzzyLocation(unboundMin ? Integer.MIN_VALUE : outerMin, unboundMax ? Integer.MAX_VALUE : outerMax, innerMin, innerMax, FuzzyLocation.RESOLVE_INNER); } else { try { createdLocation = new RangeLocation(outerMin, outerMax); } catch (IndexOutOfBoundsException ioe) { throw new BioException(ioe); } } } // Range of form: (123.567)..789 else if (startCoords.size() == 2 && endCoords.size() == 1) { outerMin = ((Integer) startCoords.get(0)).intValue(); innerMin = ((Integer) startCoords.get(1)).intValue(); innerMax = outerMax = ((Integer) endCoords.get(0)).intValue(); createdLocation = new FuzzyLocation(outerMin, outerMax, innerMin, innerMax, FuzzyLocation.RESOLVE_INNER); } // Range of form: 123..(567.789) else if (startCoords.size() == 1 && endCoords.size() == 2) { outerMin = innerMin = ((Integer) startCoords.get(0)).intValue(); innerMax = ((Integer) endCoords.get(0)).intValue(); outerMax = ((Integer) endCoords.get(1)).intValue(); createdLocation = new FuzzyLocation(outerMin, outerMax, innerMin, innerMax, FuzzyLocation.RESOLVE_INNER); } // Range of form: (123.345)..(567.789) else if (startCoords.size() == 2 && endCoords.size() == 2) { outerMin = ((Integer) startCoords.get(0)).intValue(); innerMin = ((Integer) startCoords.get(1)).intValue(); innerMax = ((Integer) endCoords.get(0)).intValue(); outerMax = ((Integer) endCoords.get(1)).intValue(); createdLocation = new FuzzyLocation(outerMin, outerMax, innerMin, innerMax, FuzzyLocation.RESOLVE_INNER); } else { // I'm really sorry about this exception message! This // should not happen throw new BioException("Internal error in location parsing; parser became confused; " + location); } startCoords.clear(); endCoords.clear(); if(mRegionSeqID == null) { subLocations.add(createdLocation); subRegions.add(new RemoteFeature.Region(createdLocation, null)); } else { subRegions.add(new RemoteFeature.Region(createdLocation, mRegionSeqID)); } mRegionSeqID = null; isPointLoc = true; unboundMin = false; unboundMax = false; fuzzyCoord = false; isBetweenLocation = false; mStrandType = StrandedFeature.POSITIVE; } /** * <code>processInstructs</code> pops an instruction off the stack * and applies it to the sub(locations). * * @exception BioException if an unsupported instruction is found. */ private void processInstructs() throws BioException { String instruct = (String) instructStack.remove(instructStack.size() - 1); if (instruct.equals("join") || instruct.equals("order")) { joinType = instruct; } else if (instruct.equals("complement")) { // This should only set the strand for a single range // within a feature. However, BioJava Locations have no // concept of strand and therefore are unable to support // construction of Features where some ranges are on // different strands. As a result the mStrandType // flag currently sets the strand for the whole feature. mStrandType = StrandedFeature.NEGATIVE; } else { // This is a primary accession number // e.g. J00194:(100..202) mRegionSeqID = instruct; } } private int countChar(final String s, final char c) { int cnt = 0; for (int i = 0; i < s.length(); ++i) if (s.charAt(i) == c) ++cnt; return cnt; } /** * <code>LocationLexer</code> is based on the * <code>LocationLexer</code> class in the Artemis source code by * Kim Rutherford. * * @author Kim Rutherford * @author <a href="mailto:kdj@sanger.ac.uk">Keith James</a> * @author Greg Cox * @since 1.2 */ private class LocationLexer { /** * <code>getNextToken</code> returns the next token. A null * indicates no more tokens. * * @return an <code>Object</code> value. */ Object getNextToken() { while (true) { if (nextCharIndex == location.length()) return null; char thisChar = location.charAt(nextCharIndex); switch (thisChar) { case ' ' : case '\t' : nextCharIndex++; continue; case ':' : case '^' : case ',' : case '(' : case ')' : case '<' : case '>' : nextCharIndex++; return new Character(thisChar); case '.' : if (location.charAt(nextCharIndex + 1) == '.') { nextCharIndex += 2; return ".."; } else { nextCharIndex++; return new Character('.'); } case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : return followInteger(); default : String text = followText(); if (text.equals("")) { nextCharIndex++; return new String("" + thisChar); } else return text; } } } /** * <code>followInteger</code> returns single sequence * coordinate. * * @return an <code>Integer</code> value. */ private Integer followInteger() { StringBuffer intString = new StringBuffer(); char thisChar = location.charAt(nextCharIndex); while (Character.isDigit(thisChar)) { intString.append(thisChar); nextCharIndex++; if (nextCharIndex >= location.length()) break; thisChar = location.charAt(nextCharIndex); } return new Integer(intString.substring(0)); } /** * <code>followText</code> returns a single text string. * * @return a <code>String</code> value. */ private String followText() { StringBuffer textString = new StringBuffer(""); char thisChar = location.charAt(nextCharIndex); // First character must be a letter if (! Character.isLetter(thisChar)) return ""; while (Character.isLetterOrDigit(thisChar) || thisChar == '.') { textString.append(thisChar); nextCharIndex++; if (nextCharIndex >= location.length()) break; thisChar = location.charAt(nextCharIndex); } return textString.substring(0); } } }
package se.crisp.codekvast.server.codekvast_server.service.impl; import com.google.common.eventbus.Subscribe; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.IntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import se.crisp.codekvast.server.agent_api.model.v1.JvmData; import se.crisp.codekvast.server.agent_api.model.v1.SignatureConfidence; import se.crisp.codekvast.server.agent_api.model.v1.SignatureData; import se.crisp.codekvast.server.agent_api.model.v1.SignatureEntry; import se.crisp.codekvast.server.codekvast_server.config.CodekvastSettings; import se.crisp.codekvast.server.codekvast_server.config.DatabaseConfig; import se.crisp.codekvast.server.codekvast_server.config.EventBusConfig; import se.crisp.codekvast.server.codekvast_server.dao.impl.AgentDAOImpl; import se.crisp.codekvast.server.codekvast_server.dao.impl.UserDAOImpl; import se.crisp.codekvast.server.codekvast_server.exception.UndefinedUserException; import se.crisp.codekvast.server.codekvast_server.model.event.display.ApplicationStatisticsDisplay; import se.crisp.codekvast.server.codekvast_server.model.event.display.ApplicationStatisticsMessage; import se.crisp.codekvast.server.codekvast_server.model.event.display.CollectorDisplay; import se.crisp.codekvast.server.codekvast_server.model.event.display.CollectorStatusMessage; import se.crisp.codekvast.server.codekvast_server.model.event.internal.InvocationDataReceivedEvent; import se.crisp.codekvast.server.codekvast_server.service.AgentService; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * @author olle.hallin@crisp.se */ @SuppressWarnings("CastToConcreteClass") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {DataSourceAutoConfiguration.class, DatabaseConfig.class, EventBusConfig.class, AgentDAOImpl.class, UserDAOImpl.class, CodekvastSettings.class, AgentServiceImpl.class}) @IntegrationTest({ "spring.datasource.url=jdbc:h2:mem:serviceTest", }) public class AgentServiceIntegTest extends AbstractServiceIntegTest { private static final String JVM_UUID = "uuid"; @Inject private AgentService agentService; @Subscribe public void onCollectorStatusMessage(CollectorStatusMessage message) { events.add(message); } @Subscribe public void onApplicationStatisticsMessage(ApplicationStatisticsMessage message) { events.add(message); } @Subscribe public void onInvocationDataReceivedEvent(InvocationDataReceivedEvent event) { events.add(event); } @Test public void testStoreJvmData_fromValidAgent() throws Exception { // given long dumpedAtMillis = now; // when agentService.storeJvmData("agent", createJvmData(dumpedAtMillis)); agentService.storeJvmData("agent", createJvmData(dumpedAtMillis + 1000L)); // then assertThat(countRows("jvm_info WHERE jvm_uuid = ? AND started_at_millis = ? AND reported_at_millis = ? ", JVM_UUID, startedAtMillis, dumpedAtMillis + 1000L), is(1)); assertEventsWithinMillis(4, 1000L); assertThat(events, hasSize(4)); assertThat(events.get(0), is(instanceOf(ApplicationStatisticsMessage.class))); assertThat(events.get(1), is(instanceOf(CollectorStatusMessage.class))); assertThat(events.get(2), is(instanceOf(ApplicationStatisticsMessage.class))); assertThat(events.get(3), is(instanceOf(CollectorStatusMessage.class))); ApplicationStatisticsMessage statsMessage = (ApplicationStatisticsMessage) events.get(0); ApplicationStatisticsDisplay stats = statsMessage.getApplications().iterator().next(); assertThat(stats.getFirstDataReceivedAtMillis(), is(startedAtMillis)); assertThat(stats.getLastDataReceivedAtMillis(), is(dumpedAtMillis)); CollectorStatusMessage csm = (CollectorStatusMessage) events.get(1); CollectorDisplay collector = csm.getCollectors().iterator().next(); assertThat(collector.getCollectorStartedAtMillis(), is(startedAtMillis)); statsMessage = (ApplicationStatisticsMessage) events.get(2); stats = statsMessage.getApplications().iterator().next(); assertThat(stats.getFirstDataReceivedAtMillis(), is(startedAtMillis)); assertThat(stats.getLastDataReceivedAtMillis(), is(dumpedAtMillis + 1000L)); } @Test(expected = UndefinedUserException.class) public void testStoreJvmData_fromUnknownAgent() throws Exception { agentService.storeJvmData("foobar", createJvmData(now)); } @Test public void testStoreInvocationData() throws Exception { agentService.storeJvmData("agent", createJvmData(now)); assertEventsWithinMillis(1, 1000L); List<SignatureEntry> signatures = new ArrayList<>(); signatures.add(new SignatureEntry("sig1", 0L, 0L, null)); signatures.add(new SignatureEntry("sig2", 100L, 100L, SignatureConfidence.EXACT_MATCH)); signatures.add(new SignatureEntry("sig1", 200L, 200L, SignatureConfidence.EXACT_MATCH)); SignatureData data = SignatureData.builder() .jvmUuid(JVM_UUID) .signatures(signatures).build(); events.clear(); agentService.storeSignatureData(data); assertEventsWithinMillis(2, 1000L); assertThat(events, hasSize(2)); assertThat(events.get(0), is(instanceOf(InvocationDataReceivedEvent.class))); assertThat(events.get(1), is(instanceOf(ApplicationStatisticsMessage.class))); } private JvmData createJvmData(long dumpedAtMillis) { return JvmData.builder() .agentComputerId("agentComputerId") .agentHostName("agentHostName") .agentUploadIntervalSeconds(300) .agentVcsId("agentVcsId") .agentVersion("agentVersion") .appName(getClass().getName()) .appVersion("appVersion") .collectorComputerId("collectorComputerId") .collectorHostName("collectorHostName") .collectorResolutionSeconds(600) .collectorVcsId("collectorVcsId") .collectorVersion("collectorVersion") .dumpedAtMillis(dumpedAtMillis) .jvmUuid(JVM_UUID) .methodVisibility("methodVisibility") .startedAtMillis(startedAtMillis) .tags(" ") .build(); } }
package org.bootstrapjsp.tags.core.panel; import org.bootstrapjsp.facet.LabelFacet; import org.bootstrapjsp.facet.Labelable; import org.bootstrapjsp.tags.html.Div; import org.tldgen.annotations.Tag; /** * Easily add a heading container to your panel with <i>&lt;panelheading&gt;</i>. * You may also include a <i>&lt;paneltitle&gt;</i> to add a pre-styled heading. * <p> * If you set a <i>label</i> attribute then a <i>&lt;paneltitle&gt;</i> will * automatically be added for you. * </p> * <p> * <dl> * <dt><b>Example</b></dt> * <dd>&lt;b:panelheading label="..."/&gt;</dd> * <dt><b>Output</b></dt> * <dd>&lt;div class="panel-heading"&gt;&lt;h3 class="panel-title"&gt;...&lt;/h3&gt;&lt;/div&gt;</dd> * </dl> * </p> */ @Tag(name="panelheading",dynamicAttributes=true) public class PanelHeading extends Div implements Labelable { public PanelHeading() { super("panel-heading"); super.addFacet(new LabelFacet()); } public PanelHeading(String label) { this(); if (label != null) { this.getFacet(LabelFacet.class).setValue(label); } } @Override public void applyLabel(String label) { super.appendChild(new PanelTitle(label), BEFORE_BODY); } }
package hq.com.control; import hq.com.aop.ctx.SpringApplicationContext; import hq.com.aop.exception.IllegalArgumentsException; import hq.com.aop.handler.ClassMethodHandler; import hq.com.aop.utils.ClassObject; import hq.com.aop.utils.RSACoderUtils; import hq.com.aop.utils.StringUtils; import hq.com.exception.IllegalOptionException; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @title : * @describle : * <p> * Create By yinhaiquan * @date 2017/5/24 10:13 */ public abstract class BaseController { public final static String REGMSG = "root\\[msg]\\["; public final static String REGROUTE = "root\\[route]\\["; public final static String MSG = "msg"; public final static String ROUTE = "route"; private final static String PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3Qz0NA1KkwvAW7Hu0cKVgOTdi\n" + "AdFIEVkWBLvyfZmsCoqky/urTS4jv3l0aruZtJ0y1pSI8fu8R/NcKE+2Aa7Ku6RH\n" + "KfbMFLa6rNqZj7838JdHbtasGvXep+SoFYJGDI+E2wmGEip5veA4Od64aidbjVbt\n" + "tA8BsBdoA22cS9u4zQIDAQAB"; public abstract Object decodeRequest(HttpServletRequest request) throws IllegalArgumentsException; public abstract Object decodeRequest(Map<String, Map<String, Object>> map) throws IllegalOptionException, IllegalArgumentsException; public abstract String encodeResponse(Object obj); public String getRegKey(String key, String regType) { if (StringUtils.isNotEmpty(key)) { switch (regType) { case MSG: return key.replaceFirst(REGMSG, "").replaceFirst(StringUtils.SUFFIX, ""); case ROUTE: return key.replaceFirst(REGROUTE, "").replaceFirst(StringUtils.SUFFIX, ""); } } return null; } public boolean isMsgOrRoute(String key, String reg) { if (StringUtils.isNotEmpty(key)) { Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(key); return matcher.find(); } return false; } /** * * * @description: 1. * 2. a. b. token * @param params * @param className /bean * @param methodName * @param route */ public void routeHandler(String className, String methodName, Map<String, String[]> route, Map<String, String[]> params) throws IllegalOptionException, IllegalArgumentsException { if (StringUtils.isNotEmpty(route)) { String[] lgs = route.get("lang"); SpringApplicationContext.setLOCALE(StringUtils.isEmpty(lgs) ? "zh_CN" : lgs[0]); /** * 2. * * @decription: a. :auth[sign]() * b. : * * map{ * className+Method auth{ * iSign:true * iLogin:false * } * } */ // 2. token // verifySignature(route,params); } } /** * * * @param route * @param params */ private void verifySignature(Map<String, String[]> route, Map<String, String[]> params) throws IllegalArgumentsException { String[] routeAuths = route.get("auth[sign]"); if (StringUtils.isNotEmpty(routeAuths)) { String sign = routeAuths[0]; Map<String, Object> data = null; try { data = new HashMap<>(); Set<Map.Entry<String, String[]>> set = params.entrySet(); for (Map.Entry<String, String[]> entry : set) { String key = entry.getKey(); String _key = key.substring(key.indexOf(StringUtils.PREFIX), key.indexOf(StringUtils.SUFFIX)); data.put(_key, entry.getValue()); } } catch (Exception e) { throw new IllegalArgumentsException(SpringApplicationContext.getMessage("exception.auth.title"),SpringApplicationContext.getMessage("exception.auth.params")); } String sign_data = RSACoderUtils.formatParameter(data); try { boolean iSign = RSACoderUtils.verify(sign_data,PUBLICKEY,sign); if (!iSign){ throw new IllegalArgumentsException(SpringApplicationContext.getMessage("exception.auth.title"),SpringApplicationContext.getMessage("exception.auth.verify")); } } catch (Exception e) { throw new IllegalArgumentsException(SpringApplicationContext.getMessage("exception.auth.title"),e.getMessage()); } }else{ throw new IllegalArgumentsException(SpringApplicationContext.getMessage("exception.auth.title"),SpringApplicationContext.getMessage("exception.auth.illegal")); } } }
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Box; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportLine; import org.ensembl.healthcheck.Reporter; import org.ensembl.healthcheck.eg_gui.Constants; import org.ensembl.healthcheck.eg_gui.JPopupTextArea; import org.ensembl.healthcheck.eg_gui.ReportPanel; import org.ensembl.healthcheck.testcase.EnsTestCase; public class GuiReporterTab extends JPanel implements Reporter { final protected TestClassList testList; final protected JScrollPane testListScrollPane; final protected TestClassListModel listModel; final protected ReportPanel reportPanel; final protected TestCaseColoredCellRenderer testCaseCellRenderer; protected boolean userClickedOnList = false; final protected Map<Class<? extends EnsTestCase>,GuiReportPanelData> reportData; public void selectDefaultListItem() { if (!userClickedOnList) { selectLastListItem(); } } /** * Selects the last item in the list and scrolls to that position. */ public void selectLastListItem() { if (listModel.getSize()>0) { int indexOfLastComponentInList =listModel.getSize()-1; testList.setSelectedIndex(indexOfLastComponentInList); testList.ensureIndexIsVisible(indexOfLastComponentInList); } } public GuiReporterTab() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); reportData = new HashMap<Class<? extends EnsTestCase>,GuiReportPanelData>(); testList = new TestClassList(TestClassList.TestClassListToolTipType.CLASS); listModel = new TestClassListModel(); reportPanel = new ReportPanel(); testList.setModel(listModel); testCaseCellRenderer = new TestCaseColoredCellRenderer(); testList.setCellRenderer(testCaseCellRenderer); testList.addMouseListener(new MouseListener() { // We want to know, when as soon as the user clicks somewhere on // the list so we can stop selecting the last item in the list. @Override public void mouseClicked(MouseEvent arg0) { userClickedOnList = true; } @Override public void mouseEntered (MouseEvent arg0) {} @Override public void mouseExited (MouseEvent arg0) {} @Override public void mousePressed (MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); // Setting the preferred size causes the scrollbars to not be adapted // to the list changing size when items are added later on, so // commented out. // testList.setPreferredSize( // new Dimension( // Constants.INITIAL_APPLICATION_WINDOW_WIDTH / 3, // Constants.INITIAL_APPLICATION_WINDOW_HEIGHT / 3 * 2 setLayout(new BorderLayout()); testListScrollPane = new JScrollPane(testList); add( new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, testListScrollPane, new JScrollPane(reportPanel) ), BorderLayout.CENTER ); testList.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } } ); } @Override public void message(final ReportLine reportLine) { final Class<? extends EnsTestCase> currentKey = reportLine.getTestCase().getClass(); if (!reportData.containsKey(currentKey)) { reportData.put(currentKey, new GuiReportPanelData(reportLine)); testCaseCellRenderer.setOutcome(currentKey, null); // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. SwingUtilities.invokeLater( new Runnable() { @Override public void run() { listModel.addTest(currentKey); // If nothing has been selected, then select // something so the user is not staring at an // empty report. //if (testList.isSelectionEmpty()) { if (!userClickedOnList) { selectDefaultListItem(); } } } ); } else { reportData.get(currentKey).addReportLine(reportLine); } // If anything was reported as a problem, the outcome is false. if (reportLine.getLevel()==ReportLine.PROBLEM) { testCaseCellRenderer.setOutcome(currentKey, false); } // If a testcase has been selected, then display the new data in the // GUI so the user can see the new line in real time. if (!testList.isSelectionEmpty()) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } ); } } @Override public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) {} @Override public void finishTestCase( final EnsTestCase testCase, final boolean result, DatabaseRegistryEntry dbre ) { // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. SwingUtilities.invokeLater( new Runnable() { @Override public void run() { testCaseCellRenderer.setOutcome(testCase.getClass(), result); } } ); } } class ReportPanel extends JPanel implements ActionListener { final protected JTextField testName; final protected JPopupTextArea description; final protected JTextField teamResponsible; final protected JTextField speciesName; final protected JPopupTextArea message; final String copy_selected_text_action = "copy_selected_text_action"; protected Component createVerticalSpacing() { return Box.createVerticalStrut(Constants.DEFAULT_VERTICAL_COMPONENT_SPACING); } public ReportPanel() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); Box singleLineInfo = Box.createVerticalBox(); testName = new JPopupTextField("Name"); description = new JPopupTextArea(3, 0); teamResponsible = new JPopupTextField("Team Responsible"); speciesName = new JPopupTextField("Species Name"); message = new JPopupTextArea (); description.setLineWrap(true); description.setWrapStyleWord(true); GuiTestRunnerFrameComponentBuilder g = null; singleLineInfo.add(g.createLeftJustifiedText("Test class:")); singleLineInfo.add(testName); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Description:")); singleLineInfo.add(description); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Team responsible:")); singleLineInfo.add(teamResponsible); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Species name:")); singleLineInfo.add(speciesName); singleLineInfo.add(createVerticalSpacing()); setLayout(new BorderLayout()); final JPopupMenu popup = new JPopupMenu(); message.add(GuiTestRunnerFrameComponentBuilder.makeMenuItem("Copy selected text", this, copy_selected_text_action)); message.setComponentPopupMenu(popup); Font currentFont = message.getFont(); Font newFont = new Font( "Courier", currentFont.getStyle(), currentFont.getSize() ); message.setFont(newFont); message.setLineWrap(true); message.setWrapStyleWord(true); singleLineInfo.add(g.createLeftJustifiedText("Output from test:")); add(singleLineInfo, BorderLayout.NORTH); add(new JScrollPane(message), BorderLayout.CENTER); } public void setData(GuiReportPanelData reportData) { testName .setText (reportData.getTestName()); description .setText (reportData.getDescription()); speciesName .setText (reportData.getSpeciesName()); teamResponsible .setText (reportData.getTeamResponsible()); message .setText (reportData.getMessage()); } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.paramString().equals(copy_selected_text_action)) { String selection = message.getSelectedText(); StringSelection data = new StringSelection(selection); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(data, data); } } }
package com.xpn.xwiki.api; import org.jmock.Mock; import org.jmock.cglib.MockObjectTestCase; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConfig; 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.objects.classes.BaseClass; import com.xpn.xwiki.user.api.XWikiUser; /** * Unit tests for {@link com.xpn.xwiki.api.User}. * * @version $Id: $ */ public class UserTest extends MockObjectTestCase { private Mock mockXWiki; private XWikiContext context; protected void setUp() throws XWikiException { this.context = new XWikiContext(); this.mockXWiki = mock(com.xpn.xwiki.XWiki.class, new java.lang.Class[] { com.xpn.xwiki.XWikiConfig.class, XWikiContext.class}, new java.lang.Object[] { new XWikiConfig(), context}); context.setWiki((XWiki) mockXWiki.proxy()); XWikiDocument doc = new XWikiDocument("XWiki", "Admin"); BaseClass userClass = new BaseClass(); userClass.addTextField("email", "email address", 20); mockXWiki.stubs().method("getClass").will(returnValue(userClass)); BaseObject userObj = doc.newObject("XWiki.XWikiUsers", context); userObj.setStringValue("email", "admin@mail.com"); mockXWiki.stubs().method("getDocument").will(returnValue(doc)); } /** * Checks that XWIKI-2040 remains fixed. */ public void testIsUserInGroupDoesNotThrowNPE() { User u = new User(null, null); assertFalse(u.isUserInGroup("XWiki.InexistentGroupName")); XWikiUser xu = new XWikiUser(null); u = new User(xu, null); assertFalse(u.isUserInGroup("XWiki.InexistentGroupName")); XWikiContext c = new XWikiContext(); u = new User(xu, c); assertFalse(u.isUserInGroup("XWiki.InexistentGroupName")); } public void testGetEmail() { User u = new User(null, null); assertNull(u.getEmail()); XWikiUser xu = new XWikiUser("XWiki.Admin"); u = new User(xu, context); assertEquals("admin@mail.com", u.getEmail()); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.event.impl.WindowEventImpl; import org.gridlab.gridsphere.layout.event.PortletTitleBarEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarListener; import org.gridlab.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portletcontainer.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent { private String title = "Portlet Unavailable"; private String portletClass = null; private PortletWindow.State windowState = PortletWindow.State.NORMAL; private String[] portletModes = null; private Portlet.Mode portletMode = Portlet.Mode.VIEW; private Portlet.Mode previousMode = null; private List listeners = new ArrayList(); private PortletSettings settings; private String[] windowStates = null; private String errorMessage = ""; private boolean hasError = false; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: " + imageSrc + "\n"); sb.append("href: " + href + "\n"); sb.append("alt tag: " + altTag + "\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String editImage = "images/window_edit.gif"; public static final String helpImage = "images/window_help.gif"; public static final String configAlt = "Configure"; public static final String editAlt = "Edit"; public static final String helpAlt = "Help"; /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode */ public PortletModeLink(String mode) throws IllegalArgumentException { // Set the image src if (mode.equalsIgnoreCase(Portlet.Mode.CONFIGURE.toString())) { imageSrc = configImage; altTag = configAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.EDIT.toString())) { imageSrc = editImage; altTag = editAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.HELP.toString())) { imageSrc = helpImage; altTag = helpAlt; } else { throw new IllegalArgumentException("No matching Portlet.Mode found for received portlet mode: " + mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ class PortletStateLink extends Link { public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String resizeImage = "images/window_resize.gif"; public static final String minimizeAlt = "Minimize"; public static final String maximizeAlt = "Maximize"; public static final String resizeAlt = "Resize"; /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state */ public PortletStateLink(String state) throws IllegalArgumentException { // Set the image src if (state.equalsIgnoreCase(PortletWindow.State.MINIMIZED.toString())) { imageSrc = minimizeImage; altTag = minimizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.MAXIMIZED.toString())) { imageSrc = maximizeImage; altTag = maximizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { imageSrc = resizeImage; altTag = resizeAlt; } else { throw new IllegalArgumentException("No matching PortletWindow.State found for received window mode: " + state); } } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowState(String state) { if (state != null) { try { this.windowState = PortletWindow.State.toState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public String getWindowState() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletMode(String mode) { try { this.portletMode = Portlet.Mode.toMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public String getPortletMode() { return portletMode.toString(); } /** * Adds a title bar listener to be notified of title bar events * * @param listener a title bar listener * @see PortletTitleBarEvent */ public void addTitleBarListener(PortletTitleBarListener listener) { listeners.add(listener); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(List list) { list = super.init(list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setClassName(this.getClass().getName()); list.add(compId); doConfig(); return list; } /** * Sets configuration information about the supported portlet modes, * allowed window states and title bar obtained from {@link PortletSettings}. * Information is queried from the {@link PortletRegistry} */ protected void doConfig() { PortletRegistry registryManager = PortletRegistry.getInstance(); String appID = registryManager.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = registryManager.getApplicationPortlet(appID); if (appPortlet != null) { ApplicationPortletConfig appConfig = appPortlet.getApplicationPortletConfig(); // get supported modes from application portlet config List supportedModes = appConfig.getSupportedModes(); portletModes = new String[supportedModes.size()]; for (int i = 0; i < supportedModes.size(); i++) { Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); portletModes[i] = mode.toString(); } ConcretePortlet concPortlet = appPortlet.getConcretePortlet(portletClass); settings = concPortlet.getPortletSettings(); // get window states from application portlet config List allowedWindowStates = appConfig.getAllowedWindowStates(); windowStates = new String[allowedWindowStates.size()]; for (int i = 0; i < allowedWindowStates.size(); i++) { PortletWindow.State state = (PortletWindow.State)allowedWindowStates.get(i); windowStates[i] = state.toString(); } } } /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ protected List createWindowLinks(GridSphereEvent event) { PortletURI portletURI; PortletResponse res = event.getPortletResponse(); for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // get rid of resized if window state is normal if (windowState == PortletWindow.State.NORMAL) { for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { windowStates[i] = ""; } } } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // create a URI for each of the window states PortletStateLink stateLink; List stateLinks = new Vector(); for (int i = 0; i < windowStates.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { stateLink = new PortletStateLink(windowStates[i]); portletURI.addParameter(GridSphereProperties.PORTLETWINDOW, windowStates[i]); stateLink.setHref(portletURI.toString()); stateLinks.add(stateLink); } catch (IllegalArgumentException e) { // do nothing } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List createModeLinks(GridSphereEvent event) { int i; PortletResponse res = event.getPortletResponse(); // subtract current portlet mode for (i = 0; i < portletModes.length; i++) { if (portletModes[i].equalsIgnoreCase(portletMode.toString())) { portletModes[i] = ""; } } // create a URI for each of the portlet modes PortletURI portletURI; PortletModeLink modeLink; List portletLinks = new ArrayList(); for (i = 0; i < portletModes.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { modeLink = new PortletModeLink(portletModes[i]); portletURI.addParameter(GridSphereProperties.PORTLETMODE, portletModes[i]); modeLink.setHref(portletURI.toString()); portletLinks.add(modeLink); } catch (IllegalArgumentException e) { } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { PortletTitleBarEvent evt = new PortletTitleBarEventImpl(event, COMPONENT_ID); PortletRequest req = event.getPortletRequest(); if (evt.getAction() == PortletTitleBarEvent.Action.WINDOW_MODIFY) { PortletResponse res = event.getPortletResponse(); windowState = evt.getState(); WindowEvent winEvent = null; if (windowState == PortletWindow.State.MAXIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MAXIMIZED); } else if (windowState == PortletWindow.State.MINIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MINIMIZED); } else if (windowState == PortletWindow.State.RESIZING) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_RESTORED); } if (winEvent != null) { try { //userManager.windowEvent(portletClass, winEvent, req, res); PortletInvoker.windowEvent(portletClass, winEvent, req, res); } catch (PortletException e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } else if (evt.getAction() == PortletTitleBarEvent.Action.MODE_MODIFY) { previousMode = portletMode; portletMode = evt.getMode(); req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, portletMode); } if (evt != null) fireTitleBarEvent(evt); } /** * Fires a title bar event notification * * @param event a portlet title bar event * @throws PortletLayoutException if a layout error occurs */ protected void fireTitleBarEvent(PortletTitleBarEvent event) throws PortletLayoutException { Iterator it = listeners.iterator(); PortletTitleBarListener l; while (it.hasNext()) { l = (PortletTitleBarListener) it.next(); l.handleTitleBarEvent(event); } } /** * Renders the portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { // title bar: configure, edit, help, title, min, max PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); // get the appropriate title for this client Client client = req.getClient(); if (settings == null) { doConfig(); } else { title = settings.getTitle(req.getLocale(), client); } List modeLinks = null, windowLinks = null; User user = req.getUser(); if (user instanceof GuestUser) { } else { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, previousMode); PrintWriter out = res.getWriter(); out.println("<tr><td class=\"window-title\">"); out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>"); // Output portlet mode icons if (modeLinks != null) { Iterator modesIt = modeLinks.iterator(); out.println("<td class=\"window-icon-left\">"); PortletModeLink mode; while (modesIt.hasNext()) { mode = (PortletModeLink) modesIt.next(); out.println("<a href=\"" + mode.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + mode.getImageSrc() + "\" title=\"" + mode.getAltTag() + "\"/></a>"); } out.println("</td>"); } // Invoke doTitle of portlet whose action was perfomed String actionStr = req.getParameter(GridSphereProperties.ACTION); out.println("<td class=\"window-title-name\">"); if (actionStr != null) { try { PortletInvoker.doTitle(portletClass, req, res); out.println(" (" + portletMode.toString() + ") "); } catch (PortletException e) { errorMessage += "Unable to invoke doTitle on active portlet\n"; hasError = true; } } else { out.println(title); } out.println("</td>"); // Output window state icons if (windowLinks != null) { Iterator windowsIt = windowLinks.iterator(); PortletStateLink state; out.println("<td class=\"window-icon-right\">"); while (windowsIt.hasNext()) { state = (PortletStateLink) windowsIt.next(); out.println("<a href=\"" + state.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + state.getImageSrc() + "\" title=\"" + state.getAltTag() + "\"/></a>"); } out.println("</td>"); } out.println("</tr></table>"); out.println("</td></tr>"); } }
package org.jitsi.videobridge.influxdb; import org.ice4j.ice.*; import org.jitsi.service.configuration.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import org.jitsi.videobridge.*; import org.jitsi.videobridge.eventadmin.*; import org.json.simple.*; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; /** * Allows logging of {@link InfluxDBEvent}s using an * <tt>InfluxDB</tt> instance. * * @author Boris Grozev * @author George Politis */ public class LoggingHandler implements EventHandler { /** * The names of the columns of a "conference created" event. */ private static final String[] CONFERENCE_CREATED_COLUMNS = new String[] {"conference_id", "focus"}; /** * The names of the columns of a "conference expired" event. */ private static final String[] CONFERENCE_EXPIRED_COLUMNS = new String[] {"conference_id"}; /** * The names of the columns of a "content created" event. */ private static final String[] CONTENT_CREATED_COLUMNS = new String[] {"name", "conference_id"}; /** * The names of the columns of a "content expired" event. */ private static final String[] CONTENT_EXPIRED_COLUMNS = new String[] {"name", "conference_id"}; /** * The names of the columns of a "channel created" event. */ private static final String[] CHANNEL_CREATED_COLUMNS = new String[] { "channel_id", "content_name", "conference_id", "endpoint_id", "lastn" }; /** * The names of the columns of a "rtp channel expired" event. */ private static final String[] RTP_CHANNEL_EXPIRED_COLUMNS = new String[] { "channel_id", "content_name", "conference_id", "endpoint_id", "stats.local_ip", "stats.local_port", "stats.remote_ip", "stats.remote_port", "stats.nb_received_bytes", "stats.nb_sent_bytes", "stats.nb_received_packets", "stats.nb_received_packets_lost", "stats.nb_sent_packets", "stats.nb_sent_packets_lost", "stats.min_download_jitter_ms", "stats.max_download_jitter_ms", "stats.avg_download_jitter_ms", "stats.min_upload_jitter_ms", "stats.max_upload_jitter_ms", "stats.avg_upload_jitter_ms" }; /** * The names of the columns of a "channel expired" event. */ private static final String[] CHANNEL_EXPIRED_COLUMNS = new String[] { "channel_id", "content_name", "conference_id", "endpoint_id" }; /** * The names of the columns of a "transport created" event. */ private static final String[] TRANSPORT_CREATED_COLUMNS = new String[] { "hash_code", "conference_id", "num_components", "ufrag", "is_controlling" }; /** * The names of the columns of a "transport manager channel added" event. */ private static final String[] TRANSPORT_CHANNEL_ADDED_COLUMNS = new String[] { "hash_code", "conference_id", "channel_id", }; /** * The names of the columns of a "transport manager channel removed" event. */ private static final String[] TRANSPORT_CHANNEL_REMOVED_COLUMNS = new String[] { "hash_code", "conference_id", "channel_id", }; /** * The names of the columns of a "transport manager connected" event. */ private static final String[] TRANSPORT_CONNECTED_COLUMNS = new String[] { "hash_code", "conference_id", "selected_pairs" }; /** * The names of the columns of a "transport manager connected" event. */ private static final String[] TRANSPORT_STATE_CHANGED_COLUMNS = new String[] { "hash_code", "conference_id", "old_state", "new_state" }; /** * The names of the columns of an "endpoint created" event. */ private static final String[] ENDPOINT_CREATED_COLUMNS = new String[] { "conference_id", "endpoint_id", }; /** * The names of the columns of an "endpoint display name" event. */ private static final String[] ENDPOINT_DISPLAY_NAME_COLUMNS = new String[] { "conference_id", "endpoint_id", "display_name" }; /** * The name of the property which specifies whether logging to an * <tt>InfluxDB</tt> is enabled. */ public static final String ENABLED_PNAME = "org.jitsi.videobridge.log.INFLUX_DB_ENABLED"; /** * The name of the property which specifies the protocol, hostname and * port number (in URL format) to use to connect to <tt>InfluxDB</tt>. */ public static final String URL_BASE_PNAME = "org.jitsi.videobridge.log.INFLUX_URL_BASE"; /** * The name of the property which specifies the name of the * <tt>InfluxDB</tt> database. */ public static final String DATABASE_PNAME = "org.jitsi.videobridge.log.INFLUX_DATABASE"; /** * The name of the property which specifies the username to use to connect * to <tt>InfluxDB</tt>. */ public static final String USER_PNAME = "org.jitsi.videobridge.log.INFLUX_USER"; /** * The name of the property which specifies the password to use to connect * to <tt>InfluxDB</tt>. */ public static final String PASS_PNAME = "org.jitsi.videobridge.log.INFLUX_PASS"; /** * The <tt>Logger</tt> used by the <tt>LoggingHandler</tt> class * and its instances to print debug information. */ private static final Logger logger = Logger.getLogger(LoggingHandler.class); /** * The <tt>Executor</tt> which is to perform the task of sending data to * <tt>InfluxDB</tt>. */ private final Executor executor = ExecutorUtils .newCachedThreadPool(true, LoggingHandler.class.getName()); /** * The <tt>URL</tt> to be used to POST to <tt>InfluxDB</tt>. Besides the * protocol, host and port also encodes the database name, user name and * password. */ private final URL url; /** * Initializes a new <tt>LoggingHandler</tt> instance, by reading * its configuration from <tt>cfg</tt>. * @param cfg the <tt>ConfigurationService</tt> to use. * * @throws Exception if initialization fails */ public LoggingHandler(ConfigurationService cfg) throws Exception { if (cfg == null) throw new NullPointerException("cfg"); String s = "Required property not set: "; String urlBase = cfg.getString(URL_BASE_PNAME, null); if (urlBase == null) throw new Exception(s + URL_BASE_PNAME); String database = cfg.getString(DATABASE_PNAME, null); if (database == null) throw new Exception(s + DATABASE_PNAME); String user = cfg.getString(USER_PNAME, null); if (user == null) throw new Exception(s + USER_PNAME); String pass = cfg.getString(PASS_PNAME, null); if (pass == null) throw new Exception(s + PASS_PNAME); String urlStr = urlBase + "/db/" + database + "/series?u=" + user +"&p=" +pass; url = new URL(urlStr); logger.info("Initialized InfluxDBLoggingService for " + urlBase + ", database \"" + database + "\""); } /** * Logs an <tt>InfluxDBEvent</tt> to an <tt>InfluxDB</tt> database. This * method returns without blocking, the blocking operations are performed * by a thread from {@link #executor}. * * @param e the <tt>Event</tt> to log. */ @SuppressWarnings("unchecked") protected void logEvent(InfluxDBEvent e) { // The following is a sample JSON message in the format used by InfluxDB // "name": "series_name", // "columns": ["column1", "column2"], // "points": [ // ["value1", 1234], // ["value2", 5678] boolean useLocalTime = e.useLocalTime(); long now = System.currentTimeMillis(); boolean multipoint = false; int pointCount = 1; JSONArray columns = new JSONArray(); JSONArray points = new JSONArray(); Object[] values = e.getValues(); if (useLocalTime) columns.add("time"); Collections.addAll(columns, e.getColumns()); if (values[0] instanceof Object[]) { multipoint = true; pointCount = values.length; } if (multipoint) { for (int i = 0; i < pointCount; i++) { if (!(values[i] instanceof Object[])) continue; JSONArray point = new JSONArray(); if (useLocalTime) point.add(now); Collections.addAll(point, (Object[]) values[i]); points.add(point); } } else { JSONArray point = new JSONArray(); if (useLocalTime) point.add(now); Collections.addAll(point, values); points.add(point); } JSONObject jsonObject = new JSONObject(); jsonObject.put("name", e.getName()); jsonObject.put("columns", columns); jsonObject.put("points", points); JSONArray jsonArray = new JSONArray(); jsonArray.add(jsonObject); // TODO: this is probably a good place to optimize by grouping multiple // events in a single POST message and/or multiple points for events // of the same type together). final String jsonString = jsonArray.toJSONString(); executor.execute(new Runnable() { @Override public void run() { sendPost(jsonString); } }); } /** * Sends the string <tt>s</tt> as the contents of an HTTP POST request to * {@link #url}. * @param s the content of the POST request. */ private void sendPost(final String s) { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/json"); connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(s); outputStream.flush(); outputStream.close(); int responseCode = connection.getResponseCode(); if (responseCode != 200) throw new IOException("HTTP response code: " + responseCode); } catch (IOException ioe) { logger.info("Failed to post to influxdb: " + ioe); } } /** * * @param conference */ private void conferenceCreated(Conference conference) { if (conference == null) { logger.debug("Could not log conference created event because " + "the conference is null."); return; } String focus = conference.getFocus(); logEvent(new InfluxDBEvent("conference_created", CONFERENCE_CREATED_COLUMNS, new Object[]{ conference.getID(), focus != null ? focus : "null" })); } /** * * @param conference */ private void conferenceExpired(Conference conference) { if (conference == null) { logger.debug("Could not log conference expired event because " + "the conference is null."); return; } logEvent(new InfluxDBEvent("conference_expired", CONFERENCE_EXPIRED_COLUMNS, new Object[]{ conference.getID() })); } /** * * @param endpoint */ private void endpointCreated(Endpoint endpoint) { if (endpoint == null) { logger.debug("Could not log endpoint created event because " + "the endpoint is null."); return; } Conference conference = endpoint.getConference(); if (conference == null) { logger.debug("Could not log endpoint created event because " + "the conference is null."); return; } logEvent(new InfluxDBEvent("endpoint_created", ENDPOINT_CREATED_COLUMNS, new Object[]{ conference.getID(), endpoint.getID() })); } /** * * @param endpoint */ private void endpointDisplayNameChanged(Endpoint endpoint) { if (endpoint == null) { logger.debug("Could not log endpoint display name changed" + " event because the endpoint is null."); return; } Conference conference = endpoint.getConference(); if (conference == null) { logger.debug("Could not log endpoint display name changed " + " event because the conference is null."); return; } logEvent(new InfluxDBEvent("endpoint_display_name", ENDPOINT_DISPLAY_NAME_COLUMNS, new Object[]{ conference.getID(), endpoint.getID(), endpoint.getDisplayName() })); } /** * * @param content */ private void contentCreated(Content content) { if (content == null) { logger.debug("Could not log content created event because " + "the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log content created event because " + "the conference is null."); return; } logEvent(new InfluxDBEvent("content_created", CONTENT_CREATED_COLUMNS, new Object[] { content.getName(), conference.getID() })); } /** * * @param content */ private void contentExpired(Content content) { if (content == null) { logger.debug("Could not log content expired event because " + "the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log content expired event because " + "the conference is null."); return; } logEvent(new InfluxDBEvent("content_expired", CONTENT_EXPIRED_COLUMNS, new Object[] { content.getName(), conference.getID() })); } private void transportChannelAdded(Channel channel) { TransportManager transportManager; try { transportManager = channel.getTransportManager(); } catch (IOException e) { logger.error("Could not log the transport channel added event " + "because of an error.", e); return; } Content content = channel.getContent(); if (content == null) { logger.debug("Could not log the transport channel added event " + "because the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log the transport channel added event " + "because the conference is null."); return; } logEvent(new InfluxDBEvent("transport_channel_added", TRANSPORT_CHANNEL_ADDED_COLUMNS, new Object[]{ String.valueOf(transportManager.hashCode()), conference.getID(), channel.getID() })); } /** * * @param channel */ private void transportChannelRemoved(Channel channel) { TransportManager transportManager; try { transportManager = channel.getTransportManager(); } catch (IOException e) { logger.error("Could not log the transport channel removed event " + "because of an error.", e); return; } Content content = channel.getContent(); if (content == null) { logger.debug("Could not log the transport channel removed event " + "because the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log the transport channel removed event " + "because the conference is null."); return; } logEvent(new InfluxDBEvent("transport_channel_removed", TRANSPORT_CHANNEL_REMOVED_COLUMNS, new Object[] { String.valueOf(transportManager.hashCode()), conference.getID(), channel.getID() })); } /** * * @param transportManager * @param oldState * @param newState */ private void transportStateChanged( IceUdpTransportManager transportManager, IceProcessingState oldState, IceProcessingState newState) { Conference conference = transportManager.getConference(); if (conference == null) { logger.debug("Could not log the transport state changed event " + "because the conference is null."); return; } logEvent(new InfluxDBEvent("transport_state_changed", TRANSPORT_STATE_CHANGED_COLUMNS, new Object[]{ String.valueOf(transportManager.hashCode()), conference.getID(), oldState == null ? "null" : oldState.toString(), newState == null ? "null" : newState.toString() })); } /** * * @param transportManager */ private void transportCreated(IceUdpTransportManager transportManager) { Conference conference = transportManager.getConference(); if (conference == null) { logger.debug("Could not log the transport created event " + "because the conference is null."); return; } Agent agent = transportManager.getAgent(); if (agent == null) { logger.debug("Could not log the transport created event " + "because the agent is null."); return; } logEvent(new InfluxDBEvent("transport_created", TRANSPORT_CREATED_COLUMNS, new Object[]{ String.valueOf(transportManager.hashCode()), conference.getID(), transportManager.getNumComponents(), agent.getLocalUfrag(), Boolean.valueOf(transportManager.isControlling()).toString() })); } /** * * @param transportManager */ private void transportConnected(IceUdpTransportManager transportManager) { Conference conference = transportManager.getConference(); if (conference == null) { logger.debug("Could not log the transport connected event " + "because the conference is null."); return; } IceMediaStream iceStream = transportManager.getIceStream(); if (iceStream == null) { logger.debug("Could not log the transport connected event " + "because the iceStream is null."); return; } StringBuilder s = new StringBuilder(); for (Component component : iceStream.getComponents()) { CandidatePair pair = component.getSelectedPair(); if (pair == null) continue; Candidate localCandidate = pair.getLocalCandidate(); Candidate remoteCandidate = pair.getRemoteCandidate(); s.append((localCandidate == null) ? "unknown" : localCandidate.getTransportAddress()) .append(" -> ") .append((remoteCandidate == null) ? "unknown" : remoteCandidate.getTransportAddress()) .append("; "); } logEvent(new InfluxDBEvent("transport_connected", TRANSPORT_CONNECTED_COLUMNS, new Object[]{ String.valueOf(transportManager.hashCode()), conference.getID(), s.toString() })); } /** * * @param channel */ private void channelCreated(Channel channel) { if (channel == null) { logger.debug("Could not log the channel created event " + "because the channel is null."); return; } Content content = channel.getContent(); if (content == null) { logger.debug("Could not log the channel created event " + "because the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log the channel created event " + "because the conference is null."); return; } String endpointID = ""; Endpoint endpoint = channel.getEndpoint(); if (endpoint != null) { endpointID = endpoint.getID(); } int lastN = -1; if (channel instanceof VideoChannel) { lastN = ((VideoChannel)channel).getLastN(); } logEvent(new InfluxDBEvent("channel_created", CHANNEL_CREATED_COLUMNS, new Object[] { channel.getID(), content.getName(), conference.getID(), endpointID, lastN })); } /** * * @param channel */ private void channelExpired(Channel channel) { if (channel == null) { logger.debug("Could not log the channel expired event " + "because the channel is null."); return; } Content content = channel.getContent(); if (content == null) { logger.debug("Could not log the channel expired event " + "because the content is null."); return; } Conference conference = content.getConference(); if (conference == null) { logger.debug("Could not log the channel expired event " + "because the conference is null."); return; } MediaStreamStats stats = null; if (channel instanceof RtpChannel) { RtpChannel rtpChannel = (RtpChannel) channel; MediaStream stream = rtpChannel.getStream(); if (stream != null) { stats = stream.getMediaStreamStats(); } } Endpoint endpoint = channel.getEndpoint(); String endpointID = endpoint == null ? "" : endpoint.getID(); if (stats != null) { Object[] values = new Object[] { channel.getID(), content.getName(), conference.getID(), endpointID, stats.getLocalIPAddress(), stats.getLocalPort(), stats.getRemoteIPAddress(), stats.getRemotePort(), stats.getNbReceivedBytes(), stats.getNbSentBytes(), // Number of packets sent from the other side stats.getNbPacketsReceived() + stats.getDownloadNbPacketLost(), stats.getDownloadNbPacketLost(), stats.getNbPacketsSent(), stats.getUploadNbPacketLost(), stats.getMinDownloadJitterMs(), stats.getMaxDownloadJitterMs(), stats.getAvgDownloadJitterMs(), stats.getMinUploadJitterMs(), stats.getMaxUploadJitterMs(), stats.getAvgUploadJitterMs() }; logEvent(new InfluxDBEvent( "channel_expired", RTP_CHANNEL_EXPIRED_COLUMNS, values)); } else { Object[] values = new Object[] { channel.getID(), content.getName(), conference.getID(), endpointID }; logEvent(new InfluxDBEvent( "channel_expired", CHANNEL_EXPIRED_COLUMNS, values)); } } @Override public void handleEvent(Event event) { if (event == null) { logger.debug("Could not handle the event because it was null."); return; } String topic = event.getTopic(); if (EventFactory.CHANNEL_CREATED_TOPIC.equals(topic)) { Channel channel = (Channel) event.getProperty(EventFactory.EVENT_SOURCE); channelCreated(channel); } else if (EventFactory.CHANNEL_EXPIRED_TOPIC.equals(topic)) { Channel channel = (Channel) event.getProperty(EventFactory.EVENT_SOURCE); channelExpired(channel); } else if ( EventFactory.CONFERENCE_CREATED_TOPIC.equals(topic)) { Conference conference = (Conference) event.getProperty(EventFactory.EVENT_SOURCE); conferenceCreated(conference); } else if (EventFactory.CONFERENCE_EXPIRED_TOPIC.equals(topic)) { Conference conference = (Conference) event.getProperty(EventFactory.EVENT_SOURCE); conferenceExpired(conference); } else if (EventFactory.CONTENT_CREATED_TOPIC.equals(topic)) { Content content = (Content) event.getProperty(EventFactory.EVENT_SOURCE); contentCreated(content); } else if (EventFactory.CONTENT_EXPIRED_TOPIC.equals(topic)) { Content content = (Content) event.getProperty(EventFactory.EVENT_SOURCE); contentExpired(content); } else if (EventFactory.ENDPOINT_CREATED_TOPIC.equals(topic)) { Endpoint endpoint = (Endpoint) event.getProperty(EventFactory.EVENT_SOURCE); endpointCreated(endpoint); } else if (EventFactory.ENDPOINT_DISPLAY_NAME_CHANGED_TOPIC.equals(topic)) { Endpoint endpoint = (Endpoint) event.getProperty(EventFactory.EVENT_SOURCE); endpointDisplayNameChanged(endpoint); } else if (EventFactory.TRANSPORT_CHANNEL_ADDED_TOPIC.equals(topic)) { Channel channel = (Channel) event.getProperty(EventFactory.EVENT_SOURCE); transportChannelAdded(channel); } else if (EventFactory.TRANSPORT_CHANNEL_REMOVED_TOPIC.equals(topic)) { Channel channel = (Channel) event.getProperty(EventFactory.EVENT_SOURCE); transportChannelRemoved(channel); } else if (EventFactory.TRANSPORT_CONNECTED_TOPIC.equals(topic)) { IceUdpTransportManager transportManager = (IceUdpTransportManager) event.getProperty( EventFactory.EVENT_SOURCE); transportConnected(transportManager); } else if (EventFactory.TRANSPORT_CREATED_TOPIC.equals(topic)) { IceUdpTransportManager transportManager = (IceUdpTransportManager) event.getProperty( EventFactory.EVENT_SOURCE); transportCreated(transportManager); } else if (EventFactory.TRANSPORT_STATE_CHANGED_TOPIC.equals(topic)) { IceUdpTransportManager transportManager = (IceUdpTransportManager) event.getProperty( EventFactory.EVENT_SOURCE); IceProcessingState oldState = (IceProcessingState) event.getProperty("oldState"); IceProcessingState newState = (IceProcessingState) event.getProperty("newState"); transportStateChanged(transportManager, oldState, newState); } } }
package org.jpos.ee.pm.core.operations; import org.jpos.ee.pm.core.PMContext; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMSession; import org.jpos.ee.pm.core.PresentationManager; import org.jpos.ee.pm.menu.Menu; import org.jpos.ee.pm.menu.MenuSupport; import org.jpos.ee.pm.security.core.InvalidPasswordException; import org.jpos.ee.pm.security.core.InvalidUserException; import org.jpos.ee.pm.security.core.PMSecurityConnector; import org.jpos.ee.pm.security.core.PMSecurityException; import org.jpos.ee.pm.security.core.PMSecurityService; import org.jpos.ee.pm.security.core.PMSecurityUser; import org.jpos.ee.pm.security.core.UserAlreadyLogged; import org.jpos.ee.pm.security.core.UserNotFoundException; /** * * @author jpaoletti */ public class LoginOperation extends OperationCommandSupport { public LoginOperation(String operationId) { super(operationId); } @Override protected boolean prepare(PMContext ctx) throws PMException { return true; } @Override protected void doExecute(PMContext ctx) throws PMException { final PresentationManager pm = ctx.getPresentationManager(); final PMSession session = pm.registerSession(null); ctx.setSessionId(session.getId()); if (pm.isLoginRequired()) { try { final PMSecurityUser u = authenticate(ctx); session.setUser(u); session.setMenu(loadMenu(session, u)); } catch (UserNotFoundException e) { pm.removeSession(session.getId()); throw new PMException("pm_security.user.not.found"); } catch (UserAlreadyLogged e) { pm.removeSession(session.getId()); throw new PMException("pm_security.user.already.logged"); } catch (InvalidPasswordException e) { pm.removeSession(session.getId()); throw new PMException("pm_security.password.invalid"); } catch (Exception e) { pm.error(e); pm.removeSession(session.getId()); throw new PMException("pm_core.unespected.error"); } } else { final PMSecurityUser user = new PMSecurityUser(); user.setName(" "); session.setUser(user); session.setMenu(loadMenu(session, user)); } } private Menu loadMenu(PMSession session, PMSecurityUser u) throws PMException { final Menu menu = MenuSupport.getMenu(u.getPermissionList()); session.put("user", u); session.put("menu", menu); return menu; } /** * @param ctx The context with all the parameters * @return The user */ private PMSecurityUser authenticate(PMContext ctx) throws PMSecurityException { PMSecurityUser u = null; final Object username = ctx.getParameter("username"); final Object password = ctx.getParameter("password"); if (username == null || password == null) { throw new InvalidUserException(); } u = getConnector(ctx).authenticate( username.toString(), password.toString()); return u; } private PMSecurityConnector getConnector(PMContext ctx) { return PMSecurityService.getService().getConnector(ctx); } @Override protected boolean checkUser() { return false; } }
package org.kwstudios.play.ragemode.commands; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.kwstudios.play.ragemode.events.EventListener; import org.kwstudios.play.ragemode.gameLogic.PlayerList; import org.kwstudios.play.ragemode.loader.PluginLoader; import org.kwstudios.play.ragemode.scores.PlayerPoints; import org.kwstudios.play.ragemode.scores.RageScores; import org.kwstudios.play.ragemode.signs.SignCreator; import org.kwstudios.play.ragemode.statistics.MySQLThread; import org.kwstudios.play.ragemode.statistics.YAMLStats; import org.kwstudios.play.ragemode.title.TitleAPI; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; import org.kwstudios.play.ragemode.toolbox.GameBroadcast; import org.kwstudios.play.ragemode.toolbox.GetGames; public class StopGame { public StopGame(Player player, String label, String[] args, FileConfiguration fileConfiguration) { if (args.length >= 2) { if (PlayerList.isGameRunning(args[1])) { String[] players = PlayerList.getPlayersInGame(args[1]); RageScores.calculateWinner(args[1], players); if (players != null) { int i = 0; int imax = players.length; while (i < imax) { if (players[i] != null) { PlayerList.removePlayer(Bukkit.getPlayer(UUID.fromString(players[i]))); PlayerList.removePlayerSynced(Bukkit.getPlayer(UUID.fromString(players[i]))); } i++; } } GameBroadcast.broadcastToGame(args[1], ConstantHolder.RAGEMODE_PREFIX + ChatColor.translateAlternateColorCodes('', PluginLoader.getMessages().GAME_STOPPED.replace("$GAME$", args[1]))); RageScores.removePointsForPlayers(players); PlayerList.setGameNotRunning(args[1]); SignCreator.updateAllSigns(args[1]); } else { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.translateAlternateColorCodes('', PluginLoader.getMessages().GAME_NOT_RUNNING)); } } else { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.translateAlternateColorCodes('', PluginLoader.getMessages().MISSING_ARGUMENTS.replace("$USAGE$", "/rm stop <GameName>"))); } } public static void stopGame(String game) { if (PlayerList.isGameRunning(game)) { String[] players = PlayerList.getPlayersInGame(game); String winnerUUID = RageScores.calculateWinner(game, players); if (Bukkit.getPlayer(UUID.fromString(winnerUUID)) != null) { Player winner = Bukkit.getPlayer(UUID.fromString(winnerUUID)); for (String playerUUID : players) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); String title = ChatColor.DARK_GREEN + winner.getName() + ChatColor.GOLD + " won this round!"; String subtitle = ChatColor.GOLD + "He has got " + ChatColor.DARK_PURPLE + Integer.toString(RageScores.getPlayerPoints(winnerUUID).getPoints()) + ChatColor.GOLD + " points and his K/D is " + ChatColor.DARK_PURPLE + Integer.toString(RageScores.getPlayerPoints(winnerUUID).getKills()) + " / " + Integer.toString(RageScores.getPlayerPoints(winnerUUID).getDeaths()) + ChatColor.GOLD + "."; PlayerList.removePlayerSynced(player); TitleAPI.sendTitle(player, 20, 160, 20, title, subtitle); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 200, 25, false, false), true); } } if (!EventListener.waitingGames.containsKey(game)) { EventListener.waitingGames.put(game, true); } else { EventListener.waitingGames.remove(game); EventListener.waitingGames.put(game, true); } final String gameName = game; PluginLoader.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(PluginLoader.getInstance(), new Runnable() { @Override public void run() { finishStopping(gameName); if (EventListener.waitingGames.containsKey(gameName)) { EventListener.waitingGames.remove(gameName); } } }, 200); } } private static void finishStopping(String game) { if (PlayerList.isGameRunning(game)) { String[] players = PlayerList.getPlayersInGame(game); int f = 0; int fmax = players.length; List<PlayerPoints> lPP = new ArrayList<PlayerPoints>(); boolean doSQL = PluginLoader.getInstance().getConfig().getString("settings.global.statistics.type") .equalsIgnoreCase("mySQL"); while (f < fmax) { if (RageScores.getPlayerPoints(players[f]) != null) { PlayerPoints pP = RageScores.getPlayerPoints(players[f]); lPP.add(pP); if (doSQL) { Thread sthread = new Thread(new MySQLThread(pP)); sthread.start(); } } f++; } Thread thread = new Thread(YAMLStats.createPlayersStats(lPP)); thread.start(); if (players != null) { int i = 0; int imax = players.length; while (i < imax) { if (players[i] != null) { PlayerList.removePlayer(Bukkit.getPlayer(UUID.fromString(players[i]))); } i++; } } RageScores.removePointsForPlayers(players); GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.translateAlternateColorCodes('', PluginLoader.getMessages().GAME_STOPPED.replace("$GAME$", game))); PlayerList.setGameNotRunning(game); SignCreator.updateAllSigns(game); } } public static void stopAllGames(FileConfiguration fileConfiguration, Logger logger) { logger.info("RageMode is searching for games to stop..."); String[] games = GetGames.getGameNames(fileConfiguration); int i = 0; int imax = games.length; while (i < imax) { if (PlayerList.isGameRunning(games[i])) { logger.info("Stopping " + games[i] + " ..."); String[] players = PlayerList.getPlayersInGame(games[i]); RageScores.calculateWinner(games[i], players); if (players != null) { int n = 0; int nmax = players.length; while (n < nmax) { if (players[n] != null) { PlayerList.removePlayer(Bukkit.getPlayer(UUID.fromString(players[n]))); } n++; } } RageScores.removePointsForPlayers(players); PlayerList.setGameNotRunning(games[i]); SignCreator.updateAllSigns(games[i]); logger.info(games[i] + " has been stopped."); } i++; } logger.info("Ragemode: All games stopped!"); } }
/* * * Adafruit16CServoDriver * */ package org.myrobotlab.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.myrobotlab.service.interfaces.I2CController; import org.myrobotlab.service.interfaces.MotorControl; import org.myrobotlab.service.interfaces.MotorController; import org.myrobotlab.service.interfaces.PinDefinition; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.ServoController; import org.slf4j.Logger; public class Adafruit16CServoDriver extends Service implements I2CControl, ServoController, MotorController { /** * SpeedControl, calculates the next position at regular intervals to make the * servo move at the desired speed * */ public class SpeedControl extends Thread { volatile ServoData servoData; String name; long now; long lastExecution; long deltaTime; public SpeedControl(String name) { super(String.format("%s.SpeedControl", name)); servoData = servoMap.get(name); servoData.isMoving = true; this.name = name; } @Override public void run() { log.info(String.format("Speed control started for %s", name)); servoData = servoMap.get(name); log.debug(String.format("Moving from %s to %s at %s degrees/second", servoData.currentOutput, servoData.targetOutput, servoData.velocity)); try { lastExecution = System.currentTimeMillis(); double _velocity; if (servoData.acceleration == -1) { _velocity = servoData.velocity; } else { _velocity = 0; } while (servoData.isMoving && servoData.isEnergized) { now = System.currentTimeMillis(); deltaTime = now - lastExecution; if (servoData.acceleration != -1) { _velocity = _velocity + (servoData.acceleration * deltaTime * 0.001); if (_velocity > servoData.velocity) { _velocity = servoData.velocity; } } if (servoData.currentOutput < servoData.targetOutput) { // Move // positive // direction servoData.currentOutput += (_velocity * deltaTime) * 0.001; if (servoData.currentOutput >= servoData.targetOutput) { servoData.currentOutput = servoData.targetOutput; servoData.isMoving = false; } } else if (servoData.currentOutput > servoData.targetOutput) { // Move // negative // direction servoData.currentOutput -= (_velocity * deltaTime * 0.001); if (servoData.currentOutput <= servoData.targetOutput) { servoData.currentOutput = servoData.targetOutput; servoData.isMoving = false; } } else { // We have reached the position so shutdown the thread servoData.isMoving = false; log.debug("This line should not repeat"); } int pulseWidthOff = SERVOMIN + (int) (servoData.currentOutput * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180)); setServo(servoData.pin, pulseWidthOff); // Sleep 100ms before sending next position lastExecution = now; log.info(String.format("Sent %s using a %s tick at velocity %s", servoData.currentOutput, deltaTime, _velocity)); Thread.sleep(50); } log.info("Shuting down SpeedControl"); } catch (Exception e) { servoData.isMoving = false; if (e instanceof InterruptedException) { log.debug("Shuting down SpeedControl"); } else { log.error("speed control threw", e); } } } } /** version of the library */ static public final String VERSION = "0.9"; private static final long serialVersionUID = 1L; // Depending on your servo make, the pulse width min and max may vary, you // want these to be as small/large as possible without hitting the hard stop // for max range. You'll have to tweak them as necessary to match the servos // you have! public final static int SERVOMIN = 150; // this // the // 'minimum' // pulse // length count (out of 4096) public final static int SERVOMAX = 600; // this // the // 'maximum' // pulse // length count (out of 4096) transient public I2CController controller; // Constant for default PWM freqency private static int defaultPwmFreq = 60; final static int minPwmFreq = 24; final static int maxPwmFreq = 1526; int pwmFreq; boolean pwmFreqSet = false; // List of possible addresses. Used by the GUI. public List<String> deviceAddressList = Arrays.asList("0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F"); // Default address public String deviceAddress = "0x40"; /** * This address is to address all Adafruit16CServoDrivers on the i2c bus Don't * use this address for any other device on the i2c bus since it will cause * collisions. */ public String broadcastAddress = "0x70"; public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7"); public String deviceBus = "1"; public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName()); public static final int PCA9685_MODE1 = 0x00; // Mod // register public static final byte PCA9685_SLEEP = 0x10; // Set sleep mode before // changing prescale value public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set autoincrement to // be able to write // more than one byte // in sequence public static final byte PCA9685_PRESCALE = (byte) 0xFE; // PreScale register // Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0 // The rest of the addresses are calculated based on pin numbers public static final int PCA9685_LED0_ON_L = 0x06; // First LED address Low public static final int PCA9685_LED0_ON_H = 0x07; // First LED address High public static final int PCA9685_LED0_OFF_L = 0x08; // First LED address Low public static final int PCA9685_LED0_OFF_H = 0x08; // First LED addressHigh public static final int PCA9685_ALL_LED_OFF_H = 0xFD; // All call i2c address // ( Used for shutdown // of all pwm ) public static final int PCA9685_TURN_ALL_LED_OFF = 0x10; // Command to turn // all LED off stop // pwm ) // public static final int PWM_FREQ = 60; // default frequency for servos public static final float osc_clock = 25000000; // clock frequency of the // internal clock public static final float precision = 4096; // pwm_precision // i2c controller public List<String> controllers; public String controllerName; // isAttached is used by the GUI's to know it the service is attached or not // It will be set when the first successful communication has been done with // the // i2c device ( bus and address have been verified ) public boolean isAttached = false; /** * @Mats - added by GroG - was wondering if this would help, probably you need * a reverse index too ? * @GroG - I only need servoNameToPin yet. To be able to move at a set speed a * few extra values are needed */ class ServoData { int pin; SpeedControl speedcontrol; double velocity = -1; double acceleration = -1; boolean isMoving = false; double targetOutput; double currentOutput; boolean isEnergized = false; } transient HashMap<String, ServoData> servoMap = new HashMap<String, ServoData>(); // Motor related constants public static final int MOTOR_FORWARD = 1; public static final int MOTOR_BACKWARD = 0; public static final int defaultMotorPwmFreq = 1000; /** * pin named map of all the pins on the board */ Map<String, PinDefinition> pinMap = null; /** * the definitive sequence of pins - "true address" */ Map<Integer, PinDefinition> pinIndex = null; public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver"); log.info("Driver {}", driver); } public Adafruit16CServoDriver(String n) { super(n); createPinList(); refreshControllers(); subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered"); } public void onRegistered(ServiceInterface s) { refreshControllers(); broadcastState(); } /* * Refresh the list of running services that can be selected in the GUI */ public List<String> refreshControllers() { controllers = Runtime.getServiceNamesFromInterface(I2CController.class); return controllers; } /* * Set the PWM pulsewidth * */ public void setPWM(Integer pin, Integer pulseWidthOn, Integer pulseWidthOff) { byte[] buffer = { (byte) (PCA9685_LED0_ON_L + (pin * 4)), (byte) (pulseWidthOn & 0xff), (byte) (pulseWidthOn >> 8), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) }; log.info(String.format("Writing pin %s, pulesWidthOn %s, pulseWidthOff %s", pin, pulseWidthOn, pulseWidthOff)); controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length); } /* * Set the PWM frequency i.e. the frequency between positive pulses. * */ public void setPWMFreq(int pin, Integer hz) { // Analog servos run at ~60 Hz float prescale_value; if (hz < minPwmFreq) { log.error(String.format("Minimum PWMFreq is %s Hz, requested freqency is %s Hz, clamping to minimum", minPwmFreq, hz)); hz = minPwmFreq; prescale_value = 255; } else if (hz > maxPwmFreq) { log.error(String.format("Maximum PWMFreq is %s Hz, requested frequency is %s Hz, clamping to maximum", maxPwmFreq, hz)); hz = maxPwmFreq; prescale_value = 3; } else { // Multiplying with factor 0.9 to correct the frequency // See prescale_value = Math.round(0.9 * osc_clock / precision / hz) - 1; } log.info(String.format("PWMFreq %s hz, prescale_value calculated to %s", hz, prescale_value)); // Set sleep mode before changing PWM freqency byte[] writeBuffer = { PCA9685_MODE1, PCA9685_SLEEP }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writeBuffer, writeBuffer.length); // Wait 1 millisecond until the oscillator has stabilized try { Thread.sleep(1); } catch (InterruptedException e) { if (Thread.interrupted()) { // Clears interrupted status! } } // Write the PWM frequency value byte[] buffer2 = { PCA9685_PRESCALE, (byte) prescale_value }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer2, buffer2.length); // Leave sleep mode, set autoincrement to be able to write several // bytes // in sequence byte[] buffer3 = { PCA9685_MODE1, PCA9685_AUTOINCREMENT }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer3, buffer3.length); // Wait 1 millisecond until the oscillator has stabilized try { Thread.sleep(1); } catch (InterruptedException e) { if (Thread.interrupted()) { // Clears interrupted status! } } pwmFreq = hz; pwmFreqSet = true; } /* * Orderly shutdown. Send a message to stop all pwm generation * */ public void stopPwm() { byte[] buffer = { (byte) (PCA9685_ALL_LED_OFF_H), (byte) PCA9685_TURN_ALL_LED_OFF }; log.info(String.format("Writing shutdown command to %s", this.getName())); controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length); } void setServo(Integer pin, Integer pulseWidthOff) { // since pulseWidthOff can be larger than > 256 it needs to be // sent as 2 bytes /* * log.debug( String.format("setServo %s deviceAddress %s pin %s pulse %s", * pin, deviceAddress, pin, pulseWidthOff)); byte[] buffer = { (byte) * (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) * (pulseWidthOff >> 8) }; controller.i2cWrite(this, * Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, * buffer.length); */ setPWM(pin, 0, pulseWidthOff); } /** * this would have been nice to have Java 8 and a default implementation in * this interface which does Servo sweeping in the Servo (already implemented) * and only if the controller can does it do sweeping on the "controller" * * For example MrlComm can sweep internally (or it used to be implemented) */ @Override public void servoSweepStart(ServoControl servo) { log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl"); } @Override public void servoSweepStop(ServoControl servo) { log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl"); } @Override public void servoMoveTo(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); if (!pwmFreqSet) { setPWMFreq(servoData.pin, defaultPwmFreq); } if (servoData.isEnergized) { // Move at max speed if (servoData.velocity == -1) { log.debug("Ada move at max speed"); servoData.currentOutput = servo.getTargetOutput(); servoData.targetOutput = servo.getTargetOutput(); log.debug(String.format("servoWrite %s deviceAddress %s targetOutput %f", servo.getName(), deviceAddress, servo.getTargetOutput())); int pulseWidthOff = SERVOMIN + (int) (servo.getTargetOutput() * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180)); setServo(servo.getPin(), pulseWidthOff); } else { log.debug(String.format("Ada move at velocity %s degrees/s", servoData.velocity)); servoData.targetOutput = servo.getTargetOutput(); // Start a thread to handle the speed for this servo if (servoData.isMoving == false) { servoData.speedcontrol = new SpeedControl(servo.getName()); servoData.speedcontrol.start(); } } } } @Override public void servoWriteMicroseconds(ServoControl servo, int uS) { ServoData servoData = servoMap.get(servo.getName()); if (!pwmFreqSet) { setPWMFreq(servoData.pin, defaultPwmFreq); } int pin = servo.getPin(); // 1000 ms => 150, 2000 ms => 600 int pulseWidthOff = (int) (uS * 0.45) - 300; // since pulseWidthOff can be larger than > 256 it needs to be // sent as 2 bytes log.debug(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, pin, pulseWidthOff)); byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length); } public String publishAttachedDevice(String deviceName) { return deviceName; } /** * Start sending pulses to the servo * */ @Override public void servoAttachPin(ServoControl servo, int pin) { ServoData servoData = servoMap.get(servo.getName()); servoData.pin = pin; } /** * Stop sending pulses to the servo, relax */ @Override public void servoDetachPin(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); setPWM(servoData.pin, 4096, 0); servoData.isEnergized = false; } public void servoSetMaxVelocity(ServoControl servo) { log.warn("servoSetMaxVelocity not implemented in Adafruit16CServoDriver"); } @Override public void motorMove(MotorControl mc) { Class<?> type = mc.getClass(); double powerOutput = mc.getPowerOutput(); if (Motor.class == type) { Motor motor = (Motor) mc; if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getPwrPin(), motor.getPwmFreq()); } setPinValue(motor.getDirPin(), (powerOutput < 0) ? MOTOR_BACKWARD : MOTOR_FORWARD); setPinValue(motor.getPwrPin(), powerOutput); } else if (MotorDualPwm.class == type) { MotorDualPwm motor = (MotorDualPwm) mc; log.info(String.format("Adafrutit16C Motor DualPwm motorMove, powerOutput = %s", powerOutput)); if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getLeftPwmPin(), motor.getPwmFreq()); setPWMFreq(motor.getRightPwmPin(), motor.getPwmFreq()); } if (powerOutput < 0) { setPinValue(motor.getLeftPwmPin(), 0); setPinValue(motor.getRightPwmPin(), Math.abs(powerOutput / 255)); } else if (powerOutput > 0) { setPinValue(motor.getRightPwmPin(), 0); setPinValue(motor.getLeftPwmPin(), Math.abs(powerOutput / 255)); } else { setPinValue(motor.getRightPwmPin(), 0); setPinValue(motor.getLeftPwmPin(), 0); } } else { error("motorMove for motor type %s not supported", type); } } @Override public void motorMoveTo(MotorControl mc) { // speed parameter? // modulo - if < 1 // speed = 1 else log.info("motorMoveTo targetPos {} powerLevel {}", mc.getTargetPos(), mc.getPowerLevel()); Class<?> type = mc.getClass(); // if pulser (with or without fake encoder // send a series of pulses ! // with current direction if (Motor.class == type) { Motor motor = (Motor) mc; // check motor direction // send motor direction // TODO powerLevel = 100 * powerlevel // FIXME !!! - this will have to send a Long for targetPos at some // point !!!! double target = Math.abs(motor.getTargetPos()); int b0 = (int) target & 0xff; int b1 = ((int) target >> 8) & 0xff; int b2 = ((int) target >> 16) & 0xff; int b3 = ((int) target >> 24) & 0xff; // TODO FIXME // sendMsg(PULSE, deviceList.get(motor.getName()).id, b3, b2, b1, // b0, (int) motor.getPowerLevel(), feedbackRate); } } @Override public void motorStop(MotorControl mc) { Class<?> type = mc.getClass(); if (Motor.class == type) { Motor motor = (Motor) mc; if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getPwrPin(), motor.getPwmFreq()); } setPinValue(motor.getPwrPin(), 0); } else if (MotorDualPwm.class == type) { MotorDualPwm motor = (MotorDualPwm) mc; setPinValue(motor.getLeftPwmPin(), 0); setPinValue(motor.getRightPwmPin(), 0); } } @Override public void motorReset(MotorControl motor) { // perhaps this should be in the motor control // motor.reset(); // opportunity to reset variables on the controller // sendMsg(MOTOR_RESET, motor.getind); } public void setPinValue(int pin, double powerOutput) { log.info(String.format("Adafruit16C setPinValue, pin = %s, powerOutput = %s", pin, powerOutput)); if (powerOutput < 0) { log.error(String.format("Adafruit16CServoDriver setPinValue. Value below zero (%s). Defaulting to 0.", powerOutput)); powerOutput = 0; } else if (powerOutput > 1) { log.error(String.format("Adafruit16CServoDriver setPinValue. Value > 1 (%s). Defaulting to 1", powerOutput)); powerOutput = 1; } int powerOn; int powerOff; // No phase shift. Simple calculation if (powerOutput == 0) { powerOn = 4096; powerOff = 0; } else if (powerOutput == 1) { powerOn = 0; powerOff = 1; } else { powerOn = (int) (powerOutput * 4096); powerOff = 4095; } log.info(String.format("powerOutput = %s, powerOn = %s, powerOff = %s", powerOutput, powerOn, powerOff)); setPWM(pin, powerOn, powerOff); } public Map<String, PinDefinition> createPinList() { pinIndex = new HashMap<Integer, PinDefinition>(); for (int i = 0; i < 16; ++i) { PinDefinition pindef = new PinDefinition(); String name = null; name = String.format("D%d", i); pindef.setDigital(true); pindef.setName(name); pindef.setAddress(i); pinIndex.put(i, pindef); } return pinMap; } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName()); meta.addDescription("Adafruit 16-Channel PWM/Servo Driver"); meta.addCategory("shield", "servo & pwm"); meta.setSponsor("Mats"); /* * meta.addPeer("arduino", "Arduino", "our Arduino"); meta.addPeer("raspi", * "RasPi", "our RasPi"); */ return meta; } @Override public void servoSetVelocity(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); servoData.velocity = servo.getVelocity(); } @Override public void servoSetAcceleration(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); servoData.acceleration = servo.getAcceleration(); } public List<PinDefinition> getPinList() { List<PinDefinition> list = new ArrayList<PinDefinition>(pinIndex.values()); pinMap = new TreeMap<String, PinDefinition>(); pinIndex = new TreeMap<Integer, PinDefinition>(); List<PinDefinition> pinList = new ArrayList<PinDefinition>(); for (int i = 0; i < 15; ++i) { PinDefinition pindef = new PinDefinition(); // begin wacky pin def logic String pinName = String.format("D%d", i); pindef.setName(pinName); pindef.setRx(false); pindef.setDigital(true); pindef.setAnalog(true); pindef.setDigital(true); pindef.canWrite(true); pindef.setPwm(true); pindef.setAddress(i); pinIndex.put(i, pindef); pinMap.put(pinName, pindef); pinList.add(pindef); } return list; } /* * @Override public boolean isAttached(String name) { return (controller != * null && controller.getName().equals(name) || servoMap.containsKey(name)); } */ @Override public boolean isAttached(Attachable instance) { if (controller != null && controller.getName().equals(instance.getName())) { return isAttached; } ; return false; } @Override public void stopService() { if (!isAttached(controller)){ detachI2CController(controller); } super.stopService(); // stop inbox and outbox } @Override public void setDeviceBus(String deviceBus) { if (isAttached) { log.error(String.format("Already attached to %s, use detach(%s) first", this.controllerName)); return; } this.deviceBus = deviceBus; broadcastState(); } @Override public void setDeviceAddress(String deviceAddress) { if (isAttached) { log.error(String.format("Already attached to %s, use detach(%s) first", this.controllerName)); return; } this.deviceAddress = deviceAddress; broadcastState(); } // This section contains all the old depreciated methods @Deprecated // use attach(ServoControl servo) void servoAttach(ServoControl device, Object... conf) { ServoControl servo = (ServoControl) device; // should initial pos be a requirement ? // This will fail because the pin data has not yet been set in Servo // servoNameToPin.put(servo.getName(), servo.getPin()); String servoName = servo.getName(); ServoData servoData = new ServoData(); servoData.pin = (int) conf[0]; servoMap.put(servoName, servoData); invoke("publishAttachedDevice", servoName); } @Deprecated // use attach(String controllerName, String deviceBus, String // deviceAddress) public void setController(String controllerName, String deviceBus, String deviceAddress) { attach(controllerName, deviceBus, deviceAddress); } @Deprecated // use attach(I2CController controller) public void setController(I2CController controller) { try { attach(controller); } catch (Exception e) { log.error("setController / attach throw", e); } } @Deprecated // use attach(I2CController controller) public void setController(I2CController controller, String deviceBus, String deviceAddress) { attach(controller, deviceBus, deviceAddress); } // This section contains all the new attach logic @Override public void attach(String service) throws Exception { attach((Attachable) Runtime.getService(service)); } @Override public void attach(Attachable service) throws Exception { if (I2CController.class.isAssignableFrom(service.getClass())) { attachI2CController((I2CController) service); return; } if (ServoControl.class.isAssignableFrom(service.getClass())) { attachServoControl((ServoControl) service); return; } } public void attach(String controllerName, String deviceBus, String deviceAddress) { attach((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress); } public void attach(I2CController controller, String deviceBus, String deviceAddress) { if (isAttached && this.controller != controller) { log.error(String.format("Already attached to %s, use detach(%s) first", this.controllerName)); } controllerName = controller.getName(); log.info(String.format("%s attach %s", getName(), controllerName)); this.deviceBus = deviceBus; this.deviceAddress = deviceAddress; attachI2CController(controller); isAttached = true; broadcastState(); } public void attachI2CController(I2CController controller) { if (isAttached(controller)) return; if (this.controllerName != controller.getName()) { log.error(String.format("Trying to attached to %s, but already attached to (%s)", controller.getName(), this.controllerName)); return; } this.controller = controller; isAttached = true; controller.attachI2CControl(this); log.info(String.format("Attached %s device on bus: %s address %s", controllerName, deviceBus, deviceAddress)); broadcastState(); } @Override public void attach(ServoControl servo, int pin) throws Exception { servo.setPin(pin); attachServoControl(servo); } public void attachServoControl(ServoControl servo) throws Exception { if (isAttachedServoControl(servo)) { log.info("servo {} already attached", servo.getName()); return; } ServoData servoData = new ServoData(); servoData.pin = servo.getPin(); servoData.targetOutput = servo.getTargetOutput(); servoData.velocity = servo.getVelocity(); servoData.isEnergized = true; servoMap.put(servo.getName(), servoData); servo.attachServoController(this); } // This section contains all the new detach logic // TODO: This default code could be in Attachable @Override public void detach(String service) { detach((Attachable) Runtime.getService(service)); } @Override public void detach(Attachable service) { if (I2CController.class.isAssignableFrom(service.getClass())) { detachI2CController((I2CController) service); return; } if (ServoControl.class.isAssignableFrom(service.getClass())) { try { servoDetachPin((ServoControl) service); detachServoControl((ServoControl) service); } catch (Exception e) { // TODO Auto-generated catch block); log.error("setController / attach throw", e); } return; } } @Override public void detachI2CController(I2CController controller) { if (!isAttached(controller)) return; stopPwm(); // stop pwm generation controller.detachI2CControl(this); isAttached = false; broadcastState(); } public void detachServoControl(ServoControl servo) throws Exception { if (servoMap.containsKey(servo)) { servoMap.remove(servo.getName()); servo.detachServoController(this); } } // This section contains all the methods used to query / show all attached // methods public boolean isAttachedServoControl(ServoControl servo) { return servoMap.containsKey(servo.getName()); } /** * Returns all the currently attached services TODO Add the list of attached * motors */ @Override public Set<String> getAttached() { HashSet<String> ret = new HashSet<String>(); if (controller != null && isAttached) { ret.add(controller.getName()); } ret.addAll(servoMap.keySet()); return ret; } @Override public String getDeviceBus() { return this.deviceBus; } @Override public String getDeviceAddress() { return this.deviceAddress; } }
package org.nschmidt.ldparteditor.data; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow; import org.nschmidt.ldparteditor.text.StringHelper; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; public class HistoryManager { private DatFile df; private boolean hasNoThread = true; private final AtomicBoolean isRunning = new AtomicBoolean(true); private final AtomicInteger action = new AtomicInteger(0); private final ProgressMonitorDialog[] m = new ProgressMonitorDialog[1]; private final SynchronousQueue<Integer> sq = new SynchronousQueue<Integer>(); private final Lock lock = new ReentrantLock(); private Queue<Object[]> workQueue = new ConcurrentLinkedQueue<Object[]>(); public HistoryManager(DatFile df) { this.df = df; } public void pushHistory(String text, int selectionStart, int selectionEnd, GData[] data, boolean[] selectedData, Vertex[] selectedVertices, int topIndex) { if (df.isReadOnly()) return; if (hasNoThread) { hasNoThread = false; new Thread(new Runnable() { @Override public void run() { final int MAX_ITEM_COUNT = 100; // default is 100 boolean restoreWasScuccessful = false; int pointer = 0; int pointerMax = 0; final ArrayList<Integer> historySelectionStart = new ArrayList<Integer>(); final ArrayList<Integer> historySelectionEnd = new ArrayList<Integer>(); final ArrayList<Integer> historyTopIndex = new ArrayList<Integer>(); final ArrayList<int[]> historyText = new ArrayList<int[]>(); final ArrayList<boolean[]> historySelectedData = new ArrayList<boolean[]>(); final ArrayList<Vertex[]> historySelectedVertices = new ArrayList<Vertex[]>(); while (isRunning.get() && Editor3DWindow.getAlive().get()) { try { Object[] newEntry = workQueue.poll(); if (newEntry != null) { final int[] result; String text = (String) newEntry[0]; GData[] data = (GData[]) newEntry[3]; if (text != null) { result = StringHelper.compress(text); } else if (data != null) { StringBuilder sb = new StringBuilder(); int size = data.length - 1; if (size > 0) { final String ld = StringHelper.getLineDelimiter(); for (int i = 0; i < size; i++) { sb.append(data[i].toString()); sb.append(ld); } sb.append(data[size].toString()); } result = StringHelper.compress(sb.toString()); } else { // throw new AssertionError("There must be data to backup!"); //$NON-NLS-1$ continue; } NLogger.debug(getClass(), "Pointer : " + pointer); //$NON-NLS-1$ NLogger.debug(getClass(), "PointerMax: " + pointerMax); //$NON-NLS-1$ NLogger.debug(getClass(), "Item Count: " + historyText.size()); //$NON-NLS-1$ if (pointer != pointerMax) { // Delete old entries removeFromListAboveOrEqualIndex(historySelectionStart, pointer + 1); removeFromListAboveOrEqualIndex(historySelectionEnd, pointer + 1); removeFromListAboveOrEqualIndex(historySelectedData, pointer + 1); removeFromListAboveOrEqualIndex(historySelectedVertices, pointer + 1); removeFromListAboveOrEqualIndex(historyText, pointer + 1); removeFromListAboveOrEqualIndex(historyTopIndex, pointer + 1); pointerMax = pointer + 1; } // Dont store more than MAX_ITEM_COUNT undo/redo entries { final int item_count = historyText.size(); if (item_count > MAX_ITEM_COUNT) { int delta = item_count - MAX_ITEM_COUNT; removeFromListLessIndex(historySelectionStart, delta + 1); removeFromListLessIndex(historySelectionEnd, delta + 1); removeFromListLessIndex(historySelectedData, delta + 1); removeFromListLessIndex(historySelectedVertices, delta + 1); removeFromListLessIndex(historyText, delta + 1); removeFromListLessIndex(historyTopIndex, delta + 1); pointerMax = pointerMax - delta; if (pointer > MAX_ITEM_COUNT) { pointer = pointer - delta; } } } historySelectionStart.add((Integer) newEntry[1]); historySelectionEnd.add((Integer) newEntry[2]); historySelectedData.add((boolean[]) newEntry[4]); historySelectedVertices.add((Vertex[]) newEntry[5]); historyTopIndex.add((Integer) newEntry[6]); historyText.add(result); // 1. Cleanup duplicated text entries if (pointer > 0) { int pStart = historySelectionStart.get(pointer - 1); int[] previous = historyText.get(pointer - 1); if (previous.length == result.length) { boolean match = true; for (int i = 0; i < previous.length; i++) { int v1 = previous[i]; int v2 = result[i]; if (v1 != v2) { match = false; break; } } if (match && !Editor3DWindow.getWindow().isAddingSomething()) { if (pStart != -1) { if ((Integer) newEntry[2] == 0) { // Skip saving this entry since only the cursor was moved removeFromListAboveOrEqualIndex(historySelectionStart, pointer); removeFromListAboveOrEqualIndex(historySelectionEnd, pointer); removeFromListAboveOrEqualIndex(historySelectedData, pointer); removeFromListAboveOrEqualIndex(historySelectedVertices, pointer); removeFromListAboveOrEqualIndex(historyText, pointer); removeFromListAboveOrEqualIndex(historyTopIndex, pointer); } else { // Remove the previous entry, because it only contains a new text selection historySelectionStart.remove(pointer - 1); historySelectionEnd.remove(pointer - 1); historySelectedData.remove(pointer - 1); historySelectedVertices.remove(pointer - 1); historyTopIndex.remove(pointer - 1); historyText.remove(pointer - 1); } pointerMax pointer } } } } // FIXME 2. There is still more cleanup work to do pointerMax++; pointer++; NLogger.debug(getClass(), "Added undo/redo data"); //$NON-NLS-1$ if (workQueue.isEmpty()) Thread.sleep(100); } else { final int action2 = action.get(); int delta = 0; if (action2 > 0 && action2 < 3) { restoreWasScuccessful = false; boolean doRestore = false; switch (action2) { case 1: // Undo if (pointer > 0) { if (pointerMax == pointer && pointer > 1) pointer NLogger.debug(getClass(), "Requested undo. " + (pointer - 1) + ' ' + pointerMax); //$NON-NLS-1$ pointer delta = -1; doRestore = true; } break; case 2: // Redo if (pointer < pointerMax - 1 && pointer + 1 < historySelectionStart.size()) { NLogger.debug(getClass(), "Requested redo. " + (pointer + 1) + ' ' + pointerMax); //$NON-NLS-1$ pointer++; delta = 1; doRestore = true; } break; } if (doRestore) { df.getVertexManager().setSkipSyncWithTextEditor(true); final boolean openTextEditor = historySelectionStart.get(pointer) != -1; boolean hasTextEditor = false; for (EditorTextWindow w : Project.getOpenTextWindows()) { for (final CTabItem t : w.getTabFolder().getItems()) { final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null && txtDat.equals(df)) { hasTextEditor = true; break; } } if (hasTextEditor) break; } while (!hasTextEditor && (pointer + delta) > -1 && (pointer + delta) < historySelectionStart.size() && historySelectionStart.get(pointer) != -1 && pointer > 0 && pointer < pointerMax - 1) { pointer += delta; } int[] text = historyText.get(pointer); final int pointer2 = pointer; NLogger.debug(getClass(), "Waiting for monitor..."); //$NON-NLS-1$ sq.put(10); if (m[0] == null || m[0].getShell() == null) { NLogger.error(getClass(), "Monitor creation failed!"); //$NON-NLS-1$ action.set(0); hasNoThread = true; return; } NLogger.debug(getClass(), "Accepted monitor."); //$NON-NLS-1$ final String decompressed = StringHelper.decompress(text); Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { sq.put(20); } catch (InterruptedException e) { } GDataCSG.resetCSG(); GDataCSG.forceRecompile(); Project.getUnsavedFiles().add(df); df.setText(decompressed); m[0].getShell().redraw(); m[0].getShell().update(); m[0].getShell().getDisplay().readAndDispatch(); df.parseForData(false); try { sq.put(60); } catch (InterruptedException e) { } m[0].getShell().redraw(); m[0].getShell().update(); m[0].getShell().getDisplay().readAndDispatch(); boolean hasTextEditor = false; try { for (EditorTextWindow w : Project.getOpenTextWindows()) { for (final CTabItem t : w.getTabFolder().getItems()) { final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null && txtDat.equals(df)) { int ti = ((CompositeTab) t).getTextComposite().getTopIndex(); Point r = ((CompositeTab) t).getTextComposite().getSelectionRange(); if (openTextEditor) { r.x = historySelectionStart.get(pointer2); r.y = historySelectionEnd.get(pointer2); ti = historyTopIndex.get(pointer2); } ((CompositeTab) t).getState().setSync(true); ((CompositeTab) t).getTextComposite().setText(decompressed); ((CompositeTab) t).getTextComposite().setTopIndex(ti); try { ((CompositeTab) t).getTextComposite().setSelectionRange(r.x, r.y); } catch (IllegalArgumentException consumed) {} ((CompositeTab) t).getTextComposite().redraw(); ((CompositeTab) t).getControl().redraw(); ((CompositeTab) t).getTextComposite().update(); ((CompositeTab) t).getControl().update(); ((CompositeTab) t).getState().setSync(false); hasTextEditor = true; break; } } if (hasTextEditor) break; } } catch (Exception undoRedoException) { // We want to know what can go wrong here // because it SHOULD be avoided!! switch (action2) { case 1: NLogger.error(getClass(), "Undo failed."); //$NON-NLS-1$ break; case 2: NLogger.error(getClass(), "Redo failed."); //$NON-NLS-1$ break; default: // Can't happen break; } NLogger.error(getClass(), undoRedoException); } final VertexManager vm = df.getVertexManager(); vm.clearSelection2(); final Vertex[] verts = historySelectedVertices.get(pointer2); if (verts != null) { for (Vertex vertex : verts) { vm.getSelectedVertices().add(vertex); } } boolean[] selection = historySelectedData.get(pointer2); if (selection != null) { int i = 0; final HashBiMap<Integer, GData> map = df.getDrawPerLine_NOCLONE(); TreeSet<Integer> ts = new TreeSet<Integer>(map.keySet()); for (Integer key : ts) { if (selection[i]) { GData gd = map.getValue(key); vm.getSelectedData().add(gd); switch (gd.type()) { case 1: vm.getSelectedSubfiles().add((GData1) gd); break; case 2: vm.getSelectedLines().add((GData2) gd); break; case 3: vm.getSelectedTriangles().add((GData3) gd); break; case 4: vm.getSelectedQuads().add((GData4) gd); break; case 5: vm.getSelectedCondlines().add((GData5) gd); break; default: break; } } i++; } ThreadsafeHashMap<GData, Set<VertexInfo>> llv = vm.getLineLinkedToVertices(); for (GData1 g1 : vm.getSelectedSubfiles()) { final Set<VertexInfo> vis = llv.get(g1); if (vis != null) { for (VertexInfo vi : vis) { vm.getSelectedVertices().add(vi.vertex); GData gd = vi.getLinkedData(); vm.getSelectedData().add(gd); switch (gd.type()) { case 2: vm.getSelectedLines().add((GData2) gd); break; case 3: vm.getSelectedTriangles().add((GData3) gd); break; case 4: vm.getSelectedQuads().add((GData4) gd); break; case 5: vm.getSelectedCondlines().add((GData5) gd); break; default: break; } } } } } vm.updateUnsavedStatus(); // Never ever call "vm.setModified_NoSync();" here. NEVER delete the following lines. vm.setModified(false, false); vm.setUpdated(true); vm.setSkipSyncWithTextEditor(false); Editor3DWindow.getWindow().updateTree_unsavedEntries(); try { sq.put(10); } catch (InterruptedException e) { } } }); } action.set(0); restoreWasScuccessful = true; } else { restoreWasScuccessful = true; if (workQueue.isEmpty()) Thread.sleep(100); } } } catch (InterruptedException e) { // We want to know what can go wrong here // because it SHOULD be avoided!! NLogger.error(getClass(), "The HistoryManager cycle was interruped [InterruptedException]! :("); //$NON-NLS-1$ NLogger.error(getClass(), e); } catch (Exception e) { NLogger.error(getClass(), "The HistoryManager cycle was throwing an exception :("); //$NON-NLS-1$ NLogger.error(getClass(), e); } if (!restoreWasScuccessful) { action.set(0); } restoreWasScuccessful = false; } } }).start(); } while (!workQueue.offer(new Object[]{text, selectionStart, selectionEnd, data, selectedData, selectedVertices, topIndex})) { try { Thread.sleep(100); } catch (InterruptedException e) {} } } public void deleteHistory() { isRunning.set(false); } public void undo(final Shell sh) { if (lock.tryLock()) { try { action(1, sh); } finally { lock.unlock(); } } else { NLogger.debug(getClass(), "Undo was skipped due to synchronisation."); //$NON-NLS-1$ } } public void redo(final Shell sh) { if (lock.tryLock()) { try { action(2, sh); } finally { lock.unlock(); } } else { NLogger.debug(getClass(), "Redo was skipped due to synchronisation."); //$NON-NLS-1$ } } private void action(final int mode, final Shell sh) { if (df.isReadOnly() || !df.getVertexManager().isUpdated() && WorkbenchManager.getUserSettingState().getSyncWithTextEditor().get()) return; BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { @Override public void run() { try { final ProgressMonitorDialog mon = new ProgressMonitorDialog(sh == null ? Editor3DWindow.getWindow().getShell() : sh); mon.run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (action.get() == 0) { action.set(mode); } m[0] = mon; NLogger.debug(getClass(), "Provided Monitor..."); //$NON-NLS-1$ monitor.beginTask(I18n.E3D_LoadingData, 100); while (action.get() > 0) { Integer inc = sq.poll(1000, TimeUnit.MILLISECONDS); if (inc != null) { monitor.worked(inc); NLogger.debug(getClass(), "Polled progress info. (" + inc + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } else { NLogger.debug(getClass(), "Progress info has timed out."); //$NON-NLS-1$ } } } catch (Exception ex) { // We want to know what can go wrong here // because it SHOULD be avoided!! switch (mode) { case 1: NLogger.error(getClass(), "Undo failed within the ProgressMonitor.run() call."); //$NON-NLS-1$ break; case 2: NLogger.error(getClass(), "Redo failed within the ProgressMonitor.run() call."); //$NON-NLS-1$ break; default: // Can't happen break; } NLogger.error(getClass(), ex); } } }); } catch (Exception undoRedoException) { // We want to know what can go wrong here // because it SHOULD be avoided!! switch (mode) { case 1: NLogger.error(getClass(), "Undo failed while the ProgressMonitor was shown."); //$NON-NLS-1$ break; case 2: NLogger.error(getClass(), "Redo failed while the ProgressMonitor was shown."); //$NON-NLS-1$ break; default: // Can't happen break; } NLogger.error(getClass(), undoRedoException); } } }); df.getVertexManager().setSelectedBgPicture(null); df.getVertexManager().setSelectedBgPictureIndex(0); Editor3DWindow.getWindow().updateBgPictureTab(); NLogger.debug(getClass(), "done."); //$NON-NLS-1$ } private void removeFromListAboveOrEqualIndex(List<?> l, int i) { i for (int j = l.size() - 1; j > i; j l.remove(j); } } private void removeFromListLessIndex(List<?> l, int i) { i for (int j = i - 1; j > -1; j l.remove(j); } } public void setDatFile(DatFile df) { this.df = df; } public Lock getLock() { return lock; } }
package org.ojalgo.optimisation; import static org.ojalgo.constant.BigMath.*; import static org.ojalgo.function.BigFunction.*; import java.math.BigDecimal; import java.util.*; import java.util.function.Function; import java.util.stream.Stream; import org.ojalgo.ProgrammingError; import org.ojalgo.array.Array1D; import org.ojalgo.array.Primitive64Array; import org.ojalgo.constant.BigMath; import org.ojalgo.netio.BasicLogger; import org.ojalgo.netio.BasicLogger.Printer; import org.ojalgo.optimisation.convex.ConvexSolver; import org.ojalgo.optimisation.integer.IntegerSolver; import org.ojalgo.optimisation.linear.LinearSolver; import org.ojalgo.structure.Access1D; import org.ojalgo.structure.Structure1D.IntIndex; import org.ojalgo.structure.Structure2D.IntRowColumn; import org.ojalgo.type.context.NumberContext; /** * <p> * Lets you construct optimisation problems by combining (mathematical) expressions in terms of variables. * Each expression or variable can be a constraint and/or contribute to the objective function. An expression * or variable is turned into a constraint by setting a lower and/or upper limit. Use * {@linkplain Expression#lower(Number)}, {@linkplain Expression#upper(Number)} or * {@linkplain Expression#level(Number)}. An expression or variable is made part of (contributing to) the * objective function by setting a contribution weight. Use {@linkplain Expression#weight(Number)}. * </p> * <p> * You may think of variables as simple (the simplest possible) expressions, and of expressions as weighted * combinations of variables. They are both model entities and it is as such they can be turned into * constraints and set to contribute to the objective function. Alternatively you may choose to disregard the * fact that variables are model entities and simply treat them as index values. In this case everything * (constraints and objective) needs to be defined using expressions. * </p> * <p> * Basic instructions: * </p> * <ol> * <li>Define (create) a set of variables. Set contribution weights and lower/upper limits as needed.</li> * <li>Create a model using that set of variables.</li> * <li>Add expressions to the model. The model is the expression factory. Set contribution weights and * lower/upper limits as needed.</li> * <li>Solve your problem using either minimise() or maximise()</li> * </ol> * <p> * When using this class you do not need to worry about which solver will actually be used. The docs of the * various solvers describe requirements on input formats and similar. This is handled for you and should * absolutely NOT be considered here! Compared to using the various solvers directly this class actually does * something for you: * </p> * <ol> * <li>You can model your problems without worrying about specific solver requirements.</li> * <li>It knows which solver to use.</li> * <li>It knows how to use that solver.</li> * <li>It has a presolver that tries to simplify the problem before invoking a solver (sometimes it turns out * there is no need to invoke a solver at all).</li> * <li>When/if needed it scales problem parameters, before creating solver specific data structures, to * minimize numerical problems in the solvers.</li> * <li>It's the only way to access the integer solver.</li> * </ol> * <p> * Different solvers can be used, and ojAlgo comes with collection built in. The default built-in solvers can * handle anythimng you can model with a couple of restrictions: * </p> * <ul> * <li>No quadratic constraints (The plan is that future versions should not have this limitation.)</li> * <li>If you use quadratic expressions make sure they're convex. This is most likely a requirement even with * 3:d party solvers.</li> * </ul> * * @author apete */ public final class ExpressionsBasedModel extends AbstractModel<GenericSolver> { public static abstract class Integration<S extends Optimisation.Solver> implements Optimisation.Integration<ExpressionsBasedModel, S> { /** * @see org.ojalgo.optimisation.Optimisation.Integration#extractSolverState(org.ojalgo.optimisation.Optimisation.Model) */ public final Result extractSolverState(final ExpressionsBasedModel model) { return this.toSolverState(model.getVariableValues(), model); } public Result toModelState(final Result solverState, final ExpressionsBasedModel model) { final int numbVariables = model.countVariables(); if (this.isSolutionMapped()) { final List<Variable> freeVariables = model.getFreeVariables(); final Set<IntIndex> fixedVariables = model.getFixedVariables(); if (solverState.count() != freeVariables.size()) { throw new IllegalStateException(); } final Primitive64Array modelSolution = Primitive64Array.make(numbVariables); for (final IntIndex fixedIndex : fixedVariables) { modelSolution.set(fixedIndex.index, model.getVariable(fixedIndex.index).getValue()); } for (int f = 0; f < freeVariables.size(); f++) { final int freeIndex = model.indexOf(freeVariables.get(f)); modelSolution.set(freeIndex, solverState.doubleValue(f)); } return new Result(solverState.getState(), modelSolution); } else { if (solverState.count() != numbVariables) { throw new IllegalStateException(); } return solverState; } } public Result toSolverState(final Result modelState, final ExpressionsBasedModel model) { if (this.isSolutionMapped()) { final List<Variable> tmpFreeVariables = model.getFreeVariables(); final int numbFreeVars = tmpFreeVariables.size(); final Primitive64Array solverSolution = Primitive64Array.make(numbFreeVars); for (int i = 0; i < numbFreeVars; i++) { final Variable variable = tmpFreeVariables.get(i); final int modelIndex = model.indexOf(variable); solverSolution.set(i, modelState.doubleValue(modelIndex)); } return new Result(modelState.getState(), solverSolution); } else { return modelState; } } /** * @param model * @param variable * @return The index with which one can reference parameters related to this variable in the solver. */ protected int getIndexInSolver(final ExpressionsBasedModel model, final Variable variable) { return model.indexOfFreeVariable(variable); } /** * @return true if the set of variables present in the solver is not precisely the same as in the * model. If fixed variables are omitted or if variables are split into a positive and * negative part, then this method must return true */ protected abstract boolean isSolutionMapped(); } public static final class Intermediate implements Optimisation.Solver { private boolean myInPlaceUpdatesOK = true; private transient ExpressionsBasedModel.Integration<?> myIntegration = null; private final ExpressionsBasedModel myModel; private transient Optimisation.Solver mySolver = null; Intermediate(final ExpressionsBasedModel model) { super(); myModel = model; myIntegration = null; mySolver = null; } /** * Force re-generation of any cached/transient data */ public void dispose() { Solver.super.dispose(); if (mySolver != null) { mySolver.dispose(); mySolver = null; } myIntegration = null; } public ExpressionsBasedModel getModel() { return myModel; } public Variable getVariable(final int globalIndex) { return myModel.getVariable(globalIndex); } public Variable getVariable(final IntIndex globalIndex) { return myModel.getVariable(globalIndex); } public Optimisation.Result solve(final Optimisation.Result candidate) { if (mySolver == null) { myModel.presolve(); } if (myModel.isInfeasible()) { final Optimisation.Result solution = candidate != null ? candidate : myModel.getVariableValues(); return new Optimisation.Result(State.INFEASIBLE, solution); } else if (myModel.isUnbounded()) { if ((candidate != null) && myModel.validate(candidate)) { return new Optimisation.Result(State.UNBOUNDED, candidate); } final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.UNBOUNDED, derivedSolution); } } else if (myModel.isFixed()) { final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.DISTINCT, derivedSolution); } else { return new Optimisation.Result(State.INVALID, derivedSolution); } } final ExpressionsBasedModel.Integration<?> integration = this.getIntegration(); final Optimisation.Solver solver = this.getSolver(); Optimisation.Result retVal = candidate != null ? candidate : myModel.getVariableValues(); retVal = integration.toSolverState(retVal, myModel); retVal = solver.solve(retVal); retVal = integration.toModelState(retVal, myModel); return retVal; } public void update(final int index) { this.update(myModel.getVariable(index)); } public void update(final IntIndex index) { this.update(myModel.getVariable(index)); } public void update(final Variable variable) { if (myInPlaceUpdatesOK && (mySolver != null) && (mySolver instanceof UpdatableSolver) && variable.isFixed()) { final UpdatableSolver updatableSolver = (UpdatableSolver) mySolver; final int indexInSolver = this.getIntegration().getIndexInSolver(myModel, variable); final double fixedValue = variable.getValue().doubleValue(); if (updatableSolver.fixVariable(indexInSolver, fixedValue)) { // Solver updated in-place return; } else { myInPlaceUpdatesOK = false; } } // Solver will be re-generated mySolver = null; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { return myModel.validate(solution, appender); } public boolean validate(final Result solution) { return myModel.validate(solution); } ExpressionsBasedModel.Integration<?> getIntegration() { if (myIntegration == null) { myIntegration = myModel.getIntegration(); } return myIntegration; } Optimisation.Solver getSolver() { if (mySolver == null) { mySolver = this.getIntegration().build(myModel); } return mySolver; } } public static abstract class Presolver extends Simplifier<Expression, Presolver> { protected Presolver(final int executionOrder) { super(executionOrder); } /** * @param expression * @param fixedVariables * @param fixedValue TODO * @param variableResolver TODO * @param precision TODO * @return True if any model entity was modified so that a re-run of the presolvers is necessary - * typically when/if a variable was fixed. */ public abstract boolean simplify(Expression expression, Set<IntIndex> fixedVariables, BigDecimal fixedValue, Function<IntIndex, Variable> variableResolver, NumberContext precision); @Override boolean isApplicable(final Expression target) { return target.isConstraint() && !target.isInfeasible() && !target.isRedundant() && (target.countQuadraticFactors() == 0); } } static abstract class Simplifier<ME extends ModelEntity<?>, S extends Simplifier<?, ?>> implements Comparable<S> { private final int myExecutionOrder; private final UUID myUUID = UUID.randomUUID(); Simplifier(final int executionOrder) { super(); myExecutionOrder = executionOrder; } public final int compareTo(final S reference) { return Integer.compare(myExecutionOrder, reference.getExecutionOrder()); } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Simplifier)) { return false; } final Simplifier<?, ?> other = (Simplifier<?, ?>) obj; if (myUUID == null) { if (other.myUUID != null) { return false; } } else if (!myUUID.equals(other.myUUID)) { return false; } return true; } @Override public final int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((myUUID == null) ? 0 : myUUID.hashCode()); return result; } final int getExecutionOrder() { return myExecutionOrder; } abstract boolean isApplicable(final ME target); } static abstract class VariableAnalyser extends Simplifier<Variable, VariableAnalyser> { protected VariableAnalyser(final int executionOrder) { super(executionOrder); } public abstract boolean simplify(Variable variable, ExpressionsBasedModel model); @Override boolean isApplicable(final Variable target) { return true; } } private static final ConvexSolver.ModelIntegration CONVEX_INTEGRATION = new ConvexSolver.ModelIntegration(); private static final IntegerSolver.ModelIntegration INTEGER_INTEGRATION = new IntegerSolver.ModelIntegration(); private static final List<ExpressionsBasedModel.Integration<?>> INTEGRATIONS = new ArrayList<>(); private static final LinearSolver.ModelIntegration LINEAR_INTEGRATION = new LinearSolver.ModelIntegration(); private static final String NEW_LINE = "\n"; private static final String OBJ_FUNC_AS_CONSTR_KEY = UUID.randomUUID().toString(); private static final String OBJECTIVE = "Generated/Aggregated Objective"; private static final TreeSet<Presolver> PRESOLVERS = new TreeSet<>(); private static final String START_END = " static { ExpressionsBasedModel.addPresolver(Presolvers.ZERO_ONE_TWO); ExpressionsBasedModel.addPresolver(Presolvers.OPPOSITE_SIGN); // ExpressionsBasedModel.addPresolver(Presolvers.BINARY_VALUE); // ExpressionsBasedModel.addPresolver(Presolvers.BIGSTUFF); } public static boolean addIntegration(final Integration<?> integration) { return INTEGRATIONS.add(integration); } public static boolean addPresolver(final Presolver presolver) { return PRESOLVERS.add(presolver); } public static void clearIntegrations() { INTEGRATIONS.clear(); } public static void clearPresolvers() { PRESOLVERS.clear(); } public static boolean removeIntegration(final Integration<?> integration) { return INTEGRATIONS.remove(integration); } public static boolean removePresolver(final Presolver presolver) { return PRESOLVERS.remove(presolver); } private final HashMap<String, Expression> myExpressions = new HashMap<>(); private final HashSet<IntIndex> myFixedVariables = new HashSet<>(); private transient int[] myFreeIndices = null; private final List<Variable> myFreeVariables = new ArrayList<>(); private transient int[] myIntegerIndices = null; private final List<Variable> myIntegerVariables = new ArrayList<>(); private transient int[] myNegativeIndices = null; private final List<Variable> myNegativeVariables = new ArrayList<>(); private transient int[] myPositiveIndices = null; private final List<Variable> myPositiveVariables = new ArrayList<>(); private final ArrayList<Variable> myVariables = new ArrayList<>(); private final boolean myWorkCopy; public ExpressionsBasedModel() { super(); myWorkCopy = false; } public ExpressionsBasedModel(final Collection<? extends Variable> variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; } public ExpressionsBasedModel(final Optimisation.Options someOptions) { super(someOptions); myWorkCopy = false; } public ExpressionsBasedModel(final Variable... variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; } ExpressionsBasedModel(final ExpressionsBasedModel modelToCopy, final boolean workCopy, final boolean allEntities) { super(modelToCopy.options); this.setMinimisation(modelToCopy.isMinimisation()); for (final Variable tmpVariable : modelToCopy.getVariables()) { this.addVariable(tmpVariable.copy()); } for (final Expression tmpExpression : modelToCopy.getExpressions()) { if (allEntities || tmpExpression.isObjective() || (tmpExpression.isConstraint() && !tmpExpression.isRedundant())) { myExpressions.put(tmpExpression.getName(), tmpExpression.copy(this, !workCopy)); } else { // BasicLogger.DEBUG.println("Discarding expression: {}", tmpExpression); } } myWorkCopy = workCopy; } public Expression addExpression() { return this.addExpression("EXPR" + myExpressions.size()); } public Expression addExpression(final String name) { final Expression retVal = new Expression(name, this); myExpressions.put(name, retVal); return retVal; } /** * Creates a special ordered set (SOS) presolver instance and links that to the supplied expression. * When/if the presolver concludes that the SOS "constraints" are not possible the linked expression is * marked as infeasible. */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int type, final Expression linkedTo) { if (type <= 0) { throw new ProgrammingError("Invalid SOS type!"); } if (!linkedTo.isConstraint()) { throw new ProgrammingError("The linked to expression needs to be a constraint!"); } final IntIndex[] sequence = new IntIndex[orderedSet.size()]; int index = 0; for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null)) { throw new ProgrammingError("Variables must be already inserted in the model!"); } else { sequence[index++] = variable.getIndex(); } } ExpressionsBasedModel.addPresolver(new SpecialOrderedSet(sequence, type, linkedTo)); } /** * Calling this method will create 2 things: * <ol> * <li>A simple expression meassuring the sum of the (binary) variable values (the number of binary * variables that are "ON"). The upper, and optionally lower, limits are set as defined by the * <code>max</code> and <code>min</code> parameter values.</li> * <li>A custom presolver (specific to this SOS) to be used by the MIP solver. This presolver help to keep * track of which combinations of variable values or feasible, and is the only thing that enforces the * order.</li> * </ol> * * @param orderedSet The set members in correct order. Each of these variables must be binary. * @param min The minimum number of binary varibales in the set that must be "ON" (Set this to 0 if there * is no minimum.) * @param max The SOS type or maximum number of binary varibales in the set that may be "ON" */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int min, final int max) { if ((max <= 0) || (min > max)) { throw new ProgrammingError("Invalid min/max number of ON variables!"); } final String name = "SOS" + max + "-" + orderedSet.toString(); final Expression expression = this.addExpression(name); for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null) || !variable.isBinary()) { throw new ProgrammingError("Variables must be binary and already inserted in the model!"); } else { expression.set(variable.getIndex(), ONE); } } expression.upper(BigDecimal.valueOf(max)); if (min > 0) { expression.lower(BigDecimal.valueOf(min)); } this.addSpecialOrderedSet(orderedSet, max, expression); } public Variable addVariable() { return this.addVariable("X" + myVariables.size()); } public Variable addVariable(final String name) { final Variable retVal = new Variable(name); this.addVariable(retVal); return retVal; } public void addVariable(final Variable variable) { if (myWorkCopy) { throw new IllegalStateException("This model is a work copy - its set of variables cannot be modified!"); } else { myVariables.add(variable); variable.setIndex(new IntIndex(myVariables.size() - 1)); } } public void addVariables(final Collection<? extends Variable> variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } public void addVariables(final Variable[] variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } /** * @return A stream of variables that are constraints and not fixed */ public Stream<Variable> bounds() { return this.variables().filter((final Variable v) -> v.isConstraint()); } /** * @return A prefiltered stream of expressions that are constraints and have not been markes as redundant */ public Stream<Expression> constraints() { return myExpressions.values().stream().filter(c -> c.isConstraint() && !c.isRedundant()); } public ExpressionsBasedModel copy() { return new ExpressionsBasedModel(this, false, true); } public int countExpressions() { return myExpressions.size(); } public int countVariables() { return myVariables.size(); } @Override public void dispose() { for (final Expression tmpExprerssion : myExpressions.values()) { tmpExprerssion.destroy(); } myExpressions.clear(); for (final Variable tmpVariable : myVariables) { tmpVariable.destroy(); } myVariables.clear(); myFixedVariables.clear(); myFreeVariables.clear(); myFreeIndices = null; myPositiveVariables.clear(); myPositiveIndices = null; myNegativeVariables.clear(); myNegativeIndices = null; myIntegerVariables.clear(); myIntegerIndices = null; } public Expression generateCut(final Expression constraint, final Optimisation.Result solution) { return null; } public Expression getExpression(final String name) { return myExpressions.get(name); } public Collection<Expression> getExpressions() { return Collections.unmodifiableCollection(myExpressions.values()); } public Set<IntIndex> getFixedVariables() { myFixedVariables.clear(); for (final Variable tmpVar : myVariables) { if (tmpVar.isFixed()) { myFixedVariables.add(tmpVar.getIndex()); } } return Collections.unmodifiableSet(myFixedVariables); } /** * @return A list of the variables that are not fixed at a specific value */ public List<Variable> getFreeVariables() { if (myFreeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myFreeVariables); } /** * @return A list of the variables that are not fixed at a specific value and are marked as integer * variables */ public List<Variable> getIntegerVariables() { if (myIntegerIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myIntegerVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include negative * values */ public List<Variable> getNegativeVariables() { if (myNegativeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myNegativeVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include positive * values and/or zero */ public List<Variable> getPositiveVariables() { if (myPositiveIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myPositiveVariables); } public Variable getVariable(final int index) { return myVariables.get(index); } public Variable getVariable(final IntIndex index) { return myVariables.get(index.index); } public List<Variable> getVariables() { return Collections.unmodifiableList(myVariables); } public Optimisation.Result getVariableValues() { return this.getVariableValues(options.feasibility); } /** * Null variable values are replaced with 0.0. If any variable value is null the state is set to * INFEASIBLE even if zero would actually be a feasible value. The objective function value is not * calculated for infeasible variable values. */ public Optimisation.Result getVariableValues(final NumberContext validationContext) { final int tmpNumberOfVariables = myVariables.size(); State retState = State.UNEXPLORED; double retValue = Double.NaN; final Array1D<BigDecimal> retSolution = Array1D.BIG.makeZero(tmpNumberOfVariables); boolean tmpAllVarsSomeInfo = true; for (int i = 0; i < tmpNumberOfVariables; i++) { final Variable tmpVariable = myVariables.get(i); if (tmpVariable.getValue() != null) { retSolution.set(i, tmpVariable.getValue()); } else { if (tmpVariable.isEqualityConstraint()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) { retSolution.set(i, DIVIDE.invoke(tmpVariable.getLowerLimit().add(tmpVariable.getUpperLimit()), TWO)); } else if (tmpVariable.isLowerLimitSet()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isUpperLimitSet()) { retSolution.set(i, tmpVariable.getUpperLimit()); } else { retSolution.set(i, ZERO); tmpAllVarsSomeInfo = false; // This var no info } } } if (tmpAllVarsSomeInfo) { if (this.validate(retSolution, validationContext)) { retState = State.FEASIBLE; retValue = this.objective().evaluate(retSolution).doubleValue(); } else { retState = State.APPROXIMATE; } } else { retState = State.INFEASIBLE; } return new Optimisation.Result(retState, retValue, retSolution); } public int indexOf(final Variable variable) { return variable.getIndex().index; } /** * @param globalIndex General, global, variable index * @return Local index among the free variables. -1 indicates the variable is not a positive variable. */ public int indexOfFreeVariable(final int globalIndex) { return myFreeIndices[globalIndex]; } public int indexOfFreeVariable(final IntIndex variableIndex) { return this.indexOfFreeVariable(variableIndex.index); } public int indexOfFreeVariable(final Variable variable) { return this.indexOfFreeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the integer variables. -1 indicates the variable is not an integer variable. */ public int indexOfIntegerVariable(final int globalIndex) { return myIntegerIndices[globalIndex]; } public int indexOfIntegerVariable(final IntIndex variableIndex) { return this.indexOfIntegerVariable(variableIndex.index); } public int indexOfIntegerVariable(final Variable variable) { return this.indexOfIntegerVariable(variable.getIndex().index); } /** * @param globalIndex General, global, variable index * @return Local index among the negative variables. -1 indicates the variable is not a negative variable. */ public int indexOfNegativeVariable(final int globalIndex) { return myNegativeIndices[globalIndex]; } public int indexOfNegativeVariable(final IntIndex variableIndex) { return this.indexOfNegativeVariable(variableIndex.index); } public int indexOfNegativeVariable(final Variable variable) { return this.indexOfNegativeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the positive variables. -1 indicates the variable is not a positive variable. */ public int indexOfPositiveVariable(final int globalIndex) { return myPositiveIndices[globalIndex]; } public int indexOfPositiveVariable(final IntIndex variableIndex) { return this.indexOfPositiveVariable(variableIndex.index); } public int indexOfPositiveVariable(final Variable variable) { return this.indexOfPositiveVariable(this.indexOf(variable)); } public boolean isAnyConstraintQuadratic() { boolean retVal = false; for (final Expression value : myExpressions.values()) { retVal |= (value.isAnyQuadraticFactorNonZero() && value.isConstraint() && !value.isRedundant()); } return retVal; } /** * Objective or any constraint has quadratic part. * * @deprecated v45 Use {@link #isAnyConstraintQuadratic()} or {@link #isAnyObjectiveQuadratic()} instead */ @Deprecated public boolean isAnyExpressionQuadratic() { boolean retVal = false; for (final Expression value : myExpressions.values()) { retVal |= value.isAnyQuadraticFactorNonZero() && (value.isConstraint() || value.isObjective()); } return retVal; } public boolean isAnyObjectiveQuadratic() { boolean retVal = false; for (final Expression value : myExpressions.values()) { retVal |= (value.isAnyQuadraticFactorNonZero() && value.isObjective()); } return retVal; } public boolean isAnyVariableFixed() { return myVariables.stream().anyMatch(v -> v.isFixed()); } public boolean isAnyVariableInteger() { boolean retVal = false; final int tmpLength = myVariables.size(); for (int i = 0; !retVal && (i < tmpLength); i++) { retVal |= myVariables.get(i).isInteger(); } return retVal; } public boolean isWorkCopy() { return myWorkCopy; } public void limitObjective(final BigDecimal lower, final BigDecimal upper) { Expression constrExpr = myExpressions.get(OBJ_FUNC_AS_CONSTR_KEY); if (constrExpr == null) { final Expression objExpr = this.objective(); if (!objExpr.isAnyQuadraticFactorNonZero()) { constrExpr = objExpr.copy(this, false); myExpressions.put(OBJ_FUNC_AS_CONSTR_KEY, constrExpr); } } if (constrExpr != null) { // int maxScale = 0; // for (final Entry<IntIndex, BigDecimal> entry : constrExpr.getLinearEntrySet()) { // maxScale = Math.max(maxScale, entry.getValue().scale()); // long gcd = -1L; // for (final Entry<IntIndex, BigDecimal> entry : constrExpr.getLinearEntrySet()) { // final long tmpLongValue = Math.abs(entry.getValue().setScale(maxScale).unscaledValue().longValue()); // if (gcd == -1L) { // gcd = tmpLongValue; // } else { // gcd = RationalNumber.gcd(gcd, tmpLongValue); // if (upper != null) { // final BigDecimal tmpSetScale = upper.setScale(maxScale, RoundingMode.FLOOR); // final long tmpLongValue = tmpSetScale.unscaledValue().longValue(); // upper = new BigDecimal(tmpLongValue).divide(new BigDecimal(gcd), maxScale, RoundingMode.FLOOR); constrExpr.lower(lower).upper(upper); } } public Optimisation.Result maximise() { this.setMaximisation(); return this.optimise(); } public Optimisation.Result minimise() { this.setMinimisation(); return this.optimise(); } public Expression objective() { final Expression retVal = new Expression(OBJECTIVE, this); Variable tmpVariable; for (int i = 0; i < myVariables.size(); i++) { tmpVariable = myVariables.get(i); if (tmpVariable.isObjective()) { retVal.set(i, tmpVariable.getContributionWeight()); } } BigDecimal tmpOldVal = null; BigDecimal tmpDiff = null; BigDecimal tmpNewVal = null; for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isObjective()) { final BigDecimal tmpContributionWeight = tmpExpression.getContributionWeight(); final boolean tmpNotOne = tmpContributionWeight.compareTo(ONE) != 0; // To avoid multiplication by 1.0 if (tmpExpression.isAnyLinearFactorNonZero()) { for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } if (tmpExpression.isAnyQuadraticFactorNonZero()) { for (final IntRowColumn tmpKey : tmpExpression.getQuadraticKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } } } return retVal; } /** * <p> * The general recommendation is to NOT call this method directly. Instead you should use/call * {@link #maximise()} or {@link #minimise()}. * </P> * <p> * The primary use case for this method is as a callback method for solvers that iteratively modifies the * model and solves at each iteration point. * </P> * <p> * With direct usage of this method: * </P> * <ul> * <li>Maximisation/Minimisation is undefined (you don't know which it is)</li> * <li>The solution is not written back to the model</li> * <li>The solution is not validated by the model</li> * </ul> */ public ExpressionsBasedModel.Intermediate prepare() { return new ExpressionsBasedModel.Intermediate(this); } public ExpressionsBasedModel relax(final boolean inPlace) { final ExpressionsBasedModel retVal = inPlace ? this : new ExpressionsBasedModel(this, true, true); for (final Variable tmpVariable : retVal.getVariables()) { tmpVariable.relax(); } return retVal; } public ExpressionsBasedModel simplify() { this.scanEntities(); this.presolve(); final ExpressionsBasedModel retVal = new ExpressionsBasedModel(this, true, false); return retVal; } /** * <p> * Most likely you should NOT have been using this method directly. Instead you should have used/called * {@link #maximise()} or {@link #minimise()}. * </P> * <p> * In case you believe it was correct to use this method, you should now use {@link #prepare()} and then * {@link Intermediate#solve(Optimisation.Result)} instead. * </P> * * @deprecated v46 */ @Deprecated public Optimisation.Result solve(final Optimisation.Result candidate) { return this.prepare().solve(candidate); } @Override public String toString() { final StringBuilder retVal = new StringBuilder(START_END); for (final Variable tmpVariable : myVariables) { tmpVariable.appendToString(retVal); retVal.append(NEW_LINE); } for (final Expression tmpExpression : myExpressions.values()) { // if ((tmpExpression.isConstraint() && !tmpExpression.isRedundant()) || tmpExpression.isObjective()) { tmpExpression.appendToString(retVal, this.getVariableValues()); retVal.append(NEW_LINE); } return retVal.append(START_END).toString(); } /** * This methods validtes model construction only. All the other validate(...) method validates the * solution (one way or another). * * @see org.ojalgo.optimisation.Optimisation.Model#validate() */ public boolean validate() { final Printer appender = options.logger_detailed ? options.logger_appender : BasicLogger.NULL; boolean retVal = true; for (final Variable tmpVariable : myVariables) { retVal &= tmpVariable.validate(appender); } for (final Expression tmpExpression : myExpressions.values()) { retVal &= tmpExpression.validate(appender); } return retVal; } public boolean validate(final Access1D<BigDecimal> solution) { final NumberContext context = options.feasibility; final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context) { final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context, final Printer appender) { ProgrammingError.throwIfNull(solution, context, appender); final int size = myVariables.size(); boolean retVal = size == solution.count(); for (int i = 0; retVal && (i < size); i++) { final Variable tmpVariable = myVariables.get(i); final BigDecimal value = solution.get(i); retVal &= tmpVariable.validate(value, context, appender); } if (retVal) { for (final Expression tmpExpression : myExpressions.values()) { final BigDecimal value = tmpExpression.evaluate(solution); retVal &= tmpExpression.validate(value, context, appender); } } return retVal; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { final NumberContext context = options.feasibility; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context) { final Result solution = this.getVariableValues(context); final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context, final Printer appender) { final Access1D<BigDecimal> solution = this.getVariableValues(context); return this.validate(solution, context, appender); } public boolean validate(final Printer appender) { final NumberContext context = options.feasibility; final Result solution = this.getVariableValues(context); return this.validate(solution, context, appender); } /** * @return A stream of variables that are not fixed */ public Stream<Variable> variables() { return myVariables.stream().filter((final Variable v) -> (!v.isEqualityConstraint())); } private void categoriseVariables() { final int tmpLength = myVariables.size(); myFreeVariables.clear(); myFreeIndices = new int[tmpLength]; Arrays.fill(myFreeIndices, -1); myPositiveVariables.clear(); myPositiveIndices = new int[tmpLength]; Arrays.fill(myPositiveIndices, -1); myNegativeVariables.clear(); myNegativeIndices = new int[tmpLength]; Arrays.fill(myNegativeIndices, -1); myIntegerVariables.clear(); myIntegerIndices = new int[tmpLength]; Arrays.fill(myIntegerIndices, -1); for (int i = 0; i < tmpLength; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { myFreeVariables.add(tmpVariable); myFreeIndices[i] = myFreeVariables.size() - 1; if (!tmpVariable.isUpperLimitSet() || (tmpVariable.getUpperLimit().signum() == 1)) { myPositiveVariables.add(tmpVariable); myPositiveIndices[i] = myPositiveVariables.size() - 1; } if (!tmpVariable.isLowerLimitSet() || (tmpVariable.getLowerLimit().signum() == -1)) { myNegativeVariables.add(tmpVariable); myNegativeIndices[i] = myNegativeVariables.size() - 1; } if (tmpVariable.isInteger()) { myIntegerVariables.add(tmpVariable); myIntegerIndices[i] = myIntegerVariables.size() - 1; } } } } private void scanEntities() { final Set<IntIndex> fixedVariables = Collections.emptySet(); final BigDecimal fixedValue = BigMath.ZERO; for (final Expression tmpExpression : myExpressions.values()) { Presolvers.LINEAR_OBJECTIVE.simplify(tmpExpression, fixedVariables, fixedValue, this::getVariable, options.feasibility); if (tmpExpression.isConstraint()) { Presolvers.ZERO_ONE_TWO.simplify(tmpExpression, fixedVariables, fixedValue, this::getVariable, options.feasibility); } } for (final Variable tmpVariable : myVariables) { Presolvers.FIXED_OR_UNBOUNDED.simplify(tmpVariable, this); } } Stream<Expression> expressions() { return myExpressions.values().stream(); } ExpressionsBasedModel.Integration<?> getIntegration() { ExpressionsBasedModel.Integration<?> retVal = null; for (final ExpressionsBasedModel.Integration<?> tmpIntegration : INTEGRATIONS) { if (tmpIntegration.isCapable(this)) { retVal = tmpIntegration; break; } } if (retVal == null) { if (this.isAnyVariableInteger()) { if (INTEGER_INTEGRATION.isCapable(this)) { retVal = INTEGER_INTEGRATION; } } else { if (CONVEX_INTEGRATION.isCapable(this)) { retVal = CONVEX_INTEGRATION; } else if (LINEAR_INTEGRATION.isCapable(this)) { retVal = LINEAR_INTEGRATION; } } } if (retVal == null) { throw new ProgrammingError("No solver integration available that can handle this model!"); } return retVal; } boolean isFixed() { return myVariables.stream().allMatch(v -> v.isFixed()); } boolean isInfeasible() { for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isInfeasible()) { return true; } } for (final Variable tmpVariable : myVariables) { if (tmpVariable.isInfeasible()) { return true; } } return false; } boolean isUnbounded() { return myVariables.stream().anyMatch(v -> v.isUnbounded()); } Optimisation.Result optimise() { if (PRESOLVERS.size() > 0) { this.scanEntities(); } Intermediate prepared = this.prepare(); final Optimisation.Result solver = prepared.solve(null); for (int i = 0, limit = myVariables.size(); i < limit; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { tmpVariable.setValue(options.solution.enforce(solver.get(i))); } } final Access1D<BigDecimal> retSolution = this.getVariableValues(); final Optimisation.State retState = solver.getState(); final double retValue = this.objective().evaluate(retSolution).doubleValue(); return new Optimisation.Result(retState, retValue, retSolution); } final void presolve() { myExpressions.values().forEach(expr -> expr.reset()); boolean needToRepeat = false; do { final Set<IntIndex> fixedVariables = this.getFixedVariables(); BigDecimal fixedValue; needToRepeat = false; for (final Expression expr : this.getExpressions()) { if (!needToRepeat && expr.isConstraint() && !expr.isInfeasible() && !expr.isRedundant() && (expr.countQuadraticFactors() == 0)) { fixedValue = options.solution.enforce(expr.calculateFixedValue(fixedVariables)); for (final Presolver presolver : PRESOLVERS) { if (!needToRepeat) { needToRepeat |= presolver.simplify(expr, fixedVariables, fixedValue, this::getVariable, options.feasibility); } } } } } while (needToRepeat); this.categoriseVariables(); } }
package org.opencms.ui.apps.search; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.FontOpenCms; import org.opencms.ui.I_CmsDialogContext; import org.opencms.ui.I_CmsDialogContext.ContextType; import org.opencms.ui.apps.A_CmsWorkplaceApp; import org.opencms.ui.apps.CmsAppWorkplaceUi; import org.opencms.ui.apps.CmsFileExplorer; import org.opencms.ui.apps.I_CmsCachableApp; import org.opencms.ui.apps.I_CmsContextProvider; import org.opencms.ui.apps.Messages; import org.opencms.ui.apps.projects.CmsProjectManagerConfiguration; import org.opencms.ui.apps.search.CmsSourceSearchForm.SearchType; import org.opencms.ui.components.CmsErrorDialog; import org.opencms.ui.components.CmsFileTable; import org.opencms.ui.components.CmsFileTableDialogContext; import org.opencms.ui.report.CmsReportOverlay; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.server.Sizeable.Unit; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.themes.ValoTheme; /** * The source search app.<p> */ public class CmsSourceSearchApp extends A_CmsWorkplaceApp implements I_CmsCachableApp { /** The folder key. */ public static final String FOLDER = "f"; /** The index key. */ public static final String INDEX = "i"; /** The locale key. */ public static final String LOCALE = "l"; /** The project ley. */ public static final String PROJECT = "p"; /** The query key. */ public static final String QUERY = "q"; /** The replace pattern key. */ public static final String REPLACE_PATTERN = "rp"; /** The resource type key. */ public static final String RESOURCE_TYPE = "rt"; /** The search pattern key. */ public static final String SEARCH_PATTERN = "sp"; /** The type key. */ public static final String SEARCH_TYPE = "t"; /** The site root key. */ public static final String SITE_ROOT = "s"; /** The XPath key. */ public static final String XPATH = "x"; /** The serial version id. */ private static final long serialVersionUID = 4675966043824229258L; /** The results file table. */ CmsFileTable m_resultTable; /** The currently selected result list resources. */ private List<CmsResource> m_currentResources; /** The current state string. */ private String m_currentState; /** The current search report. */ private CmsReportOverlay m_report; /** The result table filter input. */ private TextField m_resultTableFilter; /** The search form. */ private CmsSourceSearchForm m_searchForm; /** The search and replace thread. */ private CmsSearchReplaceThread m_thread; /** * Generates the state string for the given search settings.<p> * * @param settings the search settings * * @return the state string */ public static String generateState(CmsSearchReplaceSettings settings) { String state = ""; state = A_CmsWorkplaceApp.addParamToState(state, SITE_ROOT, settings.getSiteRoot()); state = A_CmsWorkplaceApp.addParamToState(state, SEARCH_TYPE, settings.getType().name()); state = A_CmsWorkplaceApp.addParamToState(state, SEARCH_PATTERN, settings.getSearchpattern()); if (!settings.getPaths().isEmpty()) { state = A_CmsWorkplaceApp.addParamToState(state, FOLDER, settings.getPaths().get(0)); } state = A_CmsWorkplaceApp.addParamToState(state, RESOURCE_TYPE, settings.getTypes()); state = A_CmsWorkplaceApp.addParamToState(state, LOCALE, settings.getLocale()); state = A_CmsWorkplaceApp.addParamToState(state, QUERY, settings.getQuery()); state = A_CmsWorkplaceApp.addParamToState(state, INDEX, settings.getSource()); state = A_CmsWorkplaceApp.addParamToState(state, XPATH, settings.getXpath()); return state; } /** * Returns the settings for the given state.<p> * * @param state the state * * @return the search settings */ static CmsSearchReplaceSettings getSettingsFromState(String state) { CmsSearchReplaceSettings settings = null; String typeString = A_CmsWorkplaceApp.getParamFromState(state, SEARCH_TYPE); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(typeString)) { SearchType type = SearchType.valueOf(typeString); settings = new CmsSearchReplaceSettings(); settings.setType(type); settings.setSiteRoot(A_CmsWorkplaceApp.getParamFromState(state, SITE_ROOT)); settings.setPaths(Collections.singletonList(A_CmsWorkplaceApp.getParamFromState(state, FOLDER))); String resType = A_CmsWorkplaceApp.getParamFromState(state, RESOURCE_TYPE); if (resType != null) { settings.setTypes(resType); } String project = A_CmsWorkplaceApp.getParamFromState(state, PROJECT); if (project != null) { settings.setProject(project); } settings.setSearchpattern(A_CmsWorkplaceApp.getParamFromState(state, SEARCH_PATTERN)); if (type.isContentValuesOnly()) { settings.setOnlyContentValues(true); String locale = A_CmsWorkplaceApp.getParamFromState(state, LOCALE); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(locale)) { settings.setLocale(locale); } settings.setXpath(A_CmsWorkplaceApp.getParamFromState(state, XPATH)); } if (type.isSolrSearch()) { settings.setQuery(A_CmsWorkplaceApp.getParamFromState(state, QUERY)); settings.setSource(A_CmsWorkplaceApp.getParamFromState(state, INDEX)); } } return settings; } /** * @see org.opencms.ui.apps.I_CmsCachableApp#isCachable() */ public boolean isCachable() { return true; } /** * @see org.opencms.ui.apps.I_CmsCachableApp#onRestoreFromCache() */ public void onRestoreFromCache() { if (m_resultTable.getItemCount() < CmsFileExplorer.UPDATE_FOLDER_THRESHOLD) { m_resultTable.update(m_resultTable.getAllIds(), false); } else { if (m_currentResources != null) { Set<CmsUUID> ids = new HashSet<CmsUUID>(); for (CmsResource res : m_currentResources) { ids.add(res.getStructureId()); } m_resultTable.update(ids, false); } } } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#onStateChange(java.lang.String) */ @Override public void onStateChange(String state) { if ((m_currentState == null) || !m_currentState.equals(state)) { super.onStateChange(state); } } /** * Displays the search result.<p> */ protected void displayResult() { m_resultTable.fillTable(A_CmsUI.getCmsObject(), m_thread.getMatchedResources()); m_searchForm.removeComponent(m_report); m_report = null; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getBreadCrumbForState(java.lang.String) */ @Override protected LinkedHashMap<String, String> getBreadCrumbForState(String state) { return null; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getComponentForState(java.lang.String) */ @Override protected Component getComponentForState(String state) { m_rootLayout.setMainHeightFull(true); HorizontalSplitPanel sp = new HorizontalSplitPanel(); sp.setSizeFull(); m_searchForm = new CmsSourceSearchForm(this); sp.setFirstComponent(m_searchForm); m_resultTable = new CmsFileTable(null); m_resultTable.applyWorkplaceAppSettings(); m_resultTable.setContextProvider(new I_CmsContextProvider() { /** * @see org.opencms.ui.apps.I_CmsContextProvider#getDialogContext() */ public I_CmsDialogContext getDialogContext() { CmsFileTableDialogContext context = new CmsFileTableDialogContext( CmsProjectManagerConfiguration.APP_ID, ContextType.fileTable, m_resultTable, m_resultTable.getSelectedResources()); storeCurrentFileSelection(m_resultTable.getSelectedResources()); context.setEditableProperties(CmsFileExplorer.INLINE_EDIT_PROPERTIES); return context; } }); m_resultTable.setSizeFull(); m_resultTableFilter = new TextField(); m_resultTableFilter.setIcon(FontOpenCms.FILTER); m_resultTableFilter.setInputPrompt( Messages.get().getBundle(UI.getCurrent().getLocale()).key(Messages.GUI_EXPLORER_FILTER_0)); m_resultTableFilter.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON); m_resultTableFilter.setWidth("200px"); m_resultTableFilter.addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = 1L; public void textChange(TextChangeEvent event) { m_resultTable.filterTable(event.getText()); } }); m_infoLayout.addComponent(m_resultTableFilter); sp.setSecondComponent(m_resultTable); sp.setSplitPosition(CmsFileExplorer.LAYOUT_SPLIT_POSITION, Unit.PIXELS); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(state)) { CmsSearchReplaceSettings settings = getSettingsFromState(state); if (settings != null) { m_currentState = state; m_searchForm.initFormValues(settings); search(settings, false); } } return sp; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getSubNavEntries(java.lang.String) */ @Override protected List<NavEntry> getSubNavEntries(String state) { return null; } /** * Executes the search.<p> * * @param settings the search settings * @param updateState <code>true</code> to create a new history entry */ protected void search(CmsSearchReplaceSettings settings, boolean updateState) { if (updateState) { String state = generateState(settings); CmsAppWorkplaceUi.get().changeCurrentAppState(state); m_currentState = state; } CmsObject cms; try { cms = OpenCms.initCmsObject(A_CmsUI.getCmsObject()); if (settings.getSiteRoot() != null) { cms.getRequestContext().setSiteRoot(settings.getSiteRoot()); } m_thread = new CmsSearchReplaceThread(A_CmsUI.get().getHttpSession(), cms, settings); if (m_report != null) { m_searchForm.removeComponent(m_report); } m_report = new CmsReportOverlay(m_thread); m_report.addReportFinishedHandler(new Runnable() { public void run() { displayResult(); } }); m_searchForm.addComponent(m_report); m_report.setTitle(CmsVaadinUtils.getMessageText(Messages.GUI_SOURCESEARCH_REPORT_TITLE_0)); m_thread.start(); m_resultTableFilter.clear(); } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); } } /** * Stores the currently selected resources list.<p> * * @param resources the currently selected resources */ void storeCurrentFileSelection(List<CmsResource> resources) { m_currentResources = resources; } }
package org.opencms.ui.apps.sitemanager; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.site.CmsSite; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsCssIcon; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.apps.CmsAppWorkplaceUi; import org.opencms.ui.apps.CmsFileExplorerConfiguration; import org.opencms.ui.apps.CmsPageEditorConfiguration; import org.opencms.ui.apps.CmsSitemapEditorConfiguration; import org.opencms.ui.apps.Messages; import org.opencms.ui.components.CmsResourceIcon; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.ui.contextmenu.CmsContextMenu; import org.opencms.ui.contextmenu.CmsMenuItemVisibilityMode; import org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsStringUtil; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.commons.logging.Log; import com.vaadin.event.MouseEvents; import com.vaadin.server.Resource; import com.vaadin.server.StreamResource; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.ui.Component; import com.vaadin.ui.Image; import com.vaadin.ui.themes.ValoTheme; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.data.util.filter.Or; import com.vaadin.v7.data.util.filter.SimpleStringFilter; import com.vaadin.v7.event.ItemClickEvent; import com.vaadin.v7.event.ItemClickEvent.ItemClickListener; import com.vaadin.v7.shared.ui.label.ContentMode; import com.vaadin.v7.ui.Label; import com.vaadin.v7.ui.Table; import com.vaadin.v7.ui.VerticalLayout; /** * Class to create Vaadin Table object with all available sites.<p> */ public class CmsSitesTable extends Table implements I_CmsSitesTable { /** * The edit project context menu entry.<p> */ public class EditEntry implements I_CmsSimpleContextMenuEntry<Set<String>>, I_CmsSimpleContextMenuEntry.I_HasCssStyles { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> data) { String siteRoot = data.iterator().next(); m_manager.openEditDialog(siteRoot); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry.I_HasCssStyles#getStyles() */ public String getStyles() { return ValoTheme.LABEL_BOLD; } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_PROJECTS_EDIT_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> data) { if ((data == null) || (data.size() != 1) || (m_manager.getElement(data.iterator().next()) == null)) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /**Table properties. */ protected enum TableProperty { /**Status. */ Changed("", Boolean.class, new Boolean(false)), /**Status. */ CmsSite("", CmsSite.class, null), Favicon("", Image.class, null), /**Icon. */ Icon(null, Label.class, new Label(new CmsCssIcon(OpenCmsTheme.ICON_SITE).getHtml(), ContentMode.HTML)), /**Last login. */ Is_Webserver("", Boolean.class, new Boolean(true)), /**IsIndirect?. */ New("", Boolean.class, new Boolean(false)), /**Is the user disabled? */ OK("", Boolean.class, new Boolean(true)), /**Path. */ Path(Messages.GUI_SITE_PATH_0, String.class, ""), /**Description. */ Server(Messages.GUI_SITE_SERVER_0, String.class, ""), /**From Other ou?. */ SSL("", Integer.class, new Integer(1)), /**Name. */ Title(Messages.GUI_SITE_TITLE_0, String.class, ""), /**Is the user new? */ Under_Other_Site("", Boolean.class, new Boolean(false)); /**Default value for column.*/ private Object m_defaultValue; /**Header Message key.*/ private String m_headerMessage; /**Type of column property.*/ private Class<?> m_type; /** * constructor.<p> * * @param name Name * @param type type * @param defaultValue value */ TableProperty(String name, Class<?> type, Object defaultValue) { m_headerMessage = name; m_type = type; m_defaultValue = defaultValue; } /** * The default value.<p> * * @return the default value object */ Object getDefault() { return m_defaultValue; } /** * Gets the name of the property.<p> * * @return a name */ String getName() { if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_headerMessage)) { return CmsVaadinUtils.getMessageText(m_headerMessage); } return ""; } /** * Gets the type of property.<p> * * @return the type */ Class<?> getType() { return m_type; } } /** * The delete project context menu entry.<p> */ class DeleteEntry implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(final Set<String> data) { m_manager.openDeleteDialog(data); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_PROJECTS_DELETE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> data) { if (m_manager.getElement(data.iterator().next()) == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** * The menu entry to switch to the explorer of concerning site.<p> */ class ExplorerEntry implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> data) { String siteRoot = data.iterator().next(); A_CmsUI.getCmsObject().getRequestContext().setSiteRoot(siteRoot); CmsAppWorkplaceUi.get().getNavigator().navigateTo( CmsFileExplorerConfiguration.APP_ID + "/" + A_CmsUI.getCmsObject().getRequestContext().getCurrentProject().getUuid() + "!!" + siteRoot + "!!"); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return Messages.get().getBundle(locale).key(Messages.GUI_EXPLORER_TITLE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> data) { if (data == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } if (data.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } try { CmsObject cms = OpenCms.initCmsObject(A_CmsUI.getCmsObject()); cms.getRequestContext().setSiteRoot(""); if (cms.existsResource(data.iterator().next())) { return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } catch (CmsException e) { LOG.error("Unable to inti OpenCms Object", e); } return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } } /** * Column with FavIcon.<p> */ class FavIconColumn implements Table.ColumnGenerator { /**vaadin serial id.*/ private static final long serialVersionUID = -3772456970393398685L; /** * @see com.vaadin.v7.ui.Table.ColumnGenerator#generateCell(com.vaadin.v7.ui.Table, java.lang.Object, java.lang.Object) */ public Object generateCell(Table source, Object itemId, Object columnId) { return getImageFavIcon((String)itemId); } } /** * The menu entry to switch to the page editor of concerning site.<p> */ class PageEditorEntry implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> data) { String siteRoot = data.iterator().next(); A_CmsUI.get().changeSite(siteRoot); CmsPageEditorConfiguration pageeditorApp = new CmsPageEditorConfiguration(); pageeditorApp.getAppLaunchCommand().run(); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_PAGEEDITOR_TITLE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> data) { if (data == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } if (data.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } String siteRoot = data.iterator().next(); if (m_manager.getElement(siteRoot) == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } if (!((Boolean)getItem(siteRoot).getItemProperty(TableProperty.OK).getValue()).booleanValue()) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** * The menu entry to switch to the sitemap editor of concerning site.<p> */ class SitemapEntry implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> data) { String siteRoot = data.iterator().next(); A_CmsUI.get().changeSite(siteRoot); CmsSitemapEditorConfiguration sitemapApp = new CmsSitemapEditorConfiguration(); sitemapApp.getAppLaunchCommand().run(); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_SITEMAP_TITLE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> data) { if ((data == null) || (data.size() != 1)) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } String siteRoot = data.iterator().next(); if (m_manager.getElement(siteRoot) == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** The logger for this class. */ protected static Log LOG = CmsLog.getLog(CmsSitesTable.class.getName()); /**vaadin serial id.*/ private static final long serialVersionUID = 4655464609332605219L; /** The project manager instance. */ public CmsSiteManager m_manager; /** The available menu entries. */ protected List<I_CmsSimpleContextMenuEntry<Set<String>>> m_menuEntries; /** The data container. */ private IndexedContainer m_container; /** The context menu. */ private CmsContextMenu m_menu; /**Counter for valid sites.*/ private int m_siteCounter; /** * Constructor.<p> * * @param manager the project manager */ public CmsSitesTable(CmsSiteManager manager) { m_manager = manager; m_container = new IndexedContainer(); for (TableProperty prop : TableProperty.values()) { m_container.addContainerProperty(prop, prop.getType(), prop.getDefault()); setColumnHeader(prop, prop.getName()); } setContainerDataSource(m_container); setColumnAlignment(TableProperty.Favicon, Align.CENTER); setColumnExpandRatio(TableProperty.Server, 2); setColumnExpandRatio(TableProperty.Title, 2); setColumnExpandRatio(TableProperty.Path, 2); setColumnWidth(TableProperty.Favicon, 40); setColumnWidth(TableProperty.SSL, 130); setSelectable(true); setMultiSelect(true); m_menu = new CmsContextMenu(); m_menu.setAsTableContextMenu(this); addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 1L; public void itemClick(ItemClickEvent event) { onItemClick(event, event.getItemId(), event.getPropertyId()); } }); setCellStyleGenerator(new CellStyleGenerator() { private static final long serialVersionUID = 1L; public String getStyle(Table source, Object itemId, Object propertyId) { String styles = ""; if (TableProperty.SSL.equals(propertyId)) { styles += " " + getSSLStyle( (CmsSite)source.getItem(itemId).getItemProperty(TableProperty.CmsSite).getValue()); } if (TableProperty.Server.equals(propertyId)) { styles += " " + OpenCmsTheme.HOVER_COLUMN; if (!((Boolean)source.getItem(itemId).getItemProperty( TableProperty.OK).getValue()).booleanValue()) { if (((Boolean)source.getItem(itemId).getItemProperty( TableProperty.Changed).getValue()).booleanValue()) { styles += " " + OpenCmsTheme.STATE_CHANGED; } else { styles += " " + OpenCmsTheme.EXPIRED; } } else { if (((Boolean)source.getItem(itemId).getItemProperty( TableProperty.New).getValue()).booleanValue()) { styles += " " + OpenCmsTheme.STATE_NEW; } } } if (TableProperty.Title.equals(propertyId) & ((Boolean)source.getItem(itemId).getItemProperty( TableProperty.Is_Webserver).getValue()).booleanValue()) { styles += " " + OpenCmsTheme.IN_NAVIGATION; } if (styles.isEmpty()) { return null; } return styles; } }); addGeneratedColumn(TableProperty.SSL, new ColumnGenerator() { private static final long serialVersionUID = -2144476865774782965L; public Object generateCell(Table source, Object itemId, Object columnId) { return getSSLStatus((CmsSite)source.getItem(itemId).getItemProperty(TableProperty.CmsSite).getValue()); } }); addGeneratedColumn(TableProperty.Favicon, new FavIconColumn()); setItemDescriptionGenerator(new ItemDescriptionGenerator() { private static final long serialVersionUID = 7367011213487089661L; public String generateDescription(Component source, Object itemId, Object propertyId) { if (TableProperty.Favicon.equals(propertyId)) { return ((CmsSite)(((Table)source).getItem(itemId).getItemProperty( TableProperty.CmsSite).getValue())).getSSLMode().getLocalizedMessage(); } return null; } }); setColumnCollapsingAllowed(false); setVisibleColumns( TableProperty.Icon, TableProperty.SSL, TableProperty.Favicon, TableProperty.Server, TableProperty.Title, TableProperty.Path); setColumnWidth(TableProperty.Icon, 40); } /** * Gets the style for ssl badget.<p> * * @param site to get style for * @return style string */ public static String getSSLStyle(CmsSite site) { if ((site != null) && site.getSSLMode().isSecure()) { return OpenCmsTheme.TABLE_COLUMN_BOX_CYAN; } return OpenCmsTheme.TABLE_COLUMN_BOX_GRAY; } /** * @see org.opencms.ui.apps.user.I_CmsFilterableTable#filter(java.lang.String) */ public void filter(String search) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(TableProperty.Title, search, true, false), new SimpleStringFilter(TableProperty.Path, search, true, false), new SimpleStringFilter(TableProperty.Server, search, true, false))); } if ((getValue() != null) & !((Set<String>)getValue()).isEmpty()) { setCurrentPageFirstItemId(((Set<String>)getValue()).iterator().next()); } } /** * @see org.opencms.ui.apps.sitemanager.I_CmsSitesTable#getContainer() */ public IndexedContainer getContainer() { return m_container; } /** * @see org.opencms.ui.apps.user.I_CmsFilterableTable#getEmptyLayout() */ public VerticalLayout getEmptyLayout() { return null; } /** * Returns the available menu entries.<p> * * @return the menu entries */ public List<I_CmsSimpleContextMenuEntry<Set<String>>> getMenuEntries() { if (m_menuEntries == null) { m_menuEntries = new ArrayList<I_CmsSimpleContextMenuEntry<Set<String>>>(); m_menuEntries.add(new EditEntry()); m_menuEntries.add(new DeleteEntry()); m_menuEntries.add(new ExplorerEntry()); m_menuEntries.add(new PageEditorEntry()); } return m_menuEntries; } /** * Returns number of correctly configured sites.<p> * * @return number of sites */ public int getSitesCount() { return m_siteCounter; } /** * Reads sites from Site Manager and adds them to tabel.<p> */ public void loadSites() { m_container.removeAllItems(); List<CmsSite> sites = m_manager.getAllElements(); m_siteCounter = 0; CmsCssIcon icon = new CmsCssIcon(OpenCmsTheme.ICON_SITE); icon.setOverlay(OpenCmsTheme.STATE_CHANGED + " " + CmsResourceIcon.ICON_CLASS_CHANGED); boolean showPublishButton = false; for (CmsSite site : sites) { if (site.getSiteMatcher() != null) { m_siteCounter++; Item item = m_container.addItem(site.getSiteRoot()); item.getItemProperty(TableProperty.CmsSite).setValue(site); item.getItemProperty(TableProperty.Server).setValue(site.getUrl()); item.getItemProperty(TableProperty.Title).setValue(site.getTitle()); item.getItemProperty(TableProperty.Is_Webserver).setValue(new Boolean(site.isWebserver())); item.getItemProperty(TableProperty.Path).setValue(site.getSiteRoot()); if (OpenCms.getSiteManager().isOnlyOfflineSite(site)) { item.getItemProperty(TableProperty.New).setValue(new Boolean(true)); item.getItemProperty(TableProperty.Icon).setValue( new Label(icon.getHtmlWithOverlay(), ContentMode.HTML)); showPublishButton = true; } else { item.getItemProperty(TableProperty.Icon).setValue(new Label(icon.getHtml(), ContentMode.HTML)); } item.getItemProperty(TableProperty.OK).setValue(!isSiteUnderSite(site, sites)); } } for (CmsSite site : m_manager.getCorruptedSites()) { Item item = m_container.addItem(site.getSiteRoot()); //Make sure item doesn't exist in table yet.. should never happen if (item != null) { item.getItemProperty(TableProperty.CmsSite).setValue(site); item.getItemProperty(TableProperty.Icon).setValue(new Label(icon.getHtml(), ContentMode.HTML)); item.getItemProperty(TableProperty.Server).setValue(site.getUrl()); item.getItemProperty(TableProperty.Title).setValue(site.getTitle()); item.getItemProperty(TableProperty.Is_Webserver).setValue(new Boolean(site.isWebserver())); item.getItemProperty(TableProperty.Path).setValue(site.getSiteRoot()); item.getItemProperty(TableProperty.OK).setValue(new Boolean(false)); if (!site.getSiteRootUUID().isNullUUID()) { if (m_manager.getRootCmsObject().existsResource(site.getSiteRootUUID())) { item.getItemProperty(TableProperty.Changed).setValue(new Boolean(true)); item.getItemProperty(TableProperty.Icon).setValue( new Label(icon.getHtmlWithOverlay(), ContentMode.HTML)); showPublishButton = true; } else { //Site root deleted, publish makes no sense any more (-> OK=FALSE) } } } } } /** * Sets the menu entries.<p> * * @param newEntries to be set */ public void setMenuEntries(List<I_CmsSimpleContextMenuEntry<Set<String>>> newEntries) { m_menuEntries = newEntries; } /** * Get the ssl status label.<p> * * @param site to get ssl status for * @return Label for status */ protected String getSSLStatus(CmsSite site) { if ((site != null) && site.getSSLMode().isSecure()) { return CmsVaadinUtils.getMessageText(Messages.GUI_SITE_ENCRYPTED_0); } return CmsVaadinUtils.getMessageText(Messages.GUI_SITE_UNENCRYPTED_0); } /** * Returns an favicon image with click listener on right clicks.<p> * * @param itemId of row to put image in. * @return Vaadin Image. */ Image getImageFavIcon(final String itemId) { Resource resource = getFavIconResource(itemId); if (resource != null) { Image favIconImage = new Image("", resource); favIconImage.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_SITE_FAVICON_0)); favIconImage.addClickListener(new MouseEvents.ClickListener() { private static final long serialVersionUID = 5954790734673665522L; public void click(com.vaadin.event.MouseEvents.ClickEvent event) { onItemClick(event, itemId, TableProperty.Favicon); } }); return favIconImage; } else { return null; } } /** * Handles the table item clicks, including clicks on images inside of a table item.<p> * * @param event the click event * @param itemId of the clicked row * @param propertyId column id */ @SuppressWarnings("unchecked") void onItemClick(MouseEvents.ClickEvent event, Object itemId, Object propertyId) { if (!event.isCtrlKey() && !event.isShiftKey()) { changeValueIfNotMultiSelect(itemId); // don't interfere with multi-selection using control key if (event.getButton().equals(MouseButton.RIGHT) || (propertyId == TableProperty.Icon)) { m_menu.setEntries(getMenuEntries(), (Set<String>)getValue()); m_menu.openForTable(event, itemId, propertyId, this); } else if (event.getButton().equals(MouseButton.LEFT) && TableProperty.Server.equals(propertyId)) { String siteRoot = (String)itemId; m_manager.defaultAction(siteRoot); } } } /** * Checks value of table and sets it new if needed:<p> * if multiselect: new itemId is in current Value? -> no change of value<p> * no multiselect and multiselect, but new item not selected before: set value to new item<p> * * @param itemId if of clicked item */ private void changeValueIfNotMultiSelect(Object itemId) { @SuppressWarnings("unchecked") Set<String> value = (Set<String>)getValue(); if (value == null) { select(itemId); } else if (!value.contains(itemId)) { setValue(null); select(itemId); } } /** * Loads the FavIcon of a given site.<p> * * @param siteRoot of the given site. * @return the favicon as resource or default image if no faicon was found. */ private Resource getFavIconResource(String siteRoot) { try { CmsResource favicon = m_manager.getRootCmsObject().readResource(siteRoot + "/" + CmsSiteManager.FAVICON); CmsFile faviconFile = m_manager.getRootCmsObject().readFile(favicon); final byte[] imageData = faviconFile.getContents(); return new StreamResource(new StreamResource.StreamSource() { private static final long serialVersionUID = -8868657402793427460L; public InputStream getStream() { return new ByteArrayInputStream(imageData); } }, ""); } catch (CmsException e) { return null; } } /** * Is site in other site?<p> * * @param site to check * @param sites to check * @return Boolean */ private Boolean isSiteUnderSite(CmsSite site, List<CmsSite> sites) { for (CmsSite s : sites) { if ((site.getSiteRoot().length() > s.getSiteRoot().length()) & site.getSiteRoot().startsWith(CmsFileUtil.addTrailingSeparator(s.getSiteRoot()))) { return Boolean.TRUE; } } return Boolean.FALSE; } }
package moses.client.service.helpers; import android.os.Handler; import moses.client.abstraction.PingSender; /** * @author Jaco Hofmann * */ public class KeepSessionAlive { private Handler mHandler = new Handler(); private boolean stopPosting = false; private PingSender pinger; private final int pingTime = 60000; // Every minute private Runnable mKeepAliveTask = new Runnable() { @Override public void run() { pinger.sendPing(); if (!stopPosting) mHandler.postDelayed(this, pingTime); } }; public KeepSessionAlive(Executor e) { pinger = new PingSender(e); } public void keepAlive(boolean b) { if (b) { mHandler.removeCallbacks(mKeepAliveTask); mHandler.postDelayed(mKeepAliveTask, pingTime); } else { mHandler.removeCallbacks(mKeepAliveTask); stopPosting = true; } } }
package cc.arduino.contributions; import cc.arduino.contributions.libraries.LibrariesIndexer; import cc.arduino.contributions.libraries.LibraryInstaller; import cc.arduino.contributions.libraries.filters.UpdatableLibraryPredicate; import cc.arduino.contributions.packages.ContributionInstaller; import cc.arduino.contributions.packages.ContributionsIndexer; import cc.arduino.contributions.packages.filters.UpdatablePlatformPredicate; import cc.arduino.view.NotificationPopup; import processing.app.Base; import processing.app.I18n; import javax.swing.*; import javax.swing.event.HyperlinkListener; import java.util.TimerTask; import static processing.app.I18n.tr; public class ContributionsSelfCheck extends TimerTask { private final Base base; private final HyperlinkListener hyperlinkListener; private final ContributionsIndexer contributionsIndexer; private final ContributionInstaller contributionInstaller; private final LibrariesIndexer librariesIndexer; private final LibraryInstaller libraryInstaller; private final ProgressListener progressListener; private volatile boolean cancelled; private volatile NotificationPopup notificationPopup; public ContributionsSelfCheck(Base base, HyperlinkListener hyperlinkListener, ContributionsIndexer contributionsIndexer, ContributionInstaller contributionInstaller, LibrariesIndexer librariesIndexer, LibraryInstaller libraryInstaller) { this.base = base; this.hyperlinkListener = hyperlinkListener; this.contributionsIndexer = contributionsIndexer; this.contributionInstaller = contributionInstaller; this.librariesIndexer = librariesIndexer; this.libraryInstaller = libraryInstaller; this.progressListener = new NoopProgressListener(); this.cancelled = false; } @Override public void run() { updateContributionIndex(); updateLibrariesIndex(); long updatablePlatforms = contributionsIndexer.getPackages().stream() .flatMap(pack -> pack.getPlatforms().stream()) .filter(new UpdatablePlatformPredicate(contributionsIndexer)).count(); long updatableLibraries = librariesIndexer.getInstalledLibraries().stream() .filter(new UpdatableLibraryPredicate(librariesIndexer)) .count(); if (updatableLibraries <= 0 && updatablePlatforms <= 0) { return; } String text; if (updatableLibraries > 0 && updatablePlatforms <= 0) { text = I18n.format(tr("<br/>Update available for some of your {0}libraries{1}"), "<a href=\"http://librarymanager\">", "</a>"); } else if (updatableLibraries <= 0 && updatablePlatforms > 0) { text = I18n.format(tr("<br/>Update available for some of your {0}boards{1}"), "<a href=\"http://boardsmanager\">", "</a>"); } else { text = I18n.format(tr("<br/>Update available for some of your {0}boards{1} and {2}libraries{3}"), "<a href=\"http: } if (cancelled) { return; } SwingUtilities.invokeLater(() -> { notificationPopup = new NotificationPopup(base.getActiveEditor(), hyperlinkListener, text); notificationPopup.setVisible(true); }); } @Override public boolean cancel() { cancelled = true; if (notificationPopup != null) { notificationPopup.close(); } return super.cancel(); } private void updateLibrariesIndex() { if (cancelled) { return; } try { libraryInstaller.updateIndex(progressListener); } catch (Exception e) { // ignore } } private void updateContributionIndex() { if (cancelled) { return; } try { contributionInstaller.updateIndex(progressListener); } catch (Exception e) { // ignore } } }
package com.kuxhausen.huemore.timing; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.support.v7.app.ActionBarActivity; import com.kuxhausen.huemore.HelpFragment; import com.kuxhausen.huemore.MainFragment; import com.kuxhausen.huemore.NavigationDrawerActivity; import com.kuxhausen.huemore.R; import com.kuxhausen.huemore.persistence.DatabaseDefinitions.AlarmColumns; import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments; public class AlarmsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private NavigationDrawerActivity mParrent; // Identifies a particular Loader being used in this component private static final int ALARMS_LOADER = 0; private AlarmRowAdapter dataSource; private DatabaseAlarm selectedRow; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); mParrent = (NavigationDrawerActivity) this.getActivity(); /* * Initializes the CursorLoader. The GROUPS_LOADER value is eventually * passed to onCreateLoader(). */ getLoaderManager().initLoader(ALARMS_LOADER, null, this); String[] columns = { AlarmColumns.STATE, BaseColumns._ID }; dataSource = new AlarmRowAdapter(this.getActivity(), R.layout.alarm_row, null, columns, new int[] { R.id.subTextView }, 0); setListAdapter(dataSource); View myView = inflater.inflate(R.layout.alarms_list_fragment, null); setHasOptionsMenu(true); getActivity().setTitle(R.string.alarms); ((ActionBarActivity)this.getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); return myView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.action_alarm, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case android.R.id.home: this.startActivity(new Intent(this.getActivity(),MainFragment.class)); return true; case R.id.action_add_alarm: NewAlarmDialogFragment nadf = new NewAlarmDialogFragment(); nadf.show(getFragmentManager(), InternalArguments.FRAG_MANAGER_DIALOG_TAG); nadf.onLoadLoaderManager(null); return true; case R.id.action_help: mParrent.showHelp(this.getResources().getString(R.string.help_title_alarms)); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); LinearLayout selected = (LinearLayout) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView; selectedRow = ((DatabaseAlarm) selected.getChildAt(0).getTag()); android.view.MenuInflater inflater = this.getActivity().getMenuInflater(); inflater.inflate(R.menu.context_alarm, menu); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case R.id.contextalarmmenu_edit: NewAlarmDialogFragment nadf = new NewAlarmDialogFragment(); nadf.show(getFragmentManager(), InternalArguments.FRAG_MANAGER_DIALOG_TAG); nadf.onLoadLoaderManager(selectedRow); return true; case R.id.contextalarmmenu_delete: selectedRow.delete(); return true; default: return super.onContextItemSelected(item); } } /** * Callback that's invoked when the system has initialized the Loader and is * ready to start the query. This usually happens when initLoader() is * called. The loaderID argument contains the ID value passed to the * initLoader() call. */ @Override public Loader<Cursor> onCreateLoader(int loaderID, Bundle arg1) { // Log.e("onCreateLoader", ""+loaderID); /* * Takes action based on the ID of the Loader that's being created */ switch (loaderID) { case ALARMS_LOADER: // Returns a new CursorLoader String[] columns = { AlarmColumns.STATE, BaseColumns._ID }; return new CursorLoader(getActivity(), // Parent activity context AlarmColumns.ALARMS_URI, // Table columns, // Projection to return null, // No selection clause null, // No selection arguments null // Default sort order ); default: // An invalid id was passed in return null; } } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { // Log.e("onLoaderFinished", arg0.toString()); /* * Moves the query results into the adapter, causing the ListView * fronting this adapter to re-display */ dataSource.changeCursor(cursor); registerForContextMenu(getListView()); } @Override public void onLoaderReset(Loader<Cursor> arg0) { // Log.e("onLoaderReset", arg0.toString()); /* * Clears out the adapter's reference to the Cursor. This prevents * memory leaks. */ // unregisterForContextMenu(getListView()); dataSource.changeCursor(null); } }
package pl.passworder.object.database; /* * Class * * @name * DefaultDatabase * * @package * pl.passworder.object.database */ import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import pl.passworder.syntax.database.Database; import pl.passworder.syntax.database.DatabaseDecoder; import pl.passworder.syntax.database.DatabaseEncoder; import java.nio.file.Path; import java.util.concurrent.ThreadPoolExecutor; public class DefaultDatabase implements Database { private Path path; private Gson gson; private JsonObject object; private DatabaseEncoder encoder; private DatabaseDecoder decoder; private ThreadPoolExecutor executor; public DefaultDatabase(Path var0, Gson var1, JsonObject var2, DatabaseEncoder var3, DatabaseDecoder var4, ThreadPoolExecutor var5) { this.path = var0; this.gson = var1; this.object = var2; this.encoder = var3; this.decoder = var4; this.executor = var5; } @Override public DatabaseEncoder getEncoder() { return this.encoder; } @Override public DatabaseDecoder getDecoder() { return this.decoder; } @Override public ThreadPoolExecutor getExecutor() { return this.executor; } @Override public void writeObject(String var0, Object var1) { } @Override public void removeObject(String var0) { } @Override public boolean checkObject(String var0) { String[] obj0 = var0.split("\\."); JsonElement obj1 = object; for (String obj2 : obj0) { if (obj1 != null) { if (((JsonObject) obj1).has(obj2)) { obj1 = ((JsonObject) obj1).getAsJsonObject(obj2); } } else { obj1 = null; } } return obj1 != null; } @Override public <T> T readObject(String var0, Class<T> var1) { return null; } @Override public void load() throws Exception { } @Override public void save() throws Exception { } }
public static void main(String[] args) { { private static final Logger logger = LogManager.getLogger(SensitiveInfoLog.class); String password = "Pass@0rd"; // BAD: user password is written to debug log logger.debug("User password is "+password); } { private static final Logger logger = LogManager.getLogger(SensitiveInfoLog.class); String password = "Pass@0rd"; // GOOD: user password is never written to debug log } }
package git4idea.commands; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.util.ExecUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProcessEventListener; import com.intellij.openapi.vcs.RemoteFilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.EnvironmentUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.ThrowableConsumer; import com.intellij.vcs.VcsLocaleHelper; import com.intellij.vcsUtil.VcsFileUtil; import git4idea.GitVcs; import git4idea.config.GitExecutableManager; import git4idea.config.GitVersionSpecialty; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; /** * A handler for git commands */ public abstract class GitHandler { protected static final Logger LOG = Logger.getInstance(GitHandler.class); protected static final Logger OUTPUT_LOG = Logger.getInstance("#output." + GitHandler.class.getName()); private static final Logger TIME_LOG = Logger.getInstance("#time." + GitHandler.class.getName()); private final Project myProject; @NotNull private final String myPathToExecutable; private final GitCommand myCommand; private boolean myPreValidateExecutable = true; protected final GeneralCommandLine myCommandLine; private final Map<String, String> myCustomEnv = new HashMap<>(); protected Process myProcess; private boolean myStdoutSuppressed; // If true, the standard output is not copied to version control console private boolean myStderrSuppressed; // If true, the standard error is not copied to version control console @Nullable private ThrowableConsumer<OutputStream, IOException> myInputProcessor; // The processor for stdin private final EventDispatcher<ProcessEventListener> myListeners = EventDispatcher.create(ProcessEventListener.class); protected boolean mySilent; // if true, the command execution is not logged in version control view private boolean myWithLowPriority; private boolean myWithNoTty; private long myStartTime; // git execution start timestamp private static final long LONG_TIME = 10 * 1000; /** * A constructor * * @param project a project * @param directory a process directory * @param command a command to execute */ protected GitHandler(@NotNull Project project, @NotNull File directory, @NotNull GitCommand command, @NotNull List<String> configParameters) { this(project, directory, GitExecutableManager.getInstance().getPathToGit(project), command, configParameters); myProgressParameterAllowed = GitVersionSpecialty.ABLE_TO_USE_PROGRESS_IN_REMOTE_COMMANDS.existsIn(project); } /** * A constructor * * @param project a project * @param vcsRoot a process directory * @param command a command to execute */ protected GitHandler(@NotNull Project project, @NotNull VirtualFile vcsRoot, @NotNull GitCommand command, @NotNull List<String> configParameters) { this(project, VfsUtil.virtualToIoFile(vcsRoot), command, configParameters); } /** * A constructor for handler that can be run without project association * * @param project optional project * @param directory working directory * @param pathToExecutable path to git executable * @param command git command to execute * @param configParameters list of config parameters to use for this git execution */ protected GitHandler(@Nullable Project project, @NotNull File directory, @NotNull String pathToExecutable, @NotNull GitCommand command, @NotNull List<String> configParameters) { myProject = project; myVcs = project != null ? GitVcs.getInstance(project) : null; myPathToExecutable = pathToExecutable; myCommand = command; myCommandLine = new GeneralCommandLine() .withWorkDirectory(directory) .withExePath(myPathToExecutable) .withCharset(StandardCharsets.UTF_8); for (String parameter : getConfigParameters(project, configParameters)) { myCommandLine.addParameters("-c", parameter); } myCommandLine.addParameter(command.name()); myStdoutSuppressed = true; mySilent = myCommand.lockingPolicy() != GitCommand.LockingPolicy.WRITE; } @NotNull private static List<String> getConfigParameters(@Nullable Project project, @NotNull List<String> requestedConfigParameters) { if (project == null || !GitVersionSpecialty.CAN_OVERRIDE_GIT_CONFIG_FOR_COMMAND.existsIn(project)) { return Collections.emptyList(); } List<String> toPass = new ArrayList<>(); toPass.add("core.quotepath=false"); toPass.add("log.showSignature=false"); toPass.addAll(requestedConfigParameters); return toPass; } @NotNull protected ProcessEventListener listeners() { return myListeners.getMulticaster(); } @Nullable public Project project() { return myProject; } @NotNull File getWorkingDirectory() { return myCommandLine.getWorkDirectory(); } @NotNull String getExecutablePath() { return myPathToExecutable; } @NotNull GitCommand getCommand() { return myCommand; } protected void addListener(@NotNull ProcessEventListener listener) { myListeners.addListener(listener); } /** * Execute process with lower priority */ public void withLowPriority() { myWithLowPriority = true; } /** * Detach git process from IDE TTY session */ public void withNoTty() { myWithNoTty = true; } public void addParameters(@NonNls @NotNull String... parameters) { addParameters(Arrays.asList(parameters)); } public void addParameters(@NotNull List<String> parameters) { for (String parameter : parameters) { myCommandLine.addParameter(escapeParameterIfNeeded(parameter)); } } @NotNull private String escapeParameterIfNeeded(@NotNull String parameter) { if (escapeNeeded(parameter)) { return parameter.replaceAll("\\^", "^^^^"); } return parameter; } private boolean escapeNeeded(@NotNull String parameter) { return SystemInfo.isWindows && isCmd() && parameter.contains("^"); } private boolean isCmd() { return StringUtil.toLowerCase(myCommandLine.getExePath()).endsWith("cmd"); } public void addRelativePaths(@NotNull FilePath... parameters) { addRelativePaths(Arrays.asList(parameters)); } public void addRelativePaths(@NotNull Collection<FilePath> filePaths) { for (FilePath path : filePaths) { if (path instanceof RemoteFilePath) { myCommandLine.addParameter(path.getPath()); } else { myCommandLine.addParameter(VcsFileUtil.relativePath(getWorkingDirectory(), path)); } } } public void addRelativeFiles(@NotNull final Collection<VirtualFile> files) { for (VirtualFile file : files) { myCommandLine.addParameter(VcsFileUtil.relativePath(getWorkingDirectory(), file)); } } public void addAbsoluteFile(@NotNull File file) { myCommandLine.addParameter(file.getAbsolutePath()); } /** * End option parameters and start file paths. The method adds {@code "--"} parameter. */ public void endOptions() { myCommandLine.addParameter(" } private boolean isStarted() { return myProcess != null; } /** * @return true if the command line is too big */ public boolean isLargeCommandLine() { return myCommandLine.getCommandLineString().length() > VcsFileUtil.FILE_PATH_LIMIT; } /** * @return a command line with full path to executable replace to "git" */ public String printableCommandLine() { return unescapeCommandLine(myCommandLine.getCommandLineString("git")); } @NotNull private String unescapeCommandLine(@NotNull String commandLine) { if (escapeNeeded(commandLine)) { return commandLine.replaceAll("\\^\\^\\^\\^", "^"); } return commandLine; } @NotNull public Charset getCharset() { return myCommandLine.getCharset(); } public void setCharset(@NotNull Charset charset) { myCommandLine.setCharset(charset); } /** * Set silent mode. When handler is silent, it does not logs command in version control console. * Note that this option also suppresses stderr and stdout copying. * * @param silent a new value of the flag * @see #setStderrSuppressed(boolean) * @see #setStdoutSuppressed(boolean) */ public void setSilent(boolean silent) { mySilent = silent; if (silent) { setStderrSuppressed(true); setStdoutSuppressed(true); } } boolean isSilent() { return mySilent; } /** * @return true if standard output is not copied to the console */ boolean isStdoutSuppressed() { return myStdoutSuppressed; } /** * Set flag specifying if stdout should be copied to the console * * @param stdoutSuppressed true if output is not copied to the console */ public void setStdoutSuppressed(final boolean stdoutSuppressed) { myStdoutSuppressed = stdoutSuppressed; } /** * @return true if standard output is not copied to the console */ boolean isStderrSuppressed() { return myStderrSuppressed; } /** * Set flag specifying if stderr should be copied to the console * * @param stderrSuppressed true if error output is not copied to the console */ public void setStderrSuppressed(boolean stderrSuppressed) { myStderrSuppressed = stderrSuppressed; } /** * Set processor for standard input. This is a place where input to the git application could be generated. * * @param inputProcessor the processor */ public void setInputProcessor(@Nullable ThrowableConsumer<OutputStream, IOException> inputProcessor) { myInputProcessor = inputProcessor; } /** * Add environment variable to this handler * * @param name the variable name * @param value the variable value */ public void addCustomEnvironmentVariable(String name, String value) { myCustomEnv.put(name, value); } /** * See {@link GitImplBase#run(Computable, Computable)} */ public void setPreValidateExecutable(boolean preValidateExecutable) { myPreValidateExecutable = preValidateExecutable; } /** * See {@link GitImplBase#run(Computable, Computable)} */ boolean isPreValidateExecutable() { return myPreValidateExecutable; } void runInCurrentThread() throws IOException { try { start(); if (isStarted()) { try { if (myInputProcessor != null) { myInputProcessor.consume(myProcess.getOutputStream()); } } finally { waitForProcess(); } } } finally { logTime(); } } private void logTime() { if (myStartTime > 0) { long time = System.currentTimeMillis() - myStartTime; if (!TIME_LOG.isDebugEnabled() && time > LONG_TIME) { LOG.info(String.format("git %s took %s ms. Command parameters: %n%s", myCommand, time, myCommandLine.getCommandLineString())); } else { TIME_LOG.debug(String.format("git %s took %s ms", myCommand, time)); } } else { LOG.debug(String.format("git %s finished.", myCommand)); } } private void start() { if (isStarted()) { throw new IllegalStateException("The process has been already started"); } try { if (myWithLowPriority) ExecUtil.setupLowPriorityExecution(myCommandLine); if (myWithNoTty) ExecUtil.setupNoTtyExecution(myCommandLine); myStartTime = System.currentTimeMillis(); String logDirectoryPath = myProject != null ? GitImplBase.stringifyWorkingDir(myProject.getBasePath(), myCommandLine.getWorkDirectory()) : myCommandLine.getWorkDirectory().getPath(); if (!mySilent) { LOG.info("[" + logDirectoryPath + "] " + printableCommandLine()); } else { LOG.debug("[" + logDirectoryPath + "] " + printableCommandLine()); } prepareEnvironment(); // start process myProcess = startProcess(); startHandlingStreams(); } catch (ProcessCanceledException pce) { throw pce; } catch (Throwable t) { if (!ApplicationManager.getApplication().isUnitTestMode()) { LOG.warn(t); // will surely happen if called during unit test disposal, because the working dir is simply removed then } myListeners.getMulticaster().startFailed(t); } } private void prepareEnvironment() { Map<String, String> executionEnvironment = myCommandLine.getEnvironment(); executionEnvironment.clear(); executionEnvironment.putAll(EnvironmentUtil.getEnvironmentMap()); executionEnvironment.putAll(VcsLocaleHelper.getDefaultLocaleEnvironmentVars("git")); executionEnvironment.putAll(myCustomEnv); } protected abstract Process startProcess() throws ExecutionException; /** * Start handling process output streams for the handler. */ protected abstract void startHandlingStreams(); /** * Wait for process */ protected abstract void waitForProcess(); @Override public String toString() { return myCommandLine.toString(); } //region deprecated stuff //Used by Gitflow in GitInitLineHandler.onTextAvailable @Deprecated protected final GitVcs myVcs; @Deprecated private Integer myExitCode; // exit code or null if exit code is not yet available @Deprecated private final List<String> myLastOutput = Collections.synchronizedList(new ArrayList<>()); @Deprecated private static final int LAST_OUTPUT_SIZE = 5; @Deprecated private boolean myProgressParameterAllowed = false; @Deprecated private final List<VcsException> myErrors = Collections.synchronizedList(new ArrayList<>()); /** * Adds "--progress" parameter. Usable for long operations, such as clone or fetch. * * @return is "--progress" parameter supported by this version of Git. * @deprecated use {@link #addParameters} */ @Deprecated public boolean addProgressParameter() { if (myProgressParameterAllowed) { addParameters("--progress"); return true; } return false; } /** * @return exit code for process if it is available * @deprecated use {@link GitLineHandler}, {@link Git#runCommand(GitLineHandler)} and {@link GitCommandResult} */ @Deprecated public int getExitCode() { if (myExitCode == null) { return -1; } return myExitCode.intValue(); } /** * @param exitCode a exit code for process * @deprecated use {@link GitLineHandler}, {@link Git#runCommand(GitLineHandler)} and {@link GitCommandResult} */ @Deprecated protected void setExitCode(int exitCode) { if (myExitCode == null) { myExitCode = exitCode; } else { LOG.info("Not setting exit code " + exitCode + ", because it was already set to " + myExitCode); } } /** * @deprecated only used in {@link GitTask} */ @Deprecated public void addLastOutput(String line) { if (myLastOutput.size() < LAST_OUTPUT_SIZE) { myLastOutput.add(line); } else { myLastOutput.add(0, line); Collections.rotate(myLastOutput, -1); } } /** * @deprecated only used in {@link GitTask} */ @Deprecated public List<String> getLastOutput() { return myLastOutput; } /** * @param postStartAction * @deprecated remove together with {@link GitHandlerUtil} */ @Deprecated void runInCurrentThread(@Nullable Runnable postStartAction) { try { start(); if (isStarted()) { if (postStartAction != null) { postStartAction.run(); } waitForProcess(); } } finally { logTime(); } } /** * Destroy process * * @deprecated only used in {@link GitTask} */ @Deprecated abstract void destroyProcess(); /** * add error to the error list * * @param ex an error to add to the list * @deprecated remove together with {@link GitHandlerUtil} and {@link GitTask} */ @Deprecated public void addError(VcsException ex) { myErrors.add(ex); } /** * @return unmodifiable list of errors. * @deprecated remove together with {@link GitHandlerUtil} and {@link GitTask} */ @Deprecated public List<VcsException> errors() { return Collections.unmodifiableList(myErrors); } //endregion }
package com.cmput301f16t11.a2b; import android.app.Activity; import android.util.Log; import com.google.android.gms.maps.model.LatLng; import com.google.gson.Gson; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collection; import static com.cmput301f16t11.a2b.R.id.user; /** * Controllers user and user functions * static so it can be shared by all activities */ public class UserController { private static User user = null; private static Mode mode; private static LatLng lastLocation; private static String USRFILE = "user.sav"; public UserController(User u) { user = u; } // static public boolean auth(String username){ // // no idea what this is... - joey // // is this to statically check auth? // return true; static public void setUser(User newUser) { user = newUser; } static public void setMode(Mode newMode) { mode = newMode; } static public Mode checkMode() { mode = Mode.RIDER; return mode; } static public User getUser() { if(user != null){ return user; }else{ // should always be set but for dev purposes return an existing object // TO DO: depricate this before production ElasticsearchUserController.CheckUserTask checkUserTask = new ElasticsearchUserController.CheckUserTask(); try{ user = checkUserTask.execute("Jane Doe").get();// force syncronous }catch (Exception e){ user = new User(); } return user; } } static public void updateUserInDb(){ ElasticsearchUserController.UpdateUserInfoTask updateUserInfoTask = new ElasticsearchUserController.UpdateUserInfoTask(); updateUserInfoTask.execute(UserController.getUser()); } static public void updateLocation(LatLng location) { lastLocation = location; } static public LatLng getLastLocation() { return location; } // time to depreciate this??? static public User loadUser(String username){ return new User(); } static public String getNewUserName() { return "Daniel"; } static public String getNewPass() { return "test"; } static public String getEmail() { return "test@ualberta.ca"; } public static ArrayList<UserRequest> getRequestList() { ArrayList<UserRequest> fakeList = new ArrayList<>(); return fakeList; } public static void setOffline() { } /** * Method to save the static user variable * * Stores it in internal storage as JSON in user.sav file\ */ public static void saveInFile(Activity activity) { try { // Try to convert user to JSON and save it FileOutputStream fos = activity.openFileOutput(USRFILE, 0); OutputStreamWriter writer = new OutputStreamWriter(fos); Gson gson = new Gson(); gson.toJson(user, writer); writer.flush(); } catch (Exception e) { Log.i("Error", "Couldn't save file"); throw new RuntimeException(); } } public static void goOnline() { } public static void updateRequestList() { } public static void runBackgroundTasks(String name, LoginActivity loginActivity, boolean b) { } public static void setClosedRequestsAsRider(Collection<UserRequest> requests) { user.setClosedRequestsAsRider(requests); } public static void setClosedRequestsAsDriver(Collection<UserRequest> requests) { user.setClosedRequestsAsDriver(requests); } public static void setActiveRequestsAsRider(Collection<UserRequest> requests) { user.setActiveRequestsAsRider(requests); } public static void setActiveRequestAsDriver(Collection<UserRequest> requests) { user.setActiveRequestsAsDriver(requests); } }
package com.g11x.checklistapp; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.support.annotation.Nullable; /** Application data repository. */ public class LocalRepository extends ContentProvider { // Defines the database name private static final String DB_NAME = "g11x_checklistapp"; // A string that defines the SQL statement for creating a table private static final String SQL_CREATE_MAIN = "CREATE TABLE important_info " + "(_ID INTEGER PRIMARY KEY, INFO TEXT);"; // Helper class that actually creates and manages the provider's underlying data repository. protected static final class MainDatabaseHelper extends SQLiteOpenHelper { // Instantiates an open helper for the provider's SQLite data repository. Do not do database // creation and upgrade here. MainDatabaseHelper(Context context) { super(context, DB_NAME, null, 1); } // Creates the data repository. This is called when the provider attempts to open the // repository and SQLite reports that it doesn't exist. public void onCreate(SQLiteDatabase db) { // Creates the main table db.execSQL(SQL_CREATE_MAIN); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { // TODO: This seems useful. Learn how to use it. } } // Defines a handle to the database helper object. The MainDatabaseHelper class is defined in a // following snippet. private MainDatabaseHelper openHelper; // Holds the database object private SQLiteDatabase db; @Override public boolean onCreate() { // Creates a new helper object. This method always returns quickly. Notice that the // database itself isn't created or opened until SQLiteOpenHelper.getWritableDatabase // is called. openHelper = new MainDatabaseHelper(getContext()); return true; } @Nullable @Override public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) { return null; } @Nullable @Override public String getType(Uri uri) { return null; } @Nullable @Override public Uri insert(Uri uri, ContentValues contentValues) { // Insert code here to determine which table to open, handle error-checking, and so forth // Gets a writeable database. This will trigger its creation if it doesn't already exist. db = openHelper.getWritableDatabase(); return null; } @Override public int delete(Uri uri, String s, String[] strings) { return 0; } @Override public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { return 0; } }
package net.ocheyedan.ply.dep; import net.ocheyedan.ply.FileUtil; import net.ocheyedan.ply.Output; import net.ocheyedan.ply.PlyUtil; import net.ocheyedan.ply.SystemExit; import net.ocheyedan.ply.graph.DirectedAcyclicGraph; import net.ocheyedan.ply.graph.Graph; import net.ocheyedan.ply.graph.Graphs; import net.ocheyedan.ply.graph.Vertex; import net.ocheyedan.ply.mvn.MavenPom; import net.ocheyedan.ply.mvn.MavenPomParser; import net.ocheyedan.ply.props.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import static net.ocheyedan.ply.props.PropFile.Prop; public final class Deps { /** * Encapsulates a {@link DependencyAtom} object's paths to the local {@link RepositoryAtom}. */ static class LocalPaths { final String localPath; final URL localUrl; final String localDirUrlPath; final String localDirPath; LocalPaths(String localPath, URL localUrl, String localDirUrlPath, String localDirPath) { this.localPath = localPath; this.localUrl = localUrl; this.localDirUrlPath = localDirUrlPath; this.localDirPath = localDirPath; } static LocalPaths get(DependencyAtom dependencyAtom, RepositoryAtom localRepo) { String localDirUrlPath = getDependencyDirectoryPathForRepo(dependencyAtom, localRepo); String localPath = getDependencyPathForRepo(dependencyAtom, localDirUrlPath); URL localUrl = getUrl(localPath); if (localUrl == null) { throw new AssertionError(String.format("The local path is not valid [ %s ]", localPath)); } String localDirPath = (localDirUrlPath.startsWith("file://") ? localDirUrlPath.substring(7) : localDirUrlPath); return new LocalPaths(localPath, localUrl, localDirUrlPath, localDirPath); } } /** * @param dependencyAtoms the direct dependencies from which to create a dependency graph * @param repositoryRegistry the repositories to consult when resolving {@code dependencyAtoms}. * @return a DAG {@link Graph<Dep>} implementation representing the resolved {@code dependencyAtoms} and its tree of * transitive dependencies. */ public static DirectedAcyclicGraph<Dep> getDependencyGraph(List<DependencyAtom> dependencyAtoms, RepositoryRegistry repositoryRegistry) { return getDependencyGraph(dependencyAtoms, repositoryRegistry, true); } /** * @param dependencyAtoms the direct dependencies from which to create a dependency graph * @param repositoryRegistry the repositories to consult when resolving {@code dependencyAtoms}. * @param failMissingDependency true to fail on missing dependencies; false to ignore and continue resolution * @return a DAG {@link Graph<Dep>} implementation representing the resolved {@code dependencyAtoms} and its tree of * transitive dependencies. */ public static DirectedAcyclicGraph<Dep> getDependencyGraph(List<DependencyAtom> dependencyAtoms, RepositoryRegistry repositoryRegistry, boolean failMissingDependency) { DirectedAcyclicGraph<Dep> dependencyDAG = new DirectedAcyclicGraph<Dep>(); fillDependencyGraph(null, dependencyAtoms, repositoryRegistry, dependencyDAG, new HashMap<DependencyAtom, Dep>(dependencyAtoms.size()), false, failMissingDependency); return dependencyDAG; } /** * For each resolved {@link Dep} object of {@code dependencyAtoms} a {@link Vertex<Dep>} will be created and added * to {@code graph}. If {@code parentVertex} is not null, an edge will be added from {@code parentVertex} and * each resolved property. If adding such an edge violates the acyclic nature of {@code graph} an error message * will be printed and this program will halt. * The {@code pomSufficient} exists as maven appears to be lax on transitive dependency's transitive dependency. * For instance, depending upon log4j:log4j:1.2.15 will fail b/c it depends upon javax.jms:jms:1.1 for which * there is no artifact in maven-central. But if you depend upon org.apache.zookeeper:zookeeper:3.3.2 * which depends upon log4j:log4j:1.2.15, resolution completes. It will download the pom of * javax.jms:jms:1.1 but not require the packaged artifact (which is defaulted to jar) be present. The * pom must be present. * @param parentVertex the parent of {@code dependencyAtoms} * @param dependencyAtoms the dependencies which to resolve and place into {@code graph} * @param repositoryRegistry the repositories to consult when resolving {@code dependencyAtoms}. * @param graph to fill with the resolved {@link Dep} objects of {@code dependencyAtoms}. * @param resolved a mapping from {@link DependencyAtom} to {@link Dep} of already resolved dependencies within the graph * @param pomSufficient if true, then only the pom from a maven repository is necessary to have successfully * resolved the {@code dependencyAtom}. * @param failMissingDependency if true indicates that missing dependencies are treated as failures; false, to * ignore and continue resolution */ private static void fillDependencyGraph(Vertex<Dep> parentVertex, List<DependencyAtom> dependencyAtoms, RepositoryRegistry repositoryRegistry, DirectedAcyclicGraph<Dep> graph, Map<DependencyAtom, Dep> resolved, boolean pomSufficient, boolean failMissingDependency) { if (repositoryRegistry.isEmpty()) { Output.print("^error^ No repositories found, cannot resolve dependencies."); SystemExit.exit(1); } for (DependencyAtom dependencyAtom : dependencyAtoms) { if ((parentVertex != null) && dependencyAtom.transientDep) { continue; // non-direct (transitive) transient dependencies should be skipped } // pom is sufficient for resolution if this is a transient dependency Dep resolvedDep; try { if (resolved.containsKey(dependencyAtom)) { resolvedDep = resolved.get(dependencyAtom); } else { resolvedDep = resolveDependency(dependencyAtom, repositoryRegistry, (pomSufficient || dependencyAtom.transientDep), failMissingDependency); resolved.put(dependencyAtom, resolvedDep); } if ((resolvedDep == null) && !failMissingDependency) { if (Output.isInfo()) { Output.print("^info^ Could not resolve dependency ^b^%s^r^.", dependencyAtom.toString()); String path = getPathAsString(parentVertex, dependencyAtom); if (path != null) { Output.print("^info^ path to unresolved dependency [ %s ].", path); } } continue; } } catch (Throwable t) { Output.print(t); resolvedDep = null; // allow the path to the dependency to be printed } if (resolvedDep == null) { String path = getPathAsString(parentVertex, dependencyAtom); if (path != null) { Output.print("^error^ path to missing dependency [ %s ].", path); } SystemExit.exit(1); } Vertex<Dep> vertex = graph.addVertex(resolvedDep); if (parentVertex != null) { try { graph.addEdge(parentVertex, vertex); } catch (Graph.CycleException gce) { Output.print("^error^ circular dependency [ %s ].", getCycleAsString(gce)); SystemExit.exit(1); } } if (!dependencyAtom.transientDep) { // direct transient dependencies are not recurred upon fillDependencyGraph(vertex, vertex.getValue().dependencies, repositoryRegistry, graph, resolved, true, failMissingDependency); } } } /** *@param gce the cycle exception to print *@return a string which includes the cycle and path information from {@code gce} */ @SuppressWarnings("unchecked") private static String getCycleAsString(Graph.CycleException gce) { StringBuilder buffer = new StringBuilder(); List<Vertex<?>> cycle = gce.getCycle(); List<Vertex<?>> path = gce.getPath(); for (int i = 0; i < (path.size() - 1); i++) { Vertex<Dep> vertex = (Vertex<Dep>) path.get(i); if (buffer.length() > 0) { buffer.append(" -> "); } buffer.append(vertex.getValue().toVersionString()); } for (int i = 0; i < cycle.size(); i++) { if (buffer.length() > 0) { buffer.append(" -> "); } boolean decorate = (i == 0 ) || (i == (cycle.size() - 1)); if (decorate) { buffer.append("^red^"); } buffer.append(((Vertex<Dep>) cycle.get(i)).getValue().toVersionString()); if (decorate) { buffer.append("^r^"); } } return buffer.toString(); } private static String getPathAsString(Vertex<Dep> vertex, DependencyAtom dependencyAtom) { if (vertex == null) { return null; } StringBuilder buffer = new StringBuilder(); List<String> vertices = new ArrayList<String>(); while (vertex != null) { vertices.add(vertex.getValue().toString()); vertex = vertex.getAnyParent(); } Collections.reverse(vertices); for (String vertexAsString : vertices) { if (buffer.length() > 0) { buffer.append(" -> "); } buffer.append(vertexAsString); } buffer.append(String.format(" -> ^b^%s:%s^r^", dependencyAtom.namespace, dependencyAtom.name)); return buffer.toString(); } /** * Resolves {@code dependencyAtom} by ensuring it's present in the local repository. Resolution means iterating * over the repositories within {@code repositoryRegistry} and if {@code dependencyAtom} is found downloading or * copying it (if not already present) into the {@link RepositoryRegistry#localRepository} of {@code repositoryRegistry} * The {@code pomSufficient} exists as maven appears to be lax on transitive dependencies' transitive dependencies. * For instance, depending upon log4j:log4j:1.2.15 will fail b/c it depends upon javax.jms:jms:1.1 for which * there is no artifact in maven-central. But if you depend upon org.apache.zookeeper:zookeeper:3.3.2 * which depends upon log4j:log4j:1.2.15, resolution completes. It will download the pom of * javax.jms:jms:1.1 but not require the packaged artifact (which is defaulted to jar) be present. The * pom must be present however. * @param dependencyAtom to resolve * @param repositoryRegistry repositories to use when resolving {@code dependencyAtom} * @param pomSufficient if true, then only the pom from a maven repository is necessary to have successfully * resolved the {@code dependencyAtom}. * @param failMissingDependency true to print failure message on missing dependency * @return a {@link Dep} representation of {@code dependencyAtom} or null if {@code dependencyAtom} could * not be resolved. */ static Dep resolveDependency(DependencyAtom dependencyAtom, RepositoryRegistry repositoryRegistry, boolean pomSufficient, boolean failMissingDependency) { // determine the local-repository directory for dependencyAtom; as it is needed regardless of where the dependency // if found. RepositoryAtom localRepo = repositoryRegistry.localRepository; // first consult the synthetic repository. if (repositoryRegistry.syntheticRepository != null && repositoryRegistry.syntheticRepository.containsKey(dependencyAtom)) { LocalPaths localPaths = LocalPaths.get(dependencyAtom, localRepo); return new Dep(dependencyAtom, repositoryRegistry.syntheticRepository.get(dependencyAtom), localPaths.localDirPath); } // not present within the synthetic, check the local and other (likely remote) repositories Dep resolved = resolveDependency(dependencyAtom, repositoryRegistry, localRepo, pomSufficient); if (resolved != null) { return resolved; } if (failMissingDependency) { Output.print("^error^ Dependency ^b^%s^r^ not found in any repository; ensure repositories are accessible.", dependencyAtom.toString()); Output.print("^error^ Project's local repository is ^b^%s^r^.", localRepo.toString()); int remoteRepoSize = repositoryRegistry.remoteRepositories.size(); Output.print("^error^ Project has ^b^%d^r^ other repositor%s %s", remoteRepoSize, (remoteRepoSize != 1 ? "ies" : "y"), (remoteRepoSize > 0 ? repositoryRegistry.remoteRepositories.toString() : "")); } return null; } private static Dep resolveDependency(DependencyAtom dependencyAtom, RepositoryRegistry repositoryRegistry, RepositoryAtom localRepo, boolean pomSufficient) { LocalPaths localPaths = LocalPaths.get(dependencyAtom, localRepo); // also create pom-only objects DependencyAtom pomDependencyAtom = dependencyAtom.with("pom"); LocalPaths localPomPaths = LocalPaths.get(pomDependencyAtom, localRepo); // check the local repository File localDepFile = new File(localPaths.localUrl.getFile()); File localPomDepFile = new File(localPomPaths.localUrl.getFile()); if (localDepFile.exists()) { return resolveDependency(dependencyAtom, localRepo, localPaths.localDirUrlPath, localPaths.localDirPath); } else if (pomSufficient && localPomDepFile.exists()) { return resolveDependency(pomDependencyAtom, localRepo, localPomPaths.localDirUrlPath, localPomPaths.localDirPath); } // not in the local repository, check each other repository. Dep resolved = resolveDependencyFromRemoteRepos(dependencyAtom, repositoryRegistry, localPaths, localDepFile); if ((resolved == null) && pomSufficient) { resolved = resolveDependencyFromRemoteRepos(pomDependencyAtom, repositoryRegistry, localPomPaths, localPomDepFile); } return resolved; } private static Dep resolveDependencyFromRemoteRepos(DependencyAtom dependencyAtom, RepositoryRegistry repositoryRegistry, LocalPaths localPaths, File localDepFile) { List<RepositoryAtom> nonLocalRepos = repositoryRegistry.remoteRepositories; for (RepositoryAtom remoteRepo : nonLocalRepos) { String remotePathDir = getDependencyDirectoryPathForRepo(dependencyAtom, remoteRepo); String remotePath = FileUtil.pathFromParts(remotePathDir, dependencyAtom.getArtifactName()); URL remoteUrl = getUrl(remotePath); if (remoteUrl == null) { continue; } InputStream stream; try { URLConnection urlConnection = remoteUrl.openConnection(); stream = urlConnection.getInputStream(); } catch (FileNotFoundException fnfe) { // this is fine, check next repo continue; } catch (IOException ioe) { Output.print(ioe); // TODO - parse exception and more gracefully handle http-errors. continue; } Output.print("^info^ Downloading %s from %s...", dependencyAtom.toString(), remoteRepo.toString()); if (FileUtil.copy(stream, localDepFile)) { return resolveDependency(dependencyAtom, remoteRepo, remotePathDir, localPaths.localDirPath); } } return null; } /** * Retrieves the direct dependencies of {@code dependencyAtom} (which is located within {@code repoDirPath} * of {@code repositoryAtom}) and saves them to {@code saveToRepoDirPath} as a dependencies property file. * @param dependencyAtom to retrieve the dependencies file * @param repositoryAtom from which {@code dependencyAtom} was resolved. * @param repoDirPath the directory location of {@code dependencyAtom} within the {@code repositoryAtom}. * @param saveToRepoDirPath to save the found dependency property file (should be within the local repository). * @return the property file associated with {@code dependencyAtom} (could be empty if {@code dependencyAtom} * has no dependencies). */ private static Dep resolveDependency(DependencyAtom dependencyAtom, RepositoryAtom repositoryAtom, String repoDirPath, String saveToRepoDirPath) { PropFile dependenciesFile = getDependenciesFile(dependencyAtom, repositoryAtom, repoDirPath); if (dependenciesFile == null) { Output.print("^dbug^ No dependencies file found for %s in repo %s.", dependencyAtom.toString(), repositoryAtom.toString()); dependenciesFile = new PropFile(Context.named("dependencies"), PropFile.Loc.Local); } storeDependenciesFile(dependenciesFile, saveToRepoDirPath); List<DependencyAtom> dependencyAtoms = parse(dependenciesFile); return new Dep(dependencyAtom, dependencyAtoms, saveToRepoDirPath); } public static List<DependencyAtom> parse(Collection<Prop> dependenciesProps) { List<DependencyAtom> dependencyAtoms = new ArrayList<DependencyAtom>(dependenciesProps.size()); AtomicReference<String> error = new AtomicReference<String>(); for (Prop dependencyProp : dependenciesProps) { error.set(null); String dependencyKey = dependencyProp.name; String dependencyValue = dependencyProp.value(); DependencyAtom dependencyAtom = DependencyAtom.parse(dependencyKey + ":" + dependencyValue, error); if (dependencyAtom == null) { Output.print("^warn^ Invalid dependency %s:%s; %s", dependencyKey, dependencyValue, error.get()); continue; } dependencyAtoms.add(dependencyAtom); } return dependencyAtoms; } /** * Converts {@code dependencies} into a list of {@link DependencyAtom} objects * @param dependencies to convert * @return the converted {@code dependencies} */ public static List<DependencyAtom> parse(PropFile dependencies) { List<DependencyAtom> dependencyAtoms = new ArrayList<DependencyAtom>(); AtomicReference<String> error = new AtomicReference<String>(); for (Prop dependency : dependencies.props()) { error.set(null); String dependencyValue = dependency.value(); DependencyAtom dependencyAtom = DependencyAtom.parse(dependency.name + ":" + dependencyValue, error); if (dependencyAtom == null) { Output.print("^warn^ Invalid dependency %s:%s; %s", dependency.name, dependencyValue, error.get()); continue; } dependencyAtoms.add(dependencyAtom); } return dependencyAtoms; } /** * @param graph to convert into a resolved properties file * @return a {@link PropFile} object mapping each {@link Vertex<Dep>} (reachable from {@code graph}) object's * {@link DependencyAtom} object's key (which is {@link Dep#dependencyAtom#getPropertyName()} + ":" * + {@link Dep#dependencyAtom#getPropertyName()}) to the local repository location (which is * {@link Dep#localRepositoryDirectory} + {@link File#separator} * + {@link Dep#dependencyAtom#getArtifactName()}). * */ public static PropFile convertToResolvedPropertiesFile(DirectedAcyclicGraph<Dep> graph) { final PropFile props = new PropFile(Context.named("resolved-deps"), PropFile.Loc.Local); Graphs.visit(graph, new Graphs.Visitor<Dep>() { @Override public void visit(Vertex<Dep> vertex) { Dep dep = vertex.getValue(); // exclude transitive transient dependencies if (!vertex.isRoot() && dep.dependencyAtom.transientDep) { return; } String dependencyAtomKey = dep.dependencyAtom.getPropertyName() + ":" + dep.dependencyAtom.getPropertyValue(); String location = FileUtil.pathFromParts(dep.localRepositoryDirectory, dep.dependencyAtom.getArtifactName()); if (!props.contains(dependencyAtomKey)) { props.add(dependencyAtomKey, location); } } }); return props; } /** * @param nullOnFNF if true then null is returned if the file is not found; otherwise, an empty {@link Properties} * is returned * @return the contents of ${project.build.dir}/${resolved-deps.properties} or an empty {@link Properties} if no * such file is found and {@code nullOnFNF} is false otherwise null if no such file is found and * {@code nullOnFNF} is true. */ public static PropFile getResolvedProperties(boolean nullOnFNF) { Scope scope = Scope.named(Props.get("scope", Context.named("ply")).value()); return getResolvedProperties(PlyUtil.LOCAL_CONFIG_DIR, scope, nullOnFNF); } /** * @param projectConfigDir the configuration directory from which to load properties like {@literal project.build.dir} * @param scope the scope of the resolved-deps property file. * @param nullOnFNF if true then null is returned if the file is not found; otherwise, an empty {@link Properties} * is returned * @return the contents of ${project.build.dir}/${resolved-deps.properties} relative to {@code projectConfigDir} or * an empty {@link Properties} if no such file is found and {@code nullOnFNF} is false otherwise null if no * such file is found and {@code nullOnFNF} is true. */ public static PropFile getResolvedProperties(File projectConfigDir, Scope scope, boolean nullOnFNF) { String buildDir = Props.get("build.dir", Context.named("project"), Props.getScope(), projectConfigDir).value(); File dependenciesFile = FileUtil.fromParts(FileUtil.getCanonicalPath(FileUtil.fromParts(projectConfigDir.getPath(), "..", "..")), buildDir, "resolved-deps" + scope.getFileSuffix() + ".properties"); PropFile resolvedDeps = new PropFile(Context.named("resolved-deps"), PropFile.Loc.Local); if (!dependenciesFile.exists()) { return (nullOnFNF ? null : resolvedDeps); } return PropFiles.load(dependenciesFile.getPath(), false, nullOnFNF); } /** * Constructs a classpath string for {@code resolvedDependencies} and {@code supplemental} * @param resolvedDependencies to add to the classpath * @param supplemental file references to add to the classpath * @return the classpath made up of {@code resolvedDependencies} and {@code supplemental}. */ public static String getClasspath(PropFile resolvedDependencies, String ... supplemental) { StringBuilder classpath = new StringBuilder(); for (Prop resolvedDependency : resolvedDependencies.props()) { if (DependencyAtom.isTransient(resolvedDependency.name)) { continue; } classpath.append(resolvedDependency.value()); classpath.append(File.pathSeparator); } for (String sup : supplemental) { classpath.append(sup); } return classpath.toString(); } /** * @return a {@link DependencyAtom} representing this project */ public static DependencyAtom getProjectDep() { Context projectContext = Context.named("project"); String namespace = Props.get("namespace", projectContext).value(); String name = Props.get("name", projectContext).value(); String version = Props.get("version", projectContext).value(); String artifactName = Props.get("artifact.name", projectContext).value(); String defaultArtifactName = name + "-" + version + "." + DependencyAtom.DEFAULT_PACKAGING; // don't pollute by placing artifactName explicitly even though it's the default if (artifactName.equals(defaultArtifactName)) { return new DependencyAtom(namespace, name, version); } else { return new DependencyAtom(namespace, name, version, artifactName); } } private static String getDependencyPathForRepo(DependencyAtom dependencyAtom, String dependencyDirectoryPath) { return FileUtil.pathFromParts(dependencyDirectoryPath, dependencyAtom.getArtifactName()); } /** * Resolves {@code repositoryAtom} to a canonical directory path and returns that value. * @param repositoryAtom assumed to be a {@link RepositoryAtom} to a local directory * @return the canonical directory path of {@code repositoryAtom} */ public static String getDirectoryPathForRepo(RepositoryAtom repositoryAtom) { try { String repoPath = repositoryAtom.getPropertyName(); if (repoPath.startsWith("file: repoPath = repoPath.substring(7); } return FileUtil.getCanonicalPath(new File(repoPath)); } catch (RuntimeException re) { // the path is likely invalid, attempt resolution anyway and let the subsequent code determine the // actual reason the path is invalid. } return repositoryAtom.getPropertyName(); } private static String getDependencyDirectoryPathForRepo(DependencyAtom dependencyAtom, RepositoryAtom repositoryAtom) { String startPath = repositoryAtom.getPropertyName(); if (!startPath.contains(":")) { // a file path without prefix, make absolute for URL handling startPath = "file://" + getDirectoryPathForRepo(repositoryAtom); } RepositoryAtom.Type type = repositoryAtom.getResolvedType(); String namespace = (type == RepositoryAtom.Type.ply ? dependencyAtom.namespace : dependencyAtom.namespace.replaceAll("\\.", File.separator)); String endPath = FileUtil.pathFromParts(namespace, dependencyAtom.name, dependencyAtom.version); // hygiene the start separator if (endPath.startsWith("/") || endPath.startsWith("\\")) { endPath = endPath.substring(1, endPath.length()); } return FileUtil.pathFromParts(startPath, endPath); } private static URL getUrl(String path) { try { return new URI(path).toURL(); } catch (URISyntaxException urise) { Output.print(urise); } catch (MalformedURLException murle) { Output.print(murle); } return null; } private static PropFile getDependenciesFile(DependencyAtom dependencyAtom, RepositoryAtom repositoryAtom, String repoDepDir) { if (repositoryAtom.getResolvedType() == RepositoryAtom.Type.ply) { // no dependencies file just means no dependencies, skip. URL url = null; try { url = new URL(repoDepDir); } catch (MalformedURLException murle) { Output.print(murle); } if ((url == null) || !new File(url.getFile()).exists()) { return null; } return getDependenciesFromPlyRepo(FileUtil.pathFromParts(repoDepDir, "dependencies.properties")); } else { // maven pom files are never saved with classifiers DependencyAtom pom = dependencyAtom.withoutClassifier().with("pom"); String pomName = pom.getArtifactName(); return getDependenciesFromMavenRepo(FileUtil.pathFromParts(repoDepDir, pomName), repositoryAtom); } } private static PropFile getDependenciesFromPlyRepo(String urlPath) { try { URL url = new URL(urlPath); PropFile loaded = PropFiles.load(url.getFile(), false, false); if (loaded.isEmpty()) { return null; } else { return loaded; } } catch (MalformedURLException murle) { Output.print(murle); } return null; } private static PropFile getDependenciesFromMavenRepo(String pomUrlPath, RepositoryAtom repositoryAtom) { MavenPomParser mavenPomParser = new MavenPomParser(); MavenPom mavenPom = mavenPomParser.parsePom(pomUrlPath, repositoryAtom); return (mavenPom == null ? new PropFile(Context.named("dependencies"), PropFile.Loc.Local) : mavenPom.dependencies); } private static void storeDependenciesFile(PropFile transitiveDependencies, String localRepoDepDirPath) { PropFiles.store(transitiveDependencies, FileUtil.pathFromParts(localRepoDepDirPath, "dependencies.properties"), true); } private Deps() { } }
package org.jgrapes.net; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.ArrayDeque; import java.util.HashSet; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutorService; import org.jgrapes.core.Channel; import org.jgrapes.core.Component; import org.jgrapes.core.Components; import org.jgrapes.core.EventPipeline; import org.jgrapes.core.Manager; import org.jgrapes.core.annotation.Handler; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.IOSubchannel.DefaultSubchannel; import org.jgrapes.io.NioHandler; import org.jgrapes.io.events.Closed; import org.jgrapes.io.events.HalfClosed; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.NioRegistration; import org.jgrapes.io.events.NioRegistration.Registration; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.ManagedBuffer; import org.jgrapes.io.util.ManagedBufferPool; /** * Provides a base class for the {@link TcpServer} and the {@link TcpConnector}. */ @SuppressWarnings({ "PMD.ExcessiveImports", "PMD.ExcessivePublicCount", "PMD.NcssCount", "PMD.EmptyCatchBlock", "PMD.AvoidDuplicateLiterals", "PMD.ExcessiveClassLength" }) public abstract class TcpConnectionManager extends Component { private int bufferSize; protected final Set<TcpChannel> channels = new HashSet<>(); private ExecutorService executorService; /** * Creates a new server using the given channel. * * @param componentChannel the component's channel */ public TcpConnectionManager(Channel componentChannel) { super(componentChannel); } /** * Sets the buffer size for the send an receive buffers. * If no size is set, the system defaults will be used. * * @param bufferSize the size to use for the send and receive buffers * @return the TCP connection manager for easy chaining */ public TcpConnectionManager setBufferSize(int bufferSize) { this.bufferSize = bufferSize; return this; } /** * Return the configured buffer size. * * @return the bufferSize */ public int bufferSize() { return bufferSize; } /** * Sets an executor service to be used by the event pipelines * that process the data from the network. Setting this * to an executor service with a limited number of threads * allows to control the maximum load from the network. * * @param executorService the executorService to set * @return the TCP connection manager for easy chaining * @see Manager#newEventPipeline(ExecutorService) */ public TcpConnectionManager setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * Returns the executor service. * * @return the executorService */ public ExecutorService executorService() { return executorService; } /** * Writes the data passed in the event. * * The end of record flag is used to determine if a channel is * eligible for purging. If the flag is set and all output has * been processed, the channel is purgeable until input is * received or another output event causes the state to be * reevaluated. * * @param event the event * @param channel the channel * @throws InterruptedException the interrupted exception */ @Handler public void onOutput(Output<ByteBuffer> event, TcpChannel channel) throws InterruptedException { if (channels.contains(channel)) { channel.write(event); } } /** * Removes the channel from the set of registered channels. * * @param channel the channel * @return true, if channel was registered */ protected boolean removeChannel(TcpChannel channel) { synchronized (channels) { return channels.remove(channel); } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return Components.objectName(this); } /** * The close state. */ private enum ConnectionState { OPEN, DELAYED_EVENT, DELAYED_REQUEST, HALF_CLOSED, CLOSED } /** * The purgeable state. */ private enum PurgeableState { NO, PENDING, YES } /** * The internal representation of a connection. */ protected class TcpChannel extends DefaultSubchannel implements NioHandler { private final SocketChannel nioChannel; private EventPipeline downPipeline; private final ManagedBufferPool<ManagedBuffer<ByteBuffer>, ByteBuffer> readBuffers; private Registration registration; private final Queue< ManagedBuffer<ByteBuffer>.ByteBufferView> pendingWrites = new ArrayDeque<>(); private ConnectionState connState = ConnectionState.OPEN; private PurgeableState purgeable = PurgeableState.NO; private long becamePurgeableAt; /** * @param nioChannel the channel * @throws IOException if an I/O error occured */ public TcpChannel(SocketChannel nioChannel) throws IOException { super(channel(), newEventPipeline()); this.nioChannel = nioChannel; if (executorService == null) { downPipeline = newEventPipeline(); } else { downPipeline = newEventPipeline(executorService); } String channelName = Components.objectName(TcpConnectionManager.this) + "." + Components.objectName(this); int writeBufferSize = bufferSize == 0 ? nioChannel.socket().getSendBufferSize() : bufferSize; setByteBufferPool(new ManagedBufferPool<>(ManagedBuffer::new, () -> { return ByteBuffer.allocate(writeBufferSize); }, 2) .setName(channelName + ".upstream.buffers")); int readBufferSize = bufferSize == 0 ? nioChannel.socket().getReceiveBufferSize() : bufferSize; readBuffers = new ManagedBufferPool<>(ManagedBuffer::new, () -> { return ByteBuffer.allocate(readBufferSize); }, 2) .setName(channelName + ".downstream.buffers"); // Register with dispatcher nioChannel.configureBlocking(false); TcpConnectionManager.this.fire( new NioRegistration(this, nioChannel, 0, TcpConnectionManager.this), Channel.BROADCAST); } /** * Gets the nio channel. * * @return the nioChannel */ public SocketChannel nioChannel() { return nioChannel; } /** * Gets the read buffers. * * @return the readBuffers */ public ManagedBufferPool<ManagedBuffer<ByteBuffer>, ByteBuffer> readBuffers() { return readBuffers; } /** * Gets the down pipeline. * * @return the downPipeline */ public EventPipeline downPipeline() { return downPipeline; } /** * Invoked when registration has completed. * * @param event the completed event * @throws InterruptedException if the execution was interrupted * @throws IOException if an I/O error occurred */ public void registrationComplete(NioRegistration event) throws InterruptedException, IOException { registration = event.get(); registration.updateInterested(SelectionKey.OP_READ); } /** * Checks if is purgeable. * * @return true, if is purgeable */ public boolean isPurgeable() { return purgeable == PurgeableState.YES; } /** * Gets the the time when the connection became purgeable. * * @return the time */ public long becamePurgeableAt() { return becamePurgeableAt; } /** * Write the data on this channel. * * @param event the event */ public void write(Output<ByteBuffer> event) throws InterruptedException { synchronized (pendingWrites) { if (!nioChannel.isOpen()) { return; } ManagedBuffer<ByteBuffer>.ByteBufferView reader = event.buffer().newByteBufferView(); if (!pendingWrites.isEmpty()) { reader.managedBuffer().lockBuffer(); purgeable = event.isEndOfRecord() ? PurgeableState.PENDING : PurgeableState.NO; pendingWrites.add(reader); return; } try { nioChannel.write(reader.get()); } catch (IOException e) { forceClose(e); return; } if (!reader.get().hasRemaining()) { if (event.isEndOfRecord()) { becamePurgeableAt = System.currentTimeMillis(); purgeable = PurgeableState.YES; } else { purgeable = PurgeableState.NO; } return; } reader.managedBuffer().lockBuffer(); purgeable = event.isEndOfRecord() ? PurgeableState.PENDING : PurgeableState.NO; pendingWrites.add(reader); registration.updateInterested( SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } @Override public void handleOps(int ops) throws InterruptedException { if ((ops & SelectionKey.OP_READ) != 0) { handleReadOp(); } if ((ops & SelectionKey.OP_WRITE) != 0) { handleWriteOp(); } } /** * Gets a buffer from the pool and reads available data into it. * Sends the result as event. * * @throws InterruptedException * @throws IOException */ @SuppressWarnings("PMD.EmptyCatchBlock") private void handleReadOp() throws InterruptedException { ManagedBuffer<ByteBuffer> buffer; buffer = readBuffers.acquire(); try { int bytes = buffer.fillFromChannel(nioChannel); if (bytes == 0) { buffer.unlockBuffer(); return; } if (bytes > 0) { purgeable = PurgeableState.NO; downPipeline.fire(Input.fromSink(buffer, false), this); return; } } catch (IOException e) { // Buffer already unlocked by fillFromChannel forceClose(e); return; } // EOF (-1) from other end buffer.unlockBuffer(); synchronized (nioChannel) { if (connState == ConnectionState.HALF_CLOSED) { // Other end confirms our close, complete close try { nioChannel.close(); } catch (IOException e) { // Ignored for close } connState = ConnectionState.CLOSED; downPipeline.fire(new Closed(), this); return; } } // Other end initiates close downPipeline.executorService().submit(() -> { try { // Inform downstream and wait until everything has settled. downPipeline.fire(new HalfClosed(), this).get(); // All settled. removeChannel(this); downPipeline.fire(new Closed(), this); // Close our end when everything has been written. synchronized (pendingWrites) { synchronized (nioChannel) { try { if (!pendingWrites.isEmpty()) { // Pending writes, delay close connState = ConnectionState.DELAYED_REQUEST; return; } // Nothing left to do, close nioChannel.close(); connState = ConnectionState.CLOSED; } catch (IOException e) { // Ignored for close } } } } catch (InterruptedException e) { // Nothing to do about this } }); } /** * Checks if there is still data to be written. This may be * a left over in an incompletely written buffer or a complete * pending buffer. * * @throws IOException * @throws InterruptedException */ @SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.EmptyCatchBlock", "PMD.AvoidBranchingStatementAsLastInLoop" }) private void handleWriteOp() throws InterruptedException { while (true) { ManagedBuffer<ByteBuffer>.ByteBufferView head = null; synchronized (pendingWrites) { if (pendingWrites.isEmpty()) { // Nothing left to write, stop getting ops registration.updateInterested(SelectionKey.OP_READ); // Was the connection closed while we were writing? if (connState == ConnectionState.DELAYED_REQUEST || connState == ConnectionState.DELAYED_EVENT) { synchronized (nioChannel) { try { if (connState == ConnectionState.DELAYED_REQUEST) { // Delayed close request from other end, // complete nioChannel.close(); connState = ConnectionState.CLOSED; } if (connState == ConnectionState.DELAYED_EVENT) { // Delayed close from this end, initiate nioChannel.shutdownOutput(); connState = ConnectionState.HALF_CLOSED; } } catch (IOException e) { // Ignored for close } } } else { if (purgeable == PurgeableState.PENDING) { purgeable = PurgeableState.YES; } } break; // Nothing left to do } head = pendingWrites.peek(); if (!head.get().hasRemaining()) { // Nothing left in head buffer, try next head.managedBuffer().unlockBuffer(); pendingWrites.remove(); continue; } } try { nioChannel.write(head.get()); // write... } catch (IOException e) { forceClose(e); return; } break; // ... and wait for next op } } /** * Closes this channel. * * @throws IOException if an error occurs * @throws InterruptedException if the execution was interrupted */ public void close() throws IOException, InterruptedException { if (!removeChannel(this)) { return; } synchronized (pendingWrites) { if (!pendingWrites.isEmpty()) { // Pending writes, delay close until done connState = ConnectionState.DELAYED_EVENT; return; } // Nothing left to do, proceed synchronized (nioChannel) { if (nioChannel.isOpen()) { // Initiate close, must be confirmed by other end nioChannel.shutdownOutput(); connState = ConnectionState.HALF_CLOSED; } } } } @SuppressWarnings("PMD.EmptyCatchBlock") private void forceClose(Throwable error) throws InterruptedException { try { nioChannel.close(); connState = ConnectionState.CLOSED; } catch (IOException e) { // Closed only to make sure, any failure can be ignored. } if (removeChannel(this)) { Closed evt = new Closed(error); downPipeline.fire(evt, this); } } /* * (non-Javadoc) * * @see org.jgrapes.io.IOSubchannel.DefaultSubchannel#toString() */ @SuppressWarnings("PMD.CommentRequired") public String toString() { return IOSubchannel.toString(this); } } }
package com.maxiee.heartbeat.data; import android.content.Context; import android.util.Log; import com.maxiee.heartbeat.common.TimeUtils; import com.maxiee.heartbeat.database.utils.EventUtils; import com.maxiee.heartbeat.database.utils.ImageUtils; import com.maxiee.heartbeat.database.utils.ThoughtUtils; import com.maxiee.heartbeat.model.Event; import com.maxiee.heartbeat.ui.adapter.DayCardEventAdapter; import com.maxiee.heartbeat.ui.adapter.TodayEventAdapter; public class DataManager { private static final String TAG = DataManager.class.getSimpleName(); private Context mContext; private EventManager mEventManager; private TodayManager mTodayManager; // private EventListAdapter mEventAdapter; private DayCardEventAdapter mEventAdapter; private TodayEventAdapter mTodayAdapter; private int mToday; private static DataManager mInstance; public static DataManager getInstance(Context context) { if (mInstance == null) { mInstance = new DataManager(context.getApplicationContext()); } return mInstance; } private DataManager(Context context) { mContext = context; mEventManager = new EventManager(mContext); mTodayManager = new TodayManager(mContext); // mEventAdapter = new EventListAdapter(mEventManager.getEvents()); mEventAdapter = new DayCardEventAdapter(mEventManager.getDayCardData()); mTodayAdapter = new TodayEventAdapter(mTodayManager.getEvents()); mToday = TimeUtils.getToday(); } public void reload() { mEventManager.reload(); mTodayManager.reload(); mEventAdapter.setData(mEventManager.getDayCardData()); mTodayAdapter.setData(mTodayManager.getEvents()); } public EventManager getEventManager() {return mEventManager;} // public EventListAdapter getEventAdapter() { // return mEventAdapter; public DayCardEventAdapter getEventAdapter() { return mEventAdapter; } public TodayEventAdapter getTodayAdapter() { return mTodayAdapter; } public boolean isEventEmpty() { return mEventManager.isEmpty(); } public boolean isTodayEmpty() { return mTodayManager.isEmpty(); } public int getTodayEventCount() { return mTodayManager.countTodayEvent(); } public int getTodayThoughtCount() { return mTodayManager.countTodayThought(); } public void notifyDataSetChanged() { mEventAdapter.notifyDataSetChanged(); mTodayAdapter.notifyDataSetChanged(); } public void addEvent(Event event) { // TODO move the code of DB-adding here mEventManager.addEvent(event); mTodayManager.addEvent(event); // TODO wtf mEventManager.reloadDayCardData(); } public void deleteEvent(long key) { EventUtils.deleteEvent(mContext, key); ImageUtils.deleteByEventId(mContext, key); ThoughtUtils.deleteByEventId(mContext, key); mEventManager.deleteEvent(key); mTodayManager.deleteEvent(key); // TODO wtf mEventManager.reloadDayCardData(); notifyDataSetChanged(); checkNewDay(); } public void updateEvent(long key) { Event e = EventUtils.getEvent(mContext, key); if (e == null) return; mEventManager.updateEvent(e); mTodayManager.updateEvent(e); // TODO wtf mEventManager.reloadDayCardData(); checkNewDay(); } public void checkNewDay() { int day = TimeUtils.getToday(); if (day != mToday) { mToday = day; mTodayManager.reload(); notifyDataSetChanged(); } } public void logInfo() { Log.d(TAG, "EventList size:" + String.valueOf(mEventManager.size())); Log.d(TAG, "TodayList size:" + String.valueOf(mTodayManager.size())); } }
package org.python.pydev.plugin; import java.io.IOException; import java.net.ConnectException; import java.net.Socket; import java.util.Random; /** * Utility class to find a port to debug on. * * Straight copy of package org.eclipse.jdt.launching.SocketUtil. * I just could not figure out how to import that one. * No dependencies kept it on the classpath reliably */ public class SocketUtil { private static final Random fgRandom= new Random(System.currentTimeMillis()); /** * Returns a free port number on the specified host within the given range, * or -1 if none found. * * @param host name or IP addres of host on which to find a free port * @param searchFrom the port number from which to start searching * @param searchTo the port number at which to stop searching * @return a free port in the specified range, or -1 of none found */ public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) { Exception exception=null; for (int i= 0; i < 15; i++) { Socket s= null; int port= getRandomPort(searchFrom, searchTo); try { s= new Socket(host, port); } catch (ConnectException e) { return port; } catch (IOException e) { exception = e; } finally { if (s != null) { try { s.close(); } catch (IOException ioe) { } } } } String message = "Unable to find an unused local port (is your firewall enabled?) [host:"+host+" from:"+searchFrom+" to:"+searchTo+"]"; if(exception != null){ throw new RuntimeException(message, exception); }else{ throw new RuntimeException(message); } } private static int getRandomPort(int low, int high) { return (int)(fgRandom.nextFloat() * (high-low)) + low; } }
package com.mxn.soul.specialalbum; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Rect; import android.os.Build; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewConfigurationCompat; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewParent; import android.view.animation.Interpolator; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class SlidingCard extends LinearLayout { private static final String TAG = "SlidingCard"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = true; public static final int MAX_SETTLE_DURATION = 600; private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private PhotoContent photoVo; public static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; private boolean mEnabled = true; private List<View> mIgnoredViews = new ArrayList<>(); private View mContent; private int mPrevItem = DEFAULT_ITEM; private int mCurItem = DEFAULT_ITEM; private static final int DEFAULT_ITEM = 0; private boolean mFirstLayout = true; private Scroller mScroller; private boolean mScrollingCacheEnabled; private boolean mScrolling; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private int mTouchSlop; private float mInitialMotionX; // variables for drawing private float mScrollX = 0.0f; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ protected int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. Used by * {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ protected VelocityTracker mVelocityTracker; private int mMinimumVelocity; protected int mMaximumVelocity; private int mFlingDistance; private OnPageChangeListener mOnPageChangeListener; private int listIndex; //private ImageView headShadyImageView; private SmoothImageView headImageView; private TextView headTextView; private View contentView; public int getListIndex() { return listIndex; } public void setListIndex(int listIndex) { this.listIndex = listIndex; } public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /** * Indicates that the pager is in an idle, settled state. The current page * is fully in view and no animation is in progress. */ public static final int SCROLL_STATE_IDLE = 0; /** * Indicates that the pager is currently being dragged by the user. */ public static final int SCROLL_STATE_DRAGGING = 1; /** * Indicates that the pager is in the process of settling to a final * position. */ public static final int SCROLL_STATE_SETTLING = 2; private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either * as part of a programmatically initiated smooth scroll or a user * initiated touch scroll. * * @param position Position index of the first page currently being * displayed. Page position+1 will be visible if * positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at * position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ public void onPageScrolled(SlidingCard v, int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. * Animation is not necessarily complete. * <p/> * Position index of the new selected page. */ public void onPageSelected(SlidingCard v, int prevPosition, int curPosition); /** * This method will be invoked when a new page becomes selected. after * animation has completed. * <p/> * Position index of the new selected page. */ public void onPageSelectedAfterAnimation(SlidingCard v, int prevPosition, int curPosition); /** * Called when the scroll state changes. Useful for discovering when the * user begins dragging, when the pager is automatically settling to the * current page, or when it is fully stopped/idle. * * @param state The new scroll state. * @see SlidingCard#SCROLL_STATE_IDLE * @see SlidingCard#SCROLL_STATE_DRAGGING * @see SlidingCard#SCROLL_STATE_SETTLING */ public void onPageScrollStateChanged(SlidingCard v, int state); } /** * Simple implementation of the {@link OnPageChangeListener} interface with * stub implementations of each method. Extend this if you do not intend to * override every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { public void onPageScrolled(SlidingCard v, int position, float positionOffset, int positionOffsetPixels) { // This space for rent } public void onPageSelected(SlidingCard v, int prevPosition, int curPosition) { // This space for rent } @Override public void onPageSelectedAfterAnimation(SlidingCard v, int prevPosition, int curPosition) { // This space for rent } public void onPageScrollStateChanged(SlidingCard v, int state) { // This space for rent } } public SlidingCard(Context context) { this(context, null); } public SlidingCard(Context context, AttributeSet attrs) { super(context, attrs); initSlidingCard(); setContent(new FrameLayout(context)); } void initSlidingCard() { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat .getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); final float density = context.getResources().getDisplayMetrics().density; mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int itemHeight = getContext().getResources().getDimensionPixelSize( R.dimen.card_item_height); int width = getDefaultSize(0, widthMeasureSpec); int height = getDefaultSize(0, heightMeasureSpec); setMeasuredDimension(width, itemHeight); final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width); final int contentHeight = getChildMeasureSpec(heightMeasureSpec, 0, height); mContent.measure(contentWidth, itemHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (w != oldw) { completeScroll(); scrollTo(getDestScrollX(mCurItem), getScrollY()); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; final int height = b - t; mContent.layout(0, 0, width, height); if (mFirstLayout) { scrollTo(getDestScrollX(mCurItem), getScrollY()); } mFirstLayout = false; } @Override public void computeScroll() { if (!mScroller.isFinished()) { if (mScroller.computeScrollOffset()) { int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); pageScrolled(x); } else { setScrollState(SCROLL_STATE_IDLE); } // Keep on drawing until the animation has finished. ViewCompat.postInvalidateOnAnimation(this); return; } } // Done with scroll, clean up state. completeScroll(); } @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); mScrollX = x; } private void pageScrolled(int xpos) { final int widthWithMargin = getWidth(); final int position = xpos / widthWithMargin; final int offsetPixels = xpos % widthWithMargin; final float offset = (float) offsetPixels / widthWithMargin; if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(this, position, offset, offsetPixels); } } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; disableLayers(); if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(this, newState); } } private void completeScroll() { boolean needPopulate = mScrolling; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } else { setScrollState(SCROLL_STATE_IDLE); } if (mOnPageChangeListener != null && mPrevItem != mCurItem) { mOnPageChangeListener.onPageSelectedAfterAnimation(this, mPrevItem, mCurItem); } } mScrolling = false; } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); if (enabled && isLowQuality) { child.setDrawingCacheBackgroundColor(Color.TRANSPARENT); child.setDrawingCacheQuality(DRAWING_CACHE_QUALITY_LOW); } } } } } } float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) FloatMath.sin(f); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis * @param velocity the velocity associated with a fling, if applicable. (0 * otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); setScrollState(SCROLL_STATE_IDLE); return; } setScrollingCacheEnabled(true); setScrollState(SCROLL_STATE_SETTLING); mScrolling = true; final int width = getWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio); int duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { final float pageDelta = (float) Math.abs(dx) / width; duration = (int) ((pageDelta + 1) * 100); duration = MAX_SETTLE_DURATION; } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); invalidate(); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { if (!always && mCurItem == item) { setScrollingCacheEnabled(false); return; } item = getTargetPage(item); final boolean dispatchSelected = mCurItem != item; mPrevItem = mCurItem; mCurItem = item; final int destX = getDestScrollX(mCurItem); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(this, mPrevItem, mCurItem); } if (smoothScroll) { smoothScrollTo(destX, 0, velocity); } else { completeScroll(); scrollTo(destX, 0); if (mOnPageChangeListener != null && mPrevItem != mCurItem) { mOnPageChangeListener.onPageSelectedAfterAnimation(this, mPrevItem, mCurItem); } } } int getTargetPage(int page) { page = (page > 1) ? 2 : ((page < 1) ? 0 : page); return page; } int getDestScrollX(int page) { switch (page) { case 0: return mContent.getLeft() - getCardWidth(); case 1: return mContent.getLeft(); case 2: return mContent.getLeft() + getCardWidth(); } return 0; } public void setCurrentItem(int item, boolean smoothScroll) { setCurrentItemInternal(item, smoothScroll, false); } @Override public void addView(View child) { try { super.removeAllViews(); } catch (Exception e) { Log.e("lq", String.valueOf(e.getMessage())); } mContent = child; super.addView(child); disableLayers(); } @Override public void removeView(View view) { try { super.removeView(view); } catch (Exception e) { Log.e("lq", String.valueOf(e.getMessage())); } disableLayers(); } public void setContent(int res) { setContent(LayoutInflater.from(getContext()).inflate(res, null)); } public void setContent(View v) { addView(v); } public void initCardChildView(PhotoContent userVo) { headImageView = (SmoothImageView) findViewById(R.id.user_imageview); headTextView = (TextView) findViewById(R.id.user_text); contentView = findViewById(R.id.sliding_card_content_view); if (userVo != null) { initImageLoad(userVo, headImageView); initTextView(userVo, headTextView); } } private void initTextView(PhotoContent vo, TextView textView) { switch (Integer.valueOf(vo.getId())) { case 1: textView.setText(""); break; case 2: textView.setText(""); break; case 3: textView.setText(""); break; } } private void initImageLoad(PhotoContent vo, SmoothImageView imageView) { switch (Integer.valueOf(vo.getId())) { case 1: imageView.setImageResource(R.drawable.img1); break; case 2: imageView.setImageResource(R.drawable.img2); break; case 3: imageView.setImageResource(R.drawable.img3); break; } } public boolean isCardClose() { return mCurItem == 0 || mCurItem == 2; } public int getCardWidth() { return mContent.getWidth(); } private void getHitRect(View v, Rect rect) { v.getHitRect(rect); ViewParent parent = v.getParent(); while (parent != null && parent != this) { View _parent = (View) parent; Rect parentRect = new Rect(); _parent.getHitRect(parentRect); rect.left += parentRect.left; rect.right += parentRect.left; rect.top += parentRect.top; rect.bottom += parentRect.top; parent = parent.getParent(); } } private boolean isInIgnoredView(MotionEvent ev) { Rect rect = new Rect(); for (View v : mIgnoredViews) { getHitRect(v, rect); if (rect.contains((int) ev.getX(), (int) ev.getY())) return true; } return false; } private boolean thisTouchAllowed(MotionEvent ev) { int x = (int) (ev.getX() + mScrollX); if (!isCardClose()) { return !isInIgnoredView(ev); } return false; } private boolean thisSlideAllowed(float dx) { if (!isCardClose()) { return true; } return false; } private int getLeftBound() { return mContent.getLeft() - getCardWidth(); } private int getRightBound() { return mContent.getLeft() + getCardWidth(); } private void startDrag() { mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); } private void endDrag() { mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void determineDrag(MotionEvent ev) { final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) return; final int pointerIndex = findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float dy = y - mLastMotionY; final float yDiff = Math.abs(dy); if (xDiff > mTouchSlop && xDiff > yDiff && thisSlideAllowed(dx)) { startDrag(); mLastMotionX = x; mLastMotionY = y; setScrollingCacheEnabled(true); } else if (xDiff > mTouchSlop) { mIsUnableToDrag = true; } } private int determineTargetPage(float pageOffset, int velocity, int deltaX) { int targetPage = mCurItem; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { if (velocity > 0 && deltaX > 0) { targetPage -= 1; } else if (velocity < 0 && deltaX < 0) { targetPage += 1; } } else { targetPage = (int) Math.round(mCurItem + pageOffset); } return targetPage; } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and // FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those // devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { handled = nextFocused.requestFocus(); } else if (direction == View.FOCUS_RIGHT) { if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants .getContantForFocusDirection(direction)); } return handled; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem - 1, true); return true; } return false; } boolean pageRight() { if (mCurItem <= 1) { setCurrentItem(mCurItem + 1, true); return true; } return false; } private void onSecondaryPointerUp(MotionEvent ev) { if (DEBUG) Log.v(TAG, "onSecondaryPointerUp called"); final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private int findPointerIndex(MotionEvent event, int pointerId) { int index = MotionEventCompat.findPointerIndex(event, pointerId); if (index == INVALID_POINTER) { index = 0; } return index; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mEnabled) return true; if (isCardClose()) return false; final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; if (DEBUG) if (action == MotionEvent.ACTION_DOWN) Log.v(TAG, "Received ACTION_DOWN"); if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP || (action != MotionEvent.ACTION_DOWN && mIsUnableToDrag)) { endDrag(); return false; } switch (action) { case MotionEvent.ACTION_MOVE: determineDrag(ev); break; case MotionEvent.ACTION_DOWN: mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = ev.getY(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); if (thisTouchAllowed(ev)) { completeScroll(); mIsBeingDragged = false; mIsUnableToDrag = false; } else { mIsUnableToDrag = true; } break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (!mIsBeingDragged) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!mEnabled) return true; if (isCardClose()) return false; if (!mIsBeingDragged && !thisTouchAllowed(ev)) return false; // if (!mIsBeingDragged && !mQuickReturn) // return false; final int action = ev.getAction(); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // Remember where the motion event started mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = ev.getY(); break; case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { determineDrag(ev); if (mIsUnableToDrag) return false; } if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final float leftBound = getLeftBound(); final float rightBound = getRightBound(); if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); final int scrollX = getScrollX(); final float pageOffset = (float) (scrollX - getDestScrollX(mCurItem)) / getCardWidth(); final int activePointerIndex = findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); int nextPage = determineTargetPage(pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { setCurrentItemInternal(mCurItem, true, true); mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int indexx = MotionEventCompat.getActionIndex(ev); mLastMotionX = MotionEventCompat.getX(ev, indexx); mActivePointerId = MotionEventCompat.getPointerId(ev, indexx); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); try { mLastMotionX = MotionEventCompat.getX(ev, findPointerIndex(ev, mActivePointerId)); } catch (Exception e) { } break; } return true; } @Override protected void dispatchDraw(Canvas canvas) { PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint .FILTER_BITMAP_FLAG); canvas.setDrawFilter(pfd); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child == null) return; } super.dispatchDraw(canvas); } private boolean isLowQuality = false; private void disableLayers() { ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_NONE, null); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { ViewCompat.setLayerType(getChildAt(i), ViewCompat.LAYER_TYPE_NONE, null); } } public PhotoContent getUserVo() { return photoVo; } public void setUserVo(PhotoContent photoVo) { this.photoVo = photoVo; initCardChildView(photoVo); } public void setUserImageShady(float offset) { if (offset >= 1) { offset = 0; } float imageAlpha = 0; if (offset > 0) { imageAlpha = 0.5f + offset; if (imageAlpha > 1f) { imageAlpha = 1; } } // headShadyImageView.setAlpha((int) (255 * imageAlpha)); // Drawable drawable = headShadyImageView.getBackground(); // if (drawable != null) { // int bgAlpha = (int) (255 * offset); // if (bgAlpha > 0 && bgAlpha < 160) { // bgAlpha = 40 + bgAlpha; // drawable.setAlpha(bgAlpha); } public View getContentView() { return contentView; } }
package org.genericsystem.layout; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; import org.genericsystem.cv.Img; import org.genericsystem.cv.Ocr; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.utils.Converters; public class Layout { private double x1; private double x2; private double y1; private double y2; private Map<String, Integer> labels = new HashMap<>(); private List<Layout> children = new ArrayList<>(); private Layout parent = null; public Layout(Layout parent, double x1, double x2, double y1, double y2) { this.parent = parent; this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } public Img getRoi(Img img) { return new Img(img, this); } public Rect getRect(Img imgRoot) { Rect parentRect = getParent() != null ? getParent().getRect(imgRoot) : new Rect(0, 0, imgRoot.width(), imgRoot.height()); return new Rect(new Point(parentRect.tl().x + parentRect.width * getX1(), parentRect.tl().y + parentRect.height * getY1()), new Point(parentRect.tl().x + parentRect.width * getX2(), parentRect.tl().y + parentRect.height * getY2())); } public Rect getLargeRect(Img imgRoot, int delta) { Rect rect = getRect(imgRoot); return new Rect(new Point(rect.tl().x - delta, rect.tl().y - delta), new Point(rect.br().x + delta, rect.br().y + delta)); } public Layout traverse(Img img, BiConsumer<Img, Layout> visitor) { for (Layout shard : getChildren()) shard.traverse(shard.getRoi(img), visitor); visitor.accept(img, this); return this; } public void draw(Img img, Scalar color, int thickness) { traverse(getRoi(img), (roi, shard) -> { if (shard.getChildren().isEmpty()) Imgproc.rectangle(roi.getSrc(), new Point(0, 0), new Point(roi.width() - 1, roi.height() - 1), color, thickness); }); } public void ocrTree(Img rootImg, int delta) { traverse(rootImg, (root, layout) -> { if (layout.getChildren().isEmpty()) { String ocr = Ocr.doWork(new Mat(rootImg.getSrc(), layout.getLargeRect(rootImg, delta))); if (!"".equals(ocr)) { Integer count = labels.get(ocr); layout.getLabels().put(ocr, 1 + (count != null ? count : 0)); System.out.println(layout.getLabels()); } } }); } public void addChild(Layout child) { if (!children.contains(child)) children.add(child); } public void removeChild(Layout child) { if (children.contains(child)) children.remove(child); } public boolean equiv(Layout s, double xTolerance, double yTolerance) { if (Math.abs(s.x1 - x1) <= xTolerance && Math.abs(s.x2 - x2) <= xTolerance && Math.abs(s.y1 - y1) <= yTolerance && Math.abs(s.y2 - y2) <= yTolerance) return true; return false; } public List<Layout> getChildren() { return children; } public double getX1() { return x1; } public void setX1(double x1) { this.x1 = x1; } public double getX2() { return x2; } public void setX2(double x2) { this.x2 = x2; } public double getY1() { return y1; } public void setY1(double y1) { this.y1 = y1; } public double getY2() { return y2; } public void setY2(double y2) { this.y2 = y2; } public Layout getParent() { return parent; } public void setParent(Layout parent) { this.parent = parent; } public Map<String, Integer> getLabels() { return labels; } public boolean hasChildren() { if (children != null && children.size() >= 1) return true; return false; } public String recursivToString() { StringBuilder sb = new StringBuilder(); recursivToString(this, sb, 0); return sb.toString(); } private void recursivToString(Layout shard, StringBuilder sb, int depth) { sb.append("depth : " + depth + " : "); sb.append("((" + shard.x1 + "-" + shard.y1 + "),(" + shard.x2 + "-" + shard.y2 + "))".toString()); if (shard.getChildren().isEmpty()) sb.append(" : Label : "); for (String label : shard.labels.keySet()) sb.append("/" + label); if (shard.hasChildren()) { depth++; for (Layout s : shard.getChildren()) { sb.append("\n"); for (int i = 0; i < depth; i++) sb.append(" "); recursivToString(s, sb, depth); } } } @Override public String toString() { return "tl : (" + this.x1 + "," + this.y1 + "), br :(" + this.x2 + "," + this.y2 + ")"; } public Layout tighten(Img binary, float concentration) { List<Float> Vhist = new ArrayList<>(); List<Float> Hhist = new ArrayList<>(); Converters.Mat_to_vector_float(binary.projectVertically().getSrc(), Vhist); Converters.Mat_to_vector_float(binary.projectHorizontally().transpose().getSrc(), Hhist); for (int i = 0; i < binary.getSrc().rows(); i++) { for (int j = 0; j < binary.getSrc().cols(); j++) { double value = binary.getSrc().get(i, j)[0]; if (value > 255.0) System.out.println(value); } } // System.out.println("Vhist before smooth: " + Vhist.toString()); Vhist = smoothHisto(concentration, Vhist, true, binary); // System.out.println("Vhist after smooth: " + Vhist.toString()); // System.out.println("Hhist before smooth: " + Hhist.toString()); Hhist = smoothHisto(concentration, Hhist, false, binary); // System.out.println("Hhist after smooth: " + Hhist.toString()); double[] x = getHistoLimits(Hhist); double[] y = getHistoLimits(Vhist); // System.out.println("x " + Arrays.toString(x) + " y " + Arrays.toString(y)); if (x[0] <= x[1] || y[0] <= y[1]) { return new Layout(this.getParent(), getX1() + x[0] * (getX2() - getX1()), getX1() + x[1] * (getX2() - getX1()), getY1() + y[0] * (getY2() - getY1()), getY1() + y[1] * (getY2() - getY1())); } else { return new Layout(this.getParent(), 0, 0, 0, 0); } } public static double[] getHistoLimits(List<Float> hist) { int start = 0; int end = hist.size() - 1; while (start < hist.size() && hist.get(start) >= 255.0) start++; while (end >= 0 && hist.get(end) >= 255.0) end return new double[] { Integer.valueOf(start).doubleValue() / hist.size(), Integer.valueOf(end + 1).doubleValue() / hist.size() }; } public List<Layout> split(Size morph, float concentration, Img binary) { List<Float> histoVertical = new ArrayList<>(); List<Float> histoHorizontal = new ArrayList<>(); Converters.Mat_to_vector_float(binary.projectVertically().getSrc(), histoVertical); Converters.Mat_to_vector_float((binary.projectHorizontally().transpose()).getSrc(), histoHorizontal); histoVertical = smoothHisto(concentration, histoVertical, true, binary); histoHorizontal = smoothHisto(concentration, histoHorizontal, false, binary); int kV = new Double(Math.floor(morph.height * histoVertical.size())).intValue(); int kH = new Double(Math.floor(morph.width * histoHorizontal.size())).intValue(); boolean[] closedV = getClosedFromHisto(kV, histoVertical); boolean[] closedH = getClosedFromHisto(kH, histoHorizontal); return extractZones(closedV, closedH, binary, concentration); } private static List<Float> smoothHisto(float concentration, List<Float> histo, boolean vertical, Img binary) { float min = concentration * 255; float max = (1 - concentration) * 255; for (int i = 0; i < histo.size(); i++) { float value = histo.get(i); if (histo.size() > 32) if (value <= min || value >= max) { histo.set(i, 255f); // System.out.println("mask black " + (vertical ? "line" : "column") + " " + i); if (vertical) Imgproc.line(binary.getSrc(), new Point(0, i), new Point(binary.getSrc().width() - 1, i), new Scalar(255)); else Imgproc.line(binary.getSrc(), new Point(i, 0), new Point(i, binary.getSrc().rows() - 1), new Scalar(255)); } } return histo; } private static boolean[] getClosedFromHisto(int k, List<Float> histo) { boolean[] closed = new boolean[histo.size()]; Function<Integer, Boolean> isWhite = i -> histo.get(i) == 255; for (int i = 0; i < histo.size() - 1; i++) if (!isWhite.apply(i) && isWhite.apply(i + 1)) { for (int j = k + 1; j > 0; j if (i + j < histo.size()) { if (!isWhite.apply(i + j)) { Arrays.fill(closed, i, i + j + 1, true); i += j - 1; break; } closed[i] = !isWhite.apply(i); } } else closed[i] = !isWhite.apply(i); if (!closed[histo.size() - 1]) closed[histo.size() - 1] = !isWhite.apply(histo.size() - 1); return closed; } private List<Layout> extractZones(boolean[] resultV, boolean[] resultH, Img binary, float concentration) { List<Layout> shardsV = getShards(resultV, true); List<Layout> shardsH = getShards(resultH, false); // System.out.println("Binary size : " + binary.size()); // System.out.println("Size spit : " + shardsV.size() + " " + shardsH.size()); List<Layout> shards = new ArrayList<>(); for (Layout shardv : shardsV) for (Layout shardh : shardsH) { Layout target = new Layout(this, shardh.x1, shardh.x2, shardv.y1, shardv.y2); // (0.5223880597014925-0.3358302122347066),(1.0-0.34519350811485644) Img roi = target.getRoi(binary); // System.out.println("roi : rows :" + roi.rows() + " , cols :" + roi.cols()); if (roi.rows() != 0 && roi.cols() != 0) shards.add(target.tighten(roi, concentration)); } return shards; } private List<Layout> getShards(boolean[] result, boolean vertical) { List<Layout> shards = new ArrayList<>(); Integer start = result[0] ? 0 : null; assert result.length >= 1; for (int i = 0; i < result.length - 1; i++) if (!result[i] && result[i + 1]) start = i + 1; else if (result[i] && !result[i + 1]) { shards.add(vertical ? new Layout(this, 0, 1, Integer.valueOf(start).doubleValue() / result.length, (Integer.valueOf(i).doubleValue() + 1) / result.length) : new Layout(this, Integer.valueOf(start).doubleValue() / result.length, (Integer.valueOf(i).doubleValue() + 1) / result.length, 0, 1)); start = null; } if (result[result.length - 1]) { shards.add(vertical ? new Layout(this, 0, 1, Integer.valueOf(start).doubleValue() / result.length, Integer.valueOf(result.length).doubleValue() / result.length) : new Layout(this, Integer.valueOf(start).doubleValue() / result.length, Integer.valueOf(result.length).doubleValue() / result.length, 0, 1)); start = null; } return shards; } public Layout recursivSplit(Size morph, int level, float concentration, Img img, Img binary) { // System.out.println("level : " + level); // System.out.println("Layout : " + this); assert img.size().equals(binary.size()); if (level <= 0) { // Imgproc.rectangle(img.getSrc(), new Point(0, 0), new Point(img.width(), img.height()), new Scalar(255, 0, 0), -1); return this; } List<Layout> shards = split(morph, concentration, binary); shards.removeIf(shard -> ((shard.getY2() - shard.getY1()) * img.size().height) < 4 || ((shard.getX2() - shard.getX1()) * img.size().width) < 4); if (shards.isEmpty()) { // Imgproc.rectangle(img.getSrc(), new Point(0, 0), new Point(img.width(), img.height()), new Scalar(0, 0, 255), -1); return this; } if (shards.size() == 1) { return this; } for (Layout shard : shards) { shard.recursivSplit(morph, level - 1, concentration, shard.getRoi(img), shard.getRoi(binary)); this.addChild(shard); } return this; } }
package com.pr0gramm.app.services; import com.google.common.base.Joiner; import com.google.common.primitives.Longs; import com.google.gson.Gson; import com.google.inject.Inject; import com.google.inject.Singleton; import com.pr0gramm.app.LoggerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.List; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import rx.Observable; @Singleton public class MetaService { private static final Logger logger = LoggerFactory.getLogger(MetaService.class); private final Api api; @Inject public MetaService() { api = new RestAdapter.Builder() .setLog(new LoggerAdapter(logger)) .setEndpoint("http://pr0.wibbly-wobbly.de:5003") .setConverter(new GsonConverter(new Gson())) .setLogLevel(RestAdapter.LogLevel.BASIC) .build() .create(Api.class); } public Observable<InfoResponse> getInfo(Collection<Long> items) { if(items.isEmpty()) { return Observable.just(EMPTY_INFO); } return api.info(Joiner.on(",").join(items)); } private interface Api { @FormUrlEncoded @POST("/items") Observable<InfoResponse> info(@Field("ids") String itemIds); } @SuppressWarnings("unused") public static class InfoResponse { private long[] reposts; private List<SizeInfo> sizes; InfoResponse() { reposts = new long[0]; sizes = Collections.emptyList(); } public List<Long> getReposts() { return Longs.asList(reposts); } public List<SizeInfo> getSizes() { return sizes; } } @SuppressWarnings("unused") public static class SizeInfo { private long id; private int width; private int height; public long getId() { return id; } public int getWidth() { return width; } public int getHeight() { return height; } } public static final InfoResponse EMPTY_INFO = new InfoResponse(); }
package com.rey.material.demo; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.rey.material.app.DatePickerDialog; import com.rey.material.app.Dialog; import com.rey.material.app.DialogFragment; import com.rey.material.app.TimePickerDialog; import com.rey.material.widget.Button; import com.rey.material.widget.EditText; import com.rey.material.widget.FloatingActionButton; import com.rey.material.widget.Slider; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SetRuleFragment extends Fragment implements View.OnClickListener{ private TextView startTimeText; private TextView endTimeText; private TextView tv_discrete; private TextView dateText; private Button bt_start_time_picker; private Button bt_end_time_picker; private Button bt_sumbit; private Button bt_date_picker; private Button bt_cancel; private Activity main; private MyDB myDB; private Rule rule; private static long ruleId; public static SetRuleFragment newInstance(){ ruleId = -1; SetRuleFragment fragment = new SetRuleFragment(); return fragment; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("update", "ruleId when first created " + String.valueOf(ruleId)); View v = inflater.inflate(R.layout.fragment_setrule, container, false); bt_start_time_picker = (Button)v.findViewById(R.id.button_start_time_picker); bt_end_time_picker = (Button)v.findViewById(R.id.button_end_time_picker); bt_sumbit = (Button)v.findViewById(R.id.button_submit); bt_date_picker = (Button)v.findViewById(R.id.button_date_picker); bt_cancel = (Button)v.findViewById(R.id.button_cancel); startTimeText = (TextView)v.findViewById(R.id.start_time_text); endTimeText = (TextView)v.findViewById(R.id.end_time_text); dateText = (TextView)v.findViewById(R.id.date_text); Date date = new Date(); bt_start_time_picker.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); bt_end_time_picker.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); bt_date_picker.setText(SimpleDateFormat.getDateInstance().format(date)); final EditText editText = (EditText)v.findViewById(R.id.textfield_with_label); // editText.clearComposingText(); main = this.getActivity(); myDB = MyDB.getInstance(container.getContext()); bt_start_time_picker.setOnClickListener(this); bt_end_time_picker.setOnClickListener(this); bt_date_picker.setOnClickListener(this); // set default rule values DateFormat timeFormat = new SimpleDateFormat("HH:mm"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Slider sl_discrete = (Slider)v.findViewById(R.id.volume_slider); tv_discrete = (TextView)v.findViewById(R.id.slider_volume_text); //tv_discrete.setText(String.format("volume %d", sl_discrete.getValue())); sl_discrete.setOnPositionChangeListener(new Slider.OnPositionChangeListener() { @Override public void onPositionChanged(Slider view, float oldPos, float newPos, int oldValue, int newValue) { rule.setVolume(Integer.toString(newValue)); //tv_discrete.setText(String.format("volume %d", newValue)); } }); if (ruleId == -1){ bt_cancel.setVisibility(View.GONE); editText.getText().clear(); Log.d("TextTitle", editText.getText().toString()); rule = new Rule("Rule", dateFormat.format(date), timeFormat.format(date), timeFormat.format(date), "8"); bt_sumbit.setText("submit"); bt_sumbit.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ // Log.d("submit", "editText" + editText.getText().toString()); // if (editText.getText().toString() != "") rule.setTitle(editText.getText().toString()); myDB.insert(rule); Log.d("submit", rule.getTitle()); Log.d("submit", rule.getDate()); Log.d("submit", rule.getStart_time()); Log.d("submit", rule.getEnd_time()); Log.d("submit", rule.getVolume()); Toast.makeText(main, "Rule Submitted", Toast.LENGTH_SHORT).show(); } }); sl_discrete.setValue(8, true); } else{ bt_cancel.setVisibility(View.VISIBLE); rule = myDB.selectById(ruleId); editText.setText(rule.getTitle()); Log.d("TextTitle", editText.getText().toString()); String tmp; // TODO tmp = rule.getStart_time(); try { date = timeFormat.parse(tmp); } catch (ParseException e) { e.printStackTrace(); } bt_start_time_picker.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); tmp = rule.getEnd_time(); try { date = timeFormat.parse(tmp); } catch (ParseException e) { e.printStackTrace(); } bt_end_time_picker.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); tmp = rule.getDate(); try { date = dateFormat.parse(tmp); } catch (ParseException e) { e.printStackTrace(); } DateFormat dateFormatShown = new SimpleDateFormat("MMM dd, yyyy"); bt_date_picker.setText(dateFormatShown.format(date)); bt_sumbit.setText("update"); final long passinId = ruleId; bt_sumbit.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ rule.setTitle( editText.getText().toString()); myDB.updateById(passinId, rule.getTitle(), rule.getStart_time(), rule.getEnd_time(), rule.getVolume()); Toast.makeText(main, "Rule Updated", Toast.LENGTH_SHORT).show(); } }); sl_discrete.setValue(Integer.parseInt(rule.getVolume()), true); Log.d("TextTitle", rule.getVolume().toString()); ruleId = -1; } return v; } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onClick(View v){ if (v instanceof FloatingActionButton){ FloatingActionButton bt = (FloatingActionButton)v; bt.setLineMorphingState((bt.getLineMorphingState() + 1) % 2, true); } Dialog.Builder builder = null; switch (v.getId()){ case R.id.button_start_time_picker: builder = new TimePickerDialog.Builder(6, 00){ @Override public void onPositiveActionClicked(DialogFragment fragment) { TimePickerDialog dialog = (TimePickerDialog)fragment.getDialog(); String message = dialog.getFormattedTime(DateFormat.getTimeInstance(DateFormat.SHORT)); String hour; String min; if (dialog.getHour() < 10) hour = "0" + dialog.getHour(); else hour = String.valueOf(dialog.getHour()); if (dialog.getMinute() < 10) min = "0" + dialog.getMinute(); else min = String.valueOf(dialog.getMinute()); rule.setStart_time(hour + ":" + min); bt_start_time_picker.setText(message); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; case R.id.button_end_time_picker: builder = new TimePickerDialog.Builder(6, 00){ @Override public void onPositiveActionClicked(DialogFragment fragment) { TimePickerDialog dialog = (TimePickerDialog)fragment.getDialog(); String message = dialog.getFormattedTime(DateFormat.getTimeInstance(DateFormat.SHORT)); String hour; String min; if (dialog.getHour() < 10) hour = "0" + dialog.getHour(); else hour = String.valueOf(dialog.getHour()); if (dialog.getMinute() < 10) min = "0" + dialog.getMinute(); else min = String.valueOf(dialog.getMinute()); rule.setEnd_time(hour + ":" + min); bt_end_time_picker.setText(message); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; case R.id.button_date_picker: builder = new DatePickerDialog.Builder(){ @Override public void onPositiveActionClicked(DialogFragment fragment) { DatePickerDialog dialog = (DatePickerDialog)fragment.getDialog(); String date = dialog.getFormattedDate(SimpleDateFormat.getDateInstance()); //Toast.makeText(fragment.getDialog().getContext(), "Date is " + date, Toast.LENGTH_SHORT).show(); bt_date_picker.setText(date); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); rule.setDate(dateFormat.format(dialog.getDate())); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; } DialogFragment fragment = DialogFragment.newInstance(builder); fragment.show(getFragmentManager(), null); } public void setUpdateId(long id){ this.ruleId = id; Log.d("update", "set " + String.valueOf(this.ruleId)); } }
package gillespieSSAjava; import java.util.HashMap; import java.util.Random; import org.sbml.libsbml.*; import biomodelsim.BioSim; import java.awt.BorderLayout; import java.io.*; import java.lang.Math; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class GillespieSSAJavaSingleStep { // SpeciesIndex maps from each species to a column index. // ReactionsIndex maps from each reaction to a row index. // The state change vector is a 2-D array with reactions as rows and species as columns. // The amount of molecules for reactant j in Reaction i is indexed as SateChangeVetor[i][j]. private HashMap<String, Integer> SpeciesToIndex = new HashMap<String, Integer>(); private HashMap<Integer, String> IndexToSpecies = new HashMap<Integer, String>(); private HashMap<String, Integer> ReactionsToIndex = new HashMap<String, Integer>(); private HashMap<Integer, String> IndexToReactions = new HashMap<Integer, String>(); private HashMap<String, Double> SpeciesList = new HashMap<String, Double>(); private HashMap<String, Double> GlobalParamsList = new HashMap<String, Double>(); // static HashMap<String, Double> GlobalParamsChangeList = new HashMap<String, Double>(); // static HashMap<String, Double> CompartmentList = new HashMap<String, Double>(); private HashMap<String, Double> PropensityFunctionList = new HashMap<String, Double>(); private HashMap<String, Boolean> EnoughMolecules = new HashMap<String, Boolean>(); private String SpeciesID; private String GlobalParamID; // private String CompartmentID; private double SpeciesInitAmount; private double GlobalParamValue; // private double ComparmentSize; private double PropensityFunctionValue = 0; private double PropensitySum=0.0; private double PropensityFunctionValueFW = 0; private double PropensityFunctionValueRV = 0; private double[][] StateChangeVector; private JTextField tauStep; private JComboBox nextReactionsList; private double tau=0.0; private int miu=0; private double t = 0; private int NumIrreversible = 0; private int NumReversible = 0; private int NumReactions = 0; private FileOutputStream output; private PrintStream outTSD; private double runUntil = 0; public GillespieSSAJavaSingleStep() { } public void PerformSim (String SBMLFileName,String outDir, double timeLimit) throws FileNotFoundException{ int optionValue = -1; // System.out.println("outDir = " + outDir); String outTSDName = outDir + "/run-1.tsd"; output = new FileOutputStream(outTSDName); outTSD = new PrintStream(output); SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(SBMLFileName); Model model = document.getModel(); outTSD.print("("); for (int i=0; i < model.getNumReactions(); i++){ Reaction reaction = model.getReaction(i); if (reaction.getReversible()) NumReversible ++; else NumIrreversible ++; } NumReactions = 2*NumReversible + NumIrreversible; StateChangeVector=new double[(int) NumReactions][(int) model.getNumSpecies()]; // 1. Initialize time (t) and states (x) t = 0.0; // get the species and the associated initial values for (int i=0;i<model.getNumSpecies();i++){ SpeciesID= model.getListOfSpecies().get(i).getId(); SpeciesInitAmount = model.getListOfSpecies().get(i).getInitialAmount(); SpeciesList.put(SpeciesID, SpeciesInitAmount); SpeciesToIndex.put(SpeciesID,i); IndexToSpecies.put(i,SpeciesID); } // for (int i=0;i<SpeciesList.size();i++){ // System.out.println(SpeciesList.keySet().toArray()[i] + " = " + SpeciesList.get(SpeciesList.keySet().toArray()[i])); outTSD.print("(\"time\","); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print("\"" + SpeciesList.keySet().toArray()[i] + "\"" + ","); else outTSD.print("\"" + SpeciesList.keySet().toArray()[i] + "\"),"); } outTSD.print("(" + t + ", "); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + ", "); else outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + "),"); } // get the global parameters // System.out.println("GlobalParameters:"); if(model.getNumParameters() != 0){ for (int i=0;i<model.getNumParameters();i++){ GlobalParamID= model.getListOfParameters().get(i).getId(); GlobalParamValue = model.getListOfParameters().get(i).getValue(); GlobalParamsList.put(GlobalParamID,GlobalParamValue); // GlobalParamsChangeList.put(GlobalParamID, (double) 0); } } //Currently, we assume only one compartment in one SBML file // get compartments and their sizes. // if (model.getNumCompartments() !=0){ // for (int i=0;i<model.getNumCompartments();i++){ // CompartmentID = model.getListOfCompartments().get(i).getId(); // ComparmentSize = model.getListOfCompartments().get(i).getSize(); //// CompartmentList.put(CompartmentID, ComparmentSize); //// System.out.println("Compartment " + i + "=" + CompartmentID); //// System.out.println("CompartmentSize = " + ComparmentSize); // initialize state change vector int index = 0; int l = 0; while (index<NumReactions){ Reaction currentReaction = model.getListOfReactions().get(l); // System.out.println("currentReaction = " + currentReaction.getId()); // irreversible reaction if (!currentReaction.getReversible()){ String currentReactionID = currentReaction.getId(); ReactionsToIndex.put(currentReactionID, index); IndexToReactions.put(index, currentReactionID); for (int j=0; j < currentReaction.getNumReactants(); j++){ String SpeciesAsReactant = currentReaction.getReactant(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsReactant)] = -currentReaction.getReactant(j).getStoichiometry(); } for (int j=0; j < currentReaction.getNumProducts(); j++){ String SpeciesAsProduct = currentReaction.getProduct(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsProduct)] = currentReaction.getProduct(j).getStoichiometry(); } index++; } else{ // reversible reaction String currentReactionID = currentReaction.getId(); ReactionsToIndex.put(currentReactionID, index); ReactionsToIndex.put(currentReactionID + "_rev", index+1); IndexToReactions.put(index, currentReactionID); IndexToReactions.put(index+1, currentReactionID+ "_rev"); for (int j=0; j < currentReaction.getNumReactants(); j++){ String SpeciesAsReactant = currentReaction.getReactant(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsReactant)] = -currentReaction.getReactant(j).getStoichiometry(); StateChangeVector[index+1][SpeciesToIndex.get(SpeciesAsReactant)] = currentReaction.getReactant(j).getStoichiometry(); } for (int j=0; j < currentReaction.getNumProducts(); j++){ String SpeciesAsProduct = currentReaction.getProduct(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsProduct)] = currentReaction.getProduct(j).getStoichiometry(); StateChangeVector[index+1][SpeciesToIndex.get(SpeciesAsProduct)] = -currentReaction.getProduct(j).getStoichiometry(); } index = index + 2; } l++; } // Create a table to hold the results DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("t"); tableModel.addColumn("tau"); tableModel.addColumn("Next Reaction"); SimResultsTable simResultsTbl = new SimResultsTable(tableModel); JFrame tableFrame = new JFrame("Simulation Results"); simResultsTbl.showTable(tableFrame, simResultsTbl); // while (t<=timeLimit) { InitializeEnoughMolecules(); PropensitySum = 0.0; // 2. Evaluate propensity functions // get the reactions for (int i=0;i<model.getNumReactions();i++){ Reaction currentReaction = model.getListOfReactions().get(i); // outTXT.println("Reactions" + i + ": " + currentReaction.getId()); boolean ModifierNotEmpty = true; if (currentReaction.getNumModifiers()>0){ for (int k=0; k<currentReaction.getNumModifiers();k++){ if (SpeciesList.get(currentReaction.getModifier(k).getSpecies())==0.0){ ModifierNotEmpty = false; // break; } } } String currentReactionID = currentReaction.getId(); // System.out.println("Reaction" + i + ": " + currentReactionID); // get current kinetic law KineticLaw currentKineticLaw = currentReaction.getKineticLaw(); // System.out.println("currentKineticLaw= " + currentKineticLaw.getFormula()); // get the abstract syntax tree of the current kinetic law ASTNode currentAST=currentKineticLaw.getMath(); // Start evaluation from the top AST node: index 0 of ListOfNodes ASTNode currentASTNode = currentAST.getListOfNodes().get(0); // get the list of local parameters ListOfLocalParameters currentListOfLocalParams = currentKineticLaw.getListOfLocalParameters(); HashMap<String, Double> LocalParamsList = new HashMap<String, Double>(); if (currentListOfLocalParams.size() > 0){ for (int j=0; j<currentListOfLocalParams.size(); j++){ LocalParamsList.put(currentListOfLocalParams.get(j).getId(), currentListOfLocalParams.get(j).getValue()); // System.out.println("Local Param " + currentListOfLocalParams.get(j).getId()+ " = " + currentListOfLocalParams.get(j).getValue()); } } // calculate propensity function. // For irreversible reaction, propensity function = kinetic law if (!currentReaction.getReversible()){ // enzymatic reaction with no reactants if (currentReaction.getNumReactants() == 0 && currentReaction.getNumProducts()>0 && currentReaction.getNumModifiers()>0){ boolean EnoughMoleculesCond = ModifierNotEmpty; if(!EnoughMoleculesCond){ PropensityFunctionValue = 0; EnoughMolecules.put(currentReactionID, false); } if (EnoughMolecules.get(currentReactionID)){ PropensityFunctionValue = evaluatePropensityFunction(currentASTNode, LocalParamsList); } } // other reactions if (currentReaction.getNumReactants() > 0){ for (int j=0; j < currentReaction.getNumReactants(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCond = SpeciesList.get(currentReaction.getReactant(j).getSpecies()) >= currentReaction.getReactant(j).getStoichiometry(); if(!EnoughMoleculesCond){ PropensityFunctionValue = 0; EnoughMolecules.put(currentReactionID, false); // outTXT.println("EnoughMolecules: " + currentReactionID + " = " + EnoughMolecules.get(currentReactionID)); break; } } if (EnoughMolecules.get(currentReactionID)){ PropensityFunctionValue = evaluatePropensityFunction(currentASTNode,LocalParamsList); } } PropensitySum = PropensitySum + PropensityFunctionValue; PropensityFunctionList.put(currentReactionID, PropensityFunctionValue); } else { // reversible reaction // For reversible, the root node should be a minus operation // Evaluate kinetic law for the forward reaction // Check that there are enough Molecules for the reaction to happen for (int j=0; j < currentReaction.getNumReactants(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCondFW = SpeciesList.get(currentReaction.getReactant(j).getSpecies()) >= currentReaction.getReactant(j).getStoichiometry(); if(!EnoughMoleculesCondFW){ PropensityFunctionValueFW = 0; EnoughMolecules.put(currentReactionID, false); break; } } if (EnoughMolecules.get(currentReactionID)) { // System.out.println("FW current AST Node = " + currentASTNode.getType()); // System.out.println("FW current left child = " + currentASTNode.getLeftChild().getType()); PropensityFunctionValueFW = evaluatePropensityFunction(currentASTNode.getLeftChild(), LocalParamsList); // System.out.println("PropensityFunctionValueFW = " + PropensityFunctionValueFW); } PropensitySum = PropensitySum + PropensityFunctionValueFW; PropensityFunctionList.put(currentReactionID, PropensityFunctionValueFW); // Evaluate kinetic law for the reverse reaction // Check that there are enough Molecules for the reaction to happen for (int j=0; j < currentReaction.getNumProducts(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCondRV = SpeciesList.get(currentReaction.getProduct(j).getSpecies()) >= currentReaction.getProduct(j).getStoichiometry(); if(!EnoughMoleculesCondRV){ PropensityFunctionValueRV = 0; EnoughMolecules.put(currentReactionID+"_rev", false); break; } } if (EnoughMolecules.get(currentReactionID+"_rev")){ PropensityFunctionValueRV = evaluatePropensityFunction(currentASTNode.getRightChild(),LocalParamsList); } PropensitySum = PropensitySum + PropensityFunctionValueRV; PropensityFunctionList.put(currentReactionID+"_rev", PropensityFunctionValueRV); } } // 3. Determine the time, tau, until the next reaction. // Detect if user specifies the time increment tau. Random generator = new Random(); // Draw one uniform(0,1) random numbers r1. double r1 = generator.nextDouble(); // Determine randomly the time, tau, until the next reaction. tau = (1/PropensitySum)*Math.log(1/r1); // 5. Determine the next reaction: (miu is the row index of state change vector array) double SumLeft = 0.0; int count; double r2 = generator.nextDouble(); for (count=0; SumLeft <= r2*PropensitySum; count++){ SumLeft = SumLeft + PropensityFunctionList.get(IndexToReactions.get(count)); if (SumLeft > r2*PropensitySum) break; } miu = count; // Pop up the interactive menu and asks the user to specify tau and miu String[] CustomParams=new String[3]; // optionValue: 0=step, 1=run, 2=terminate boolean hasRunModeStarted = false; boolean isRunMode = (optionValue == 1) && t < runUntil; if (!isRunMode) { CustomParams = openInteractiveMenu(tau,miu); optionValue = Integer.parseInt(CustomParams[2]); if (optionValue == 0) { tau = Double.parseDouble(CustomParams[0]); miu = ReactionsToIndex.get(CustomParams[1]); } else if(optionValue == 1 && t >= runUntil){ String[] CustomParamsRun = openRunMenu(); int runUntil_optVal = Integer.parseInt(CustomParamsRun[1]); // runUntil_optVal: 0=Run, 1=Cancel if (runUntil_optVal == 0) { runUntil = t + Double.parseDouble(CustomParamsRun[0]); hasRunModeStarted = true; } else { // runUntil_optVal == 1 (Cancel) continue; } } else { break; } } // 6. Determine the new state: t = t + tau and x = x + v[miu] double t_current = t; t = t + tau; // Determine the next reaction to fire, in row miu of StateChangeVector. // Update the species amounts according to the state-change-vector in row miu. for (int i=0; i < model.getNumSpecies(); i++){ if (StateChangeVector[miu][i]!=0){ String SpeciesToUpdate = IndexToSpecies.get(i); // System.out.println("SpeciesToUpdate = " + SpeciesToUpdate); if (EnoughMolecules.get(IndexToReactions.get(miu))){ double SpeciesToUpdateAmount = SpeciesList.get(SpeciesToUpdate) + StateChangeVector[miu][i]; SpeciesList.put(SpeciesToUpdate, SpeciesToUpdateAmount); } } } // System.out.println("t = " + t_current); // System.out.println("tau = " + tau); // System.out.println("miu = " + miu); // System.out.println("Next reaction is " + IndexToReactions.get(miu)); // Print results to a table and display it. if ((!isRunMode && !hasRunModeStarted) || (isRunMode && t >= runUntil)){ tableModel.addRow(new Object[]{t_current, tau, IndexToReactions.get(miu)}); simResultsTbl.showTable(tableFrame, simResultsTbl); } outTSD.print("(" + t + ", "); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + ", "); else outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + "),"); } } outTSD.print(")"); } static { try { System.loadLibrary("sbmlj"); } catch (Exception e) { System.err.println("Could not load libSBML library:" + e.getMessage()); } } public void InitializeEnoughMolecules(){ for (int i = 0; i < ReactionsToIndex.size(); i++){ EnoughMolecules.put((String)ReactionsToIndex.keySet().toArray()[i], true); } } public String[] openInteractiveMenu(double tau, int miu) { String[] tau_miu_optVal = new String[3]; JPanel tauPanel = new JPanel(); JPanel nextReactionsListPanel = new JPanel(); JPanel mainPanel = new JPanel(new BorderLayout()); tauPanel.add(new JLabel("Tau:")); tauStep = new JTextField(10); tauStep.setText("" + tau); tauPanel.add(tauStep); nextReactionsListPanel.add(new JLabel("Next reaction:")); // String[] nextReactionsArray = new String[NumReactions]; int l = 0; for (int i=0; i<NumReactions; i++){ // Check if a reaction has enough molecules to fire if (EnoughMolecules.get(IndexToReactions.get(i))){ l++; } } String[] nextReactionsArray = new String[l]; int k = 0; for (int i=0; i<NumReactions; i++){ // Check if a reaction has enough molecules to fire if (EnoughMolecules.get(IndexToReactions.get(i))){ nextReactionsArray[k] = IndexToReactions.get(i); k++; } } nextReactionsList = new JComboBox(nextReactionsArray); nextReactionsListPanel.add(nextReactionsList); mainPanel.add(tauPanel, "North"); mainPanel.add(nextReactionsListPanel, "Center"); Object[] options = {"Step", "Run", "Terminate"}; int optionValue; optionValue = JOptionPane.showOptionDialog(BioSim.frame, mainPanel, "Next Simulation Step", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); tau_miu_optVal[0]=tauStep.getText().trim(); tau_miu_optVal[1]=(String) nextReactionsList.getSelectedItem(); tau_miu_optVal[2]="" + optionValue; return tau_miu_optVal; } public String[] openRunMenu(){ int optlVal; String[] runTimeLimit_optVal = new String[2]; do { JPanel runTimeLimitPanel = new JPanel(); runTimeLimitPanel.add(new JLabel("Time limit to run:")); JTextField runTimeLimit = new JTextField(10); runTimeLimitPanel.add(runTimeLimit); Object[] options = {"Run", "Cancel"}; optlVal = JOptionPane.showOptionDialog(BioSim.frame, runTimeLimitPanel, "Specify Run Time Limit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); runTimeLimit_optVal[0] = runTimeLimit.getText().trim(); runTimeLimit_optVal[1] = "" + optlVal; // System.out.println("runUntil_optVal[0] = " + runUntil_optVal[0]); if (optlVal == 0 && runTimeLimit_optVal[0].equals("")) { JOptionPane.showMessageDialog(BioSim.frame, "Please specify a time limit.", "Error in Run", JOptionPane.ERROR_MESSAGE); } if (optlVal == 1) { break; } } while (optlVal == 0 && runTimeLimit_optVal[0].equals("")); return runTimeLimit_optVal; } public double evaluatePropensityFunction(ASTNode currentASTNode, HashMap<String, Double>ListOfLocalParameters) { double ret = 0; if(isLeafNode(currentASTNode)){ ret = evalChild(currentASTNode, ListOfLocalParameters); } else{ // internal node with left and right children int type_const=currentASTNode.getType(); if(type_const==libsbml.AST_PLUS){ ret = evaluatePropensityFunction(currentASTNode.getLeftChild(),ListOfLocalParameters) + evaluatePropensityFunction(currentASTNode.getRightChild(),ListOfLocalParameters); } if(type_const==libsbml.AST_MINUS){ ret = evaluatePropensityFunction(currentASTNode.getLeftChild(),ListOfLocalParameters) - evaluatePropensityFunction(currentASTNode.getRightChild(),ListOfLocalParameters); } if(type_const==libsbml.AST_TIMES){ ret = evaluatePropensityFunction(currentASTNode.getLeftChild(),ListOfLocalParameters) * evaluatePropensityFunction(currentASTNode.getRightChild(),ListOfLocalParameters); } if(type_const==libsbml.AST_DIVIDE){ ret = evaluatePropensityFunction(currentASTNode.getLeftChild(),ListOfLocalParameters) / evaluatePropensityFunction(currentASTNode.getRightChild(),ListOfLocalParameters); } if(type_const==libsbml.AST_FUNCTION_POWER){ ret = Math.pow(evaluatePropensityFunction(currentASTNode.getLeftChild(),ListOfLocalParameters), evaluatePropensityFunction(currentASTNode.getRightChild(),ListOfLocalParameters)); } } return ret; } public boolean isLeafNode(ASTNode node ){ boolean ret = false; ret = node.isConstant() || node.isInteger() || node.isName() || node.isNumber() || node.isRational() || node.isReal(); return ret; } public double evalChild(ASTNode currentASTNode, HashMap<String, Double> currentListOfLocalParams){ double node_val=0; if(currentASTNode.isInteger()){ node_val = currentASTNode.getInteger(); } else if(currentASTNode.isReal()){ node_val = currentASTNode.getReal(); } else if(currentASTNode.isName()){ if (SpeciesToIndex.containsKey(currentASTNode.getName())){ node_val = SpeciesList.get(currentASTNode.getName()); } else if (GlobalParamsList.containsKey(currentASTNode.getName()) & !currentListOfLocalParams.containsKey(currentASTNode.getName())){ node_val = GlobalParamsList.get(currentASTNode.getName()); } else if (currentListOfLocalParams.containsKey(currentASTNode.getName())){ node_val =currentListOfLocalParams.get(currentASTNode.getName()); } } return node_val; } }
package com.sanchez.fmf.fragment; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.drawable.ColorDrawable; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.Button; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.sanchez.fmf.MarketDetailActivity; import com.sanchez.fmf.MarketListActivity; import com.sanchez.fmf.R; import com.sanchez.fmf.adapter.FavoriteListAdapter; import com.sanchez.fmf.adapter.PlaceAutocompleteAdapter; import com.sanchez.fmf.application.FMFApplication; import com.sanchez.fmf.event.FavoriteClickEvent; import com.sanchez.fmf.event.FavoriteRemoveEvent; import com.sanchez.fmf.util.LocationUtil; import com.sanchez.fmf.util.ViewUtils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; public class MainFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener { public String TAG = MainFragment.class.getSimpleName(); @Bind(R.id.search_autocomplete) AutoCompleteTextView mSearchAutocomplete; @Bind(R.id.search_icon) View mSearchIcon; @Bind(R.id.clear_icon) View mClearSearch; @Bind(R.id.use_location_button) Button mUseLocationButton; @Bind(R.id.market_favorites_list) RecyclerView mFavoritesList; @Bind(R.id.no_favorites_text) View mNoFavorites; View contentView; private static final int GOOGLE_API_CLIENT_ID = 0; private static final LatLngBounds BOUNDS_NORTH_AMERICA = new LatLngBounds(new LatLng(18.000000, -64.000000), new LatLng(67.000000, -165.000000)); private GoogleApiClient mGoogleApiClient = null; private PlaceAutocompleteAdapter mAutocompleteAdapter = null; private String mSelectedPlace = null; private String mSelectedPlaceId = null; private Snackbar mFetchingSnackbar; private Runnable delayedShowFetching = this::showFetching; public abstract class OnGetCoordinatesFromLocationListener { public abstract void onFinished(ArrayList<Double> results); } public static MainFragment newInstance() { return new MainFragment(); } public MainFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // register client for Google APIs mGoogleApiClient = new GoogleApiClient .Builder(getActivity()) .addApi(Places.GEO_DATA_API) .enableAutoManage(getActivity(), GOOGLE_API_CLIENT_ID, this) .build(); } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } @Override public void onResume() { super.onResume(); updateFavoritesList(null); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.bind(this, rootView); contentView = getActivity().findViewById(android.R.id.content); // linear RecyclerView RecyclerView.LayoutManager linearLM = new LinearLayoutManager(getContext()); mFavoritesList.setLayoutManager(linearLM); mFavoritesList.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT); mFavoritesList.setAdapter(new FavoriteListAdapter(new LinkedHashMap<>())); // customize place autocomplete adapter mAutocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(), android.R.layout.simple_list_item_1, mGoogleApiClient, BOUNDS_NORTH_AMERICA, null); mSearchAutocomplete.setAdapter(mAutocompleteAdapter); // customize autocomplete mSearchAutocomplete.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS); mSearchAutocomplete.setDropDownVerticalOffset(8); // just below search box mSearchAutocomplete.setDropDownBackgroundDrawable(new ColorDrawable(getResources() .getColor(R.color.pure_white))); mSearchAutocomplete.setDropDownAnchor(R.id.card_search); // remember place ID of selected dropdown item mSearchAutocomplete.setOnItemClickListener(mAutocompleteClickListener); // search when search IME option pressed mSearchAutocomplete.setOnEditorActionListener((v, actionId, event) -> { if (actionId == EditorInfo.IME_ACTION_SEARCH) { String searchText = mSearchAutocomplete.getText().toString(); String[] tokens = searchText.split(","); mSelectedPlace = tokens[0]; getCoordinatesFromLocation(searchText, new OnGetCoordinatesFromLocationListener() { @Override public void onFinished(ArrayList<Double> results) { //TODO: checkout the coords to make sure they're valid launchMarketList(new double[] { results.get(0), results.get(1) }, false); } }); ViewUtils.hideKeyboard(getActivity()); mSearchAutocomplete.dismissDropDown(); contentView.postDelayed(delayedShowFetching, 300); // As a fail safe if something errors out contentView.postDelayed(this::cancelShowFetching, 8000); return true; } return false; }); // show search 'clear' icon when text is present mSearchAutocomplete.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { if (mClearSearch.getVisibility() == View.GONE) { mClearSearch.setVisibility(View.VISIBLE); } } else { mClearSearch.setVisibility(View.GONE); } } }); // icon press triggers search also mSearchIcon.setOnClickListener((v) -> { mSearchAutocomplete.requestFocus(); ViewUtils.showKeyboard(getActivity(), mSearchAutocomplete); }); mClearSearch.setOnClickListener((v) -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { mSearchAutocomplete.setText("", false); } else { mSearchAutocomplete.setText(""); } }); // set backgroundTint programmatically as xml method is undefined... int primaryColor = getResources().getColor(R.color.primary); ColorStateList cSL = new ColorStateList(new int[][]{new int[0]}, new int[]{primaryColor}); ((AppCompatButton)mUseLocationButton).setSupportBackgroundTintList(cSL); mUseLocationButton.setOnClickListener((v) -> { boolean locEnabled = new LocationUtil().getLocation(getContext(), new LocationUtil.LocationResult() { @Override public void gotLocation(Location location) { getActivity().runOnUiThread(() -> { if (location == null) { Snackbar.make(contentView, R.string.location_error, Snackbar.LENGTH_LONG).show(); } else { double[] coords = {location.getLatitude(), location.getLongitude()}; launchMarketList(coords, true); } }); } }); if (locEnabled) { contentView.postDelayed(delayedShowFetching, 300); // As a fail safe if something errors out contentView.postDelayed(this::cancelShowFetching, 8000); } else { final Snackbar s = Snackbar.make(contentView, R.string.enable_location_prompt, Snackbar.LENGTH_INDEFINITE); s.setAction(R.string.enable, (view) -> { s.dismiss(); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); }); s.setActionTextColor(getResources().getColor(R.color.pure_white)); s.show(); } }); // no keyboard popup on launch removeFocusFromAll(); return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } private void showFetching() { mFetchingSnackbar = Snackbar.make(contentView, R.string.fetching_location, Snackbar.LENGTH_INDEFINITE); mFetchingSnackbar.show(); mSearchAutocomplete.setEnabled(false); mUseLocationButton.setEnabled(false); } private void cancelShowFetching() { contentView.removeCallbacks(delayedShowFetching); if(mFetchingSnackbar != null) { mFetchingSnackbar.dismiss(); } mSearchAutocomplete.setEnabled(true); mUseLocationButton.setEnabled(true); } private void updateFavoritesList(LinkedHashMap<String, String> favorites) { // check to see if we got a parameter if(null == favorites) { favorites = FMFApplication .getGlobalPreferences() .getFavoriteMarkets(); } // see if the persistent data lookup returned anything if (null == favorites) { mNoFavorites.setVisibility(View.VISIBLE); } else { ((FavoriteListAdapter)mFavoritesList.getAdapter()).replaceData(favorites); if(favorites.size() > 0) { mNoFavorites.setVisibility(View.GONE); } else { mNoFavorites.setVisibility(View.VISIBLE); } } } private void launchMarketList(double[] coords, boolean usedDeviceCoordinates) { // start market list activity with coordinates from search Intent i = new Intent(getActivity(), MarketListActivity.class); i.putExtra(MarketListActivity.EXTRA_COORDINATES, coords); i.putExtra(MarketListActivity.EXTRA_PLACE_TITLE, mSelectedPlace); i.putExtra(MarketListActivity.EXTRA_PLACE_ID, mSelectedPlaceId); i.putExtra(MarketListActivity.EXTRA_USED_DEVICE_COORDINATES, usedDeviceCoordinates); startActivity(i); cancelShowFetching(); } private void removeFocusFromAll() { contentView.requestFocus(); } private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // retrieve the place ID of the selected item from the Adapter. PlaceAutocompleteAdapter.PlaceAutocomplete item = mAutocompleteAdapter.getItem(position); mSelectedPlaceId = String.valueOf(item.placeId); /* Issue a request to the Places Geo Data API to retrieve a Place object with additional details about the place. */ // PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi // .getPlaceById(mGoogleApiClient, placeId); // placeResult.setResultCallback(mUpdatePlaceDetailsCallback); // Log.i(TAG, "Called getPlaceById to get Place details for " + item.placeId); } }; /** * Callback for results from a Places Geo Data API query that shows the first place result in * the details view on screen. */ // to display attributions and extra place info // private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback // = new ResultCallback<PlaceBuffer>() { // @Override // public void onResult(PlaceBuffer places) { // if (!places.getStatus().isSuccess()) { // // Request did not complete successfully // Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString()); // places.release(); // return; // // Get the Place object from the buffer. // final Place place = places.get(0); // // Format details of the place for display and show it in a TextView. // mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(), // place.getId(), place.getAddress(), place.getPhoneNumber(), // place.getWebsiteUri())); // // Display the third party attributions if set. // final CharSequence thirdPartyAttribution = places.getAttributions(); // if (thirdPartyAttribution == null) { // mPlaceDetailsAttribution.setVisibility(View.GONE); // } else { // mPlaceDetailsAttribution.setVisibility(View.VISIBLE); // mPlaceDetailsAttribution.setText(Html.fromHtml(thirdPartyAttribution.toString())); // Log.i(TAG, "Place details received: " + place.getName()); // places.release(); // private Spanned formatPlaceDetails(Resources res, CharSequence name, String id, // CharSequence address, CharSequence phoneNumber, Uri websiteUri) { // Log.e(TAG, res.getString(R.string.place_details, name, id, address, phoneNumber, // websiteUri)); // return Html.fromHtml(res.getString(R.string.place_details, name, id, address, phoneNumber, // websiteUri)); @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.e(TAG, "Google Places API connection failed with error code: " + connectionResult.getErrorCode()); } public void getCoordinatesFromLocation(String location, final OnGetCoordinatesFromLocationListener listener) { new AsyncTask<Void, Void, ArrayList<Double>>() { @Override protected ArrayList<Double> doInBackground(Void... arg0) { ArrayList<Double> returnList = new ArrayList<Double>(); try { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); List<Address> addresses = geocoder.getFromLocationName(location, 1); if (addresses.size() > 0) { Address address = addresses.get(0); returnList.add(address.getLatitude()); returnList.add(address.getLongitude()); return returnList; } } catch (Exception e) { Log.e(TAG, e.getMessage()); return null; } return returnList; } @Override protected void onPostExecute(ArrayList<Double> results) { if(null == results) { Snackbar.make(contentView, "Network error", Snackbar.LENGTH_LONG).show(); cancelShowFetching(); } else if (results.size() > 0) { listener.onFinished(results); } else { Snackbar.make(contentView, "Invalid input", Snackbar.LENGTH_LONG).show(); cancelShowFetching(); } } }.execute(); } public void onEvent(FavoriteClickEvent event) { Intent i = new Intent(getActivity(), MarketDetailActivity.class); i.putExtra(MarketDetailActivity.EXTRA_MARKET_ID, event.getId()); i.putExtra(MarketDetailActivity.EXTRA_MARKET_NAME, event.getName()); startActivity(i); } public void onEvent(FavoriteRemoveEvent event) { LinkedHashMap<String, String> favoritesMap = FMFApplication.getGlobalPreferences().getFavoriteMarkets(); favoritesMap.remove(event.getId()); FMFApplication.getGlobalPreferences().setFavoriteMarkets(favoritesMap); updateFavoritesList(favoritesMap); } }
package verification.platu.partialOrders; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import verification.platu.main.Options; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; public class StaticSets { private Transition curTran; private HashMap<Integer, Transition[]> allTransitions; private HashSet<LpnTransitionPair> disableSet; private HashSet<LpnTransitionPair> disableByStealingToken; private HashSet<LpnTransitionPair> enableSet; private HashSet<LpnTransitionPair> curTranDisableOtherTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> otherTranDisableCurTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> modifyAssignment; public StaticSets(Transition curTran, HashMap<Integer,Transition[]> allTransitions) { this.curTran = curTran; this.allTransitions = allTransitions; disableSet = new HashSet<LpnTransitionPair>(); disableByStealingToken = new HashSet<LpnTransitionPair>(); curTranDisableOtherTranFailEnablingCond = new HashSet<LpnTransitionPair>(); otherTranDisableCurTranFailEnablingCond = new HashSet<LpnTransitionPair>(); enableSet = new HashSet<LpnTransitionPair>(); modifyAssignment = new HashSet<LpnTransitionPair>(); } /** * Build a set of transitions that curTran can disable. * @param curLpnIndex */ public void buildCurTranDisableOtherTransSet(int curLpnIndex) { // Test if curTran can disable other transitions by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } } } // Test if curTran can disable other transitions by executing its assignments if (!curTran.getAssignments().isEmpty()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree anotherTranEnablingTree = anotherTran.getEnablingTree(); if (anotherTranEnablingTree != null && (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='f' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can disable " + anotherTran.getName() + ". " + anotherTran.getName() + "'s enabling condition, which is " + anotherTranEnablingTree + ", may become false due to firing of " + curTran.getName() + "."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = F."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = f."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = X."); } curTranDisableOtherTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(curTranDisableOtherTranFailEnablingCond); // printIntegerSet(disableByStealingToken, "disableByStealingToken"); // printIntegerSet(disableByFailingEnableCond, "disableByFailingEnableCond"); } /** * Build a set of transitions that disable curTran. * @param curLpnIndex */ public void buildOtherTransDisableCurTranSet(int curLpnIndex) { // Test if other transition(s) can disable curTran by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } } } // Test if other transitions can disable curTran by executing their assignments if (!curTran.isPersistent()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; if (!anotherTran.getAssignments().isEmpty()) { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='f' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can be disabled by " + anotherTran.getName() + ". " + curTran.getName() + "'s enabling condition, which is " + curTranEnablingTree + ", may become false due to firing of " + anotherTran.getName() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = F."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = f."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } otherTranDisableCurTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(otherTranDisableCurTranFailEnablingCond); buildModifyAssignSet(); disableSet.addAll(modifyAssignment); otherTranDisableCurTranFailEnablingCond.addAll(modifyAssignment); } private boolean tranFormsSelfLoop() { boolean isSelfLoop = false; Place[] curPreset = curTran.getPreset(); Place[] curPostset = curTran.getPostset(); for (Place preset : curPreset) { for (Place postset : curPostset) { if (preset == postset) { isSelfLoop = true; break; } } if (isSelfLoop) break; } return isSelfLoop; } /** * Construct a set of transitions that can make the enabling condition of curTran true, by firing their assignments. * @param lpnIndex */ public void buildEnableSet() { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='t' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { enableSet.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } public void buildModifyAssignSet() { // modifyAssignment contains transitions (T) that satisfy at least one of the conditions below: for every t in T, // (1) intersection(VA(curTran), supportA(t)) != empty // (2) intersection(VA(t), supportA(curTran)) != empty // (3) intersection(VA(t), VA(curTran) != empty // VA(t) : set of variables being assigned in transition t. // supportA(t): set of variables appearing in the expressions assigned to the variables of t (r.h.s of the assignment). for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; for (String v : curTran.getAssignTrees().keySet()) { for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } for (ExprTree exprTree : curTran.getAssignTrees().values()) { for (String v : anotherTran.getAssignTrees().keySet()) { if (exprTree != null && exprTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } for (String v1 : curTran.getAssignTrees().keySet()) { for (String v2 : anotherTran.getAssignTrees().keySet()) { if (v1.equals(v2)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } } public HashSet<LpnTransitionPair> getModifyAssignSet() { return modifyAssignment; } public HashSet<LpnTransitionPair> getDisableSet() { return disableSet; } public HashSet<LpnTransitionPair> getOtherTransDisableCurTranSet() { return otherTranDisableCurTranFailEnablingCond; } public HashSet<LpnTransitionPair> getDisableByStealingToken() { return disableByStealingToken; } public HashSet<LpnTransitionPair> getEnable() { return enableSet; } public Transition getTran() { return curTran; } // private void printIntegerSet(HashSet<Integer> integerSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + ": "); // if (integerSet == null) { // System.out.println("null"); // else if (integerSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Integer> curTranDisableIter = integerSet.iterator(); curTranDisableIter.hasNext();) { // Integer tranInDisable = curTranDisableIter.next(); // System.out.print(lpn.getAllTransitions()[tranInDisable] + " "); // System.out.print("\n"); }
package me.devsaki.hentoid.json; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.enums.StatusContent; class JsonImageFile { private Integer order; private String url; private String name; private boolean isCover; private boolean favourite; private boolean isRead; private StatusContent status; private String mimeType; private long pHash; private JsonImageFile() { } static JsonImageFile fromEntity(ImageFile f) { JsonImageFile result = new JsonImageFile(); result.order = f.getOrder(); result.url = f.getUrl(); result.name = f.getName(); result.status = f.getStatus(); result.isCover = f.isCover(); result.favourite = f.isFavourite(); result.isRead = f.isRead(); result.mimeType = f.getMimeType(); result.pHash = f.getImageHash(); return result; } ImageFile toEntity(int maxPages) { ImageFile result = new ImageFile(order, url, status, maxPages); result.setName(name); result.setIsCover(isCover); result.setFavourite(favourite); result.setRead(isRead); result.setMimeType(mimeType); result.setImageHash(pHash); return result; } }
package verification.platu.partialOrders; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import verification.platu.main.Options; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; public class StaticSets { private Transition curTran; private HashMap<Integer, Transition[]> allTransitions; private HashSet<LpnTransitionPair> disableSet; private HashSet<LpnTransitionPair> disableByStealingToken; private HashSet<LpnTransitionPair> enableByBringingToken; private HashSet<LpnTransitionPair> enableBySettingEnablingTrue; private HashSet<LpnTransitionPair> curTranDisableOtherTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> otherTranDisableCurTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> modifyAssignment; //private HashSet<LpnTransitionPair> enableSet; public StaticSets(Transition curTran, HashMap<Integer,Transition[]> allTransitions) { this.curTran = curTran; this.allTransitions = allTransitions; disableSet = new HashSet<LpnTransitionPair>(); disableByStealingToken = new HashSet<LpnTransitionPair>(); curTranDisableOtherTranFailEnablingCond = new HashSet<LpnTransitionPair>(); otherTranDisableCurTranFailEnablingCond = new HashSet<LpnTransitionPair>(); enableBySettingEnablingTrue = new HashSet<LpnTransitionPair>(); modifyAssignment = new HashSet<LpnTransitionPair>(); } /** * Build a set of transitions that curTran can disable. * @param curLpnIndex */ public void buildCurTranDisableOtherTransSet(int curLpnIndex) { // Test if curTran can disable other transitions by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can steal tokens from these transitions:"); for (Transition t : curTran.getConflictSet()) { System.out.print(t.getName() + ", "); } System.out.println(); } } } // Test if curTran can disable other transitions by executing its assignments if (!curTran.getAssignments().isEmpty()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree anotherTranEnablingTree = anotherTran.getEnablingTree(); if (anotherTranEnablingTree != null && (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='f' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can disable " + anotherTran.getName() + ". " + anotherTran.getName() + "'s enabling condition, which is " + anotherTranEnablingTree + ", may become false due to firing of " + curTran.getName() + "."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = F."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = f."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = X."); } curTranDisableOtherTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(curTranDisableOtherTranFailEnablingCond); // printIntegerSet(disableByStealingToken, "disableByStealingToken"); // printIntegerSet(disableByFailingEnableCond, "disableByFailingEnableCond"); } /** * Build a set of transitions that disable curTran. * @param curLpnIndex */ public void buildOtherTransDisableCurTranSet(int curLpnIndex) { // Test if other transition(s) can disable curTran by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can steal tokens from these transitions:"); for (Transition t : curTran.getConflictSet()) { System.out.print(t.getName() + ", "); } System.out.println(); } } } // Test if other transitions can disable curTran by executing their assignments if (!curTran.isPersistent()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; if (!anotherTran.getAssignments().isEmpty()) { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='f' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can be disabled by " + anotherTran.getName() + ". " + curTran.getName() + "'s enabling condition, which is " + curTranEnablingTree + ", may become false due to firing of " + anotherTran.getName() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = F."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = f."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } otherTranDisableCurTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(otherTranDisableCurTranFailEnablingCond); buildModifyAssignSet(); disableSet.addAll(modifyAssignment); otherTranDisableCurTranFailEnablingCond.addAll(modifyAssignment); } private boolean tranFormsSelfLoop() { boolean isSelfLoop = false; Place[] curPreset = curTran.getPreset(); Place[] curPostset = curTran.getPostset(); for (Place preset : curPreset) { for (Place postset : curPostset) { if (preset == postset) { isSelfLoop = true; break; } } if (isSelfLoop) break; } return isSelfLoop; } /** * Construct a set of transitions that can make the enabling condition of curTran true, by executing their assignments. */ public void buildEnableBySettingEnablingTrue() { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='t' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { enableBySettingEnablingTrue.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can be enabled by " + anotherTran.getName() + ". " + curTran.getName() + "'s enabling condition, which is " + curTranEnablingTree + ", may become true due to firing of " + anotherTran.getName() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = T."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='t') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = t."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } } } } } /** * Construct a set of transitions that can bring a token to curTran. */ public void buildEnableByBringingToken() { for (Place p : curTran.getPreset()) { for (Transition presetTran : p.getPreset()) { int lpnIndex = presetTran.getLpn().getLpnIndex(); enableByBringingToken.add(new LpnTransitionPair(lpnIndex, presetTran.getIndex())); } } } public void buildModifyAssignSet() { // for every transition curTran in T, where T is the set of all transitions, we check t (t != curTran) in T, // (1) intersection(VA(curTran), supportA(t)) != empty // (2) intersection(VA(t), supportA(curTran)) != empty // (3) intersection(VA(t), VA(curTran) != empty // VA(t0) : set of variables being assigned to (left hand side of the assignment) in transition t0. // supportA(t0): set of variables appearing in the expressions assigned to the variables of t0 (right hand side of the assignment). for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; for (String v : curTran.getAssignTrees().keySet()) { for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); if (Options.getDebugMode()) { System.out.println("Variable " + v + " in " + curTran.getName() + " may change the right hand side of assignment " + anotherTranAssignTree + " in " + anotherTran.getName()); } } } } for (ExprTree curTranAssignTree : curTran.getAssignTrees().values()) { for (String v : anotherTran.getAssignTrees().keySet()) { if (curTranAssignTree != null && curTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); if (Options.getDebugMode()) { System.out.println("Variable " + v + " in " + anotherTran.getName() + " may change the right hand side of assignment " + curTranAssignTree + " in " + anotherTran.getName()); } } } } for (String v1 : curTran.getAssignTrees().keySet()) { for (String v2 : anotherTran.getAssignTrees().keySet()) { if (v1.equals(v2)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); if (Options.getDebugMode()) { System.out.println("Variable " + v1 + " are assigned in " + curTran.getName() + " and " + anotherTran.getName()); } } } } } } } public HashSet<LpnTransitionPair> getModifyAssignSet() { return modifyAssignment; } public HashSet<LpnTransitionPair> getDisableSet() { return disableSet; } public HashSet<LpnTransitionPair> getOtherTransDisableCurTranSet() { return otherTranDisableCurTranFailEnablingCond; } public HashSet<LpnTransitionPair> getDisableByStealingToken() { return disableByStealingToken; } public HashSet<LpnTransitionPair> getEnableByBringingToken() { return enableByBringingToken; } public HashSet<LpnTransitionPair> getEnableBySettingEnablingTrue() { return enableBySettingEnablingTrue; } public Transition getTran() { return curTran; } // private void printIntegerSet(HashSet<Integer> integerSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + ": "); // if (integerSet == null) { // System.out.println("null"); // else if (integerSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Integer> curTranDisableIter = integerSet.iterator(); curTranDisableIter.hasNext();) { // Integer tranInDisable = curTranDisableIter.next(); // System.out.print(lpn.getAllTransitions()[tranInDisable] + " "); // System.out.print("\n"); }
package me.devsaki.hentoid.util; import android.content.ContentProviderClient; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.documentfile.provider.DocumentFile; import com.annimon.stream.Stream; import com.google.firebase.crashlytics.FirebaseCrashlytics; import org.apache.commons.lang3.tuple.ImmutablePair; import org.greenrobot.eventbus.EventBus; import org.threeten.bp.Instant; import java.io.File; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import javax.annotation.Nonnull; import me.devsaki.hentoid.R; import me.devsaki.hentoid.activities.ImageViewerActivity; import me.devsaki.hentoid.activities.UnlockActivity; import me.devsaki.hentoid.activities.bundles.BaseWebActivityBundle; import me.devsaki.hentoid.activities.bundles.ImageViewerActivityBundle; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.ObjectBoxDAO; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.database.domains.QueueRecord; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.StatusContent; import me.devsaki.hentoid.events.DownloadEvent; import me.devsaki.hentoid.json.JsonContent; import me.devsaki.hentoid.json.JsonContentCollection; import me.devsaki.hentoid.util.exception.ContentNotRemovedException; import me.devsaki.hentoid.util.exception.FileNotRemovedException; import timber.log.Timber; import static com.annimon.stream.Collectors.toList; /** * Utility class for Content-related operations */ public final class ContentHelper { private static final String UNAUTHORIZED_CHARS = "[^a-zA-Z0-9.-]"; private static final int[] libraryStatus = new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.EXTERNAL.getCode()}; // TODO empty this cache at some point private static final Map<String, String> fileNameMatchCache = new HashMap<>(); private ContentHelper() { throw new IllegalStateException("Utility class"); } public static int[] getLibraryStatuses() { return libraryStatus; } /** * Open the app's web browser to view the given Content's gallery page * * @param context Context to use for the action * @param content Content to view */ public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content) { viewContentGalleryPage(context, content, false); } /** * Open the app's web browser to view the given Content's gallery page * * @param context Context to use for the action * @param content Content to view * @param wrapPin True if the intent should be wrapped with PIN protection */ public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content, boolean wrapPin) { if (content.getSite().equals(Site.NONE)) return; Intent intent = new Intent(context, content.getWebActivityClass()); BaseWebActivityBundle.Builder builder = new BaseWebActivityBundle.Builder(); builder.setUrl(content.getGalleryUrl()); intent.putExtras(builder.getBundle()); if (wrapPin) intent = UnlockActivity.wrapIntent(context, intent); context.startActivity(intent); } /** * Update the given Content's JSON file with its current values * * @param context Context to use for the action * @param content Content whose JSON file to update */ public static void updateContentJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); if (content.isArchive()) return; DocumentFile file = FileHelper.getFileFromSingleUriString(context, content.getJsonUri()); if (null == file) throw new InvalidParameterException("'" + content.getJsonUri() + "' does not refer to a valid file"); try { JsonHelper.updateJson(context, JsonContent.fromEntity(content), JsonContent.class, file); } catch (IOException e) { Timber.e(e, "Error while writing to %s", content.getJsonUri()); } } /** * Create the given Content's JSON file and populate it with its current values * * @param content Content whose JSON file to create */ public static void createContentJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); if (content.isArchive()) return; DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) return; try { JsonHelper.jsonToFile(context, JsonContent.fromEntity(content), JsonContent.class, folder); } catch (IOException e) { Timber.e(e, "Error while writing to %s", content.getStorageUri()); } } /** * Update the JSON file that stores the queue with the current contents of the queue * * @param context Context to be used * @param dao DAO to be used * @return True if the queue JSON file has been updated properly; false instead */ public static boolean updateQueueJson(@NonNull Context context, @NonNull CollectionDAO dao) { Helper.assertNonUiThread(); List<QueueRecord> queue = dao.selectQueue(); // Save current queue (to be able to restore it in case the app gets uninstalled) List<Content> queuedContent = Stream.of(queue).map(qr -> qr.content.getTarget()).withoutNulls().toList(); JsonContentCollection contentCollection = new JsonContentCollection(); contentCollection.setQueue(queuedContent); DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri()); if (null == rootFolder) return false; try { JsonHelper.jsonToFile(context, contentCollection, JsonContentCollection.class, rootFolder, Consts.QUEUE_JSON_FILE_NAME); } catch (IOException | IllegalArgumentException e) { // even though all the file existence checks are in place // ("Failed to determine if primary:.Hentoid/queue.json is child of primary:.Hentoid: java.io.FileNotFoundException: Missing file for primary:.Hentoid/queue.json at /storage/emulated/0/.Hentoid/queue.json") Timber.e(e); FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance(); crashlytics.recordException(e); return false; } return true; } /** * Open the given Content in the built-in image viewer * * @param context Context to use for the action * @param content Content to view * @param searchParams Current search parameters (so that the next/previous book feature * is faithful to the library screen's order) */ public static boolean openHentoidViewer(@NonNull Context context, @NonNull Content content, Bundle searchParams) { // Check if the book has at least its own folder if (content.getStorageUri().isEmpty()) return false; Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageUri()); ImageViewerActivityBundle.Builder builder = new ImageViewerActivityBundle.Builder(); builder.setContentId(content.getId()); if (searchParams != null) builder.setSearchParams(searchParams); Intent viewer = new Intent(context, ImageViewerActivity.class); viewer.putExtras(builder.getBundle()); context.startActivity(viewer); return true; } /** * Update the given Content's number of reads in both DB and JSON file * * @param context Context to use for the action * @param dao DAO to use for the action * @param content Content to update */ public static void updateContentReads(@NonNull Context context, @Nonnull CollectionDAO dao, @NonNull Content content) { content.increaseReads().setLastReadDate(Instant.now().toEpochMilli()); dao.insertContent(content); if (!content.getJsonUri().isEmpty()) updateContentJson(context, content); else createContentJson(context, content); } /** * Find the picture files for the given Content * NB1 : Pictures with non-supported formats are not included in the results * NB2 : Cover picture is not included in the results * * @param content Content to retrieve picture files for * @return List of picture files */ public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) { Helper.assertNonUiThread(); String storageUri = content.getStorageUri(); Timber.d("Opening: %s from: %s", content.getTitle(), storageUri); DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, storageUri); if (null == folder) { Timber.d("File not found!! Exiting method."); return new ArrayList<>(); } return FileHelper.listFoldersFilter(context, folder, displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME) && ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName)) ) ); } /** * Remove the given Content from the disk and the DB * * @param context Context to be used * @param dao DAO to be used * @param content Content to be removed * @throws ContentNotRemovedException in case an issue prevents the content from being actually removed */ public static void removeContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException { Helper.assertNonUiThread(); // Remove from DB // NB : start with DB to have a LiveData feedback, because file removal can take much time dao.deleteContent(content); if (content.isArchive()) { // Remove an archive DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri()); if (null == archive) throw new FileNotRemovedException(content, "Failed to find archive " + content.getStorageUri()); if (archive.delete()) { Timber.i("Archive removed : %s", content.getStorageUri()); } else { throw new FileNotRemovedException(content, "Failed to delete archive " + content.getStorageUri()); } // Remove the cover stored in the app's persistent folder File appFolder = context.getFilesDir(); File[] images = appFolder.listFiles((dir, name) -> FileHelper.getFileNameWithoutExtension(name).equals(content.getId() + "")); if (images != null) for (File f : images) FileHelper.removeFile(f); } else { // Remove a folder and its content // If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) throw new FileNotRemovedException(content, "Failed to find directory " + content.getStorageUri()); if (folder.delete()) { Timber.i("Directory removed : %s", content.getStorageUri()); } else { throw new FileNotRemovedException(content, "Failed to delete directory " + content.getStorageUri()); } } } // TODO doc public static void removeAllExternalContent(@NonNull final Context context) { // Remove all external books from DB CollectionDAO dao = new ObjectBoxDAO(context); try { dao.deleteAllExternalBooks(); } finally { dao.cleanup(); } // Remove all images stored in the app's persistent folder (archive covers) File appFolder = context.getFilesDir(); File[] images = appFolder.listFiles((dir, name) -> ImageHelper.isSupportedImage(name)); if (images != null) for (File f : images) FileHelper.removeFile(f); } /** * Remove the given Content from the queue, disk and the DB * * @param context Context to be used * @param dao DAO to be used * @param content Content to be removed * @throws ContentNotRemovedException in case an issue prevents the content from being actually removed */ public static void removeQueuedContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException { Helper.assertNonUiThread(); // Check if the content is on top of the queue; if so, send a CANCEL event List<QueueRecord> queue = dao.selectQueue(); if (!queue.isEmpty() && queue.get(0).content.getTargetId() == content.getId()) EventBus.getDefault().post(new DownloadEvent(content, DownloadEvent.EV_CANCEL)); // Remove from queue dao.deleteQueue(content); // Remove content itself removeContent(context, dao, content); } /** * Add new content to the library * * @param dao DAO to be used * @param content Content to add to the library * @return ID of the newly added Content */ public static long addContent( @NonNull final Context context, @NonNull final CollectionDAO dao, @NonNull final Content content) { content.populateAuthor(); long newContentId = dao.insertContent(content); content.setId(newContentId); // Perform group operations only if // - the book is in the library (i.e. not queued) // - the book is linked to no group from the given grouping if (Helper.getListFromPrimitiveArray(libraryStatus).contains(content.getStatus().getCode())) { List<Grouping> staticGroupings = Stream.of(Grouping.values()).filter(Grouping::canReorderBooks).toList(); for (Grouping g : staticGroupings) if (content.getGroupItems(g).isEmpty()) { if (g.equals(Grouping.ARTIST)) { int nbGroups = (int) dao.countGroupsFor(g); AttributeMap attrs = content.getAttributeMap(); List<Attribute> artists = new ArrayList<>(); List<Attribute> sublist = attrs.get(AttributeType.ARTIST); if (sublist != null) artists.addAll(sublist); sublist = attrs.get(AttributeType.CIRCLE); if (sublist != null) artists.addAll(sublist); for (Attribute a : artists) { Group group = a.getGroup().getTarget(); if (null == group) { group = new Group(Grouping.ARTIST, a.getName(), ++nbGroups); if (!a.contents.isEmpty()) group.picture.setTarget(a.contents.get(0).getCover()); } GroupHelper.addContentToAttributeGroup(dao, group, a, content); } } } } // Extract the cover to the app's persistent folder if the book is an archive if (content.isArchive()) { DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri()); if (archive != null) { try { List<Uri> outputFiles = ArchiveHelper.extractZipEntries( context, archive, Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(), context.getFilesDir(), Stream.of(newContentId + "").toList()); if (!outputFiles.isEmpty() && content.getImageFiles() != null) { content.getCover().setFileUri(outputFiles.get(0).toString()); dao.replaceImageList(newContentId, content.getImageFiles()); } } catch (IOException e) { Timber.w(e); } } } return newContentId; } /** * Remove the given pages from the disk and the DB * * @param images Pages to be removed * @param dao DAO to be used * @param context Context to be used */ public static void removePages(@NonNull List<ImageFile> images, @NonNull CollectionDAO dao, @NonNull final Context context) { Helper.assertNonUiThread(); // Remove from DB // NB : start with DB to have a LiveData feedback, because file removal can take much time dao.deleteImageFiles(images); // Remove the pages from disk for (ImageFile image : images) FileHelper.removeFile(context, Uri.parse(image.getFileUri())); // Lists all relevant content List<Long> contents = Stream.of(images).filter(i -> i.content != null).map(i -> i.content.getTargetId()).distinct().toList(); // Update content JSON if it exists (i.e. if book is not queued) for (Long contentId : contents) { Content content = dao.selectContent(contentId); if (content != null && !content.getJsonUri().isEmpty()) updateContentJson(context, content); } } /** * Define a new cover among a Content's ImageFiles * * @param newCover ImageFile to be used as a cover for the Content it is related to * @param dao DAO to be used * @param context Context to be used */ public static void setContentCover(@NonNull ImageFile newCover, @NonNull CollectionDAO dao, @NonNull final Context context) { Helper.assertNonUiThread(); // Get all images from the DB Content content = dao.selectContent(newCover.content.getTargetId()); if (null == content) return; List<ImageFile> images = content.getImageFiles(); if (null == images) return; // Remove current cover from the set for (int i = 0; i < images.size(); i++) if (images.get(i).isCover()) { images.remove(i); break; } // Duplicate given picture and set it as a cover ImageFile cover = ImageFile.newCover(newCover.getUrl(), newCover.getStatus()).setFileUri(newCover.getFileUri()).setMimeType(newCover.getMimeType()); images.add(0, cover); // Update cover URL to "ping" the content to be updated too (useful for library screen that only detects "direct" content updates) content.setCoverImageUrl(newCover.getUrl()); // Update the whole list dao.insertContent(content); // Update content JSON if it exists (i.e. if book is not queued) if (!content.getJsonUri().isEmpty()) updateContentJson(context, content); } /** * Create the download directory of the given content * * @param context Context * @param content Content for which the directory to create * @return Created directory */ @Nullable public static DocumentFile createContentDownloadDir(@NonNull Context context, @NonNull Content content) { DocumentFile siteDownloadDir = getOrCreateSiteDownloadDir(context, null, content.getSite()); if (null == siteDownloadDir) return null; String bookFolderName = formatBookFolderName(content); DocumentFile bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName); if (null == bookFolder) { // Create return siteDownloadDir.createDirectory(bookFolderName); } else return bookFolder; } /** * Format the download directory path of the given content according to current user preferences * * @param content Content to get the path from * @return Canonical download directory path of the given content, according to current user preferences */ public static String formatBookFolderName(@NonNull final Content content) { String result = ""; String title = content.getTitle(); title = (null == title) ? "" : title.replaceAll(UNAUTHORIZED_CHARS, "_"); String author = content.getAuthor().toLowerCase().replaceAll(UNAUTHORIZED_CHARS, "_"); switch (Preferences.getFolderNameFormat()) { case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_ID: result += title; break; case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID: result += author + " - " + title; break; case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_AUTH_ID: result += title + " - " + author; break; } result += " - "; // Unique content ID String suffix = formatBookId(content); // Truncate folder dir to something manageable for Windows // If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters. int truncLength = Preferences.getFolderTruncationNbChars(); int titleLength = result.length(); if (truncLength > 0 && titleLength + suffix.length() > truncLength) result = result.substring(0, truncLength - suffix.length() - 1); result += suffix; return result; } /** * Format the Content ID for folder naming purposes * * @param content Content whose ID to format * @return Formatted Content ID */ @SuppressWarnings("squid:S2676") // Math.abs is used for formatting purposes only public static String formatBookId(@NonNull final Content content) { String id = content.getUniqueSiteId(); // For certain sources (8muses, fakku), unique IDs are strings that may be very long // => shorten them by using their hashCode if (id.length() > 10) id = Helper.formatIntAsStr(Math.abs(id.hashCode()), 10); return "[" + id + "]"; } /** * Return the given site's download directory. Create it if it doesn't exist. * * @param context Context to use for the action * @param site Site to get the download directory for * @return Download directory of the given Site */ @Nullable static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable ContentProviderClient client, @NonNull Site site) { String appUriStr = Preferences.getStorageUri(); if (appUriStr.isEmpty()) { Timber.e("No storage URI defined for the app"); return null; } DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr)); if (null == appFolder || !appFolder.exists()) { Timber.e("App folder %s does not exist", appUriStr); return null; } String siteFolderName = site.getFolder(); DocumentFile siteFolder; if (null == client) siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName); else siteFolder = FileHelper.findFolder(context, appFolder, client, siteFolderName); if (null == siteFolder) // Create return appFolder.createDirectory(siteFolderName); else return siteFolder; } /** * Open the "share with..." Android dialog for the given Content * * @param context Context to use for the action * @param item Content to share */ public static void shareContent(@NonNull final Context context, @NonNull final Content item) { String url = item.getGalleryUrl(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, item.getTitle()); intent.putExtra(Intent.EXTRA_TEXT, url); context.startActivity(Intent.createChooser(intent, context.getString(R.string.send_to))); } /** * Parse the given download parameters string into a map of strings * * @param downloadParamsStr String representation of the download parameters to parse * @return Map of strings describing the given download parameters */ public static Map<String, String> parseDownloadParams(final String downloadParamsStr) { // Handle empty and {} if (null == downloadParamsStr || downloadParamsStr.trim().length() <= 2) return new HashMap<>(); try { return JsonHelper.jsonToObject(downloadParamsStr, JsonHelper.MAP_STRINGS); } catch (IOException e) { Timber.w(e); } return new HashMap<>(); } /** * Remove the leading zeroes and the file extension of the given string * * @param s String to be cleaned * @return Input string, without leading zeroes and extension */ private static String removeLeadingZeroesAndExtension(@Nullable String s) { if (null == s) return ""; int beginIndex = 0; if (s.startsWith("0")) beginIndex = -1; for (int i = 0; i < s.length(); i++) { if (-1 == beginIndex && s.charAt(i) != '0') beginIndex = i; if ('.' == s.charAt(i)) return s.substring(beginIndex, i); } return (-1 == beginIndex) ? "0" : s.substring(beginIndex); } /** * Remove the leading zeroes and the file extension of the given string using cached results * * @param s String to be cleaned * @return Input string, without leading zeroes and extension */ private static String removeLeadingZeroesAndExtensionCached(String s) { if (fileNameMatchCache.containsKey(s)) return fileNameMatchCache.get(s); else { String result = removeLeadingZeroesAndExtension(s); fileNameMatchCache.put(s, result); return result; } } /** * Matches the given files to the given ImageFiles according to their name (without leading zeroes nor file extension) * * @param files Files to be matched to the given ImageFiles * @param images ImageFiles to be matched to the given files * @return List of matched ImageFiles, with the Uri of the matching file */ public static List<ImageFile> matchFilesToImageList(@NonNull final List<DocumentFile> files, @NonNull final List<ImageFile> images) { Map<String, ImmutablePair<String, Long>> fileNameProperties = new HashMap<>(files.size()); List<ImageFile> result = new ArrayList<>(); for (DocumentFile file : files) fileNameProperties.put(removeLeadingZeroesAndExtensionCached(file.getName()), new ImmutablePair<>(file.getUri().toString(), file.length())); for (ImageFile img : images) { String imgName = removeLeadingZeroesAndExtensionCached(img.getName()); if (fileNameProperties.containsKey(imgName)) { ImmutablePair<String, Long> property = fileNameProperties.get(imgName); if (property != null) result.add(img.setFileUri(property.left).setSize(property.right).setStatus(StatusContent.DOWNLOADED).setIsCover(imgName.equals(Consts.THUMB_FILE_NAME))); } else Timber.i(">> img dropped %s", imgName); } return result; } /** * Create the list of ImageFiles from the given folder * * @param context Context to be used * @param folder Folder to read the images from * @return List of ImageFiles corresponding to all supported pictures inside the given folder, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFolder(@NonNull final Context context, @NonNull final DocumentFile folder) { List<DocumentFile> imageFiles = FileHelper.listFiles(context, folder, ImageHelper.getImageNamesFilter()); if (!imageFiles.isEmpty()) return createImageListFromFiles(imageFiles); else return Collections.emptyList(); } /** * Create the list of ImageFiles from the given files * * @param files Files to find images into * @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFiles(@NonNull final List<DocumentFile> files) { return createImageListFromFiles(files, StatusContent.DOWNLOADED, 0, ""); } /** * Create the list of ImageFiles from the given files * * @param files Files to find images into * @param targetStatus Target status of the ImageFiles to create * @param startingOrder Starting order of the ImageFiles to create * @param namePrefix Prefix to add in front of the name of the ImageFiles to create * @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFiles( @NonNull final List<DocumentFile> files, @NonNull final StatusContent targetStatus, int startingOrder, @NonNull final String namePrefix) { Helper.assertNonUiThread(); List<ImageFile> result = new ArrayList<>(); int order = startingOrder; // Sort files by anything that resembles a number inside their names List<DocumentFile> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberFileComparator()).collect(toList()); for (DocumentFile f : fileList) { String name = namePrefix + ((f.getName() != null) ? f.getName() : ""); ImageFile img = new ImageFile(); if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true); else order++; img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(f.getUri().toString()).setStatus(targetStatus).setFileUri(f.getUri().toString()).setSize(f.length()); img.setMimeType(FileHelper.getMimeTypeFromFileName(name)); result.add(img); } return result; } public static List<ImageFile> createImageListFromZipEntries( @NonNull final Uri zipFileUri, @NonNull final List<ZipEntry> files, @NonNull final StatusContent targetStatus, int startingOrder, @NonNull final String namePrefix) { Helper.assertNonUiThread(); List<ImageFile> result = new ArrayList<>(); int order = startingOrder; // Sort files by anything that resembles a number inside their names (default entry order from ZipInputStream is chaotic) List<ZipEntry> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberZipComparator()).collect(toList()); for (ZipEntry f : fileList) { String name = namePrefix + f.getName(); String path = zipFileUri.toString() + File.separator + f.getName(); ImageFile img = new ImageFile(); if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true); else order++; img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(path).setStatus(targetStatus).setFileUri(path).setSize(f.getSize()); img.setMimeType(FileHelper.getMimeTypeFromFileName(name)); result.add(img); } return result; } /** * Comparator to be used to sort files according to their names : * - Sort according to the concatenation of all its numerical characters, if any * - If none, sort alphabetically (default string compare) */ private static class InnerNameNumberFileComparator implements Comparator<DocumentFile> { @Override public int compare(@NonNull DocumentFile o1, @NonNull DocumentFile o2) { String name1 = o1.getName(); if (null == name1) name1 = ""; String name2 = o2.getName(); if (null == name2) name2 = ""; return new InnerNameNumberComparator().compare(name1, name2); } } private static class InnerNameNumberZipComparator implements Comparator<ZipEntry> { @Override public int compare(@NonNull ZipEntry o1, @NonNull ZipEntry o2) { return new ContentHelper.InnerNameNumberComparator().compare(o1.getName(), o2.getName()); } } public static class InnerNameNumberComparator implements Comparator<String> { @Override public int compare(@NonNull String name1, @NonNull String name2) { long innerNumber1 = Helper.extractNumeric(name1); if (-1 == innerNumber1) return name1.compareTo(name2); long innerNumber2 = Helper.extractNumeric(name2); if (-1 == innerNumber2) return name1.compareTo(name2); return Long.compare(innerNumber1, innerNumber2); } } }
package me.writeily.writeilypro; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.io.File; import java.util.ArrayList; import me.writeily.writeilypro.adapter.NotesAdapter; import me.writeily.writeilypro.dialog.FilesystemDialog; import me.writeily.writeilypro.model.Constants; import me.writeily.writeilypro.model.WriteilySingleton; public class NotesFragment extends Fragment { private Context context; private View layoutView; private ListView filesListView; private TextView hintTextView; private Button previousDirButton; private File rootDir; private File currentDir; private WriteilySingleton writeilySingleton; private ArrayList<File> files; private NotesAdapter filesAdapter; private ActionMode actionMode; public NotesFragment() { super(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layoutView = inflater.inflate(R.layout.notes_fragment, container, false); hintTextView = (TextView) layoutView.findViewById(R.id.empty_hint); if (files == null) { files = new ArrayList<File>(); hintTextView.setVisibility(View.VISIBLE); hintTextView.setText(getString(R.string.empty_notes_list_hint)); } checkIfDataEmpty(); context = getActivity().getApplicationContext(); filesListView = (ListView) layoutView.findViewById(R.id.notes_listview); filesAdapter = new NotesAdapter(context, files); filesListView.setOnItemClickListener(new NotesItemClickListener()); filesListView.setMultiChoiceModeListener(new ActionModeCallback()); filesListView.setAdapter(filesAdapter); previousDirButton = (Button) layoutView.findViewById(R.id.import_header_btn); previousDirButton.setOnClickListener(new PreviousDirClickListener()); rootDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.WRITEILY_FOLDER); return layoutView; } @Override public void onResume() { writeilySingleton = WriteilySingleton.getInstance(); retrieveCurrentFolder(); listFilesInDirectory(currentDir); super.onResume(); } @Override public void onPause() { saveCurrentFolder(); super.onPause(); } private void retrieveCurrentFolder() { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(context); boolean isLastDirStored = pm.getBoolean(getString(R.string.pref_remember_directory_key), false); if (isLastDirStored) { String rememberedDir = pm.getString(getString(R.string.pref_last_open_directory), null); currentDir = (rememberedDir != null) ? new File(rememberedDir) : null; } // Two-fold check, in case user doesn't have the preference to remember directories enabled // This code remembers last directory WITHIN the app (not leaving it) if (currentDir == null) { currentDir = (writeilySingleton.getNotesLastDirectory() != null) ? writeilySingleton.getNotesLastDirectory() : rootDir; } } private void saveCurrentFolder() { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(context); boolean isLastDirStored = pm.getBoolean(getString(R.string.pref_remember_directory_key), false); if (isLastDirStored) { String saveDir = (currentDir == null) ? rootDir.getAbsolutePath() : currentDir.getAbsolutePath(); pm.edit().putString(getString(R.string.pref_last_open_directory), saveDir).apply(); } writeilySingleton.setNotesLastDirectory(currentDir); } private void promptForDirectory() { FragmentManager fragManager = getFragmentManager(); Bundle args = new Bundle(); args.putString(Constants.FILESYSTEM_ACTIVITY_ACCESS_TYPE_KEY, Constants.FILESYSTEM_FOLDER_ACCESS_TYPE); FilesystemDialog filesystemDialog = new FilesystemDialog(); filesystemDialog.setArguments(args); filesystemDialog.show(fragManager, Constants.FILESYSTEM_MOVE_DIALOG_TAG); } private void checkIfDataEmpty() { if (files.isEmpty()) { hintTextView.setVisibility(View.VISIBLE); hintTextView.setText(getString(R.string.empty_notes_list_hint)); } else { hintTextView.setVisibility(View.INVISIBLE); } } public void listFilesInCurrentDirectory() { listFilesInDirectory(new File(getCurrentDir())); } private void listFilesInDirectory(File directory) { files = new ArrayList<File>(); try { // Load from SD card files = WriteilySingleton.getInstance().addFilesFromDirectory(directory, files); } catch (Exception e) { e.printStackTrace(); } // Refresh the files adapter with the new ArrayList if (filesAdapter != null) { filesAdapter = new NotesAdapter(context, files); filesListView.setAdapter(filesAdapter); } checkDirectoryStatus(); } private void goToPreviousDir() { if (currentDir != null) { currentDir = currentDir.getParentFile(); } listFilesInDirectory(currentDir); } private void checkDirectoryStatus() { if (writeilySingleton.isRootDir(currentDir, rootDir)) { previousDirButton.setVisibility(View.GONE); currentDir = null; } else { previousDirButton.setVisibility(View.VISIBLE); } // Check if dir is empty if (writeilySingleton.isDirectoryEmpty(files)) { hintTextView.setVisibility(View.VISIBLE); hintTextView.setText(getString(R.string.empty_directory)); } else { hintTextView.setVisibility(View.INVISIBLE); } } public String getCurrentDir() { return (currentDir == null) ? getRootDir() : currentDir.getAbsolutePath(); } public void setCurrentDir(File dir) { currentDir = dir; } public String getRootDir() { return rootDir.getAbsolutePath(); } public ListView getFilesListView() { return filesListView; } public NotesAdapter getFilesAdapter() { return filesAdapter; } public void finishActionMode() { actionMode.finish(); } /** Search **/ public void search(CharSequence query) { if (query.length() > 0) { filesAdapter.getFilter().filter(query); } } public void clearSearchFilter() { filesAdapter.getFilter().filter(""); // Workaround to an (apparently) bug in Android's ArrayAdapter... not pretty filesAdapter = new NotesAdapter(context, files); filesListView.setAdapter(filesAdapter); filesAdapter.notifyDataSetChanged(); } public void clearItemSelection() { filesAdapter.notifyDataSetChanged(); } private class ActionModeCallback implements ListView.MultiChoiceModeListener { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.notes_context_menu, menu); mode.setTitle("Select files"); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { actionMode = mode; switch (item.getItemId()) { case R.id.context_menu_delete: WriteilySingleton.getInstance().deleteSelectedNotes(filesListView, filesAdapter); listFilesInDirectory(rootDir); mode.finish(); return true; case R.id.context_menu_move: promptForDirectory(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { } @Override public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) { final int numSelected = filesListView.getCheckedItemCount(); switch (numSelected) { case 0: actionMode.setSubtitle(null); break; case 1: actionMode.setSubtitle("One item selected"); break; default: actionMode.setSubtitle(numSelected + " items selected"); break; } } }; private class NotesItemClickListener implements android.widget.AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { File file = filesAdapter.getItem(i); // Refresh list if directory, else import if (file.isDirectory()) { currentDir = file; listFilesInDirectory(file); } else { File note = filesAdapter.getItem(i); Intent intent = new Intent(context, NoteActivity.class); intent.putExtra(Constants.NOTE_KEY, note); startActivity(intent); getActivity().overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_left); } } } private class PreviousDirClickListener implements View.OnClickListener { @Override public void onClick(View v) { goToPreviousDir(); } } }
package moe.mal.waifus.activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.credentials.Credential; import com.google.android.gms.common.api.ResolvingResultCallbacks; import com.google.android.gms.common.api.Status; import butterknife.BindView; import butterknife.ButterKnife; import moe.mal.waifus.Ougi; import moe.mal.waifus.R; import moe.mal.waifus.model.User; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LoginActivity extends AuthActivity { private static final int RC_SAVE = 1; @BindView(R.id.usernameField) EditText usernameField; @BindView(R.id.passwordField) EditText passwordField; @BindView(R.id.loginButton) Button loginButton; @BindView(R.id.signUpButton) Button signUpButton; private String username; private String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); if (Ougi.getInstance().getUser().isLoggedIn()) { usernameField.setText(Ougi.getInstance().getUser().getUsername()); passwordField.setText(Ougi.getInstance().getUser().getPassword()); } loginButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { loginPressed(); } } ); signUpButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { signUpPressed(); } } ); } private void attemptLogin() { Call<User> call = Ougi.getInstance().getWaifuAPI() .getUserInfo(username, User.buildAuth(username, password)); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { handleServerResponse(response, true); } @Override public void onFailure(Call<User> call, Throwable t) { handleServerResponse(null, true); } }); } private void handleServerResponse(Response<User> response, boolean login) { if ((response == null) || (response.code() != 200)) { if (login) { showToast("Those credentials weren't correct."); } else { showToast("Sign up failed. Are you already registered?"); } return; } // Create a Credential with the user's email as the ID and storing the password. We // could also add 'Name' and 'ProfilePictureURL' but that is outside the scope of this // minimal sample. final Credential credential = new Credential.Builder(username) .setPassword(password) .build(); User user = response.body(); user.setCredential(credential); Ougi.getInstance().setUser(user); // NOTE: this method unconditionally saves the Credential built, even if all the fields // are blank or it is invalid in some other way. In a real application you should contact // your app's back end and determine that the credential is valid before saving it to the // Credentials backend. Auth.CredentialsApi.save(mCredentialsApiClient, credential).setResultCallback( new ResolvingResultCallbacks<Status>(this, RC_SAVE) { @Override public void onSuccess(Status status) { } @Override public void onUnresolvableFailure(Status status) { } }); showScreen(SadActivity.class); } public boolean validate() { boolean valid = true; String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); if (username.isEmpty()) { usernameField.setError("enter a valid username address"); valid = false; } else { usernameField.setError(null); } if (password.isEmpty()) { passwordField.setError("enter a valid password"); valid = false; } else { passwordField.setError(null); } return valid; } public void onValidateFailed() { showToast("Please enter valid credentials."); } public void loginPressed() { if (!validate()) { onValidateFailed(); return; } username = usernameField.getText().toString(); password = passwordField.getText().toString(); attemptLogin(); } public void signUpPressed() { if (!validate()) { onValidateFailed(); return; } username = usernameField.getText().toString(); password = passwordField.getText().toString(); Call<User> call = Ougi.getInstance().getWaifuAPI() .signUp(username, password); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { handleServerResponse(response, false); } @Override public void onFailure(Call<User> call, Throwable t) { handleServerResponse(null, false); } }); } }
package edu.oakland.OUSoft.items; import edu.oakland.OUSoft.linkedList.LLNode; import java.time.LocalTime; /** * "includes information for a course such as course name, instructor, class meeting time, etc. * The instructor field of a Course object should reference to a valid Instructor object." */ public class Course implements LLNode<Course> { private Course link; private String ID; private String name; private Instructor instructor; private LocalTime timeStart; private LocalTime timeEnd; /** * Create a new Course * * @param name The name of the Course */ public Course(String ID, String name) { this.ID = ID; this.name = name; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } @Override public String toString() { return this.ID + ": " + this.name + ", Taught by " + this.getInstructor().getFirstName() + " " + this.getInstructor().getLastName() + ". " + "Start: " + timeStart.toString() + " End: " + timeEnd.toString(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Instructor getInstructor() { return instructor; } public void setInstructor(Instructor instructor) { this.instructor = instructor; } public LocalTime getTimeStart() { return timeStart; } public void setTimeStart(LocalTime timeStart) { this.timeStart = timeStart; } public LocalTime getTimeEnd() { return timeEnd; } public void setTimeEnd(LocalTime timeEnd) { this.timeEnd = timeEnd; } /** * Get the link to the next object * * @return The next object in the list */ @Override public Course getLink() { return this.link; } /** * Set the link to the next object * * @param Link The next object in the list */ @Override public void setLink(Course Link) { this.link = Link; } }
package h2o.dao.advanced; import h2o.common.concurrent.factory.InstanceFactory; import h2o.common.concurrent.factory.InstanceTable; import h2o.common.spring.util.Assert; import h2o.common.util.collections.builder.ListBuilder; import h2o.common.util.debug.Mode; import h2o.common.util.lang.StringUtil; import h2o.dao.Dao; import h2o.dao.DbUtil; import h2o.dao.colinfo.ColInfo; import java.util.List; public final class DaoBasicUtil<E> { private static boolean CACHE = Mode.isUserMode("DONT_CACHE_ENTITYPARSER") ? false : true; private static final InstanceTable<Class<?>,EntityParser> ENTITYPARSER_TABLE = new InstanceTable<Class<?>, EntityParser>( new InstanceFactory<EntityParser>() { @Override public EntityParser create( Object entityClazz ) { return new EntityParser( (Class<?>) entityClazz ); } @Override public void free(Object id, EntityParser entityParser) { } }); private final Dao dao; private final EntityParser entityParser; public DaoBasicUtil( Class<?> entityClazz ) { this( entityClazz , DbUtil.getDao() ); } public DaoBasicUtil( Class<?> entityClazz , Dao dao ) { this.dao = dao; this.entityParser = CACHE ? ENTITYPARSER_TABLE.getAndCreateIfAbsent(entityClazz) : new EntityParser( entityClazz ); } public void add( E entity ) { dao.update( DbUtil.sqlBuilder.buildInsertSql(entity) , entity ); } public void batAdd( List<E> entities ) { dao.batchUpdate( DbUtil.sqlBuilder.buildInsertSqlIncludeNull( entities.get(0) ) , entities ); } public int edit( E entity ) { return editByColInfos( entity , checkAndGetPk() ); } public int editByUnique( E entity , String uniqueName ) { return editByColInfos( entity , checkAndGetUnique(uniqueName) ); } public int editByAttr( E entity , String... attrNames ) { return editByColInfos( entity , checkAndGetAttrs(attrNames) ); } private int editByColInfos( E entity , List<ColInfo> cis ) { List<String> ks = ListBuilder.newList(); for ( ColInfo ci : cis ) { ks.add( ci.attrName ); } return dao.update( DbUtil.sqlBuilder.buildUpdateSql3( entity , buildWhereStr( cis ) , (String[])ks.toArray( new String[ks.size() ] ) ) , entity ); } public E get( E entity ) { return this.get( entity , false ); } public E getAndLock( E entity ) { return this.get( entity , true ); } public E get( E entity , boolean lock ) { return getByColInfos( entity , checkAndGetPk() , lock ); } public E getByUnique( E entity , boolean lock , String uniqueName ) { return getByColInfos( entity , checkAndGetUnique(uniqueName) , lock ); } public E getByAttr( E entity , boolean lock , String... attrNames ) { return getByColInfos( entity , checkAndGetAttrs(attrNames) , lock ); } private E getByColInfos( E entity , List<ColInfo> cis , boolean lock ) { StringBuilder sql = new StringBuilder(); StringUtil.append( sql , "select * from " , this.entityParser.getTableName() , " where " , buildWhereStr( cis ) ); if( lock ) { sql.append(" for update "); } return (E)dao.get( entity.getClass() , sql.toString() , entity ); } public List<E> loadByAttr( E entity , String... attrNames ) { List<ColInfo> cis = checkAndGetAttrs(attrNames); StringBuilder sql = new StringBuilder(); StringUtil.append( sql , "select * from " , this.entityParser.getTableName() , " where " , buildWhereStr( cis ) ); return (List<E>)dao.load( entity.getClass() , sql.toString() , entity ); } public int del( E entity ) { return delByColInfos( entity , checkAndGetPk() ); } public int delByUnique( E entity , String uniqueName ) { return delByColInfos( entity , checkAndGetUnique(uniqueName) ); } public int delByAttr( E entity , String... attrNames ) { return delByColInfos( entity , checkAndGetAttrs(attrNames) ); } private int delByColInfos( E entity , List<ColInfo> cis ) { return dao.update( "delete from " + this.entityParser.getTableName() + " where " + buildWhereStr( cis ) , entity ); } private List<ColInfo> checkAndGetPk() { List<ColInfo> cis = this.entityParser.getPK(); Assert.notEmpty( cis , "Primary key not defined" ); return cis; } private List<ColInfo> checkAndGetUnique( String uniqueName ) { List<ColInfo> cis = this.entityParser.getUnique( uniqueName ); Assert.notEmpty( cis , "The unique constraint '" + uniqueName + "' is undefined" ); return cis; } private List<ColInfo> checkAndGetAttrs( String[] attrNames ) { List<ColInfo> cis = this.entityParser.getAttrs( attrNames ); Assert.notEmpty( cis , "Column is undefined" ); return cis; } private String buildWhereStr(List<ColInfo> wColInfos ) { StringBuilder sb = new StringBuilder(); int i = 0; for ( ColInfo ci : wColInfos ) { if ( i++ > 0 ) { sb.append( " and "); } sb.append( ci.colName ); sb.append( " = :"); sb.append( ci.attrName ); } sb.append( ' ' ); return sb.toString(); } }
package org.neo4j.kernel.ha; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.factory.GraphDatabaseBuilder; import org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory; import org.neo4j.test.ProcessStreamHandler; import org.neo4j.test.TargetDirectory; import org.neo4j.tooling.GlobalGraphOperations; @Ignore public class TestHardKillIT { private static final File path = TargetDirectory.forTest( TestHardKillIT.class ).graphDbDir( true ); private ProcessStreamHandler processHandler; @Test public void testMasterSwitchHappensOnKillMinus9() throws Exception { Process proc = null; try { proc = run( "1" ); Thread.sleep( 12000 ); HighlyAvailableGraphDatabase dbWithId2 = startDb( 2 ); HighlyAvailableGraphDatabase dbWithId3 = startDb( 3 ); assertTrue( !dbWithId2.isMaster() ); assertTrue( !dbWithId3.isMaster() ); proc.destroy(); proc = null; Thread.sleep( 60000 ); assertTrue( dbWithId2.isMaster() ); assertTrue( !dbWithId3.isMaster() ); HighlyAvailableGraphDatabase oldMaster = startDb( 1 ); long oldMasterNode = createNamedNode( oldMaster, "Old master" ); assertEquals( oldMasterNode, getNamedNode( dbWithId2, "Old master" ) ); } finally { if (proc != null) { proc.destroy(); } } } private long getNamedNode( HighlyAvailableGraphDatabase db, String name ) { for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() ) if ( name.equals( node.getProperty( "name", null ) ) ) return node.getId(); fail( "Couldn't find named node '" + name + "' at " + db ); // The lone above will prevent this return from happening return -1; } private long createNamedNode( HighlyAvailableGraphDatabase db, String name ) { Transaction tx = db.beginTx(); try { Node node = db.createNode(); node.setProperty( "name", name ); tx.success(); return node.getId(); } finally { tx.finish(); } } private Process run( String machineId ) throws IOException { List<String> allArgs = new ArrayList<String>( Arrays.asList( "java", "-cp", System.getProperty( "java" + ".class.path" ), TestHardKillIT.class.getName() ) ); allArgs.add( machineId ); Process process = Runtime.getRuntime().exec( allArgs.toArray( new String[allArgs.size()] )); processHandler = new ProcessStreamHandler( process, false ); processHandler.launch(); return process; } /* * Used to launch the master instance */ public static void main( String[] args ) { int machineId = Integer.parseInt( args[0] ); HighlyAvailableGraphDatabase db = startDb( machineId ); } private static HighlyAvailableGraphDatabase startDb( int serverId ) { GraphDatabaseBuilder builder = new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( path( serverId ) ) .setConfig( HaSettings.server_id, "" + serverId ) .setConfig( HaSettings.ha_server, ":" + (8001 + serverId) ) .setConfig( HaSettings.initial_hosts, "127.0.0.1:5002,127.0.0.1:5003,127.0.0.1:5004" ) .setConfig( HaSettings.cluster_server, "127.0.0.1:" + (5001 + serverId) ) .setConfig( HaSettings.tx_push_factor, "0" ) ; HighlyAvailableGraphDatabase db = (HighlyAvailableGraphDatabase) builder.newGraphDatabase(); Transaction tx = db.beginTx(); tx.finish(); try { Thread.sleep( 2000 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } return db; } private static String path( int i ) { return new File( path, "" + i ).getAbsolutePath(); } }
package org.commcare.android.framework; import java.lang.reflect.Field; import org.commcare.android.database.user.models.ACase; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.tasks.templates.CommCareTask; import org.commcare.android.tasks.templates.CommCareTaskConnector; import org.commcare.android.util.SessionUnavailableException; import org.commcare.dalvik.activities.CommCareHomeActivity; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.dialogs.DialogController; import org.commcare.util.SessionFrame; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.util.NoLocalizedTextException; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.AudioController; import org.odk.collect.android.views.media.MediaState; import org.odk.collect.android.views.media.MediaEntity; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.os.Build; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; /** * Base class for CommCareActivities to simplify * common localization and workflow tasks * * @author ctsims * */ public abstract class CommCareActivity<R> extends FragmentActivity implements CommCareTaskConnector<R>, AudioController, DialogController { protected final static int DIALOG_PROGRESS = 32; protected final static String DIALOG_TEXT = "cca_dialog_text"; public final static String KEY_DIALOG_FRAG = "dialog_fragment"; StateFragment stateHolder; private boolean firstRun = true; //Fields for implementation of AudioController private MediaEntity currentEntity; private AudioButton currentButton; private MediaState stateBeforePause; //fields for implementing task transitions for CommCareTaskConnector boolean inTaskTransition; boolean shouldDismissDialog = true; @Override @TargetApi(14) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = this.getSupportFragmentManager(); stateHolder = (StateFragment) fm.findFragmentByTag("state"); // If the state holder is null, create a new one for this activity if (stateHolder == null) { stateHolder = new StateFragment(); fm.beginTransaction().add(stateHolder, "state").commit(); } else { if(stateHolder.getPreviousState() != null){ firstRun = stateHolder.getPreviousState().isFirstRun(); loadPreviousAudio(stateHolder.getPreviousState()); } else{ firstRun = true; } } if(this.getClass().isAnnotationPresent(ManagedUi.class)) { this.setContentView(this.getClass().getAnnotation(ManagedUi.class).value()); loadFields(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayShowCustomEnabled(true); //Add breadcrumb bar BreadcrumbBarFragment bar = (BreadcrumbBarFragment) fm.findFragmentByTag("breadcrumbs"); // If the state holder is null, create a new one for this activity if (bar == null) { bar = new BreadcrumbBarFragment(); fm.beginTransaction().add(bar, "breadcrumbs").commit(); } } } private void loadPreviousAudio(AudioController oldController) { MediaEntity oldEntity = oldController.getCurrMedia(); if (oldEntity != null) { this.currentEntity = oldEntity; oldController.removeCurrentMediaEntity(); } } private void playPreviousAudio() { if (currentEntity == null) return; switch (currentEntity.getState()) { case PausedForRenewal: playCurrentMediaEntity(); break; case Paused: break; case Playing: case Ready: System.out.println("WARNING: state in loadPreviousAudio is invalid"); } } /* * Method to override in classes that need some functions called only once at the start * of the life cycle. Called by the CommCareActivity onResume() method; so, after the onCreate() * method of all classes, but before the onResume() of the overriding activity. State maintained in * stateFragment Fragment and firstRun boolean. */ public void fireOnceOnStart(){ // override when needed } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: try { CommCareApplication._().getCurrentSession().clearAllState(); } catch(SessionUnavailableException sue) { // probably won't go anywhere with this } // app icon in action bar clicked; go home Intent intent = new Intent(this, CommCareHomeActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void loadFields() { CommCareActivity oldActivity = stateHolder.getPreviousState(); Class c = this.getClass(); for(Field f : c.getDeclaredFields()) { if(f.isAnnotationPresent(UiElement.class)) { UiElement element = f.getAnnotation(UiElement.class); try{ f.setAccessible(true); try { View v = this.findViewById(element.value()); f.set(this, v); if(oldActivity != null) { View oldView = (View)f.get(oldActivity); if(oldView != null) { if(v instanceof TextView) { ((TextView)v).setText(((TextView)oldView).getText()); } v.setVisibility(oldView.getVisibility()); v.setEnabled(oldView.isEnabled()); continue; } } if(element.locale() != "") { if(v instanceof TextView) { ((TextView)v).setText(Localization.get(element.locale())); } else { throw new RuntimeException("Can't set the text for a " + v.getClass().getName() + " View!"); } } } catch (IllegalArgumentException e) { e.printStackTrace(); throw new RuntimeException("Bad Object type for field " + f.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't access the activity field for some reason"); } } finally { f.setAccessible(false); } } } } protected CommCareActivity getDestroyedActivityState() { return stateHolder.getPreviousState(); } protected boolean isTopNavEnabled() { return false; } boolean visible = false; /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override @TargetApi(11) protected void onResume() { super.onResume(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //If we're in honeycomb this is taken care of by the fragment } else { this.setTitle(getTitle(this, getActivityTitle())); } visible = true; playPreviousAudio(); //set that this activity has run if(isFirstRun()){ fireOnceOnStart(); setActivityHasRun(); } } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); visible = false; if (currentEntity != null) saveEntityStateAndClear(); } protected boolean isInVisibleState() { return visible; } /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); if (currentEntity != null) attemptSetStateToPauseForRenewal(); } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#connectTask(org.commcare.android.tasks.templates.CommCareTask) */ @Override public <A, B, C> void connectTask(CommCareTask<A, B, C, R> task) { //If stateHolder is null here, it's because it is restoring itself, it doesn't need //this step wakelock(); stateHolder.connectTask(task); //If we've left an old dialog showing during the task transition and it was from the same task //as the one that is starting, don't dismiss it CustomProgressDialog currDialog = getCurrentDialog(); if (currDialog != null && currDialog.getTaskId() == task.getTaskId()) { shouldDismissDialog = false; } } /* * (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#getReceiver() */ @Override public R getReceiver() { return (R)this; } /** * Override these to control the UI for your task */ /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#startBlockingForTask() */ @Override public void startBlockingForTask(int id) { //attempt to dismiss the dialog from the last task before showing this one attemptDismissDialog(); //ONLY if shouldDismissDialog = true, i.e. if we chose to dismiss the last dialog during transition, show a new one if (id >= 0 && shouldDismissDialog) { this.showProgressDialog(id); } } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#stopBlockingForTask() */ @Override public void stopBlockingForTask(int id) { if (id >= 0) { if (inTaskTransition) { shouldDismissDialog = true; } else { dismissProgressDialog(); } } unlock(); } @Override public void startTaskTransition() { inTaskTransition = true; } @Override public void stopTaskTransition() { inTaskTransition = false; attemptDismissDialog(); //reset shouldDismissDialog to true after this transition cycle is over shouldDismissDialog = true; } //if shouldDismiss flag has not been set to false in the course of a task transition, //then dismiss the dialog public void attemptDismissDialog() { if (shouldDismissDialog) { dismissProgressDialog(); } } /** * Handle an error in task execution. * * @param e */ protected void taskError(Exception e) { //TODO: For forms with good error reporting, integrate that Toast.makeText(this, Localization.get("activity.task.error.generic", new String[] {e.getMessage()}), Toast.LENGTH_LONG).show(); Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, e.getMessage()); } /** * Display exception details as a pop-up to the user. * * @param e Exception to handle */ protected void displayException(Exception e) { String mErrorMessage = e.getMessage(); AlertDialog mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(Localization.get("notification.case.predicate.title")); mAlertDialog.setMessage(Localization.get("notification.case.predicate.action", new String[] {mErrorMessage})); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: finish(); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(Localization.get("dialog.ok"), errorListener); mAlertDialog.show(); } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#taskCancelled(int) */ @Override public void taskCancelled(int id) { } public void cancelCurrentTask() { stateHolder.cancelTask(); } @Override public void onStop() { super.onStop(); } private void wakelock() { int lockLevel = getWakeLockingLevel(); if(lockLevel == -1) { return;} stateHolder.wakelock(lockLevel); } private void unlock() { stateHolder.unlock(); } /** * @return The WakeLock flags that should be used for this activity's tasks. -1 * if this activity should not acquire/use the wakelock for tasks */ protected int getWakeLockingLevel() { return -1; } //Graphical stuff below, needs to get modularized public void TransplantStyle(TextView target, int resource) { //get styles from here TextView tv = (TextView)View.inflate(this, resource, null); int[] padding = {target.getPaddingLeft(), target.getPaddingTop(), target.getPaddingRight(),target.getPaddingBottom() }; target.setTextColor(tv.getTextColors().getDefaultColor()); target.setTypeface(tv.getTypeface()); target.setBackgroundDrawable(tv.getBackground()); target.setPadding(padding[0], padding[1], padding[2], padding[3]); } /** * The right-hand side of the title associated with this activity. * * This will update dynamically as the activity loads/updates, but if * it will ever have a value it must return a blank string when one * isn't available. * * @return */ public String getActivityTitle() { return null; } public static String getTopLevelTitleName(Context c) { String topLevel = null; try { topLevel = Localization.get("app.display.name"); return topLevel; } catch(NoLocalizedTextException nlte) { //nothing, app display name is optional for now. } return c.getString(org.commcare.dalvik.R.string.title_bar_name); } public static String getTitle(Context c, String local) { String topLevel = getTopLevelTitleName(c); String[] stepTitles = new String[0]; try { stepTitles = CommCareApplication._().getCurrentSession().getHeaderTitles(); //See if we can insert any case hacks int i = 0; for(String[] step : CommCareApplication._().getCurrentSession().getFrame().getSteps()){ try { if(SessionFrame.STATE_DATUM_VAL.equals(step[0])) { //Haaack if("case_id".equals(step[1])) { ACase foundCase = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class).getRecordForValue(ACase.INDEX_CASE_ID, step[2]); stepTitles[i] = Localization.get("title.datum.wrapper", new String[] { foundCase.getName()}); } } } catch(Exception e) { //TODO: Your error handling is bad and you should feel bad } ++i; } } catch(SessionUnavailableException sue) { } String returnValue = topLevel; for(String title : stepTitles) { if(title != null) { returnValue += " > " + title; } } if(local != null) { returnValue += " > " + local; } return returnValue; } public void setActivityHasRun(){ this.firstRun = false; } public boolean isFirstRun(){ return this.firstRun; } /* * All methods for implementation of AudioController */ @Override public MediaEntity getCurrMedia() { return currentEntity; } @Override public void refreshCurrentAudioButton(AudioButton clicked) { if (currentButton != null && currentButton != clicked) { currentButton.setStateToReady(); } } @Override public void setCurrent(MediaEntity e, AudioButton b) { refreshCurrentAudioButton(b); setCurrent(e); setCurrentAudioButton(b); } @Override public void setCurrent(MediaEntity e) { releaseCurrentMediaEntity(); currentEntity = e; } @Override public void setCurrentAudioButton(AudioButton b) { currentButton = b; } @Override public void releaseCurrentMediaEntity() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); mp.reset(); mp.release(); } currentEntity = null; } @Override public void playCurrentMediaEntity() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); mp.start(); currentEntity.setState(MediaState.Playing); } } @Override public void pauseCurrentMediaEntity() { if (currentEntity != null && currentEntity.getState().equals(MediaState.Playing)) { MediaPlayer mp = currentEntity.getPlayer(); mp.pause(); currentEntity.setState(MediaState.Paused); } } @Override public Object getMediaEntityId() { return currentEntity.getId(); } @Override public void attemptSetStateToPauseForRenewal() { if (stateBeforePause != null && stateBeforePause.equals(MediaState.Playing)) { currentEntity.setState(MediaState.PausedForRenewal); } } @Override public void saveEntityStateAndClear() { stateBeforePause = currentEntity.getState(); pauseCurrentMediaEntity(); refreshCurrentAudioButton(null); } @Override public void setMediaEntityState(MediaState state) { currentEntity.setState(state); } @Override public void removeCurrentMediaEntity() { currentEntity = null; } /** All methods for implementation of DialogController **/ @Override public void updateProgress(String updateText, int taskId) { CustomProgressDialog mProgressDialog = getCurrentDialog(); if (mProgressDialog != null) { if (mProgressDialog.getTaskId() == taskId) { mProgressDialog.updateMessage(updateText); } else { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Attempting to update a progress dialog whose taskId does not match the" + "task for which the update message was intended."); } } } @Override public void showProgressDialog(int taskId) { CustomProgressDialog dialog = generateProgressDialog(taskId); if (dialog != null) { dialog.show(getSupportFragmentManager(), KEY_DIALOG_FRAG); } } @Override public CustomProgressDialog getCurrentDialog() { return (CustomProgressDialog) getSupportFragmentManager(). findFragmentByTag(KEY_DIALOG_FRAG); } @Override public void dismissProgressDialog() { CustomProgressDialog mProgressDialog = getCurrentDialog(); if (mProgressDialog != null && mProgressDialog.isAdded()) { mProgressDialog.dismissAllowingStateLoss(); } } @Override public CustomProgressDialog generateProgressDialog(int taskId) { //dummy method for compilation, implementation handled in those subclasses that need it return null; } }
package org.catacombae.io; import org.catacombae.util.Util; /** * A substream class using a SynchronizedReadableRandomAccess as source for a * completely independent stream with its own file pointer and access to the * same data. * * @author Erik Larsson */ public class ReadableRandomAccessSubstream extends BasicReadableRandomAccessStream { private static final boolean DEBUG = Util.booleanEnabledByProperties(false, "org.catacombae.debug", "org.catacombae.io.debug", "org.catacombae.io." + ReadableRandomAccessSubstream.class.getSimpleName() + ".debug"); private SynchronizedReadableRandomAccess sourceStream; private long internalFP; private boolean closed = false; public ReadableRandomAccessSubstream(SynchronizedReadableRandomAccess iSourceStream) { this.sourceStream = iSourceStream; this.internalFP = 0; sourceStream.addReference(this); } @Override public synchronized void close() throws RuntimeIOException { if(closed) { throw new RuntimeException(this + " already closed!"); } sourceStream.removeReference(this); closed = true; } @Override public void seek(long pos) throws RuntimeIOException { internalFP = pos; } @Override public long length() throws RuntimeIOException { return sourceStream.length(); } @Override public long getFilePointer() throws RuntimeIOException { return internalFP; } @Override public int read(byte[] b, int pos, int len) throws RuntimeIOException { if(DEBUG) { System.err.println("ReadableRandomAccessSubstream.read(byte[" + b.length + "], " + pos + ", " + len + ");"); System.err.println(" readFrom: " + internalFP); } int bytesRead = sourceStream.readFrom(internalFP, b, pos, len); if(bytesRead > 0) { internalFP += bytesRead; if(DEBUG) { System.err.println(" returning: " + bytesRead); } return bytesRead; } else { if(DEBUG) { System.err.println(" returning: -1"); } return -1; } } }
package org.odk.collect.android.views.media; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.media.MediaPlayer; import android.net.Uri; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.MediaController; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import org.commcare.android.util.MediaUtil; import org.commcare.dalvik.R; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.dalvik.preferences.DeveloperPreferences; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.odk.collect.android.utilities.QRCodeEncoder; import org.odk.collect.android.views.ResizingImageView; import java.io.File; /** * This layout is used anywhere we can have image/audio/video/text. * TODO: Put this in a layout file!!!! * * @author carlhartung */ public class MediaLayout extends RelativeLayout { private static final String t = "AVTLayout"; private TextView mView_Text; private AudioButton mAudioButton; private ImageButton mVideoButton; private ResizingImageView mImageView; private TextView mMissingImage; public MediaLayout(Context c) { super(c); mView_Text = null; mAudioButton = null; mImageView = null; mMissingImage = null; mVideoButton = null; } public void setAVT(TextView text, String audioURI, String imageURI, final String videoURI, final String bigImageURI) { setAVT(text, audioURI, imageURI, videoURI, bigImageURI, null); } public void setAVT(TextView text, String audioURI, String imageURI, final String videoURI, final String bigImageURI, final String qrCodeContent) { setAVT(text, audioURI, imageURI, videoURI, bigImageURI, null, null); } public void setAVT(TextView text, String audioURI, String imageURI, final String videoURI, final String bigImageURI, final String qrCodeContent, String inlineVideoURI) { mView_Text = text; RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams audioParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams videoParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams questionTextPaneParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams mediaPaneParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); RelativeLayout questionTextPane = new RelativeLayout(this.getContext()); questionTextPane.setId(2342134); if (audioURI != null) { mAudioButton = new AudioButton(getContext(), audioURI, true); // random ID to be used by the relative layout. mAudioButton.setId(3245345); } // Then set up the video button if (videoURI != null) { mVideoButton = new ImageButton(getContext()); mVideoButton.setImageResource(android.R.drawable.ic_media_play); mVideoButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String videoFilename = ""; try { videoFilename = ReferenceManager._().DeriveReference(videoURI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e(t, "Invalid reference exception"); e.printStackTrace(); } File videoFile = new File(videoFilename); if (!videoFile.exists()) { // We should have a video clip, but the file doesn't exist. String errorMsg = getContext().getString(R.string.file_missing, videoFilename); Log.e(t, errorMsg); Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show(); return; } Intent i = new Intent("android.intent.action.VIEW"); /** * Creates a video view for the provided URI or an error view elaborating why the video * couldn't be displayed. * * @param inlineVideoURI JavaRosa Reference URI * @param viewLayoutParams the layout params that will be applied to the view. Expect to be * mutated by this method */ private View getInlineVideoView(String inlineVideoURI, RelativeLayout.LayoutParams viewLayoutParams) { String error = null; try { final String videoFilename = ReferenceManager._().DeriveReference(inlineVideoURI).getLocalURI(); int[] maxBounds = getMaxCenterViewBounds(); File videoFile = new File(videoFilename); if(!videoFile.exists()) { error = "No video file found at: " + videoFilename; } else { //NOTE: This has odd behavior when you have a text input on the screen //since clicking the video view to bring up controls has weird effects. //since we shotgun grab the focus for the input widget. final MediaController ctrl = new MediaController(this.getContext()); VideoView videoView = new VideoView(this.getContext()); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { ctrl.show(); } }); videoView.setVideoPath(videoFilename); videoView.setMediaController(ctrl); ctrl.setAnchorView(videoView); //These surprisingly get re-jiggered as soon as the video is loaded, so we //just want to give it the _max_ bounds, it'll pick the limiter and shrink //itself when it's ready. viewLayoutParams.width = maxBounds[0]; viewLayoutParams.height = maxBounds[1]; return videoView; } }catch(InvalidReferenceException ire) { Log.e(t, "invalid video reference exception"); ire.printStackTrace(); error = "Invalid reference: " + ire.getReferenceString(); } if(error != null) { mMissingImage = new TextView(getContext()); mMissingImage.setText(error); mMissingImage.setPadding(10, 10, 10, 10); mMissingImage.setId(234873453); return mMissingImage; } else { return null; } } private boolean useResizingImageView() { // only allow ResizingImageView to be used if not also using smart inflation return !CommCarePreferences.isSmartInflationEnabled() && (ResizingImageView.resizeMethod.equals("full") || ResizingImageView.resizeMethod.equals("half") || ResizingImageView.resizeMethod.equals("width")); } /** * @return The appropriate max size of an image view pane in this widget. returned as an int * array of [width, height] */ private int[] getMaxCenterViewBounds() { DisplayMetrics metrics = this.getContext().getResources().getDisplayMetrics(); int maxWidth = metrics.widthPixels; int maxHeight = metrics.heightPixels; // subtract height for textview and buttons, if present if(mView_Text != null){ maxHeight = maxHeight - mView_Text.getHeight(); } if(mVideoButton != null){ maxHeight = maxHeight - mVideoButton.getHeight(); } else if(mAudioButton != null){ maxHeight = maxHeight - mAudioButton.getHeight(); } // reduce by third for safety return new int[] {maxWidth, (2 * maxHeight)/3}; } /** * This adds a divider at the bottom of this layout. Used to separate * fields in lists. */ public void addDivider(ImageView v) { RelativeLayout.LayoutParams dividerParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if (mImageView != null) { dividerParams.addRule(RelativeLayout.BELOW, mImageView.getId()); } else if (mMissingImage != null) { dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId()); } else if (mVideoButton != null) { dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId()); } else if (mAudioButton != null) { dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId()); } else if (mView_Text != null) { // No picture dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId()); } else { Log.e(t, "Tried to add divider to uninitialized ATVWidget"); return; } addView(v, dividerParams); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (visibility != View.VISIBLE) { if (mAudioButton != null) { mAudioButton.endPlaying(); } } } }
package org.sana.android.activity; import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask.Status; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.content.LocalBroadcastManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import org.sana.R; import org.sana.analytics.Runner; import org.sana.android.Constants; import org.sana.android.activity.settings.Settings; import org.sana.android.app.DefaultActivityRunner; import org.sana.android.app.Locales; import org.sana.android.content.Intents; import org.sana.android.content.Uris; import org.sana.android.content.core.PatientWrapper; import org.sana.android.db.ModelWrapper; import org.sana.android.fragment.AuthenticationDialogFragment.AuthenticationDialogListener; import org.sana.android.media.EducationResource; import org.sana.android.procedure.Procedure; import org.sana.android.provider.EncounterTasks; import org.sana.android.provider.Encounters; import org.sana.android.provider.Observers; import org.sana.android.provider.Patients; import org.sana.android.provider.Procedures; import org.sana.android.provider.Subjects; import org.sana.android.provider.Tasks; import org.sana.android.service.ISessionCallback; import org.sana.android.service.ISessionService; import org.sana.android.service.impl.DispatchService; import org.sana.android.service.impl.SessionService; import org.sana.android.task.ResetDatabaseTask; import org.sana.android.util.Logf; import org.sana.android.util.SanaUtil; import org.sana.api.IModel; import org.sana.api.task.EncounterTask; import org.sana.core.Observer; import org.sana.core.Patient; import org.sana.net.Response; import java.io.IOException; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.UUID; /** * Main Activity which handles user authentication and initializes services that * Sana uses. * @author Sana Dev Team */ public class MainActivity extends BaseActivity implements AuthenticationDialogListener{ public static final String TAG = MainActivity.class.getSimpleName(); public static final String CLOSE = "org.sana.android.intent.CLOSE"; public static final int AUTHENTICATE = 0; public static final int PICK_PATIENT = 1; public static final int PICK_ENCOUNTER = 2; public static final int PICK_ENCOUNTER_TASK = 3; public static final int PICK_PROCEDURE = 4; public static final int RUN_PROCEDURE = 5; public static final int RUN_REGISTRATION = 6; public static final int VIEW_ENCOUNTER = 7; public static final int SETTINGS = 8; public static final int EXECUTE_TASK = 9; // public static final int VIEW_ASSIGNED_TASK = 10; private Runner<Intent,Intent> runner; private String mWorkflow = "org.sana.android.app.workflow.DEFAULT"; // This is the initial state private Intent mIntent = new Intent(Intent.ACTION_MAIN); private Intent mPrevious = new Intent(Intent.ACTION_MAIN); private boolean checkUpdate = true; private boolean init = false; @Override protected void onNewIntent(Intent intent){ Logf.D(TAG, "onNewIntent()"); //super.onNewIntent(intent); onUpdateAppState(intent); dump(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ Logf.I(TAG, "onActivityResult()", ((resultCode == RESULT_OK)? "OK":"CANCELED" )); Uri uri = Uri.EMPTY; switch(resultCode){ case RESULT_CANCELED: switch(requestCode){ case AUTHENTICATE: Logf.W(TAG, "onActivityResult()", "Authentication failure..Exiting"); finish(); case SETTINGS: break; } //onNext(data); break; case RESULT_OK: if(data != null) onUpdateAppState(data); Uri dataUri = (data != null)? data.getData(): Uri.EMPTY; Intent intent = new Intent(); onSaveAppState(intent); switch(requestCode){ case AUTHENTICATE: hideViewsByRole(); break; case RUN_REGISTRATION: mEncounter = Uri.EMPTY; break; case PICK_PATIENT: intent.setAction(Intent.ACTION_PICK) .setData(Procedures.CONTENT_URI) .putExtras(data); startActivityForResult(intent, PICK_PROCEDURE); break; case PICK_PROCEDURE: intent.setAction(Intents.ACTION_RUN_PROCEDURE) .setData(data.getData()) .putExtras(data); startActivityForResult(intent, RUN_PROCEDURE); break; case PICK_ENCOUNTER: //intent.setAction(Intent.ACTION_VIEW) //.setData(data.getData()) intent.setClass(this, ObservationList.class) .setData(data.getData()) .putExtras(data); startActivity(intent); break; case PICK_ENCOUNTER_TASK: // Implement new behavior here // Patient(subject) is stored in the task Uri taskUri = data.getData(); // Get patient Uri - Task subject column = patient uuid // mTask = taskUri; final String[] projection = new String[]{ Tasks.Contract.SUBJECT }; String patientUUID = null; Cursor cursor = null; try { cursor = getContentResolver().query(taskUri, projection, null, null, null); if (cursor.getCount() == 1 && cursor.moveToFirst()) { patientUUID = cursor.getString(0); } // Uri Patient_uri = Uris.withAppendedUuid(taskUri, Tasks.Contract.SUBJECT); Uri Patient_uri = Uris.withAppendedUuid( Patients.CONTENT_URI, patientUUID); // Create new Intent to launch PatientView Intent intent1 = new Intent(this, PatientViewActivity.class); // Set new Intent data Uri to the Patient uri intent1.setData(Patient_uri); // Start Activity // startActivityForResult(intent1); startActivity(intent1); } catch (Exception e){ } finally { if(cursor != null) cursor.close(); } break; case EXECUTE_TASK: dump(); startService(data); markTaskStatusCompleted(mTask,mEncounter); mTask = Uri.EMPTY; mEncounter = Uri.EMPTY; break; case RUN_PROCEDURE: case Intents.RUN_PROCEDURE: // Handle any content type specific actions switch(Uris.getDescriptor(dataUri)) { case Uris.ENCOUNTER_ITEM: // startService(data); case Uris.ENCOUNTER_UUID: break; default: } switch(Uris.getDescriptor(dataUri)){ case Uris.SUBJECT_ITEM: startService(data); case Uris.SUBJECT_UUID: // startService(data); // Add the task creation after the // new patient has been sent to the // dispatch service Patient patient = getPatient( data.getData()); /** * TODO * work on the procedure to return and the observer */ List<EncounterTask> tasks = getVisits( patient,null,null); createTasks(tasks); break; default: } mEncounter = Uri.EMPTY; String onComplete = data.getStringExtra(Intents.EXTRA_ON_COMPLETE); // If procedure onComplete was set start it if(!TextUtils.isEmpty(onComplete)) { try { Intent next = null; next = Intent.parseUri(onComplete, Intent .URI_INTENT_SCHEME); onSaveAppState(next); startActivityForResult(next, RUN_PROCEDURE); } catch (Exception e) { e.printStackTrace(); } } break; // case VIEW_ASSIGNED_TASK: // //Uri task = data.getParcelableExtra(Intents.EXTRA_TASK); // int flags1 = data.getFlags(); // uri = Uri.EMPTY; // if(data.hasCategory(Intents.CATEGORY_TASK_COMPLETE)){ // Log.i(TAG, "....Task complete: "+ mTask); // uri = intent.getParcelableExtra(Intents.EXTRA_ENCOUNTER); // intent.setClass(this, ObservationList.class) // .setData(uri) // .putExtras(data); // startActivity(intent); // } else { // Log.i(TAG, "....Task in progress: "+ mTask); // //markTaskStatusInProgress(mTask); // uri = intent.getParcelableExtra(Intents.EXTRA_PROCEDURE); // intent.setAction(Intent.ACTION_VIEW) // .setData(uri) // .putExtras(data); // startActivityForResult(intent, EXECUTE_TASK); // break; default: } //data.setAction(Intents.ACTION_OK); //onNext(data); break; } } public void hideViewsByRole(){ mRoot = isAdmin(mObserver); if(!mRoot){ LinearLayout main = (LinearLayout) findViewById(R.id.main_root); // TODO RBAC //main.removeView(findViewById(R.id.btn_main_select_patient)); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Logf.I(TAG, "onCreate()"); mDebug = this.getResources().getBoolean(R.bool.debug); Locales.updateLocale(this, getString(R.string.force_locale)); setContentView(R.layout.main); /* if(mDebug) setContentView(R.layout.main); else setContentView(R.layout.main_ht); */ // TODO rethink where to integrate this checkUpdate(Uris.buildUri("package", "org.sana.provider" , "")); runner = new DefaultActivityRunner(); init(); if(Uris.isEmpty(mObserver)){ onNext(null); } } @Override protected void onPause() { super.onPause(); Logf.I(TAG, "onPause()"); LocalBroadcastManager.getInstance(this.getApplicationContext()).unregisterReceiver(mReceiver); } @Override protected void onResume() { super.onResume(); Logf.I(TAG, "onResume()"); IntentFilter filter = new IntentFilter(Response.RESPONSE); try{ filter.addDataType(Encounters.CONTENT_ITEM_TYPE); filter.addDataType(EncounterTasks.CONTENT_ITEM_TYPE); } catch (Exception e){} LocalBroadcastManager.getInstance(this.getApplicationContext()).registerReceiver(mReceiver, filter); //bindSessionService(); // This prevents us from relaunching the login on every resume dump(); hideViewsByRole(); } @Override protected void onStart(){ super.onStart(); Logf.I(TAG, "onStart()"); // We want the session service to be running if Main has been started // and until after it stops. startService(new Intent(SessionService.ACTION_START)); } @Override protected void onStop() { Log.d(TAG, "onDestroy()"); super.onStop(); // kill the session service if there is nothing else bound if(mBound) stopService(new Intent(SessionService.ACTION_START)); else stopService(new Intent(SessionService.ACTION_START)); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy()"); super.onDestroy(); } // Option menu codes private static final int OPTION_EXPORT_DATABASE = 0; private static final int OPTION_SETTINGS = 1; private static final int OPTION_SYNC = 2; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if(mDebug){ menu.add(0, OPTION_EXPORT_DATABASE, 0, "Export Data"); } if(mRoot || mDebug){ menu.add(0, OPTION_SETTINGS, 1, getString(R.string.menu_settings)); menu.add(0, OPTION_SYNC, 2, getString(R.string.menu_sync)); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case OPTION_EXPORT_DATABASE: try { boolean exported = SanaUtil.exportDatabase(this, "models.db"); } catch (IOException e) { e.printStackTrace(); } return true; case OPTION_SETTINGS: Intent i = new Intent(Intent.ACTION_PICK); i.setClass(this, Settings.class); startActivityForResult(i, SETTINGS); return true; case OPTION_SYNC: //doUpdatePatientDatabase(); return true; } return false; } @Override public void onBackPressed() { Log.d("CDA", "onBackPressed Called"); clearCredentials(); onClearAppState(); onNext(null); } /** * Launches the home activity */ void showHomeActivity() { Intent intent = new Intent(); intent.setClass(this, MainActivity.class); // pass the app state fields onSaveAppState(intent); } /** * Launches the authentication activity */ void showAuthenticationActivity() { Intent intent = new Intent(); intent.setClass(this, AuthenticationActivity.class); startActivityForResult(intent, AUTHENTICATE); } protected void onNext(Intent intent){ if(intent == null){ showAuthenticationActivity(); return; } intent.putExtra(Intents.EXTRA_REQUEST, mIntent); mPrevious = Intents.copyOf(mIntent); mIntent = runner.next(intent); if(mIntent.hasExtra(Intents.EXTRA_TASKS)){ Logf.D(TAG, "onNext(Intent)", "sending tasks to dispatcher"); Intent tasks = new Intent(MainActivity.this, DispatchService.class); tasks.putExtra(Intents.EXTRA_TASKS, mIntent.getParcelableArrayListExtra(Intents.EXTRA_TASKS)); startService(tasks); } if(mIntent.getAction().equals(Intents.ACTION_FINISH)){ Logf.D(TAG, "onNext(Intent)", "finishing"); finish(); } else { Logf.D(TAG, "onNext(Intent)", "starting for result"); this.onSaveAppState(mIntent); startActivityForResult(mIntent, Intents.parseActionDescriptor(mIntent)); } } /** * Checks whether the application needs to be updated. */ protected void checkUpdate(Uri uri){ if(!checkUpdate){ Intent update = new Intent("org.sana.intent.action.READ"); update.setData(uri);//, "application/vnd.android.package-archive"); startService(update); checkUpdate = false; } } int loginsRemaining = 0; protected boolean mBound = false; protected ISessionService mService = null; // connector to the session service protected ServiceConnection mConnection = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG, "ServiceConnection.onServiceConnected()"); mService = ISessionService.Stub.asInterface(service); mBound = true; } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "ServiceConnection.onServiceDisconnected()"); mService = null; mBound = false; } }; // handles initiating the session service binding protected void bindSessionService(){ Log.i(TAG, "bindSessionService()"); if(!mBound){ if(mService == null){ bindService(new Intent(SessionService.ACTION_START), mConnection, Context.BIND_AUTO_CREATE); //bindService(new Intent(SessionService.BIND_REMOTE), mCallbackConnection, Context.BIND_AUTO_CREATE); } } } // handles disconnecting from the session service bindings protected void unbindSessionService(){ // Unbind from the service if (mBound){ // Detach unbindService(mConnection); mBound = false; } } private ResetDatabaseTask mResetDatabaseTask; void init(){ Logf.D(TAG, "init()"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean dbInit =preferences.getBoolean(Constants.DB_INIT, false); PreferenceManager.setDefaultValues(this, R.xml.settings, true); PreferenceManager.setDefaultValues(this, R.xml.network_settings,true); PreferenceManager.setDefaultValues(this, R.xml.resource_settings, true); PreferenceManager.setDefaultValues(this, R.xml.notifications, true); if(!dbInit){ Logf.D(TAG, "init()", "Initializing"); doClearDatabase(); // Make sure directory structure is in place on external drive EducationResource.intializeDevice(); Procedure.intializeDevice(); preferences.edit().putBoolean(Constants.DB_INIT, true).commit(); init = true; } else { Logf.D(TAG, "init()", "reloading"); // RELOAD Database //preferences.edit().clear().commit(); //PreferenceManager.setDefaultValues(this, R.xml.network_settings,true); doClearDatabase(new Uri[]{ Procedures.CONTENT_URI }); preferences.edit().putBoolean(Constants.DB_INIT, true).commit(); } preferences.edit().putString("s_phone_name", getPhoneNumber()).commit(); } /** Executes a task to clear out the database */ private void doClearDatabase() { // TODO: context leak if(mResetDatabaseTask!= null && mResetDatabaseTask.getStatus() != Status.FINISHED) return; mResetDatabaseTask = (ResetDatabaseTask) new ResetDatabaseTask(this,true).execute(this); } private void doClearDatabase(Uri[] uris) { // TODO: context leak if(mResetDatabaseTask!= null && mResetDatabaseTask.getStatus() != Status.FINISHED) return; mResetDatabaseTask = (ResetDatabaseTask) new ResetDatabaseTask(this,true,uris).execute(this); } private void saveLocalTaskState(Bundle outState){ final ResetDatabaseTask rTask = mResetDatabaseTask; if (rTask != null && rTask.getStatus() != Status.FINISHED) { rTask.cancel(true); outState.putBoolean("_resetdb", true); } } @Override protected void onRestoreInstanceState(Bundle inState) { super.onRestoreInstanceState(inState); try { mIntent = Intent.parseUri(inState.getString("mIntent"), Intent.URI_INTENT_SCHEME); mPrevious = Intent.parseUri(inState.getString("mPrevious"), Intent.URI_INTENT_SCHEME); checkUpdate = inState.getBoolean("update"); } catch (URISyntaxException e) { e.printStackTrace(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveLocalTaskState(outState); outState.putString("mIntent", mIntent.toUri(Intent.URI_INTENT_SCHEME)); outState.putString("mPrevious", mPrevious.toUri(Intent.URI_INTENT_SCHEME)); outState.putBoolean("update", checkUpdate); } void showAuthenticationDialog(){ } /* (non-Javadoc) * @see org.sana.android.fragment.AuthenticationDialogFragment.AuthenticationDialogListener#onDialogPositiveClick(android.support.v4.app.DialogFragment) */ @Override public void onDialogPositiveClick(DialogFragment dialog) { EditText userEdit = (EditText)dialog.getDialog().findViewById(R.id.username); EditText userPassword = (EditText)dialog.getDialog().findViewById(R.id.username); } /* (non-Javadoc) * @see org.sana.android.fragment.AuthenticationDialogFragment.AuthenticationDialogListener#onDialogNegativeClick(android.support.v4.app.DialogFragment) */ @Override public void onDialogNegativeClick(DialogFragment dialog) { try{ dialog.dismiss(); } catch(Exception e){ e.printStackTrace(); } finally { if(dialog.getId() == R.id.dialog_authentication) this.finish(); } } /** * Retrieves the device phone number using the TelephonyManager * @return the device phone number */ public String getPhoneNumber(){ TelephonyManager tMgr =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); String phoneNumber = tMgr.getLine1Number(); return phoneNumber; } public void submit(View v){ Intent intent = null; switch(v.getId()){ case R.id.btn_main_select_patient: intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(Subjects.CONTENT_URI, Subjects.CONTENT_TYPE); startActivityForResult(intent, PICK_PATIENT); break; case R.id.btn_main_transfers: intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Encounters.CONTENT_URI, Encounters.CONTENT_TYPE); startActivityForResult(intent, PICK_ENCOUNTER); break; case R.id.btn_main_register_patient: intent = new Intent(Intent.ACTION_INSERT); //intent.setDataAndType(Patients.CONTENT_URI, Subjects.CONTENT_TYPE); intent.setDataAndType(Patients.CONTENT_URI, Subjects.CONTENT_TYPE) .putExtra(Intents.EXTRA_PROCEDURE, Uris.withAppendedUuid(Procedures.CONTENT_URI, getString(R.string.procs_subject_short_form1))) .putExtra(Intents.EXTRA_PROCEDURE_ID,R.raw .mapping_form_midwife) .putExtra(Intents.EXTRA_OBSERVER, mObserver); startActivityForResult(intent, Intents.RUN_PROCEDURE); break; case R.id.btn_main_view_ambulance_drivers: intent = new Intent(MainActivity.this, AmbulanceDriverListActivity.class); Log.d(TAG,intent.toUri(Intent.URI_INTENT_SCHEME)); startActivity(intent); break; /* case R.id.btn_main_procedures: intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(Procedures.CONTENT_URI, Procedures.CONTENT_TYPE); startActivityForResult(intent, PICK_PROCEDURE); break;*/ case R.id.btn_main_tasks: intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(EncounterTasks.CONTENT_URI, EncounterTasks.CONTENT_TYPE); onSaveAppState(intent); startActivityForResult(intent, PICK_ENCOUNTER_TASK); // Toast.makeText(MainActivity.this, "testing", Toast.LENGTH_SHORT).show(); break; case R.id.btn_training_mode: String subj = getString(R.string.tr_subject); // String proc = getString(R.string.tr_procedure); String reg_uuid = getString(R.string.procs_subject_short_form); intent = new Intent(Intent.ACTION_VIEW) .setData(Uris.withAppendedUuid(Procedures.CONTENT_URI, reg_uuid)) .putExtra(Intents.EXTRA_SUBJECT, Uris.withAppendedUuid(Subjects.CONTENT_URI, subj)) .putExtra(Intents.EXTRA_OBSERVER, mObserver); startActivityForResult(intent, RUN_PROCEDURE); break; /* case R.id.button_call_ambulance: intent = new Intent(MainActivity.this, AmbulanceDriverListActivity.class); startActivity(intent); break; */ /*case R.id.btn_main_unregistered_subject: intent = new Intent(Intents.ACTION_RUN_PROCEDURE); intent.setDataAndType(Patients.CONTENT_URI, Subjects.CONTENT_TYPE) .putExtra(Intents.EXTRA_PROCEDURE, Uris.withAppendedUuid(Procedures.CONTENT_URI, getString(R.string.procs_subject_short_form))) .putExtra(Intents.EXTRA_PROCEDURE_ID,R.raw .registration_short_en) .putExtra(Intents.EXTRA_OBSERVER, mObserver); startActivityForResult(intent, Intents.RUN_PROCEDURE); break;*/ case R.id.btn_exit: clearCredentials(); onClearAppState(); onNext(null); break; } } // The callback to get data from the asynchronous calls private ISessionCallback mCallback = new ISessionCallback.Stub() { @Override public void onValueChanged(int arg0, String arg1, String arg2) throws RemoteException { Log.d(TAG, ".mCallback.onValueChanged( " +arg0 +", "+arg1+ ", " + arg2+ " )"); Bundle data = new Bundle(); data.putString(Intents.EXTRA_INSTANCE, arg1); data.putString(Intents.EXTRA_OBSERVER, arg2); mHandler.sendMessage(mHandler.obtainMessage(arg0, data)); } }; // This is the handler which responds to the SessionService // It expects a Message with msg.what = FAILURE or SUCCESS // and a Bundle with the new session key if successful. private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { int state = msg.what; Log.i(TAG, "handleMessage(): " + msg.what); cancelProgressDialogFragment(); switch(state){ case SessionService.FAILURE: loginsRemaining // TODO use a string resource Toast.makeText(MainActivity.this, "Username and password incorrect! Logins remaining: " +loginsRemaining, Toast.LENGTH_SHORT).show(); showAuthenticationDialog(); break; case SessionService.SUCCESS: loginsRemaining = 0; Bundle b = msg.getData(); //(Bundle)msg.obj; Uri uri = Uris.withAppendedUuid(Observers.CONTENT_URI, b.getString(Intents.EXTRA_OBSERVER)); Log.i(TAG, uri.toString()); onUpdateAppState(b); Intent data = new Intent(); data.setData(uri); data.putExtras(b); onSaveAppState(data); mIntent = new Intent(Intent.ACTION_MAIN); break; default: Log.e(TAG, "Should never get here"); } // Finish if remaining logins => 0 if(loginsRemaining == 0){ finish(); } } }; public boolean isAdmin(Uri observer){ Log.i(TAG,"isAdmin() " + observer); if(Uris.isEmpty(observer)) return false; String uuid = observer.getLastPathSegment(); String[] admins = this.getResources().getStringArray(R.array.admins); boolean admin = false; for(String adminUuid:admins) if(uuid.compareTo(adminUuid) == 0){ admin = true; break; } Log.d(TAG,"...." + admin); return admin; } public void handleTaskStatusChange(Uri task, org.sana.api.task.Status status, String now){ handleTaskStatusChange(task,status,now,null); } public void handleTaskStatusChange(Uri task, org.sana.api.task.Status status, String now, ContentValues values){ if(now == null) now = timeStamp(); if(values == null) values = new ContentValues(); Log.i(TAG, "Updating status: " + now + " --> " + status + " --> " + values.size() + " --> " + task); // update in db values.put(Tasks.Contract.STATUS, status.toString()); values.put(Tasks.Contract.MODIFIED, now); // Convert to a Bundle so that we can pass it Log.d(TAG, "FORM data"); Bundle form = new Bundle(); form.putString(Tasks.Contract.STATUS,String.valueOf(status.code)); form.putString(Tasks.Contract.MODIFIED,now); int updated = getContentResolver().update(task,values,null,null); // send to sync Intent intent = new Intent(Intents.ACTION_UPDATE,task); intent.putExtra("form", form); startService(intent); } public void markTaskStatusInProgress(Uri task){ Log.i(TAG, "markStatusInProgress(): " + task); org.sana.api.task.Status status = org.sana.api.task.Status.IN_PROGRESS; String now = timeStamp(); ContentValues values = new ContentValues(); values.put(Tasks.Contract.STATUS, "In Progress"); values.put(Tasks.Contract.MODIFIED, now); values.put(Tasks.Contract.STARTED, now); getContentResolver().update(task,values,null,null); Bundle form = new Bundle(); form.putString(Tasks.Contract.STATUS, "In Progress"); form.putString(Tasks.Contract.MODIFIED,now); form.putString(Tasks.Contract.STARTED,now); // send to sync Intent intent = new Intent(Intents.ACTION_UPDATE,task); intent.putExtra("form", form); startService(intent); } public void markTaskStatusCompleted(Uri task, Uri encounter){ Log.i(TAG, "markStatusCompleted(): " + task); org.sana.api.task.Status status = org.sana.api.task.Status.COMPLETED; String now = timeStamp(); String uuid = ModelWrapper.getUuid(encounter,getContentResolver()); ContentValues values = new ContentValues(); values.put(Tasks.Contract.STATUS, status.toString()); values.put(Tasks.Contract.COMPLETED, now); values.put(EncounterTasks.Contract.ENCOUNTER, uuid); values.put(Tasks.Contract.MODIFIED, now); int updated = getContentResolver().update(task, values, null, null); Bundle form = new Bundle(); form.putString(Tasks.Contract.STATUS, status.toString()); form.putString(Tasks.Contract.MODIFIED,now); form.putString(Tasks.Contract.COMPLETED,now); form.putString(EncounterTasks.Contract.ENCOUNTER, uuid); // send to sync Intent intent = new Intent(Intents.ACTION_UPDATE,task); intent.putExtra("form", form); startService(intent); } static final SimpleDateFormat sdf = new SimpleDateFormat(IModel.DATE_FORMAT, Locale.US); public String timeStamp(String key, ContentValues values){ Date now = new Date(); String nowStr = sdf.format(now); values.put(key, nowStr); return nowStr; } public String timeStamp(){ Date now = new Date(); String nowStr = sdf.format(now); return nowStr; } // public Patient getPatient(Uri uri){ //uri Patient px = PatientWrapper.get(this, uri); // return px; public Patient getPatient(Uri uri){ return (Patient)PatientWrapper.get(this, uri); } public void setEdd(Patient patient){ Date lmd = patient.getLMD(); Calendar c3= Calendar.getInstance(); c3.setTime(new Date()); Date x1 = c3.getTime(); long day = x1.getTime() - lmd.getTime(); long days1 = day / (1000 * 60 * 60 * 24); int age1 = (int) (days1); int gestation_days = 280; c3.setTime(lmd); c3.add(Calendar.DATE, gestation_days); // age.setText((age1)); Date edd1 = c3.getTime(); ContentValues val = new ContentValues(); val.put(Patients.Contract.EDD,sdf.format(edd1)); String uuid1 = mSubject.getLastPathSegment(); Uri uri = Uris.withAppendedUuid(Patients.CONTENT_URI,uuid1); getContentResolver().update( uri, val,null,null); } public EncounterTask calculateFirstVisit(Patient patient, Procedure procedure, Observer observer) { EncounterTask task = new EncounterTask(); //assignedTo =task.observer; // assignedTo. //Uris.withAppendedUuid(EncounterTasks.CONTENT_URI, task.getUuid()); Date lmd = patient.getLMD(); String anc = patient.getANC_status(); Date dob = patient.getDob(); Date anc_visit = patient.getANC_visit(); //String uuid = this.get String uuid1 = mSubject.getLastPathSegment(); String uuid3 = mObserver.getLastPathSegment(); /** * TODO * think about the procedure or activity to call when the due date is reached */ /*If girls is greater than 12 weeks pregnant and has never attended ANC* *Get the day of week when she is mapped * Add the number of days to either Tuesday or Thursday */ Calendar c2 = Calendar.getInstance(); c2.setTime(new Date()); Date x = c2.getTime(); long days = x.getTime() - lmd.getTime(); int day_of_week = c2.get(Calendar.DAY_OF_WEEK); //String Due_Date; // long age = x.getTime() - dob.getTime(); long no_LMD = days / (60 * 24 * 60 * 1000); Log.i(TAG, "the number of lmd days are" + no_LMD); if (no_LMD > 84 && anc.equals("No")) { Calendar c1 = Calendar.getInstance(); //c1.setTime(new Date()); switch (day_of_week) { case Calendar.MONDAY: c1.add(Calendar.DATE, 8); // Adding 8 days Date due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.TUESDAY: c1.add(Calendar.DATE, 7); // Adding 7 days due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.WEDNESDAY: c1.add(Calendar.DATE, 6); // Adding 6 days due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.THURSDAY: c1.add(Calendar.DATE, 5); // Adding 5 days due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.FRIDAY: c1.add(Calendar.DATE, 4); // Adding 4 days due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.SATURDAY: c1.add(Calendar.DATE, 3); // Adding 3 days due_on= c1.getTime(); task.due_on = due_on; break; case Calendar.SUNDAY: c1.add(Calendar.DATE, 2); // Adding 2 days due_on= c1.getTime(); task.due_on = due_on; break; default: } } /* If girl is less than 12 weeks pregnant and has never attended ANC Get a random number , add it to the day she was mapped Then work out the logic of her appointment being between Tuesday and Thursday */ else if(no_LMD < 84 && anc.equals("No")){ Calendar c = Calendar.getInstance(); int new_lmd = (int)no_LMD; // cast lmd to int (maximum of random number to be generated) int rand_diff = 84-new_lmd; // The minimum of the random number to be generated Random rand = new Random(); int randomNum = rand.nextInt((rand_diff-0) ) ; // generate a random number btn current weeks of gestation and the maximum days left to go to 12th week // if (randomNum<42) c.add(Calendar.DATE,randomNum);// Add random number to current date Date rand_due_on = c.getTime(); //get date instance c.setTime(rand_due_on); // set it as calendar object int due_day_of_week = c.get(Calendar.DAY_OF_WEEK); // get day of week Log.i(TAG,"the new date is" +rand_due_on); switch(due_day_of_week) { case Calendar.MONDAY: c.add(Calendar.DATE, 3); // Adding 4 days Date due_on =c.getTime(); task.due_on = due_on; break; case Calendar.TUESDAY: c.add(Calendar.DATE, 2); // Adding 3 days due_on =c.getTime(); task.due_on = due_on; break; case Calendar.WEDNESDAY: c.add(Calendar.DATE, 6); // Adding 6 days due_on =c.getTime(); task.due_on = due_on; break; case Calendar.THURSDAY: c.add(Calendar.DATE, 5); // Adding 5 days due_on =c.getTime(); task.due_on = due_on; break; case Calendar.FRIDAY: c.add(Calendar.DATE, 4); // Adding 4 days due_on =c.getTime(); task.due_on = due_on; break; case Calendar.SATURDAY: c.add(Calendar.DATE, 5); // Adding 3 days due_on =c.getTime(); task.due_on = due_on; break; case Calendar.SUNDAY: c.add(Calendar.DATE, 4); // Adding 2 days due_on= c.getTime(); task.due_on = due_on; break; default: } } /*if girl has ever attended ANC *Pick ANC date from card */ else if (anc.equals("Yes")){ Date due_on = patient.getANC_visit(); task.due_on = due_on; } return task; } public List<EncounterTask> getVisits(Patient patient, Procedure procedure, Observer observer){ //invoke methods from (2) above //adding the encounterTasks to the list List<EncounterTask> encounterTasks = new ArrayList<EncounterTask>(); encounterTasks.add(calculateFirstVisit(patient, procedure,observer)); return encounterTasks; } public void createTasks(List<EncounterTask> tasks) { org.sana.api.task.Status status = org.sana.api.task.Status.ASSIGNED ; //String uuid = ModelWrapper.getUuid(Patients.CONTENT_URI,getContentResolver()); String uuid1 = mObserver.getLastPathSegment(); String uuid3 = mSubject.getLastPathSegment(); //EncounterTask task= new EncounterTask(); String uuid = UUID.randomUUID().toString(); //InputStream uuid= this.getResources().openRawResource(R.raw.midwife_appointment_notexml); //tasks. //UUID uui= UUID.randomUUID(); //String uuid2 = uuid.toString(); //String uuid1 = uui.toString(); //String uuid2 = uui.toString(); for ( EncounterTask task : tasks) { ContentValues values = new ContentValues(); values.put(Tasks.Contract.OBSERVER,uuid1); values.put(Tasks.Contract.SUBJECT,uuid3.toString()); values.put(Tasks.Contract.PROCEDURE,getString(R.string.cfg_appointment_note)); values.put(Tasks.Contract.DUE_DATE, sdf.format(task.due_on)); values.put(Tasks.Contract.STATUS, status.toString()); values.put(Tasks.Contract.UUID,uuid); getContentResolver().insert( EncounterTasks.CONTENT_URI, values); Bundle form = new Bundle(); form.putString(Tasks.Contract.OBSERVER,uuid1 ); form.putString(Tasks.Contract.SUBJECT,uuid3.toString()); form.putString(Tasks.Contract.PROCEDURE,getString(R.string.cfg_appointment_note)); form.putString(Tasks.Contract.DUE_DATE, sdf.format(task.due_on)); form.putString(Tasks.Contract.STATUS,status.toString()); form.putString(Tasks.Contract.UUID,uuid); // send to sync Intent intent = new Intent(Intents.ACTION_CREATE, Uris.withAppendedUuid (EncounterTasks.CONTENT_URI, uuid)); intent.putExtra("form", form); startService(intent); } } @Override protected void handleBroadcast(Intent data){ Log.i(TAG,"handleBroadcast()"); cancelProgressDialogFragment(); String message = data.getStringExtra(Response.MESSAGE); Response.Code code = Response.Code.get(data.getIntExtra(Response.CODE,-1)); Uri uri = data.getData(); int descriptor = (uri != null)? Uris.getDescriptor(uri): Uris.NO_MATCH; Log.i(TAG,"....descriptor="+descriptor); switch(code){ case CONTINUE: switch(descriptor){ case Uris.ENCOUNTER_ITEM: case Uris.ENCOUNTER_UUID: if(showProgressForeground()) showProgressDialogFragment(message); break; default: } default: switch(descriptor){ case Uris.ENCOUNTER_ITEM: case Uris.ENCOUNTER_UUID: hideProgressDialogFragment(); if(!TextUtils.isEmpty(message)){ Toast.makeText(this,message,Toast.LENGTH_LONG).show(); } break; default: } } } }
package com.esri.hadoop.hive; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.UDFType; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.log4j.Logger; import com.esri.core.geometry.OperatorContains; import com.esri.core.geometry.Geometry.GeometryAccelerationDegree; import com.esri.core.geometry.ogc.OGCGeometry; @UDFType(deterministic = true) @Description( name = "ST_Contains", value = "_FUNC_(geometry1, geometry2) - return true if geometry1 contains geometry2", extended = "Example:\n" + "SELECT _FUNC_(st_polygon(1,1, 1,4, 4,4, 4,1), st_point(2, 3) from src LIMIT 1; -- return true\n" + "SELECT _FUNC_(st_polygon(1,1, 1,4, 4,4, 4,1), st_point(8, 8) from src LIMIT 1; -- return false" ) public class ST_Contains extends GenericUDF { private static Logger LOG = Logger.getLogger(ST_Contains.class); private static final int NUM_ARGS = 2; private static final int GEOM_1 = 0; private static final int GEOM_2 = 1; private transient HiveGeometryOIHelper geomHelper1; private transient HiveGeometryOIHelper geomHelper2; private transient OperatorContains opContains = OperatorContains.local(); private transient boolean firstRun = true; private transient boolean geom1IsAccelerated = false; @Override public ObjectInspector initialize(ObjectInspector[] OIs) throws UDFArgumentException { if (OIs.length != NUM_ARGS) { throw new UDFArgumentException("The function ST_Contains requires 2 arguments."); } geomHelper1 = HiveGeometryOIHelper.create(OIs[GEOM_1], GEOM_1); geomHelper2 = HiveGeometryOIHelper.create(OIs[GEOM_2], GEOM_2); if (LOG.isDebugEnabled()) { LOG.debug("OI[0]=" + geomHelper1); LOG.debug("OI[1]=" + geomHelper2); } firstRun = true; geom1IsAccelerated = false; return PrimitiveObjectInspectorFactory.javaBooleanObjectInspector; } @Override public Object evaluate(DeferredObject[] args) throws HiveException { OGCGeometry geom1 = geomHelper1.getGeometry(args); OGCGeometry geom2 = geomHelper2.getGeometry(args); if (geom1 == null || geom2 == null) { return false; } if (firstRun && geomHelper1.isConstant()) { // accelerate geometry 1 for quick contains operations since it is constant geom1IsAccelerated = opContains.accelerateGeometry(geom1.getEsriGeometry(), geom1.getEsriSpatialReference(), GeometryAccelerationDegree.enumMedium); } firstRun = false; return opContains.execute(geom1.getEsriGeometry(), geom2.getEsriGeometry(), geom1.getEsriSpatialReference(), null); } public void close() { if (geom1IsAccelerated && geomHelper1 != null && geomHelper1.getConstantGeometry() != null) { OperatorContains.deaccelerateGeometry(geomHelper1.getConstantGeometry().getEsriGeometry()); } } @Override public String getDisplayString(String[] args) { return String.format("returns true if %s contains %s", args[0], args[1]); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.davis.frames; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFrame; import eu.seebetter.ini.chips.DavisChip; import java.nio.file.Paths; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.chip.Chip2D; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventio.AEDataFile; import net.sf.jaer.eventprocessing.EventFilter; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.graphics.DavisRenderer; import net.sf.jaer.graphics.AEViewer.PlayMode; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.ImageDisplay.Legend; import org.apache.commons.io.FilenameUtils; @Description("Method to acquire a frame from a stream of APS sample events") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class ApsFrameExtractor extends EventFilter2D { protected JFrame apsFrame = null; protected ImageDisplay apsDisplay; // actually draws the display protected DavisChip apsChip = null; protected boolean newFrameAvailable; // boolen set true if during processing packet a new frame was completed protected boolean useExtRender = false; // useExtRender means using something like OpenCV to render the // data. If false, the rawFrame is displayed private float[] resetBuffer, signalBuffer; // the two buffers that are subtracted to get the DDS frame /** * Raw pixel values from sensor, before conversion, brightness, etc. */ protected float[] rawFrame; /** * The RGB pixel buffer * */ protected float[] apsDisplayPixmapBuffer; /** * Cooked pixel values, after brightness, contrast, log intensity * conversion, etc. */ protected float[] displayFrame; // format is 0-1 mono values public int width, height, maxADC, maxIDX; // maxADC is max binary value, i.e. 10 bits =1023 private float grayValue; protected boolean showAPSFrameDisplay = getBoolean("showAPSFrameDisplay", true); protected final Legend apsDisplayLegend; /** * A PropertyChangeEvent with this value is fired when a new frame has been * completely read. The oldValue is null. The newValue is the float[] * displayFrame that will be rendered. */ public static final String EVENT_NEW_FRAME = DavisRenderer.EVENT_NEW_FRAME_AVAILBLE; private int lastFrameTimestamp = -1; public static enum Extraction { ResetFrame, SignalFrame, CDSframe } private boolean invertIntensity = getBoolean("invertIntensity", false); private boolean preBufferFrame = getBoolean("preBufferFrame", true); private boolean logCompress = getBoolean("logCompress", false); private boolean logDecompress = getBoolean("logDecompress", false); private float displayContrast = getFloat("displayContrast", 1.0f); private float displayBrightness = getFloat("displayBrightness", 0.0f); public Extraction extractionMethod = Extraction.valueOf(getString("extractionMethod", "CDSframe")); /** Shows pixel info */ protected MouseInfo mouseInfo = null; public ApsFrameExtractor(final AEChip chip) { super(chip); apsDisplay = ImageDisplay.createOpenGLCanvas(); mouseInfo = new MouseInfo(getApsDisplay()); apsDisplay.addMouseMotionListener(mouseInfo); apsFrame = new JFrame("APS Frame"); apsFrame.setPreferredSize(new Dimension(400, 400)); apsFrame.getContentPane().add(apsDisplay, BorderLayout.CENTER); apsFrame.pack(); apsFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { setShowAPSFrameDisplay(false); } }); apsDisplayLegend = apsDisplay.addLegend("", 0, 0); final float[] displayColor = new float[3]; displayColor[0] = 1.0f; displayColor[1] = 1.0f; displayColor[2] = 1.0f; apsDisplayLegend.color = displayColor; setPropertyTooltip("invertIntensity", "Inverts grey scale, e.g. for raw samples of signal level"); setPropertyTooltip("preBufferFrame", "Only display and use complete frames; otherwise display APS samples as they arrive"); setPropertyTooltip("logCompress", "Should the displayBuffer be log compressed"); setPropertyTooltip("logDecompress", "Should the logComressed displayBuffer be rendered in log scale (true) or linearly (false)"); setPropertyTooltip("displayContrast", "Gain for the rendering of the APS display, i.e. displayed values are processed with (raw+brightness)*displayContrast"); setPropertyTooltip("displayBrightness", "Offset for the rendering of the APS display, i.e, value added to all displayed pixel values, scaled as in maxADC (>1)"); setPropertyTooltip("extractionMethod", "Method to extract a frame; CDSframe is the final result after subtracting signal from reset frame. Signal and reset frames are the raw sensor output before correlated double sampling."); setPropertyTooltip("showAPSFrameDisplay", "Shows the JFrame frame display if true"); } @Override public void initFilter() { if (DavisChip.class.isAssignableFrom(chip.getClass())) { getApsDisplay().checkPixmapAllocation(); apsChip = (DavisChip) chip; maxADC = apsChip.getMaxADC(); newFrameAvailable = false; width = chip.getSizeX(); // note that on initial construction width=0 because this constructor is called while // chip is still being built height = chip.getSizeY(); maxIDX = width * height; getApsDisplay().setImageSize(width, height); resetBuffer = new float[width * height]; signalBuffer = new float[width * height]; displayFrame = new float[width * height]; rawFrame = new float[width * height]; apsDisplayPixmapBuffer = new float[3 * width * height]; Arrays.fill(resetBuffer, 0.0f); Arrays.fill(signalBuffer, 0.0f); Arrays.fill(displayFrame, 0.0f); Arrays.fill(rawFrame, 0.0f); Arrays.fill(apsDisplayPixmapBuffer, 0.0f); } else { EventFilter.log.warning("The filter ApsFrameExtractor can only be used for chips that extend the ApsDvsChip class"); return; } } @Override public void resetFilter() { } @Override public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) { checkDisplay(); if (getEnclosedFilterChain() != null) { in = getEnclosedFilterChain().filterPacket(in); } final ApsDvsEventPacket packet = (ApsDvsEventPacket) in; if (packet == null) { return null; } if (packet.getEventClass() != ApsDvsEvent.class) { EventFilter.log.warning("wrong input event class, got " + packet.getEventClass() + " but we need to have " + ApsDvsEvent.class); return null; } final Iterator apsItr = packet.fullIterator(); while (apsItr.hasNext()) { final ApsDvsEvent e = (ApsDvsEvent) apsItr.next(); if (e.isApsData()) { processApsEvent(e); } else { processDvsEvent(e); } } if (showAPSFrameDisplay) { getApsDisplay().repaint(); } return in; } /** * Call this before processing packet */ protected void checkDisplay() { if (showAPSFrameDisplay && !apsFrame.isVisible()) { apsFrame.setVisible(true); } } /** * Subclasses can override this method to process DVS events * * @param e */ protected void processDvsEvent(ApsDvsEvent e) { } /** * Process a single APS data sample or flag event (e.g. end of frame * readout). Following call, newFrame could be set * * @param e * @see #hasNewFrameAvailable() */ public void processApsEvent(final ApsDvsEvent e) { if (!e.isApsData()) { return; } // if(e.isStartOfFrame())timestampFrameStart=e.timestampFrameStart; final ApsDvsEvent.ReadoutType type = e.getReadoutType(); final float val = e.getAdcSample(); final int idx = getIndex(e.x, e.y); if (idx >= maxIDX) { return; } if (e.isStartOfFrame()) { if (newFrameAvailable && useExtRender) { EventFilter.log.warning("new frame started even though old frame was never gotten by anyone calling getNewFrame()"); } } if (e.isEndOfFrame()) { if (preBufferFrame && (rawFrame != null) && !useExtRender && showAPSFrameDisplay) { displayPreBuffer(); } newFrameAvailable = true; lastFrameTimestamp = e.timestamp; processNewFrame(); getSupport().firePropertyChange(ApsFrameExtractor.EVENT_NEW_FRAME, null, displayFrame); return; } switch (type) { case SignalRead: signalBuffer[idx] = val; break; case ResetRead: default: resetBuffer[idx] = val; break; } switch (extractionMethod) { case ResetFrame: rawFrame[idx] = resetBuffer[idx]; break; case SignalFrame: rawFrame[idx] = signalBuffer[idx]; break; case CDSframe: default: rawFrame[idx] = resetBuffer[idx] - signalBuffer[idx]; break; } if (invertIntensity) { rawFrame[idx] = maxADC - rawFrame[idx]; } if (logCompress) { if (rawFrame[idx] < 1) { rawFrame[idx] = 0; } else { rawFrame[idx] = (float) Math.log(rawFrame[idx]); } } if (logCompress && logDecompress) { grayValue = scaleGrayValue((float) (Math.exp(rawFrame[idx]))); } else { grayValue = scaleGrayValue(rawFrame[idx]); } displayFrame[idx] = grayValue; if (!preBufferFrame && !useExtRender && showAPSFrameDisplay) { getApsDisplay().setPixmapGray(e.x, e.y, grayValue); } else { apsDisplayPixmapBuffer[3 * idx] = grayValue; apsDisplayPixmapBuffer[(3 * idx) + 1] = grayValue; apsDisplayPixmapBuffer[(3 * idx) + 2] = grayValue; } } public void saveImage() { final BufferedImage theImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_INT_RGB); for (int y = 0; y < chip.getSizeY(); y++) { for (int x = 0; x < chip.getSizeX(); x++) { final int idx = getApsDisplay().getPixMapIndex(x, chip.getSizeY() - y - 1); final int value = ((int) (256 * getApsDisplay().getPixmapArray()[idx]) << 16) | ((int) (256 * getApsDisplay().getPixmapArray()[idx + 1]) << 8) | (int) (256 * getApsDisplay().getPixmapArray()[idx + 2]); theImage.setRGB(x, y, value); } } final Date d = new Date(); final String PNG = "png"; final String fn = "ApsFrame-" + AEDataFile.DATE_FORMAT.format(d) + "." + PNG; // if user is playing a file, use folder that file lives in String userDir = Paths.get(".").toAbsolutePath().normalize().toString(); if (chip.getAeViewer() != null && chip.getAeViewer().getAePlayer() != null && chip.getAeViewer().getPlayMode() == PlayMode.PLAYBACK && chip.getAeViewer().getInputFile() != null) { userDir = chip.getAeViewer().getInputFile().getAbsolutePath(); } File outputfile = new File(userDir + File.separator + fn); boolean done = false; while (!done) { JFileChooser fd = new JFileChooser(outputfile); fd.setApproveButtonText("Save as"); fd.setSelectedFile(outputfile); fd.setVisible(true); final int ret = fd.showOpenDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } outputfile = fd.getSelectedFile(); if (!FilenameUtils.isExtension(outputfile.getAbsolutePath(), PNG)) { String ext = FilenameUtils.getExtension(outputfile.toString()); String newfile = outputfile.getAbsolutePath(); if (ext != null && !ext.isEmpty() && !ext.equals(PNG)) { newfile = outputfile.getAbsolutePath().replace(ext, PNG); } else { newfile = newfile + "." + PNG; } outputfile = new File(newfile); } if (outputfile.exists()) { int overwrite = JOptionPane.showConfirmDialog(fd, outputfile.toString() + " exists, overwrite?"); switch (overwrite) { case JOptionPane.OK_OPTION: done = true; break; case JOptionPane.CANCEL_OPTION: return; case JOptionPane.NO_OPTION: break; } } else { done = true; } } try { ImageIO.write(theImage, "png", outputfile); log.info("wrote PNG " + outputfile); // JOptionPane.showMessageDialog(chip.getFilterFrame(), "Wrote "+userDir+File.separator+fn, "Saved PNG image", JOptionPane.INFORMATION_MESSAGE); } catch (final IOException ex) { Logger.getLogger(ApsFrameExtractor.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns timestampFrameStart of last frame, which is the * timestampFrameStart of the frame end event * * @return the timestampFrameStart (usually in us) */ public int getLastFrameTimestamp() { return lastFrameTimestamp; } /** * Scales the raw value to the display value using * <pre> * v = ((displayContrast * value) + displayBrightness) / maxADC * </pre> * * @param value, from ADC, i.e. 0-1023 for 10-bit ADC * @return a float clipped to range 0-1 */ protected float scaleGrayValue(final float value) { float v; v = ((displayContrast * value) + displayBrightness) / maxADC; if (v < 0) { v = 0; } else if (v > 1) { v = 1; } return v; } public void updateDisplayValue(final int xAddr, final int yAddr, final float value) { if (logCompress && logDecompress) { grayValue = scaleGrayValue((float) (Math.exp(value))); } else { grayValue = scaleGrayValue(value); } getApsDisplay().setPixmapGray(xAddr, yAddr, grayValue); } public void setPixmapArray(final float[] pixmapArray) { getApsDisplay().setPixmapArray(pixmapArray); } public void displayPreBuffer() { getApsDisplay().setPixmapArray(apsDisplayPixmapBuffer); } /** * returns the index <code>y * width + x</code> into pixel arrays for a * given x,y location where x is horizontal address and y is vertical and it * starts at lower left corner with x,y=0,0 and x and y increase to right * and up. * * @param x * @param y * @param idx the array index * @see #getWidth() * @see #getHeight() */ public int getIndex(final int x, final int y) { return (y * width) + x; } /** * Checks if new frame is available. This flag is reset by getNewFrame() * * @return true if new frame is available * @see #getNewFrame() */ public boolean hasNewFrameAvailable() { return newFrameAvailable; } /** * Returns a float[] buffer of latest displayed frame with adjustments like * brightness, contrast, log intensity conversion, etc. The array is indexed * by y * width + x. To access a particular pixel, use getIndex(). newFrame * is set to false by this call. * * @return the double[] frame * @see #getRawFrame() */ public float[] getNewFrame() { newFrameAvailable = false; return displayFrame; } /** * Called when a new frame is complete and available in frameBuffer */ protected void processNewFrame() { } /** * Returns a clone of the latest float rawFrame. This buffer contains raw * pixel values from sensor, before conversion, brightness, etc. The array * is indexed by <code>y * width + x</code>. To access a particular pixel, * use getIndex() for convenience. newFrame is set to false by this call. * * The only processing applied to rawFrame is inversion of values and log * conversion. * <pre> * if (invertIntensity) { * rawFrame[idx] = maxADC - rawFrame[idx]; * } * if (logCompress) { * rawFrame[idx] = (float) Math.log(rawFrame[idx] + logSafetyOffset); * } * </pre> * * @return the float[] of pixel values * @see #getIndex(int, int) * @see #getNewFrame() */ public float[] getRawFrame() { newFrameAvailable = false; return rawFrame.clone(); } /** * Tell chip to acquire new frame, return immediately. * */ public void acquireNewFrame() { apsChip.takeSnapshot(); } public float getMinBufferValue() { float minBufferValue = 0.0f; if (logCompress) { minBufferValue = (float) Math.log(minBufferValue); } return minBufferValue; } public float getMaxBufferValue() { float maxBufferValue = maxADC; if (logCompress) { maxBufferValue = (float) Math.log(maxBufferValue); } return maxBufferValue; } /** * Sets whether external source sets the displayed data. * * @param yes true to not fill image values, false to set image values from * ApsFrameExtractor * @see #setDisplayFrameRGB(float[]) * @see #setDisplayGrayFrame(double[]) */ public void setExtRender(final boolean yes) { useExtRender = yes; } public void setLegend(final String legend) { apsDisplayLegend.s = legend; } /** * Sets the displayed frame gray values from a double array * * @param frame array with same pixel ordering as rawFrame and displayFrame */ public void setDisplayGrayFrame(final float[] frame) { int xc = 0; int yc = 0; for (final float element : frame) { getApsDisplay().setPixmapGray(xc, yc, (float) element); xc++; if (xc == width) { xc = 0; yc++; } } } /** * Sets the displayed frame RGB values from a double array * * @param frame array with same pixel ordering as rawFrame and displayFrame * but with RGB values for each pixel */ public void setDisplayFrameRGB(final float[] frame) { int xc = 0; int yc = 0; for (int i = 0; i < frame.length; i += 3) { getApsDisplay().setPixmapRGB(xc, yc, frame[i + 2], frame[i + 1], frame[i]); xc++; if (xc == width) { xc = 0; yc++; } } } /** * @return the invertIntensity */ public boolean isInvertIntensity() { return invertIntensity; } /** * @param invertIntensity the invertIntensity to set */ public void setInvertIntensity(final boolean invertIntensity) { this.invertIntensity = invertIntensity; putBoolean("invertIntensity", invertIntensity); } /** * @return the preBufferFrame */ public boolean isPreBufferFrame() { return preBufferFrame; } /** * @param preBufferFrame the preBufferFrame to set */ public void setPreBufferFrame(final boolean preBuffer) { preBufferFrame = preBuffer; putBoolean("preBufferFrame", preBufferFrame); } /** * @return the logDecompress */ public boolean isLogDecompress() { return logDecompress; } /** * @param logDecompress the logDecompress to set */ public void setLogDecompress(final boolean logDecompress) { this.logDecompress = logDecompress; putBoolean("logDecompress", logDecompress); } /** * @return the logCompress */ public boolean isLogCompress() { return logCompress; } /** * Raw pixel values in rawFrame are natural log of raw pixel values * * @param logCompress the logCompress to set */ public void setLogCompress(final boolean logCompress) { this.logCompress = logCompress; putBoolean("logCompress", logCompress); } /** * @return the displayContrast */ public float getDisplayContrast() { return displayContrast; } /** * @param displayContrast the displayContrast to set */ public void setDisplayContrast(final float displayContrast) { this.displayContrast = displayContrast; putFloat("displayContrast", displayContrast); resetFilter(); } /** * @return the displayBrightness */ public float getDisplayBrightness() { return displayBrightness; } /** * @param displayBrightness the displayBrightness to set */ public void setDisplayBrightness(final float displayBrightness) { this.displayBrightness = displayBrightness; putFloat("displayBrightness", displayBrightness); resetFilter(); } public Extraction getExtractionMethod() { return extractionMethod; } synchronized public void setExtractionMethod(final Extraction extractionMethod) { getSupport().firePropertyChange("extractionMethod", this.extractionMethod, extractionMethod); putString("edgePixelMethod", extractionMethod.toString()); this.extractionMethod = extractionMethod; resetFilter(); } /** * @return the showAPSFrameDisplay */ public boolean isShowAPSFrameDisplay() { return showAPSFrameDisplay; } /** * @param showAPSFrameDisplay the showAPSFrameDisplay to set */ public void setShowAPSFrameDisplay(final boolean showAPSFrameDisplay) { this.showAPSFrameDisplay = showAPSFrameDisplay; putBoolean("showAPSFrameDisplay", showAPSFrameDisplay); if (apsFrame != null) { apsFrame.setVisible(showAPSFrameDisplay); } getSupport().firePropertyChange("showAPSFrameDisplay", null, showAPSFrameDisplay); } /** * Overrides to add check for DavisChip */ @Override public synchronized void setFilterEnabled(boolean yes) { if (yes && !(chip instanceof DavisChip)) { log.warning("not a DAVIS camera, not enabling filter"); return; } if (!isFilterEnabled()) { if (apsFrame != null) { apsFrame.setVisible(false); } } super.setFilterEnabled(yes); //To change body of generated methods, choose Tools | Templates. } /** * returns frame width in pixels. * * @return the width */ public int getWidth() { return width; } /** * returns frame height in pixels * * @return the height */ public int getHeight() { return height; } /** * returns max ADC value * * @return the maxADC */ public int getMaxADC() { return maxADC; } /** * returns max index into frame buffer arrays * * @return the maxIDX */ public int getMaxIDX() { return maxIDX; } public void doSaveAsPNG() { saveImage(); } private class MouseInfo extends MouseMotionAdapter { ImageDisplay apsImageDisplay; public MouseInfo(final ImageDisplay display) { apsImageDisplay = display; } @Override public void mouseMoved(final MouseEvent e) { final Point2D.Float p = apsImageDisplay.getMouseImagePosition(e); if ((p.x >= 0) && (p.x < chip.getSizeX()) && (p.y >= 0) && (p.y < chip.getSizeY())) { final int idx = getIndex((int) p.x, (int) p.y); if (resetBuffer == null || signalBuffer == null || idx < 0 || idx >= resetBuffer.length) { return; } EventFilter.log.info(String.format("reset= %d, signal= %d, reset-signal= %+d", (int) resetBuffer[idx], (int) signalBuffer[idx], (int) (resetBuffer[idx] - signalBuffer[idx]))); } } } /** * @return the apsDisplay */ public ImageDisplay getApsDisplay() { return apsDisplay; } }
package com.freetymekiyan.algorithms.level.easy; /** * Reverse a singly linked list. * <p> * click to show more hints. * <p> * Hint: * A linked list can be reversed either iteratively or recursively. Could you implement both? * <p> * Company Tags: Uber, Facebook, Twitter, Zenefits, Amazon, Microsoft, Snapchat, Apple, Yahoo, Bloomberg, Yelp, Adobe * Tags: Linked List * Similar Problems: (M) Reverse Linked List II, (M) Binary Tree Upside Down, (E) Palindrome Linked List */ public class ReverseLinkedList { /** * Recursive. * <p> * Divide the list into 2 parts - head and the rest starts from head.next. * Reverse the rest of the linked list. * Append head to the tail of reversed linked list, which is head's next. * Return newHead of the reversed linked list. */ public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { // 1 or no node return head; } ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } /** * Iterative. * Create a new head. * Loop through the list. * For each node, get its next first. * Point itself to the previous head. * Move previous head to current node. * Then move to the next node and do the same thing. * Stop when reach the end. */ public ListNode reverseList2(ListNode head) { ListNode newHead = null; while (head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } }
package algorithms.graphs; import algorithms.graphs.ApproxGraphSearchZeng.Graph; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; /** * * @author nichole */ public class StarStructureTest extends TestCase { public StarStructureTest(String testName) { super(testName); } public void test0() { List<Graph> dbs = new ArrayList<Graph>(); Graph q = ApproxGraphSearchZengTest.getG0(dbs); int nV = 14; // dB has 15, q has 14 StarStructure[] stars = StarStructure.createStarStructureMultiset(q); assertEquals(nV, stars.length); int ged; ged = StarStructure.calculateEditDistanceV(stars[0], stars[1]); assertEquals(0, ged); ged = StarStructure.calculateEditDistance(stars[0], stars[1]); assertEquals(0, ged); ged = StarStructure.calculateEditDistanceV(stars[0], stars[8]); assertEquals(1, ged); ged = StarStructure.calculateEditDistance(stars[0], stars[8]); assertEquals(1, ged); int s3 = StarStructure.calculateSupport(stars, 3); assertEquals(6, s3); int s4 = StarStructure.calculateSupport(stars, 4); assertEquals(3+3+3, s4); s4 = StarStructure.calculateSupport( StarStructure.createStarStructureMultiset(dbs.get(0)), 4); assertEquals(4+3+3, s4); StarStructure[] stars2 = StarStructure.copy(stars); assertEquals(stars.length, stars2.length); ged = StarStructure.calculateEditDistanceV(stars2[0], stars2[1]); assertEquals(0, ged); ged = StarStructure.calculateEditDistance(stars2[0], stars2[1]); assertEquals(0, ged); ged = StarStructure.calculateEditDistanceV(stars2[0], stars2[8]); assertEquals(1, ged); ged = StarStructure.calculateEditDistance(stars2[0], stars2[8]); assertEquals(1, ged); s3 = StarStructure.calculateSupport(stars2, 3); assertEquals(6, s3); s4 = StarStructure.calculateSupport(stars2, 4); assertEquals(3+3+3, s4); } /** * Test of calculateEditDistanceNoRelabeling method, of class StarStructure. */ public void testCalculateEditDistanceNoRelabeling() { } /** * Test of calculateEditDistanceNoRelabelingV method, of class StarStructure. */ public void testCalculateEditDistanceNoRelabelingV() { } /** * Test of createDistanceMatrix method, of class StarStructure. */ public void testCreateDistanceMatrix() { } /** * Test of createDistanceMatrixV method, of class StarStructure. */ public void testCreateDistanceMatrixV() { } /** * Test of createDistanceMatrixNoRelabeling method, of class StarStructure. */ public void testCreateDistanceMatrixNoRelabeling() { } /** * Test of createDistanceMatrixNoRelabelingV method, of class StarStructure. */ public void testCreateDistanceMatrixNoRelabelingV() { } }
package com.redhat.ceylon.compiler.typechecker.model; import static com.redhat.ceylon.compiler.typechecker.model.Util.addToIntersection; import static com.redhat.ceylon.compiler.typechecker.model.Util.addToUnion; import static com.redhat.ceylon.compiler.typechecker.model.Util.arguments; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A produced type with actual type arguments. * This represents something that is actually * considered a "type" in the language * specification. * * @author Gavin King */ public class ProducedType extends ProducedReference { ProducedType() {} @Override public TypeDeclaration getDeclaration() { return (TypeDeclaration) super.getDeclaration(); } boolean isEquivalentToCases() { TypeDeclaration dec = getDeclaration(); return dec.getCaseTypes()!=null && !(dec instanceof TypeParameter); } /** * Is this type exactly the same type as the * given type? */ public boolean isExactly(ProducedType type) { if (getDeclaration() instanceof BottomType) { return type.getDeclaration() instanceof BottomType; } else if (isEquivalentToCases()) { List<ProducedType> cases = getCaseTypes(); if (type.isEquivalentToCases()) { List<ProducedType> otherCases = type.getCaseTypes(); if (cases.size()!=otherCases.size()) { return false; } else { for (ProducedType c: cases) { boolean found = false; for (ProducedType oc: otherCases) { if (c.isExactly(oc)) { found = true; break; } } if (!found) { return false; } } return true; } } else if (cases.size()==1) { ProducedType st = cases.get(0); return st.isExactly(type); } else { return false; } } else if (getDeclaration() instanceof IntersectionType) { //TODO: if any intersected type is an enumerated type, // replace it with the union of its cases, then // canonicalize the resulting intersection List<ProducedType> types = getSatisfiedTypes(); if (type.getDeclaration() instanceof IntersectionType) { List<ProducedType> otherTypes = type.getSatisfiedTypes(); if (types.size()!=otherTypes.size()) { return false; } else { for (ProducedType c: types) { boolean found = false; for (ProducedType oc: otherTypes) { if (c.isExactly(oc)) { found = true; break; } } if (!found) { return false; } } return true; } } else if (types.size()==1) { ProducedType st = types.get(0); return st.isExactly(type); } else { return false; } } else if (type.isEquivalentToCases()) { List<ProducedType> otherCases = type.getCaseTypes(); if (otherCases.size()==1) { ProducedType st = otherCases.get(0); return this.isExactly(st); } else { return false; } } else if (type.getDeclaration() instanceof IntersectionType) { //TODO: if any intersected type is an enumerated type, // replace it with the union of its cases, then // canonicalize the resulting intersection List<ProducedType> otherTypes = type.getSatisfiedTypes(); if (otherTypes.size()==1) { ProducedType st = otherTypes.get(0); return this.isExactly(st); } else { return false; } } else { if (!type.getDeclaration().equals(getDeclaration())) { ProducedType selfType = getDeclaration().getSelfType(); if (selfType!=null && type.isExactly(selfType.substitute(getTypeArguments()))) { return true; } ProducedType typeSelfType = type.getDeclaration().getSelfType(); if (typeSelfType!=null && isExactly(typeSelfType.substitute(type.getTypeArguments()))) { return true; } return false; } else { ProducedType qt = getQualifyingType(); ProducedType tqt = type.getQualifyingType(); if (qt==null) { if (tqt!=null) { return false; } } else { if (tqt==null) { return false; } else { TypeDeclaration totd = (TypeDeclaration) type.getDeclaration().getContainer(); ProducedType tqts = tqt.getSupertype(totd); TypeDeclaration otd = (TypeDeclaration) getDeclaration().getContainer(); ProducedType qts = qt.getSupertype(otd); if ( !qts.isExactly(tqts) ) { return false; } } } for (TypeParameter p: getDeclaration().getTypeParameters()) { ProducedType arg = getTypeArguments().get(p); ProducedType otherArg = type.getTypeArguments().get(p); if (arg==null || otherArg==null) { return false; /*throw new RuntimeException( "Missing type argument for: " + p.getName() + " of " + getDeclaration().getName());*/ } else if (!arg.isExactly(otherArg)) { return false; } } return true; } } } /** * Is this type a supertype of the given type? */ public boolean isSupertypeOf(ProducedType type) { return type.isSubtypeOf(this); } /** * Is this type a subtype of the given type? */ public boolean isSubtypeOf(ProducedType type) { return type!=null && getUnionOfCases(false).isSubtypeOf(type, null); } /** * Is this type a subtype of the given type? Ignore * a certain self type constraint. */ public boolean isSubtypeOf(ProducedType type, TypeDeclaration selfTypeToIgnore) { if (getDeclaration() instanceof BottomType) { return true; } else if (type.getDeclaration() instanceof BottomType) { return false; } else if (getDeclaration().getCaseTypes()!=null) { boolean assignable = true; for (ProducedType ct: getInternalCaseTypes()) { if (ct==null || !ct.isSubtypeOf(type, selfTypeToIgnore)) { assignable = false; } } if (assignable) { return true; } else if (type.getDeclaration() instanceof UnionType) { return false; } //else fall through } else if (type.isEquivalentToCases()) { for (ProducedType ct: type.getInternalCaseTypes()) { if (ct!=null && isSubtypeOf(ct, selfTypeToIgnore)) { return true; } } if (type.getDeclaration() instanceof UnionType) { return false; } //else fall through } else if (type.getDeclaration() instanceof IntersectionType) { for (ProducedType ct: type.getInternalSatisfiedTypes()) { if (ct!=null && !isSubtypeOf(ct, selfTypeToIgnore)) { return false; } } return true; } else if (getDeclaration() instanceof IntersectionType) { for (ProducedType ct: getInternalSatisfiedTypes()) { //TODO: if ct is an enumerated type, replace it // with the union of its cases, then // canonicalize the resulting intersection if (ct==null || ct.isSubtypeOf(type, selfTypeToIgnore)) { return true; } } return false; } //else { ProducedType st = getSupertype(type.getDeclaration(), selfTypeToIgnore); if (st==null) { return false; } else { ProducedType stqt = st.getQualifyingType(); ProducedType tqt = type.getQualifyingType(); if (stqt==null) { if (tqt!=null) { //probably extraneous! return false; } } else { if (tqt==null) { //probably extraneous! return false; } else { //note that the qualifying type of the //given type may be an invariant subtype //of the type that declares the member //type, as long as it doesn't refine the //member type TypeDeclaration totd = (TypeDeclaration) type.getDeclaration().getContainer(); ProducedType tqts = tqt.getSupertype(totd); if (!stqt.isSubtypeOf(tqts)) { return false; } } } for (TypeParameter p: type.getDeclaration().getTypeParameters()) { ProducedType arg = st.getTypeArguments().get(p); ProducedType otherArg = type.getTypeArguments().get(p); if (arg==null || otherArg==null) { /*throw new RuntimeException("Missing type argument for type parameter: " + p.getName() + " of " + type.getDeclaration().getName());*/ return false; } else if (p.isCovariant()) { if (!arg.isSubtypeOf(otherArg)) { return false; } } else if (p.isContravariant()) { if (!otherArg.isSubtypeOf(arg)) { return false; } } else { if (!arg.isExactly(otherArg)) { return false; } } } return true; } } /** * Eliminate the given type from the union type. * (Performs a set complement operation.) Note * that this operation is not robust and only * works if this is a union of the given type * with some other types that don't involve the * given type. */ public ProducedType minus(ClassOrInterface ci) { if (getDeclaration().equals(ci)) { return getDeclaration().getUnit().getBottomDeclaration().getType(); } else if (getDeclaration() instanceof UnionType) { List<ProducedType> types = new ArrayList<ProducedType>(); for (ProducedType ct: getCaseTypes()) { if (ct.getSupertype(ci)==null) { addToUnion(types, ct.minus(ci)); } } UnionType ut = new UnionType(getDeclaration().getUnit()); ut.setCaseTypes(types); return ut.getType(); } else { return this; } } /** * Substitute the given types for the corresponding * given type parameters wherever they appear in the * type. */ public ProducedType substitute(Map<TypeParameter, ProducedType> substitutions) { return new Substitution().substitute(this, substitutions); } private ProducedType substituteInternal(Map<TypeParameter, ProducedType> substitutions) { return new InternalSubstitution().substitute(this, substitutions); } /** * A member or member type of the type with actual type * arguments to the receiving type and invocation. */ public ProducedReference getTypedReference(Declaration member, List<ProducedType> typeArguments) { if (member instanceof TypeDeclaration) { return getTypeMember( (TypeDeclaration) member, typeArguments ); } else { return getTypedMember( (TypedDeclaration) member, typeArguments); } } /** * A member of the type with actual type arguments * to the receiving type and invocation. * * @param member the declaration of a member of * this type * @param typeArguments the type arguments of the * invocation */ public ProducedTypedReference getTypedMember(TypedDeclaration member, List<ProducedType> typeArguments) { ProducedType declaringType = getSupertype((TypeDeclaration) member.getContainer()); /*if (declaringType==null) { return null; } else {*/ ProducedTypedReference ptr = new ProducedTypedReference(); ptr.setDeclaration(member); ptr.setQualifyingType(declaringType); Map<TypeParameter, ProducedType> map = arguments(member, declaringType, typeArguments); //map.putAll(sub(map)); ptr.setTypeArguments(map); return ptr; } /** * A member type of the type with actual type arguments * to the receiving type and invocation. * * @param member the declaration of a member type of * this type * @param typeArguments the type arguments of the * invocation */ public ProducedType getTypeMember(TypeDeclaration member, List<ProducedType> typeArguments) { ProducedType declaringType = getSupertype((TypeDeclaration) member.getContainer()); ProducedType pt = new ProducedType(); pt.setDeclaration(member); pt.setQualifyingType(declaringType); Map<TypeParameter, ProducedType> map = arguments(member, declaringType, typeArguments); //map.putAll(sub(map)); pt.setTypeArguments(map); return pt; } /** * Substitute invocation type arguments into an upper bound * on a type parameter of the invocation, where this type * represents an upper bound. * * @param receiver the type that receives the invocation * @param member the invoked member * @param typeArguments the explicit or inferred type * arguments of the invocation * * @return the upper bound of a type parameter, after * performing all type argument substitution */ public ProducedType getProducedType(ProducedType receiver, Declaration member, List<ProducedType> typeArguments) { ProducedType rst = (receiver==null) ? null : receiver.getSupertype((TypeDeclaration) member.getContainer()); return new Substitution().substitute(this, arguments(member, rst, typeArguments)); } public ProducedType getType() { return this; } /** * Get all supertypes of the type by traversing the whole * type hierarchy. Avoid using this! */ public List<ProducedType> getSupertypes() { return getSupertypes(new ArrayList<ProducedType>()); } private List<ProducedType> getSupertypes(List<ProducedType> list) { if ( isWellDefined() && Util.addToSupertypes(list, this) ) { ProducedType extendedType = getExtendedType(); if (extendedType!=null) { extendedType.getSupertypes(list); } for (ProducedType dst: getSatisfiedTypes()) { dst.getSupertypes(list); } ProducedType selfType = getSelfType(); if (selfType!=null) { if (!(selfType.getDeclaration() instanceof TypeParameter)) { //TODO: is this really correct??? selfType.getSupertypes(list); } } if (getDeclaration() instanceof UnionType) { //trying to infer supertypes of algebraic //types from their cases was resulting in //stack overflows and is not currently //required by the spec List<ProducedType> caseTypes = getCaseTypes(); if (caseTypes!=null) { for (ProducedType t: caseTypes) { List<ProducedType> candidates = t.getSupertypes(); for (ProducedType st: candidates) { boolean include = true; for (ProducedType ct: getDeclaration().getCaseTypes()) { if (!ct.isSubtypeOf(st)) { include = false; break; } } if (include) { Util.addToSupertypes(list, st); } } } } } } return list; } /** * Given a type declaration, return a produced type of * which this type is an invariant subtype. * * @param dec a type declaration * * @return a produced type of the given type declaration * which is a supertype of this type, or null if * there is no such supertype */ public ProducedType getSupertype(TypeDeclaration dec) { return getSupertype(dec, null); } /** * Given a type declaration, return a produced type of * which this type is an invariant subtype. Ignore a * given self type constraint. * * @param dec a type declaration * @param selfTypeToIgnore a self type to ignore when * searching for supertypes * * @return a produced type of the given type declaration * which is a supertype of this type, or null if * there is no such supertype */ private ProducedType getSupertype(final TypeDeclaration dec, TypeDeclaration selfTypeToIgnore) { Criteria c = new Criteria() { @Override public boolean satisfies(TypeDeclaration type) { return type.equals(dec); } }; return getSupertype(c, new ArrayList<ProducedType>(), selfTypeToIgnore); } /** * Given a predicate, return a produced type for a * declaration satisfying the predicate, of which * this type is an invariant subtype. */ ProducedType getSupertype(Criteria c) { return getSupertype(c, new ArrayList<ProducedType>(), null); } static interface Criteria { boolean satisfies(TypeDeclaration type); } /** * Search for the most-specialized supertype * satisfying the given predicate. */ private ProducedType getSupertype(final Criteria c, List<ProducedType> list, final TypeDeclaration ignoringSelfType) { if (c.satisfies(getDeclaration())) { return qualifiedByDeclaringType(); } if ( isWellDefined() && Util.addToSupertypes(list, this) ) { //search for the most-specific supertype //for the given declaration ProducedType result = null; ProducedType extendedType = getInternalExtendedType(); if (extendedType!=null) { ProducedType possibleResult = extendedType.getSupertype(c, list, ignoringSelfType); if (possibleResult!=null) { result = possibleResult; } } for (ProducedType dst: getInternalSatisfiedTypes()) { ProducedType possibleResult = dst.getSupertype(c, list, ignoringSelfType); if (possibleResult!=null) { if (result==null || possibleResult.isSubtypeOf(result, ignoringSelfType)) { result = possibleResult; } else if ( !result.isSubtypeOf(possibleResult, ignoringSelfType) ) { //TODO: this is still needed even though we keep intersections // in canonical form because you can have stuff like // empty of Iterable<String>&Sized List<ProducedType> args = new ArrayList<ProducedType>(); TypeDeclaration dec = result.getDeclaration(); //TODO; get this from the Criteria? for (TypeParameter tp: dec.getTypeParameters()) { List<ProducedType> l = new ArrayList<ProducedType>(); Unit unit = getDeclaration().getUnit(); ProducedType arg; ProducedType rta = result.getTypeArguments().get(tp); ProducedType prta = possibleResult.getTypeArguments().get(tp); if (tp.isContravariant()) { addToUnion(l, rta); addToUnion(l, prta); UnionType ut = new UnionType(unit); ut.setCaseTypes(l); arg = ut.getType(); } else {//if (tp.isCovariant()) { addToIntersection(l, rta, unit); addToIntersection(l, prta, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(l); arg = it.canonicalize().getType(); } // else { // if (rta.isExactly(prta)) { // arg = rta; // else { // //TODO: think this case through better! // return null; args.add(arg); } //TODO: broken for member types! ugh :-( result = dec.getProducedType(result.getQualifyingType(), args); } } } if (!getDeclaration().equals(ignoringSelfType)) { ProducedType selfType = getInternalSelfType(); if (selfType!=null) { ProducedType possibleResult = selfType.getSupertype(c, list, ignoringSelfType); if (possibleResult!=null && (result==null || possibleResult.isSubtypeOf(result, ignoringSelfType))) { result = possibleResult; } } } if (getDeclaration() instanceof UnionType) { //trying to infer supertypes of algebraic //types from their cases was resulting in //stack overflows and is not currently //required by the spec final List<ProducedType> caseTypes = getInternalCaseTypes(); if (caseTypes!=null && !caseTypes.isEmpty()) { //first find a common superclass or superinterface //declaration that satisfies the criteria, ignoring //type arguments for now Criteria c2 = new Criteria() { @Override public boolean satisfies(TypeDeclaration type) { if ( c.satisfies(type) ) { for (ProducedType ct: caseTypes) { if (ct.getSupertype(type, ignoringSelfType)==null) { return false; } } return true; } else { return false; } } }; ProducedType stc = caseTypes.get(0).getSupertype(c2, list, ignoringSelfType); if (stc!=null) { //we found the declaration, now try to construct a //produced type that is a true common supertype ProducedType candidateResult = getCommonSupertype(caseTypes, stc.getDeclaration(), ignoringSelfType); if (candidateResult!=null && (result==null || candidateResult.isSubtypeOf(result, ignoringSelfType))) { result = candidateResult; } } } } return result; } else { return null; } } private ProducedType qualifiedByDeclaringType() { ProducedType qt = getQualifyingType(); if (qt==null) { return this; } else { ProducedType pt = new ProducedType(); pt.setDeclaration(getDeclaration()); pt.setTypeArguments(getTypeArguments()); //replace the qualifying type with //the supertype of the qualifying //type that declares this nested //type, substituting type arguments ProducedType declaringType = qt.getSupertype((TypeDeclaration) getDeclaration().getContainer()); pt.setQualifyingType(declaringType); return pt; } } private ProducedType getCommonSupertype(final List<ProducedType> caseTypes, TypeDeclaration dec, final TypeDeclaration selfTypeToIgnore) { //now try to construct a common produced //type that is a common supertype by taking //the type args and unioning them List<ProducedType> args = new ArrayList<ProducedType>(); for (TypeParameter tp: dec.getTypeParameters()) { List<ProducedType> list2 = new ArrayList<ProducedType>(); ProducedType result; if (tp.isContravariant()) { for (ProducedType pt: caseTypes) { if (pt==null) { return null; } ProducedType st = pt.getSupertype(dec, selfTypeToIgnore); if (st==null) { return null; } addToIntersection(list2, st.getTypeArguments().get(tp), getDeclaration().getUnit()); } IntersectionType it = new IntersectionType(getDeclaration().getUnit()); it.setSatisfiedTypes(list2); result = it.canonicalize().getType(); } else { for (ProducedType pt: caseTypes) { if (pt==null) { return null; } ProducedType st = pt.getSupertype(dec, selfTypeToIgnore); if (st==null) { return null; } addToUnion(list2, st.getTypeArguments().get(tp)); } UnionType ut = new UnionType(getDeclaration().getUnit()); ut.setCaseTypes(list2); result = ut.getType(); } args.add(result); } //check that the unioned type args //satisfy the type constraints //disabled this according to /*for (int i=0; i<args.size(); i++) { TypeParameter tp = dec.getTypeParameters().get(i); for (ProducedType ub: tp.getSatisfiedTypes()) { if (!args.get(i).isSubtypeOf(ub)) { return null; } } }*/ //recurse to the qualifying type ProducedType outerType; if (dec.isMember()) { TypeDeclaration outer = (TypeDeclaration) dec.getContainer(); List<ProducedType> list = new ArrayList<ProducedType>(); for (ProducedType pt: caseTypes) { if (pt==null) { return null; } ProducedType st = pt.getQualifyingType().getSupertype(outer, null); list.add(st); } outerType = getCommonSupertype(list, outer, null); } else { outerType = null; } //make the resulting type ProducedType candidateResult = dec.getProducedType(outerType, args); //check the the resulting type is *really* //a subtype (take variance into account) for (ProducedType pt: caseTypes) { if (!pt.isSubtypeOf(candidateResult)) { return null; } } return candidateResult; } /** * Get the type arguments as a tuple. */ public List<ProducedType> getTypeArgumentList() { List<ProducedType> lpt = new ArrayList<ProducedType>(); for (TypeParameter tp : getDeclaration().getTypeParameters()) { lpt.add(getTypeArguments().get(tp)); } return lpt; } public List<TypeDeclaration> checkDecidability() { List<TypeDeclaration> errors = new ArrayList<TypeDeclaration>(); for (TypeParameter tp: getDeclaration().getTypeParameters()) { ProducedType pt = getTypeArguments().get(tp); if (pt!=null) { pt.checkDecidability(tp.isCovariant(), tp.isContravariant(), errors); } } return errors; } private void checkDecidability(boolean covariant, boolean contravariant, List<TypeDeclaration> errors) { if (getDeclaration() instanceof TypeParameter) { //nothing to do } else if (getDeclaration() instanceof UnionType) { for (ProducedType ct: getCaseTypes()) { ct.checkDecidability(covariant, contravariant, errors); } } else if (getDeclaration() instanceof IntersectionType) { for (ProducedType ct: getSatisfiedTypes()) { ct.checkDecidability(covariant, contravariant, errors); } } else { for (TypeParameter tp: getDeclaration().getTypeParameters()) { if (!covariant && tp.isContravariant()) { //a type with contravariant parameters appears at //a contravariant location in satisfies / extends errors.add(getDeclaration()); } ProducedType pt = getTypeArguments().get(tp); if (pt!=null) { if (tp.isCovariant()) { pt.checkDecidability(covariant, contravariant, errors); } else if (tp.isContravariant()) { if (covariant|contravariant) { pt.checkDecidability(!covariant, !contravariant, errors); } else { //else if we are in a nonvariant position, it stays nonvariant pt.checkDecidability(covariant, contravariant, errors); } } else { pt.checkDecidability(false, false, errors); } } } } } public List<TypeParameter> checkVariance(boolean covariant, boolean contravariant, Declaration declaration) { List<TypeParameter> errors = new ArrayList<TypeParameter>(); checkVariance(covariant, contravariant, declaration, errors); return errors; } private void checkVariance(boolean covariant, boolean contravariant, Declaration declaration, List<TypeParameter> errors) { //TODO: fix this to allow reporting multiple errors! if (getDeclaration() instanceof TypeParameter) { TypeParameter tp = (TypeParameter) getDeclaration(); boolean ok = tp.getDeclaration().equals(declaration) || ((covariant || !tp.isCovariant()) && (contravariant || !tp.isContravariant())); if (!ok) { //a covariant type parameter appears in a contravariant location, or //a contravariant type parameter appears in a covariant location. errors.add(tp); } } else if (getDeclaration() instanceof UnionType) { for (ProducedType ct: getCaseTypes()) { ct.checkVariance(covariant, contravariant, declaration, errors); } } else if (getDeclaration() instanceof IntersectionType) { for (ProducedType ct: getSatisfiedTypes()) { ct.checkVariance(covariant, contravariant, declaration, errors); } } else { if (getQualifyingType()!=null) { getQualifyingType().checkVariance(covariant, contravariant, declaration, errors); } for (TypeParameter tp: getDeclaration().getTypeParameters()) { ProducedType pt = getTypeArguments().get(tp); if (pt!=null) { if (tp.isCovariant()) { pt.checkVariance(covariant, contravariant, declaration, errors); } else if (tp.isContravariant()) { if (covariant|contravariant) { pt.checkVariance(!covariant, !contravariant, declaration, errors); } else { //else if we are in a nonvariant position, it stays nonvariant pt.checkVariance(covariant, contravariant, declaration, errors); } } else { pt.checkVariance(false, false, declaration, errors); } } } } } /** * Is the type welldefined? Are any of its arguments * garbage unknown types? */ public boolean isWellDefined() { for (ProducedType at: getTypeArgumentList()) { if (at==null || !at.isWellDefined() ) { return false; } } return true; } private ProducedType getInternalSelfType() { ProducedType selfType = getDeclaration().getSelfType(); return selfType==null?null:selfType.substituteInternal(getTypeArguments()); } private List<ProducedType> getInternalSatisfiedTypes() { List<ProducedType> satisfiedTypes = new ArrayList<ProducedType>(); for (ProducedType st: getDeclaration().getSatisfiedTypes()) { satisfiedTypes.add(st.substituteInternal(getTypeArguments())); } return satisfiedTypes; } private ProducedType getInternalExtendedType() { ProducedType extendedType = getDeclaration().getExtendedType(); return extendedType==null?null:extendedType.substituteInternal(getTypeArguments()); } private List<ProducedType> getInternalCaseTypes() { if (getDeclaration().getCaseTypes()==null) { return null; } else { List<ProducedType> caseTypes = new ArrayList<ProducedType>(); for (ProducedType ct: getDeclaration().getCaseTypes()) { caseTypes.add(ct.substituteInternal(getTypeArguments())); } return caseTypes; } } private ProducedType getSelfType() { ProducedType selfType = getDeclaration().getSelfType(); return selfType==null?null:selfType.substitute(getTypeArguments()); } private List<ProducedType> getSatisfiedTypes() { List<ProducedType> satisfiedTypes = new ArrayList<ProducedType>(); for (ProducedType st: getDeclaration().getSatisfiedTypes()) { satisfiedTypes.add(st.substitute(getTypeArguments())); } return satisfiedTypes; } private ProducedType getExtendedType() { ProducedType extendedType = getDeclaration().getExtendedType(); return extendedType==null?null:extendedType.substitute(getTypeArguments()); } private List<ProducedType> getCaseTypes() { if (getDeclaration().getCaseTypes()==null) { return null; } else { List<ProducedType> caseTypes = new ArrayList<ProducedType>(); for (ProducedType ct: getDeclaration().getCaseTypes()) { caseTypes.add(ct.substitute(getTypeArguments())); } return caseTypes; } } /** * Substitutes type arguments for type parameters. * This default strategy eliminates duplicate types * from unions after substituting arguments. * @author Gavin King */ static class Substitution { ProducedType substitute(ProducedType pt, Map<TypeParameter, ProducedType> substitutions) { Declaration dec; if (pt.getDeclaration() instanceof UnionType) { UnionType ut = new UnionType(pt.getDeclaration().getUnit()); List<ProducedType> types = new ArrayList<ProducedType>(); for (ProducedType ct: pt.getDeclaration().getCaseTypes()) { addTypeToUnion(ct, substitutions, types); } ut.setCaseTypes(types); dec = ut; } else if (pt.getDeclaration() instanceof IntersectionType) { IntersectionType it = new IntersectionType(pt.getDeclaration().getUnit()); List<ProducedType> types = new ArrayList<ProducedType>(); for (ProducedType ct: pt.getDeclaration().getSatisfiedTypes()) { addTypeToIntersection(ct, substitutions, types); } it.setSatisfiedTypes(types); dec = it.canonicalize(); } else { if (pt.getDeclaration() instanceof TypeParameter) { ProducedType sub = substitutions.get(pt.getDeclaration()); if (sub!=null) { return sub; } } dec = pt.getDeclaration(); } return substitutedType(dec, pt, substitutions); } void addTypeToUnion(ProducedType ct, Map<TypeParameter, ProducedType> substitutions, List<ProducedType> types) { if (ct==null) { types.add(null); } else { addToUnion(types, substitute(ct, substitutions)); } } void addTypeToIntersection(ProducedType ct, Map<TypeParameter, ProducedType> substitutions, List<ProducedType> types) { if (ct==null) { types.add(null); } else { addToIntersection(types, substitute(ct, substitutions), ct.getDeclaration().getUnit()); } } private Map<TypeParameter, ProducedType> substitutedTypeArguments(ProducedType pt, Map<TypeParameter, ProducedType> substitutions) { Map<TypeParameter, ProducedType> map = new HashMap<TypeParameter, ProducedType>(); for (Map.Entry<TypeParameter, ProducedType> e: pt.getTypeArguments().entrySet()) { if (e.getValue()!=null) { map.put(e.getKey(), substitute(e.getValue(), substitutions)); } } /*ProducedType dt = pt.getDeclaringType(); if (dt!=null) { map.putAll(substituted(dt, substitutions)); }*/ return map; } private ProducedType substitutedType(Declaration dec, ProducedType pt, Map<TypeParameter, ProducedType> substitutions) { ProducedType type = new ProducedType(); type.setDeclaration(dec); ProducedType qt = pt.getQualifyingType(); if (qt!=null) { type.setQualifyingType(substitute(qt, substitutions)); } type.setTypeArguments(substitutedTypeArguments(pt, substitutions)); return type; } } /** * This special strategy for internal use by the * containing class does not eliminate duplicate * types from unions after substituting arguments. * This is to avoid a stack overflow that otherwise * results! (Determining if a union contains * duplicates requires recursion to the argument * substitution code via some very difficult-to- * understand flow.) * @author Gavin King */ static class InternalSubstitution extends Substitution { private void addType(ProducedType ct, Map<TypeParameter, ProducedType> substitutions, List<ProducedType> types) { if (ct!=null) { types.add(substitute(ct, substitutions)); } } @Override void addTypeToUnion(ProducedType ct, Map<TypeParameter, ProducedType> substitutions, List<ProducedType> types) { addType(ct, substitutions, types); } @Override void addTypeToIntersection(ProducedType ct, Map<TypeParameter, ProducedType> substitutions, List<ProducedType> types) { addType(ct, substitutions, types); } } @Override public String toString() { return "Type[" + getProducedTypeName() + "]"; } public String getProducedTypeName() { return getProducedTypeName(true); } public String getProducedTypeName(boolean abbreviate) { if (getDeclaration()==null) { //unknown type return null; } if (abbreviate && getDeclaration() instanceof UnionType) { UnionType ut = (UnionType) getDeclaration(); if (ut.getCaseTypes().size()==2) { Unit unit = getDeclaration().getUnit(); if (Util.isElementOfUnion(ut, unit.getNothingDeclaration())) { return unit.getDefiniteType(this) .getProducedTypeName() + "?"; } if (Util.isElementOfUnion(ut, unit.getEmptyDeclaration()) && Util.isElementOfUnion(ut, unit.getSequenceDeclaration())) { return unit.getElementType(this) .getProducedTypeName() + "[]"; } } } String producedTypeName = ""; if (getDeclaration().isMember()) { producedTypeName += getQualifyingType().getProducedTypeName(abbreviate); producedTypeName += "."; } producedTypeName += getDeclaration().getName(); if (!getTypeArgumentList().isEmpty()) { producedTypeName += "<"; for (ProducedType t : getTypeArgumentList()) { if (t==null) { producedTypeName += "unknown,"; } else { producedTypeName += t.getProducedTypeName(abbreviate) + ","; } } producedTypeName += ">"; producedTypeName = producedTypeName.replace(",>", ">"); } return producedTypeName; } public String getProducedTypeQualifiedName() { if (getDeclaration()==null) { //unknown type return null; } String producedTypeName = ""; if (getDeclaration().isMember()) { producedTypeName += getQualifyingType().getProducedTypeQualifiedName(); producedTypeName += "."; } producedTypeName += getDeclaration().getQualifiedNameString(); if (!getTypeArgumentList().isEmpty()) { producedTypeName += "<"; for (ProducedType t : getTypeArgumentList()) { if (t==null) { producedTypeName += "?,"; } else { producedTypeName += t.getProducedTypeQualifiedName() + ","; } } producedTypeName += ">"; producedTypeName = producedTypeName.replace(",>", ">"); } return producedTypeName; } public ProducedType getUnionOfCases(boolean typeParams) { TypeDeclaration sdt = getDeclaration(); Unit unit = getDeclaration().getUnit(); if (sdt instanceof IntersectionType) { List<ProducedType> list = new ArrayList<ProducedType>(); for (ProducedType st: sdt.getSatisfiedTypes()) { addToIntersection(list, st.getUnionOfCases(typeParams) .substitute(getTypeArguments()), unit); //argument substitution is unnecessary } IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } /*if (switchType.getDeclaration() instanceof UnionType) { //this branch is not really necessary, because it //does basically the same thing as the else clause //but it's slightly simpler because there are no //type arguments to substitute List<ProducedType> list = new ArrayList<ProducedType>(); for (ProducedType st: switchType.getDeclaration().getCaseTypes()) { addToUnion(list, getUnionOfCases(st)); } UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); }*/ else if (sdt.getCaseTypes()==null) { return this; } else if (sdt instanceof TypeParameter && !typeParams) { return this; } else { //build a union of all the cases List<ProducedType> list = new ArrayList<ProducedType>(); for (ProducedType ct: sdt.getCaseTypes()) { addToUnion(list, ct.substitute(getTypeArguments()) .getUnionOfCases(typeParams)); //note recursion } UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } } }
package com.suse.salt.netapi.examples; import com.suse.salt.netapi.AuthModule; import com.suse.salt.netapi.calls.WheelResult; import com.suse.salt.netapi.calls.modules.Grains; import com.suse.salt.netapi.calls.modules.Test; import com.suse.salt.netapi.calls.wheel.Key; import com.suse.salt.netapi.client.SaltClient; import com.suse.salt.netapi.datatypes.target.Glob; import com.suse.salt.netapi.datatypes.target.MinionList; import com.suse.salt.netapi.datatypes.target.Target; import com.suse.salt.netapi.exception.SaltException; import com.suse.salt.netapi.results.Result; import java.net.URI; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Example code calling salt modules using the generic interface. */ public class Calls { private static final String SALT_API_URL = "http://localhost:8000"; private static final String USER = "saltdev"; private static final String PASSWORD = "saltdev"; public static void main(String[] args) throws SaltException { // Init the client SaltClient client = new SaltClient(URI.create(SALT_API_URL)); // Ping all minions using a glob matcher Target<String> globTarget = new Glob("*"); Map<String, Result<Boolean>> results = Test.ping().callSync( client, globTarget, USER, PASSWORD, AuthModule.AUTO); System.out.println("--> Ping results:\n"); results.forEach((minion, result) -> System.out.println(minion + " -> " + result)); // Get the grains from a list of minions Target<List<String>> minionList = new MinionList("minion1", "minion2"); Map<String, Result<Map<String, Object>>> grainResults = Grains.items(false) .callSync(client, minionList, USER, PASSWORD, AuthModule.AUTO); grainResults.forEach((minion, grains) -> { System.out.println("\n--> Listing grains for '" + minion + "':\n"); String grainsOutput = grains.fold( error -> "Error: " + error.toString(), grainsMap -> grainsMap.entrySet().stream() .map(e -> e.getKey() + ": " + e.getValue()) .collect(Collectors.joining("\n")) ); System.out.println(grainsOutput); }); // Call a wheel function: list accepted and pending minion keys WheelResult<Key.Names> keyResults = Key.listAll().callSync( client, USER, PASSWORD, AuthModule.AUTO); Key.Names keys = keyResults.getData().getResult(); System.out.println("\n--> Accepted minion keys:\n"); keys.getMinions().forEach(System.out::println); System.out.println("\n--> Pending minion keys:\n"); keys.getUnacceptedMinions().forEach(System.out::println); } }
package com.thaiopensource.validate.xerces; import com.thaiopensource.validate.SchemaReaderFactory; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.Option; import com.thaiopensource.validate.xerces.SchemaReaderImpl; import com.thaiopensource.xml.util.WellKnownNamespaces; import org.apache.xerces.parsers.XMLGrammarPreparser; public class XsdSchemaReaderFactory implements SchemaReaderFactory { public XsdSchemaReaderFactory() { // Force a linkage error if Xerces is not available new XMLGrammarPreparser(); } public SchemaReader createSchemaReader(String namespaceUri) { if (WellKnownNamespaces.XML_SCHEMA.equals(namespaceUri)) return new SchemaReaderImpl(); return null; } public Option getOption(String uri) { return null; } }
package com.tinkerrocks.structure; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine; import org.apache.tinkerpop.gremlin.structure.*; import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Iterator; public class RocksTest { RocksGraph graph; @Before public void setup() throws IOException, InstantiationException { Configuration configuration = new BaseConfiguration(); FileUtils.deleteDirectory(new File("/tmp/databases")); FileUtils.forceMkdir(new File("/tmp/databases")); graph = RocksGraph.open(configuration); } @Test public void testMultiValues() { Vertex marko = graph.addVertex(T.label, "person", T.id, "jumbaho", "name", "marko", "age", 29); marko.property(VertexProperty.Cardinality.list, "country", "usa"); marko.property(VertexProperty.Cardinality.set, "country", "uk"); marko.property(VertexProperty.Cardinality.list, "country", "japan"); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); System.out.println(g.V("jumbaho").has("country", "japan").properties().toList()); //marko.properties().forEachRemaining(System.out::println); } @Test public void addVertexTest() { graph.createIndex("age", Vertex.class); graph.createIndex("weight", Edge.class); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); //System.out.println("g=" + g); System.out.println("traversed edge" + g.V().toList()); //.bothE("knows").has("weight", 0.5f).tryNext().orElse(null)); //g.addV() //g.addV().addE() Vertex marko = graph.addVertex(T.label, "person", T.id, 1, "name", "marko", "age", 29); Vertex vadas = graph.addVertex(T.label, "person", T.id, 2, "name", "vadas", "age", 27); Vertex lop = graph.addVertex(T.label, "software", T.id, 3, "name", "lop", "lang", "java"); Vertex josh = graph.addVertex(T.label, "person", T.id, 4, "name", "josh", "age", 32); Vertex ripple = graph.addVertex(T.label, "software", T.id, 5, "name", "ripple", "lang", "java"); Vertex peter = graph.addVertex(T.label, "person", T.id, 6, "name", "peter", "age", 35); marko.addEdge("knows", vadas, T.id, 7, "weight", 0.5f, "weight1", 10.6f); marko.addEdge("knows", josh, T.id, 8, "weight", 1.0f); marko.addEdge("created", lop, T.id, 9, "weight", 0.4f); josh.addEdge("created", ripple, T.id, 10, "weight", 1.0f); josh.addEdge("created", lop, T.id, 11, "weight", 0.4f); peter.addEdge("created", lop, T.id, 12, "weight", 0.2f); Iterator<Vertex> iter = graph.vertices(1); while (iter.hasNext()) { Vertex test = iter.next(); Iterator<VertexProperty<Object>> properties = test.properties(); while (properties.hasNext()) { System.out.println("vertex:" + test + "\tproperties:" + properties.next()); } Iterator<Edge> edges = test.edges(Direction.BOTH); while (edges.hasNext()) { Edge edge = edges.next(); System.out.println("Edge: " + edge); Iterator<Property<Object>> edge_properties = edge.properties(); while (edge_properties.hasNext()) { System.out.println("edge:" + test + "\tproperties:" + edge_properties.next()); } } //System.out.println(iter.next().edges(Direction.BOTH).hasNext()); } } @Test public void PerfTest() { graph.createIndex("name", Vertex.class); long start = System.currentTimeMillis(); int ITERATIONS = 10000; for (int i = 0; i < ITERATIONS; i++) { graph.addVertex(T.label, "person", T.id, 200 + i, "name", "marko" + i, "age", 29); } long end = System.currentTimeMillis() - start; System.out.println("write time takes to add " + ITERATIONS + " vertices (ms):\t" + end); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { graph.vertices(200 + i).next().property("name"); } end = System.currentTimeMillis() - start; System.out.println("read time takes to read " + ITERATIONS + " vertices (ms):\t" + end); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { graph.vertices(200).next().property("name"); } end = System.currentTimeMillis() - start; System.out.println("read time takes to access same vertex " + ITERATIONS + " times (ms):\t" + end); Vertex supernode = graph.vertices(200).next(); Vertex supernodeSink = graph.vertices(201).next(); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { supernode.addEdge("knows", supernodeSink, T.id, 700 + i, "weight", 0.5f); } end = System.currentTimeMillis() - start; System.out.println("time to add " + ITERATIONS + " edges (ms):\t" + end); start = System.currentTimeMillis(); supernode.edges(Direction.BOTH); end = System.currentTimeMillis() - start; System.out.println("time to read " + ITERATIONS + " edges (ms):\t" + end); start = System.currentTimeMillis(); Iterator<Edge> test = supernode.edges(Direction.OUT, "knows"); end = System.currentTimeMillis() - start; System.out.println("time to read " + ITERATIONS + " cached edges (ms):\t" + end); long count = IteratorUtils.count(test); System.out.println("got edges: " + count); } @Test public void IndexTest() { graph.createIndex("age", Vertex.class); int i = 0; while (i < 5000) { graph.addVertex(T.label, "person", T.id, "index" + i, "name", "marko", "age", 29); i++; } while (i < 5000) { graph.addVertex(T.label, "personal", T.id, "index" + (5000 + i), "name", "marko", "age", 29); i++; } while (i < 200000) { graph.addVertex(T.label, "movie", T.id, "index" + (10000 + i), "name", "marko"); i++; } graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 30); graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 31); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); long start = System.currentTimeMillis(); System.out.println(g.V().has("age", 31).toList().size()); long end = System.currentTimeMillis(); System.out.println("time taken to search:" + (end - start)); } @After public void close() throws Exception { this.graph.close(); } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.ClearByCategoryCommand; import seedu.taskboss.testutil.TestTask; public class ClearByCategoryCommandTest extends TaskBossGuiTest { //@@author A0147990R // Equivalence partition: clear by an existing category @Test public void clearByCategory_existingCategory() { String categoryDetails = "c/friends"; TestTask[] expectedTaskList = new TestTask[]{td.carl, td.elle, td.daniel, td.george, td.fiona}; boolean isShortedCommand = false; assertClearSuccess(isShortedCommand, categoryDetails, expectedTaskList); } //@@author A0147990R // EP: use short command to clear by an existing category @Test public void clearByCategory_existingCategoryWithShortcut() { String categoryDetails = "c/friends"; TestTask[] expectedTaskList = new TestTask[]{td.carl, td.elle, td.daniel, td.george, td.fiona}; boolean isShortedCommand = true; assertClearSuccess(isShortedCommand, categoryDetails, expectedTaskList); } //@@author A0147990R // EP: invalid command word @Test public void clearByCategory_invalidCommand_fail() { commandBox.runCommand("clearare"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); } //@@author A0147990R // EP: invalid command format @Test public void clearByCategory_invalidCommandFormat_fail() { commandBox.runCommand("clear w/try"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ClearByCategoryCommand.MESSAGE_USAGE)); } //@@author A0147990R // EP: clear by an inexistent category @Test public void clearByCategory_nonExistingCategory() { commandBox.runCommand("clear c/strange"); assertResultMessage(String.format(ClearByCategoryCommand.MESSAGE_CATEGORY_NOT_FOUND)); } //@@author A0147990R /** * Checks whether the edited task has the correct updated details. * @param isShortCommand * @param categoryDetails category to clear as input to the ClearCategoryCommand * @param expectedTaskList the expected task list after clearing tasks by category */ private void assertClearSuccess(boolean isShortCommand, String categoryDetails, TestTask[] expectedTaskList) { if (isShortCommand) { commandBox.runCommand("c " + categoryDetails); } else { commandBox.runCommand("clear " + categoryDetails); } assertTrue(taskListPanel.isListMatching(expectedTaskList)); assertResultMessage(String.format(ClearByCategoryCommand.MESSAGE_CLEAR_TASK_SUCCESS)); } }
package hudson.plugins.groovy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import hudson.model.Result; import hudson.model.FreeStyleProject; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; public class ClassPathTest { @Rule public JenkinsRule j = new JenkinsRule(); /** * Tests that groovy build step accepts wild cards on class path */ @Issue("JENKINS-26070") @Test public void testWildcartOnClassPath() throws Exception { final String testJar = "groovy-cp-test.jar"; final ScriptSource script = new StringScriptSource(new SecureGroovyScript( "def printCP(classLoader){\n " + " classLoader.getURLs().each {println \"$it\"}\n" + " if(classLoader.parent) {printCP(classLoader.parent)}\n" + "}\n" + "printCP(this.class.classLoader)", true, null));
package imagej.dataset; import java.util.ArrayList; import imagej.MetaData; import imagej.data.Type; // TODOs // Dataset matches parent in extent of its subset of axes. i.e. given [1,2,5] and axes [0,1,-1] the dataset has extent 5 in its only free axis. // Would like to come up with a subsetting view that could have smaller bounds than parent. This would cause us to have to write bounds checking // code for that class on every data access. // TODO - this is a first pass implementation. it has many instance vars that could be trimmed down. fix as possible. /** a DatasetView is Dataset that acts like a view into a larger Dataset with some axes fixed. */ public class DatasetView implements Dataset { // Core instance variables for this implementation private Dataset fullSpaceDataset; private int[] fullSpaceAxisValues; private int[] viewDimensions; private int[] viewAxesIndices; // caching variables for performance private int[] fullSpaceIndex; private int[] oneDimWorkspace; private int firstFixedAxis; private int fullDimensionsLength; private int viewDimensionsLength; // general Dataset support variables private Dataset parent; private MetaData metadata; /** Constructor * * @param referenceDataset - the Dataset this view will be constrained within * @param fullSpaceAxisValues - a specified list of axis values. one entry per axis present in viewed Dataset. An example value of fixed axes * might be [1,0,3,-1,-1] which implies x=1. y=0, z=3, c and t vary. This creates a two dim view of the larger dataset in c & t. */ public DatasetView(Dataset referenceDataset, int[] fullSpaceAxisValues) { int[] fullDimensions = referenceDataset.getDimensions(); this.fullSpaceAxisValues = fullSpaceAxisValues; this.fullDimensionsLength = fullDimensions.length; int inputAxesLength = fullSpaceAxisValues.length; if (inputAxesLength != this.fullDimensionsLength) throw new IllegalArgumentException("specified axes of interest are not the correct length"); this.firstFixedAxis = Integer.MAX_VALUE; for (int i = 0; i < inputAxesLength; i++) { if (fullSpaceAxisValues[i] != -1) { this.firstFixedAxis = i; i = inputAxesLength; } } int[] tempValues = new int[inputAxesLength]; int[] tempIndices = new int[inputAxesLength]; int numAxesInView = 0; for (int i = 0; i < inputAxesLength; i++) { if (fullSpaceAxisValues[i] == -1) { tempValues[numAxesInView] = fullDimensions[i]; tempIndices[numAxesInView] = i; numAxesInView++; } } if (numAxesInView == 0) throw new IllegalArgumentException("no axes of interest specified"); this.viewDimensions = new int[numAxesInView]; for (int i = 0; i < numAxesInView; i++) this.viewDimensions[i] = tempValues[i]; this.viewAxesIndices = new int[numAxesInView]; for (int i = 0; i < numAxesInView; i++) this.viewAxesIndices[i] = tempIndices[i]; this.fullSpaceDataset = referenceDataset; this.metadata = new MetaData(); // TODO - or from reference dataset??? this.parent = null; this.fullSpaceIndex = fullSpaceAxisValues.clone(); this.oneDimWorkspace = new int[1]; this.viewDimensionsLength = this.viewDimensions.length; } private boolean anyAxesFixedLeftOfPartialIndex(int[] partialFullSpaceIndex) { int unreferencedAxes = this.fullDimensionsLength - partialFullSpaceIndex.length; return (this.firstFixedAxis < unreferencedAxes); } private int[] createPartialFullSpaceIndex(int[] viewSpaceIndex) { ArrayList<Integer> indices = new ArrayList<Integer>(); int fullSpaceIndex = this.fullDimensionsLength - 1; while ((fullSpaceIndex >= 0) && (this.fullSpaceAxisValues[fullSpaceIndex] != -1)) { indices.add(0, this.fullSpaceAxisValues[fullSpaceIndex]); fullSpaceIndex } int viewIndex = viewSpaceIndex.length-1; while (viewIndex >= 0) { // add specified view coord axis indices.add(0, viewSpaceIndex[viewIndex]); viewIndex fullSpaceIndex // add any other fixed axes present while ((fullSpaceIndex >= 0) && (this.fullSpaceAxisValues[fullSpaceIndex] != -1)) { indices.add(0, this.fullSpaceAxisValues[fullSpaceIndex]); fullSpaceIndex } } int partialIndexSize = indices.size(); int[] partialFullSpaceIndex = new int [partialIndexSize]; for (int i = 0; i < partialIndexSize; i++) partialFullSpaceIndex[i] = indices.get(i); return partialFullSpaceIndex; } private void fillFullSpaceIndex(int[] fromSubspaceIndex) { for (int i = 0; i < this.viewDimensionsLength; i++) { int indexOfAxis = this.viewAxesIndices[i]; this.fullSpaceIndex[indexOfAxis] = fromSubspaceIndex[i]; } } @Override public int[] getDimensions() { return this.viewDimensions; } @Override public Type getType() { return this.fullSpaceDataset.getType(); } @Override public MetaData getMetaData() { return this.metadata; } @Override public void setMetaData(MetaData metadata) { this.metadata = metadata; } @Override public boolean isComposite() { return true; } @Override public Dataset getParent() { return this.parent; } @Override public void setParent(Dataset dataset) { this.parent = dataset; } @Override public Object getData() { return null; } @Override public void releaseData() { // do nothing } @Override public void setData(Object data) { throw new IllegalArgumentException("cannot setData() on a DatasetView"); } @Override public Dataset insertNewSubset(int position) { throw new IllegalArgumentException("cannot insertNewSubset() on a DatasetView"); } @Override public Dataset removeSubset(int position) { throw new IllegalArgumentException("cannot removeSubset() on a DatasetView"); } @Override public Dataset getSubset(int position) { this.oneDimWorkspace[0] = position; return getSubset(this.oneDimWorkspace); } /* ds = [2,3,4,5]; view = [-1,-1,2,3]; view.is2d(); view.getSubset([] should return [2,3] of master dataset); view.getSubset([i] should return [i,2,3] of master dataset); view.getSubset([j,i] should return [j,i,2,3] of master dataset); view = [-1,-1,-1,3]; view.is3d(); view.getSubset([] should return [3] of master dataset); view.getSubset([i] should return [i,3] of master dataset); view.getSubset([j,i] should return [j,i,3] of master dataset); view.getSubset([k,j,i] should return [k,j,i,3] of master dataset); view = [-1,-1,3,-1]; view.is3d(); view.getSubset([] is broken as it returns master dataset but z not constrained to 3); view.getSubset([i] should work - use index [3,i] of master dataset); view.getSubset([j,i] should work - use index [j,3,i] of master dataset); view.getSubset([k,j,i] should work - use index [k,j,3,i] of master dataset); view = [-1,3,-1,-1]; view.is3d(); view.getSubset([] is broken as it returns master dataset but y not constrained to 3); view.getSubset([i] will not work - gives back a 3d subset of master dataset but y is not constrained to 3); view.getSubset([j,i] should work - use index [3,j,i] of master dataset); view.getSubset([k,j,i] should work - use index [k,3,j,i] of master dataset); view = [3,-1,-1,-1]; view.is3d(); view.getSubset([] is broken as it returns master dataset but x not constrained to 3); view.getSubset([i] will not work - gives back a 3d subset of master dataset but y is not constrained to 3); view.getSubset([j,i] will not work - gives back a 2d subset of master dataset but x is not constrained to 3); view.getSubset([k,j,i] should work - use index [3,k,j,i] of master dataset); if no fixed dims left of my last partial index axis then its safe to subset */ @Override public Dataset getSubset(int[] index) { int[] partialFullSpaceIndex = createPartialFullSpaceIndex(index); if (anyAxesFixedLeftOfPartialIndex(partialFullSpaceIndex)) throw new IllegalArgumentException("dataset has too many fixed axes to successfully find subset with given partial index"); return this.fullSpaceDataset.getSubset(partialFullSpaceIndex); } @Override public double getDouble(int[] position) { fillFullSpaceIndex(position); return this.fullSpaceDataset.getDouble(this.fullSpaceIndex); } @Override public void setDouble(int[] position, double value) { fillFullSpaceIndex(position); this.fullSpaceDataset.setDouble(this.fullSpaceIndex, value); } @Override public long getLong(int[] position) { fillFullSpaceIndex(position); return this.fullSpaceDataset.getLong(this.fullSpaceIndex); } @Override public void setLong(int[] position, long value) { fillFullSpaceIndex(position); this.fullSpaceDataset.setLong(this.fullSpaceIndex, value); } }
package com.opensymphony.workflow.designer; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; import java.util.List; import java.util.Properties; import javax.swing.*; import com.opensymphony.workflow.designer.actions.*; import com.opensymphony.workflow.designer.dnd.DragData; import com.opensymphony.workflow.designer.layout.LayoutAlgorithm; import com.opensymphony.workflow.designer.layout.SugiyamaLayoutAlgorithm; import com.opensymphony.workflow.designer.views.*; import com.opensymphony.workflow.loader.JoinDescriptor; import com.opensymphony.workflow.loader.SplitDescriptor; import com.opensymphony.workflow.loader.StepDescriptor; import com.opensymphony.workflow.loader.WorkflowDescriptor; import org.jgraph.JGraph; import org.jgraph.graph.*; public class WorkflowGraph extends JGraph implements DropTargetListener { private Layout layout = new Layout(); private Point menuLocation = new Point(); private WorkflowDescriptor descriptor; private JPopupMenu menu; private JPopupMenu delete; public WorkflowGraph(GraphModel model, WorkflowDescriptor descriptor, Layout layout, boolean doAutoLayout) { super(model); ToolTipManager.sharedInstance().registerComponent(this); this.layout = layout; setDescriptor(descriptor); if(doAutoLayout) { autoLayout(); } setSelectNewCells(true); setGridEnabled(true); setGridColor(java.awt.Color.gray.brighter()); setGridSize(12); setTolerance(2); setGridVisible(true); setGridMode(JGraph.LINE_GRID_MODE); setBendable(true); setMarqueeHandler(new WorkflowMarqueeHandler(this)); setCloneable(false); setPortsVisible(true); // one set of menu <==> one graph <==> one workflow descriptor menu = new JPopupMenu(); JMenu n = new JMenu("New"); menu.add(n); n.add(new CreateStep(descriptor, getWorkflowGraphModel(), menuLocation)); // n.add(new CreateInitialAction(descriptor, getWorkflowGraphModel(), menuLocation)); n.add(new CreateJoin(descriptor, getWorkflowGraphModel(), menuLocation)); n.add(new CreateSplit(descriptor, getWorkflowGraphModel(), menuLocation)); delete = new JPopupMenu(); delete.add(new Delete(descriptor, this, menuLocation)); new DropTarget(this, this); } public void setDescriptor(WorkflowDescriptor descriptor) { if(descriptor != null) { this.descriptor = descriptor; List initialActionList = descriptor.getInitialActions(); addInitialActions(initialActionList); List stepsList = descriptor.getSteps(); for(int i = 0; i < stepsList.size(); i++) { StepDescriptor step = (StepDescriptor)stepsList.get(i); addStepDescriptor(step); } List splitsList = descriptor.getSplits(); for(int i = 0; i < splitsList.size(); i++) { SplitDescriptor split = (SplitDescriptor)splitsList.get(i); addSplitDescriptor(split); } List joinsList = descriptor.getJoins(); for(int i = 0; i < joinsList.size(); i++) { JoinDescriptor join = (JoinDescriptor)joinsList.get(i); addJoinDescriptor(join); } getWorkflowGraphModel().insertResultConnections(); } } protected PortView createPortView(Object object, CellMapper mapper) { return new CustomPortView(object, this, mapper); } public void autoLayout() { if(descriptor.getSteps().size() > 0) { LayoutAlgorithm algo = new SugiyamaLayoutAlgorithm(); Properties p = new Properties(); p.put(SugiyamaLayoutAlgorithm.KEY_HORIZONTAL_SPACING, "110"); p.put(SugiyamaLayoutAlgorithm.KEY_VERTICAL_SPACING, "70"); algo.perform(this, true, p); } } public void addInitialActions(List initialActionList) { InitialActionCell initialActionCell = new InitialActionCell("Start"); // Create Vertex Attributes if(layout != null) { Rectangle bounds = layout.getBounds(initialActionCell.toString()); if(bounds != null) { GraphConstants.setBounds(initialActionCell.getAttributes(), bounds); } if(initialActionCell.getChildCount() == 0) { WorkflowPort port = new WorkflowPort(); initialActionCell.add(port); } } else { WorkflowPort port = new WorkflowPort(); initialActionCell.add(port); } getWorkflowGraphModel().insertInitialActions(initialActionList, initialActionCell, null, null, null); } public void addJoinDescriptor(JoinDescriptor descriptor) { JoinCell join = new JoinCell(descriptor); // Create Vertex Attributes if(layout != null) { Rectangle bounds = layout.getBounds(join.toString()); if(bounds != null) join.getAttributes().put(GraphConstants.BOUNDS, bounds); if(join.getChildCount() == 0) { WorkflowPort port = new WorkflowPort(); join.add(port); } } else { WorkflowPort port = new WorkflowPort(); join.add(port); } getWorkflowGraphModel().insertJoinCell(join, null, null, null); } public void addSplitDescriptor(SplitDescriptor descriptor) { SplitCell split = new SplitCell(descriptor); if(layout != null) { Rectangle bounds = layout.getBounds(split.toString()); if(bounds != null) split.getAttributes().put(GraphConstants.BOUNDS, bounds); if(split.getChildCount() == 0) { WorkflowPort port = new WorkflowPort(); split.add(port); } } else { WorkflowPort port = new WorkflowPort(); split.add(port); } getWorkflowGraphModel().insertSplitCell(split, null, null, null); } public void addStepDescriptor(StepDescriptor descriptor) { StepCell step = new StepCell(descriptor); if(layout != null) { Rectangle bounds = layout.getBounds(step.toString()); if(bounds != null) { step.getAttributes().put(GraphConstants.BOUNDS, bounds); } if(step.getChildCount() == 0) { WorkflowPort port = new WorkflowPort(); step.add(port); } } else { } // Insert into Model getWorkflowGraphModel().insertStepCell(step, null, null, null); } public WorkflowGraphModel getWorkflowGraphModel() { return (WorkflowGraphModel)getModel(); } /** * Overriding method as required by JGraph API, * In order to return right View object corresponding to Cell. */ protected VertexView createVertexView(Object v, CellMapper cm) { if(v instanceof StepCell) return new StepView(v, this, cm); if(v instanceof SplitCell) return new SplitView(v, this, cm); if(v instanceof JoinCell) return new JoinView(v, this, cm); if(v instanceof InitialActionCell) return new InitialActionView(v, this, cm); // Else Call Superclass return super.createVertexView(v, cm); } public void showMenu(int x, int y) { menuLocation.x = x; menuLocation.y = y; menu.show(this, x, y); } public void showDelete(int x, int y) { menuLocation.x = x; menuLocation.y = y; delete.show(this, x, y); } public boolean removeEdge(ResultEdge edge) { return getWorkflowGraphModel().removeEdge(edge); } public boolean removeStep(StepCell step) { getWorkflowGraphModel().removeStep(step); return true; } public boolean removeJoin(JoinCell join) { return getWorkflowGraphModel().removeJoin(join); } public boolean removeSplit(SplitCell split) { return getWorkflowGraphModel().removeSplit(split); } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { } public void dropActionChanged(DropTargetDragEvent dtde) { } public void drop(DropTargetDropEvent dtde) { try { //Ok, get the dropped object and try to figure out what it is. Transferable tr = dtde.getTransferable(); DataFlavor[] flavors = tr.getTransferDataFlavors(); for(int i = 0; i < flavors.length; i++) { if(flavors[i].isFlavorSerializedObjectType()) { if(flavors[i].equals(DragData.scriptFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); DragData o = (DragData)tr.getTransferData(flavors[i]); dtde.dropComplete(true); CellFactory.createCell(this.descriptor, this.getWorkflowGraphModel(), dtde.getLocation(), o); return; } } } dtde.rejectDrop(); } catch(Exception e) { e.printStackTrace(); dtde.rejectDrop(); } } public void dragExit(DropTargetEvent dte) { } }
package mho.qbar.objects; import mho.wheels.iterables.ExhaustiveProvider; import mho.wheels.iterables.RandomProvider; import mho.wheels.math.Combinatorics; import mho.wheels.math.MathUtils; import mho.wheels.misc.BigDecimalUtils; import mho.wheels.misc.FloatUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import mho.qbar.iterableProviders.QBarExhaustiveProvider; import mho.qbar.iterableProviders.QBarIterableProvider; import mho.qbar.iterableProviders.QBarRandomProvider; import org.jetbrains.annotations.NotNull; import org.junit.Test; import sun.jvm.hotspot.utilities.Assert; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Random; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; import static mho.qbar.objects.Rational.*; import static org.junit.Assert.*; public class RationalProperties { private static boolean USE_RANDOM; private static final String RATIONAL_CHARS = "-/0123456789"; private static final int SMALL_LIMIT = 1000; private static int LIMIT; private static QBarIterableProvider P; private static void initialize() { if (USE_RANDOM) { P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL)); LIMIT = 1000; } else { P = QBarExhaustiveProvider.INSTANCE; LIMIT = 10000; } } @Test public void testAllProperties() { for (boolean useRandom : Arrays.asList(false, true)) { System.out.println("Testing " + (useRandom ? "randomly" : "exhaustively")); USE_RANDOM = useRandom; propertiesOf_BigInteger_BigInteger(); propertiesOf_long_long(); propertiesOf_int_int(); propertiesOf_BigInteger(); propertiesOf_long(); propertiesOf_int(); propertiesOf_float(); propertiesOf_double(); propertiesOfExact_float(); propertiesOfExact_double(); propertiesOf_BigDecimal(); propertiesBigIntegerValue_RoundingMode(); propertiesBigIntegerValue(); propertiesBigIntegerValueExact(); propertiesByteValueExact(); propertiesShortValueExact(); propertiesIntValueExact(); propertiesLongValueExact(); propertiesHasTerminatingDecimalExpansion(); propertiesBigDecimalValue_int_RoundingMode(); propertiesBigDecimalValue_int(); propertiesBigDecimalValueExact(); propertiesBinaryExponent(); propertiesFloatValue_RoundingMode(); propertiesFloatValue(); propertiesFloatValueExact(); propertiesDoubleValue_RoundingMode(); propertiesDoubleValue(); propertiesDoubleValueExact(); propertiesNegate(); propertiesInvert(); propertiesAbs(); propertiesSignum(); propertiesAdd(); propertiesSubtract(); propertiesMultiply_Rational_Rational(); propertiesMultiply_BigInteger(); propertiesMultiply_int(); propertiesDivide_Rational_Rational(); propertiesDivide_BigInteger(); propertiesDivide_int(); propertiesSum(); propertiesProduct(); propertiesDelta(); propertiesHarmonicNumber(); propertiesPow(); propertiesFloor(); propertiesCeiling(); propertiesFractionalPart(); propertiesRoundToDenominator(); propertiesShiftLeft(); propertiesShiftRight(); propertiesEquals(); propertiesHashCode(); propertiesCompareTo(); propertiesRead(); propertiesToString(); System.out.println(); } System.out.println("Done"); } private static void propertiesOf_BigInteger_BigInteger() { initialize(); System.out.println("testing of(BigInteger, BigInteger) properties..."); Iterable<Pair<BigInteger, BigInteger>> ps = filter( p -> { assert p.b != null; return !p.b.equals(BigInteger.ZERO); }, P.pairs(P.bigIntegers()) ); for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational r = of(p.a, p.b); validate(r); assertEquals(p.toString(), of(p.a).divide(p.b), r); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { try { of(i, BigInteger.ZERO); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesOf_long_long() { initialize(); System.out.println("testing of(long, long) properties..."); BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE); BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE); Iterable<Pair<Long, Long>> ps = filter(p -> p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational r = of(p.a, p.b); validate(r); assertEquals(p.toString(), of(p.a).divide(BigInteger.valueOf(p.b)), r); assertTrue(p.toString(), ge(r.getNumerator(), minLong)); assertTrue(p.toString(), le(r.getNumerator(), maxLong)); assertTrue(p.toString(), ge(r.getDenominator(), minLong)); assertTrue(p.toString(), le(r.getDenominator(), maxLong)); } for (long l : take(LIMIT, P.longs())) { try { of(l, 0L); fail(Long.toString(l)); } catch (ArithmeticException ignored) {} } } private static void propertiesOf_int_int() { initialize(); System.out.println("testing of(int, int) properties..."); BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE); BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE); Iterable<Pair<Integer, Integer>> ps = filter(p -> p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational r = of(p.a, p.b); validate(r); assertEquals(p.toString(), of(p.a).divide(p.b), r); assertTrue(p.toString(), ge(r.getNumerator(), minInt)); assertTrue(p.toString(), le(r.getNumerator(), maxInt)); assertTrue(p.toString(), ge(r.getDenominator(), minInt)); assertTrue(p.toString(), le(r.getDenominator(), maxInt)); } for (int i : take(LIMIT, P.integers())) { try { of(i, 0); fail(Integer.toString(i)); } catch (ArithmeticException ignored) {} } } private static void propertiesOf_BigInteger() { initialize(); System.out.println("testing of(BigInteger) properties..."); for (BigInteger i : take(LIMIT, P.bigIntegers())) { Rational r = of(i); validate(r); assertEquals(i.toString(), r.getDenominator(), BigInteger.ONE); } } private static void propertiesOf_long() { initialize(); System.out.println("testing of(long) properties..."); BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE); BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE); for (long l : take(LIMIT, P.longs())) { Rational r = of(l); validate(r); assertEquals(Long.toString(l), r.getDenominator(), BigInteger.ONE); assertTrue(Long.toString(l), ge(r.getNumerator(), minLong)); assertTrue(Long.toString(l), le(r.getNumerator(), maxLong)); } } private static void propertiesOf_int() { initialize(); System.out.println("testing of(int) properties..."); BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE); BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE); for (int i : take(LIMIT, P.integers())) { Rational r = of(i); validate(r); assertEquals(Integer.toString(i), r.getDenominator(), BigInteger.ONE); assertTrue(Integer.toString(i), ge(r.getNumerator(), minInt)); assertTrue(Integer.toString(i), le(r.getNumerator(), maxInt)); } } private static void propertiesOf_float() { initialize(); System.out.println("testing of(float) properties..."); Iterable<Float> fs = filter(f -> Float.isFinite(f) && !Float.isNaN(f), P.floats()); for (float f : take(LIMIT, fs)) { Rational r = of(f); assert r != null; validate(r); assertTrue(Float.toString(f), r.hasTerminatingDecimalExpansion()); } for (float f : take(LIMIT, P.ordinaryFloats())) { Rational r = of(f); assert r != null; aeq(Float.toString(f), f, r.floatValue()); aeq(Float.toString(f), new BigDecimal(Float.toString(f)), r.bigDecimalValueExact()); } } private static void propertiesOf_double() { initialize(); System.out.println("testing of(double) properties..."); Iterable<Double> ds = filter(d -> Double.isFinite(d) && !Double.isNaN(d), P.doubles()); for (double d : take(LIMIT, ds)) { Rational r = of(d); assert r != null; validate(r); assertTrue(Double.toString(d), r.hasTerminatingDecimalExpansion()); } for (double d : take(LIMIT, P.ordinaryDoubles())) { Rational r = of(d); assert r != null; aeq(Double.toString(d), d, r.doubleValue()); aeq(Double.toString(d), new BigDecimal(Double.toString(d)), r.bigDecimalValueExact()); } } private static void propertiesOfExact_float() { initialize(); System.out.println("testing ofExact(float) properties..."); BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(149); BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE.shiftLeft(104)); Iterable<Float> fs = filter(f -> Float.isFinite(f) && !Float.isNaN(f), P.floats()); for (float f : take(LIMIT, fs)) { Rational r = ofExact(f); assert r != null; validate(r); assertTrue(Float.toString(f), MathUtils.isAPowerOfTwo(r.getDenominator())); assertTrue(Float.toString(f), le(r.getDenominator(), denominatorLimit)); assertTrue(Float.toString(f), le(r.getNumerator(), numeratorLimit)); } for (float f : take(LIMIT, P.ordinaryFloats())) { Rational r = ofExact(f); assert r != null; aeq(Float.toString(f), f, r.floatValue()); } } private static void propertiesOfExact_double() { initialize(); System.out.println("testing ofExact(double) properties..."); BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(1074); BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(1024).subtract(BigInteger.ONE.shiftLeft(971)); Iterable<Double> ds = filter(d -> Double.isFinite(d) && !Double.isNaN(d), P.doubles()); for (double d : take(LIMIT, ds)) { Rational r = ofExact(d); assert r != null; validate(r); assertTrue(Double.toString(d), MathUtils.isAPowerOfTwo(r.getDenominator())); assertTrue(Double.toString(d), le(r.getDenominator(), denominatorLimit)); assertTrue(Double.toString(d), le(r.getNumerator(), numeratorLimit)); } for (double d : take(LIMIT, P.ordinaryDoubles())) { Rational r = ofExact(d); assert r != null; aeq(Double.toString(d), d, r.doubleValue()); } } private static void propertiesOf_BigDecimal() { initialize(); System.out.println("testing of(BigDecimal) properties..."); for (BigDecimal bd : take(LIMIT, P.bigDecimals())) { Rational r = of(bd); validate(r); aeq(bd.toString(), bd, r.bigDecimalValueExact()); assertTrue(bd.toString(), r.hasTerminatingDecimalExpansion()); } } private static void propertiesBigIntegerValue_RoundingMode() { initialize(); System.out.println("testing bigIntegerValue(RoundingMode) properties..."); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> { assert p.a != null; return p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE); }, P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigInteger rounded = p.a.bigIntegerValue(p.b); assertTrue(p.toString(), rounded.equals(BigInteger.ZERO) || rounded.signum() == p.a.signum()); assertTrue(p.toString(), lt(subtract(p.a, of(rounded)).abs(), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), of(i).bigIntegerValue(RoundingMode.UNNECESSARY), i); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.FLOOR), r.floor()); assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.CEILING), r.ceiling()); assertTrue(r.toString(), le(of(r.bigIntegerValue(RoundingMode.DOWN)).abs(), r.abs())); assertTrue(r.toString(), ge(of(r.bigIntegerValue(RoundingMode.UP)).abs(), r.abs())); assertTrue(r.toString(), le(subtract(r, of(r.bigIntegerValue(RoundingMode.HALF_DOWN))).abs(), of(1, 2))); assertTrue(r.toString(), le(subtract(r, of(r.bigIntegerValue(RoundingMode.HALF_UP))).abs(), of(1, 2))); assertTrue(r.toString(), le(subtract(r, of(r.bigIntegerValue(RoundingMode.HALF_EVEN))).abs(), of(1, 2))); } Iterable<Rational> rs = filter(r -> lt(r.abs().fractionalPart(), of(1, 2)), P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.DOWN)); assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.DOWN)); assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.DOWN)); } rs = filter(r -> gt(r.abs().fractionalPart(), of(1, 2)), P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.UP)); assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP)); assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.UP)); } //odd multiples of 1/2 rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), BigInteger.valueOf(2)), P.bigIntegers()); for (Rational r : take(LIMIT, rs)) { assertEquals( r.toString(), r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.DOWN)) ; assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP)); assertFalse(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN).testBit(0)); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.bigIntegerValue(RoundingMode.UNNECESSARY); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesBigIntegerValue() { initialize(); System.out.println("testing bigIntegerValue() properties..."); for (Rational r : take(LIMIT, P.rationals())) { BigInteger rounded = r.bigIntegerValue(); assertTrue(r.toString(), rounded.equals(BigInteger.ZERO) || rounded.signum() == r.signum()); assertTrue(r.toString(), le(subtract(r, of(r.bigIntegerValue())).abs(), of(1, 2))); } Iterable<Rational> rs = filter(r -> lt(r.abs().fractionalPart(), of(1, 2)), P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.DOWN)); } rs = filter(r -> gt(r.abs().fractionalPart(), of(1, 2)), P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.UP)); } //odd multiples of 1/2 rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), BigInteger.valueOf(2)), P.bigIntegers()); for (Rational r : take(LIMIT, rs)) { assertFalse(r.toString(), r.bigIntegerValue().testBit(0)); } } private static void propertiesBigIntegerValueExact() { initialize(); System.out.println("testing bigIntegerValueExact() properties..."); for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), of(i).bigIntegerValueExact(), i); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.bigIntegerValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesByteValueExact() { initialize(); System.out.println("testing byteValueExact() properties..."); for (byte b : take(LIMIT, P.bytes())) { assertEquals(Byte.toString(b), of(b).byteValueExact(), b); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.byteValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, range(BigInteger.valueOf(Byte.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).byteValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> below = rangeBy( BigInteger.valueOf(Byte.MIN_VALUE).subtract(BigInteger.ONE), BigInteger.valueOf(-1) ); for (BigInteger i : take(LIMIT, below)) { try { of(i).byteValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesShortValueExact() { initialize(); System.out.println("testing shortValueExact() properties..."); for (short s : take(LIMIT, P.shorts())) { assertEquals(Short.toString(s), of(s).shortValueExact(), s); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.shortValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, range(BigInteger.valueOf(Short.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).shortValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> below = rangeBy( BigInteger.valueOf(Short.MIN_VALUE).subtract(BigInteger.ONE), BigInteger.valueOf(-1) ); for (BigInteger i : take(LIMIT, below)) { try { of(i).shortValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesIntValueExact() { initialize(); System.out.println("testing intValueExact() properties..."); for (int i : take(LIMIT, P.integers())) { assertEquals(Integer.toString(i), of(i).intValueExact(), i); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.intValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, range(BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).intValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> below = rangeBy( BigInteger.valueOf(Integer.MIN_VALUE).subtract(BigInteger.ONE), BigInteger.valueOf(-1) ); for (BigInteger i : take(LIMIT, below)) { try { of(i).intValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesLongValueExact() { initialize(); System.out.println("testing longValueExact() properties..."); for (long l : take(LIMIT, P.longs())) { assertEquals(Long.toString(l), of(l).longValueExact(), l); } for (Rational r : take(LIMIT, filter(s -> !s.getDenominator().equals(BigInteger.ONE), P.rationals()))) { try { r.longValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, range(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).longValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> below = rangeBy( BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), BigInteger.valueOf(-1) ); for (BigInteger i : take(LIMIT, below)) { try { of(i).longValueExact(); fail(i.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesHasTerminatingDecimalExpansion() { initialize(); System.out.println("testing hasTerminatingDecimalExpansion() properties..."); for (Rational r : take(LIMIT, P.rationals())) { r.hasTerminatingDecimalExpansion(); } Iterable<Rational> rs = filter(Rational::hasTerminatingDecimalExpansion, P.rationals()); for (Rational r : take(LIMIT, rs)) { r.bigDecimalValue(0); List<BigInteger> dPrimeFactors = toList( nub(map(p -> p.a, MathUtils.compactPrimeFactors(r.getDenominator()))) ); assertTrue( r.toString(), isSubsetOf(dPrimeFactors, Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(5))) ); } } private static void propertiesBigDecimalValue_int_RoundingMode() { initialize(); System.out.println("testing bigDecimalValue(int, RoundingMode)..."); Iterable<Pair<Rational, Pair<Integer, RoundingMode>>> ps; if (P instanceof ExhaustiveProvider) { ps = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs(P.naturalIntegers(), P.roundingModes()) ); } else { ps = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs( ((RandomProvider) P).naturalIntegersGeometric(20), P.roundingModes() ) ); } ps = filter( p -> { try { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; p.a.bigDecimalValue(p.b.a, p.b.b); return true; } catch (ArithmeticException e) { return false; } }, ps ); for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; BigDecimal bd = p.a.bigDecimalValue(p.b.a, p.b.b); assertTrue(p.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum()); } for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, filter(q -> q.b.a != 0 && q.a != ZERO, ps))) { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; BigDecimal bd = p.a.bigDecimalValue(p.b.a, p.b.b); assertTrue(p.toString(), bd.precision() == p.b.a); } Iterable<Pair<Rational, Integer>> pris; if (P instanceof ExhaustiveProvider) { pris = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.naturalIntegers()); } else { pris = P.pairs(P.rationals(), ((RandomProvider) P).naturalIntegersGeometric(20)); } pris = filter( p -> { try { assert p.a != null; assert p.b != null; p.a.bigDecimalValue(p.b); return true; } catch (ArithmeticException e) { return false; } }, pris ); Iterable<Pair<Rational, Integer>> priExact = filter(p -> of(p.a.bigDecimalValue(p.b)).equals(p.a), pris); for (Pair<Rational, Integer> pri : take(LIMIT, priExact)) { assert pri.a != null; assert pri.b != null; BigDecimal bd = pri.a.bigDecimalValue(pri.b, RoundingMode.UNNECESSARY); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.UP)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_DOWN)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_UP)); assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_EVEN)); } Iterable<Pair<Rational, Integer>> priInexact = filter(p -> !of(p.a.bigDecimalValue(p.b)).equals(p.a), pris); for (Pair<Rational, Integer> pri : take(LIMIT, priInexact)) { assert pri.a != null; assert pri.b != null; BigDecimal low = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR); BigDecimal high = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING); assertTrue(pri.toString(), lt(low, high)); } for (Pair<Rational, Integer> pri : take(LIMIT, filter(p -> p.a.signum() == 1, priInexact))) { assert pri.a != null; assert pri.b != null; BigDecimal floor = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR); BigDecimal down = pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN); BigDecimal ceiling = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING); BigDecimal up = pri.a.bigDecimalValue(pri.b, RoundingMode.UP); assertEquals(pri.toString(), floor, down); assertEquals(pri.toString(), ceiling, up); } for (Pair<Rational, Integer> pri : take(LIMIT, filter(p -> p.a.signum() == -1, priInexact))) { assert pri.a != null; assert pri.b != null; BigDecimal floor = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR); BigDecimal down = pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN); BigDecimal ceiling = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING); BigDecimal up = pri.a.bigDecimalValue(pri.b, RoundingMode.UP); assertEquals(pri.toString(), floor, up); assertEquals(pri.toString(), ceiling, down); } Iterable<Pair<BigDecimal, Integer>> notMidpoints; if (P instanceof ExhaustiveProvider) { notMidpoints = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), P.naturalIntegers()); } else { notMidpoints = P.pairs(P.bigDecimals(), ((RandomProvider) P).naturalIntegersGeometric(20)); } notMidpoints = filter( p -> { assert p.a != null; assert p.b != null; if (p.a.precision() <= 1) return false; if (p.b != p.a.precision() - 1) return false; return !p.a.abs().unscaledValue().mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(5)); }, notMidpoints ); for (Pair<BigDecimal, Integer> p : take(LIMIT, notMidpoints)) { assert p.a != null; assert p.b != null; Rational r = of(p.a); BigDecimal down = r.bigDecimalValue(p.b, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValue(p.b, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValue(p.b, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValue(p.b, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValue(p.b, RoundingMode.HALF_EVEN); boolean closerToDown = lt(subtract(r, of(down)).abs(), subtract(r, of(up)).abs()); assertEquals(p.toString(), halfDown, closerToDown ? down : up); assertEquals(p.toString(), halfUp, closerToDown ? down : up); assertEquals(p.toString(), halfEven, closerToDown ? down : up); } Iterable<BigDecimal> midpoints = filter( x -> x.precision() > 1, map( x -> new BigDecimal( x.unscaledValue().multiply(BigInteger.TEN).add(BigInteger.valueOf(5)), x.scale() ), P.bigDecimals() ) ); for (BigDecimal bd : take(LIMIT, midpoints)) { Rational r = of(bd); int precision = bd.precision() - 1; BigDecimal down = r.bigDecimalValue(precision, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValue(precision, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValue(precision, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValue(precision, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValue(precision, RoundingMode.HALF_EVEN); assertEquals(bd.toString(), down, halfDown); assertEquals(bd.toString(), up, halfUp); assertTrue(bd.toString(), bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0)); } Iterable<Pair<Rational, Pair<Integer, RoundingMode>>> psFail; if (P instanceof ExhaustiveProvider) { psFail = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs(P.negativeIntegers(), P.roundingModes()) ); } else { psFail = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs( ((RandomProvider) P).negativeIntegersGeometric(20), P.roundingModes() ) ); } for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; try { p.a.bigDecimalValue(p.b.a, p.b.b); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } Iterable<Rational> rs = filter(r -> !r.hasTerminatingDecimalExpansion(), P.rationals()); Iterable<Pair<Rational, Integer>> prisFail; if (P instanceof ExhaustiveProvider) { prisFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(rs, P.naturalIntegers()); } else { prisFail = P.pairs(rs, ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<Rational, Integer> p : take(LIMIT, prisFail)) { assert p.a != null; assert p.b != null; try { p.a.bigDecimalValue(p.b, RoundingMode.UNNECESSARY); fail(p.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesBigDecimalValue_int() { initialize(); System.out.println("testing bigDecimalValue(int)..."); Iterable<Pair<Rational, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.naturalIntegers()); } else { ps = P.pairs(P.rationals(), ((RandomProvider) P).naturalIntegersGeometric(20)); } ps = filter( p -> { try { assert p.a != null; assert p.b != null; p.a.bigDecimalValue(p.b); return true; } catch (ArithmeticException e) { return false; } }, ps ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; BigDecimal bd = p.a.bigDecimalValue(p.b); assertEquals(p.toString(), bd, p.a.bigDecimalValue(p.b, RoundingMode.HALF_EVEN)); assertTrue(p.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum()); } for (Pair<Rational, Integer> p : take(LIMIT, filter(q -> q.b != 0 && q.a != ZERO, ps))) { assert p.a != null; assert p.b != null; BigDecimal bd = p.a.bigDecimalValue(p.b); assertTrue(p.toString(), bd.precision() == p.b); } Iterable<Pair<BigDecimal, Integer>> notMidpoints; if (P instanceof ExhaustiveProvider) { notMidpoints = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), P.naturalIntegers()); } else { notMidpoints = P.pairs(P.bigDecimals(), ((RandomProvider) P).naturalIntegersGeometric(20)); } notMidpoints = filter( p -> { assert p.a != null; assert p.b != null; if (p.a.precision() <= 1) return false; if (p.b != p.a.precision() - 1) return false; return !p.a.abs().unscaledValue().mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(5)); }, notMidpoints ); for (Pair<BigDecimal, Integer> p : take(LIMIT, notMidpoints)) { assert p.a != null; assert p.b != null; Rational r = of(p.a); BigDecimal down = r.bigDecimalValue(p.b, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValue(p.b, RoundingMode.UP); BigDecimal halfEven = r.bigDecimalValue(p.b); boolean closerToDown = lt(subtract(r, of(down)).abs(), subtract(r, of(up)).abs()); assertEquals(p.toString(), halfEven, closerToDown ? down : up); } Iterable<BigDecimal> midpoints = filter( x -> x.precision() > 1, map( x -> new BigDecimal( x.unscaledValue().multiply(BigInteger.TEN).add(BigInteger.valueOf(5)), x.scale() ), P.bigDecimals() ) ); for (BigDecimal bd : take(LIMIT, midpoints)) { Rational r = of(bd); int precision = bd.precision() - 1; BigDecimal halfEven = r.bigDecimalValue(precision); assertTrue(bd.toString(), bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0)); } Iterable<Pair<Rational, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.negativeIntegers()); } else { psFail = P.pairs(P.rationals(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<Rational, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { p.a.bigDecimalValue(p.b); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } } private static void propertiesBigDecimalValueExact() { initialize(); System.out.println("testing bigDecimalValueExact()..."); Iterable<Rational> rs = filter(Rational::hasTerminatingDecimalExpansion, P.rationals()); for (Rational r : take(LIMIT, rs)) { BigDecimal bd = r.bigDecimalValueExact(); assertEquals(r.toString(), bd, r.bigDecimalValue(0, RoundingMode.UNNECESSARY)); assertTrue(r.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == r.signum()); assertEquals(r.toString(), of(bd), r); } Iterable<Pair<Rational, Integer>> psFail; if (P instanceof ExhaustiveProvider) { psFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.negativeIntegers()); } else { psFail = P.pairs(P.rationals(), ((RandomProvider) P).negativeIntegersGeometric(20)); } for (Pair<Rational, Integer> p : take(LIMIT, psFail)) { assert p.a != null; assert p.b != null; try { p.a.bigDecimalValue(p.b); fail(p.toString()); } catch (IllegalArgumentException ignored) {} } Iterable<Rational> rsFail = filter(r -> !r.hasTerminatingDecimalExpansion(), P.rationals()); for (Rational r : take(LIMIT, rsFail)) { try { r.bigDecimalValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesBinaryExponent() { initialize(); System.out.println("testing binaryExponent() properties..."); for (Rational r : take(LIMIT, P.positiveRationals())) { int exponent = r.binaryExponent(); Rational power = ONE.shiftLeft(exponent); assertTrue(r.toString(), power.compareTo(r) <= 0); assertTrue(r.toString(), r.compareTo(power.shiftLeft(1)) < 0); } for (Rational r : take(LIMIT, P.rationals(Interval.lessThanOrEqualTo(ZERO)))) { try { r.binaryExponent(); fail(r.toString()); } catch (IllegalArgumentException ignored) {} } } private static boolean floatEquidistant(@NotNull Rational r) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); if (below == above || Float.isInfinite(below) || Float.isInfinite(above)) return false; Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); return belowDistance.equals(aboveDistance); } private static void propertiesFloatValue_RoundingMode() { initialize(); System.out.println("testing floatValue(RoundingMode) properties..."); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> p.b != RoundingMode.UNNECESSARY || p.a.equals(ofExact(p.a.floatValue(RoundingMode.FLOOR))), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; float rounded = p.a.floatValue(p.b); assertTrue(p.toString(), !Float.isNaN(rounded)); assertTrue(p.toString(), rounded == 0.0 || Math.signum(rounded) == p.a.signum()); } Iterable<Rational> rs = map( Rational::ofExact, filter(f -> !Float.isNaN(f) && Float.isFinite(f) && !f.equals(-0.0f), P.floats()) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.UNNECESSARY); assertEquals(r.toString(), r, ofExact(rounded)); assertTrue(r.toString(), Float.isFinite(rounded)); assertTrue(r.toString(), !new Float(rounded).equals(-0.0f)); } rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.FLOOR); float successor = FloatUtils.successor(rounded); assertTrue(r.toString(), le(ofExact(rounded), r)); assertTrue(r.toString(), gt(ofExact(successor), r)); assertTrue(r.toString(), rounded < 0 || Float.isFinite(rounded)); assertTrue(r.toString(), !new Float(rounded).equals(-0.0f)); } rs = filter( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.CEILING); float predecessor = FloatUtils.predecessor(rounded); assertTrue(r.toString(), ge(ofExact(rounded), r)); assertTrue(r.toString(), lt(ofExact(predecessor), r)); assertTrue(r.toString(), rounded > 0 || Float.isFinite(rounded)); } rs = P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.DOWN); assertTrue(r.toString(), le(ofExact(rounded).abs(), r.abs())); assertTrue(r.toString(), Float.isFinite(rounded)); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.DOWN); float successor = FloatUtils.successor(rounded); float predecessor = FloatUtils.predecessor(rounded); float down = r.signum() == -1 ? successor : predecessor; assertTrue(r.toString(), lt(ofExact(down).abs(), r.abs())); } rs = filter( r -> !r.abs().equals(LARGEST_FLOAT), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { assertTrue(r.toString(), !new Float(r.floatValue(RoundingMode.UP)).equals(-0.0f)); } rs = filter(r -> !r.equals(SMALLEST_FLOAT), P.rationals(Interval.of(ZERO, SMALLEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.FLOOR), 0.0f); aeq(r.toString(), r.floatValue(RoundingMode.DOWN), 0.0f); float rounded = r.floatValue(RoundingMode.UP); float successor = FloatUtils.successor(rounded); float predecessor = FloatUtils.predecessor(rounded); float up = r.signum() == -1 ? predecessor : successor; assertTrue(r.toString(), gt(ofExact(up).abs(), r.abs())); } rs = filter( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())) ); for (Rational r : take(LIMIT, rs)) { float floor = r.floatValue(RoundingMode.FLOOR); aeq(r.toString(), floor, Float.NEGATIVE_INFINITY); float up = r.floatValue(RoundingMode.UP); aeq(r.toString(), up, Float.NEGATIVE_INFINITY); float halfUp = r.floatValue(RoundingMode.HALF_UP); aeq(r.toString(), halfUp, Float.NEGATIVE_INFINITY); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); aeq(r.toString(), halfEven, Float.NEGATIVE_INFINITY); } rs = P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT)); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.FLOOR), Float.MAX_VALUE); aeq(r.toString(), r.floatValue(RoundingMode.DOWN), Float.MAX_VALUE); aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), Float.MAX_VALUE); } rs = filter( r -> r != ZERO && !r.equals(SMALLEST_FLOAT.negate()), P.rationals(Interval.of(SMALLEST_FLOAT.negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.CEILING), -0.0f); aeq(r.toString(), r.floatValue(RoundingMode.DOWN), -0.0f); } rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { float ceiling = r.floatValue(RoundingMode.CEILING); aeq(r.toString(), ceiling, Float.POSITIVE_INFINITY); float up = r.floatValue(RoundingMode.UP); aeq(r.toString(), up, Float.POSITIVE_INFINITY); float halfUp = r.floatValue(RoundingMode.HALF_UP); aeq(r.toString(), halfUp, Float.POSITIVE_INFINITY); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); aeq(r.toString(), halfEven, Float.POSITIVE_INFINITY); } rs = P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.CEILING), -Float.MAX_VALUE); aeq(r.toString(), r.floatValue(RoundingMode.DOWN), -Float.MAX_VALUE); aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), -Float.MAX_VALUE); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f); Rational hi = ofExact(FloatUtils.successor(f)); assert lo != null; assert hi != null; return add(lo, hi).shiftRight(1); }, filter(f -> !f.equals(-0.0f) && f != Float.MAX_VALUE, P.ordinaryFloats()) ); for (Rational r : take(LIMIT, midpoints)) { float down = r.floatValue(RoundingMode.DOWN); float up = r.floatValue(RoundingMode.UP); aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), down); aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), up); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); assertTrue(r.toString(), ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == halfEven); } Iterable<Rational> notMidpoints = filter( r -> ge(r, LARGEST_FLOAT.negate()) && le(r, LARGEST_FLOAT) && !floatEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); float closest = lt(belowDistance, aboveDistance) ? below : above; aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), closest); aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), closest); aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), closest); } rs = P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), 0.0f); aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), 0.0f); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), -0.0f); aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), -0.0f); } rs = filter( r -> !r.equals(SMALLEST_FLOAT.shiftRight(1)), P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), 0.0f); } rs = filter( r -> r != ZERO && !r.equals(SMALLEST_FLOAT.shiftRight(1).negate()), P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), -0.0f); } for (Rational r : take(LIMIT, P.rationals())) { float floor = r.floatValue(RoundingMode.FLOOR); assertFalse(r.toString(), Float.valueOf(floor).equals(-0.0f)); assertFalse(r.toString(), floor == Float.POSITIVE_INFINITY); float ceiling = r.floatValue(RoundingMode.CEILING); assertFalse(r.toString(), ceiling == Float.NEGATIVE_INFINITY); float down = r.floatValue(RoundingMode.DOWN); assertFalse(r.toString(), down == Float.NEGATIVE_INFINITY); assertFalse(r.toString(), down == Float.POSITIVE_INFINITY); float up = r.floatValue(RoundingMode.UP); assertFalse(r.toString(), Float.valueOf(up).equals(-0.0f)); float halfDown = r.floatValue(RoundingMode.HALF_DOWN); assertFalse(r.toString(), halfDown == Float.NEGATIVE_INFINITY); assertFalse(r.toString(), halfDown == Float.POSITIVE_INFINITY); } Iterable<Rational> rsFail = filter( r -> !ofExact(r.floatValue(RoundingMode.FLOOR)).equals(r), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rsFail)) { try { r.floatValue(RoundingMode.UNNECESSARY); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesFloatValue() { initialize(); System.out.println("testing floatValue() properties..."); for (Rational r : take(LIMIT, P.rationals())) { float rounded = r.floatValue(); aeq(r.toString(), rounded, r.floatValue(RoundingMode.HALF_EVEN)); assertTrue(r.toString(), !Float.isNaN(rounded)); assertTrue(r.toString(), rounded == 0.0 || Math.signum(rounded) == r.signum()); } Iterable<Rational> rs = filter( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(); aeq(r.toString(), rounded, Float.NEGATIVE_INFINITY); } rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(); aeq(r.toString(), rounded, Float.POSITIVE_INFINITY); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f); Rational hi = ofExact(FloatUtils.successor(f)); assert lo != null; assert hi != null; return add(lo, hi).shiftRight(1); }, filter(f -> !f.equals(-0.0f) && f != Float.MAX_VALUE, P.ordinaryFloats()) ); for (Rational r : take(LIMIT, midpoints)) { float down = r.floatValue(RoundingMode.DOWN); float up = r.floatValue(RoundingMode.UP); float rounded = r.floatValue(); assertTrue(r.toString(), ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == rounded); } Iterable<Rational> notMidpoints = filter( r -> ge(r, LARGEST_FLOAT.negate()) && le(r, LARGEST_FLOAT) && !floatEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); float closest = lt(belowDistance, aboveDistance) ? below : above; aeq(r.toString(), r.floatValue(), closest); } rs = P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(), 0.0f); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.floatValue(), -0.0f); } } private static void propertiesFloatValueExact() { initialize(); System.out.println("testing floatValueExact() properties..."); Iterable<Rational> rs = filter(r -> r.equals(ofExact(r.floatValue(RoundingMode.FLOOR))), P.rationals()); for (Rational r : take(LIMIT, rs)) { float f = r.floatValueExact(); assertTrue(r.toString(), !Float.isNaN(f)); assertTrue(r.toString(), f == 0.0 || Math.signum(f) == r.signum()); } rs = map( Rational::ofExact, filter(f -> !Float.isNaN(f) && Float.isFinite(f) && !f.equals(-0.0f), P.floats()) ); for (Rational r : take(LIMIT, rs)) { float f = r.floatValueExact(); assertEquals(r.toString(), r, ofExact(f)); assertTrue(r.toString(), Float.isFinite(f)); assertTrue(r.toString(), !new Float(f).equals(-0.0f)); } Iterable<Rational> rsFail = filter( r -> !ofExact(r.floatValue(RoundingMode.FLOOR)).equals(r), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rsFail)) { try { r.floatValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static boolean doubleEquidistant(@NotNull Rational r) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); if (below == above || Double.isInfinite(below) || Double.isInfinite(above)) return false; Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); return belowDistance.equals(aboveDistance); } private static void propertiesDoubleValue_RoundingMode() { initialize(); System.out.println("testing doubleValue(RoundingMode) properties..."); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> p.b != RoundingMode.UNNECESSARY || p.a.equals(ofExact(p.a.doubleValue(RoundingMode.FLOOR))), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; double rounded = p.a.doubleValue(p.b); assertTrue(p.toString(), !Double.isNaN(rounded)); assertTrue(p.toString(), rounded == 0.0 || Math.signum(rounded) == p.a.signum()); } Iterable<Rational> rs = map( Rational::ofExact, filter(f -> !Double.isNaN(f) && Double.isFinite(f) && !f.equals(-0.0f), P.doubles()) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.UNNECESSARY); assertEquals(r.toString(), r, ofExact(rounded)); assertTrue(r.toString(), Double.isFinite(rounded)); assertTrue(r.toString(), !new Double(rounded).equals(-0.0f)); } rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.FLOOR); double successor = FloatUtils.successor(rounded); assertTrue(r.toString(), le(ofExact(rounded), r)); assertTrue(r.toString(), gt(ofExact(successor), r)); assertTrue(r.toString(), rounded < 0 || Double.isFinite(rounded)); assertTrue(r.toString(), !new Double(rounded).equals(-0.0f)); } rs = filter( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.CEILING); double predecessor = FloatUtils.predecessor(rounded); assertTrue(r.toString(), ge(ofExact(rounded), r)); assertTrue(r.toString(), lt(ofExact(predecessor), r)); assertTrue(r.toString(), rounded > 0 || Double.isFinite(rounded)); } rs = P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.DOWN); assertTrue(r.toString(), le(ofExact(rounded).abs(), r.abs())); assertTrue(r.toString(), Double.isFinite(rounded)); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.DOWN); double successor = FloatUtils.successor(rounded); double predecessor = FloatUtils.predecessor(rounded); double down = r.signum() == -1 ? successor : predecessor; assertTrue(r.toString(), lt(ofExact(down).abs(), r.abs())); } rs = filter( r -> !r.abs().equals(LARGEST_DOUBLE), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { assertTrue(r.toString(), !new Double(r.doubleValue(RoundingMode.UP)).equals(-0.0f)); } rs = filter(r -> !r.equals(SMALLEST_DOUBLE), P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.FLOOR), 0.0f); aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), 0.0f); double rounded = r.doubleValue(RoundingMode.UP); double successor = FloatUtils.successor(rounded); double predecessor = FloatUtils.predecessor(rounded); double up = r.signum() == -1 ? predecessor : successor; assertTrue(r.toString(), gt(ofExact(up).abs(), r.abs())); } rs = filter( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())) ); for (Rational r : take(LIMIT, rs)) { double floor = r.doubleValue(RoundingMode.FLOOR); aeq(r.toString(), floor, Double.NEGATIVE_INFINITY); double up = r.doubleValue(RoundingMode.UP); aeq(r.toString(), up, Double.NEGATIVE_INFINITY); double halfUp = r.doubleValue(RoundingMode.HALF_UP); aeq(r.toString(), halfUp, Double.NEGATIVE_INFINITY); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); aeq(r.toString(), halfEven, Double.NEGATIVE_INFINITY); } rs = P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.FLOOR), Double.MAX_VALUE); aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), Double.MAX_VALUE); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), Double.MAX_VALUE); } rs = filter( r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.negate()), P.rationals(Interval.of(SMALLEST_DOUBLE.negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.CEILING), -0.0f); aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), -0.0f); } rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { double ceiling = r.doubleValue(RoundingMode.CEILING); aeq(r.toString(), ceiling, Double.POSITIVE_INFINITY); double up = r.doubleValue(RoundingMode.UP); aeq(r.toString(), up, Double.POSITIVE_INFINITY); double halfUp = r.doubleValue(RoundingMode.HALF_UP); aeq(r.toString(), halfUp, Double.POSITIVE_INFINITY); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); aeq(r.toString(), halfEven, Double.POSITIVE_INFINITY); } rs = P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.CEILING), -Double.MAX_VALUE); aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), -Double.MAX_VALUE); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), -Double.MAX_VALUE); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f); Rational hi = ofExact(FloatUtils.successor(f)); assert lo != null; assert hi != null; return add(lo, hi).shiftRight(1); }, filter(f -> !f.equals(-0.0f) && f != Double.MAX_VALUE, P.ordinaryDoubles()) ); for (Rational r : take(LIMIT, midpoints)) { double down = r.doubleValue(RoundingMode.DOWN); double up = r.doubleValue(RoundingMode.UP); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), down); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), up); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); assertTrue(r.toString(), ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == halfEven); } Iterable<Rational> notMidpoints = filter( r -> ge(r, LARGEST_DOUBLE.negate()) && le(r, LARGEST_DOUBLE) && !doubleEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); double closest = lt(belowDistance, aboveDistance) ? below : above; aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), closest); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), closest); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), closest); } rs = P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), 0.0f); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), 0.0f); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), -0.0f); aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), -0.0f); } rs = filter( r -> !r.equals(SMALLEST_DOUBLE.shiftRight(1)), P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), 0.0f); } rs = filter( r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.shiftRight(1).negate()), P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), -0.0f); } for (Rational r : take(LIMIT, P.rationals())) { double floor = r.doubleValue(RoundingMode.FLOOR); assertFalse(r.toString(), Double.valueOf(floor).equals(-0.0f)); assertFalse(r.toString(), floor == Double.POSITIVE_INFINITY); double ceiling = r.doubleValue(RoundingMode.CEILING); assertFalse(r.toString(), ceiling == Double.NEGATIVE_INFINITY); double down = r.doubleValue(RoundingMode.DOWN); assertFalse(r.toString(), down == Double.NEGATIVE_INFINITY); assertFalse(r.toString(), down == Double.POSITIVE_INFINITY); double up = r.doubleValue(RoundingMode.UP); assertFalse(r.toString(), Double.valueOf(up).equals(-0.0f)); double halfDown = r.doubleValue(RoundingMode.HALF_DOWN); assertFalse(r.toString(), halfDown == Double.NEGATIVE_INFINITY); assertFalse(r.toString(), halfDown == Double.POSITIVE_INFINITY); } Iterable<Rational> rsFail = filter( r -> !ofExact(r.doubleValue(RoundingMode.FLOOR)).equals(r), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rsFail)) { try { r.doubleValue(RoundingMode.UNNECESSARY); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesDoubleValue() { initialize(); System.out.println("testing doubleValue() properties..."); for (Rational r : take(LIMIT, P.rationals())) { double rounded = r.doubleValue(); aeq(r.toString(), rounded, r.doubleValue(RoundingMode.HALF_EVEN)); assertTrue(r.toString(), !Double.isNaN(rounded)); assertTrue(r.toString(), rounded == 0.0 || Math.signum(rounded) == r.signum()); } Iterable<Rational> rs = filter( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(); aeq(r.toString(), rounded, Double.NEGATIVE_INFINITY); } rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(); aeq(r.toString(), rounded, Double.POSITIVE_INFINITY); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f); Rational hi = ofExact(FloatUtils.successor(f)); assert lo != null; assert hi != null; return add(lo, hi).shiftRight(1); }, filter(f -> !f.equals(-0.0f) && f != Double.MAX_VALUE, P.ordinaryDoubles()) ); for (Rational r : take(LIMIT, midpoints)) { double down = r.doubleValue(RoundingMode.DOWN); double up = r.doubleValue(RoundingMode.UP); double rounded = r.doubleValue(); assertTrue(r.toString(), ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == rounded); } Iterable<Rational> notMidpoints = filter( r -> ge(r, LARGEST_DOUBLE.negate()) && le(r, LARGEST_DOUBLE) && !doubleEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); Rational belowDistance = subtract(r, ofExact(below)); Rational aboveDistance = subtract(ofExact(above), r); double closest = lt(belowDistance, aboveDistance) ? below : above; aeq(r.toString(), r.doubleValue(), closest); } rs = P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(), 0.0f); } rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeq(r.toString(), r.doubleValue(), -0.0f); } } private static void propertiesDoubleValueExact() { initialize(); System.out.println("testing doubleValueExact() properties..."); Iterable<Rational> rs = filter(r -> r.equals(ofExact(r.doubleValue(RoundingMode.FLOOR))), P.rationals()); for (Rational r : take(LIMIT, rs)) { double f = r.doubleValueExact(); assertTrue(r.toString(), !Double.isNaN(f)); assertTrue(r.toString(), f == 0.0 || Math.signum(f) == r.signum()); } rs = map( Rational::ofExact, filter(f -> !Double.isNaN(f) && Double.isFinite(f) && !f.equals(-0.0f), P.doubles()) ); for (Rational r : take(LIMIT, rs)) { double f = r.doubleValueExact(); assertEquals(r.toString(), r, ofExact(f)); assertTrue(r.toString(), Double.isFinite(f)); assertTrue(r.toString(), !new Double(f).equals(-0.0f)); } Iterable<Rational> rsFail = filter( r -> !ofExact(r.doubleValue(RoundingMode.FLOOR)).equals(r), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rsFail)) { try { r.doubleValueExact(); fail(r.toString()); } catch (ArithmeticException ignored) {} } } private static void propertiesNegate() { initialize(); System.out.println("testing negate() properties..."); for (Rational r : take(LIMIT, P.rationals())) { Rational negativeR = r.negate(); validate(negativeR); assertEquals(r.toString(), r, negativeR.negate()); assertTrue(add(r, negativeR) == ZERO); } Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals()); for (Rational r : take(LIMIT, rs)) { Rational negativeR = r.negate(); assertTrue(r.toString(), !r.equals(negativeR)); } } private static void propertiesInvert() { initialize(); System.out.println("testing invert() properties..."); Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals()); for (Rational r : take(LIMIT, rs)) { Rational inverseR = r.invert(); validate(inverseR); assertEquals(r.toString(), r, inverseR.invert()); assertTrue(multiply(r, inverseR) == ONE); assertTrue(inverseR != ZERO); } rs = filter(r -> r != ZERO && r.abs() != ONE, P.rationals()); for (Rational r : take(LIMIT, rs)) { Rational inverseR = r.invert(); assertTrue(r.toString(), !r.equals(inverseR)); } } private static void propertiesAbs() { initialize(); System.out.println("testing abs() properties..."); for (Rational r : take(LIMIT, P.rationals())) { Rational absR = r.abs(); validate(absR); assertEquals(r.toString(), absR, absR.abs()); assertTrue(r.toString(), ge(absR, ZERO)); } } private static void propertiesSignum() { initialize(); System.out.println("testing signum() properties..."); for (Rational r : take(LIMIT, P.rationals())) { int signumR = r.signum(); assertEquals(r.toString(), signumR, Ordering.compare(r, ZERO).toInt()); assertTrue(r.toString(), signumR == -1 || signumR == 0 || signumR == 1); } } private static void propertiesAdd() { initialize(); System.out.println("testing add(Rational, Rational) properties..."); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; Rational sum = add(p.a, p.b); validate(sum); assertEquals(p.toString(), sum, add(p.b, p.a)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), add(ZERO, r), r); assertEquals(r.toString(), add(r, ZERO), r); assertTrue(r.toString(), add(r, r.negate()) == ZERO); } for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) { assert t.a != null; assert t.b != null; assert t.c != null; Rational sum1 = add(add(t.a, t.b), t.c); Rational sum2 = add(t.a, add(t.b, t.c)); assertEquals(t.toString(), sum1, sum2); } } private static void propertiesSubtract() { initialize(); System.out.println("testing subtract(Rational, Rational) properties..."); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; Rational difference = subtract(p.a, p.b); validate(difference); assertEquals(p.toString(), difference, subtract(p.b, p.a).negate()); assertEquals(p.toString(), p.a, add(difference, p.b)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), subtract(ZERO, r), r.negate()); assertEquals(r.toString(), subtract(r, ZERO), r); assertTrue(r.toString(), subtract(r, r) == ZERO); } } private static void propertiesMultiply_Rational_Rational() { initialize(); System.out.println("testing multiply(Rational, Rational) properties..."); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; Rational product = multiply(p.a, p.b); validate(product); assertEquals(p.toString(), product, multiply(p.b, p.a)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), multiply(ONE, r), r); assertEquals(r.toString(), multiply(r, ONE), r); assertTrue(r.toString(), multiply(ZERO, r) == ZERO); assertTrue(r.toString(), multiply(r, ZERO) == ZERO); } Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals()); for (Rational r : take(LIMIT, rs)) { assertTrue(r.toString(), multiply(r, r.invert()) == ONE); } for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) { assert t.a != null; assert t.b != null; assert t.c != null; Rational product1 = multiply(multiply(t.a, t.b), t.c); Rational product2 = multiply(t.a, multiply(t.b, t.c)); assertEquals(t.toString(), product1, product2); } for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = multiply(add(t.a, t.b), t.c); Rational expression2 = add(multiply(t.a, t.c), multiply(t.b, t.c)); assertEquals(t.toString(), expression1, expression2); } } private static void propertiesMultiply_BigInteger() { initialize(); System.out.println("testing multiply(BigInteger) properties..."); Iterable<Pair<Rational, BigInteger>> ps = P.pairs(P.rationals(), P.bigIntegers()); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational product = p.a.multiply(p.b); validate(product); assertEquals(p.toString(), product, multiply(p.a, of(p.b))); assertEquals(p.toString(), product, multiply(of(p.b), p.a)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), ONE.multiply(i), of(i)); assertTrue(i.toString(), ZERO.multiply(i) == ZERO); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.multiply(BigInteger.ONE), r); assertTrue(r.toString(), r.multiply(BigInteger.ZERO) == ZERO); } Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()); for (BigInteger i : take(LIMIT, bis)) { assertTrue(i.toString(), of(i).invert().multiply(i) == ONE); } Iterable<Rational> rs = P.rationals(); for (Triple<Rational, Rational, BigInteger> t : take(LIMIT, P.triples(rs, rs, P.bigIntegers()))) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = add(t.a, t.b).multiply(t.c); Rational expression2 = add(t.a.multiply(t.c), t.b.multiply(t.c)); assertEquals(t.toString(), expression1, expression2); } } private static void propertiesMultiply_int() { initialize(); System.out.println("testing multiply(int) properties..."); for (Pair<Rational, Integer> p :take(LIMIT, P.pairs(P.rationals(), P.integers()))) { assert p.a != null; assert p.b != null; Rational product = p.a.multiply(p.b); validate(product); assertEquals(p.toString(), product, multiply(p.a, of(p.b))); assertEquals(p.toString(), product, multiply(of(p.b), p.a)); } for (int i : take(LIMIT, P.integers())) { assertEquals(Integer.toString(i), ONE.multiply(i), of(i)); assertTrue(Integer.toString(i), ZERO.multiply(i) == ZERO); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.multiply(1), r); assertTrue(r.toString(), r.multiply(0) == ZERO); } Iterable<Integer> is = filter(i -> i != 0, P.integers()); for (int i : take(LIMIT, is)) { assertTrue(Integer.toString(i), of(i).invert().multiply(i) == ONE); } Iterable<Rational> rs = P.rationals(); for (Triple<Rational, Rational, Integer> t : take(LIMIT, P.triples(rs, rs, P.integers()))) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = add(t.a, t.b).multiply(t.c); Rational expression2 = add(t.a.multiply(t.c), t.b.multiply(t.c)); assertEquals(t.toString(), expression1, expression2); } } private static void propertiesDivide_Rational_Rational() { initialize(); System.out.println("testing divide(Rational, Rational) properties..."); Iterable<Pair<Rational, Rational>> ps = filter(p -> p.b != ZERO, P.pairs(P.rationals())); for (Pair<Rational, Rational> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational quotient = divide(p.a, p.b); validate(quotient); assertEquals(p.toString(), p.a, multiply(quotient, p.b)); } ps = filter(p -> p.a != ZERO && p.b != ZERO, P.pairs(P.rationals())); for (Pair<Rational, Rational> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), divide(p.a, p.b), divide(p.b, p.a).invert()); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), divide(r, ONE), r); } Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), divide(ONE, r), r.invert()); assertTrue(r.toString(), divide(r, r) == ONE); } } private static void propertiesDivide_BigInteger() { initialize(); System.out.println("testing divide(BigInteger) properties..."); Iterable<Pair<Rational, BigInteger>> ps = P.pairs( P.rationals(), filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational quotient = p.a.divide(p.b); validate(quotient); assertEquals(p.toString(), p.a, quotient.multiply(p.b)); } ps = P.pairs( (Iterable<Rational>) filter(r -> r != ZERO, P.rationals()), filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), p.a.divide(p.b), divide(of(p.b), p.a).invert()); } Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()); for (BigInteger i : take(LIMIT, bis)) { assertEquals(i.toString(), ONE.divide(i), of(i).invert()); assertEquals(i.toString(), of(i).divide(i), ONE); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.divide(BigInteger.ONE), r); } } private static void propertiesDivide_int() { initialize(); System.out.println("testing divide(int) properties..."); Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), filter(i -> i != 0, P.integers())); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational quotient = p.a.divide(p.b); validate(quotient); assertEquals(p.toString(), p.a, quotient.multiply(p.b)); } ps = P.pairs((Iterable<Rational>) filter(r -> r != ZERO, P.rationals()), filter(i -> i != 0, P.integers())); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), p.a.divide(p.b), divide(of(p.b), p.a).invert()); } Iterable<Integer> is = filter(i -> i != 0, P.integers()); for (int i : take(LIMIT, is)) { assertEquals(Integer.toString(i), ONE.divide(i), of(i).invert()); assertEquals(Integer.toString(i), of(i).divide(i), ONE); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.divide(1), r); } } private static void propertiesSum() { initialize(); System.out.println("testing sum(Iterable<Rational>) properties..."); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { validate(sum(rs)); } Iterable<Pair<List<Rational>, List<Rational>>> ps = filter( q -> { assert q.a != null; assert q.b != null; return !q.a.equals(q.b); }, P.dependentPairsLogarithmic(P.lists(P.rationals()), Combinatorics::permutationsIncreasing) ); for (Pair<List<Rational>, List<Rational>> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), sum(p.a), sum(p.b)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), sum(Arrays.asList(r)), r); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), sum(Arrays.asList(p.a, p.b)), add(p.a, p.b)); } Iterable<List<Rational>> failRss = map(p -> { assert p.a != null; assert p.b != null; return toList(insert(p.a, p.b, null)); }, (Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic( P.lists(P.rationals()), rs -> range(0, rs.size()) )); for (List<Rational> rs : take(LIMIT, failRss)) { try { sum(rs); fail(rs.toString()); } catch (IllegalArgumentException ignored) {} } } private static void propertiesProduct() { initialize(); System.out.println("testing product(Iterable<Rational>) properties..."); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { validate(product(rs)); } Iterable<Pair<List<Rational>, List<Rational>>> ps = filter( q -> { assert q.a != null; assert q.b != null; return !q.a.equals(q.b); }, P.dependentPairsLogarithmic(P.lists(P.rationals()), Combinatorics::permutationsIncreasing) ); for (Pair<List<Rational>, List<Rational>> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), product(p.a), product(p.b)); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), product(Arrays.asList(r)), r); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; assertEquals(p.toString(), product(Arrays.asList(p.a, p.b)), multiply(p.a, p.b)); } Iterable<List<Rational>> failRss = map(p -> { assert p.a != null; assert p.b != null; return toList(insert(p.a, p.b, null)); }, (Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic( P.lists(P.rationals()), rs -> range(0, rs.size()) )); for (List<Rational> rs : take(LIMIT, failRss)) { try { product(rs); fail(rs.toString()); } catch (IllegalArgumentException ignored) {} } } private static void propertiesDelta() { initialize(); System.out.println("testing delta(Iterable<Rational>) properties..."); for (List<Rational> rs : take(LIMIT, filter(ss -> !ss.isEmpty(), P.lists(P.rationals())))) { Iterable<Rational> deltas = delta(rs); aeq(rs.toString(), length(deltas), length(rs) - 1); Iterable<Rational> reversed = reverse(map(Rational::negate, delta(reverse(rs)))); aeq(rs.toString(), deltas, reversed); try { deltas.iterator().remove(); } catch (UnsupportedOperationException ignored) {} } for (Rational r : take(LIMIT, P.rationals())) { assertTrue(r.toString(), isEmpty(delta(Arrays.asList(r)))); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; aeq(p.toString(), delta(Arrays.asList(p.a, p.b)), Arrays.asList(subtract(p.b, p.a))); } Iterable<List<Rational>> failRss = map(p -> { assert p.a != null; assert p.b != null; return toList(insert(p.a, p.b, null)); }, (Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic( P.lists(P.rationals()), rs -> range(0, rs.size()) )); for (List<Rational> rs : take(LIMIT, failRss)) { try { toList(delta(rs)); fail(rs.toString()); } catch (IllegalArgumentException | NullPointerException ignored) {} } } private static void propertiesHarmonicNumber() { initialize(); System.out.println("testing harmonicNumber(int) properties..."); Iterable<Integer> is; if (P instanceof ExhaustiveProvider) { is = P.positiveIntegers(); } else { is = ((RandomProvider) P).positiveIntegersGeometric(100); } for (int i : take(SMALL_LIMIT, is)) { Rational h = harmonicNumber(i); validate(h); assertTrue(Integer.toString(i), ge(h, ONE)); } is = map(i -> i + 1, is); for (int i : take(SMALL_LIMIT, is)) { Rational h = harmonicNumber(i); assertTrue(Integer.toString(i), gt(h, harmonicNumber(i - 1))); assertFalse(Integer.toString(i), h.getDenominator().equals(BigInteger.ONE)); } } private static void propertiesPow() { initialize(); System.out.println("testing pow(int) properties..."); Iterable<Integer> exps; if (P instanceof QBarExhaustiveProvider) { exps = P.integers(); } else { exps = ((RandomProvider) P).integersGeometric(20); } Iterable<Pair<Rational, Integer>> ps = filter(p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), exps)); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational r = p.a.pow(p.b); validate(r); } ps = P.pairs(filter(r -> r != ZERO, P.rationals()), exps); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational r = p.a.pow(p.b); assertEquals(p.toString(), r, p.a.pow(-p.b).invert()); assertEquals(p.toString(), r, p.a.invert().pow(-p.b)); } Iterable<Integer> pexps; if (P instanceof QBarExhaustiveProvider) { pexps = P.positiveIntegers(); } else { pexps = ((RandomProvider) P).positiveIntegersGeometric(20); } for (int i : take(LIMIT, pexps)) { assertTrue(Integer.toString(i), ZERO.pow(i) == ZERO); } for (Rational r : take(LIMIT, P.rationals())) { assertTrue(r.toString(), r.pow(0) == ONE); assertEquals(r.toString(), r.pow(1), r); assertEquals(r.toString(), r.pow(2), multiply(r, r)); } Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals()); for (Rational r : take(LIMIT, rs)) { assertEquals(r.toString(), r.pow(-1), r.invert()); } Iterable<Triple<Rational, Integer, Integer>> ts1 = filter( p -> p.b >= 0 && p.c >= 0 || p.a != ZERO, P.triples(P.rationals(), exps, exps) ); for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = multiply(t.a.pow(t.b), t.a.pow(t.c)); Rational expression2 = t.a.pow(t.b + t.c); assertEquals(t.toString(), expression1, expression2); } ts1 = filter( t -> t.a != ZERO || t.c == 0 && t.b >= 0, P.triples(P.rationals(), exps, exps) ); for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = divide(t.a.pow(t.b), t.a.pow(t.c)); Rational expression2 = t.a.pow(t.b - t.c); assertEquals(t.toString(), expression1, expression2); } ts1 = filter( t -> t.a != ZERO || t.b >= 0 && t.c >= 0, P.triples(P.rationals(), exps, exps) ); for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression5 = t.a.pow(t.b).pow(t.c); Rational expression6 = t.a.pow(t.b * t.c); assertEquals(t.toString(), expression5, expression6); } Iterable<Triple<Rational, Rational, Integer>> ts2 = filter( t -> t.a != ZERO && t.b != ZERO || t.c >= 0, P.triples(P.rationals(), P.rationals(), exps) ); for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = multiply(t.a, t.b).pow(t.c); Rational expression2 = multiply(t.a.pow(t.c), t.b.pow(t.c)); assertEquals(t.toString(), expression1, expression2); } ts2 = filter( t -> t.a != ZERO || t.c >= 0, P.triples(P.rationals(), filter(r -> r != ZERO, P.rationals()), exps) ); for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational expression1 = divide(t.a, t.b).pow(t.c); Rational expression2 = divide(t.a.pow(t.c), t.b.pow(t.c)); assertEquals(t.toString(), expression1, expression2); } } private static void propertiesFloor() { initialize(); System.out.println("testing floor() properties..."); for (Rational r : take(LIMIT, P.rationals())) { BigInteger floor = r.floor(); assertTrue(r.toString(), le(of(floor), r)); assertTrue(r.toString(), le(subtract(r, of(floor)), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), of(i).floor(), i); } } private static void propertiesCeiling() { initialize(); System.out.println("testing ceiling() properties..."); for (Rational r : take(LIMIT, P.rationals())) { BigInteger ceiling = r.ceiling(); assertTrue(r.toString(), ge(of(ceiling), r)); assertTrue(r.toString(), le(subtract(of(ceiling), r), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), of(i).ceiling(), i); } } private static void propertiesFractionalPart() { initialize(); System.out.println("testing fractionalPart() properties..."); for (Rational r : take(LIMIT, P.rationals())) { Rational fractionalPart = r.fractionalPart(); validate(fractionalPart); assertTrue(r.toString(), ge(fractionalPart, ZERO)); assertTrue(r.toString(), lt(fractionalPart, ONE)); assertEquals(r.toString(), add(of(r.floor()), fractionalPart), r); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i.toString(), of(i).fractionalPart(), ZERO); } } private static void propertiesRoundToDenominator() { initialize(); System.out.println("testing roundToDenominator(BigInteger, RoundingMode) properties..."); Iterable<Triple<Rational, BigInteger, RoundingMode>> ts = filter( p -> { assert p.a != null; assert p.b != null; return p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO); }, P.triples(P.rationals(), P.positiveBigIntegers(), P.roundingModes()) ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; Rational rounded = t.a.roundToDenominator(t.b, t.c); validate(rounded); assertEquals(t.toString(), t.b.mod(rounded.getDenominator()), BigInteger.ZERO); assertTrue(t.toString(), rounded == ZERO || rounded.signum() == t.a.signum()); assertTrue(t.toString(), lt(subtract(t.a, rounded).abs(), of(BigInteger.ONE, t.b))); } Iterable<Pair<Rational, RoundingMode>> ps1 = filter( p -> { assert p.a != null; return p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE); }, P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps1)) { assert p.a != null; assert p.b != null; Rational rounded = p.a.roundToDenominator(BigInteger.ONE, p.b); assertEquals(p.toString(), rounded.getNumerator(), p.a.bigIntegerValue(p.b)); assertEquals(p.toString(), rounded.getDenominator(), BigInteger.ONE); } Iterable<Pair<Rational, BigInteger>> ps2 = filter( p -> { assert p.a != null; assert p.b != null; return p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO); }, P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { assert p.a != null; assert p.b != null; assertTrue(p.toString(), p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY).equals(p.a)); } ps2 = P.pairs(P.rationals(), P.positiveBigIntegers()); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { assert p.a != null; assert p.b != null; assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.FLOOR), p.a)); assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.CEILING), p.a)); assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.DOWN).abs(), p.a.abs())); assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.UP).abs(), p.a.abs())); assertTrue( p.toString(), le( subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN)).abs(), of(p.b).shiftLeft(1).invert() ) ); assertTrue( p.toString(), le( subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_UP)).abs(), of(p.b).shiftLeft(1).invert() ) ); assertTrue( p.toString(), le( subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN)).abs(), of(p.b).shiftLeft(1).invert() ) ); } ps2 = filter( p -> { assert p.a != null; assert p.b != null; return lt((Rational) p.a.abs().multiply(p.b).fractionalPart(), of(1, 2)); }, P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { assert p.a != null; assert p.b != null; assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN), p.a.roundToDenominator(p.b, RoundingMode.DOWN) ); assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_UP), p.a.roundToDenominator(p.b, RoundingMode.DOWN) ); assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN), p.a.roundToDenominator(p.b, RoundingMode.DOWN) ); } ps2 = filter( p -> { assert p.a != null; assert p.b != null; return gt((Rational) p.a.abs().multiply(p.b).fractionalPart(), of(1, 2)); }, P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { assert p.a != null; assert p.b != null; assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN), p.a.roundToDenominator(p.b, RoundingMode.UP) ); assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_UP), p.a.roundToDenominator(p.b, RoundingMode.UP) ); assertEquals( p.toString(), p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN), p.a.roundToDenominator(p.b, RoundingMode.UP) ); } Iterable<Rational> rs = filter(r -> !r.getDenominator().testBit(0), P.rationals()); for (Rational r : take(LIMIT, rs)) { BigInteger denominator = r.getDenominator().shiftRight(1); assertEquals(r.toString(), r.abs().multiply(denominator).fractionalPart(), of(1, 2)); Rational hd = r.roundToDenominator(denominator, RoundingMode.HALF_DOWN); assertEquals(r.toString(), hd, r.roundToDenominator(denominator, RoundingMode.DOWN)); Rational hu = r.roundToDenominator(denominator, RoundingMode.HALF_UP); assertEquals(r.toString(), hu, r.roundToDenominator(denominator, RoundingMode.UP)); Rational he = r.roundToDenominator(denominator, RoundingMode.HALF_EVEN); assertEquals(r.toString(), he.multiply(denominator).getNumerator().testBit(0), false); } } private static void propertiesShiftLeft() { initialize(); System.out.println("testing shiftLeft(int) properties..."); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(50); } Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), is); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational shifted = p.a.shiftLeft(p.b); validate(shifted); assertEquals(p.toString(), p.a.negate().shiftLeft(p.b), shifted.negate()); assertEquals(p.toString(), shifted, p.a.shiftRight(-p.b)); } if (P instanceof QBarExhaustiveProvider) { is = P.naturalIntegers(); } else { is = ((QBarRandomProvider) P).naturalIntegersGeometric(50); } ps = P.pairs(P.rationals(), is); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational shifted = p.a.shiftLeft(p.b); assertEquals(p.toString(), shifted, p.a.multiply(BigInteger.ONE.shiftLeft(p.b))); } } private static void propertiesShiftRight() { initialize(); System.out.println("testing shiftRight(int) properties..."); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(50); } Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), is); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational shifted = p.a.shiftRight(p.b); validate(shifted); assertEquals(p.toString(), p.a.negate().shiftRight(p.b), shifted.negate()); assertEquals(p.toString(), shifted, p.a.shiftLeft(-p.b)); } if (P instanceof QBarExhaustiveProvider) { is = P.naturalIntegers(); } else { is = ((QBarRandomProvider) P).naturalIntegersGeometric(50); } ps = P.pairs(P.rationals(), is); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; Rational shifted = p.a.shiftRight(p.b); assertEquals(p.toString(), shifted, p.a.divide(BigInteger.ONE.shiftLeft(p.b))); } } private static void propertiesEquals() { initialize(); System.out.println("testing equals(Object) properties..."); for (Rational r : take(LIMIT, P.rationals())) { //noinspection EqualsWithItself assertTrue(r.toString(), r.equals(r)); //noinspection ObjectEqualsNull assertFalse(r.toString(), r.equals(null)); } } private static void propertiesHashCode() { initialize(); System.out.println("testing hashCode() properties..."); for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.hashCode(), r.hashCode()); } } private static void propertiesCompareTo() { initialize(); System.out.println("testing compareTo(Rational) properties..."); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; int compare = p.a.compareTo(p.b); assertTrue(p.toString(), compare == -1 || compare == 0 || compare == 1); assertEquals(p.toString(), p.b.compareTo(p.a), -compare); assertEquals(p.toString(), subtract(p.a, p.b).signum(), compare); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r.toString(), r.compareTo(r), 0); } Iterable<Triple<Rational, Rational, Rational>> ts = filter( t -> { assert t.a != null; assert t.b != null; return lt(t.a, t.b) && lt(t.b, t.c); }, P.triples(P.rationals()) ); for (Triple<Rational, Rational, Rational> t : take(LIMIT, ts)) { assert t.a != null; assert t.c != null; assertEquals(t.toString(), t.a.compareTo(t.c), -1); } } private static void propertiesRead() { initialize(); System.out.println("testing read(String) properties..."); for (String s : take(LIMIT, P.strings())) { read(s); } Iterable<Character> cs; if (P instanceof QBarExhaustiveProvider) { cs = fromString(RATIONAL_CHARS); } else { cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_CHARS); } Iterable<String> ss = filter(s -> read(s).isPresent(), P.strings(cs)); for (String s : take(LIMIT, ss)) { Optional<Rational> or = read(s); validate(or.get()); } Pair<Iterable<String>, Iterable<String>> slashPartition = partition(s -> s.contains("/"), ss); assert slashPartition.a != null; assert slashPartition.b != null; for (String s : take(LIMIT, slashPartition.a)) { int slashIndex = s.indexOf('/'); String left = s.substring(0, slashIndex); String right = s.substring(slashIndex + 1); assertTrue(s, Readers.readBigInteger(left).isPresent()); assertTrue(s, Readers.readBigInteger(right).isPresent()); } for (String s : take(LIMIT, slashPartition.b)) { assertTrue(s, Readers.readBigInteger(s).isPresent()); } } private static void propertiesToString() { initialize(); System.out.println("testing toString() properties..."); for (Rational r : take(LIMIT, P.rationals())) { String s = r.toString(); assertTrue(isSubsetOf(s, RATIONAL_CHARS)); Optional<Rational> readR = read(s); assertTrue(r.toString(), readR.isPresent()); assertEquals(r.toString(), readR.get(), r); } } private static void validate(@NotNull Rational r) { assertEquals(r.toString(), r.getNumerator().gcd(r.getDenominator()), BigInteger.ONE); assertEquals(r.toString(), r.getDenominator().signum(), 1); if (r.equals(ZERO)) assertTrue(r.toString(), r == ZERO); if (r.equals(ONE)) assertTrue(r.toString(), r == ONE); } private static <T> void aeq(String message, Iterable<T> xs, Iterable<T> ys) { assertTrue(message, equal(xs, ys)); } private static void aeq(String message, int i, int j) { assertEquals(message, i, j); } private static void aeq(String message, long i, long j) { assertEquals(message, i, j); } private static void aeq(String message, float x, float y) { assertEquals(message, Float.toString(x), Float.toString(y)); } private static void aeq(String message, double x, double y) { assertEquals(message, Double.toString(x), Double.toString(y)); } private static void aeq(String message, BigDecimal x, BigDecimal y) { assertEquals(message, x.stripTrailingZeros(), y.stripTrailingZeros()); } }
package imagej.process; import ij.Prefs; import ij.process.Blitter; import ij.process.ByteProcessor; import ij.process.FloatProcessor; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import imagej.io.ImageOpener; import imagej.process.function.AbsUnaryFunction; import imagej.process.function.AddBinaryFunction; import imagej.process.function.AddNoiseUnaryFunction; import imagej.process.function.AddUnaryFunction; import imagej.process.function.AndBinaryFunction; import imagej.process.function.AndUnaryFunction; import imagej.process.function.AverageBinaryFunction; import imagej.process.function.BinaryFunction; import imagej.process.function.CopyInput2BinaryFunction; import imagej.process.function.CopyInput2InvertedBinaryFunction; import imagej.process.function.CopyInput2TransparentBinaryFunction; import imagej.process.function.CopyInput2ZeroTransparentBinaryFunction; import imagej.process.function.DifferenceBinaryFunction; import imagej.process.function.DivideBinaryFunction; import imagej.process.function.ExpUnaryFunction; import imagej.process.function.FillUnaryFunction; import imagej.process.function.GammaUnaryFunction; import imagej.process.function.InvertUnaryFunction; import imagej.process.function.LogUnaryFunction; import imagej.process.function.MaxBinaryFunction; import imagej.process.function.MaxUnaryFunction; import imagej.process.function.MinBinaryFunction; import imagej.process.function.MinUnaryFunction; import imagej.process.function.MultiplyBinaryFunction; import imagej.process.function.MultiplyUnaryFunction; import imagej.process.function.OrBinaryFunction; import imagej.process.function.OrUnaryFunction; import imagej.process.function.SqrUnaryFunction; import imagej.process.function.SqrtUnaryFunction; import imagej.process.function.SubtractBinaryFunction; import imagej.process.function.ThresholdUnaryFunction; import imagej.process.function.UnaryFunction; import imagej.process.function.XorBinaryFunction; import imagej.process.function.XorUnaryFunction; import imagej.process.operation.ApplyLutOperation; import imagej.process.operation.BinaryTransformOperation; import imagej.process.operation.BlurFilterOperation; import imagej.process.operation.Convolve3x3FilterOperation; import imagej.process.operation.FindEdgesFilterOperation; import imagej.process.operation.HistogramOperation; import imagej.process.operation.MaskedFillOperation; import imagej.process.operation.MinMaxOperation; import imagej.process.operation.TernaryAssignOperation; import imagej.process.operation.UnaryTransformOperation; import imagej.process.operation.ResetUsingMaskOperation; import imagej.process.operation.SetFloatValuesOperation; import imagej.process.operation.SetPlaneOperation; import imagej.process.operation.SetPlaneOperation.DataType; import imagej.process.operation.UnaryTransformPositionalOperation; import imagej.selection.MaskOnSelectionFunction; import imagej.selection.SelectionFunction; import java.awt.Color; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.MemoryImageSource; import loci.common.DataTools; import mpicbg.imglib.container.basictypecontainer.array.PlanarAccess; import mpicbg.imglib.cursor.LocalizableByDimCursor; import mpicbg.imglib.image.Image; import mpicbg.imglib.type.numeric.RealType; import mpicbg.imglib.type.numeric.integer.ByteType; import mpicbg.imglib.type.numeric.integer.GenericByteType; import mpicbg.imglib.type.numeric.integer.GenericShortType; import mpicbg.imglib.type.numeric.integer.IntType; import mpicbg.imglib.type.numeric.integer.LongType; import mpicbg.imglib.type.numeric.integer.ShortType; import mpicbg.imglib.type.numeric.integer.UnsignedByteType; import mpicbg.imglib.type.numeric.integer.UnsignedIntType; import mpicbg.imglib.type.numeric.integer.UnsignedShortType; import mpicbg.imglib.type.numeric.real.DoubleType; import mpicbg.imglib.type.numeric.real.FloatType; // NOTES // Image may change to Img to avoid name conflict with java.awt.Image. // TODO // 1. Add a new container that uses array-backed data of the proper primitive // type, plane by plane. // 2. Then we can return the data with getPixels by reference in that case // (and use the current cursor approach in other cases). // For create8BitImage, we can call imageData.getDisplay().get8Bit* to extract // displayable image data as bytes [was LocalizableByPlaneCursor relevant here // as well? can't remember]. // For getPlane* methods, we can use a LocalizablePlaneCursor (see // ImageJVirtualStack.extractSliceFloat for an example) to grab the data // plane-by-plane; this way the container knows the optimal way to traverse. // More TODO / NOTES // For filters we're mirroring IJ's behavior. This means no min/max/median/erode/dilate for anything but UnsignedByteType. Change this? // Make sure that resetMinAndMax() and/or findMinAndMax() are called at appropriate times. Maybe base class does this for us? // I have not yet mirrored ImageJ's signed 16 bit hacks. Will need to test Image<ShortType> and see if things work versus an ImagePlus. // Review imglib's various cursors and perhaps change which ones I'm using. // Nearly all methods below broken for ComplexType and LongType // All methods below assume x and y first two dimensions and that the Image<T> consists of XY planes // In createImagePlus we rely on image to be 5d or less. We should modify ImageJ to have a setDimensions(int[] dimension) and integrate // its use throughout the application. // Just realized the constructor that takes plane number may not make a ton of sense as implemented. We assume X & Y are the first 2 dimensions. // This ideally means that its broken into planes in the last two dimensions. This may just be a convention we use but it may break things too. // Must investigate. (as a workaround for now we are incrementing indexes from left to right) // Rename ImgLibProcessor to GenericProcessor???? // Rename TypeManager to TypeUtils // Rename Image<> to something else like Dataset<> or NumericDataset<> // Improvements to ImgLib // Rename LocalizableByDimCursor to PositionCursor. Be able to say posCursor.setPosition(int[] pos) and posCursor.setPosition(long sampIndex). // Another possibility: just call it a Cursor. And then cursor.get() or cursor.get(int[] pos) or cursor.get(long sampleNumber) // Create ROICursors directly from an Image<T> and have that ctor setup its own LocalizableByDimCursor for you. // Allow new Image<ByteType>(rows,cols). Have a default factory and a default container and have other constructors that you use in the cases // where you want to specify them. Also allow new Image<UnsignedByte>(rows,cols,pixels). // Have a few static ContainerFactories that we can just refer to rather than newing them all the time. Maybe do so also for Types so that // we're not always having to pass a new UnsignedByteType() but rather a static one and if a new one needed the ctor can clone. // In general come up with much shorter names to make use less cumbersome. // It would be good to specify axis order of a cursor's traversal : new Cursor(image,"zxtcy") and then just call cursor.get() as needed. // Also could do cursor.fwd("t" or some enum value) which would iterate forward in the (here t) plane of the image skipping large groups of // samples at a time. // Put our ImageUtils class code somewhere in Imglib. Also maybe include the Index and Span classes too. Also TypeManager class. public class ImgLibProcessor<T extends RealType<T>> extends ImageProcessor implements java.lang.Cloneable { /** filter numbers: copied from various processors */ public static final int BLUR_MORE=0, FIND_EDGES=1, MEDIAN_FILTER=2, MIN=3, MAX=4, CONVOLVE=5, ERODE=10, DILATE=11; /** filter types: to replace filter numbers */ public static enum FilterType {BLUR_MORE, FIND_EDGES, MEDIAN_FILTER, MIN, MAX, CONVOLVE, ERODE, DILATE}; /** the ImgLib image that contains the plane of data this processor refers to */ /** the image coordinates of the plane within the ImgLib image. Example: 5d image - this xy plane where z=1,c=2,t=3 - planePosition = {1,2,3} */ /** the underlying ImgLib type of the image data */ /** flag for determining if we are working with integral data (or float otherwise) */ /** flag for determining if we are working with unsigned byte data */ /** flag for determining if we are working with unsigned short data */ /** flag for determining if we are working with float data */ /** the 8 bit image created in create8bitImage() - the method and this variable probably belong in base class */ /** the snapshot undo buffer associated with this processor */ /** value of background. used for various fill operations. only applies to UnsignedByte Type data. */ /** the smallest value actually present in the image */ /** the largest value actually present in the image */ /** used by some methods that fill in default values. only applies to float data */ /** used by erode() and dilate(). for UnsignedByteType data only. */ /** used by erode() and dilate(). for UnsignedByteType data only. */ /** used by snapshot() and reset(). not applicable to UnsignedByteType data. */ /** used by snapshot() and reset(). not applicable to UnsignedByteType data. */ /** a per thread variable. a cursor used to facilitate fast access to the ImgLib image. */ /** constructor: takes an ImgLib image and the position of the plane within the image */ /** constructor: takes an ImgLib image and the integer position of the plane within the image */ /** Uses bilinear interpolation to find the pixel value at real coordinates (x,y). */ /** required method. used in createImage(). creates an 8bit image from our image data of another type. */ /** called by filterUnsignedByte(). */ /** applies the various filter operations to UnsignedByteType data*/ /** find the median value of a list of exactly 9 values. adapted from ByteProcessor::findMedian() */ /** find the minimum and maximum values present in this plane of the image data */ /** returns a copy of our pixels as an array in the specified type. specified type probably has to match image's type */ /** called by filterEdge(). returns the pixel at x,y. if x,y out of bounds returns nearest edge pixel. */ /** called by filterEdge(). returns the pixel at x,y. if x,y out of bounds returns the background color. */ /** called by filterEdge(). returns the pixel at x,y. if x,y out of bounds returns the foreground color. */ /** returns the coordinates of the image origin as an int[] */ /** returns the coordinates of the ROI origin as an int[] */ /** sets the pixels for the specified image and plane position to the passed in array of pixels */ /** sets the min and max variables associated with this processor and does nothing else! */ /** sets the pixels of the image from provided FloatProcessor's pixel values */ /** sets the pixels of a plane in an image. called by setImagePlanePixels(). input pixels' type info must have been determined earlier. */ /** returns the span of the image plane as an int[] */ /** returns the span of the ROI plane as an int[] */ /** verifies that the passed in lut is compatible with the current data type. Throws an exception if the lut length is wrong * for the pixel layout type. */ private void verifyLutLengthOkay( int[] lut ) { if ( this.type instanceof GenericByteType< ? > ) { if (lut.length!=256) throw new IllegalArgumentException("lut.length != expected length for type " + this.type ); } else if( this.type instanceof GenericShortType< ? > ) { if (lut.length!=65536) throw new IllegalArgumentException("lut.length != expected length for type " + this.type ); } else { throw new IllegalArgumentException("lut not applicable for type " + this.type ); } } /** apply the ABS point operation over the current ROI area of the current plane of data */ /** apply the ADD point operation over the current ROI area of the current plane of data */ /** apply the ADD point operation over the current ROI area of the current plane of data */ /** apply the AND point operation over the current ROI area of the current plane of data */ /** runs super class autoThreshold() for integral data */ /** does a lut substitution on current ROIO area image data. applies only to integral data. */ /** sometimes it is useful to work with two images of the exact same type. this method will take any ImageProcessor and return an * ImageLibProcessor of the exact same type as itself. if the input image matches already it is simply returned. otherwise a new * processor is created and its pixels are populated from this ImgLibProcessor. * */ public ImgLibProcessor<T> getImgLibProcThatMatchesMyType(ImageProcessor inputProc) { // if inputProc's type matches me // just return inputProc if (inputProc instanceof ImgLibProcessor<?>) { ImgLibProcessor<?> imglibProc = (ImgLibProcessor<?>) inputProc; if (TypeManager.sameKind(this.type, imglibProc.getType())) return (ImgLibProcessor<T>) imglibProc; } // otherwise // create a processor of my type with size matching ip's dimensions // populate the pixels // return it Image<T> image = imageData.createNewImage(new int[]{ inputProc.getWidth(), inputProc.getHeight() } ); ImgLibProcessor<T> newProc = new ImgLibProcessor<T>(image, 0); boolean oldIntegralData = false; if ((inputProc instanceof ByteProcessor) || (inputProc instanceof ShortProcessor)) oldIntegralData = true; if (!oldIntegralData) { newProc.setPixels(inputProc.getPixels()); } else // funky issue where Java's signedness and IJ's unsignedness complicate setting the pixels { int w = newProc.getWidth(); int h = newProc.getHeight(); int value; for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { // Must turn into int data and remove signedness value = inputProc.get(x, y) & 0xffff; newProc.setd(x, y, value); } } } return newProc; } /** convolves the current image plane data with the provided kernel */ @Override public void convolve(float[] kernel, int kernelWidth, int kernelHeight) { FloatProcessor fp = toFloat(0,null); fp.setRoi(getRoi()); new ij.plugin.filter.Convolver().convolve(fp, kernel, kernelWidth, kernelHeight); double min = this.min; double max = this.max; setPixelsFromFloatProc(fp); if ((min != 0) && (max != 0)) // IJ will recalc min/max in this case which is not desired setMinAndMax(min,max); } /** convolves the current ROI area data with the provided 3x3 kernel */ @Override public void convolve3x3(int[] kernel) { /* Could do this but Wayne says its 3X slower than his special case way float[] floatKernel = new float[9]; for (int i = 0; i < 9; i++) floatKernel[i] = kernel[i]; convolve(floatKernel,3,3); */ // our special case way int[] origin = originOfRoi(); int[] span = spanOfRoiPlane(); Convolve3x3FilterOperation<T> convolveOp = new Convolve3x3FilterOperation<T>(this, origin, span, kernel); convolveOp.execute(); } // not an override /** uses a blitter to copy pixels to xloc,yloc from ImageProcessor ip using the given function */ public void copyBits(ImageProcessor ip, int xloc, int yloc, BinaryFunction function) { ImgLibProcessor<T> otherProc = getImgLibProcThatMatchesMyType(ip); new GenericBlitter<T>(this).copyBits(otherProc, xloc, yloc, function); } /** uses a blitter to copy pixels to xloc,yloc from ImageProcessor ip using the given mode */ @Deprecated @Override public void copyBits(ImageProcessor ip, int xloc, int yloc, int mode) { BinaryFunction function; switch (mode) { case Blitter.COPY: function = new CopyInput2BinaryFunction(); break; case Blitter.COPY_INVERTED: function = new CopyInput2InvertedBinaryFunction(this.type); break; case Blitter.COPY_TRANSPARENT: function = new CopyInput2TransparentBinaryFunction(this.type, this); break; case Blitter.COPY_ZERO_TRANSPARENT: function = new CopyInput2ZeroTransparentBinaryFunction(); break; case Blitter.ADD: function = new AddBinaryFunction(this.type); break; case Blitter.SUBTRACT: function = new SubtractBinaryFunction(this.type); break; case Blitter.MULTIPLY: function = new MultiplyBinaryFunction(this.type); break; case Blitter.DIVIDE: function = new DivideBinaryFunction(this.type); break; case Blitter.AVERAGE: function = new AverageBinaryFunction(this.type); break; case Blitter.DIFFERENCE: function = new DifferenceBinaryFunction(); break; case Blitter.AND: function = new AndBinaryFunction(); break; case Blitter.OR: function = new OrBinaryFunction(); break; case Blitter.XOR: function = new XorBinaryFunction(); break; case Blitter.MIN: function = new MinBinaryFunction(); break; case Blitter.MAX: function = new MaxBinaryFunction(); break; default: throw new IllegalArgumentException("copyBits(mode): unknown mode "+mode); } copyBits(ip,xloc,yloc,function); } //TODO ask about changing name of Image to avoid conflict with java.awt /** creates a java.awt.Image from super class variables */ @Override public java.awt.Image createImage() { int width = getWidth(); int height = getHeight(); boolean firstTime = this.pixels8==null; if (firstTime || !super.lutAnimation) create8BitImage(); if (super.cm==null) makeDefaultColorModel(); if (super.source==null) { super.source = new MemoryImageSource(width, height, super.cm, this.pixels8, 0, width); super.source.setAnimated(true); super.source.setFullBufferUpdates(true); super.img = Toolkit.getDefaultToolkit().createImage(super.source); } else if (super.newPixels) { super.source.newPixels(this.pixels8, super.cm, 0, width); super.newPixels = false; } else super.source.newPixels(); super.lutAnimation = false; return super.img; } /** creates a new ImgLibProcessor of desired height and width. copies some state from this processor. as a side effect it creates * a new 2D ImgLib Image that is owned by the ImgLibProcessor and is available via proc.getImage(). */ @Override public ImageProcessor createProcessor(int width, int height) { Image<T> image = this.imageData.createNewImage(new int[]{width,height}); ImageProcessor ip2 = new ImgLibProcessor<T>(image, 0); ip2.setColorModel(getColorModel()); // TODO - ByteProcessor does this conditionally. Do we mirror here? if (!(this.isUnsignedByte && (super.baseCM == null))) ip2.setMinAndMax(getMin(), getMax()); ip2.setInterpolationMethod(super.interpolationMethod); return ip2; } /** creates an ImgLibProcessor on a new image whose size and contents match the current ROI area. */ @Override @SuppressWarnings({"unchecked"}) public ImageProcessor crop() { int[] imageOrigin = originOfRoi(); int[] imageSpan = spanOfRoiPlane(); int[] newImageOrigin = Index.create(2); int[] newImageSpan = Span.singlePlane(imageSpan[0], imageSpan[1], 2); ImgLibProcessor<T> ip2 = (ImgLibProcessor<T>) createProcessor(imageSpan[0], imageSpan[1]); ImageUtils.copyFromImageToImage(this.imageData, imageOrigin, imageSpan, ip2.getImage(), newImageOrigin, newImageSpan); return ip2; /* Rectangle roi = getRoi(); int[] imageOrigin = originOfRoi(); int[] imageSpan = spanOfRoiPlane(); int[] newImageOrigin = Index.create(2); int[] newImageSpan = Span.singlePlane(roi.width, roi.height, 2); Image<T> newImage = this.imageData.createNewImage(newImageSpan); ImageUtils.copyFromImageToImage(this.imageData, imageOrigin, imageSpan, newImage, newImageOrigin, newImageSpan); ImageProcessor newProc = new ImgLibProcessor<T>(newImage, 0); return newProc; */ } /** does a filter operation vs. min or max as appropriate. applies to UnsignedByte data only.*/ @Override public void dilate() { if (this.isUnsignedByte) { if (isInvertedLut()) filter(FilterType.MAX); else filter(FilterType.MIN); } } // not an override : mirrors code in ByteProcessor /** does a dilate filter operation. applies to UnsignedByte data only.*/ public void dilate(int count, int background) { if (this.isUnsignedByte) { binaryCount = count; binaryBackground = background; filter(FilterType.DILATE); } } // not an override /** do a binary operation to the current ROI plane using the passed in BinaryFunction and reference ImgLibProcessor */ public void doBinaryOperation(ImgLibProcessor<T> other, BinaryFunction function, SelectionFunction selector1, SelectionFunction selector2) { Rectangle otherRoi = other.getRoi(); Image<T> image1 = this.imageData; int[] origin1 = originOfRoi(); int[] span1 = spanOfRoiPlane(); Image<T> image2 = other.getImage(); int[] origin2 = Index.create(otherRoi.x, otherRoi.y, other.getPlanePosition()); int[] span2 = Span.singlePlane(otherRoi.width, otherRoi.height, image2.getNumDimensions()); BinaryTransformOperation<T> transform = new BinaryTransformOperation<T>(image1,origin1,span1,image2,origin2,span2,function); transform.setSelectionFunctions(selector1, selector2); transform.execute(); } // not an override /** do a point operation to the current ROI plane using the passed in UnaryFunction */ public void doPointOperation(UnaryFunction function, SelectionFunction selector) { int[] origin = originOfRoi(); int[] span = spanOfRoiPlane(); UnaryTransformOperation<T> pointOp = new UnaryTransformOperation<T>(this.imageData, origin, span, function); pointOp.setSelectionFunction(selector); pointOp.execute(); if ((span[0] == getWidth()) && (span[1] == getHeight()) && !(function instanceof imagej.process.function.FillUnaryFunction)) findMinAndMax(); } // not an override /** do a binary operation to the current ROI plane using the passed in BinaryFunction and reference ImgLibProcessor */ public void doTernaryAssignOperation(ImgLibProcessor<T> other1, ImgLibProcessor<T> other2, BinaryFunction function, SelectionFunction[] selectors) { Image<T> image0 = this.imageData; int[] origin0 = originOfRoi(); int[] span0 = spanOfRoiPlane(); Rectangle other1Roi = other1.getRoi(); Image<T> image1 = other1.getImage(); int[] origin1 = Index.create(other1Roi.x, other1Roi.y, other1.getPlanePosition()); int[] span1 = Span.singlePlane(other1Roi.width, other1Roi.height, image1.getNumDimensions()); Rectangle other2Roi = other2.getRoi(); Image<T> image2 = other2.getImage(); int[] origin2 = Index.create(other2Roi.x, other2Roi.y, other2.getPlanePosition()); int[] span2 = Span.singlePlane(other2Roi.width, other2Roi.height, image2.getNumDimensions()); TernaryAssignOperation<T> transform = new TernaryAssignOperation<T>(image0,origin0,span0,image1,origin1,span1,image2,origin2,span2,function); transform.setSelectionFunctions(selectors); transform.execute(); } /** set the pixel at x,y to the fill/foreground value. if x,y outside clip region does nothing. */ @Override public void drawPixel(int x, int y) { if (x>=super.clipXMin && x<=super.clipXMax && y>=super.clipYMin && y<=super.clipYMax) { if (this.isIntegral) putPixel(x, y, getFgColor()); else putPixel(x, y, Float.floatToIntBits((float)fillColor)); } } /** creates a processor of the same size and sets its pixel values to this processor's current plane data */ @Override @SuppressWarnings({"unchecked"}) public ImageProcessor duplicate() { int width = getWidth(); int height = getHeight(); ImageProcessor proc = createProcessor(width, height); int[] origin = originOfImage(); int[] span = spanOfImagePlane(); ImgLibProcessor<T> imgLibProc = (ImgLibProcessor<T>) proc; ImageUtils.copyFromImageToImage(this.imageData,origin,span,imgLibProc.getImage(),origin,span); return proc; } /** does a filter operation vs. min or max as appropriate. applies to UnsignedByte data only.*/ @Override public void erode() { if (this.isUnsignedByte) { if (isInvertedLut()) filter(FilterType.MIN); else filter(FilterType.MAX); } } // not an override : mirrors code in ByteProcessor /** does an erode filter operation. applies to UnsignedByte data only.*/ public void erode(int count, int background) { if (this.isUnsignedByte) { binaryCount = count; binaryBackground = background; filter(FilterType.ERODE); } } /** apply the EXP point operation over the current ROI area of the current plane of data */ @Override public void exp() { ExpUnaryFunction function = new ExpUnaryFunction(this.type, this.max); doPointOperation(function, null); } /** apply the FILL point operation over the current ROI area of the current plane of data */ @Override public void fill() { double fillValue = this.fillColor; if (this.isIntegral) fillValue = getFgColor(); FillUnaryFunction func = new FillUnaryFunction(fillValue); doPointOperation(func, null); } // TODO - could refactor as some sort of operation between two datasets. Would need to make a dataset from mask. Slower than orig impl. /** fills the current ROI area of the current plane of data with the fill color wherever the input mask is nonzero */ @Override public void fill(ImageProcessor mask) { if (mask==null) { fill(); return; } int[] origin = originOfRoi(); int[] span = spanOfRoiPlane(); byte[] byteMask = (byte[]) mask.getPixels(); double color = this.fillColor; if (this.isIntegral) color = getFgColor(); MaskedFillOperation<T> fillOp = new MaskedFillOperation<T>(this.imageData, origin, span, byteMask, color); fillOp.execute(); /* version that uses a selection function to filter pixels FillUnaryFunction fillFunc = new FillUnaryFunction(color); UnaryTransformPositionalOperation<T> xform = new UnaryTransformPositionalOperation<T>(this.imageData, origin, span, fillFunc); SelectionFunction selector = new MaskOnSelectionFunction(origin, span, byteMask); xform.setSelectionFunction(selector); xform.execute(); */ } // not an override : way to phase out passing in filter numbers // TODO - figure out way to pass in a filter function of some sort and then we can phase out the FilterType enum too /** run specified filter (a FilterType) on current ROI area of current plane data */ public void filter(FilterType type) { int[] origin = originOfRoi(); int[] span = spanOfRoiPlane(); switch (type) { case BLUR_MORE: new BlurFilterOperation<T>(this,origin,span).execute(); break; case FIND_EDGES: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here : might be able to eliminate this special case - test else new FindEdgesFilterOperation<T>(this,origin,span).execute(); break; case MEDIAN_FILTER: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here break; case MIN: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here break; case MAX: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here break; case ERODE: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here break; case DILATE: if (this.isUnsignedByte) filterUnsignedByte(type); // TODO refactor here break; // NOTE - case CONVOLVE: purposely missing. It was allowed by mistake in IJ and would crash. default: throw new IllegalArgumentException("filter(FilterTye): invalid filter type specified - "+type); } } /** run specified filter (an int) on current ROI area of current plane data */ @Deprecated @Override public void filter(int type) { switch (type) { case BLUR_MORE: filter(FilterType.BLUR_MORE); break; case FIND_EDGES: filter(FilterType.FIND_EDGES); break; case MEDIAN_FILTER: filter(FilterType.MEDIAN_FILTER); break; case MIN: filter(FilterType.MIN); break; case MAX: filter(FilterType.MAX); break; case CONVOLVE: filter(FilterType.CONVOLVE); break; case ERODE: filter(FilterType.ERODE); break; case DILATE: filter(FilterType.DILATE); break; default: throw new IllegalArgumentException("filter(): unknown filter type requested - "+type); } } /** swap the rows of the current ROI area about its central row */ @Override public void flipVertical() { Rectangle roi = getRoi(); int x,y,mirrorY; int halfY = roi.height/2; for (int yOff = 0; yOff < halfY; yOff++) { y = roi.y + yOff; mirrorY = roi.y + roi.height - yOff - 1; for (int xOff = 0; xOff < roi.width; xOff++) { x = roi.x + xOff; double tmp = getd(x, y); setd(x, y, getd(x, mirrorY)); setd(x, mirrorY, tmp); } } } /** apply the GAMMA point operation over the current ROI area of the current plane of data */ @Override public void gamma(double value) { GammaUnaryFunction function = new GammaUnaryFunction(this.type, this.min, this.max, value); doPointOperation(function, null); } /** get the pixel value at x,y as an int. for float data it returns float encoded into int bits */ @Override public int get(int x, int y) { double value; int[] position = Index.create(x, y, this.planePosition); final LocalizableByDimCursor<T> cursor = this.cachedCursor.get(); cursor.setPosition( position ); value = cursor.getType().getRealDouble(); // do not close cursor - using cached one if (this.isIntegral) return (int) value; // else fall through to default float behavior in IJ return Float.floatToIntBits((float)value); } /** get the pixel value at index as an int. for float data it returns float encoded into int bits */ @Override public int get(int index) { int width = getWidth(); int x = index % width; int y = index / width; return get(x, y) ; } @Override public double getBicubicInterpolatedPixel(double x0, double y0, ImageProcessor ip2) { int u0 = (int) Math.floor(x0); //use floor to handle negative coordinates too int v0 = (int) Math.floor(y0); if (u0<=0 || u0>=super.width-2 || v0<=0 || v0>=super.height-2) return ip2.getBilinearInterpolatedPixel(x0, y0); double q = 0; for (int j = 0; j <= 3; j++) { int v = v0 - 1 + j; double p = 0; for (int i = 0; i <= 3; i++) { int u = u0 - 1 + i; p = p + ip2.getf(u,v) * cubic(x0 - u); // TODO - orig code uses getf(). could we transition to getd()? } q = q + p * cubic(y0 - v); } return q; } // not an override /** get the pixel value at x,y as a double. */ public double getd(int x, int y) { int[] position = Index.create(x, y, this.planePosition); LocalizableByDimCursor<T> cursor = this.cachedCursor.get(); cursor.setPosition(position); RealType<?> pixRef = cursor.getType(); return pixRef.getRealDouble(); // do not close cursor - using cached one } // not an override /** get the pixel value at index as a double. */ public double getd(int index) { int width = getWidth(); int x = index % width; int y = index / width; return getd(x, y); } /** get the pixel value at x,y as a float. */ @Override public float getf(int x, int y) { float value; int[] position = Index.create(x, y, this.planePosition); LocalizableByDimCursor<T> cursor = this.cachedCursor.get(); cursor.setPosition(position); value = ( float ) cursor.getType().getRealDouble(); // do not close cursor - using cached one return value; } /** get the pixel value at index as a float. */ @Override public float getf(int index) { int width = getWidth(); int x = index % width; int y = index / width; return getf(x, y) ; } /** get the current background value. always 0 if not UnsignedByte data */ @Override public double getBackgroundValue() { if (this.isUnsignedByte) return this.backgroundValue; return 0.0; } /** calculate the histogram of the current ROI area of the current plane. */ @Override public int[] getHistogram() { if ((this.isUnsignedByte) || (this.isUnsignedShort)) { int[] origin = originOfRoi(); int[] span = spanOfRoiPlane(); int lutSize = (int) (this.getMaxAllowedValue() + 1); HistogramOperation<T> histOp = new HistogramOperation<T>(this.imageData,origin,span,getMask(),lutSize); histOp.execute(); return histOp.getHistogram(); } return null; } // not an override /** returns the ImgLib image this processor is associated with */ public Image<T> getImage() { return this.imageData; } /** returns an interpolated pixel value from double coordinates using current interpolation method */ @Override public double getInterpolatedPixel(double x, double y) { if (super.interpolationMethod == BICUBIC) return getBicubicInterpolatedPixel(x, y, this); else { if (x<0.0) x = 0.0; if (x>=width-1.0) x = width-1.001; if (y<0.0) y = 0.0; if (y>=height-1.0) y = height-1.001; return calcBilinearPixel(x, y); } } /** returns the maximum data value currently present in the image plane (except when UnsignedByteType) */ @Override public double getMax() { return this.max; } // not an override /** returns the theoretical maximum possible sample value for this type of processor */ public double getMaxAllowedValue() { return this.type.getMaxValue(); } /** returns the minimum data value currently present in the image plane (except when UnsignedByteType) */ @Override public double getMin() { return this.min; } // not an override /** returns the theoretical minimum possible sample value for this type of processor */ public double getMinAllowedValue() { return this.type.getMinValue(); } // not an override /** returns the number of samples in my plane */ public long getTotalSamples() { return ((long) super.width) * super.height; } /** returns the pixel at x,y. if coords are out of bounds returns 0. */ @Override public int getPixel(int x, int y) { if ((x >= 0) && (x < super.width) && (y >= 0) && (y < super.height)) return get(x, y); return 0; } /** given x,y, double coordinates this returns an interpolated pixel using the current interpolations methods. unlike getInterpolatedPixel() * which assumes you're doing some kind of interpolation, this method will return nearest neighbors when no interpolation selected. note * that it returns as an int so float values are encoded as int bits. */ @Override public int getPixelInterpolated(double x, double y) { if (super.interpolationMethod == BILINEAR) { if (x<0.0 || y<0.0 || x>=width-1 || y>=height-1) return 0; else if (this.isIntegral) return (int) Math.round(getInterpolatedPixel(x, y)); else return Float.floatToIntBits((float)getInterpolatedPixel(x, y)); } else if (interpolationMethod==BICUBIC) { if (this.isIntegral) { double value = getInterpolatedPixel(x, y) + 0.5; value = TypeManager.boundValueToType(this.type, value); return (int)value; } return Float.floatToIntBits((float)getBicubicInterpolatedPixel(x, y, this)); } else return getPixel((int)(x+0.5), (int)(y+0.5)); } /** returns the pixel value at x,y as a float. if x,y, out of bounds returns 0. */ @Override public float getPixelValue(int x, int y) { int width = getWidth(); int height = getHeight(); // make sure its in bounds if ((x >= 0) && (x < width) && (y >= 0) && (y < height)) return getf(x, y); return 0f; } /** returns a copy of the current plane data pixels as an array of the appropriate type */ @Override public Object getPixels() { final PlanarAccess<?> planarAccess = ImageOpener.getPlanarAccess(this.imageData); if (planarAccess == null) { System.out.println("getPixels() - nonoptimal container type - can only return a copy of pixels"); return getCopyOfPixelsFromImage(this.imageData, this.type, this.planePosition); } else // we have the special planar container in place { int[] planeDimsMaxes = ImageUtils.getDimsBeyondXY(this.imageData.getDimensions()); long planeNumber = ImageUtils.getSampleNumber(planeDimsMaxes, this.planePosition); if (planeNumber >= Integer.MAX_VALUE) throw new IllegalArgumentException("too many planes"); return planarAccess.getPlane((int)planeNumber); } } /** returns a copy of some pixels as an array of the appropriate type. depending upon super class variable "snapshotCopyMode" * it will either copy current plane data or it will copy current snapshot data. */ @Override public Object getPixelsCopy() { if (this.snapshot!=null && getSnapshotCopyMode()) { setSnapshotCopyMode(false); Image<T> snapStorage = this.snapshot.getStorage(); int[] planePosOfZero = Index.create(this.planePosition.length); // this is correct! return getCopyOfPixelsFromImage(snapStorage, this.type, planePosOfZero); } else { return getCopyOfPixelsFromImage(this.imageData, this.type, this.planePosition); } } // not an override /** return the current plane data pixels as an array of doubles. converts types as needed. */ public double[] getPlaneData() { return ImageUtils.getPlaneData(this.imageData, getWidth(), getHeight(), this.planePosition); } // not an override /** return the plane position of this processor within its parent ImgLib image */ public int[] getPlanePosition() { return this.planePosition.clone(); } /** returns a copy of the pixels in the current snapshot */ @Override public Object getSnapshotPixels() { if (this.snapshot == null) return null; Image<T> snapStorage = this.snapshot.getStorage(); int[] planePosOfZero = Index.create(this.planePosition.length); // this is correct! return getCopyOfPixelsFromImage(snapStorage, this.type, planePosOfZero); } // not an override /** return the underlying ImgLib type of this processor */ public RealType<?> getType() { return this.type; } /** apply the INVERT point operation over the current ROI area of the current plane of data */ @Override public void invert() { if (this.isIntegral) resetMinAndMax(); InvertUnaryFunction function = new InvertUnaryFunction(this.type, this.min, this.max); doPointOperation(function, null); } /** apply the LOG point operation over the current ROI area of the current plane of data */ @Override public void log() { LogUnaryFunction function = new LogUnaryFunction(this.type, this.max); doPointOperation(function, null); } /** apply the MAXIMUM point operation over the current ROI area of the current plane of data */ @Override public void max(double value) { MaxUnaryFunction function = new MaxUnaryFunction(value); doPointOperation(function, null); } /** run the MEDIAN_FILTER on current ROI area of current plane data. only applies to UnsignedByte data */ @Override public void medianFilter() { if (this.isUnsignedByte) { filter(FilterType.MEDIAN_FILTER); } } /** apply the MINIMUM point operation over the current ROI area of the current plane of data */ @Override public void min(double value) { MinUnaryFunction function = new MinUnaryFunction(value); doPointOperation(function, null); } /** apply the MULT point operation over the current ROI area of the current plane of data */ @Override public void multiply(double value) { MultiplyUnaryFunction function = new MultiplyUnaryFunction(this.type, value); doPointOperation(function, null); } /** add noise to the current ROI area of current plane data. */ @Override public void noise(double range) { AddNoiseUnaryFunction function = new AddNoiseUnaryFunction(this.type, range); doPointOperation(function, null); } /** apply the OR point operation over the current ROI area of the current plane of data */ @Override public void or(int value) { if (!this.isIntegral) return; OrUnaryFunction func = new OrUnaryFunction(this.type, value); doPointOperation(func, null); } /** set the pixel at x,y to the given int value. if float data value is a float encoded as an int. if x,y, out of bounds do nothing. */ @Override public void putPixel(int x, int y, int value) { if (x>=0 && x<getWidth() && y>=0 && y<getHeight()) { if (this.isIntegral) { value = (int)TypeManager.boundValueToType(this.type, value); set(x, y, value); } else setf(x, y, Float.intBitsToFloat(value)); } } /** set the pixel at x,y to the given double value. if integral data the value is biased by 0.5 do force rounding. * if x,y, out of bounds do nothing. */ @Override public void putPixelValue(int x, int y, double value) { if (x>=0 && x<getWidth() && y>=0 && y<getHeight()) { if (this.isIntegral) { value = TypeManager.boundValueToType(this.type, value); set(x, y, (int)(value+0.5)); } else setd(x, y, value); } } /** sets the current plane data to that stored in the snapshot */ @Override public void reset() { if (this.snapshot!=null) this.snapshot.pasteIntoImage(this.imageData); } /** sets the current ROI area data to that stored in the snapshot wherever the mask is nonzero */ @Override public void reset(ImageProcessor mask) { if (mask==null || this.snapshot==null) return; Rectangle roi = getRoi(); if ((mask.getWidth() != roi.width) || (mask.getHeight() != roi.height)) throw new IllegalArgumentException(maskSizeError(mask)); Image<T> snapData = this.snapshot.getStorage(); int[] snapOrigin = Index.create(roi.x, roi.y, new int[snapData.getNumDimensions()-2]); int[] snapSpan = Span.singlePlane(roi.width, roi.height, snapData.getNumDimensions()); int[] imageOrigin = originOfRoi(); int[] imageSpan = spanOfRoiPlane(); ResetUsingMaskOperation<T> resetOp = new ResetUsingMaskOperation<T>(snapData,snapOrigin,snapSpan,this.imageData,imageOrigin,imageSpan,mask); resetOp.execute(); if (!this.isUnsignedByte) { this.min = this.snapshotMin; this.max = this.snapshotMax; } // TODO : replace resetOp with a BinaryAssignPositionalOperation (need to define) like refactor of MaskedFillOperation // call elsewhere in this file. Use a selector function (MaskOnSlectionFunction) to filter which samples are acted on. } // TODO - refactor /** create a new processor that has specified dimensions. populate it's data with interpolated pixels from this processor's ROI area data. */ @Override public ImageProcessor resize(int dstWidth, int dstHeight) { // TODO - for some reason Float and Short don't check for crop() only and their results are different than doing crop!!! if (this.isUnsignedByte) if (roiWidth==dstWidth && roiHeight==dstHeight) return crop(); double srcCenterX = roiX + roiWidth/2.0; double srcCenterY = roiY + roiHeight/2.0; double dstCenterX = dstWidth/2.0; double dstCenterY = dstHeight/2.0; double xScale = (double)dstWidth/roiWidth; double yScale = (double)dstHeight/roiHeight; if (interpolationMethod!=NONE) { dstCenterX += xScale/2.0; dstCenterY += yScale/2.0; } ImgLibProcessor<?> ip2 = (ImgLibProcessor<?>)createProcessor(dstWidth, dstHeight); ProgressTracker tracker = new ProgressTracker(this, ((long)dstHeight)*dstWidth, 30*dstWidth); double xs, ys; if (interpolationMethod==BICUBIC) { for (int y=0; y<=dstHeight-1; y++) { ys = (y-dstCenterY)/yScale + srcCenterY; int index = y*dstWidth; for (int x=0; x<=dstWidth-1; x++) { xs = (x-dstCenterX)/xScale + srcCenterX; double value = getBicubicInterpolatedPixel(xs, ys, this); if (this.isIntegral) { value += 0.5; value = TypeManager.boundValueToType(this.type, value); } ip2.setd(index++, value); tracker.update(); } } } else { // not BICUBIC double xlimit = width-1.0, xlimit2 = width-1.001; double ylimit = height-1.0, ylimit2 = height-1.001; int index1, index2; for (int y=0; y<=dstHeight-1; y++) { ys = (y-dstCenterY)/yScale + srcCenterY; if (interpolationMethod==BILINEAR) { if (ys<0.0) ys = 0.0; if (ys>=ylimit) ys = ylimit2; } index1 = width*(int)ys; index2 = y*dstWidth; for (int x=0; x<=dstWidth-1; x++) { xs = (x-dstCenterX)/xScale + srcCenterX; if (interpolationMethod==BILINEAR) { if (xs<0.0) xs = 0.0; if (xs>=xlimit) xs = xlimit2; double value = getInterpolatedPixel(xs, ys); if (this.isIntegral) { value += 0.5; value = TypeManager.boundValueToType(this.type, value); } ip2.setd(index2++, value); } else // interp == NONE { double value = getd(index1+(int)xs); ip2.setd(index2++, value); } tracker.update(); } } } tracker.done(); return ip2; } // TODO - refactor /** rotates current ROI area pixels by given angle. destructive. interpolates pixel values as needed. */ @Override public void rotate(double angle) { // TODO - for some reason Float and Short don't check for rotate by 0.0 and their results are different than doing nothing!!!!! if ((angle%360==0) && (this.isUnsignedByte)) return; Object pixels2 = getPixelsCopy(); ImgLibProcessor<?> ip2 = ImageUtils.createProcessor(getWidth(), getHeight(), pixels2, TypeManager.isUnsignedType(this.type)); if (interpolationMethod==BICUBIC) ip2.setBackgroundValue(getBackgroundValue()); double centerX = roiX + (roiWidth-1)/2.0; double centerY = roiY + (roiHeight-1)/2.0; int xMax = roiX + roiWidth - 1; // TODO in original ByteProcessor code here: // if (!bgColorSet && isInvertedLut()) bgColor = 0; double angleRadians = -angle/(180.0/Math.PI); double ca = Math.cos(angleRadians); double sa = Math.sin(angleRadians); double tmp1 = centerY*sa-centerX*ca; double tmp2 = -centerX*sa-centerY*ca; double tmp3, tmp4, xs, ys; int index, ixs, iys; double dwidth=width, dheight=height; double xlimit = width-1.0, xlimit2 = width-1.001; double ylimit = height-1.0, ylimit2 = height-1.001; ProgressTracker tracker = new ProgressTracker(this, ((long)roiWidth)*roiHeight, 30*roiWidth); if (interpolationMethod==BICUBIC) { for (int y=roiY; y<(roiY + roiHeight); y++) { index = y*width + roiX; tmp3 = tmp1 - y*sa + centerX; tmp4 = tmp2 + y*ca + centerY; for (int x=roiX; x<=xMax; x++) { xs = x*ca + tmp3; ys = x*sa + tmp4; double value = getBicubicInterpolatedPixel(xs, ys, ip2); if (this.isIntegral) { value = (int) (value+0.5); value = TypeManager.boundValueToType(this.type, value); } setd(index++,value); tracker.update(); } } } else { for (int y=roiY; y<(roiY + roiHeight); y++) { index = y*width + roiX; tmp3 = tmp1 - y*sa + centerX; tmp4 = tmp2 + y*ca + centerY; for (int x=roiX; x<=xMax; x++) { xs = x*ca + tmp3; ys = x*sa + tmp4; if ((xs>=-0.01) && (xs<dwidth) && (ys>=-0.01) && (ys<dheight)) { if (interpolationMethod==BILINEAR) { if (xs<0.0) xs = 0.0; if (xs>=xlimit) xs = xlimit2; if (ys<0.0) ys = 0.0; if (ys>=ylimit) ys = ylimit2; double value = ip2.getInterpolatedPixel(xs, ys); if (this.isIntegral) { value = (int) (value+0.5); value = TypeManager.boundValueToType(this.type, value); } setd(index++, value); } else { ixs = (int)(xs+0.5); iys = (int)(ys+0.5); if (ixs>=width) ixs = width - 1; if (iys>=height) iys = height -1; setd(index++, ip2.getd(ixs,iys)); } } else { double value = 0; if (this.isIntegral) value = this.getBackgroundValue(); setd(index++,value); } tracker.update(); } } } tracker.done(); } // TODO - refactor /** scale current ROI area in x and y by given factors. destructive. calculates interpolated pixels as needed */ @Override public void scale(double xScale, double yScale) { // TODO - in original ByteProcessor code right here // if (!bgColorSet && isInvertedLut()) bgColor = 0; double xCenter = roiX + roiWidth/2.0; double yCenter = roiY + roiHeight/2.0; int xmin, xmax, ymin, ymax; if ((xScale>1.0) && (yScale>1.0)) { //expand roi xmin = (int)(xCenter-(xCenter-roiX)*xScale); if (xmin<0) xmin = 0; xmax = xmin + (int)(roiWidth*xScale) - 1; if (xmax>=width) xmax = width - 1; ymin = (int)(yCenter-(yCenter-roiY)*yScale); if (ymin<0) ymin = 0; ymax = ymin + (int)(roiHeight*yScale) - 1; if (ymax>=height) ymax = height - 1; } else { xmin = roiX; xmax = roiX + roiWidth - 1; ymin = roiY; ymax = roiY + roiHeight - 1; } Object pixels2 = getPixelsCopy(); ImgLibProcessor<?> ip2 = ImageUtils.createProcessor(getWidth(), getHeight(), pixels2, TypeManager.isUnsignedType(this.type)); boolean checkCoordinates = (xScale < 1.0) || (yScale < 1.0); int index1, index2, xsi, ysi; double ys, xs; ProgressTracker tracker = new ProgressTracker(this, ((long)roiWidth)*roiHeight, 30*roiWidth); if (interpolationMethod==BICUBIC) { for (int y=ymin; y<=ymax; y++) { ys = (y-yCenter)/yScale + yCenter; int index = y*width + xmin; for (int x=xmin; x<=xmax; x++) { xs = (x-xCenter)/xScale + xCenter; double value = getBicubicInterpolatedPixel(xs, ys, ip2); if (this.isIntegral) { value = (int) (value+0.5); value = TypeManager.boundValueToType(this.type, value); } setd(index++,value); tracker.update(); } } } else { double xlimit = width-1.0, xlimit2 = width-1.001; double ylimit = height-1.0, ylimit2 = height-1.001; for (int y=ymin; y<=ymax; y++) { ys = (y-yCenter)/yScale + yCenter; ysi = (int)ys; if (ys<0.0) ys = 0.0; if (ys>=ylimit) ys = ylimit2; index1 = y*width + xmin; index2 = width*(int)ys; for (int x=xmin; x<=xmax; x++) { xs = (x-xCenter)/xScale + xCenter; xsi = (int)xs; if (checkCoordinates && ((xsi<xmin) || (xsi>xmax) || (ysi<ymin) || (ysi>ymax))) { if (this.isUnsignedByte) setd(index1++, this.getBackgroundValue()); else setd(index1++, this.min); } else // interpolated pixel within bounds of image { if (interpolationMethod==BILINEAR) { if (xs<0.0) xs = 0.0; if (xs>=xlimit) xs = xlimit2; double value = ip2.getInterpolatedPixel(xs, ys); if (this.isIntegral) { value = (int) (value+0.5); value = TypeManager.boundValueToType(this.type, value); } setd(index1++, value); } else // interpolation type of NONE { setd(index1++, ip2.getd(index2+xsi)); } } tracker.update(); } } } tracker.done(); } /** set the pixel at x,y, to provided int value. if float data then value is a float encoded as an int */ @Override public void set(int x, int y, int value) { int[] position = Index.create(x, y, this.planePosition); LocalizableByDimCursor<T> cursor = this.cachedCursor.get(); cursor.setPosition(position); double dVal = value; if (!this.isIntegral) dVal = Float.intBitsToFloat(value); cursor.getType().setReal( dVal ); // do not close cursor - using cached one } /** set the pixel at index to provided int value. if float data then value is a float encoded as an int */ @Override public void set(int index, int value) { int width = getWidth(); int x = index % width; int y = index / width; set( x, y, value) ; } /** set the current background value. only applies to UnsignedByte data */ @Override public void setBackgroundValue(double value) { // only set for unsigned byte type like ImageJ (maybe need to extend to integral types and check min/max pixel ranges) if (this.isUnsignedByte) { if (value < 0) value = 0; if (value > 255) value = 255; value = (int) value; this.backgroundValue = value; } } /** set the current foreground value. */ @Override public void setColor(Color color) { int bestIndex = getBestIndex(color); if (this.type instanceof GenericByteType<?>) { super.drawingColor = color; setFgColor(bestIndex); } else { // not a Byte type double min = getMin(); double max = getMax(); if ((bestIndex>0) && (min == 0) && (max == 0)) { if (this.isIntegral) setValue(bestIndex); else // floating type this.fillColor = bestIndex; setMinAndMax(0,255); } else if ((bestIndex == 0) && (min > 0) && ((color.getRGB()&0xffffff) == 0)) { if (!this.isIntegral) this.fillColor = 0; else { // integral data that is not byte if (TypeManager.isUnsignedType(this.type)) // TODO - this logic is different than original code. Test! setValue(0.0); else setValue(this.type.getMaxValue()); } } else { double value = (min + (max-min)*(bestIndex/255.0)); if (this.isIntegral) setFgColor((int)value); else this.fillColor = value; } } } // not an override /** set the pixel at x,y to the provided double value. truncates values for integral types. */ public void setd(int x, int y, double value) { int[] position = Index.create(x, y, this.planePosition); LocalizableByDimCursor<T> cursor = this.cachedCursor.get(); cursor.setPosition(position); RealType<?> pixRef = cursor.getType(); // TODO - verify the following implementation is what we want to do: // NOTE - for an integer type backed data store imglib rounds float values. ImageJ has always truncated float values. // I need to detect beforehand and do my truncation if an integer type. if (this.isIntegral) value = (double)Math.floor(value); pixRef.setReal( value ); // do not close cursor - using cached one } // not an override /** set the pixel at index to the provided double value. truncates values for integral types. */ public void setd(int index, double value) { int width = getWidth(); int x = index % width; int y = index / width; setd( x, y, value); } /** set the pixel at x,y to the given float value. truncates values for integral types. */ @Override public void setf(int x, int y, float value) { setd(x, y, (double)value); } /** set the pixel at index to the given float value. truncates values for integral types. */ @Override public void setf(int index, float value) { int width = getWidth(); int x = index % width; int y = index / width; setf( x, y, value); } /** set min and max values to provided values. resets the threshold as needed. if passed (0,0) it will calculate actual min and max 1st. */ @Override public void setMinAndMax(double min, double max) { if ((min==0.0 && max==0.0) && (!this.isUnsignedByte)) { resetMinAndMax(); return; } this.min = min; this.max = max; if (this.isIntegral) { this.min = (int) this.min; this.max = (int) this.max; } // TODO - From FloatProc - there is code for setting the fixedScale boolean. May need it. resetThreshold(); } /** set the current image plane data to the provided pixel values */ @Override public void setPixels(Object pixels) { if (pixels != null) setImagePlanePixels(this.imageData, this.planePosition, pixels); super.resetPixels(pixels); if (pixels==null) // free up memory { this.snapshot = null; this.pixels8 = null; } } /** set the current image plane data to the pixel values of the provided FloatProcessor. channelNumber is ignored. */ @Override public void setPixels(int channelNumber, FloatProcessor fp) { // like ByteProcessor ignore channel number //OLD WAY setPixels(fp.getPixels()); setPixelsFromFloatProc(fp); setMinAndMax(fp.getMin(), fp.getMax()); } /** sets the current snapshot pixels to the provided pixels. it copies data rather than changing snapshot reference. */ @Override public void setSnapshotPixels(Object pixels) { if (pixels == null) { this.snapshot = null; return; } // must create snapshot data structures if they don't exist. we'll overwrite it's data soon. if (this.snapshot == null) snapshot(); Image<T> snapStorage = this.snapshot.getStorage(); int[] planePosition = Index.create(snapStorage.getNumDimensions()-2); setImagePlanePixels(snapStorage, planePosition, pixels); } /** sets the current fill/foreground value */ @Override public void setValue(double value) { this.fillColor = value; if (this.isIntegral) { setFgColor((int) TypeManager.boundValueToType(this.type, this.fillColor)); } } /** copy the current pixels to the snapshot array */ @Override public void snapshot() { int[] origins = originOfImage(); int[] spans = spanOfImagePlane(); this.snapshot = new Snapshot<T>(this.imageData, origins, spans); this.snapshotMin = this.min; this.snapshotMax = this.max; } /** apply the SQR point operation over the current ROI area of the current plane of data */ @Override public void sqr() { SqrUnaryFunction function = new SqrUnaryFunction(this.type); doPointOperation(function, null); } /** apply the SQRT point operation over the current ROI area of the current plane of data */ @Override public void sqrt() { SqrtUnaryFunction function = new SqrtUnaryFunction(this.type); doPointOperation(function, null); } /** calculates actual min and max values present and resets the threshold */ @Override public void resetMinAndMax() { // TODO - From FloatProc - there is code for setting the fixedScale boolean. May need it. findMinAndMax(); resetThreshold(); } /** makes the image binary (values of 0 and 255) splitting the pixels based on their relationship to the threshold level. * only applies to integral data types. */ @Override public void threshold(int thresholdLevel) { if (!this.isIntegral) return; thresholdLevel = (int) TypeManager.boundValueToType(this.type, thresholdLevel); ThresholdUnaryFunction function = new ThresholdUnaryFunction(thresholdLevel); doPointOperation(function, null); } /** creates a FloatProcessor whose pixel values are set to those of this processor. */ @Override public FloatProcessor toFloat(int channelNumber, FloatProcessor fp) { int width = getWidth(); int height = getHeight(); long size = getTotalSamples(); if (size > Integer.MAX_VALUE) throw new IllegalArgumentException("desired size of pixel array is too large (> "+Integer.MAX_VALUE+" entries)"); int allocatedSize = (int) size; if (fp == null || fp.getWidth()!=width || fp.getHeight()!=height) fp = new FloatProcessor(width, height, new float[allocatedSize], super.cm); int[] origin = originOfImage(); int[] span = spanOfImagePlane(); SetFloatValuesOperation<T> floatOp = new SetFloatValuesOperation<T>(this.imageData, origin, span, fp); floatOp.execute(); fp.setRoi(getRoi()); fp.setMask(getMask()); if ((this.isFloat) && (this.min == 0) && (this.max == 0)) ; // do nothing : otherwise a resetMinAndMax triggered which is not what we want else fp.setMinAndMax(this.min, this.max); fp.setThreshold(getMinThreshold(), getMaxThreshold(), ImageProcessor.NO_LUT_UPDATE); return fp; } /** apply the XOR point operation over the current ROI area of the current plane of data */ @Override public void xor(int value) { if (!this.isIntegral) return; XorUnaryFunction func = new XorUnaryFunction(this.type, value); doPointOperation(func, null); } }
package edu.mit.streamjit.impl.distributed; import java.util.Set; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.BlobFactory; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.Configuration.IntParameter; import edu.mit.streamjit.impl.common.Configuration.Parameter; import edu.mit.streamjit.impl.common.Workers; import edu.mit.streamjit.impl.compiler.Compiler; import edu.mit.streamjit.impl.compiler.CompilerBlobFactory; import edu.mit.streamjit.impl.interp.Interpreter.InterpreterBlobFactory; /** * This BlobFactory is not for any specific blob implementation. Internally, it * uses {@link CompilerBlobFactory} and {@link InterpreterBlobFactory} to get * default configurations for a given stream graph. In addition to that, it adds * all parameters, such as worker to machine assignment, multiplication factor * for each machine and etc, which are related to distributed tuning. * <p> * This {@link BlobFactory} becomes statefull because of the numbers of the * machine connected. * </p> * <p> * TODO: For the moment this factory just deal with compiler blob. Need to make * interpreter blob as well based on the dynamic edges. * * @author Sumanan sumanan@mit.edu * @since Sep 24, 2013 */ public class DistributedBlobFactory implements BlobFactory { private int noOfMachines; public DistributedBlobFactory(int noOfMachines) { this.noOfMachines = noOfMachines; } @Override public Blob makeBlob(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState) { return new Compiler(workers, config, maxNumCores, initialState) .compile(); } @Override public Configuration getDefaultConfiguration(Set<Worker<?, ?>> workers) { BlobFactory compilerBf = new CompilerBlobFactory(); Configuration compilercfg = compilerBf.getDefaultConfiguration(workers); Configuration.Builder builder = Configuration.builder(compilercfg); Configuration.IntParameter multiplierParam = (Configuration.IntParameter) builder .removeParameter("multiplier"); for (int i = 0; i < noOfMachines; i++) { builder.addParameter(new Configuration.IntParameter(String.format( "multiplier%d", (i + 1)), multiplierParam.getRange(), multiplierParam.getValue())); } // Configuration.Builder builder = Configuration.builder(); for (Worker<?, ?> w : workers) { Parameter p = new Configuration.IntParameter(String.format( "worker%dtomachine", Workers.getIdentifier(w)), 1, noOfMachines, 1); builder.addParameter(p); } // This parameter cannot be tuned. Its added here because we need this // parameter to run the app. // TODO: Consider using partition parameter and extradata to store this // kind of not tunable data. IntParameter noOfMachinesParam = new IntParameter("noOfMachines", noOfMachines, noOfMachines, noOfMachines); builder.addParameter(noOfMachinesParam); return builder.build(); } @Override public boolean equals(Object o) { return getClass() == o.getClass() && noOfMachines == ((DistributedBlobFactory) o).noOfMachines; } @Override public int hashCode() { return 31 * noOfMachines; } }
package net.bramp.ffmpeg; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import com.google.common.io.CountingOutputStream; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.fixtures.Samples; import net.bramp.ffmpeg.job.FFmpegJob; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import net.bramp.ffmpeg.progress.Progress; import net.bramp.ffmpeg.progress.RecordingProgressListener; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests actually shelling out ffmpeg and ffprobe. Could be flakey if ffmpeg or ffprobe change. */ public class FFmpegExecutorTest { @Rule public Timeout timeout = new Timeout(30, TimeUnit.SECONDS); final FFmpeg ffmpeg = new FFmpeg(); final FFprobe ffprobe = new FFprobe(); final FFmpegExecutor ffExecutor = new FFmpegExecutor(ffmpeg, ffprobe); final ExecutorService executor = Executors.newSingleThreadExecutor(); public FFmpegExecutorTest() throws IOException {} @Test public void testTwoPass() throws InterruptedException, ExecutionException, IOException { FFmpegProbeResult in = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); assertFalse(in.hasError()); FFmpegBuilder builder = new FFmpegBuilder().setInput(in).overrideOutputFiles(true).addOutput(Samples.output_mp4) .setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .setVideoFrameRate(FFmpeg.FPS_30).setVideoResolution(320, 240) .setTargetSize(1024 * 1024).done(); FFmpegJob job = ffExecutor.createTwoPassJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } @Test public void testFilter() throws InterruptedException, ExecutionException, IOException { FFmpegBuilder builder = new FFmpegBuilder().setInput(Samples.big_buck_bunny_720p_1mb).overrideOutputFiles(true) .addOutput(Samples.output_mp4).setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .setVideoFilter("scale=320:trunc(ow/a/2)*2").done(); FFmpegJob job = ffExecutor.createJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } @Test public void testMetaTags() throws InterruptedException, ExecutionException, IOException { FFmpegBuilder builder = new FFmpegBuilder().setInput(Samples.big_buck_bunny_720p_1mb).overrideOutputFiles(true) .addOutput(Samples.output_mp4).setFormat("mp4").disableAudio().setVideoCodec("mpeg4") .addMetaTag("comment", "This=Nice!").addMetaTag("title", "Big Buck Bunny").done(); FFmpegJob job = ffExecutor.createJob(builder); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); } /** * Test if addStdoutOutput() actually works, and the output can be correctly captured. * * @throws InterruptedException * @throws ExecutionException * @throws IOException */ @Test public void testStdout() throws InterruptedException, ExecutionException, IOException { // @formatter:off FFmpegBuilder builder = new FFmpegBuilder() .setInput(Samples.big_buck_bunny_720p_1mb) .addStdoutOutput() .setFormat("s8") .setAudioChannels(1) .done(); List<String> newArgs = ImmutableList.<String>builder() .add(FFmpeg.FFMPEG) .addAll(builder.build()) .build(); // @formatter:on Process p = new ProcessBuilder(newArgs).start(); CountingOutputStream out = new CountingOutputStream(ByteStreams.nullOutputStream()); ByteStreams.copy(p.getInputStream(), out); p.waitFor(); // This is perhaps fragile, but one byte per audio sample assertEquals(254976, out.getCount()); } @Test public void testProgress() throws InterruptedException, ExecutionException, IOException { FFmpegProbeResult in = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); assertFalse(in.hasError()); FFmpegBuilder builder = new FFmpegBuilder().readAtNativeFrameRate() // Slows the test down .setInput(in).overrideOutputFiles(true).addOutput(Samples.output_mp4).done(); RecordingProgressListener listener = new RecordingProgressListener(); FFmpegJob job = ffExecutor.createJob(builder, listener); runAndWait(job); assertEquals(FFmpegJob.State.FINISHED, job.getState()); List<Progress> progesses = listener.progesses; // Since the results of ffmpeg are not predictable, test for the bare minimum. assertThat(progesses, hasSize(greaterThanOrEqualTo(2))); assertThat(progesses.get(0).progress, is("continue")); assertThat(progesses.get(progesses.size() - 1).progress, is("end")); } protected void runAndWait(FFmpegJob job) throws ExecutionException, InterruptedException { executor.submit(job).get(); } }
package edu.psu.compbio.seqcode.gse.deepseq.utilities; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.apache.log4j.Logger; import edu.psu.compbio.seqcode.gse.datasets.general.NamedRegion; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.datasets.seqdata.SeqLocator; import edu.psu.compbio.seqcode.gse.datasets.species.Genome; import edu.psu.compbio.seqcode.gse.datasets.species.Organism; import edu.psu.compbio.seqcode.gse.deepseq.DeepSeqExpt; import edu.psu.compbio.seqcode.gse.deepseq.discovery.SingleConditionFeatureFinder; import edu.psu.compbio.seqcode.gse.ewok.verbs.ChromRegionIterator; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.gse.utils.ArgParser; import edu.psu.compbio.seqcode.gse.utils.NotFoundException; import edu.psu.compbio.seqcode.gse.utils.Pair; /** * Outputs a BED format file for a deep-seq experiment. * * @author Shaun Mahony * @version %I%, %G% */ public class BEDExporter { private Organism org; private Genome gen; protected DeepSeqExpt expt; protected int [] stackedHitCountsPos; protected int [] stackedHitCountsNeg; private String outName="out"; private boolean dbconnected=false; private static final Logger logger = Logger.getLogger(SingleConditionFeatureFinder.class); public static void main(String[] args) throws SQLException, NotFoundException { BEDExporter bed = new BEDExporter(args); bed.execute(); System.exit(0); } public BEDExporter(String [] args) { if(args.length==0){ System.err.println("BEDExporter usage:\n" + "\t--species <organism;genome>\n" + "\t--(rdb)expt <experiment names>\n" + "\t--out <output file name>"); System.exit(1); } ArgParser ap = new ArgParser(args); try { if(ap.hasKey("species")){ Pair<Organism, Genome> pair = Args.parseGenome(args); if(pair != null){ gen = pair.cdr(); dbconnected=true; } }else{ //Make fake genome... chr lengths provided??? if(ap.hasKey("geninfo") || ap.hasKey("g")){ String fName = ap.hasKey("geninfo") ? ap.getKeyValue("geninfo") : ap.getKeyValue("g"); gen = new Genome("Genome", new File(fName), true); }else{ gen = null; } } }catch (NotFoundException e) { e.printStackTrace(); } outName = Args.parseString(args,"out",outName); // Load the experiments List<SeqLocator> dbexpts = Args.parseSeqExpt(args, "dbexpt"); List<SeqLocator> rdbexpts = Args.parseSeqExpt(args,"rdbexpt"); List<File> expts = Args.parseFileHandles(args, "expt"); boolean nonUnique = ap.hasKey("nonunique") ? true : false; String fileFormat = Args.parseString(args, "format", "ELAND"); if(expts.size()>0 && dbexpts.size() == 0 && rdbexpts.size()==0){ expt= new DeepSeqExpt(gen, expts, nonUnique, fileFormat, 1); }else if (dbexpts.size() > 0 && expts.size() == 0) { expt = new DeepSeqExpt(gen, dbexpts, "db", 1); dbconnected = true; }else if (rdbexpts.size()>0 && expts.size() == 0){ expt = new DeepSeqExpt(gen, rdbexpts, "readdb", -1); dbconnected=true; }else { logger.error("Must provide either an aligner output file or Gifford lab DB experiment name for the signal experiment (but not both)"); System.exit(1); } logger.info("Expt hit count: " + (int) expt.getHitCount() + ", weight: " + (int) expt.getWeightTotal()); } public void execute(){ try { FileWriter fw = new FileWriter(outName); ChromRegionIterator chroms = new ChromRegionIterator(gen); while(chroms.hasNext()){ NamedRegion currentRegion = chroms.next(); //Split the job up into chunks of 100Mbp for(int x=currentRegion.getStart(); x<=currentRegion.getEnd(); x+=100000000){ int y = x+100000000; if(y>currentRegion.getEnd()){y=currentRegion.getEnd();} Region currSubRegion = new Region(gen, currentRegion.getChrom(), x, y); String BEDhits = expt.getBED_StrandedReads(currSubRegion, '+', 2.0); fw.write(BEDhits); BEDhits = expt.getBED_StrandedReads(currSubRegion, '-', 2.0); fw.write(BEDhits); } } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //keep the number in bounds protected final double inBounds(double x, double min, double max){ if(x<min){return min;} if(x>max){return max;} return x; } protected final int inBounds(int x, int min, int max){ if(x<min){return min;} if(x>max){return max;} return x; } }
package cz.hobrasoft.pdfmu; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparsers; /** * Gets or sets the version of a PDF file * * <p> * Usage: * <ul> * <li>{@code pdfmu version --in in.pdf --out out.pdf --set 1.6}</li> * <li>{@code pdfmu version --in in.pdf --get}</li> * <li>{@code pdfmu version inout.pdf --force}</li> * </ul> * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public class OperationVersion implements Operation { /** * Copies a PDF document, changing its version */ private void setPdfVersion(File outFile, PdfReader inPdfReader, char outPdfVersion) { // Open file output stream FileOutputStream os = null; try { os = new FileOutputStream(outFile); } catch (FileNotFoundException ex) { System.err.println("Could not open the output file: " + ex.getMessage()); } if (os != null) { // Open PDF stamper PdfStamper pdfStamper = null; try { // Set version immediately when opening the stamper pdfStamper = new PdfStamper(inPdfReader, os, outPdfVersion); } catch (DocumentException | IOException ex) { System.err.println("Could not open PDF stamper: " + ex.getMessage()); } System.out.println("The PDF version has been successfully set."); if (pdfStamper != null) { // Close PDF stamper try { pdfStamper.close(); } catch (DocumentException | IOException ex) { System.err.println("Could not close PDF stamper: " + ex.getMessage()); } } } } @Override public void execute(Namespace namespace) { File inFile = namespace.get("in"); // "in" argument is required. // TODO: Lift the requirement here assert inFile != null; System.out.println(String.format("Input PDF document: %s", inFile)); FileInputStream inStream = null; try { inStream = new FileInputStream(inFile); } catch (FileNotFoundException ex) { System.err.println("Input file not found: " + ex.getMessage()); } if (inStream != null) { // PdfReader parses a PDF document PdfReader pdfReader = null; try { pdfReader = new PdfReader(inStream); } catch (IOException e) { System.err.println("Could not open the input PDF document: " + e.getMessage()); } if (pdfReader != null) { // Fetch the PDF version of the input PDF document PdfVersion inVersion = new PdfVersion(pdfReader.getPdfVersion()); System.out.println(String.format("Input PDF document version: %s", inVersion)); if (!namespace.getBoolean("get")) { // Commence to set the PDF version of the output PDF document PdfVersion outVersion = namespace.get("set"); System.out.println(String.format("Desired output PDF version: %s", outVersion)); if (outVersion.compareTo(inVersion) < 0) { // The desired version is lower than the current version. System.err.println(String.format("Cannot lower the PDF version.")); // TODO: Add --force-lower-version flag that enables lowering the version } else { File outFile = namespace.get("out"); if (outFile == null) { System.out.println("--out option not specified; assuming in-place version change"); outFile = inFile; } System.out.println(String.format("Output PDF document: %s", outFile)); if (outFile.exists()) { System.out.println("Output file already exists."); } if (!outFile.exists() || namespace.getBoolean("force")) { // Creating a new file or allowed to overwrite the old one setPdfVersion(outFile, pdfReader, outVersion.toChar()); } else { System.err.println("Set --force flag to overwrite."); } } } else { System.out.println("--get flag is set; no modifications will be made."); } pdfReader.close(); } try { inStream.close(); } catch (IOException ex) { System.err.println("Could not close the input file: " + ex.getMessage()); } } } @Override public Subparser addParser(Subparsers subparsers) { String help = "Set or display version of a PDF document"; String metavarIn = "IN.pdf"; String metavarOut = "OUT.pdf"; String metavarSet = "VERSION"; // Add the subparser Subparser subparser = subparsers.addParser("version") .help(help) .description(help) .defaultHelp(true) .setDefault("command", OperationVersion.class); // Add arguments to the subparser subparser.addArgument("-i", "--in") .type(Arguments.fileType().acceptSystemIn().verifyCanRead()) .help("input PDF document") .required(true) .metavar(metavarIn); subparser.addArgument("-o", "--out") .type(Arguments.fileType().verifyCanCreate()) .help("output PDF document") .nargs("?") .metavar(metavarOut); subparser.addArgument("-s", "--set") .type(PdfVersion.class) .help(String.format("set PDF version to %s", metavarSet)) .nargs("?") .setDefault(new PdfVersion("1.6")) .metavar(metavarSet); subparser.addArgument("-g", "--get") .type(boolean.class) .help(String.format("display version of %s without setting the version", metavarIn)) .action(Arguments.storeTrue()); subparser.addArgument("--force") .help(String.format("overwrite %s if already present", metavarOut)) .type(boolean.class) .action(Arguments.storeTrue()); return subparser; } /** * Represents a PDF version * * <p> * Versions 1.2 to 1.7 are supported. This range corresponds to the versions * supported by iText, as seen in {@link com.itextpdf.text.pdf.PdfWriter} * static fields {@link com.itextpdf.text.pdf.PdfWriter#VERSION_1_2} etc. */ static public class PdfVersion implements Comparable<PdfVersion> { static private Pattern p = Pattern.compile("1\\.(?<charValue>[2-7])"); private char charValue; public PdfVersion(String stringValue) throws IllegalArgumentException { Matcher m = p.matcher(stringValue); if (!m.matches()) { throw new IllegalArgumentException("Invalid or unsupported PDF version; use 1.2 to 1.7"); } String charValueString = m.group("charValue"); assert charValueString.length() == 1; charValue = charValueString.charAt(0); } public PdfVersion(char charValue) throws IllegalArgumentException { if (charValue < '2' || charValue > '7') { throw new IllegalArgumentException("Invalid or unsupported PDF version; use 2 to 7"); } this.charValue = charValue; } @Override public String toString() { return String.format("1.%c", charValue); } /** * Returns the last character of the PDF version * * <p> * This format of PDF version is accepted for example by * {@link com.itextpdf.text.pdf.PdfStamper#PdfStamper(com.itextpdf.text.pdf.PdfReader, OutputStream, char)} * * @return last character of the PDF version */ public char toChar() { return charValue; } @Override public int compareTo(PdfVersion o) { return charValue - o.charValue; } } }
package edu.washington.escience.myriad.parallel; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.washington.escience.myriad.parallel.ipc.ChannelContext; import edu.washington.escience.myriad.parallel.ipc.MessageChannelHandler; import edu.washington.escience.myriad.proto.DataProto.DataMessage; import edu.washington.escience.myriad.proto.TransportProto.TransportMessage; import edu.washington.escience.myriad.proto.TransportProto.TransportMessage.Builder; import edu.washington.escience.myriad.proto.TransportProto.TransportMessage.TransportMessageType; @Sharable public class MasterDataHandler extends SimpleChannelUpstreamHandler implements MessageChannelHandler<TransportMessage> { /** * A simple message wrapper for use in current queue-based master message processing. * */ public static class MessageWrapper { public int senderID; public TransportMessage message; public MessageWrapper(final int senderID, final TransportMessage message) { this.senderID = senderID; this.message = message; } } /** The logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(MasterDataHandler.class.getName()); /** * messageQueue. * */ private final LinkedBlockingQueue<MessageWrapper> messageQueue; /** * constructor. * */ MasterDataHandler(final LinkedBlockingQueue<MessageWrapper> messageQueue) { this.messageQueue = messageQueue; channel2OperatorID = new ConcurrentHashMap<Integer, Long>(); } private final ConcurrentHashMap<Integer, Long> channel2OperatorID; @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { ChannelContext cs = null; ChannelContext.RegisteredChannelContext ecc = null; final Channel channel = e.getChannel(); cs = ChannelContext.getChannelContext(channel); ecc = cs.getRegisteredChannelContext(); final Integer senderID = ecc.getRemoteID(); TransportMessage tm = (TransportMessage) e.getMessage(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("received a message from " + senderID + ": of type " + tm.getType()); } if (tm.getType() == TransportMessageType.DATA) { DataMessage dm = tm.getData(); switch (dm.getType()) { case NORMAL: case EOI: Builder tmB = tm.toBuilder(); tmB.getDataBuilder().setOperatorID(channel2OperatorID.get(channel.getId())); tm = tmB.build(); while (!processMessage(channel, senderID, tm)) { if (LOGGER.isErrorEnabled()) { LOGGER .error("unable to push data for processing. Normally this should not happen. Maybe the input buffer is out of memory."); } } break; case BOS: channel2OperatorID.put(channel.getId(), tm.getData().getOperatorID()); break; case EOS: tmB = tm.toBuilder(); tmB.getDataBuilder().setOperatorID(channel2OperatorID.get(channel.getId())); tm = tmB.build(); channel2OperatorID.remove(channel.getId()); while (!processMessage(channel, senderID, tm)) { if (LOGGER.isErrorEnabled()) { LOGGER .error("unable to push data for processing. Normally this should not happen. Maybe the input buffer is out of memory."); } } break; } } else { if (tm.getType() == TransportMessageType.CONTROL) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Received a control message from : " + senderID + " of type: " + tm.getControl().getType().name()); } } while (!processMessage(channel, senderID, tm)) { if (LOGGER.isErrorEnabled()) { LOGGER .error("unable to push data for processing. Normally this should not happen. Maybe the input buffer is out of memory."); } } } ctx.sendUpstream(e); } @Override public boolean processMessage(final Channel channel, final int remoteID, final TransportMessage message) { final MessageWrapper mw = new MessageWrapper(remoteID, message); return messageQueue.offer(mw); } }
package org.davidmoten.rx.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import java.sql.Time; import java.sql.Timestamp; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.davidmoten.rx.jdbc.annotations.Column; import org.davidmoten.rx.jdbc.annotations.Index; import org.davidmoten.rx.jdbc.annotations.Query; import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; import org.davidmoten.rx.jdbc.pool.DatabaseCreator; import org.davidmoten.rx.jdbc.pool.DatabaseType; import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; import org.davidmoten.rx.jdbc.pool.Pools; import org.davidmoten.rx.jdbc.tuple.Tuple2; import org.davidmoten.rx.jdbc.tuple.Tuple3; import org.davidmoten.rx.jdbc.tuple.Tuple4; import org.davidmoten.rx.jdbc.tuple.Tuple5; import org.davidmoten.rx.jdbc.tuple.Tuple6; import org.davidmoten.rx.jdbc.tuple.Tuple7; import org.davidmoten.rx.jdbc.tuple.TupleN; import org.davidmoten.rx.pool.PoolClosedException; import org.h2.jdbc.JdbcSQLException; import org.hsqldb.jdbc.JDBCBlobFile; import org.hsqldb.jdbc.JDBCClobFile; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.davidmoten.guavamini.Lists; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.Single; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subscribers.TestSubscriber; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DatabaseTest { private static final long FRED_REGISTERED_TIME = 1442515672690L; private static final int NAMES_COUNT_BIG = 5163; private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); private static final int TIMEOUT_SECONDS = 10; private static Database db() { return DatabaseCreator.create(1); } private static Database blocking() { return DatabaseCreator.createBlocking(); } private static Database db(int poolSize) { return DatabaseCreator.create(poolSize); } private static Database big(int poolSize) { return DatabaseCreator.create(poolSize, true, Schedulers.computation()); } @Test public void testSelectUsingQuestionMark() { try (Database db = db()) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingNamedParameterList() { try (Database db = db()) { db.select("select score from person where name=:name") .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingQuestionMarkFlowableParameters() { try (Database db = db()) { db.select("select score from person where name=?") .parameterStream(Flowable.just("FRED", "JOSEPH")) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingQuestionMarkFlowableParametersInLists() { try (Database db = db()) { db.select("select score from person where name=?") .parameterListStream( Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testDrivingSelectWithoutParametersUsingParameterStream() { try (Database db = db()) { db.select("select count(*) from person") .parameters(1, 2, 3) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 3, 3) .assertComplete(); } } @Test public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { try (Database db = db()) { db.select("select score from person where name=? and score = ?") .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { try (Database db = db()) { db.select("select score from person where name=? and score = ?") .parameterListStream( Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { try (Database db = Database.test()) { db .select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectWithFetchSize() { try (Database db = db()) { db.select("select score from person order by name") .fetchSize(2) .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34, 25) .assertComplete(); } } @Test public void testSelectWithFetchSizeZero() { try (Database db = db()) { db.select("select score from person order by name") .fetchSize(0) .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34, 25) .assertComplete(); } } @Test(expected = IllegalArgumentException.class) public void testSelectWithFetchSizeNegative() { try (Database db = db()) { db.select("select score from person order by name") .fetchSize(-1); } } @Test public void testSelectUsingNonBlockingBuilder() { NonBlockingConnectionPool pool = Pools .nonBlocking() .connectionProvider(DatabaseCreator.connectionProvider()) .maxIdleTime(1, TimeUnit.MINUTES) .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) .checkoutRetryInterval(1, TimeUnit.SECONDS) .healthCheck(c -> c.prepareStatement("select 1").execute()) .maxPoolSize(3) .build(); try (Database db = Database.from(pool)) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectSpecifyingHealthCheck() { NonBlockingConnectionPool pool = Pools .nonBlocking() .connectionProvider(DatabaseCreator.connectionProvider()) .maxIdleTime(1, TimeUnit.MINUTES) .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) .checkoutRetryInterval(1, TimeUnit.SECONDS) .healthCheck(DatabaseType.H2) .maxPoolSize(3) .build(); try (Database db = Database.from(pool)) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test(timeout = 40000) public void testSelectUsingNonBlockingBuilderConcurrencyTest() throws InterruptedException, TimeoutException { info(); try { try (Database db = db(3)) { Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); int n = 10000; CountDownLatch latch = new CountDownLatch(n); AtomicInteger count = new AtomicInteger(); for (int i = 0; i < n; i++) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .subscribeOn(scheduler) .toList() .doOnSuccess(x -> { if (!x.equals(Lists.newArrayList(21, 34))) { throw new RuntimeException("run broken"); } else { // log.debug(iCopy + " succeeded"); } }) .doOnSuccess(x -> { count.incrementAndGet(); latch.countDown(); }) .doOnError(x -> latch.countDown()) .subscribe(); } if (!latch.await(20, TimeUnit.SECONDS)) { throw new TimeoutException("timeout"); } assertEquals(n, count.get()); } } finally { debug(); } } @Test(timeout = 5000) public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { debug(); try { try (Database db = db(1)) { Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); int n = 2; CountDownLatch latch = new CountDownLatch(n); AtomicInteger count = new AtomicInteger(); for (int i = 0; i < n; i++) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .subscribeOn(scheduler) .toList() .doOnSuccess(x -> { if (!x.equals(Lists.newArrayList(21, 34))) { throw new RuntimeException("run broken"); } }) .doOnSuccess(x -> { count.incrementAndGet(); latch.countDown(); }) .doOnError(x -> latch.countDown()) .subscribe(); log.info("submitted " + i); } if (!latch.await(5000, TimeUnit.SECONDS)) { throw new TimeoutException("timeout"); } assertEquals(n, count.get()); } } finally { debug(); } } @Test public void testDatabaseClose() { try (Database db = db()) { db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingName() { try (Database db = db()) { db .select("select score from person where name=:name") .parameter("name", "FRED") .parameter("name", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(21, 34) .assertComplete(); } } @Test public void testSelectUsingNameNotGiven() { try (Database db = db()) { db .select("select score from person where name=:name and name<>:name2") .parameter("name", "FRED") .parameter("name", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertError(NamedParameterMissingException.class) .assertNoValues(); } } @Test public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { db() .select("select score from person where name=?") .parameter(Parameter.create("name", "FRED")) .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) .assertNoValues(); } @Test public void testUpdateWithNull() { try (Database db = db()) { db .update("update person set date_of_birth = :dob") .parameter(Parameter.create("dob", null)) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); } } @Test public void testUpdateClobWithNull() { try (Database db = db()) { insertNullClob(db); db .update("update person_clob set document = :doc") .parameter("doc", Database.NULL_CLOB) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateClobWithClob() throws SQLException { try (Database db = db()) { Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); insertNullClob(db); db .update("update person_clob set document = :doc") .parameter("doc", clob) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateClobWithReader() throws FileNotFoundException { try (Database db = db()) { Reader reader = new FileReader(new File("src/test/resources/big.txt")); insertNullClob(db); db .update("update person_clob set document = :doc") .parameter("doc", reader) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateBlobWithBlob() throws SQLException { try (Database db = db()) { Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); insertPersonBlob(db); db .update("update person_blob set document = :doc") .parameter("doc", blob) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateBlobWithNull() { try (Database db = db()) { insertPersonBlob(db); db .update("update person_blob set document = :doc") .parameter("doc", Database.NULL_BLOB) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test(expected = NullPointerException.class) public void testSelectUsingNullNameInParameter() { try (Database db = db()) { db .select("select score from person where name=:name") .parameter(null, "FRED"); } } @Test(expected = IllegalArgumentException.class) public void testSelectUsingNameDoesNotExist() { try (Database db = db()) { db .select("select score from person where name=:name") .parameters("nam", "FRED"); } } @Test(expected = IllegalArgumentException.class) public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { try (Database db = db()) { db .select("select score from person where name=:name") .parameters("FRED", "JOSEPH"); } } @Test public void testSelectTransacted() { try (Database db = db()) { db .select("select score from person where name=?") .parameters("FRED", "JOSEPH") .transacted() .getAs(Integer.class) .doOnNext(tx -> log .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(3) .assertComplete(); } } @Test public void testSelectAutomappedAnnotatedTransacted() { try (Database db = db()) { db .select(Person10.class) .transacted() .valuesOnly() .get().test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(3) .assertComplete(); } } @Test public void testSelectAutomappedTransactedValuesOnly() { try (Database db = db()) { db .select("select name, score from person") .transacted() .valuesOnly() .autoMap(Person2.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(3) .assertComplete(); } } @Test public void testSelectAutomappedTransacted() { try (Database db = db()) { db .select("select name, score from person") .transacted() .autoMap(Person2.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(4) .assertComplete(); } } @Test public void testSelectTransactedTuple2() { try (Database db = db()) { Tx<Tuple2<String, Integer>> t = db .select("select name, score from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); } } @Test public void testSelectTransactedTuple3() { try (Database db = db()) { Tx<Tuple3<String, Integer, String>> t = db .select("select name, score, name from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class, String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); assertEquals("FRED", t.value()._3()); } } @Test public void testSelectTransactedTuple4() { try (Database db = db()) { Tx<Tuple4<String, Integer, String, Integer>> t = db .select("select name, score, name, score from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class, String.class, Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); assertEquals("FRED", t.value()._3()); assertEquals(21, (int) t.value()._4()); } } @Test public void testSelectTransactedTuple5() { try (Database db = db()) { Tx<Tuple5<String, Integer, String, Integer, String>> t = db .select("select name, score, name, score, name from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class, String.class, Integer.class, String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); assertEquals("FRED", t.value()._3()); assertEquals(21, (int) t.value()._4()); assertEquals("FRED", t.value()._5()); } } @Test public void testSelectTransactedTuple6() { try (Database db = db()) { Tx<Tuple6<String, Integer, String, Integer, String, Integer>> t = db .select("select name, score, name, score, name, score from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); assertEquals("FRED", t.value()._3()); assertEquals(21, (int) t.value()._4()); assertEquals("FRED", t.value()._5()); assertEquals(21, (int) t.value()._6()); } } @Test public void testSelectTransactedTuple7() { try (Database db = db()) { Tx<Tuple7<String, Integer, String, Integer, String, Integer, String>> t = db .select("select name, score, name, score, name, score, name from person where name=?") .parameters("FRED") .transacted() .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class, String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values().get(0); assertEquals("FRED", t.value()._1()); assertEquals(21, (int) t.value()._2()); assertEquals("FRED", t.value()._3()); assertEquals(21, (int) t.value()._4()); assertEquals("FRED", t.value()._5()); assertEquals(21, (int) t.value()._6()); assertEquals("FRED", t.value()._7()); } } @Test public void testSelectTransactedTupleN() { try (Database db = db()) { List<Tx<TupleN<Object>>> list = db .select("select name, score from person where name=?") .parameters("FRED") .transacted() .getTupleN() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values(); assertEquals("FRED", list.get(0).value().values().get(0)); assertEquals(21, (int) list.get(0).value().values().get(1)); assertTrue(list.get(1).isComplete()); assertEquals(2, list.size()); } } @Test public void testSelectTransactedCount() { try (Database db = db()) { db .select("select name, score, name, score, name, score, name from person where name=?") .parameters("FRED") .transacted() .count() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(1) .assertComplete(); } } @Test public void testSelectTransactedGetAs() { try (Database db = db()) { db .select("select name from person") .transacted() .getAs(String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(4) .assertComplete(); } } @Test public void testSelectTransactedGetAsOptional() { try (Database db = db()) { List<Tx<Optional<String>>> list = db .select("select name from person where name=?") .parameters("FRED") .transacted() .getAsOptional(String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(2) .assertComplete() .values(); assertTrue(list.get(0).isValue()); assertEquals("FRED", list.get(0).value().get()); assertTrue(list.get(1).isComplete()); } } @Test public void testDatabaseFrom() { Database.from(DatabaseCreator.nextUrl(), 3) .select("select name from person") .getAs(String.class) .count() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertError(JdbcSQLException.class); } @Test public void testSelectTransactedChained() throws Exception { try (Database db = db()) { db .select("select score from person where name=?") .parameters("FRED", "JOSEPH") .transacted() .transactedValuesOnly() .getAs(Integer.class) .doOnNext(tx -> log .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) .flatMap(tx -> tx .select("select name from person where score = ?") .parameter(tx.value()) .valuesOnly() .getAs(String.class)) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues("FRED", "JOSEPH") .assertComplete(); } } @Test public void databaseIsAutoCloseable() { try (Database db = db()) { log.debug(db.toString()); } } private static void println(Object o) { log.debug("{}", o); } @Test public void testSelectChained() { try (Database db = db(1)) { // we can do this with 1 connection only! db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .doOnNext(DatabaseTest::println) .concatMap(score -> { log.info("score={}", score); return db .select("select name from person where score = ?") .parameter(score) .getAs(String.class) .doOnComplete( () -> log.info("completed select where score=" + score)); }) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues("FRED", "JOSEPH") .assertComplete(); } } @Test @SuppressFBWarnings public void testReadMeFragment1() { try (Database db = db()) { db.select("select name from person") .getAs(String.class) .forEach(DatabaseTest::println); } } @Test public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { try (Database db = Database.test()) { db.select("select nam from person") .getAs(String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(SQLSyntaxErrorException.class); } } @Test public void testReadMeFragmentDerbyHealthCheck() { try (Database db = Database.test()) { db.select("select 'a' from sysibm.sysdummy1") .getAs(String.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue("a") .assertComplete(); } } @Test @SuppressFBWarnings public void testTupleSupport() { try (Database db = db()) { db.select("select name, score from person") .getAs(String.class, Integer.class) .forEach(DatabaseTest::println); } } @Test public void testDelayedCallsAreNonBlocking() throws InterruptedException { List<String> list = new CopyOnWriteArrayList<String>(); try (Database db = db(1)) { db.select("select score from person where name=?") .parameter("FRED") .getAs(Integer.class) .doOnNext(x -> Thread.sleep(1000)) .subscribeOn(Schedulers.io()) .subscribe(); Thread.sleep(100); CountDownLatch latch = new CountDownLatch(1); db.select("select score from person where name=?") .parameter("FRED") .getAs(Integer.class) .doOnNext(x -> list.add("emitted")) .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) .doOnNext(x -> latch.countDown()) .subscribe(); list.add("subscribed"); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); assertEquals(Arrays.asList("subscribed", "emitted"), list); } } @Test public void testAutoMapToInterface() { try (Database db = db()) { db .select("select name from person") .autoMap(Person.class) .map(p -> p.name()) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValueCount(3) .assertComplete(); } } @Test public void testAutoMapToInterfaceWithoutAnnotationstsError() { try (Database db = db()) { db .select("select name from person") .autoMap(PersonNoAnnotation.class) .map(p -> p.name()) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(AnnotationsNotFoundException.class); } } @Test public void testAutoMapToInterfaceWithTwoMethods() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person2.class) .firstOrError() .map(Person2::score) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(21) .assertComplete(); } } @Test public void testAutoMapToInterfaceWithExplicitColumnName() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person3.class) .firstOrError() .map(Person3::examScore) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(21) .assertComplete(); } } @Test public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person4.class) .firstOrError() .map(Person4::examScore) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(ColumnNotFoundException.class); } } @Test public void testAutoMapToInterfaceWithIndex() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person5.class) .firstOrError() .map(Person5::examScore) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(21) .assertComplete(); } } @Test public void testAutoMapToInterfaceWithIndexTooLarge() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person6.class) .firstOrError() .map(Person6::examScore) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(ColumnIndexOutOfRangeException.class); } } @Test public void testAutoMapToInterfaceWithIndexTooSmall() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person7.class) .firstOrError() .map(Person7::examScore) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(ColumnIndexOutOfRangeException.class); } } @Test public void testAutoMapWithUnmappableColumnType() { try (Database db = db()) { db .select("select name from person order by name") .autoMap(Person8.class) .map(p -> p.name()) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(ClassCastException.class); } } @Test public void testAutoMapWithMixIndexAndName() { try (Database db = db()) { db .select("select name, score from person order by name") .autoMap(Person9.class) .firstOrError() .map(Person9::score) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(21) .assertComplete(); } } @Test public void testAutoMapWithQueryInAnnotation() { try (Database db = db()) { db.select(Person10.class) .get() .firstOrError() .map(Person10::score) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(21) .assertComplete(); } } @Test @Ignore public void testAutoMapForReadMe() { try (Database db = Database.test()) { db.select(Person10.class) .get(Person10::name) .blockingForEach(DatabaseTest::println); } } @Test(expected = QueryAnnotationMissingException.class) public void testAutoMapWithoutQueryInAnnotation() { try (Database db = db()) { db.select(Person.class); } } @Test public void testSelectWithoutWhereClause() { try (Database db = db()) { Assert.assertEquals(3, (long) db.select("select name from person") .count() .blockingGet()); } } @Test public void testTuple3() { try (Database db = db()) { db .select("select name, score, name from person order by name") .getAs(String.class, Integer.class, String.class) .firstOrError() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete() .assertValue(Tuple3.create("FRED", 21, "FRED")); } } @Test public void testTuple4() { try (Database db = db()) { db .select("select name, score, name, score from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class) .firstOrError() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete() .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); } } @Test public void testTuple5() { try (Database db = db()) { db .select("select name, score, name, score, name from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class) .firstOrError() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); } } @Test public void testTuple6() { try (Database db = db()) { db .select("select name, score, name, score, name, score from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class) .firstOrError() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete() .assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); } } @Test public void testTuple7() { try (Database db = db()) { db .select("select name, score, name, score, name, score, name from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class, String.class) .firstOrError() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete() .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); } } @Test public void testTupleN() { try (Database db = db()) { db .select("select name, score, name from person order by name") .getTupleN() .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertComplete() .assertValue(TupleN.create("FRED", 21, "FRED")); } } @Test public void testHealthCheck() throws InterruptedException { AtomicBoolean once = new AtomicBoolean(true); testHealthCheck(c -> { log.debug("doing health check"); return !once.compareAndSet(true, false); }); } @Test public void testHealthCheckThatThrows() throws InterruptedException { AtomicBoolean once = new AtomicBoolean(true); testHealthCheck(c -> { log.debug("doing health check"); if (!once.compareAndSet(true, false)) return true; else throw new RuntimeException("health check failed"); }); } @Test public void testUpdateOneRow() { try (Database db = db()) { db.update("update person set score=20 where name='FRED'") .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateThreeRows() { try (Database db = db()) { db.update("update person set score=20") .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); } } @Test public void testUpdateWithParameter() { try (Database db = db()) { db.update("update person set score=20 where name=?") .parameter("FRED").counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testUpdateWithParameterTwoRuns() { try (Database db = db()) { db.update("update person set score=20 where name=?") .parameters("FRED", "JOSEPH").counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 1) .assertComplete(); } } @Test public void testUpdateAllWithParameterFourRuns() { try (Database db = db()) { db.update("update person set score=?") .parameters(1, 2, 3, 4) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 3, 3, 3) .assertComplete(); } } @Test public void testUpdateWithBatchSize2() { try (Database db = db()) { db.update("update person set score=?") .batchSize(2) .parameters(1, 2, 3, 4) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 3, 3, 3) .assertComplete(); } } @Test public void testUpdateWithBatchSize3GreaterThanNumRecords() { try (Database db = db()) { db.update("update person set score=?") .batchSize(3) .parameters(1, 2, 3, 4) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 3, 3, 3) .assertComplete(); } } @Test public void testInsert() { try (Database db = db()) { db.update("insert into person(name, score) values(?,?)") .parameters("DAVE", 12, "ANNE", 18) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 1) .assertComplete(); List<Tuple2<String, Integer>> list = db.select("select name, score from person") .getAs(String.class, Integer.class) .toList() .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .blockingGet(); assertTrue(list.contains(Tuple2.create("DAVE", 12))); assertTrue(list.contains(Tuple2.create("ANNE", 18))); } } @Test public void testReturnGeneratedKeys() { try (Database db = db()) { // note is a table with auto increment db.update("insert into note(text) values(?)") .parameters("HI", "THERE") .returnGeneratedKeys() .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 2) .assertComplete(); db.update("insert into note(text) values(?)") .parameters("ME", "TOO") .returnGeneratedKeys() .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 4) .assertComplete(); } } @Test public void testReturnGeneratedKeysDerby() { Database db = DatabaseCreator.createDerby(1); // note is a table with auto increment db.update("insert into note2(text) values(?)") .parameters("HI", "THERE") .returnGeneratedKeys() .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors().assertValues(1, 3) .assertComplete(); db.update("insert into note2(text) values(?)") .parameters("ME", "TOO") .returnGeneratedKeys() .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(5, 7) .assertComplete(); } @Test(expected = IllegalArgumentException.class) public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { try (Database db = db()) { // note is a table with auto increment db.update("insert into note(text) values(?)") .parameters("HI", "THERE") .batchSize(2) .returnGeneratedKeys(); } } @Test public void testTransactedReturnGeneratedKeys() { try (Database db = db()) { // note is a table with auto increment db.update("insert into note(text) values(?)") .parameters("HI", "THERE") .transacted() .returnGeneratedKeys() .valuesOnly() .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 2) .assertComplete(); db.update("insert into note(text) values(?)") .parameters("ME", "TOO") .transacted() .returnGeneratedKeys() .valuesOnly() .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3, 4) .assertComplete(); } } @Test public void testTransactedReturnGeneratedKeys2() { try (Database db = db()) { // note is a table with auto increment Flowable<Integer> a = db.update("insert into note(text) values(?)") .parameters("HI", "THERE") .transacted() .returnGeneratedKeys() .valuesOnly() .getAs(Integer.class); db.update("insert into note(text) values(?)") .parameters("ME", "TOO") .transacted() .returnGeneratedKeys() .valuesOnly() .getAs(Integer.class) .startWith(a) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 2, 3, 4) .assertComplete(); } } @Test public void testUpdateWithinTransaction() { try (Database db = db()) { db .select("select name from person") .transactedValuesOnly() .getAs(String.class) .doOnNext(DatabaseTest::println) .flatMap(tx -> tx .update("update person set score=-1 where name=:name") .batchSize(1) .parameter("name", tx.value()) .valuesOnly() .counts()) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 1, 1) .assertComplete(); } } @Test public void testSelectDependsOnFlowable() { try (Database db = db()) { Flowable<Integer> a = db.update("update person set score=100 where name=?") .parameter("FRED") .counts(); db.select("select score from person where name=?") .parameter("FRED") .dependsOn(a) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(100) .assertComplete(); } } @Test public void testSelectDependsOnObservable() { try (Database db = db()) { Observable<Integer> a = db.update("update person set score=100 where name=?") .parameter("FRED") .counts().toObservable(); db.select("select score from person where name=?") .parameter("FRED") .dependsOn(a) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(100) .assertComplete(); } } @Test public void testSelectDependsOnOnSingle() { try (Database db = db()) { Single<Long> a = db.update("update person set score=100 where name=?") .parameter("FRED") .counts().count(); db.select("select score from person where name=?") .parameter("FRED") .dependsOn(a) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(100) .assertComplete(); } } @Test public void testSelectDependsOnCompletable() { try (Database db = db()) { Completable a = db.update("update person set score=100 where name=?") .parameter("FRED") .counts().ignoreElements(); db.select("select score from person where name=?") .parameter("FRED") .dependsOn(a) .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(100) .assertComplete(); } } @Test public void testUpdateWithinTransactionBatchSize0() { try (Database db = db()) { db .select("select name from person") .transactedValuesOnly() .getAs(String.class) .doOnNext(DatabaseTest::println) .flatMap(tx -> tx .update("update person set score=-1 where name=:name") .batchSize(0) .parameter("name", tx.value()) .valuesOnly() .counts()) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(1, 1, 1) .assertComplete(); } } private static void info() { LogManager.getRootLogger().setLevel(Level.INFO); } private static void debug() { LogManager.getRootLogger().setLevel(Level.INFO); } @Test public void testCreateBig() { info(); big(5).select("select count(*) from person") .getAs(Integer.class) .test().awaitDone(20, TimeUnit.SECONDS) .assertValue(5163) .assertComplete(); debug(); } @Test public void testTxWithBig() { info(); big(1) .select("select name from person") .transactedValuesOnly() .getAs(String.class) .flatMap(tx -> tx .update("update person set score=-1 where name=:name") .batchSize(1) .parameter("name", tx.value()) .valuesOnly() .counts()) .count() .test().awaitDone(20, TimeUnit.SECONDS) .assertValue((long) NAMES_COUNT_BIG) .assertComplete(); debug(); } @Test public void testTxWithBigInputBatchSize2000() { info(); big(1) .select("select name from person") .transactedValuesOnly() .getAs(String.class) .flatMap(tx -> tx .update("update person set score=-1 where name=:name") .batchSize(2000) .parameter("name", tx.value()) .valuesOnly() .counts()) .count() .test().awaitDone(20, TimeUnit.SECONDS) .assertValue((long) NAMES_COUNT_BIG) .assertComplete(); debug(); } @Test public void testInsertNullClobAndReadClobAsString() { try (Database db = db()) { insertNullClob(db); db.select("select document from person_clob where name='FRED'") .getAsOptional(String.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(Optional.<String>empty()) .assertComplete(); } } private static void insertNullClob(Database db) { db.update("insert into person_clob(name,document) values(?,?)") .parameters("FRED", Database.NULL_CLOB) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } @Test public void testClobMethod() { assertEquals(Database.NULL_CLOB, Database.clob(null)); } @Test public void testBlobMethod() { assertEquals(Database.NULL_BLOB, Database.blob(null)); } @Test public void testClobMethodPresent() { assertEquals("a", Database.clob("a")); } @Test public void testBlobMethodPresent() { byte[] b = new byte[1]; assertEquals(b, Database.blob(b)); } @Test public void testDateOfBirthNullableForReadMe() { Database.test() .select("select date_of_birth from person where name='FRED'") .getAsOptional(Instant.class) .blockingForEach(DatabaseTest::println); } @Test public void testInsertNullClobAndReadClobAsTuple2() { try (Database db = db()) { insertNullClob(db); db.select("select document, document from person_clob where name='FRED'") .getAs(String.class, String.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(Tuple2.create(null, null)) .assertComplete(); } } @Test public void testInsertClobAndReadClobAsString() { try (Database db = db()) { db.update("insert into person_clob(name,document) values(?,?)") .parameters("FRED", "some text here") .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); db.select("select document from person_clob where name='FRED'") .getAs(String.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some // text // here") .assertComplete(); } } @Test public void testInsertClobAndReadClobUsingReader() { try (Database db = db()) { db.update("insert into person_clob(name,document) values(?,?)") .parameters("FRED", "some text here") .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); db.select("select document from person_clob where name='FRED'") .getAs(Reader.class) .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue("some text here") .assertComplete(); } } @Test public void testInsertBlobAndReadBlobAsByteArray() { try (Database db = db()) { insertPersonBlob(db); db.select("select document from person_blob where name='FRED'") .getAs(byte[].class) .map(b -> new String(b)) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue("some text here") .assertComplete(); } } private static void insertPersonBlob(Database db) { byte[] bytes = "some text here".getBytes(); db.update("insert into person_blob(name,document) values(?,?)") .parameters("FRED", bytes) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } @Test public void testInsertBlobAndReadBlobAsInputStream() { try (Database db = db()) { byte[] bytes = "some text here".getBytes(); db.update("insert into person_blob(name,document) values(?,?)") .parameters("FRED", new ByteArrayInputStream(bytes)) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); db.select("select document from person_blob where name='FRED'") .getAs(InputStream.class) .map(is -> read(is)) .map(b -> new String(b)) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue("some text here") .assertComplete(); } } private static String read(Reader reader) throws IOException { StringBuffer s = new StringBuffer(); char[] ch = new char[128]; int n = 0; while ((n = reader.read(ch)) != -1) { s.append(ch, 0, n); } reader.close(); return s.toString(); } private static byte[] read(InputStream is) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] b = new byte[128]; int n = 0; while ((n = is.read(b)) != -1) { bytes.write(b, 0, n); } is.close(); return bytes.toByteArray(); } private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException { TestScheduler scheduler = new TestScheduler(); NonBlockingConnectionPool pool = Pools .nonBlocking() .connectionProvider(DatabaseCreator.connectionProvider()) .maxIdleTime(10, TimeUnit.MINUTES) .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) .healthCheck(healthy) .scheduler(scheduler) .maxPoolSize(1) .build(); try (Database db = Database.from(pool)) { TestSubscriber<Integer> ts0 = db.select( "select score from person where name=?") .parameter("FRED") .getAs(Integer.class) .test(); ts0.assertValueCount(0) .assertNotComplete(); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); ts0.assertValueCount(1) .assertComplete(); TestSubscriber<Integer> ts = db.select( "select score from person where name=?") .parameter("FRED") .getAs(Integer.class) .test() .assertValueCount(0); log.debug("done2"); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); Thread.sleep(200); ts.assertValueCount(1); Thread.sleep(200); ts.assertValue(21) .assertComplete(); } } @Test public void testShutdownBeforeUse() { NonBlockingConnectionPool pool = Pools .nonBlocking() .connectionProvider(DatabaseCreator.connectionProvider()) .scheduler(Schedulers.io()) .maxPoolSize(1) .build(); pool.close(); Database.from(pool) .select("select score from person where name=?") .parameter("FRED") .getAs(Integer.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(PoolClosedException.class); } @Test public void testFewerColumnsMappedThanAvailable() { try (Database db = db()) { db.select("select name, score from person where name='FRED'") .getAs(String.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues("FRED") .assertComplete(); } } @Test public void testMoreColumnsMappedThanAvailable() { try (Database db = db()) { db .select("select name, score from person where name='FRED'") .getAs(String.class, Integer.class, String.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoValues() .assertError(MoreColumnsRequestedThanExistException.class); } } @Test public void testSelectTimestamp() { try (Database db = db()) { db .select("select registered from person where name='FRED'") .getAs(Long.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(FRED_REGISTERED_TIME) .assertComplete(); } } @Test public void testSelectTimestampAsDate() { try (Database db = db()) { db .select("select registered from person where name='FRED'") .getAs(Date.class) .map(d -> d.getTime()) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(FRED_REGISTERED_TIME) .assertComplete(); } } @Test public void testSelectTimestampAsInstant() { try (Database db = db()) { db .select("select registered from person where name='FRED'") .getAs(Instant.class) .map(d -> d.toEpochMilli()) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(FRED_REGISTERED_TIME) .assertComplete(); } } @Test public void testUpdateCalendarParameter() { Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); try (Database db = db()) { db.update("update person set registered=?") .parameter(c) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); db.select("select registered from person") .getAs(Long.class) .firstOrError() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(c.getTimeInMillis()) .assertComplete(); } } @Test public void testUpdateTimeParameter() { try (Database db = db()) { Time t = new Time(1234); db.update("update person set registered=?") .parameter(t) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); db.select("select registered from person") .getAs(Long.class) .firstOrError() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1234L) .assertComplete(); } } @Test public void testUpdateTimestampParameter() { try (Database db = db()) { Timestamp t = new Timestamp(1234); db.update("update person set registered=?") .parameter(t) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); db.select("select registered from person") .getAs(Long.class) .firstOrError() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1234L) .assertComplete(); } } @Test public void testUpdateSqlDateParameter() { try (Database db = db()) { java.sql.Date t = new java.sql.Date(1234); db.update("update person set registered=?") .parameter(t) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); db.select("select registered from person") .getAs(Long.class) .firstOrError() .test() .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // TODO make a more accurate comparison using the current TZ .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) .assertComplete(); } } @Test public void testUpdateUtilDateParameter() { try (Database db = db()) { Date d = new Date(1234); db.update("update person set registered=?") .parameter(d) .counts() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(3) .assertComplete(); db.select("select registered from person") .getAs(Long.class) .firstOrError() .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1234L) .assertComplete(); } } @Test public void testUpdateTimestampAsInstant() { try (Database db = db()) { db.update("update person set registered=? where name='FRED'") .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); db.select("select registered from person where name='FRED'") .getAs(Long.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(FRED_REGISTERED_TIME) .assertComplete(); } } @Test public void testUpdateTimestampAsZonedDateTime() { try (Database db = db()) { db.update("update person set registered=? where name='FRED'") .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), ZoneOffset.UTC.normalized())) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); db.select("select registered from person where name='FRED'") .getAs(Long.class) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(FRED_REGISTERED_TIME) .assertComplete(); } } @Test public void testCompleteCompletes() { try (Database db = db(1)) { db .update("update person set score=-3 where name='FRED'") .complete() .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .blockingAwait(); int score = db.select("select score from person where name='FRED'") .getAs(Integer.class) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .blockingFirst(); assertEquals(-3, score); } } @Test public void testComplete() throws InterruptedException { try (Database db = db(1)) { Completable a = db .update("update person set score=-3 where name='FRED'") .complete(); db.update("update person set score=-4 where score = -3") .dependsOn(a) .counts() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(1) .assertComplete(); } } @Test public void testCountsOnlyInTransaction() { try (Database db = db()) { db.update("update person set score = -3") .transacted() .countsOnly() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValues(3) .assertComplete(); } } @Test public void testCountsInTransaction() { try (Database db = db()) { db.update("update person set score = -3") .transacted() .counts() .doOnNext(DatabaseTest::println) .toList() .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 && list.get(1).isComplete() && list.size() == 2) .assertComplete(); } } @Test public void testTx() throws InterruptedException { Database db = db(3); Single<Tx<?>> transaction = db .update("update person set score=-3 where name='FRED'") .transaction(); transaction .doOnDispose(() -> log.debug("disposing")) .doOnSuccess(DatabaseTest::println) .flatMapPublisher(tx -> { log.debug("flatmapping"); return tx .update("update person set score = -4 where score = -3") .countsOnly() .doOnSubscribe(s -> log.debug("subscribed")) .doOnNext(num -> log.debug("num=" + num)); }) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValue(1) .assertComplete(); } @Test public void testTxAfterSelect() { Database db = db(3); Single<Tx<Integer>> transaction = db .select("select score from person where name='FRED'") .transactedValuesOnly() .getAs(Integer.class) .firstOrError(); transaction .doOnDispose(() -> log.debug("disposing")) .doOnSuccess(DatabaseTest::println) .flatMapPublisher(tx -> { log.debug("flatmapping"); return tx .update("update person set score = -4 where score = ?") .parameter(tx.value()) .countsOnly() .doOnSubscribe(s -> log.debug("subscribed")) .doOnNext(num -> log.debug("num=" + num)); }) .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValue(1) .assertComplete(); } @Test public void testSingleFlatMap() { Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) .assertComplete(); } @Test public void testAutomappedInstanceHasMeaningfulToStringMethod() { info(); String s = Database.test() .select("select name, score from person where name=?") .parameterStream(Flowable.just("FRED")) .autoMap(Person2.class) .map(x -> x.toString()) .blockingSingle(); assertEquals("Person2[name=FRED, score=21]", s); } @Test public void testAutomappedEquals() { boolean b = Database.test() .select("select name, score from person where name=?") .parameterStream(Flowable.just("FRED")) .autoMap(Person2.class) .map(x -> x.equals(x)) .blockingSingle(); assertTrue(b); } @Test public void testAutomappedDoesNotEqualNull() { boolean b = Database.test() .select("select name, score from person where name=?") .parameterStream(Flowable.just("FRED")) .autoMap(Person2.class) .map(x -> x.equals(null)) .blockingSingle(); assertFalse(b); } @Test public void testAutomappedDoesNotEqual() { boolean b = Database.test() .select("select name, score from person where name=?") .parameterStream(Flowable.just("FRED")) .autoMap(Person2.class) .map(x -> x.equals(new Object())) .blockingSingle(); assertFalse(b); } @Test public void testAutomappedHashCode() { Person2 p = Database.test() .select("select name, score from person where name=?") .parameterStream(Flowable.just("FRED")) .autoMap(Person2.class) .blockingSingle(); assertTrue(p.hashCode() != 0); } @Test public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { Database.test() .select("select name, score from person where name=?") .parameters("FRED", "FRED") .autoMap(Person2.class) .doOnNext(DatabaseTest::println) .test() .awaitDone(2000, TimeUnit.SECONDS) .assertNoErrors() .assertValueCount(2) .assertComplete(); } @Test public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { Database.test() .select("select name, score from person where name=?") .parameters("FRED", "FRED") .autoMap(Person2.class) .distinct() .doOnNext(DatabaseTest::println) .test() .awaitDone(2000, TimeUnit.SECONDS) .assertNoErrors() .assertValueCount(1) .assertComplete(); } @Test public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { PersonDistinct1 p1 = Database.test() .select("select name, score from person where name=?") .parameters("FRED") .autoMap(PersonDistinct1.class) .blockingFirst(); PersonDistinct2 p2 = Database.test() .select("select name, score from person where name=?") .parameters("FRED") .autoMap(PersonDistinct2.class) .blockingFirst(); assertNotEquals(p1, p2); } @Test public void testAutomappedObjectsWhenDefaultMethodInvoked() { PersonWithDefaultMethod p = Database.test() .select("select name, score from person where name=?") .parameters("FRED") .autoMap(PersonWithDefaultMethod.class) .blockingFirst(); assertEquals("fred", p.nameLower()); } // @Test // public void testDefaultMethod() throws NoSuchMethodException, // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, // "nameLower", // MethodType.methodType(String.class, new Class[] {}), // PersonWithDefaultMethod.class) //// .bindTo(x); @Test(expected = AutomappedInterfaceInaccessibleException.class) public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { PersonWithDefaultMethodNonPublic p = Database.test() .select("select name, score from person where name=?") .parameters("FRED") .autoMap(PersonWithDefaultMethodNonPublic.class) .blockingFirst(); p.nameLower(); } @Test public void testBlockingDatabase() { Database db = blocking(); db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .getAs(Integer.class) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } @Test public void testBlockingDatabaseTransacted() { Database db = blocking(); db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .transactedValuesOnly() .getAs(Integer.class) .map(x -> x.value()) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues(21, 34) .assertComplete(); } @Test public void testBlockingDatabaseTransactedNested() { Database db = blocking(); db.select("select score from person where name=?") .parameters("FRED", "JOSEPH") .transactedValuesOnly() .getAs(Integer.class) .flatMap(tx -> tx.select("select name from person where score=?") .parameter(tx.value()) .valuesOnly() .getAs(String.class)) .test() .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) .assertNoErrors() .assertValues("FRED", "JOSEPH") .assertComplete(); } public interface PersonWithDefaultMethod { @Column String name(); @Column int score(); public default String nameLower() { return name().toLowerCase(); } } interface PersonWithDefaultMethodNonPublic { @Column String name(); @Column int score(); default String nameLower() { return name().toLowerCase(); } } interface PersonDistinct1 { @Column String name(); @Column int score(); } interface PersonDistinct2 { @Column String name(); @Column int score(); } interface Score { @Column int score(); } interface Person { @Column String name(); } interface Person2 { @Column String name(); @Column int score(); } interface Person3 { @Column("name") String fullName(); @Column("score") int examScore(); } interface Person4 { @Column("namez") String fullName(); @Column("score") int examScore(); } interface Person5 { @Index(1) String fullName(); @Index(2) int examScore(); } interface Person6 { @Index(1) String fullName(); @Index(3) int examScore(); } interface Person7 { @Index(1) String fullName(); @Index(0) int examScore(); } interface Person8 { @Column int name(); } interface Person9 { @Column String name(); @Index(2) int score(); } interface PersonNoAnnotation { String name(); } @Query("select name, score from person order by name") interface Person10 { @Column String name(); @Column int score(); } }
package eu.ydp.empiria.player.client.resources; import com.google.gwt.i18n.client.Constants; @SuppressWarnings("PMD") public interface StyleNameConstants extends Constants { @DefaultStringValue("qp-assessment-view") public String QP_ASSESSMENT_VIEW(); @DefaultStringValue("qp-body") public String QP_BODY(); @DefaultStringValue("qp-bookmark-clearable") public String QP_BOOKMARK_CLEARABLE(); @DefaultStringValue("qp-bookmark-popup") public String QP_BOOKMARK_POPUP(); @DefaultStringValue("qp-bookmark-popup-button-cancel") public String QP_BOOKMARK_POPUP_BUTTON_CANCEL(); @DefaultStringValue("qp-bookmark-popup-button-close") public String QP_BOOKMARK_POPUP_BUTTON_CLOSE(); @DefaultStringValue("qp-bookmark-popup-button-delete") public String QP_BOOKMARK_POPUP_BUTTON_DELETE(); @DefaultStringValue("qp-bookmark-popup-button-ok") public String QP_BOOKMARK_POPUP_BUTTON_OK(); @DefaultStringValue("qp-bookmark-popup-buttons-panel") public String QP_BOOKMARK_POPUP_BUTTONS_PANEL(); @DefaultStringValue("qp-bookmark-popup-container-inner") public String QP_BOOKMARK_POPUP_CONTAINER_INNER(); @DefaultStringValue("qp-bookmark-popup-container-inner-inner") public String QP_BOOKMARK_POPUP_CONTAINER_INNER_INNER(); @DefaultStringValue("qp-bookmark-popup-container-outer") public String QP_BOOKMARK_POPUP_CONTAINER_OUTER(); @DefaultStringValue("qp-bookmark-popup-contents") public String QP_BOOKMARK_POPUP_CONTENTS(); @DefaultStringValue("qp-bookmark-popup-glass") public String QP_BOOKMARK_POPUP_GLASS(); @DefaultStringValue("qp-bookmark-popup-title") public String QP_BOOKMARK_POPUP_TITLE(); @DefaultStringValue("qp-bookmark-popup-title-panel") public String QP_BOOKMARK_POPUP_TITLE_PANEL(); @DefaultStringValue("qp-bookmark-selectable") public String QP_BOOKMARK_SELECTABLE(); @DefaultStringValue("qp-bookmark-selected") public String QP_BOOKMARK_SELECTED(); @DefaultStringValue("qp-choice-label") public String QP_CHOICE_LABEL(); @DefaultStringValue("qp-choice-module") public String QP_CHOICE_MODULE(); @DefaultStringValue("qp-choice-option") public String QP_CHOICE_OPTION(); @DefaultStringValue("qp-choice-option-box") public String QP_CHOICE_OPTION_BOX(); @DefaultStringValue("qp-choice-option-container") public String QP_CHOICE_OPTION_CONTAINER(); @DefaultStringValue("qp-choice-option-cover") public String QP_CHOICE_OPTION_COVER(); @DefaultStringValue("qp-connection") public String QP_CONNECTION(); @DefaultStringValue("qp-connection-center-column") public String QP_CONNECTION_CENTER_COLUMN(); @DefaultStringValue("qp-connection-item") public String QP_CONNECTION_ITEM(); @DefaultStringValue("qp-connection-item-content") public String QP_CONNECTION_ITEM_CONTENT(); @DefaultStringValue("qp-connection-item-selected") public String QP_CONNECTION_ITEM_SELECTED(); @DefaultStringValue("qp-connection-item-selection-button") public String QP_CONNECTION_ITEM_SELECTION_BUTTON(); @DefaultStringValue("qp-connection-left-column") public String QP_CONNECTION_LEFT_COLUMN(); @DefaultStringValue("qp-connection-right-column") public String QP_CONNECTION_RIGHT_COLUMN(); @DefaultStringValue("qp-footer") public String QP_FOOTER(); @DefaultStringValue("qp-header") public String QP_HEADER(); @DefaultStringValue("qp-img") public String QP_IMG(); @DefaultStringValue("qp-img-container") public String QP_IMG_CONTAINER(); @DefaultStringValue("qp-img-content") public String QP_IMG_CONTENT(); @DefaultStringValue("qp-img-default") public String QP_IMG_DEFAULT(); @DefaultStringValue("qp-img-description") public String QP_IMG_DESCRIPTION(); @DefaultStringValue("qp-img-explorable") public String QP_IMG_EXPLORABLE(); @DefaultStringValue("qp-img-explorable-image-canvas") public String QP_IMG_EXPLORABLE_IMAGE_CANVAS(); @DefaultStringValue("qp-img-explorable-image-canvas-panel") public String QP_IMG_EXPLORABLE_IMAGE_CANVAS_PANEL(); @DefaultStringValue("qp-img-explorable-image-img-img") public String QP_IMG_EXPLORABLE_IMAGE_IMG_IMG(); @DefaultStringValue("qp-img-explorable-image-img-panel") public String QP_IMG_EXPLORABLE_IMAGE_IMG_PANEL(); @DefaultStringValue("qp-img-explorable-image-img-window") public String QP_IMG_EXPLORABLE_IMAGE_IMG_WINDOW(); @DefaultStringValue("qp-img-explorable-image-panel") public String QP_IMG_EXPLORABLE_IMAGE_PANEL(); @DefaultStringValue("qp-img-explorable-toolbox") public String QP_IMG_EXPLORABLE_TOOLBOX(); @DefaultStringValue("qp-img-explorable-window") public String QP_IMG_EXPLORABLE_WINDOW(); @DefaultStringValue("qp-img-explorable-zoomin") public String QP_IMG_EXPLORABLE_ZOOMIN(); @DefaultStringValue("qp-img-explorable-zoomout") public String QP_IMG_EXPLORABLE_ZOOMOUT(); @DefaultStringValue("qp-img-labelled-canvas") public String QP_IMG_LABELLED_CANVAS(); @DefaultStringValue("qp-img-labelled-image") public String QP_IMG_LABELLED_IMAGE(); @DefaultStringValue("qp-img-labelled-panel") public String QP_IMG_LABELLED_PANEL(); @DefaultStringValue("qp-img-labelled-text") public String QP_IMG_LABELLED_TEXT(); @DefaultStringValue("qp-img-labelled-text-panel") public String QP_IMG_LABELLED_TEXT_PANEL(); @DefaultStringValue("qp-img-title") public String QP_IMG_TITLE(); @DefaultStringValue("qp-info") public String QP_INFO(); @DefaultStringValue("qp-info-content") public String QP_INFO_CONTENT(); @DefaultStringValue("qp-info-text") public String QP_INFO_TEXT(); @DefaultStringValue("qp-item-title") public String QP_ITEM_TITLE(); @DefaultStringValue("qp-item-title-index") public String QP_ITEM_TITLE_INDEX(); @DefaultStringValue("qp-item-title-text") public String QP_ITEM_TITLE_TEXT(); @DefaultStringValue("qp-link") public String QP_LINK(); @DefaultStringValue("qp-link-content") public String QP_LINK_CONTENT(); @DefaultStringValue("qp-link-over") public String QP_LINK_OVER(); @DefaultStringValue("qp-markanswsers-button-correct") public String QP_MARKANSWERS_BUTTON_CORRECT(); @DefaultStringValue("qp-markanswsers-button-inactive") public String QP_MARKANSWERS_BUTTON_INACTIVE(); @DefaultStringValue("qp-markanswsers-button-none") public String QP_MARKANSWERS_BUTTON_NONE(); @DefaultStringValue("qp-markanswsers-button-wrong") public String QP_MARKANSWERS_BUTTON_WRONG(); @DefaultStringValue("qp-markanswsers-label-correct") public String QP_MARKANSWERS_LABEL_CORRECT(); @DefaultStringValue("qp-markanswsers-label-inactive") public String QP_MARKANSWERS_LABEL_INACTIVE(); @DefaultStringValue("qp-markanswsers-label-none") public String QP_MARKANSWERS_LABEL_NONE(); @DefaultStringValue("qp-markanswsers-label-wrong") public String QP_MARKANSWERS_LABEL_WRONG(); @DefaultStringValue("qp-markanswsers-marker-correct") public String QP_MARKANSWERS_MARKER_CORRECT(); @DefaultStringValue("qp-markanswsers-marker-inactive") public String QP_MARKANSWERS_MARKER_INACTIVE(); @DefaultStringValue("qp-markanswsers-marker-none") public String QP_MARKANSWERS_MARKER_NONE(); @DefaultStringValue("qp-markanswsers-marker-wrong") public String QP_MARKANSWERS_MARKER_WRONG(); @DefaultStringValue("qp-math-choice-popup-option-empty") public String QP_MATH_CHOICE_POPUP_OPTION_EMPTY(); @DefaultStringValue("qp-mathinteraction") public String QP_MATHINTERACTION(); @DefaultStringValue("qp-mathinteraction-gaps") public String QP_MATHINTERACTION_GAPS(); @DefaultStringValue("qp-mathinteraction-inner") public String QP_MATHINTERACTION_INNER(); @DefaultStringValue("qp-media-center-progress-button") public String QP_MEDIA_CENTER_PROGRESS_BUTTON(); @DefaultStringValue("qp-media-currenttime") public String QP_MEDIA_CURRENTTIME(); @DefaultStringValue("qp-media-description") public String QP_MEDIA_DESCRIPTION(); @DefaultStringValue("qp-media-fullscreen-button") public String QP_MEDIA_FULLSCREEN_BUTTON(); @DefaultStringValue("qp-media-fullscreen-container") public String QP_MEDIA_FULLSCREEN_CONTAINER(); @DefaultStringValue("qp-media-fullscreen-controls") public String QP_MEDIA_FULLSCREEN_CONTROLS(); @DefaultStringValue("qp-media-mute") public String QP_MEDIA_MUTE(); @DefaultStringValue("qp-media-play-pause") public String QP_MEDIA_PLAY_PAUSE(); @DefaultStringValue("qp-media-positioninstream") public String QP_MEDIA_POSITIONINSTREAM(); @DefaultStringValue("qp-media-progressbar") public String QP_MEDIA_PROGRESSBAR(); @DefaultStringValue("qp-media-text-track") public String QP_MEDIA_TEXT_TRACK(); @DefaultStringValue("qp-media-title") public String QP_MEDIA_TITLE(); @DefaultStringValue("qp-media-totaltime") public String QP_MEDIA_TOTALTIME(); @DefaultStringValue("qp-media-volume-scrollbar") public String QP_MEDIA_VOLUME_SCROLLBAR(); @DefaultStringValue("qp-media-volume-scrollbar-button") public String QP_MEDIA_VOLUME_SCROLLBAR_BUTTON(); @DefaultStringValue("qp-page") public String QP_PAGE(); @DefaultStringValue("qp-page-content") public String QP_PAGE_CONTENT(); @DefaultStringValue("qp-page-error") public String QP_PAGE_ERROR(); @DefaultStringValue("qp-page-error-text") public String QP_PAGE_ERROR_TEXT(); @DefaultStringValue("qp-page-in-page") public String QP_PAGE_IN_PAGE(); @DefaultStringValue("qp-page-item") public String QP_PAGE_ITEM(); @DefaultStringValue("qp-page-next") public String QP_PAGE_NEXT(); @DefaultStringValue("qp-page-preloader") public String QP_PAGE_PRELOADER(); @DefaultStringValue("qp-page-prev") public String QP_PAGE_PREV(); @DefaultStringValue("qp-page-selected") public String QP_PAGE_SELECTED(); @DefaultStringValue("qp-page-title") public String QP_PAGE_TITLE(); @DefaultStringValue("qp-page-unselected") public String QP_PAGE_UNSELECTED(); @DefaultStringValue("qp-player") public String QP_PLAYER(); @DefaultStringValue("qp-player-body") public String QP_PLAYER_BODY(); @DefaultStringValue("qp-player-footer") public String QP_PLAYER_FOOTER(); @DefaultStringValue("qp-player-header") public String QP_PLAYER_HEADER(); @DefaultStringValue("qp-prompt") public String QP_PROMPT(); @DefaultStringValue("qp-report") public String QP_REPORT(); @DefaultStringValue("qp-report-cell") public String QP_REPORT_CELL(); @DefaultStringValue("qp-report-table") public String QP_REPORT_TABLE(); @DefaultStringValue("qp-report-table-row") public String QP_REPORT_TABLE_ROW(); @DefaultStringValue("qp-resultpage-items") public String QP_RESULTPAGE_ITEMS(); @DefaultStringValue("qp-resultpage-percents") public String QP_RESULTPAGE_PERCENTS(); @DefaultStringValue("qp-resultpage-points") public String QP_RESULTPAGE_POINTS(); @DefaultStringValue("qp-resultpage-score") public String QP_RESULTPAGE_SCORE(); @DefaultStringValue("qp-resultpage-time") public String QP_RESULTPAGE_TIME(); @DefaultStringValue("qp-selection-choice") public String QP_SELECTION_CHOICE(); @DefaultStringValue("qp-selection-item") public String QP_SELECTION_ITEM(); @DefaultStringValue("qp-selection-item-correct") public String QP_SELECTION_ITEM_CORRECT(); @DefaultStringValue("qp-selection-item-label") public String QP_SELECTION_ITEM_LABEL(); @DefaultStringValue("qp-selection-item-none") public String QP_SELECTION_ITEM_NONE(); @DefaultStringValue("qp-selection-item-wrong") public String QP_SELECTION_ITEM_WRONG(); @DefaultStringValue("qp-simpletext") public String QP_SIMPLETEXT(); @DefaultStringValue("qp-simulation") public String QP_SIMULATION(); @DefaultStringValue("qp-slideshow") public String QP_SLIDESHOW(); @DefaultStringValue("qp-slideshow-button-next") public String QP_SLIDESHOW_BUTTON_NEXT(); @DefaultStringValue("qp-slideshow-button-panel") public String QP_SLIDESHOW_BUTTON_PANEL(); @DefaultStringValue("qp-slideshow-button-pause") public String QP_SLIDESHOW_BUTTON_PAUSE(); @DefaultStringValue("qp-slideshow-button-play") public String QP_SLIDESHOW_BUTTON_PLAY(); @DefaultStringValue("qp-slideshow-button-previous") public String QP_SLIDESHOW_BUTTON_PREVIOUS(); @DefaultStringValue("qp-slideshow-button-stop") public String QP_SLIDESHOW_BUTTON_STOP(); @DefaultStringValue("qp-slideshow-slide-image") public String QP_SLIDESHOW_SLIDE_IMAGE(); @DefaultStringValue("qp-slideshow-slide-image-panel") public String QP_SLIDESHOW_SLIDE_IMAGE_PANEL(); @DefaultStringValue("qp-slideshow-slide-narration-panel") public String QP_SLIDESHOW_SLIDE_NARRATION_PANEL(); @DefaultStringValue("qp-slideshow-slide-panel") public String QP_SLIDESHOW_SLIDE_PANEL(); @DefaultStringValue("qp-slideshow-slide-title-panel") public String QP_SLIDESHOW_SLIDE_TITLE_PANEL(); @DefaultStringValue("qp-slideshow-slides-panel") public String QP_SLIDESHOW_SLIDES_PANEL(); @DefaultStringValue("qp-slideshow-title-panel") public String QP_SLIDESHOW_TITLE_PANEL(); @DefaultStringValue("qp-summary") public String QP_SUMMARY(); @DefaultStringValue("qp-table") public String QP_TABLE(); @DefaultStringValue("qp-table-cell") public String QP_TABLE_CELL(); @DefaultStringValue("qp-table-table") public String QP_TABLE_TABLE(); @DefaultStringValue("qp-text") public String QP_TEXT(); @DefaultStringValue("qp-text-inline") public String QP_TEXT_INLINE(); @DefaultStringValue("qp-text-textentry") public String QP_TEXT_TEXTENTRY(); @DefaultStringValue("qp-text-textentry-content") public String QP_TEXT_TEXTENTRY_CONTENT(); @DefaultStringValue("qp-text-textentry-correct") public String QP_TEXT_TEXTENTRY_CORRECT(); @DefaultStringValue("qp-text-textentry-none") public String QP_TEXT_TEXTENTRY_NONE(); @DefaultStringValue("qp-text-textentry-prefix") public String QP_TEXT_TEXTENTRY_PREFIX(); @DefaultStringValue("qp-text-textentry-sufix") public String QP_TEXT_TEXTENTRY_SUFIX(); @DefaultStringValue("qp-text-textentry-wrong") public String QP_TEXT_TEXTENTRY_WRONG(); @DefaultStringValue("qp-textinteraction") public String QP_TEXTINTERACTION(); @DefaultStringValue("qp-toc") public String QP_TOC(); @DefaultStringValue("qp-toc-item-title") public String QP_TOC_ITEM_TITLE(); @DefaultStringValue("qp-toc-item-title-hover") public String QP_TOC_ITEM_TITLE_HOVER(); @DefaultStringValue("qp-toc-items") public String QP_TOC_ITEMS(); @DefaultStringValue("qp-toc-title") public String QP_TOC_TITLE(); }
package org.jsapar.schema; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringWriter; import org.jsapar.JSaParException; import org.jsapar.Line; import org.jsapar.StringCell; import org.jsapar.input.LineErrorEvent; import org.jsapar.input.LineParsedEvent; import org.jsapar.input.ParseException; import org.jsapar.input.ParsingEventListener; import org.junit.Test; public class CSVSchemaLineTest { boolean foundError=false; private class NullParsingEventListener implements ParsingEventListener { public void lineErrorEvent(LineErrorEvent event) throws ParseException { } public void lineParsedEvent(LineParsedEvent event) throws JSaParException { } } @Test public final void testCSVSchemaLine() { CsvSchemaLine schemaLine = new CsvSchemaLine(); assertEquals("", schemaLine.getLineType()); assertEquals("", schemaLine.getLineTypeControlValue()); } @Test public final void testCSVSchemaLine_String() { CsvSchemaLine schemaLine = new CsvSchemaLine("LineType"); assertEquals("LineType", schemaLine.getLineType()); assertEquals("LineType", schemaLine.getLineTypeControlValue()); } @Test public void testBuild() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); String sLine = "Jonas;Stenberg;Hemvgen 19;111 22;Stockholm"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); } }); assertEquals(true, rc); } @Test public void testBuild_2byte_unicode() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator("\uFFD0"); String sLine = "Jonas\uFFD0Stenberg\uFFD0Hemvgen 19\uFFD0111 22\uFFD0Stockholm"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); } }); assertEquals(true, rc); } @Test public void testBuild_quoted() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;\"Hemvgen ;19\";111 22;Stockholm"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals(5, line.getNumberOfCells()); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); assertEquals("Hemvgen ;19", line.getCell(2).getStringValue()); assertEquals("111 22", line.getCell(3).getStringValue()); assertEquals("Stockholm", line.getCell(4).getStringValue()); } }); assertEquals(true, rc); } @Test public void testBuild_quoted_last() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;\"Hemvgen ;19\""; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals(3, line.getNumberOfCells()); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); assertEquals("Hemvgen ;19", line.getCell(2).getStringValue()); } }); assertEquals(true, rc); } @Test public void testBuild_quoted_last_cellsep() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;\"Hemvgen ;19\";"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals(3, line.getNumberOfCells()); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); assertEquals("Hemvgen ;19", line.getCell(2).getStringValue()); } }); assertEquals(true, rc); } @Test public void testBuild_quoted_missing_end() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;\"Hemvgen ;19;111 22;Stockholm"; try { @SuppressWarnings("unused") boolean rc = schemaLine.parse(1, sLine, new NullParsingEventListener()); } catch (ParseException e) { return; } fail("Should throw ParseException for missing end quote"); } @Test public void testBuild_quoted_miss_placed_start() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;H\"emvgen ;19\";111 22;Stockholm"; try { @SuppressWarnings("unused") boolean rc = schemaLine.parse(1, sLine, new NullParsingEventListener()); } catch (ParseException e) { return; } fail("Should throw ParseException for miss-placed quote"); } @Test public void testBuild_quoted_miss_placed_end() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setQuoteChar('\"'); String sLine = "Jonas;Stenberg;\"Hemvgen ;1\"9;111 22;Stockholm"; try { @SuppressWarnings("unused") boolean rc = schemaLine.parse(1, sLine, new NullParsingEventListener()); } catch (ParseException e) { return; } fail("Should throw ParseException for miss-placed quote"); } @Test public void testBuild_withNames() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); String sLine = "Jonas;-)Stenberg"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { // TODO Auto-generated method stub } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Stenberg", line.getCell(1).getStringValue()); assertEquals("First Name", line.getCell(0).getName()); assertEquals("Last Name", line.getCell(1).getName()); } }); assertEquals(true, rc); } @Test public void testBuild_withDefault() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); CsvSchemaCell happyCell = new CsvSchemaCell("Happy"); happyCell.setDefaultValue("yes"); schemaLine.addSchemaCell(happyCell); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); String sLine = "Jonas;-);-)Stenberg"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { // TODO Auto-generated method stub } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Jonas", line.getStringCellValue("First Name")); assertEquals("Stenberg", line.getCell(2).getStringValue()); assertEquals("yes", line.getStringCellValue("Happy")); assertEquals("First Name", line.getCell(0).getName()); assertEquals("Last Name", line.getCell(2).getName()); } }); assertEquals(true, rc); } @Test public void testBuild_default_and_mandatory() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); CsvSchemaCell happyCell = new CsvSchemaCell("Happy"); happyCell.setDefaultValue("yes"); happyCell.setMandatory(true); schemaLine.addSchemaCell(happyCell); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); String sLine = "Jonas;-);-)Stenberg"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { assertEquals("Happy", event.getCellParseError().getCellName()); foundError = true; } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Jonas", line.getStringCellValue("First Name")); assertEquals("Stenberg", line.getCell(2).getStringValue()); assertEquals("yes", line.getStringCellValue("Happy")); assertEquals("First Name", line.getCell(0).getName()); assertEquals("Last Name", line.getCell(2).getName()); } }); assertEquals(true, rc); assertEquals(true, foundError); } @Test public void testBuild_withDefaultLast() throws JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); CsvSchemaCell happyCell = new CsvSchemaCell("Happy"); happyCell.setDefaultValue("yes"); schemaLine.addSchemaCell(happyCell); String sLine = "Jonas;-)Stenberg"; boolean rc = schemaLine.parse(1, sLine, new ParsingEventListener() { @Override public void lineErrorEvent(LineErrorEvent event) throws ParseException { // TODO Auto-generated method stub } @Override public void lineParsedEvent(LineParsedEvent event) throws JSaParException { Line line = event.getLine(); assertEquals("Jonas", line.getCell(0).getStringValue()); assertEquals("Jonas", line.getStringCellValue("First Name")); assertEquals("Stenberg", line.getCell(1).getStringValue()); assertEquals("yes", line.getStringCellValue("Happy")); assertEquals("First Name", line.getCell(0).getName()); assertEquals("Last Name", line.getCell(1).getName()); } }); assertEquals(true, rc); } @Test public void testOutput() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); Line line = new Line(); line.addCell(new StringCell("First Name", "Jonas")); line.addCell(new StringCell("Last Name", "Stenberg")); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas;-)Stenberg", writer.toString()); } @Test public void testOutput_2byte_unicode() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator("\uFFD0"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); Line line = new Line(); line.addCell(new StringCell("First Name", "Jonas")); line.addCell(new StringCell("Last Name", "Stenberg")); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas\uFFD0Stenberg", writer.toString()); } @Test public void testOutput_not_found_in_line() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Shoe size")); Line line = new Line(); line.addCell(new StringCell("First Name", "Jonas")); line.addCell(new StringCell("Last Name", "Stenberg")); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas;-)Stenberg;-)", writer.toString()); } @Test public void testOutput_null_value() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Shoe size")); Line line = new Line(); line.addCell(new StringCell("First Name", "Jonas")); line.addCell(new StringCell("Last Name", "Stenberg")); line.addCell(new StringCell("Shoe size", null)); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas;-)Stenberg;-)", writer.toString()); } @Test public void testOutput_reorder() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); schemaLine.setCellSeparator(";"); Line line = new Line(); line.addCell(new StringCell("Last Name", "Stenberg")); line.addCell(new StringCell("First Name", "Jonas")); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas;Stenberg", writer.toString()); } @Test public void testOutput_default() throws IOException, JSaParException { CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); schemaLine.addSchemaCell(new CsvSchemaCell("First Name")); CsvSchemaCell lastNameSchema = new CsvSchemaCell("Last Name"); lastNameSchema.setDefaultValue("Svensson"); schemaLine.addSchemaCell(lastNameSchema); Line line = new Line(); line.addCell(new StringCell("First Name", "Jonas")); StringWriter writer = new StringWriter(); schemaLine.output(line, writer); assertEquals("Jonas;-)Svensson", writer.toString()); } @Test public void testGetSchemaCell(){ CsvSchemaLine schemaLine = new CsvSchemaLine(1); schemaLine.setCellSeparator(";-)"); CsvSchemaCell cell1 = new CsvSchemaCell("First Name"); schemaLine.addSchemaCell(cell1); schemaLine.addSchemaCell(new CsvSchemaCell("Last Name")); assertNull(schemaLine.getSchemaCell("Does not exist")); assertSame(cell1, schemaLine.getSchemaCell("First Name")); } }
package org.pentaho.ui.xul.swt.tags; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.ICellEditorListener; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.TreeViewerEditor; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.IShellProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TreeColumn; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.DefaultBinding; import org.pentaho.ui.xul.binding.InlineBindingExpression; import org.pentaho.ui.xul.components.XulTreeCell; import org.pentaho.ui.xul.components.XulTreeCol; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.containers.XulTreeChildren; import org.pentaho.ui.xul.containers.XulTreeCols; import org.pentaho.ui.xul.containers.XulTreeItem; import org.pentaho.ui.xul.containers.XulTreeRow; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swt.AbstractSwtXulContainer; import org.pentaho.ui.xul.swt.TableSelection; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeTextCellEditor; import org.pentaho.ui.xul.util.ColumnType; import org.pentaho.ui.xul.util.TreeCellEditor; import org.pentaho.ui.xul.util.TreeCellRenderer; public class SwtTree extends AbstractSwtXulContainer implements XulTree { // Tables and trees // share so much of the same API, I wrapped their common methods // into an interface (TabularWidget) and set the component to two // separate member variables here so that I don't have to reference // them separately. private static final Log logger = LogFactory.getLog(SwtTree.class); protected XulTreeCols columns = null; protected XulTreeChildren rootChildren = null; protected XulComponent parentComponent = null; private Object data = null; private boolean disabled = false; private boolean enableColumnDrag = false; private boolean editable = false; private String onedit; private String onSelect = null; private int rowsToDisplay = 0; private TableSelection selType = TableSelection.SINGLE; private boolean isHierarchical = false; private ColumnType[] currentColumnTypes = null; private int activeRow = -1; private int activeColumn = -1; private XulDomContainer domContainer; private TableViewer table; private TreeViewer tree; private int selectedIndex = -1; protected boolean controlDown; private int[] selectedRows; public SwtTree(Element self, XulComponent parent, XulDomContainer container, String tagName) { super(tagName); this.parentComponent = parent; // According to XUL spec, in order for a hierarchical tree to be rendered, a // primary column must be identified AND at least one treeitem must be // listed as a container. // Following code does not work with the current instantiation routine. When // transitioned to onDomReady() instantiation this should work. domContainer = container; } @Override public void layout() { XulComponent primaryColumn = this .getElementByXPath("//treecol[@primary='true']"); XulComponent isaContainer = this .getElementByXPath("treechildren/treeitem[@container='true']"); isHierarchical = (primaryColumn != null) || (isaContainer != null); if (isHierarchical) { int style = (this.selType == TableSelection.MULTIPLE) ? SWT.MULTI : SWT.None; tree = new TreeViewer((Composite) parentComponent.getManagedObject(), style); setManagedObject(tree); } else { table = new TableViewer((Composite) parentComponent.getManagedObject(), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); setManagedObject(table); } if (isHierarchical) { setupTree(); } else { setupTable(); } this.initialized = true; } private void setupTree() { tree.setCellEditors(new CellEditor[]{new XulTreeTextCellEditor(tree.getTree())}); tree.setCellModifier(new XulTreeColumnModifier(this)); tree.setLabelProvider(new XulTreeLabelProvider(this)); tree.setContentProvider(new XulTreeContentProvider(this)); tree.setInput(this); tree.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); tree.setColumnProperties(new String[] { "0" }); //TreeViewerColumn tc = new TreeViewerColumn(tree, SWT.LEFT); TreeViewerEditor.create(tree, new ColumnViewerEditorActivationStrategy(tree){ @Override protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) { return super.isEditorActivationEvent(event); } }, ColumnViewerEditor.DEFAULT); tree.getTree().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = true; break; case SWT.ESC: // End editing session tree.getTree().deselectAll(); setSelectedRows(new int[]{}); break; } } @Override public void keyReleased(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = false; break; } } }); // Add a focus listener to clear the contol down selector tree.getTree().addFocusListener(new FocusListener(){ public void focusGained(FocusEvent arg0) {} public void focusLost(FocusEvent arg0) { if(tree.getCellEditors()[0].isActivated() == false){ SwtTree.this.controlDown = false; } } }); tree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { // if the selection is empty clear the label if (event.getSelection().isEmpty()) { SwtTree.this.setSelectedIndex(-1); return; } if (event.getSelection() instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); int[] selected = new int[selection.size()]; List selectedItems = new ArrayList(); int i=0; for(Object o : selection.toArray()){ XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(),getRootChildren(), selectedItem); selected[i++] = b.curPos; selectedItems.add(b.selectedItem); } if(selected.length == 0){ setSelectedIndex(-1); } else { setSelectedIndex(selected[0]); } int[] selectedRows = null; if(SwtTree.this.controlDown && Arrays.equals(selected, selectedRows) && tree.getCellEditors()[0].isActivated() == false){ tree.getTree().deselectAll(); selectedRows = new int[]{}; } else { selectedRows = selected; } changeSupport.firePropertyChange("selectedRows",null, selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); } } }); } private class SearchBundle { int curPos; boolean found; Object selectedItem; } private SearchBundle findSelectedIndex(SearchBundle bundle, XulTreeChildren children, XulTreeItem selectedItem) { for (XulComponent c : children.getChildNodes()) { if (c == selectedItem) { bundle.found = true; if(elements != null){ bundle.selectedItem = findSelectedTreeItem(bundle.curPos); } return bundle; } bundle.curPos++; if (c.getChildNodes().size() > 1) { SearchBundle b = findSelectedIndex(bundle, (XulTreeChildren) c .getChildNodes().get(1), selectedItem); if (b.found) { return b; } } } return bundle; } private Object findSelectedTreeItem(int pos){ if(this.isHierarchical && this.elements != null){ if(elements == null || elements.size() == 0){ return null; } String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get"+(property.substring(0,1).toUpperCase() + property.substring(1)); if (pos == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(pos)); return tuple != null ? tuple.selectedItem : null; } return null; } private void setupTable() { table.setContentProvider(new XulTableContentProvider(this)); table.setLabelProvider(new XulTableColumnLabelProvider(this)); table.setCellModifier(new XulTableColumnModifier(this)); Table baseTable = table.getTable(); baseTable.setLayoutData(new GridData(GridData.FILL_BOTH)); setupColumns(); table.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf( selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i=0; for(Iterator it = selection.iterator(); it.hasNext();){ Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } changeSupport.firePropertyChange("selectedRows",null, selectedRows); Collection selectedItems = findSelectedTableRows(selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); } }); // Turn on the header and the lines baseTable.setHeaderVisible(true); baseTable.setLinesVisible(true); table.setInput(this); final Composite parentComposite = ((Composite) parentComponent .getManagedObject()); parentComposite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { resizeColumns(); } }); table.getTable().setEnabled(! this.disabled); table.refresh(); } private Collection findSelectedTableRows(int[] selectedRows){ if(elements == null){ return Collections.emptyList(); } List selectedItems = new ArrayList(); for(int i=0; i<selectedRows.length; i++){ if(selectedRows[i] >= 0 && selectedRows[i] < elements.size()){ selectedItems.add(elements.toArray()[selectedRows[i]]); } } return selectedItems; } private void resizeColumns(){ final Composite parentComposite = ((Composite) parentComponent .getManagedObject()); Rectangle area = parentComposite.getClientArea(); Point preferredSize = table.getTable().computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width - 2 * table.getTable().getBorderWidth(); if (preferredSize.y > area.height + table.getTable().getHeaderHeight()) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getTable().getVerticalBar().getSize(); width -= vBarSize.x; } width -= 20; double totalFlex = 0; for (XulComponent col : getColumns().getChildNodes()) { totalFlex += ((XulTreeCol) col).getFlex(); } int colIdx = 0; for (XulComponent col : getColumns().getChildNodes()) { if(colIdx >= table.getTable().getColumnCount()){ break; } TableColumn c = table.getTable().getColumn(colIdx); int colFlex = ((XulTreeCol) col).getFlex(); if (totalFlex == 0) { c.setWidth(Math.round(width / getColumns().getColumnCount())); } else if (colFlex > 0) { c.setWidth(Integer.parseInt("" + Math.round(width * (colFlex / totalFlex)))); } colIdx++; } } private void setSelectedIndex(int idx) { this.selectedIndex = idx; changeSupport.firePropertyChange("selectedRows", null, new int[] { idx }); if (this.onSelect != null) { invoke(this.onSelect, new Object[] { new Integer(idx) }); } } private void createColumnTypesSnapshot(){ if(this.columns.getChildNodes().size() > 0){ Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); currentColumnTypes = new ColumnType[xulTreeColArray.length]; for(int i = 0; i < xulTreeColArray.length; i++){ currentColumnTypes[i] = ColumnType.valueOf(((XulTreeCol)xulTreeColArray[i]).getType()); } } else { // Create an empty array to indicate that it has been processed, but contains 0 columns currentColumnTypes = new ColumnType[0]; } } private boolean columnsNeedUpdate(){ // Differing number of columsn if(table.getTable().getColumnCount() != this.columns.getColumnCount()){ return true; } // First run, always update if(currentColumnTypes == null){ return true; } // Column Types have changed Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); for(int i = 0; i < xulTreeColArray.length; i++){ if(!currentColumnTypes[i].toString().equalsIgnoreCase(((XulTreeCol)xulTreeColArray[i]).getType())){ // A column has changed its type. Columns need updating return true; } } // Columns have not changed and do not need updating return false; } private void setupColumns() { if(columnsNeedUpdate()){ while(table.getTable().getColumnCount() > 0){ table.getTable().getColumn(0).dispose(); } // Add Columns for (XulComponent col : this.columns.getChildNodes()) { TableColumn tc = new TableColumn(table.getTable(), SWT.LEFT); String lbl = ((XulTreeCol) col).getLabel(); tc.setText(lbl != null ? lbl : ""); //$NON-NLS-1$ } // Pack the columns for (int i = 0; i < table.getTable().getColumnCount(); i++) { table.getTable().getColumn(i).pack(); } } if (table.getCellEditors() != null) { for (int i = 0; i < table.getCellEditors().length; i++) { table.getCellEditors()[i].dispose(); } } CellEditor[] editors = new CellEditor[this.columns.getChildNodes().size()]; String[] names = new String[getColumns().getColumnCount()]; int i = 0; for (XulComponent c : this.columns.getChildNodes()) { XulTreeCol col = (XulTreeCol) c; final int colIdx = i; CellEditor editor; ColumnType type = col.getColumnType(); switch (type) { case CHECKBOX: editor = new CheckboxCellEditor(table.getTable()); break; case COMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}, SWT.READ_ONLY); break; case EDITABLECOMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}); final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); editableControl.addKeyListener(new KeyAdapter(){ @Override public void keyReleased(KeyEvent arg0) { super.keyReleased(arg0); XulTreeCell cell = getCell(colIdx); cell.setLabel(editableControl.getText()); } }); break; case TEXT: default: editor = new TextCellEditor(table.getTable()); final Text textControl = (Text) ((TextCellEditor) editor).getControl(); textControl.addKeyListener(new KeyAdapter(){ @Override public void keyReleased(KeyEvent arg0) { super.keyReleased(arg0); XulTreeCell cell = getCell(colIdx); cell.setLabel(textControl.getText()); } }); break; } // Create selection listener for comboboxes. if(type == ColumnType.EDITABLECOMBOBOX || type == ColumnType.COMBOBOX){ final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); editableControl.addSelectionListener(new SelectionAdapter(){ @Override public void widgetDefaultSelected(SelectionEvent arg0) { // TODO Auto-generated method stub super.widgetDefaultSelected(arg0); } @Override public void widgetSelected(SelectionEvent arg0) { super.widgetSelected(arg0); XulTreeCell cell = getCell(colIdx); cell.setSelectedIndex(editableControl.getSelectionIndex()); } }); } editors[i] = editor; names[i] = "" + i; //$NON-NLS-1$ i++; } table.setCellEditors(editors); table.setColumnProperties(names); resizeColumns(); createColumnTypesSnapshot(); } private XulTreeCell getCell(int colIdx){ return ((XulTreeItem) (table.getTable().getSelection()[0]).getData()).getRow().getCell(colIdx); } public boolean isHierarchical() { return isHierarchical; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; if (this.isHierarchical() == false && table != null) { table.getTable().setEnabled(!disabled); } } public int getRows() { return rowsToDisplay; } public void setRows(int rowsToDisplay) { this.rowsToDisplay = rowsToDisplay; if (table != null && (!table.getTable().isDisposed()) && (rowsToDisplay > 0)) { int ht = rowsToDisplay * table.getTable().getItemHeight(); if (table.getTable().getLayoutData() != null) { // tree.setSize(tree.getSize().x,height); ((GridData) table.getTable().getLayoutData()).heightHint = ht; ((GridData) table.getTable().getLayoutData()).minimumHeight = ht; table.getTable().getParent().layout(true); } } } public enum SELECTION_MODE { SINGLE, CELL, MULTIPLE }; public String getSeltype() { return selType.toString(); } public void setSeltype(String selType) { if (selType.equalsIgnoreCase(getSeltype())) { return; // nothing has changed } this.selType = TableSelection.valueOf(selType.toUpperCase()); } public TableSelection getTableSelection() { return selType; } public boolean isEditable() { return editable; } public boolean isEnableColumnDrag() { return enableColumnDrag; } public void setEditable(boolean edit) { editable = edit; } public void setEnableColumnDrag(boolean drag) { enableColumnDrag = drag; } public String getOnselect() { return onSelect; } public void setOnselect(final String method) { if (method == null) { return; } onSelect = method; } public void setColumns(XulTreeCols columns) { this.columns = columns; } public XulTreeCols getColumns() { return columns; } public XulTreeChildren getRootChildren() { if (rootChildren == null) { rootChildren = (XulTreeChildren) this.getChildNodes().get(1); } return rootChildren; } public void setRootChildren(XulTreeChildren rootChildren) { this.rootChildren = rootChildren; } public int[] getActiveCellCoordinates() { return new int[] { activeRow, activeColumn }; } public void setActiveCellCoordinates(int row, int column) { activeRow = row; activeColumn = column; } public Object[][] getValues() { Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns() .getColumnCount()]; int y = 0; for (XulComponent item : getRootChildren().getChildNodes()) { int x = 0; for (XulComponent tempCell : ((XulTreeItem) item).getRow() .getChildNodes()) { XulTreeCell cell = (XulTreeCell) tempCell; switch (columns.getColumn(x).getColumnType()) { case CHECKBOX: Boolean flag = (Boolean) cell.getValue(); if (flag == null) { flag = Boolean.FALSE; } data[y][x] = flag; break; case COMBOBOX: Vector values = (Vector) cell.getValue(); int idx = cell.getSelectedIndex(); data[y][x] = values.get(idx); break; default: // label data[y][x] = cell.getLabel(); break; } x++; } y++; } return data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public int[] getSelectedRows() { if (selectedIndex > -1) { return new int[] { selectedIndex }; } else { return new int[] {}; } } public Collection getSelectedItems(){ if(elements == null){ return null; } if(isHierarchical()){ List selectedItems = new ArrayList(); IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); int i=0; for(Object o : selection.toArray()){ XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(),getRootChildren(), selectedItem); selectedItems.add(b.selectedItem); } return selectedItems; } else { IStructuredSelection selection = (IStructuredSelection) table.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf( selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i=0; for(Iterator it = selection.iterator(); it.hasNext();){ Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } return findSelectedTableRows(selectedRows); } } public void addTreeRow(XulTreeRow row) { this.addChild(row); XulTreeItem item = new SwtTreeItem(this.getRootChildren()); row.setParentTreeItem(item); ((SwtTreeRow) row).layout(); } public void removeTreeRows(int[] rows) { // TODO Auto-generated method stub } public void update() { if (this.isHierarchical) { this.tree.setInput(this); this.tree.refresh(); if ("true".equals(getAttributeValue("expanded"))) { tree.expandAll(); } } else { setupColumns(); this.table.setInput(this); this.table.refresh(); } this.selectedIndex = -1; } public void clearSelection() { } public void setSelectedRows(int[] rows) { if(this.isHierarchical){ Object selected = getSelectedTreeItem(rows); int prevSelected = -1; if(selectedRows != null && selectedRows.length > 0){ prevSelected = selectedRows[0]; // single selection only for now } changeSupport.firePropertyChange("selectedItem", prevSelected, selected); } else { table.getTable().setSelection(rows); } if(rows.length > 0){ this.selectedIndex = rows[0]; // single selection only for now } changeSupport.firePropertyChange("selectedRows", this.selectedRows, rows); this.selectedRows = rows; } public String getOnedit() { return onedit; } public void setOnedit(String onedit) { this.onedit = onedit; } private Collection elements; private boolean suppressEvents = false; public <T> void setElements(Collection<T> elements) { this.elements = elements; this.getRootChildren().removeAll(); if (elements == null) { update(); changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); return; } try { if (this.isHierarchical == false) { for (T o : elements) { XulTreeRow row = this.getRootChildren().addNewRow(); for (int x = 0; x < this.getColumns().getChildNodes().size(); x++) { XulComponent col = this.getColumns().getColumn(x); final XulTreeCell cell = (XulTreeCell) getDocument().createElement( "treecell"); XulTreeCol column = (XulTreeCol) col; for (InlineBindingExpression exp : ((XulTreeCol) col) .getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + o + "]"); String colType = column.getType(); if (StringUtils.isEmpty(colType) == false && colType.equals("dynamic")) { colType = extractDynamicColType(o, x); } Object bob = null; if ((colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")) && column.getCombobinding() != null) { DefaultBinding binding = new DefaultBinding(o, column .getCombobinding(), cell, "value"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); binding = new DefaultBinding(o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex"); binding.setConversion(new BindingConvertor<Object, Integer>() { @Override public Integer sourceToTarget(Object value) { int index = ((Vector) cell.getValue()).indexOf(value); return index > -1 ? index : 0; } @Override public Object targetToSource(Integer value) { return ((Vector) cell.getValue()).get(value); } }); domContainer.addBinding(binding); binding.fireSourceChanged(); if (colType.equalsIgnoreCase("editablecombobox")) { binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp .getXulCompAttr()); if (!this.editable) { binding.setBindingType(Binding.Type.ONE_WAY); } else { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } domContainer.addBinding(binding); } } else if (colType.equalsIgnoreCase("checkbox")) { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp .getModelAttr(), cell, "value"); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } else { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp .getModelAttr(), cell, exp.getXulCompAttr()); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } } if (column.getDisabledbinding() != null) { String prop = column.getDisabledbinding(); DefaultBinding bind = new DefaultBinding(o, column .getDisabledbinding(), cell, "disabled"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } row.addCell(cell); } } } else {// tree for (T o : elements) { SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(o, newRow); } } update(); suppressEvents = false; // treat as a selection change changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); } catch (XulException e) { logger.error("error adding elements", e); } catch (Exception e) { logger.error("error adding elements", e); } } private <T> void addTreeChild(T element, XulTreeRow row) { try { XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns() .getChildNodes().get(0)).getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + element + "]"); // Tree Bindings are one-way for now as you cannot edit tree nodes DefaultBinding binding = new DefaultBinding(element, exp.getModelAttr(), cell, exp.getXulCompAttr()); if(this.isEditable()){ binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } else { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } row.addCell(cell); // find children String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); Method childrenMethod = element.getClass().getMethod(property, new Class[] {}); Method imageMethod; String imageSrc = null; property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getImagebinding(); if(property != null){ property = "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); imageMethod = element.getClass().getMethod(property); imageSrc = (String) imageMethod.invoke(element); ((XulTreeItem) row.getParent()).setImage(imageSrc); } Collection<T> children = (Collection<T>) childrenMethod.invoke(element, new Object[] {}); XulTreeChildren treeChildren = null; if (children != null && children.size() > 0) { treeChildren = (XulTreeChildren) getDocument().createElement( "treechildren"); row.getParent().addChild(treeChildren); } if(children == null){ return; } for (T child : children) { SwtTreeItem item = new SwtTreeItem(treeChildren); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); treeChildren.addChild(item); addTreeChild(child, newRow); } } catch (Exception e) { logger.error("error adding elements", e); } } public <T> Collection<T> getElements() { return null; } private String extractDynamicColType(Object row, int columnPos) { try { Method method = row.getClass().getMethod( this.columns.getColumn(columnPos).getColumntypebinding()); return (String) method.invoke(row, new Object[] {}); } catch (Exception e) { logger.debug("Could not extract column type from binding"); } return "text"; // default //$NON-NLS-1$ } public Object getSelectedItem() { // TODO Auto-generated method stub return null; } private Object getSelectedTreeItem(int[] currentSelection) { if(this.isHierarchical && this.elements != null){ int[] vals = currentSelection; if(vals == null || vals.length == 0 || elements == null || elements.size() == 0){ return null; } String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get"+(property.substring(0,1).toUpperCase() + property.substring(1)); int selectedIdx = vals[0]; if (selectedIdx == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(selectedIdx)); return tuple != null ? tuple.selectedItem : null; } return null; } private void fireSelectedItem(){ this.changeSupport.firePropertyChange("selectedItem", null, getSelectedItem()); } private static class FindSelectedItemTuple{ Object selectedItem = null; int curpos = -1; //ignores first element (root) int selectedIndex; public FindSelectedItemTuple(int selectedIndex){ this.selectedIndex = selectedIndex; } } private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty, FindSelectedItemTuple tuple){ if(tuple.curpos == tuple.selectedIndex){ tuple.selectedItem = parent; return tuple; } Collection children = null; Method childrenMethod = null; try{ childrenMethod = parent.getClass().getMethod(childrenMethodProperty, new Class[]{}); } catch(NoSuchMethodException e){ if(parent instanceof Collection){ children = (Collection) parent; } } try{ if(childrenMethod != null){ children = (Collection) childrenMethod.invoke(parent, new Object[]{}); } } catch(Exception e){ logger.error(e); return null; } if(children == null || children.size() == 0){ return null; } for(Object child : children){ tuple.curpos++; findSelectedItem(child, childrenMethodProperty, tuple); if(tuple.selectedItem != null){ return tuple; } } return null; } public void registerCellEditor(String key, TreeCellEditor editor) { // TODO Auto-generated method stub } public void registerCellRenderer(String key, TreeCellRenderer renderer) { // TODO Auto-generated method stub } public void collapseAll() { if (this.isHierarchical){ tree.collapseAll(); } } public void expandAll() { if (this.isHierarchical){ tree.expandAll(); } } }
package experimentalcode.remigius.Visualizers; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.batik.util.SVGConstants; import org.w3c.dom.Element; import de.lmu.ifi.dbs.elki.algorithm.clustering.ByLabelClustering; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.cluster.Cluster; import de.lmu.ifi.dbs.elki.data.model.Model; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.logging.LoggingUtil; import de.lmu.ifi.dbs.elki.math.AggregatingHistogram; import de.lmu.ifi.dbs.elki.math.MinMax; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.utilities.optionhandling.Flag; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.elki.utilities.pairs.Pair; import de.lmu.ifi.dbs.elki.visualization.css.CSSClass; import de.lmu.ifi.dbs.elki.visualization.css.CSSClassManager.CSSNamingConflict; import de.lmu.ifi.dbs.elki.visualization.scales.LinearScale; import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot; import de.lmu.ifi.dbs.elki.visualization.svg.SVGSimpleLinearAxis; import experimentalcode.remigius.ShapeLibrary; /** * Generates a SVG-Element containing a histogram representing the distribution of the database's objects. * * @author Remigius Wojdanowski * * @param <NV> * @param <N> */ public class HistogramVisualizer<NV extends NumberVector<NV, N>, N extends Number> extends ScalarVisualizer<NV, N> { public static final OptionID STYLE_ROW_ID = OptionID.getOrCreateOptionID("histogram.row", "Alternative style: Rows."); private final Flag STYLE_ROW_PARAM = new Flag(STYLE_ROW_ID); private boolean row; private static final String NAME = "Histograms"; private static final int BINS = 20; private double frac; private Result result; private Clustering<Model> clustering; public HistogramVisualizer() { addOption(STYLE_ROW_PARAM); } @Override public List<String> setParameters(List<String> args) throws ParameterException { List<String> remainingParameters = super.setParameters(args); row = STYLE_ROW_PARAM.getValue(); rememberParametersExcept(args, remainingParameters); return remainingParameters; } public void init(Database<NV> database, Result result) { init(database, NAME); this.frac = 1. / database.size(); this.result = result; setupClustering(); } private void setupClustering() { List<Clustering<?>> clusterings = ResultUtil.getClusteringResults(result); if(clusterings != null && clusterings.size() > 0) { clustering = (Clustering<Model>) clusterings.get(0); } else { clustering = new ByLabelClustering<NV>().run(database); } } // private void setupCSS() { // int clusterID = 0; // for (Cluster<Model> cluster : clustering.getAllClusters()){ // clusterID+=1; // CSSClass bin = visManager.createCSSClass(ShapeLibrary.BIN + clusterID); // bin.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, "0.5"); // bin.setStatement(SVGConstants.CSS_FILL_PROPERTY, // COLORS.getColor(clusterID)); // visManager.registerCSSClass(bin); private void setupCSS(SVGPlot svgp, int clusterID) { CSSClass bin = new CSSClass(svgp, ShapeLibrary.BIN + clusterID); bin.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, "0.5"); bin.setStatement(SVGConstants.CSS_FILL_PROPERTY, COLORS.getColor(clusterID)); try { svgp.getCSSClassManager().addClass(bin); svgp.updateStyleElement(); } catch(CSSNamingConflict e) { LoggingUtil.exception("Equally-named CSSClass with different owner already exists", e); } } @Override public Element visualize(SVGPlot svgp) { Element layer = ShapeLibrary.createSVG(svgp.getDocument()); Map<Integer, AggregatingHistogram<Double, Double>> hists = new HashMap<Integer, AggregatingHistogram<Double, Double>>(); // Creating histograms int clusterID = 0; MinMax<Double> minmax = new MinMax<Double>(); for(Cluster<Model> cluster : clustering.getAllClusters()) { clusterID += 1; AggregatingHistogram<Double, Double> hist = AggregatingHistogram.DoubleSumHistogram(BINS, scales[dim].getMin(), scales[dim].getMax()); for(int id : cluster.getIDs()) { hist.aggregate(database.get(id).getValue(dim).doubleValue(), frac); } for(int bin = 0; bin < hist.getNumBins(); bin++) { double val = hist.get(bin * (scales[dim].getMax() - scales[dim].getMin()) / BINS); minmax.put(val); } hists.put(clusterID, hist); setupCSS(svgp, clusterID); } System.out.println(minmax.getMax()); LinearScale scale = new LinearScale(minmax.getMin(), minmax.getMax()); // Axis try { SVGSimpleLinearAxis.drawAxis(svgp, layer, scale, 0, 1, 0, 0, true, false); svgp.updateStyleElement(); } catch(CSSNamingConflict e) { // TODO Auto-generated catch block e.printStackTrace(); } // Visualizing // TODO: Drawing centered instead of left-end values of bins. for(int key = 1; key <= hists.size(); key++) { AggregatingHistogram<Double, Double> hist = hists.get(key); if(row) { for(int bin = 0; bin < hist.getNumBins(); bin++) { // TODO: calculating the value *must* be simpler. Something is wrong // here. double val = hist.get(bin * (scales[dim].getMax() - scales[dim].getMin()) / BINS)/minmax.getMax(); layer.appendChild(ShapeLibrary.createRow(svgp.getDocument(), getPositioned(bin * hist.getBinsize(), dim), 1 - val, 1./BINS, val, dim, key, bin)); } } else { // TODO: Path is still buggy. Element path = ShapeLibrary.createPath(svgp.getDocument(), 1, 1, key, Integer.toString(key)); // Just a hack to ensure the path ends at its beginning. ShapeLibrary.addLine(path, 0, 1); for(int bin = 0; bin < hist.getNumBins(); bin++) { double val = hist.get((bin * (scales[dim].getMax() - scales[dim].getMin()) / BINS))/minmax.getMax(); ShapeLibrary.addLine(path, getPositioned(bin * hist.getBinsize(), dim), 1 - val); } layer.appendChild(path); } } return layer; } }
package ifc.awt; import com.sun.star.awt.XTabController; import com.sun.star.awt.XUnoControlContainer; import lib.MultiMethodTest; import lib.Status; /** * Testing <code>com.sun.star.awt.XUnoControlContainer</code> * interface methods : * <ul> * <li><code> addTabController()</code></li> * <li><code> removeTabController()</code></li> * <li><code> getTabControllers()</code></li> * <li><code> setTabControllers()</code></li> * </ul> <p> * * This test needs the following object relations : * <ul> * <li> <code>'TABCONTROL1'</code> (of type <code>XTabController</code>)</li> * <li> <code>'TABCONTROL2'</code> (of type <code>XTabController</code>)</li> *</ul> * * Test is <b> NOT </b> multithread compilant. <p> */ public class _XUnoControlContainer extends MultiMethodTest { public XUnoControlContainer oObj = null; private XTabController[] TabControllers = new XTabController[2]; private XTabController tabControl1 = null; private XTabController tabControl2 = null; /** * This method gets the object relations. * */ protected void before() { tabControl1 = (XTabController) tEnv.getObjRelation("TABCONTROL1"); tabControl2 = (XTabController) tEnv.getObjRelation("TABCONTROL2"); if ((tabControl1 == null) || (tabControl2 == null)){ log.println("ERROR: Needed object realtions 'TABCONTROL1' and " + "'TABCONTROL2' are not found."); } TabControllers[0] = tabControl1; TabControllers[1] = tabControl2; } /** * This tests removes the object relations <code>TABCONTROL1</code> and * <code>TABCONTROL1</code>. * Has <b> OK </b> status if the sequenze of <code>XTabController[]</code> * get before calling method is smaller then sequenze of * <code>XTabController[]</code> get after calling method.<p> * * The following method tests are to be completed successfully before : * <ul> * <li> <code> getTabControllers() </code> </li> * <li> <code> removeTabController() </code> </li> * </ul> */ public void _setTabControllers() { requiredMethod( "getTabControllers()"); requiredMethod( "removeTabController()"); log.println("removing TABCONTROL1 and TABCONTROL2"); oObj.removeTabController(tabControl1); oObj.removeTabController(tabControl2); log.println("get current controllers"); XTabController[] myTabControllers = oObj.getTabControllers(); log.println("set new controllers"); oObj.setTabControllers( TabControllers ); log.println("get new current controllers"); XTabController[] myNewTabControllers = oObj.getTabControllers(); tRes.tested("setTabControllers()", (myTabControllers.length < myNewTabControllers.length )); } /** * Test calls the method, then checks returned value.<p> * Has <b> OK </b> status if method returns a value that greater then zerro.<p> * * The following method tests are to be completed successfully before : * <ul> * <li> <code> addTabController() </code></li> * </ul> */ public void _getTabControllers() { requiredMethod( "addTabController()"); XTabController[] myTabControllers = oObj.getTabControllers(); tRes.tested("getTabControllers()", ( myTabControllers.length > 0)); } /** * Test calls the method with object relation 'TABCONTROL1' as a parameter.<p> * Has <b> OK </b> status if the sequenze of <code>XTabController[]</code> * get before calling method is smaller then sequenze of * <code>XTabController[]</code> get after calling method.<p> */ public void _addTabController() { log.println("get current controllers"); XTabController[] myTabControllers = oObj.getTabControllers(); log.println("add TABCONTROL1"); oObj.addTabController( tabControl1 ); log.println("get new current controllers"); XTabController[] myNewTabControllers = oObj.getTabControllers(); tRes.tested("addTabController()", (myTabControllers.length < myNewTabControllers.length )); } /** * Test calls the method with object relation 'TABCONTROL2' as a parameter.<p> * Has <b> OK </b> status if the sequenze of <code>XTabController[]</code> * get before calling method is smaller then sequenze of * <code>XTabController[]</code> get after calling method.<p> * * The following method tests are to be completed successfully before : * <ul> * <li> <code> getTabControllers() </code></li> * <li> <code> addTabController() </code></li> * </ul> */ public void _removeTabController() { requiredMethod( "getTabControllers()"); requiredMethod( "addTabController()"); log.println("add TABCONTROL2"); oObj.addTabController( tabControl2 ); log.println("get current controllers"); XTabController[] myTabControllers = oObj.getTabControllers(); log.println("remove TABCONTROL2"); oObj.removeTabController(tabControl2); log.println("get new current controllers"); XTabController[] myNewTabControllers = oObj.getTabControllers(); tRes.tested("removeTabController()", (myTabControllers.length > myNewTabControllers.length )); } }
package org.junit.internal; import java.util.Arrays; import org.junit.Test; import static org.junit.Assert.*; public class MethodSorterTest { @Test public void getDeclaredMethods() throws Exception { assertEquals("[void epsilon(), void beta(int[][]), java.lang.Object alpha(int,double,java.lang.Thread), void delta(), int gamma(), void gamma(boolean)]", declaredMethods(Dummy.class)); assertEquals("[void testOne()]", declaredMethods(Super.class)); assertEquals("[void testTwo()]", declaredMethods(Sub.class)); } private static String declaredMethods(Class<?> c) { return Arrays.toString(MethodSorter.getDeclaredMethods(c)).replace(c.getName() + '.', ""); } private static class Dummy { Object alpha(int i, double d, Thread t) {return null;} void beta(int[][] x) {} int gamma() {return 0;} void gamma(boolean b) {} void delta() {} void epsilon() {} } private static class Super { void testOne() {} } private static class Sub extends Super { void testTwo() {} } }
package mod._dbaccess; import java.io.PrintWriter; import java.util.Comparator; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.AccessibilityTools; import util.FormTools; import util.SOfficeFactory; import util.WriterTools; import util.utils; import com.sun.star.accessibility.AccessibleRole; import com.sun.star.accessibility.XAccessible; import com.sun.star.accessibility.XAccessibleAction; import com.sun.star.awt.Point; import com.sun.star.awt.Size; import com.sun.star.awt.XControlModel; import com.sun.star.awt.XDevice; import com.sun.star.awt.XExtendedToolkit; import com.sun.star.awt.XGraphics; import com.sun.star.awt.XToolkit; import com.sun.star.awt.XWindow; import com.sun.star.awt.XWindowPeer; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNameContainer; import com.sun.star.drawing.XControlShape; import com.sun.star.drawing.XShape; import com.sun.star.form.XBoundComponent; import com.sun.star.form.XGridColumnFactory; import com.sun.star.form.XLoadable; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sdbc.XResultSetUpdate; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.util.URL; import com.sun.star.util.XCloseable; import com.sun.star.view.XControlAccess; /** * Test for object which represents the control of the Grid model. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::util::XModifyBroadcaster</code></li> * <li> <code>com::sun::star::form::XGridFieldDataSupplier</code></li> * <li> <code>com::sun::star::view::XSelectionSupplier</code></li> * <li> <code>com::sun::star::form::XGrid</code></li> * <li> <code>com::sun::star::awt::XControl</code></li> * <li> <code>com::sun::star::util::XModeSelector</code></li> * <li> <code>com::sun::star::container::XElementAccess</code></li> * <li> <code>com::sun::star::awt::XWindow</code></li> * <li> <code>com::sun::star::form::XUpdateBroadcaster</code></li> * <li> <code>com::sun::star::frame::XDispatch</code></li> * <li> <code>com::sun::star::container::XEnumerationAccess</code></li> * <li> <code>com::sun::star::form::XBoundComponent</code></li> * <li> <code>com::sun::star::frame::XDispatchProviderInterception</code></li> * <li> <code>com::sun::star::container::XIndexAccess</code></li> * <li> <code>com::sun::star::lang::XComponent</code></li> * <li> <code>com::sun::star::awt::XView</code></li> * <li> <code>com::sun::star::container::XContainer</code></li> * </ul> * This object test <b> is NOT </b> designed to be run in several * threads concurently. * @see com.sun.star.util.XModifyBroadcaster * @see com.sun.star.form.XGridFieldDataSupplier * @see com.sun.star.view.XSelectionSupplier * @see com.sun.star.form.XGrid * @see com.sun.star.awt.XControl * @see com.sun.star.util.XModeSelector * @see com.sun.star.container.XElementAccess * @see com.sun.star.awt.XWindow * @see com.sun.star.form.XUpdateBroadcaster * @see com.sun.star.frame.XDispatch * @see com.sun.star.container.XEnumerationAccess * @see com.sun.star.form.XBoundComponent * @see com.sun.star.frame.XDispatchProviderInterception * @see com.sun.star.container.XIndexAccess * @see com.sun.star.lang.XComponent * @see com.sun.star.awt.XView * @see com.sun.star.container.XContainer * @see ifc.util._XModifyBroadcaster * @see ifc.form._XGridFieldDataSupplier * @see ifc.view._XSelectionSupplier * @see ifc.form._XGrid * @see ifc.awt._XControl * @see ifc.util._XModeSelector * @see ifc.container._XElementAccess * @see ifc.awt._XWindow * @see ifc.form._XUpdateBroadcaster * @see ifc.frame._XDispatch * @see ifc.container._XEnumerationAccess * @see ifc.form._XBoundComponent * @see ifc.frame._XDispatchProviderInterception * @see ifc.container._XIndexAccess * @see ifc.lang._XComponent * @see ifc.awt._XView * @see ifc.container._XContainer */ public class SbaXGridControl extends TestCase { XTextDocument xTextDoc; /** * Creates Writer document. */ protected void initialize(TestParameters Param, PrintWriter log) { SOfficeFactory SOF = SOfficeFactory.getFactory((XMultiServiceFactory)Param.getMSF()); try { log.println("creating a textdocument"); xTextDoc = SOF.createTextDoc(null); } catch (com.sun.star.uno.Exception e) { // Some exception occures.FAILED e.printStackTrace(log); throw new StatusException("Couldn't create document", e); } } /** * Disposes Writer document. */ protected void cleanup(TestParameters tParam, PrintWriter log) { //closing the appearing dialog before disposing the document XInterface toolkit = null; try { toolkit = (XInterface) ((XMultiServiceFactory)tParam.getMSF()) .createInstance("com.sun.star.awt.Toolkit"); } catch (com.sun.star.uno.Exception e) { log.println("Couldn't get toolkit"); e.printStackTrace(log); throw new StatusException("Couldn't get toolkit", e); } XExtendedToolkit tk = (XExtendedToolkit) UnoRuntime.queryInterface( XExtendedToolkit.class, toolkit); Object atw = tk.getActiveTopWindow(); XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, atw); XAccessible xRoot = AccessibilityTools.getAccessibleObject(xWindow); XInterface button = AccessibilityTools.getAccessibleObjectForRole(xRoot, AccessibleRole.PUSH_BUTTON); XAccessibleAction action = (XAccessibleAction) UnoRuntime.queryInterface( XAccessibleAction.class, button); try { action.doAccessibleAction(0); } catch (com.sun.star.lang.IndexOutOfBoundsException iob) { log.println("couldn't close dialog"); } catch (com.sun.star.lang.DisposedException e) { log.println("couldn't close dialog"); } log.println(" disposing xTextDoc "); try { XCloseable closer = (XCloseable) UnoRuntime.queryInterface( XCloseable.class, xTextDoc); closer.close(true); } catch (com.sun.star.util.CloseVetoException e) { log.println("couldn't close document"); } catch (com.sun.star.lang.DisposedException e) { log.println("couldn't close document"); } } /** * Creating a Testenvironment for the interfaces to be tested. * For object creation first a * <code>com.sun.star.form.component.GridControl<code> instance * is added to the <code>ControlShape</code>. Then this model's * control is retrieved. * * Object relations created : * <ul> * <li> <code>'GRAPHICS'</code> for * {@link ifc.awt_XView} test : <code>XGraphics</code> * object different that belong to the object tested.</li> * <li> <code>'CONTEXT'</code> for * {@link ifc.awt._XControl} </li> * <li> <code>'WINPEER'</code> for * {@link ifc.awt._XCOntrol} </li> * <li> <code>'TOOLKIT'</code> for * {@link ifc.awt._XCOntrol} </li> * <li> <code>'MODEL'</code> for * {@link ifc.awt._XCOntrol} </li> * <li> <code>'XWindow.AnotherWindow'</code> for * {@link ifc.awt._XWindow} for switching focus.</li> * <li> <code>'XDispatch.URL'</code> for * {@link ifc.frame._XDispatch} the url which moves * DB cursor to the next row (".uno:FormSlots/moveToNext").</li> * <li> <code>'XContainer.Container'</code> for * {@link ifc.container._XContainer} as the component created * doesn't support <code>XContainer</code> itself, but * it is supported by its model. So this model is passed.</li> * <li> <code>'INSTANCE'</code> for * {@link ifc.container._XContainer} the instance to be * inserted into collection. Is a column instance.</li> * </ul> */ protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; XWindowPeer the_win = null; XToolkit the_kit = null; XDevice aDevice = null; XGraphics aGraphic = null; XPropertySet aControl = null; XPropertySet aControl2 = null; XPropertySet aControl3 = null; XPropertySet aControl4 = null; XGridColumnFactory columns = null; //Insert a ControlShape and get the ControlModel XControlShape aShape = createGrid(xTextDoc, 3000, 4500, 15000, 10000); XControlModel the_Model = aShape.getControl(); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); XLoadable formLoader = FormTools.bindForm(xTextDoc); //Try to query XControlAccess XControlAccess the_access = (XControlAccess) UnoRuntime.queryInterface( XControlAccess.class, xTextDoc.getCurrentController()); try { columns = (XGridColumnFactory) UnoRuntime.queryInterface( XGridColumnFactory.class, the_Model); aControl = columns.createColumn("TextField"); aControl.setPropertyValue("DataField", "Identifier"); aControl.setPropertyValue("Label", "Identifier"); aControl2 = columns.createColumn("TextField"); aControl2.setPropertyValue("DataField", "Publisher"); aControl2.setPropertyValue("Label", "Publisher"); aControl3 = columns.createColumn("TextField"); aControl3.setPropertyValue("DataField", "Author"); aControl3.setPropertyValue("Label", "Author"); aControl4 = columns.createColumn("TextField"); aControl4.setPropertyValue("DataField", "Title"); aControl4.setPropertyValue("Label", "Title"); } catch (com.sun.star.lang.IllegalArgumentException e) { // Some exception occures.FAILED log.println("!!! Couldn't create instance : " + e); throw new StatusException("Can't create column instances.", e); } catch (com.sun.star.lang.WrappedTargetException e) { // Some exception occures.FAILED log.println("!!! Couldn't create instance : " + e); throw new StatusException("Can't create column instances.", e); } catch (com.sun.star.beans.PropertyVetoException e) { // Some exception occures.FAILED log.println("!!! Couldn't create instance : " + e); throw new StatusException("Can't create column instances.", e); } catch (com.sun.star.beans.UnknownPropertyException e) { // Some exception occures.FAILED log.println("!!! Couldn't create instance : " + e); throw new StatusException("Can't create column instances.", e); } XNameContainer aContainer = (XNameContainer) UnoRuntime.queryInterface( XNameContainer.class, the_Model); try { aContainer.insertByName("First", aControl); aContainer.insertByName("Second", aControl2); } catch (com.sun.star.uno.Exception e) { log.println("!!! Could't insert column Instance"); e.printStackTrace(log); throw new StatusException("Can't insert columns", e); } //now get the OGridControl try { oObj = the_access.getControl(the_Model); the_win = the_access.getControl(the_Model).getPeer(); the_kit = the_win.getToolkit(); aDevice = the_kit.createScreenCompatibleDevice(200, 200); aGraphic = aDevice.createGraphics(); } catch (com.sun.star.uno.Exception e) { log.println("Couldn't get GridControl"); e.printStackTrace(log); throw new StatusException("Couldn't get GridControl", e); } // creating another window aShape = FormTools.createControlShape(xTextDoc, 3000, 4500, 15000, 10000, "TextField"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); the_Model = aShape.getControl(); //Try to query XControlAccess the_access = (XControlAccess) UnoRuntime.queryInterface( XControlAccess.class, xTextDoc.getCurrentController()); //now get the TextControl XWindow win = null; Object cntrl = null; try { cntrl = the_access.getControl(the_Model); win = (XWindow) UnoRuntime.queryInterface(XWindow.class, cntrl); } catch (com.sun.star.uno.Exception e) { log.println("Couldn't get Control"); e.printStackTrace(log); throw new StatusException("Couldn't get Control", e); } log.println("creating a new environment for object"); TestEnvironment tEnv = new TestEnvironment(oObj); //Relations for XSelectionSupplier tEnv.addObjRelation("Selections", new Object[] { new Object[] { new Integer(0) }, new Object[] { new Integer(1) } }); tEnv.addObjRelation("Comparer", new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).compareTo((Integer)o2); } public boolean equals(Object obj) { return compare(this, obj) == 0; } }); //Realtion for XContainer tEnv.addObjRelation("XContainer.Container", aContainer); tEnv.addObjRelation("INSTANCE", aControl3); tEnv.addObjRelation("INSTANCE2", aControl4); //Adding ObjRelation for XView tEnv.addObjRelation("GRAPHICS", aGraphic); //Adding ObjRelation for XControl tEnv.addObjRelation("CONTEXT", xTextDoc); tEnv.addObjRelation("WINPEER", the_win); tEnv.addObjRelation("TOOLKIT", the_kit); tEnv.addObjRelation("MODEL", the_Model); // Adding relation for XWindow tEnv.addObjRelation("XWindow.AnotherWindow", win); // Adding relation for XDispatch URL url = new URL(); url.Complete = ".uno:FormSlots/moveToNext"; //url.Complete = ".uno:GridSlots/RowHeight"; //url.Complete = ".uno:GridSlots/RowHeight" ; tEnv.addObjRelation("XDispatch.URL", url); log.println("ImplName: " + utils.getImplName(oObj)); FormTools.switchDesignOf((XMultiServiceFactory)Param.getMSF(), xTextDoc); // adding relation for XUpdateBroadcaster final XInterface ctrl = oObj; final XLoadable formLoaderF = formLoader; final XPropertySet ps = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, aControl2); tEnv.addObjRelation("XUpdateBroadcaster.Checker", new ifc.form._XUpdateBroadcaster.UpdateChecker() { private String lastText = ""; public void update() throws com.sun.star.uno.Exception { if (!formLoaderF.isLoaded()) { formLoaderF.load(); } lastText = "_" + ps.getPropertyValue("Text"); ps.setPropertyValue("Text", lastText); } public void commit() throws com.sun.star.sdbc.SQLException { XBoundComponent bound = (XBoundComponent) UnoRuntime.queryInterface( XBoundComponent.class, ctrl); XResultSetUpdate update = (XResultSetUpdate) UnoRuntime.queryInterface( XResultSetUpdate.class, formLoaderF); bound.commit(); update.updateRow(); } public boolean wasCommited() throws com.sun.star.uno.Exception { String getS = (String) ps.getPropertyValue("Text"); return lastText.equals(getS); } }); return tEnv; } // finish method getTestEnvironment public static XControlShape createGrid(XComponent oDoc, int height, int width, int x, int y) { Size size = new Size(); Point position = new Point(); XControlShape oCShape = null; XControlModel aControl = null; //get MSF XMultiServiceFactory oDocMSF = (XMultiServiceFactory) UnoRuntime.queryInterface( XMultiServiceFactory.class, oDoc); try { Object oInt = oDocMSF.createInstance( "com.sun.star.drawing.ControlShape"); Object aCon = oDocMSF.createInstance( "com.sun.star.form.component.GridControl"); XPropertySet model_props = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, aCon); model_props.setPropertyValue("DefaultControl", "com.sun.star.form.control.InteractionGridControl"); aControl = (XControlModel) UnoRuntime.queryInterface( XControlModel.class, aCon); oCShape = (XControlShape) UnoRuntime.queryInterface( XControlShape.class, oInt); size.Height = height; size.Width = width; position.X = x; position.Y = y; oCShape.setSize(size); oCShape.setPosition(position); } catch (com.sun.star.uno.Exception e) { // Some exception occures.FAILED System.out.println("Couldn't create Grid" + e); throw new StatusException("Couldn't create Grid", e); } oCShape.setControl(aControl); return oCShape; } // finish createGrid }
package seedu.taskmanager.testutil; 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 org.loadui.testfx.GuiTest; import org.testfx.api.FxToolkit; import seedu.taskmanager.TestApp; import seedu.taskmanager.commons.exceptions.IllegalValueException; import seedu.taskmanager.commons.util.FileUtil; import seedu.taskmanager.commons.util.XmlUtil; import seedu.taskmanager.model.TaskManager; import seedu.taskmanager.model.item.ItemDate; import seedu.taskmanager.model.item.Item; import seedu.taskmanager.model.item.ItemType; import seedu.taskmanager.model.item.Name; import seedu.taskmanager.model.item.ReadOnlyItem; import seedu.taskmanager.model.item.ItemTime; import seedu.taskmanager.model.item.UniqueItemList; import seedu.taskmanager.model.tag.Tag; import seedu.taskmanager.model.tag.UniqueTagList; import seedu.taskmanager.storage.XmlSerializableTaskManager; 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; /** * A utility class for test cases. */ public class TestUtil { public static String LS = System.lineSeparator(); public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) { try { executable.run(); } catch (Throwable actualException) { if (!actualException.getClass().isAssignableFrom(expected)) { String message = String.format("Expected thrown: %s, actual: %s", expected.getName(), actualException.getClass().getName()); throw new AssertionFailedError(message); } else return; } throw new AssertionFailedError( String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName())); } /** * Folder used for temp files created during testing. Ignored by Git. */ public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/"); public static final Item[] sampleItemData = getSampleItemData(); private static Item[] getSampleItemData() { try { return new Item[]{ new Item(new ItemType("event"), new Name("Game of Life"), new ItemDate("07-07"), new ItemTime("00:00"), new ItemDate("08-07"), new ItemTime("12:00"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("This is a deadline"), new ItemDate(""), new ItemTime(""), new ItemDate("2017-05-05"), new ItemTime("23:59"), new UniqueTagList()), new Item(new ItemType("task"), new Name("Win at Life"), new ItemDate(""), new ItemTime(""), new ItemDate(""), new ItemTime(""), new UniqueTagList()), new Item(new ItemType("event"), new Name("This is an event"), new ItemDate("2018-05-05"), new ItemTime("23:59"), new ItemDate("2019-01-01"), new ItemTime("02:30"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("Pay my bills"), new ItemDate(""), new ItemTime(""), new ItemDate("2020-12-30"), new ItemTime("04:49"), new UniqueTagList()), new Item(new ItemType("task"), new Name("This is a task"), new ItemDate(""), new ItemTime(""), new ItemDate(""), new ItemTime(""), new UniqueTagList()), new Item(new ItemType("event"), new Name("2103 exam"), new ItemDate("2018-05-05"), new ItemTime("21:59"), new ItemDate("2022-01-01"), new ItemTime("19:21"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("Submit report"), new ItemDate(""), new ItemTime(""), new ItemDate("2023-03-03"), new ItemTime("14:21"), new UniqueTagList()), new Item(new ItemType("task"), new Name("Buy a dozen cartons of milk"), new ItemDate(""), new ItemTime(""), new ItemDate("2016-11-21"), new ItemTime("13:10"), new UniqueTagList()), new Item(new ItemType("event"), new Name("Java Workshop"), new ItemDate("2017-01-02"), new ItemTime("08:00"), new ItemDate("2017-01-02"), new ItemTime("12:00"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("Submit essay assignment"), new ItemDate(""), new ItemTime(""), new ItemDate("2016-11-28"), new ItemTime("21:29"), new UniqueTagList()), new Item(new ItemType("task"), new Name("Call for the electrician"), new ItemDate(""), new ItemTime(""), new ItemDate(""), new ItemTime(""), new UniqueTagList()) }; } catch (IllegalValueException e) { assert false; //not possible return null; } } public static final Tag[] sampleTagData = getSampleTagData(); 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<Item> generateSampleItemData() { return Arrays.asList(sampleItemData); } /** * 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 TaskManager generateEmptyTaskManager() { return new TaskManager(new UniqueItemList(), new UniqueTagList()); } public static XmlSerializableTaskManager generateSampleStorageTaskManager() { return new XmlSerializableTaskManager(generateEmptyTaskManager()); } /** * 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 persons. * @param items The list of persons * @param itemsToRemove The subset of persons. * @return The modified persons after removal of the subset from persons. */ public static TestItem[] removeItemsFromList(final TestItem[] items, TestItem... itemsToRemove) { List<TestItem> listOfItems = asList(items); listOfItems.removeAll(asList(itemsToRemove)); return listOfItems.toArray(new TestItem[listOfItems.size()]); } /** * Returns a copy of the list with the person at specified index removed. * @param list original list to copy from * @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index. */ public static TestItem[] removeItemFromList(final TestItem[] list, int targetIndexInOneIndexedFormat) { return removeItemsFromList(list, list[targetIndexInOneIndexedFormat-1]); } /** * Returns a copy of the list with items at the specified multiple indexes removed. * @param list original list to copy from * @param targetIndexes the integer array of indexes of the items to be removed */ public static TestItem[] removeItemsFromList(final TestItem[] list, int[] targetIndexes) { TestItem[] itemsToRemove = new TestItem[targetIndexes.length]; int numToRemove = 0; for (int targetIndex : targetIndexes) { itemsToRemove[numToRemove] = list[targetIndex-1]; numToRemove += 1; } return removeItemsFromList(list, itemsToRemove); } /** * Replaces items[i] with an item. * @param items The array of items. * @param item The replacement item * @param index The index of the item to be replaced. * @return */ public static TestItem[] replaceItemFromList(TestItem[] items, TestItem item, int index) { items[index] = item; return items; } /** * Appends items to the array of items. * @param items A array of items. * @param itemsToAdd The items that are to be appended behind the original array. * @return The modified array of items. */ public static TestItem[] addItemsToList(final TestItem[] items, TestItem... itemsToAdd) { List<TestItem> listOfItems = asList(items); listOfItems.addAll(asList(itemsToAdd)); return listOfItems.toArray(new TestItem[listOfItems.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 compareCardAndItem(TaskCardHandle card, ReadOnlyItem item) { return card.isSamePerson(item); } public static Tag[] getTagList(String tags) { if (tags.equals("")) { 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 org.flymine.web; import javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.HashMap; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; /** * Form bean to represent the inputs to a text-based query * * @author Andrew Varley */ public class QueryBuildForm extends ActionForm { // field to which a constraint is to be added protected String newFieldName; // map from constraint name to constaintOp index protected Map fieldOps = new HashMap(); // map from constraint name to constraint value (a string) protected Map fieldValues = new HashMap(); /** * Set newFieldName * @param newFieldName the new field name */ public void setNewFieldName(String newFieldName) { this.newFieldName = newFieldName; } /** * Get newFieldName * @return the new field name */ public String getNewFieldName() { return newFieldName; } /** * Set the map field name/values for QueryClass * * @param fieldOps a map of fieldname/operation */ public void setFieldOps(Map fieldOps) { this.fieldOps = fieldOps; } /** * Get the map of field values * * @return the map of field values */ public Map getFieldOps() { return this.fieldOps; } /** * Set a value for the given field of QueryClass * * @param key the field name * @param value value to set */ public void setFieldOp(String key, Object value) { fieldOps.put(key, value); } /** * Get the value for the given field * * @param key the field name * @return the field value */ public Object getFieldOp(String key) { return fieldOps.get(key); } /** * Set the map field name/values for QueryClass * * @param fieldValues a map of fieldname/value */ public void setFieldValues(Map fieldValues) { this.fieldValues = fieldValues; } /** * Get the map of field values * * @return the map of field values */ public Map getFieldValues() { return this.fieldValues; } /** * Set a value for the given field of QueryClass * * @param key the field name * @param value value to set */ public void setFieldValue(String key, Object value) { fieldValues.put(key, value); } /** * Get the value for the given field * * @param key the field name * @return the field value */ public Object getFieldValue(String key) { return fieldValues.get(key); } /** * @see ActionForm#reset */ public void reset(ActionMapping mapping, HttpServletRequest request) { fieldValues.clear(); fieldOps.clear(); } }
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.android.dex.ClassData; import com.android.dex.ClassData.Method; import com.android.dex.ClassDef; import com.android.dex.Code; import com.android.dex.Dex; import com.android.dex.Dex.Section; import com.android.dex.FieldId; import com.android.dex.MethodId; import com.android.dex.ProtoId; import com.android.dex.TypeList; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.files.DexFile; public class DexNode implements IDexNode { public static final int NO_INDEX = -1; private final RootNode root; private final Dex dexBuf; private final DexFile file; private final int dexId; private final List<ClassNode> classes = new ArrayList<>(); private final Map<ClassInfo, ClassNode> clsMap = new HashMap<>(); private final ArgType[] typesCache; public DexNode(RootNode root, DexFile input, int dexId) { this.root = root; this.file = input; this.dexBuf = input.getDexBuf(); this.dexId = dexId; this.typesCache = new ArgType[dexBuf.typeIds().size()]; } public void loadClasses() { for (ClassDef cls : dexBuf.classDefs()) { addClassNode(new ClassNode(this, cls)); } // sort classes by name, expect top classes before inner classes.sort(Comparator.comparing(ClassNode::getFullName)); } public void addClassNode(ClassNode clsNode) { classes.add(clsNode); clsMap.put(clsNode.getClassInfo(), clsNode); } void initInnerClasses() { // move inner classes List<ClassNode> inner = new ArrayList<>(); for (ClassNode cls : classes) { if (cls.getClassInfo().isInner()) { inner.add(cls); } } List<ClassNode> updated = new ArrayList<>(); for (ClassNode cls : inner) { ClassInfo clsInfo = cls.getClassInfo(); ClassNode parent = resolveClass(clsInfo.getParentClass()); if (parent == null) { clsMap.remove(clsInfo); clsInfo.notInner(root); clsMap.put(clsInfo, cls); updated.add(cls); } else { parent.addInnerClass(cls); } } // reload names for inner classes of updated parents for (ClassNode updCls : updated) { for (ClassNode innerCls : updCls.getInnerClasses()) { innerCls.getClassInfo().updateNames(root); } } } public List<ClassNode> getClasses() { return classes; } @Nullable ClassNode resolveClassLocal(ClassInfo clsInfo) { return clsMap.get(clsInfo); } @Nullable public ClassNode resolveClass(ClassInfo clsInfo) { ClassNode classNode = resolveClassLocal(clsInfo); if (classNode != null) { return classNode; } return root.resolveClass(clsInfo); } @Nullable public ClassNode resolveClass(@NotNull ArgType type) { if (type.isGeneric()) { type = ArgType.object(type.getObject()); } return resolveClass(ClassInfo.fromType(root, type)); } @Nullable public MethodNode resolveMethod(@NotNull MethodInfo mth) { ClassNode cls = resolveClass(mth.getDeclClass()); if (cls != null) { return cls.searchMethod(mth); } return null; } @Nullable MethodNode deepResolveMethod(@NotNull ClassNode cls, String signature) { for (MethodNode m : cls.getMethods()) { if (m.getMethodInfo().getShortId().startsWith(signature)) { return m; } } MethodNode found; ArgType superClass = cls.getSuperClass(); if (superClass != null) { ClassNode superNode = resolveClass(superClass); if (superNode != null) { found = deepResolveMethod(superNode, signature); if (found != null) { return found; } } } for (ArgType iFaceType : cls.getInterfaces()) { ClassNode iFaceNode = resolveClass(iFaceType); if (iFaceNode != null) { found = deepResolveMethod(iFaceNode, signature); if (found != null) { return found; } } } return null; } @Nullable public FieldNode resolveField(FieldInfo field) { ClassNode cls = resolveClass(field.getDeclClass()); if (cls != null) { return cls.searchField(field); } return null; } @Nullable FieldNode deepResolveField(@NotNull ClassNode cls, FieldInfo fieldInfo) { FieldNode field = cls.searchFieldByNameAndType(fieldInfo); if (field != null) { return field; } ArgType superClass = cls.getSuperClass(); if (superClass != null) { ClassNode superNode = resolveClass(superClass); if (superNode != null) { FieldNode found = deepResolveField(superNode, fieldInfo); if (found != null) { return found; } } } for (ArgType iFaceType : cls.getInterfaces()) { ClassNode iFaceNode = resolveClass(iFaceType); if (iFaceNode != null) { FieldNode found = deepResolveField(iFaceNode, fieldInfo); if (found != null) { return found; } } } return null; } public DexFile getDexFile() { return file; } // DexBuffer wrappers public String getString(int index) { if (index == DexNode.NO_INDEX) { return null; } return dexBuf.strings().get(index); } public ArgType getType(int index) { if (index == DexNode.NO_INDEX) { return null; } ArgType type = typesCache[index]; if (type != null) { return type; } // no synchronization because exactly one ArgType instance not needed, just reduce instances count // note: same types but different instances will exist in other dex nodes ArgType parsedType = ArgType.parse(getString(dexBuf.typeIds().get(index))); typesCache[index] = parsedType; return parsedType; } public MethodId getMethodId(int mthIndex) { return dexBuf.methodIds().get(mthIndex); } public FieldId getFieldId(int fieldIndex) { return dexBuf.fieldIds().get(fieldIndex); } public ProtoId getProtoId(int protoIndex) { return dexBuf.protoIds().get(protoIndex); } public ClassData readClassData(ClassDef cls) { return dexBuf.readClassData(cls); } public List<ArgType> readParamList(int parametersOffset) { TypeList paramList = dexBuf.readTypeList(parametersOffset); List<ArgType> args = new ArrayList<>(paramList.getTypes().length); for (short t : paramList.getTypes()) { args.add(getType(t)); } return Collections.unmodifiableList(args); } public Code readCode(Method mth) { return dexBuf.readCode(mth); } public Section openSection(int offset) { return dexBuf.open(offset); } public boolean checkOffset(int dataOffset) { return dataOffset >= 0 && dataOffset < dexBuf.getLength(); } @Override public RootNode root() { return root; } @Override public DexNode dex() { return this; } @Override public String typeName() { return "dex"; } public int getDexId() { return dexId; } @Override public String toString() { return "DEX: " + file; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.whirled.spot.client; import com.samskivert.util.ResultListener; import com.samskivert.util.StringUtil; import com.threerings.presents.client.BasicDirector; import com.threerings.presents.client.Client; import com.threerings.presents.client.InvocationService.ConfirmListener; import com.threerings.presents.data.ClientObject; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.ObjectAccessException; import com.threerings.presents.dobj.Subscriber; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.client.LocationAdapter; import com.threerings.crowd.client.LocationDirector; import com.threerings.crowd.data.PlaceObject; import com.threerings.whirled.client.SceneDirector; import com.threerings.whirled.data.SceneModel; import com.threerings.whirled.data.ScenedBodyObject; import com.threerings.whirled.util.WhirledContext; import com.threerings.whirled.spot.Log; import com.threerings.whirled.spot.data.ClusteredBodyObject; import com.threerings.whirled.spot.data.Location; import com.threerings.whirled.spot.data.Portal; import com.threerings.whirled.spot.data.SpotCodes; import com.threerings.whirled.spot.data.SpotScene; /** * Extends the standard scene director with facilities to move between * locations within a scene. */ public class SpotSceneDirector extends BasicDirector implements SpotCodes, Subscriber, AttributeChangeListener { /** * Creates a new spot scene director with the specified context and * which will cooperate with the supplied scene director. * * @param ctx the active client context. * @param locdir the location director with which we will be * cooperating. * @param scdir the scene director with which we will be cooperating. */ public SpotSceneDirector (WhirledContext ctx, LocationDirector locdir, SceneDirector scdir) { super(ctx); _ctx = ctx; _scdir = scdir; // wire ourselves up to hear about leave place notifications locdir.addLocationObserver(new LocationAdapter() { public void locationDidChange (PlaceObject place) { // we need to clear some things out when we leave a place handleDeparture(); } }); } /** * Configures this spot scene director with a chat director, with * which it will coordinate to implement cluster chatting. */ public void setChatDirector (ChatDirector chatdir) { _chatdir = chatdir; } /** * Returns our current location unless we have a location change * pending, in which case our pending location is returned. */ public Location getIntendedLocation () { return (_pendingLoc != null) ? _pendingLoc : _location; } /** * Requests that this client move to the location specified by the * supplied portal id. A request will be made and when the response is * received, the location observers will be notified of success or * failure. * * @return true if the request was issued, false if it was rejected by * a location observer or because we have another request outstanding. */ public boolean traversePortal (int portalId) { return traversePortal(portalId, null); } /** * Requests that this client move to the location specified by the * supplied portal id. A request will be made and when the response is * received, the location observers will be notified of success or * failure. */ public boolean traversePortal (int portalId, ResultListener rl) { // look up the destination scene and location SpotScene scene = (SpotScene)_scdir.getScene(); if (scene == null) { Log.warning("Requested to traverse portal when we have " + "no scene [portalId=" + portalId + "]."); return false; } // sanity check the server's notion of what scene we're in with // our notion of it int sceneId = _scdir.getScene().getId(); ScenedBodyObject sbobj = (ScenedBodyObject) _ctx.getClient().getClientObject(); if (sceneId != sbobj.getSceneId()) { Log.warning("Client and server differ in opinion of what scene " + "we're in [sSceneId=" + sbobj.getSceneId() + ", cSceneId=" + sceneId + "]."); return false; } // find the portal they're talking about Portal dest = scene.getPortal(portalId); if (dest == null) { Log.warning("Requested to traverse non-existent portal " + "[portalId=" + portalId + ", portals=" + StringUtil.toString(scene.getPortals()) + "]."); return false; } // prepare to move to this scene (sets up pending data) if (!_scdir.prepareMoveTo(dest.targetSceneId, rl)) { Log.info("Portal traversal vetoed by scene director " + "[portalId=" + portalId + "]."); return false; } // check the version of our cached copy of the scene to which // we're requesting to move; if we were unable to load it, assume // a cached version of zero int sceneVer = 0; SceneModel pendingModel = _scdir.getPendingModel(); if (pendingModel != null) { sceneVer = pendingModel.version; } // issue a traversePortal request Log.info("Issuing traversePortal(" + sceneId + ", " + dest + ", " + sceneVer + ")."); _sservice.traversePortal( _ctx.getClient(), sceneId, portalId, sceneVer, _scdir); return true; } /** * Issues a request to change our location within the scene to the * specified location. * * @param loc the new location to which to move. * @param listener will be notified of success or failure. Most client * entities find out about location changes via changes to the * occupant info data, but the initiator of a location change request * can be notified of its success or failure, primarily so that it can * act in anticipation of a successful location change (like by * starting a sprite moving toward the new location), but backtrack if * it finds out that the location change failed. */ public void changeLocation (Location loc, final ResultListener listener) { // refuse if there's a pending location change or if we're already // at the specified location if (loc.equivalent(_location)) { Log.info("Not going to " + loc + "; we're at " + _location + " and we're headed to " + _pendingLoc + "."); if (listener != null) { listener.requestFailed(new Exception(ALREADY_THERE)); } return; } if (_pendingLoc != null) { Log.info("Not going to " + loc + "; we're at " + _location + " and we're headed to " + _pendingLoc + "."); if (listener != null) { listener.requestFailed(new Exception(MOVE_IN_PROGRESS)); } return; } SpotScene scene = (SpotScene)_scdir.getScene(); if (scene == null) { Log.warning("Requested to change locations, but we're not " + "currently in any scene [loc=" + loc + "]."); if (listener != null) { listener.requestFailed(new Exception(NO_SUCH_PLACE)); } return; } int sceneId = _scdir.getScene().getId(); Log.info("Sending changeLocation request [scid=" + sceneId + ", loc=" + loc + "]."); _pendingLoc = (Location)loc.clone(); ConfirmListener clist = new ConfirmListener() { public void requestProcessed () { _location = _pendingLoc; _pendingLoc = null; if (listener != null) { listener.requestCompleted(_location); } } public void requestFailed (String reason) { _pendingLoc = null; if (listener != null) { listener.requestFailed(new Exception(reason)); } } }; _sservice.changeLocation(_ctx.getClient(), sceneId, loc, clist); } /** * Issues a request to join the cluster associated with the specified * user (starting one if necessary). * * @param froid the bodyOid of another user; the calling user will * be made to join the target user's cluster. * @param listener will be notified of success or failure. */ public void joinCluster (int froid, final ResultListener listener) { SpotScene scene = (SpotScene)_scdir.getScene(); if (scene == null) { Log.warning("Requested to join cluster, but we're not " + "currently in any scene [froid=" + froid + "]."); if (listener != null) { listener.requestFailed(new Exception(NO_SUCH_PLACE)); } return; } Log.info("Joining cluster [friend=" + froid + "]."); _sservice.joinCluster(_ctx.getClient(), froid, new ConfirmListener() { public void requestProcessed () { if (listener != null) { listener.requestCompleted(null); } } public void requestFailed (String reason) { if (listener != null) { listener.requestFailed(new Exception(reason)); } } }); } /** * Sends a chat message to the other users in the cluster to which the * location that we currently occupy belongs. * * @return true if a cluster speak message was delivered, false if we * are not in a valid cluster and refused to deliver the request. */ public boolean requestClusterSpeak (String message) { return requestClusterSpeak(message, ChatCodes.DEFAULT_MODE); } /** * Sends a chat message to the other users in the cluster to which the * location that we currently occupy belongs. * * @return true if a cluster speak message was delivered, false if we * are not in a valid cluster and refused to deliver the request. */ public boolean requestClusterSpeak (String message, byte mode) { // make sure we're currently in a scene SpotScene scene = (SpotScene)_scdir.getScene(); if (scene == null) { Log.warning("Requested to speak to cluster, but we're not " + "currently in any scene [message=" + message + "]."); return false; } // make sure we're part of a cluster if (_self.getClusterOid() <= 0) { Log.info("Ignoring cluster speak as we're not in a cluster " + "[cloid=" + _self.getClusterOid() + "]."); return false; } message = _chatdir.filter(message, null, true); if (message != null) { _sservice.clusterSpeak(_ctx.getClient(), message, mode); } return true; } // documentation inherited from interface public void objectAvailable (DObject object) { clearCluster(false); int oid = object.getOid(); if (oid != _self.getClusterOid()) { // we got it too late, just unsubscribe DObjectManager omgr = _ctx.getDObjectManager(); omgr.unsubscribeFromObject(oid, this); } else { // it's our new cluster! _clobj = object; if (_chatdir != null) { _chatdir.addAuxiliarySource(object, CLUSTER_CHAT_TYPE); } } } // documentation inherited from interface public void requestFailed (int oid, ObjectAccessException cause) { Log.warning("Unable to subscribe to cluster chat object " + "[oid=" + oid + ", cause=" + cause + "]."); } // documentation inherited from interface public void attributeChanged (AttributeChangedEvent event) { if (event.getName().equals(_self.getClusterField()) && !event.getValue().equals(event.getOldValue())) { maybeUpdateCluster(); } } // documentation inherited public void clientDidLogon (Client client) { super.clientDidLogon(client); ClientObject clientObj = client.getClientObject(); if (clientObj instanceof ClusteredBodyObject) { // listen to the client object clientObj.addListener(this); _self = (ClusteredBodyObject) clientObj; // we may need to subscribe to a cluster due to session resumption maybeUpdateCluster(); } } // documentation inherited public void clientObjectDidChange (Client client) { super.clientObjectDidChange(client); // listen to the client object ClientObject clientObj = client.getClientObject(); clientObj.addListener(this); _self = (ClusteredBodyObject) clientObj; } // documentation inherited public void clientDidLogoff (Client client) { super.clientDidLogoff(client); // clear out our business _location = null; _pendingLoc = null; _sservice = null; clearCluster(true); // stop listening to the client object client.getClientObject().removeListener(this); _self = null; } // documentation inherited protected void fetchServices (Client client) { _sservice = (SpotService)client.requireService(SpotService.class); } /** * Clean up after a few things when we depart from a scene. */ protected void handleDeparture () { // clear out our last known location id _location = null; } /** * Checks to see if our cluster has changed and does the necessary * subscription machinations if necessary. */ protected void maybeUpdateCluster () { int cloid = _self.getClusterOid(); if ((_clobj == null && cloid <= 0) || (_clobj != null && cloid == _clobj.getOid())) { // our cluster didn't change, we can stop now return; } // clear out any old cluster object clearCluster(false); // if there's a new cluster object, subscribe to it if (_chatdir != null && cloid > 0) { DObjectManager omgr = _ctx.getDObjectManager(); // we'll wire up to the chat director when this completes omgr.subscribeToObject(cloid, this); } } /** * Convenience routine to unwire chat for and unsubscribe from our * current cluster, if any. * * @param force clear the cluster even if we're still apparently in it. */ protected void clearCluster (boolean force) { if (_clobj != null && (force || (_clobj.getOid() != _self.getClusterOid()))) { if (_chatdir != null) { _chatdir.removeAuxiliarySource(_clobj); } DObjectManager omgr = _ctx.getDObjectManager(); omgr.unsubscribeFromObject(_clobj.getOid(), this); _clobj = null; } } /** The active client context. */ protected WhirledContext _ctx; /** Access to spot scene services. */ protected SpotService _sservice; /** The scene director with which we are cooperating. */ protected SceneDirector _scdir; /** A casted reference to our clustered body object. */ protected ClusteredBodyObject _self; /** A reference to the chat director with which we coordinate. */ protected ChatDirector _chatdir; /** The location we currently occupy. */ protected Location _location; /** The location to which we have an outstanding change location * request. */ protected Location _pendingLoc; /** The cluster chat object for the cluster we currently occupy. */ protected DObject _clobj; }
package uk.ac.ed.ph.snuggletex.definitions; /** * Defines all of the {@link AccentMap}s for the various types of accents we support. * * <h2>Developer Note</h2> * * Add more entries to here as required, subject to the resulting accented characters * having adequate font support across the targetted browsers. * * @author David McKain * @version $Revision:179 $ */ public interface AccentMaps { public static final AccentMap ACCENT = new AccentMap(new char[] { 'A', '\u00c1', 'E', '\u00c9', 'I', '\u00cd', 'O', '\u00d3', 'U', '\u00da', 'a', '\u00e1', 'e', '\u00e9', 'i', '\u00ed', 'o', '\u00f3', 'u', '\u00fa', 'y', '\u00fd' }, ""); public static final AccentMap GRAVE = new AccentMap(new char[] { 'A', '\u00c0', 'E', '\u00c9', 'I', '\u00cc', 'O', '\u00d2', 'U', '\u00d9', 'a', '\u00e0', 'e', '\u00e8', 'i', '\u00ec', 'o', '\u00f2', 'u', '\u00f9' }, ""); public static final AccentMap CIRCUMFLEX = new AccentMap(new char[] { 'A', '\u00c2', 'E', '\u00ca', 'I', '\u00ce', 'O', '\u00d4', 'U', '\u00db', 'a', '\u00e2', 'e', '\u00ea', 'i', '\u00ee', 'o', '\u00f4', 'u', '\u00fb' }, ""); public static final AccentMap TILDE = new AccentMap(new char[] { 'A', '\u00c3', 'O', '\u00d5', 'a', '\u00e3', 'n', '\u00f1', 'o', '\u00f5', }, ""); public static final AccentMap UMLAUT = new AccentMap(new char[] { 'A', '\u00c4', 'E', '\u00cb', 'I', '\u00cf', 'O', '\u00d6', 'U', '\u00dc', 'a', '\u00e4', 'e', '\u00eb', 'i', '\u00ef', 'o', '\u00f6', 'u', '\u00fc' }, ""); }
package uk.co.vurt.taskhelper.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import uk.co.vurt.taskhelper.domain.definition.TaskDefinition; import uk.co.vurt.taskhelper.domain.job.JobDefinition; import uk.co.vurt.taskhelper.domain.job.Submission; import android.accounts.Account; import android.content.Context; import android.net.ParseException; import android.preference.PreferenceManager; import android.util.Log; final public class NetworkUtilities { /** The tag used to log to adb console. **/ private static final String TAG = "NetworkUtilities"; /** The Intent extra to store password. **/ public static final String PARAM_PASSWORD = "password"; public static final String PARAM_AUTHTOKEN = "authToken"; /** The Intent extra to store username. **/ public static final String PARAM_USERNAME = "username"; public static final String PARAM_UPDATED = "timestamp"; public static final String USER_AGENT = "TaskHelper/1.0"; public static final int REQUEST_TIMEOUT_MS = 30 * 1000; //public static final String BASE_URL = "http://dev.vurt.co.uk/taskhelper"; /**TODO: Load Server URL from resource file?? */ // public static final String BASE_URL = "http://10.32.48.36:8080/taskhelper_server"; /**TODO: Load Server URL from resource file?? */ //public static final String BASE_URL = "http://appsdev.wmfs.net:8280/taskhelper_server"; /**TODO: Load Server URL from resource file?? */ public static final String AUTH_URI = "/auth"; public static final String FETCH_JOBS_URI = "/jobs/for"; // public static final String FETCH_TASK_DEFINITIONS_URI = "/taskdefinitions"; public static final String SUBMIT_JOB_DATA_URI = "/submissions/job/"; private NetworkUtilities() { } private static String getBaseUrl(Context context){ return PreferenceManager.getDefaultSharedPreferences(context).getString("sync_server", null); } /** * Configures the httpClient to connect to the URL provided. */ public static HttpClient getHttpClient() { HttpClient httpClient = new DefaultHttpClient(); final HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT_MS); HttpConnectionParams.setSoTimeout(params, REQUEST_TIMEOUT_MS); ConnManagerParams.setTimeout(params, REQUEST_TIMEOUT_MS); return httpClient; } /** * Connects to the server, authenticates the provided username and * password. * * @param username The user's username * @param password The user's password * @param handler The hander instance from the calling UI thread. * @param context The context of the calling Activity. * @return boolean The boolean result indicating whether the user was * successfully authenticated. */ public static String authenticate(Context context, String username, String password) { final HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); HttpEntity entity = null; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new AssertionError(e); } String baseUrl = getBaseUrl(context); if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "Authentication to: " + baseUrl + AUTH_URI); } final HttpPost post = new HttpPost(baseUrl + AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); String authToken = null; try { resp = getHttpClient().execute(post); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = (resp.getEntity() != null) ? resp.getEntity().getContent() : null; if(inputStream != null){ BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); authToken = reader.readLine().trim(); } } if((authToken != null) && (authToken.length() > 0)){ if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "Successful authentication: " + authToken); } } else { if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "Error authenticating" + resp.getStatusLine()); } } } catch (final IOException e) { if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "IOException when getting authtoken", e); } } finally { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "getAuthtoken completing"); } } return authToken; } /** * Submit job data back to the server * * essentially json encoded version of the dataitems submitted as form * data. * @param account * @param authToken * @return */ public static boolean submitData(Context context, Account account, String authToken, Submission submission){ StringEntity stringEntity; try { stringEntity = new StringEntity(submission.toJSON().toString()); final HttpPost post = new HttpPost(getBaseUrl(context) + SUBMIT_JOB_DATA_URI); post.setEntity(stringEntity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); final HttpResponse httpResponse = getHttpClient().execute(post); if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED){ return true; }else{ Log.e(TAG, "Data submission failed: " + httpResponse.getStatusLine().getStatusCode()); return false; } } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unable to convert submission to JSON", e); } catch (ClientProtocolException e) { Log.e(TAG, "Error submitting json", e); } catch (IOException e) { Log.e(TAG, "Error submitting json", e); } return false; } public static List<JobDefinition> fetchJobs(Context context, Account account, String authToken, Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<JobDefinition> jobList = new ArrayList<JobDefinition>(); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String data = fetchData(getBaseUrl(context) + FETCH_JOBS_URI + "/" + account.name + "/" + dateFormatter.format(lastUpdated), null, null, null); Log.d(TAG, "JOBS DATA: " + data); final JSONArray jobs = new JSONArray(data); for (int i = 0; i < jobs.length(); i++) { jobList.add(JobDefinition.valueOf(jobs.getJSONObject(i))); } return jobList; } private static String fetchData(String url, Account account, String authToken, ArrayList<NameValuePair> params) throws ClientProtocolException, IOException, AuthenticationException{ Log.d(TAG, "Fetching data from: " + url); String data = null; if(params == null){ params = new ArrayList<NameValuePair>(); } if(account != null){ params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); params.add(new BasicNameValuePair(PARAM_AUTHTOKEN, authToken)); } Log.i(TAG, params.toString()); HttpEntity entity = new UrlEncodedFormEntity(params); final HttpPost post = new HttpPost(url); post.addHeader(entity.getContentType()); post.setEntity(entity); final HttpResponse httpResponse = getHttpClient().execute(post); if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ data = EntityUtils.toString(httpResponse.getEntity()); } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in fetching remote task definitions"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in fetching remote task definitions: " + httpResponse.getStatusLine()); throw new IOException(); } return data; } public static List<TaskDefinition> fetchTaskDefinitions(Account account, String authToken, Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<TaskDefinition> definitionList = new ArrayList<TaskDefinition>(); /** * I'm commenting this out for the time being as the current emphasis is on working with lists of pre-set jobs, rather than choosing * from a list of possible tasks. It'll be reinstated as and when required. */ // final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); // params.add(new BasicNameValuePair(PARAM_AUTHTOKEN, authToken)); // if (lastUpdated != null) { // final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter.format(lastUpdated))); // Log.i(TAG, params.toString()); // HttpEntity entity = null; // entity = new UrlEncodedFormEntity(params); // final HttpPost post = new HttpPost(FETCH_TASK_DEFINITIONS_URI); // post.addHeader(entity.getContentType()); // post.setEntity(entity); // final HttpResponse resp = getHttpClient().execute(post); // final String response = EntityUtils.toString(resp.getEntity()); // if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // // Succesfully connected to the samplesyncadapter server and // // authenticated. // final JSONArray definitions = new JSONArray(response); // Log.d(TAG, response); // for (int i = 0; i < definitions.length(); i++) { // definitionList.add(TaskDefinition.valueOf(definitions.getJSONObject(i))); // } else { // if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { // Log.e(TAG, "Authentication exception in fetching remote task definitions"); // throw new AuthenticationException(); // } else { // Log.e(TAG, "Server error in fetching remote task definitions: " + resp.getStatusLine()); // throw new IOException(); return definitionList; } }
/* * $Log: ResultWriter.java,v $ * Revision 1.6 2007-09-19 13:22:25 europe\L190409 * avoid NPE * * Revision 1.5 2007/09/19 13:00:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added openDocument() and closeDocument() * added openBlock() and closeBlock() * * Revision 1.4 2007/09/11 11:51:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.3 2007/09/10 11:11:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed logic processing from writePrefix to calling class * renamed writePrefix() and writeSuffix() into open/closeRecordType() * * Revision 1.2 2007/09/05 13:02:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.1 2007/08/03 08:37:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * first version * */ package nl.nn.adapterframework.batch; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import nl.nn.adapterframework.core.PipeLineSession; import org.apache.commons.lang.StringUtils; /** * Baseclass for resulthandlers that write the transformed record to a writer. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>classname</td><td>nl.nn.adapterframework.batch.ResultWriter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>Name of the resulthandler</td><td>&nbsp;</td></tr> * <tr><td>{@link #setPrefix(String) prefix}</td><td>Prefix that has to be written before record, if the record is in another block than the previous record</td><td>&nbsp;</td></tr> * <tr><td>{@link #setSuffix(String) suffix}</td><td>Suffix that has to be written after the record, if the record is in another block than the next record</td><td>&nbsp;</td></tr> * <tr><td>{@link #setDefault(boolean) default}</td><td>If true, this resulthandler is the default for all RecordHandlingFlow that do not have a handler specified</td><td>&nbsp;</td></tr> * </table> * </p> * * @author Gerrit van Brakel * @since 4.7 * @version Id */ public abstract class ResultWriter extends AbstractResultHandler { public static final String version = "$RCSfile: ResultWriter.java,v $ $Revision: 1.6 $ $Date: 2007-09-19 13:22:25 $"; private String onOpenDocument="<document name=\"#name#\">"; private String onCloseDocument="</document>"; private String onOpenBlock="<#name#>"; private String onCloseBlock="</#name#>"; private String blockNamePattern="#name#"; private Map openWriters = Collections.synchronizedMap(new HashMap()); protected abstract Writer createWriter(PipeLineSession session, String streamId) throws Exception; public void openDocument(PipeLineSession session, String streamId) throws Exception { super.openDocument(session,streamId); getWriter(session, streamId, true); write(session,streamId,replacePattern(getOnOpenDocument(),streamId)); } public void closeDocument(PipeLineSession session, String streamId) { Writer w = (Writer)openWriters.remove(streamId); if (w != null) { try { w.close(); } catch (IOException e) { log.error("Exception closing ["+streamId+"]",e); } } super.closeDocument(session,streamId); } public Object finalizeResult(PipeLineSession session, String streamId, boolean error) throws Exception { log.debug("finalizeResult ["+streamId+"]"); write(session,streamId,replacePattern(getOnCloseDocument(),streamId)); return null; } public void handleResult(PipeLineSession session, String streamId, String recordKey, Object result) throws Exception { if (result instanceof String) { write(session, streamId, (String)result); } else if (result instanceof String[]) { write(session, streamId, (String[])result); } } protected void writeNewLine(Writer w) throws IOException { if (w instanceof BufferedWriter) { ((BufferedWriter)w).newLine(); } else { w.write("\n"); } } private void write(PipeLineSession session, String streamId, String line) throws Exception { if (line!=null) { Writer w = getWriter(session, streamId, false); if (w==null) { throw new NullPointerException("No Writer Found for stream ["+streamId+"]"); } w.write(line); writeNewLine(w); } } private void write(PipeLineSession session, String streamId, String[] lines) throws Exception { Writer w = getWriter(session, streamId, false); for (int i = 0; i < lines.length; i++) { if (lines[i]!=null) { w.write(lines[i]); writeNewLine(w); } } } public void openRecordType(PipeLineSession session, String streamId) throws Exception { Writer w = getWriter(session, streamId, false); if (w != null && ! StringUtils.isEmpty(getPrefix())) { write(session, streamId, getPrefix()); } } public void closeRecordType(PipeLineSession session, String streamId) throws Exception { Writer w = getWriter(session, streamId, false); if (w != null && ! StringUtils.isEmpty(getSuffix())) { write(session, streamId, getSuffix()); } } protected String replacePattern(String target, String blockName) { if (StringUtils.isEmpty(target)) { return null; } if (StringUtils.isEmpty(getBlockNamePattern())) { return target; } String result=target.replaceAll(getBlockNamePattern(),blockName); //if (log.isDebugEnabled()) log.debug("target ["+target+"] pattern ["+getBlockNamePattern()+"] value ["+blockName+"] result ["+result+"]"); return result; } public void openBlock(PipeLineSession session, String streamId, String blockName) throws Exception { write(session,streamId, replacePattern(getOnOpenBlock(),blockName)); } public void closeBlock(PipeLineSession session, String streamId, String blockName) throws Exception { write(session,streamId, replacePattern(getOnCloseBlock(),blockName)); } protected Writer getWriter(PipeLineSession session, String streamId, boolean create) throws Exception { log.debug("getWriter ["+streamId+"], create ["+create+"]"); Writer writer; writer = (Writer)openWriters.get(streamId); if (writer != null) { return writer; } if (!create) { return null; } writer = createWriter(session,streamId); if (writer==null) { throw new IOException("cannot get writer for stream ["+streamId+"]"); } openWriters.put(streamId,writer); return writer; } public void setOnOpenDocument(String line) { onOpenDocument = line; } public String getOnOpenDocument() { return onOpenDocument; } public void setOnCloseDocument(String line) { onCloseDocument = line; } public String getOnCloseDocument() { return onCloseDocument; } public void setOnOpenBlock(String line) { onOpenBlock = line; } public String getOnOpenBlock() { return onOpenBlock; } public void setOnCloseBlock(String line) { onCloseBlock = line; } public String getOnCloseBlock() { return onCloseBlock; } public void setBlockNamePattern(String pattern) { blockNamePattern = pattern; } public String getBlockNamePattern() { return blockNamePattern; } }
package us.kbase.typedobj.db.test; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import us.kbase.typedobj.core.AbsoluteTypeDefId; import us.kbase.typedobj.core.TypeDefId; import us.kbase.typedobj.core.TypeDefName; import us.kbase.typedobj.db.FileTypeStorage; import us.kbase.typedobj.db.MongoTypeStorage; import us.kbase.typedobj.db.RefInfo; import us.kbase.typedobj.db.SemanticVersion; import us.kbase.typedobj.db.TypeChange; import us.kbase.typedobj.db.TypeDefinitionDB; import us.kbase.typedobj.db.TypeStorage; import us.kbase.typedobj.db.UserInfoProviderForTests; import us.kbase.typedobj.exceptions.TypeStorageException; @RunWith(Parameterized.class) public class TypeRegisteringTest { private TestTypeStorage storage = null; private TypeDefinitionDB db = null; private final boolean useMongo; private static String adminUser = "admin"; public static void main(String[] args) throws Exception { TypeRegisteringTest test = new TypeRegisteringTest(false); test.cleanupBefore(); try { test.testRollback(); } finally { test.cleanupAfter(); } } public TypeRegisteringTest(boolean useMongoParam) throws Exception { useMongo = useMongoParam; File dir = new File("temp_files"); if (!dir.exists()) dir.mkdir(); TypeStorage innerStorage; if (useMongo) { innerStorage = new MongoTypeStorage(new MongoClient("localhost", MongoClientOptions.builder().autoConnectRetry(true).build()).getDB(getTestDbName())); } else { innerStorage = new FileTypeStorage(dir.getAbsolutePath()); } storage = TestTypeStorageFactory.createTypeStorageWrapper(innerStorage); db = new TypeDefinitionDB(storage, dir, new UserInfoProviderForTests()); } @Parameters public static Collection<Object[]> generateData() { return Arrays.asList(new Object[][] { {false}, {true} }); } private static String getTestDbName() { String ret = System.getProperty("test.mongo.db1"); if (ret == null) ret = "test"; return ret; } @Before public void cleanupBefore() throws Exception { storage.removeAllData(); storage.removeAllTypeStorageListeners(); } @After public void cleanupAfter() throws Exception { //cleanupBefore(); } @Test public void testSimple() throws Exception { String user = adminUser; String taxonomySpec = loadSpec("simple", "Taxonomy"); initModule("Taxonomy", user); readOnlyMode(); db.registerModule(taxonomySpec, Arrays.asList("taxon"), Collections.<String>emptyList(), user, true); storage.removeAllTypeStorageListeners(); db.registerModule(taxonomySpec, Arrays.asList("taxon"), user); releaseType("Taxonomy", "taxon", user); String sequenceSpec = loadSpec("simple", "Sequence"); initModule("Sequence", user); db.registerModule(sequenceSpec, Arrays.asList("sequence_id", "sequence_pos"), user); releaseType("Sequence", "sequence_id", user); releaseType("Sequence", "sequence_pos", user); String annotationSpec = loadSpec("simple", "Annotation"); initModule("Annotation", user); db.registerModule(annotationSpec, Arrays.asList("genome", "gene"), user); releaseType("Annotation", "genome", user); releaseType("Annotation", "gene", user); checkTypeDep("Annotation", "gene", "Sequence", "sequence_pos", null, true); String regulationSpec = loadSpec("simple", "Regulation"); initModule("Regulation", user); db.registerModule(regulationSpec, Arrays.asList("regulator", "binding_site"), user); checkTypeDep("Regulation", "binding_site", "Regulation", "regulator", "0.1", true); releaseType("Regulation", "regulator", user); releaseType("Regulation", "binding_site", user); checkTypeDep("Regulation", "binding_site", "Regulation", "regulator", "1.0", true); String reg2spec = loadSpec("simple", "Regulation", "2"); readOnlyMode(); Map<TypeDefName, TypeChange> changes = db.registerModule(reg2spec, Arrays.asList("new_regulator"), Collections.<String>emptyList(), user, true); Assert.assertEquals(3, changes.size()); Assert.assertFalse(changes.get(new TypeDefName("Regulation.new_regulator")).isUnregistered()); Assert.assertEquals("0.1", changes.get(new TypeDefName("Regulation.new_regulator")).getTypeVersion().getVerString()); Assert.assertFalse(changes.get(new TypeDefName("Regulation.binding_site")).isUnregistered()); Assert.assertEquals("2.0", changes.get(new TypeDefName("Regulation.binding_site")).getTypeVersion().getVerString()); Assert.assertTrue(changes.get(new TypeDefName("Regulation.regulator")).isUnregistered()); storage.removeAllTypeStorageListeners(); db.registerModule(reg2spec, Arrays.asList("new_regulator"), Collections.<String>emptyList(), user); checkTypeDep("Regulation", "binding_site", "Regulation", "regulator", null, false); checkTypeDep("Regulation", "binding_site", "Regulation", "new_regulator", "0.1", true); Assert.assertEquals(5, db.getAllModuleVersions("Regulation").size()); Assert.assertEquals("2.0", db.getLatestTypeVersion(new TypeDefName("Regulation.binding_site"))); } @Test public void testDescr() throws Exception { String sequenceSpec = loadSpec("descr", "Descr"); initModule("Descr", adminUser); db.registerModule(sequenceSpec, Arrays.asList("sequence_id", "sequence_pos"), adminUser); Assert.assertEquals("Descr module.\n\nEnd of comment.", db.getModuleDescription("Descr")); Assert.assertEquals("", db.getTypeDescription(new TypeDefId("Descr.sequence_id"))); Assert.assertEquals("", db.getFuncDescription("Descr", "invis_func", null)); Assert.assertEquals("position of fragment on a sequence", db.getTypeDescription(new TypeDefId("Descr.sequence_pos"))); Assert.assertEquals("The super function.", db.getFuncDescription("Descr", "super_func", null)); } @Test public void testBackward() throws Exception { String regulationSpec = loadSpec("backward", "Regulation"); initModule("Regulation", adminUser); db.registerModule(regulationSpec, Arrays.asList("gene", "binding_site"), adminUser); releaseType("Regulation", "gene", adminUser); releaseType("Regulation", "binding_site", adminUser); db.releaseFunc("Regulation", "get_gene_descr", adminUser); db.releaseFunc("Regulation", "get_nearest_binding_sites", adminUser); db.releaseFunc("Regulation", "get_regulated_genes", adminUser); String reg2spec = loadSpec("backward", "Regulation", "2"); Map<TypeDefName, TypeChange> changes = db.registerModule(reg2spec, Arrays.<String>asList(), Collections.<String>emptyList(), adminUser); Assert.assertEquals(2, changes.size()); Assert.assertEquals("1.1", changes.get(new TypeDefName("Regulation.gene")).getTypeVersion().getVerString()); Assert.assertEquals("2.0", changes.get(new TypeDefName("Regulation.binding_site")).getTypeVersion().getVerString()); checkFuncVer("Regulation", "get_gene_descr", "2.0"); checkFuncVer("Regulation", "get_nearest_binding_sites", "2.0"); checkFuncVer("Regulation", "get_regulated_genes", "1.1"); String reg3spec = loadSpec("backward", "Regulation", "3"); Map<TypeDefName, TypeChange> changes3 = db.registerModule(reg3spec, Arrays.<String>asList(), Collections.<String>emptyList(), adminUser); Assert.assertEquals(2, changes3.size()); Assert.assertEquals("1.2", changes3.get(new TypeDefName("Regulation.gene")).getTypeVersion().getVerString()); Assert.assertEquals("3.0", changes3.get(new TypeDefName("Regulation.binding_site")).getTypeVersion().getVerString()); checkFuncVer("Regulation", "get_gene_descr", "2.0"); checkFuncVer("Regulation", "get_nearest_binding_sites", "3.0"); checkFuncVer("Regulation", "get_regulated_genes", "1.2"); String reg4spec = loadSpec("backward", "Regulation", "4"); Map<TypeDefName, TypeChange> changes4 = db.registerModule(reg4spec, Arrays.<String>asList(), Collections.<String>emptyList(), adminUser); Assert.assertEquals(2, changes4.size()); Assert.assertEquals("2.0", changes4.get(new TypeDefName("Regulation.gene")).getTypeVersion().getVerString()); Assert.assertEquals("4.0", changes4.get(new TypeDefName("Regulation.binding_site")).getTypeVersion().getVerString()); checkFuncVer("Regulation", "get_gene_descr", "3.0"); checkFuncVer("Regulation", "get_nearest_binding_sites", "4.0"); checkFuncVer("Regulation", "get_regulated_genes", "2.0"); } @Test public void testRollback() throws Exception { String spec1 = loadSpec("rollback", "First"); initModule("First", adminUser); long verAfterInit = db.getLastModuleVersion("First"); int typesAfterInit = db.getAllRegisteredTypes("First").size(); int funcsAfterInit = db.getAllRegisteredFuncs("First").size(); String objAfterInit = getStorageObjects(); for (String errMethod : Arrays.asList( "writeTypeSchemaRecord", "writeTypeParseRecord", "writeFuncParseRecord", "writeModuleRecords", "addRefs")) { storage.removeAllTypeStorageListeners(); withErrorAfterMethod(errMethod); Assert.assertEquals(1, storage.getTypeStorageListeners().size()); try { db.registerModule(spec1, Arrays.asList("seq_id", "seq_pos"), adminUser); Assert.fail("Error should occur before this line"); } catch (Exception ex) { Assert.assertEquals("Method has test error at the end of body.", ex.getMessage()); Assert.assertEquals(verAfterInit, db.getLastModuleVersion("First")); Assert.assertEquals(typesAfterInit, db.getAllRegisteredTypes("First").size()); Assert.assertEquals(funcsAfterInit, db.getAllRegisteredFuncs("First").size()); Assert.assertEquals(objAfterInit, getStorageObjects()); } } } private String getStorageObjects() throws Exception { Map<String, Long> ret = storage.listObjects(); for (String key : new ArrayList<String>(ret.keySet())) if (ret.get(key) == 0) ret.remove(key); return "" + ret; } private void checkFuncVer(String module, String funcName, String version) throws Exception { Assert.assertEquals(version, db.getLatestFuncVersion(module, funcName)); } private void readOnlyMode() { storage.addTypeStorageListener(new TypeStorageListener() { @Override public void onMethodStart(String method, Object[] params) throws TypeStorageException { if (method.startsWith("add") || method.startsWith("write") || method.startsWith("init") || method.startsWith("remove")) throw new TypeStorageException("Type storage is in read only mode."); } @Override public void onMethodEnd(String method, Object[] params, Object ret) throws TypeStorageException { } }); } private void withErrorAfterMethod(final String errMethodName) { storage.addTypeStorageListener(new TypeStorageListener() { @Override public void onMethodStart(String method, Object[] params) throws TypeStorageException { //System.out.println("TypeStorage method starts: " + method); } @Override public void onMethodEnd(String method, Object[] params, Object ret) throws TypeStorageException { if (method.equals(errMethodName)) throw new TypeStorageException("Method has test error at the end of body."); } }); } private void initModule(String moduleName, String user) throws Exception { db.requestModuleRegistration(moduleName, user); db.approveModuleRegistrationRequest(adminUser, moduleName, user); } private void releaseType(String module, String type, String user) throws Exception { db.releaseType(new TypeDefName(module + "." + type), user); } private String loadSpec(String testName, String specName) throws Exception { return loadSpec(testName, specName, null); } private String loadSpec(String testName, String specName, String version) throws Exception { String resName = testName + "." + specName + (version == null ? "" : ("." +version)) + ".spec.properties"; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream is = getClass().getResourceAsStream(resName); if (is == null) throw new IllegalStateException("Resource not found: " + resName); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String line = br.readLine(); if (line == null) break; pw.println(line); } br.close(); pw.close(); return sw.toString(); } private void checkTypeDep(String depModule, String depType, String refModule, String refType, String refVer, boolean res) throws Exception { SemanticVersion depVer = new SemanticVersion(db.getLatestTypeVersion(new TypeDefName(depModule + "." + depType))); Set<RefInfo> refs = db.getTypeRefsByDep(new AbsoluteTypeDefId(new TypeDefName(depModule + "." + depType), depVer.getMajor(), depVer.getMinor())); RefInfo ret = null; for (RefInfo ri : refs) { if (ri.getRefModule().equals(refModule) && ri.getRefName().equals(refType)) { ret = ri; break; } } Assert.assertEquals(res, ret != null); if (ret != null && refVer != null) { Assert.assertEquals(refVer, ret.getRefVersion()); } } }
package com.beetle.framework.util.structure; public class DynamicByteArray { private static int INITIAL_CAPACITY = 10;; private int totalCapacity; private int size; private byte[] b; public DynamicByteArray(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); this.b = new byte[initialCapacity]; totalCapacity = initialCapacity; size = 0; } public DynamicByteArray() { this(INITIAL_CAPACITY); } public int size() { return size; } public byte[] getBytes() { return b; } public void add(byte[] incrb) { add(incrb, incrb.length); } public void add(byte[] incrb, int flag) { int iAdd = flag + size - totalCapacity; if (iAdd > 0) { totalCapacity = flag + size; byte[] oldByte = this.b; this.b = new byte[totalCapacity]; System.arraycopy(oldByte, 0, this.b, 0, oldByte.length); } System.arraycopy(incrb, 0, this.b, size, flag); size = size + flag; } }
package hevs.aislab.magpie.android; import hevs.aislab.magpie.android.MagpieService.MagpieBinder; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.util.Log; public abstract class MagpieActivity extends Activity implements ServiceConnection, MagpieConnection { /** * Used for debugging */ private final String TAG = getClass().getName(); protected MagpieService mService; public MagpieActivity() { } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart()"); Intent intent = MagpieService.makeIntent(this); bindService(intent, this, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { Log.i(TAG, "onStop()"); unbindService(this); super.onStop(); } @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "onServiceConnected()"); mService = ((MagpieBinder) service).getService(); onEnvironmentConnected(); } @Override public void onServiceDisconnected(ComponentName arg0) { } }
package ameba.container.grizzly.server; import ameba.Ameba; import ameba.container.Container; import ameba.container.grizzly.server.http.GrizzlyHttpContainer; import ameba.container.grizzly.server.http.GrizzlyServerUtil; import ameba.container.grizzly.server.http.websocket.WebSocketServerContainer; import ameba.container.server.Connector; import ameba.core.Application; import ameba.exception.AmebaException; import ameba.i18n.Messages; import ameba.util.ClassUtils; import ameba.websocket.WebSocketException; import ameba.websocket.WebSocketFeature; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.glassfish.grizzly.GrizzlyFuture; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.NetworkListener; import org.glassfish.grizzly.http.server.ServerConfiguration; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.threadpool.ThreadPoolConfig; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.jersey.server.ContainerFactory; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.tyrus.core.Utils; import javax.websocket.DeploymentException; import javax.websocket.server.ServerContainer; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @author icode */ public class GrizzlyContainer extends Container { public static final String WEB_SOCKET_CONTEXT_PATH = "websocket.contextPath"; /** * Server-side property to set custom worker {@link org.glassfish.grizzly.threadpool.ThreadPoolConfig}. * <p/> * Value is expected to be instance of {@link org.glassfish.grizzly.threadpool.ThreadPoolConfig}, can be {@code null} (it won't be used). */ public static final String WORKER_THREAD_POOL_CONFIG = "container.server.workerThreadPoolConfig"; /** * Server-side property to set custom selector {@link org.glassfish.grizzly.threadpool.ThreadPoolConfig}. * <p/> * Value is expected to be instance of {@link org.glassfish.grizzly.threadpool.ThreadPoolConfig}, can be {@code null} (it won't be used). */ public static final String SELECTOR_THREAD_POOL_CONFIG = "container.server.selectorThreadPoolConfig"; private static final String TYPE_NAME = "Grizzly"; private HttpServer httpServer; private GrizzlyHttpContainer container; private WebSocketContainerProvider webSocketServerContainerProvider; private WebSocketServerContainer webSocketServerContainer; private List<Connector> connectors; private boolean webSocketEnabled; public GrizzlyContainer(Application app) { super(app); } @Override public ServiceLocator getServiceLocator() { return container.getApplicationHandler().getServiceLocator(); } private void buildWebSocketContainer() { webSocketServerContainer = new WebSocketServerContainer(getApplication().getProperties()); } @Override protected void configureHttpServer() { final Map<String, Object> properties = getApplication().getProperties(); connectors = Connector.createDefaultConnectors(properties); if (connectors.size() == 0) { logger.warn(Messages.get("info.connector.none")); connectors.add(Connector.createDefault(Maps.<String, String>newHashMap())); } List<NetworkListener> listeners = GrizzlyServerUtil.createListeners(connectors, GrizzlyServerUtil.createCompressionConfig("http", properties)); webSocketEnabled = !"false".equals(properties.get(WebSocketFeature.WEB_SOCKET_ENABLED_CONF)); final String contextPath = StringUtils.defaultIfBlank((String) properties.get(WEB_SOCKET_CONTEXT_PATH), "/"); if (webSocketEnabled) { buildWebSocketContainer(); GrizzlyServerUtil.bindWebSocket(contextPath, getWebSocketContainerProvider(), listeners); } httpServer = new HttpServer() { @Override public synchronized void start() throws IOException { if (webSocketServerContainer != null) try { webSocketServerContainer.start(contextPath, -1); } catch (DeploymentException e) { logger.error("websocket", e); } super.start(); } @Override public synchronized GrizzlyFuture<HttpServer> shutdown(long gracePeriod, TimeUnit timeUnit) { if (webSocketServerContainer != null) webSocketServerContainer.stop(); return super.shutdown(gracePeriod, timeUnit); } @Override public synchronized void shutdownNow() { if (webSocketServerContainer != null) webSocketServerContainer.stop(); super.shutdownNow(); } }; httpServer.getServerConfiguration().setJmxEnabled(getApplication().isJmxEnabled()); ThreadPoolConfig workerThreadPoolConfig = null; String workerThreadPoolConfigClass = Utils.getProperty(properties, WORKER_THREAD_POOL_CONFIG, String.class); if (StringUtils.isNotBlank(workerThreadPoolConfigClass)) { workerThreadPoolConfig = ClassUtils.newInstance(workerThreadPoolConfigClass); } ThreadPoolConfig selectorThreadPoolConfig = null; String selectorThreadPoolConfigClass = Utils.getProperty(properties, SELECTOR_THREAD_POOL_CONFIG, String.class); if (StringUtils.isNotBlank(selectorThreadPoolConfigClass)) { selectorThreadPoolConfig = ClassUtils.newInstance(selectorThreadPoolConfigClass); } TCPNIOTransportBuilder transportBuilder = null; if (workerThreadPoolConfig != null || selectorThreadPoolConfig != null) { transportBuilder = TCPNIOTransportBuilder.newInstance(); if (workerThreadPoolConfig != null) { transportBuilder.setWorkerThreadPoolConfig(workerThreadPoolConfig); } if (selectorThreadPoolConfig != null) { transportBuilder.setSelectorThreadPoolConfig(selectorThreadPoolConfig); } } for (NetworkListener listener : listeners) { if (transportBuilder != null) { listener.setTransport(transportBuilder.build()); } httpServer.addListener(listener); } final ServerConfiguration config = httpServer.getServerConfiguration(); config.setPassTraceRequest(true); config.setHttpServerName(getApplication().getApplicationName()); String version = getApplication().getApplicationVersion().toString(); config.setHttpServerVersion( config.getHttpServerName().equals(Application.DEFAULT_APP_NAME) ? Ameba.getVersion() : version); config.setName("Ameba-HttpServer-" + getApplication().getApplicationName()); } @Override protected void configureHttpContainer() { container = ContainerFactory.createContainer(GrizzlyHttpContainer.class, getApplication().getConfig()); ServerConfiguration serverConfiguration = httpServer.getServerConfiguration(); String charset = StringUtils.defaultIfBlank((String) getApplication().getProperty("app.encoding"), "utf-8"); serverConfiguration.setSendFileEnabled(true); serverConfiguration.setDefaultQueryEncoding(Charset.forName(charset)); GrizzlyHttpContainer httpHandler = container; httpHandler.setRequestURIEncoding(charset); serverConfiguration.addHttpHandler(httpHandler); } @Override public ServerContainer getWebSocketContainer() { return webSocketServerContainer; } @Override protected void configureWebSocketContainerProvider() { webSocketServerContainerProvider = new WebSocketContainerProvider() { @Override public void dispose(ServerContainer serverContainer) { if (serverContainer instanceof org.glassfish.tyrus.spi.ServerContainer) ((org.glassfish.tyrus.spi.ServerContainer) serverContainer).stop(); } }; } @Override protected WebSocketContainerProvider getWebSocketContainerProvider() { return webSocketServerContainerProvider; } @Override protected void doReload(ResourceConfig odlConfig) { WebSocketServerContainer old = null; if (webSocketEnabled) { old = webSocketServerContainer; buildWebSocketContainer(); } container.reload(getApplication().getConfig()); if (webSocketServerContainer != null && old != null) try { webSocketServerContainer.start(old.getContextPath(), old.getPort()); } catch (IOException | DeploymentException e) { throw new WebSocketException("reload web socket endpoint error", e); } } @Override public void doStart() { try { httpServer.start(); } catch (IOException e) { throw new AmebaException("", e); } } @Override public void doShutdown() throws Exception { httpServer.shutdown().get(); } @Override public List<Connector> getConnectors() { return connectors; } @Override public String getType() { return TYPE_NAME; } }
package com.namelessdev.mpdroid; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDServerException; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.Music; import org.a0z.mpd.event.MPDConnectionStateChangedEvent; import org.a0z.mpd.event.MPDPlaylistChangedEvent; import org.a0z.mpd.event.MPDRandomChangedEvent; import org.a0z.mpd.event.MPDRepeatChangedEvent; import org.a0z.mpd.event.MPDStateChangedEvent; import org.a0z.mpd.event.MPDTrackChangedEvent; import org.a0z.mpd.event.MPDTrackPositionChangedEvent; import org.a0z.mpd.event.MPDUpdateStateChangedEvent; import org.a0z.mpd.event.MPDVolumeChangedEvent; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.event.TrackPositionListener; import com.namelessdev.mpdroid.R; import com.namelessdev.mpdroid.R.drawable; import com.namelessdev.mpdroid.R.id; import com.namelessdev.mpdroid.R.layout; import com.namelessdev.mpdroid.R.string; import com.namelessdev.mpdroid.CoverAsyncHelper.CoverDownloadListener; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.util.DisplayMetrics; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.SeekBar; import android.widget.ViewSwitcher.ViewFactory; public class MainMenuActivity extends Activity implements StatusChangeListener, TrackPositionListener, CoverDownloadListener { private Logger myLogger = Logger.global; public static final String PREFS_NAME = "mpdroid.properties"; public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; private TextView artistNameText; private TextView songNameText; private TextView albumNameText; public static final int ALBUMS = 4; public static final int FILES = 3; private SeekBar progressBarVolume = null; private SeekBar progressBarTrack = null; private TextView trackTime = null; private CoverAsyncHelper oCoverAsyncHelper = null; long lastSongTime = 0; long lastElapsedTime = 0; private ImageSwitcher coverSwitcher; private ProgressBar coverSwitcherProgress; private static final int VOLUME_STEP = 5; private static final int TRACK_STEP = 10; private static final int ANIMATION_DURATION_MSEC = 1000; private static Toast notification = null; private StreamingService streamingServiceBound; private boolean isStreamServiceBound; private ButtonEventHandler buttonEventHandler; private boolean streamingMode; private boolean connected; private Timer volTimer = new Timer(); private TimerTask volTimerTask = null; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SETTINGS: break; default: break; } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); //WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE); myLogger.log(Level.INFO, "onCreate"); MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.addStatusChangeListener(this); app.oMPDAsyncHelper.addTrackPositionListener(this); app.setActivity(this); //registerReceiver(, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION) ); registerReceiver(MPDConnectionHandler.getInstance(), new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION) ); gestureDetector = new GestureDetector(new MyGestureDetector()); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; //oMPDAsyncHelper.addConnectionListener(MPDConnectionHandler.getInstance(this)); init(); } @Override protected void onRestart() { super.onRestart(); myLogger.log(Level.INFO, "onRestart"); } @Override protected void onStart() { super.onStart(); myLogger.log(Level.INFO, "onStart"); } @Override protected void onResume() { super.onResume(); /* WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); int wifistate = wifi.getWifiState(); if(wifistate!=wifi.WIFI_STATE_ENABLED && wifistate!=wifi.WIFI_STATE_ENABLING) { setTitle("No WIFI"); return; } while(wifistate!=wifi.WIFI_STATE_ENABLED) setTitle("Waiting for WIFI"); */ } private void init() { setContentView(R.layout.main); streamingMode = ((MPDApplication)getApplication()).isStreamingMode(); connected = ((MPDApplication)getApplication()).oMPDAsyncHelper.oMPD.isConnected(); artistNameText = (TextView) findViewById(R.id.artistName); albumNameText = (TextView) findViewById(R.id.albumName); songNameText = (TextView) findViewById(R.id.songName); progressBarTrack = (SeekBar) findViewById(R.id.progress_track); progressBarVolume = (SeekBar) findViewById(R.id.progress_volume); trackTime = (TextView) findViewById(R.id.trackTime); Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); fadeIn.setDuration(ANIMATION_DURATION_MSEC); Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); fadeOut.setDuration(ANIMATION_DURATION_MSEC); coverSwitcher = (ImageSwitcher) findViewById(R.id.albumCover); coverSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView i = new ImageView(MainMenuActivity.this); i.setBackgroundColor(0x00FF0000); i.setScaleType(ImageView.ScaleType.FIT_CENTER); //i.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return i; } }); coverSwitcher.setInAnimation(fadeIn); coverSwitcher.setOutAnimation(fadeOut); coverSwitcherProgress = (ProgressBar) findViewById(R.id.albumCoverProgress); coverSwitcherProgress.setIndeterminate(true); coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); oCoverAsyncHelper = new CoverAsyncHelper(); oCoverAsyncHelper.addCoverDownloadListener(this); buttonEventHandler = new ButtonEventHandler(); ImageButton button = (ImageButton) findViewById(R.id.next); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.prev); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.back); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.playpause); button.setOnClickListener(buttonEventHandler); button.setOnLongClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.forward); button.setOnClickListener(buttonEventHandler); progressBarVolume.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub System.out.println("Vol2:" + progressBarVolume.getProgress()); } }); progressBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } public void onStartTrackingTouch(SeekBar seekBar) { volTimerTask = new TimerTask() { public void run() { MPDApplication app = (MPDApplication)getApplication(); try { if ( lastSentVol != progress.getProgress()) { lastSentVol = progress.getProgress(); app.oMPDAsyncHelper.oMPD.setVolume(lastSentVol); } } catch( MPDServerException e) { e.printStackTrace(); } } int lastSentVol = -1; SeekBar progress; public TimerTask setProgress(SeekBar prg) { progress = prg; return this; } }.setProgress(seekBar); volTimer.scheduleAtFixedRate(volTimerTask, 0, 100); } public void onStopTrackingTouch(SeekBar seekBar) { volTimerTask.cancel(); // Afraid this will run syncronious volTimerTask.run(); /* try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.setVolume(progress); } catch (MPDServerException e) { e.printStackTrace(); } */ } }); progressBarTrack.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStopTrackingTouch(SeekBar seekBar) { MPDApplication app = (MPDApplication)getApplication(); Runnable async = new Runnable(){ @SuppressWarnings("unchecked") @Override public void run() { try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.seek((int)progress); } catch (MPDServerException e) { e.printStackTrace(); } } public int progress; public Runnable setProgress(int prg) { progress =prg; return this; } }.setProgress(seekBar.getProgress()); app.oMPDAsyncHelper.execAsync(async); /* try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.seek((int)progress); } catch (MPDServerException e) { e.printStackTrace(); } */ } }); songNameText.setText(getResources().getString(R.string.notConnected)); myLogger.log(Level.INFO, "Initialization succeeded"); } private class ButtonEventHandler implements Button.OnClickListener, Button.OnLongClickListener { public void onClick(View v) { MPDApplication app = (MPDApplication)getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; Intent i = null; try { switch(v.getId()) { case R.id.next: mpd.next(); if(((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.RESET_STREAMING"); startService(i); } break; case R.id.prev: mpd.previous(); if(((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.RESET_STREAMING"); startService(i); } break; case R.id.back: mpd.seek(lastElapsedTime - TRACK_STEP); break; case R.id.forward: mpd.seek(lastElapsedTime + TRACK_STEP); break; case R.id.playpause: /** * If playing or paused, just toggle state, otherwise start playing. * @author slubman */ String state = mpd.getStatus().getState(); if(state.equals(MPDStatus.MPD_STATE_PLAYING) || state.equals(MPDStatus.MPD_STATE_PAUSED)) { mpd.pause(); } else { mpd.play(); } break; } } catch (MPDServerException e) { myLogger.log(Level.WARNING, e.getMessage()); } } public boolean onLongClick(View v) { MPDApplication app = (MPDApplication)getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; try { switch(v.getId()) { case R.id.playpause: // Implements the ability to stop playing (may be useful for streams) mpd.stop(); Intent i; if(((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.STOP_STREAMING"); startService(i); } break; default: return false; } return true; } catch (MPDServerException e) { } return true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { MPDApplication app = (MPDApplication)getApplication(); try { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: if(((MPDApplication) getApplication()).isStreamingMode()) { return super.onKeyDown(keyCode, event); } else { progressBarVolume.incrementProgressBy(VOLUME_STEP); app.oMPDAsyncHelper.oMPD.adjustVolume(VOLUME_STEP); return true; } case KeyEvent.KEYCODE_VOLUME_DOWN: if(((MPDApplication) getApplication()).isStreamingMode()) { return super.onKeyDown(keyCode, event); } else { progressBarVolume.incrementProgressBy(-VOLUME_STEP); app.oMPDAsyncHelper.oMPD.adjustVolume(-VOLUME_STEP); return true; } case KeyEvent.KEYCODE_DPAD_LEFT: app.oMPDAsyncHelper.oMPD.previous(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: app.oMPDAsyncHelper.oMPD.next(); return true; default: return super.onKeyDown(keyCode, event); } } catch (MPDServerException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); /*menu.add(0,ARTISTS, 0, R.string.artists).setIcon(R.drawable.ic_menu_pmix_artists); menu.add(0,ALBUMS, 1, R.string.albums).setIcon(R.drawable.ic_menu_pmix_albums); menu.add(0,FILES, 2, R.string.files).setIcon(android.R.drawable.ic_menu_agenda);*/ menu.add(0,LIBRARY, 1, R.string.libraryTabActivity).setIcon(R.drawable.ic_menu_music_library); menu.add(0,PLAYLIST, 3, R.string.playlist).setIcon(R.drawable.ic_menu_pmix_playlist); menu.add(0,STREAM, 4, R.string.stream).setIcon(android.R.drawable.ic_menu_upload_you_tube); menu.add(0,SETTINGS, 5, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences); return result; } @Override public boolean onTouchEvent ( MotionEvent event) { if (gestureDetector.onTouchEvent(event)) return true; return false; } class MyGestureDetector extends SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { // Next MPDApplication app = (MPDApplication)getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; mpd.next(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { // Previous MPDApplication app = (MPDApplication)getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; mpd.previous(); } } catch (Exception e) { // nothing } return false; } } @Override public boolean onPrepareOptionsMenu(Menu menu) { MPDApplication app = (MPDApplication)getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; if(!mpd.isConnected()) { if(menu.findItem(CONNECT) == null) { menu.findItem(LIBRARY).setEnabled(false); menu.findItem(PLAYLIST).setEnabled(false); menu.findItem(STREAM).setEnabled(false); menu.add(0,CONNECT, 0, R.string.connect); } } else { if(menu.findItem(CONNECT) != null) { menu.findItem(LIBRARY).setEnabled(true); menu.findItem(PLAYLIST).setEnabled(true); menu.findItem(STREAM).setEnabled(true); menu.removeItem(CONNECT); } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = null; switch (item.getItemId()) { case ARTISTS: i = new Intent(this, ArtistsActivity.class); startActivityForResult(i, ARTISTS); return true; case ALBUMS: i = new Intent(this, AlbumsActivity.class); startActivityForResult(i, ALBUMS); return true; case FILES: i = new Intent(this, FSActivity.class); startActivityForResult(i, FILES); return true; case LIBRARY: i = new Intent(this, LibraryTabActivity.class); startActivityForResult(i, SETTINGS); return true; case SETTINGS: if(((MPDApplication) getApplication()).oMPDAsyncHelper.oMPD.isMpdConnectionNull()) { startActivityForResult(new Intent(this, WifiConnectionSettings.class), SETTINGS); } else { i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); } return true; case PLAYLIST: i = new Intent(this, PlaylistActivity.class); startActivityForResult(i, PLAYLIST); // TODO juste pour s'y retrouver return true; case CONNECT: ((MPDApplication) getApplication()).connect(); return true; case STREAM: if(((MPDApplication) getApplication()).isStreamingMode()) { // yeah, yeah getApplication for that may be ugly but ... i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.DIE"); startService(i); ((MPDApplication) getApplication()).setStreamingMode(false); //Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.START_STREAMING"); startService(i); ((MPDApplication) getApplication()).setStreamingMode(true); //Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } return true; default: // showAlert("Menu Item Clicked", "Not yet implemented", "ok", null, // false, null); return true; } } //private MPDPlaylist playlist; public void playlistChanged(MPDPlaylistChangedEvent event) { try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.getPlaylist().refresh(); } catch (MPDServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void randomChanged(MPDRandomChangedEvent event) { // TODO Auto-generated method stub } public void repeatChanged(MPDRepeatChangedEvent event) { // TODO Auto-generated method stub } public void stateChanged(MPDStateChangedEvent event) { MPDStatus status = event.getMpdStatus(); String state = status.getState(); if(state!=null) { if(state.equals(MPDStatus.MPD_STATE_PLAYING)) { ImageButton button = (ImageButton) findViewById(R.id.playpause); button.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_pause)); } else { ImageButton button = (ImageButton) findViewById(R.id.playpause); button.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_play)); } } } private String lastArtist = ""; private String lastAlbum = ""; public void trackChanged(MPDTrackChangedEvent event) { MPDStatus status = event.getMpdStatus(); if(status!=null) { String state = status.getState(); if(state != null) { int songId = status.getSongPos(); if(songId>=0) { MPDApplication app = (MPDApplication)getApplication(); Music actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getMusic(songId); String artist = actSong.getArtist(); String title = actSong.getTitle(); String album = actSong.getAlbum(); artist = artist==null ? "" : artist; title = title==null ? "" : title; album = album==null ? "" : album; artistNameText.setText(artist); songNameText.setText(title); albumNameText.setText(album); progressBarTrack.setMax((int)actSong.getTime()); if(!lastAlbum.equals(album) || !lastArtist.equals(artist)) { //coverSwitcher.setVisibility(ImageSwitcher.INVISIBLE); coverSwitcherProgress.setVisibility(ProgressBar.VISIBLE); oCoverAsyncHelper.downloadCover(artist, album); lastArtist = artist; lastAlbum = album; } } else { artistNameText.setText(""); songNameText.setText(""); albumNameText.setText(""); progressBarTrack.setMax(0); } } } } public void updateStateChanged(MPDUpdateStateChangedEvent event) { // TODO Auto-generated method stub } @Override public void connectionStateChanged(MPDConnectionStateChangedEvent event) { // TODO Auto-generated method stub checkConnected(); /*MPDStatus status = event.getMpdStatus(); String state = status.getState();*/ } public void checkConnected() { connected = ((MPDApplication)getApplication()).oMPDAsyncHelper.oMPD.isConnected(); if(connected) { songNameText.setText(getResources().getString(R.string.noSongInfo)); } else { songNameText.setText(getResources().getString(R.string.notConnected)); } return; } public void volumeChanged(MPDVolumeChangedEvent event) { progressBarVolume.setProgress(event.getMpdStatus().getVolume()); } @Override protected void onPause() { super.onPause(); myLogger.log(Level.INFO, "onPause"); } @Override protected void onStop() { super.onStop(); myLogger.log(Level.INFO, "onStop"); } @Override protected void onDestroy() { super.onDestroy(); MPDApplication app = (MPDApplication)getApplicationContext(); app.oMPDAsyncHelper.removeStatusChangeListener(this); app.oMPDAsyncHelper.removeTrackPositionListener(this); app.unsetActivity(this); myLogger.log(Level.INFO, "onDestroy"); } public SeekBar getVolumeSeekBar() { return progressBarVolume; } public SeekBar getProgressBarTrack() { return progressBarTrack; } public void trackPositionChanged(MPDTrackPositionChangedEvent event) { MPDStatus status = event.getMpdStatus(); lastElapsedTime = status.getElapsedTime(); lastSongTime = status.getTotalTime(); trackTime.setText(timeToString(lastElapsedTime) + " - " + timeToString(lastSongTime)); progressBarTrack.setProgress((int) status.getElapsedTime()); } private static String timeToString(long seconds) { long min = seconds / 60; long sec = seconds - min * 60; return (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec); } public static void notifyUser(String message, Context context) { if (notification != null) { notification.setText(message); notification.show(); } else { notification = Toast.makeText(context, message, Toast.LENGTH_SHORT); notification.show(); } } public void onCoverDownloaded(Bitmap cover) { coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if(cover != null) { cover.setDensity((int)metrics.density); BitmapDrawable myCover = new BitmapDrawable(cover); coverSwitcher.setImageDrawable(myCover); //coverSwitcher.setVisibility(ImageSwitcher.VISIBLE); coverSwitcher.showNext(); //Little trick so the animation gets displayed coverSwitcher.showPrevious(); } else { // Should not be happening, but happened. onCoverNotFound(); } } public void onCoverNotFound() { coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); coverSwitcher.setImageResource(R.drawable.gmpcnocover); //coverSwitcher.setVisibility(ImageSwitcher.VISIBLE); } }
// (MIT) // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package be.yildiz.module.graphic.ogre; import be.yildiz.common.Color; import be.yildiz.common.Size; import be.yildiz.common.exeption.NativeException; import be.yildiz.common.log.Logger; import be.yildiz.common.nativeresources.NativeResourceLoader; import be.yildiz.common.resource.FileResource.FileType; import be.yildiz.common.util.Checker; import be.yildiz.common.util.Util; import be.yildiz.module.graphic.*; import be.yildiz.module.graphic.Shader.FragmentProfileList; import be.yildiz.module.graphic.Shader.ShaderType; import be.yildiz.module.graphic.Shader.VertexProfileList; import be.yildiz.module.window.WindowEngine; import be.yildiz.module.window.WindowHandle; import lombok.Getter; import lombok.NonNull; import java.io.File; public final class OgreGraphicEngine implements GraphicEngine { /** * Local part of the native Ogre::Root object, mainly used to build renderer, scene manager,.... */ private final Root root; /** * Ogre render window. */ private final RenderWindow renderWindow; @Getter private final OgreGuiBuilder guiBuilder; /** * Screen size. */ private final Size size; /** * Only one can be created at a time. */ private SelectionRectangle selection; /** * Deprecated use public OgreGraphicEngine(final WindowEngine windowEngine). */ @Deprecated public OgreGraphicEngine(final Size screenSize, final WindowHandle handle) { super(); this.size = screenSize; Logger.info("Initializing Ogre graphic engine..."); NativeResourceLoader.loadBaseLibrary("libgcc_s_sjlj-1", "libstdc++-6"); NativeResourceLoader.loadLibrary("libphysfs", "OgreMain", "OgreOverlay", "libyildizogre"); this.root = new Root(); this.loadPlugins(); this.loadRenderer(); this.renderWindow = this.root.createWindow(this.size, handle); this.guiBuilder = null; Logger.info("Ogre graphic engine initialized."); } /** * Simple constructor. * * @param windowEngine WindowEngine wrapping this graphic context. * @throws NullPointerException If windowEngine is null. */ //@Ensures this.size == windowEngine.size //@Ensures this.root != null public OgreGraphicEngine(final WindowEngine windowEngine) { super(); this.size = windowEngine.getScreenSize(); Logger.info("Initializing Ogre graphic engine..."); NativeResourceLoader.loadBaseLibrary("libgcc_s_sjlj-1", "libstdc++-6"); NativeResourceLoader.loadLibrary("libphysfs", "OgreMain", "OgreOverlay", "libyildizogre"); this.root = new Root(); this.loadPlugins(); this.loadRenderer(); if (Util.isLinux()) { this.renderWindow = this.root.createWindow(this.size); } else { this.renderWindow = this.root.createWindow(this.size, windowEngine.getHandle()); } this.guiBuilder = new OgreGuiBuilder(this.size); Logger.info("Ogre graphic engine initialized."); } @Deprecated public OgreGraphicEngine(final Size screenSize) { this(screenSize, new WindowHandle(0)); } private void loadPlugins() { this.root.setPlugin(NativeResourceLoader.getLibPath("Plugin_ParticleFX")); //this.root.setPlugin(NativeResourceLoader.getLibPath("Plugin_CgProgramManager")); } private void loadRenderer() { try { this.root.setRenderer(NativeResourceLoader.getLibPath("RenderSystem_GL")); } catch (NativeException e) { Logger.error(e); } } @Override public SelectionRectangle createSelectionRectangle(final Material texture, final Material material2) { if (this.selection == null) { this.selection = new OgreSelectionRectangle(texture, material2); } return this.selection; } @Override public OgreSceneManager createGraphicWorld(final String name, final ShadowType shadowType) { OgreSceneManager sm = new OgreSceneManager(this.root.createScene(name), this.renderWindow, this.size.width, this.size.height); sm.setShadowType(shadowType); return sm; } @Override public void close() { this.root.closeRoot(); } @Override public void printScreen() { this.renderWindow.getPrintScreen(); } @Override public void update() { this.root.render(); } @Override public void addResourcePath(final String name, final String path, final FileType type) { String[] cpEntries = System.getProperty("java.class.path", "").split(File.pathSeparator); boolean found = false; for (String cpEntry : cpEntries) { if (!cpEntry.contains(".jar")) { cpEntry = cpEntry.replace("\\", "/").replace("/target/classes", "/"); if (new File(cpEntry + path).exists()) { this.root.addResourcePath(name, cpEntry + path, type); found = true; break; } } } if (!found) { this.root.addResourcePath(name, path, type); } } @Override public Material createMaterial(final String name) { return new OgreMaterial(name); } @Override public OgreSkybox createSkybox(final String name, final String path) { return new OgreSkybox(name, path); } @Override public Font createFont(@NonNull String name, @NonNull String path, int size, @NonNull Color color) { Checker.exceptionNotGreaterThanZero(size); OgreFont font = new OgreFont(name, path, size, color); font.load(); return font; } @Override public float getFPS() { return this.renderWindow.getFramerate(); } @Override public Shader createFragmentShader(final String name, final String file, final String entry, final FragmentProfileList profile) { return new OgreShader(name, file, entry, ShaderType.FRAGMENT, profile); } @Override public Shader createVertexShader(final String name, final String file, final String entry, final VertexProfileList profile) { return new OgreShader(name, file, entry, ShaderType.VERTEX, profile); } @Override public ClientWorld createWorld() { OgreSceneManager graphic = this.createGraphicWorld("sc", ShadowType.NONE); return new OgreWorld(graphic); } @Override public Size getScreenSize() { return this.size; } }
package ch.openech.frontend.e07; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.minimalj.frontend.Frontend; import org.minimalj.frontend.Frontend.IComponent; import org.minimalj.frontend.Frontend.Input; import org.minimalj.frontend.form.element.AbstractFormElement; import org.minimalj.model.Keys; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.repository.sql.EmptyObjects; import org.minimalj.util.Codes; import org.minimalj.util.mock.Mocking; import ch.openech.datagenerator.DataGenerator; import ch.openech.model.common.MunicipalityIdentification; public class MunicipalityFormElement extends AbstractFormElement<MunicipalityIdentification> implements Mocking { private final List<MunicipalityIdentification> municipalities; private final Input<MunicipalityIdentification> comboBox; public MunicipalityFormElement(MunicipalityIdentification key, boolean allowFederalRegister) { this(Keys.getProperty(key), allowFederalRegister); } public MunicipalityFormElement(PropertyInterface property, boolean allowFederalRegister) { super(property); municipalities = Codes.get(MunicipalityIdentification.class); Collections.sort(municipalities); List<MunicipalityIdentification> items; if (!allowFederalRegister) { items = new ArrayList<>(); for (MunicipalityIdentification municipality : municipalities) { if (municipality.id > 0) { items.add(municipality); } } // Cheerpj doesn't work with Collectors.toList() // items = municipalities.stream().filter((municipalityIdentification) -> (municipalityIdentification.id > 0)).collect(Collectors.toList()); } else { items = new ArrayList<>(municipalities); } Collections.sort(items); comboBox = Frontend.getInstance().createComboBox(items, listener()); } @Override public IComponent getComponent() { return comboBox; } @Override public void setValue(MunicipalityIdentification object) { if (EmptyObjects.isEmpty(object)) { object = null; } comboBox.setValue(object); } @Override public MunicipalityIdentification getValue() { MunicipalityIdentification municipality = new MunicipalityIdentification(); if (comboBox.getValue() != null) { comboBox.getValue().copyTo(municipality); } return municipality; } @Override public void mock() { setValue(DataGenerator.municipalityIdentification()); } }
package com.InfinityRaider.AgriCraft.utility; import chococraft.common.items.seeds.ItemGysahlSeeds; import com.InfinityRaider.AgriCraft.blocks.BlockModPlant; import com.InfinityRaider.AgriCraft.compatibility.ModIntegration; import com.InfinityRaider.AgriCraft.compatibility.chococraft.ChococraftHelper; import com.InfinityRaider.AgriCraft.compatibility.plantmegapack.PlantMegaPackHelper; import com.InfinityRaider.AgriCraft.handler.ConfigurationHandler; import com.InfinityRaider.AgriCraft.init.Crops; import com.InfinityRaider.AgriCraft.items.ItemModSeed; import com.InfinityRaider.AgriCraft.reference.Constants; import com.InfinityRaider.AgriCraft.reference.Names; import com.InfinityRaider.AgriCraft.reference.SeedInformation; import ivorius.psychedelicraft.blocks.IvTilledFieldPlant; import mods.natura.common.NContent; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; import java.util.*; public abstract class SeedHelper { private static List<ItemStack> seedBlackList; private static HashMap<ItemSeeds, Integer[]> spreadChances; private static HashMap<ItemSeeds, Integer[]> seedTiers; public static void init() { initSeedBlackList(); initSpreadChancesOverrides(); initTiers(); } private static void initSeedBlackList() { String[] data = IOHelper.getLinesArrayFromData(ConfigurationHandler.readSeedBlackList()); ArrayList<ItemStack> list = new ArrayList<ItemStack>(); for(String line:data) { LogHelper.debug(new StringBuffer("parsing ").append(line)); ItemStack seedStack = IOHelper.getStack(line); Item seed = seedStack!=null?seedStack.getItem():null; boolean success = seed!=null && seed instanceof ItemSeeds; String errorMsg = "Invalid seed"; if(success) { list.add(seedStack); } else { LogHelper.info(new StringBuffer("Error when adding seed to blacklist: ").append(errorMsg).append(" (line: ").append(line).append(")")); } } seedBlackList = list; LogHelper.info("Registered seeds blacklist:"); for(ItemStack seed:seedBlackList) { LogHelper.info(new StringBuffer(" - ").append(Item.itemRegistry.getNameForObject(seed.getItem())).append(":").append(seed.getItemDamage())); } } private static void initSpreadChancesOverrides() { //read mutation chance overrides & initialize the arrays setMutationChances(IOHelper.getLinesArrayFromData(ConfigurationHandler.readSpreadChances())); LogHelper.info("Registered Mutations Chances overrides:"); for(Map.Entry<ItemSeeds, Integer[]> entry:spreadChances.entrySet()) { for(int i=0;i<entry.getValue().length;i++) { Integer chance = entry.getValue()[i]; if(chance!=null) { StringBuffer override = new StringBuffer(" - ").append(Item.itemRegistry.getNameForObject(entry.getKey())).append(':').append(i).append(" - ").append(chance).append(" percent"); LogHelper.info(override); } } } } private static void initTiers() { setSeedTiers(IOHelper.getLinesArrayFromData(ConfigurationHandler.readSeedTiers())); LogHelper.info("Registered seed tiers:"); for(Map.Entry<ItemSeeds, Integer[]> entry:seedTiers.entrySet()) { for(int i=0;i<entry.getValue().length;i++) { Integer tier = entry.getValue()[i]; if(tier!=null) { StringBuffer override = new StringBuffer(" - ").append(Item.itemRegistry.getNameForObject(entry.getKey())).append(':').append(i).append(" - tier:").append(tier); LogHelper.info(override); } } } } //initializes the mutation chances overrides private static void setMutationChances(String[] input) { spreadChances = new HashMap<ItemSeeds, Integer[]>(); LogHelper.debug("reading mutation chance overrides"); for(String line:input) { String[] data = IOHelper.getData(line); boolean success = data.length==2; String errorMsg = "Incorrect amount of arguments"; LogHelper.debug("parsing "+line); if(success) { ItemStack seedStack = IOHelper.getStack(data[0]); Item seedItem = seedStack!=null?seedStack.getItem():null; success = seedItem!=null && seedItem instanceof ItemSeeds; errorMsg = "Invalid seed"; if(success) { int chance = Integer.parseInt(data[1]); success = chance>=0 && chance<=100; errorMsg = "Chance should be between 0 and 100"; if(success) { ItemSeeds seed = (ItemSeeds) seedStack.getItem(); if(spreadChances.get(seed)==null) { spreadChances.put(seed, new Integer[16]); } spreadChances.get(seed)[seedStack.getItemDamage()] = chance; } } } if(!success) { LogHelper.info(new StringBuffer("Error when adding mutation chance override: ").append(errorMsg).append(" (line: ").append(line).append(")")); } } } //initializes the seed tier overrides private static void setSeedTiers(String[] input) { seedTiers = new HashMap<ItemSeeds, Integer[]>(); LogHelper.debug("reading seed tier overrides"); for(String line:input) { String[] data = IOHelper.getData(line); boolean success = data.length==2; String errorMsg = "Incorrect amount of arguments"; LogHelper.debug("parsing "+line); if(success) { ItemStack seedStack = IOHelper.getStack(data[0]); Item seedItem = seedStack!=null?seedStack.getItem():null; success = seedItem!=null && seedItem instanceof ItemSeeds; errorMsg = "Invalid seed"; if(success) { int tier = Integer.parseInt(data[1]); success = tier>=1 && tier<=5; errorMsg = "Chance should be between 1 and 5"; if(success) { ItemSeeds seed = (ItemSeeds) seedStack.getItem(); if(seedTiers.get(seed)==null) { seedTiers.put(seed, new Integer[16]); } seedTiers.get(seed)[seedStack.getItemDamage()] = tier; } } } if(!success) { LogHelper.info(new StringBuffer("Error when adding seed tier override: ").append(errorMsg).append(" (line: ").append(line).append(")")); } } } public static double getSpreadChance(ItemSeeds seed, int meta) { Integer[] value = spreadChances.get(seed); if(value!=null && value.length>meta && value[meta]!=null) { return ((double) value[meta]) / 100; } return 1.00/ SeedHelper.getSeedTier(seed, meta); } public static int getSeedTier(ItemSeeds seed, int meta) { if(seed == null) { return 0; } Integer[] tierArray = seedTiers.get(seed); if(tierArray!=null && tierArray.length>meta) { Integer tier = seedTiers.get(seed)[meta]; if (tier != null) { return tier; } } if(seed instanceof ItemModSeed) { return ((ItemModSeed) seed).getPlant().tier; } String domain = Item.itemRegistry.getNameForObject(seed).substring(0, Item.itemRegistry.getNameForObject(seed).indexOf(':')); if(domain.equalsIgnoreCase("harvestcraft")) { return 2; } if(domain.equalsIgnoreCase("natura")) { return 2; } if(domain.equalsIgnoreCase("magicalcrops")) { return 4; } if(domain.equalsIgnoreCase("plantmegapack")) { return 2; } if(domain.equalsIgnoreCase("weeeflowers")) { return 2; } return 1; } public static int getBaseGrowth(int tier) { switch(tier) { case 1: return Constants.growthTier1; case 2: return Constants.growthTier2; case 3: return Constants.growthTier3; case 4: return Constants.growthTier4; case 5: return Constants.growthTier5; default: return 0; } } //find the crop for a seed public static Block getPlant(ItemSeeds seed) { if(seed == null) { return null; } else if(seed == Items.melon_seeds) { return Crops.melon; } else if(seed == Items.pumpkin_seeds) { return Crops.pumpkin; } else { return seed.getPlant(null, 0, 0, 0); } } public static boolean isAnalyzedSeed(ItemStack seedStack) { return (seedStack!=null) && (seedStack.getItem()!=null) && (seedStack.getItem() instanceof ItemSeeds) && (seedStack.hasTagCompound()) && (seedStack.stackTagCompound.hasKey(Names.NBT.analyzed)) && (seedStack.stackTagCompound.getBoolean(Names.NBT.analyzed)); } //gets the seed domain public static String getPlantDomain(ItemSeeds seed) { String name = Item.itemRegistry.getNameForObject(seed); return name.substring(0, name.indexOf(":")).toLowerCase(); } //gets the fruits public static ArrayList<ItemStack> getPlantFruits(ItemSeeds seed, World world, int x, int y, int z, int gain, int meta) { int nr = (int) (Math.ceil((gain + 0.00) / 3)); Block plant = getPlant(seed); ArrayList<ItemStack> items = new ArrayList<ItemStack>(); //nether wart exception if(plant==Blocks.nether_wart) { LogHelper.debug("Getting fruit for nether wart"); items.add(new ItemStack(seed, nr, 0)); } //agricraft crop else if(plant instanceof BlockModPlant) { LogHelper.debug("Getting fruit for agricraft plant"); items.addAll(((BlockModPlant) plant).getFruit(nr, world.rand)); } //natura crop else if(ModIntegration.LoadedMods.natura && getPlantDomain(seed).equalsIgnoreCase("natura")) { LogHelper.debug("Getting fruit for natura plant"); items.add(new ItemStack(NContent.plantItem, nr, meta*3)); } //chococraft crop else if(ModIntegration.LoadedMods.chococraft && seed instanceof ItemGysahlSeeds) { LogHelper.debug("Getting fruit for gyshahls"); items.add(ChococraftHelper.getFruit(gain, nr)); } //other crop else { LogHelper.debug("Getting fruit from ore dictionary"); addFruitsFromOreDict(items, seed, meta, world.rand, nr); } if(items.size()==0) { LogHelper.debug("Getting fruit from plant"); int harvestMeta = 7; //plant mega pack crop if(ModIntegration.LoadedMods.plantMegaPack && getPlantDomain(seed).equalsIgnoreCase("plantmegapack")) { harvestMeta=PlantMegaPackHelper.getTextureIndex(seed, harvestMeta); } addFruitsFromPlant(items, plant, world, x, y, z, harvestMeta, nr); } return items; } public static void addFruitsFromPlant(List<ItemStack> items, Block plant, World world, int x, int y, int z, int harvestMeta, int nr) { ArrayList<ItemStack> defaultDrops = plant.getDrops(world, x, y, z, harvestMeta, 0); for (ItemStack drop : defaultDrops) { if (!(drop.getItem() instanceof ItemSeeds) && drop.getItem()!=null) { boolean add = true; for(ItemStack item:items) { if(item.getItem()==drop.getItem() && item.getItemDamage()==drop.getItemDamage()) { add = false; } } if(add) { items.add(new ItemStack(drop.getItem(), nr, drop.getItemDamage())); } } } } //get all plant fruits public static ArrayList<ItemStack> getAllPlantFruits(ItemSeeds seed, World world, int x, int y, int z, int gain, int meta) { Block plant = getPlant(seed); ArrayList<ItemStack> items = new ArrayList<ItemStack>(); if(plant instanceof BlockModPlant) { items.addAll(((BlockModPlant) plant).getFruits()); } //chococraft crop else if(ModIntegration.LoadedMods.chococraft && seed instanceof ItemGysahlSeeds) { items.addAll(ChococraftHelper.getFruits()); } //other crop else { items = (ArrayList<ItemStack>) getFruitsFromOreDict(seed, meta); } if(items == null || items.size()==0) { items = getPlantFruits(seed, world, x, y, z, gain, meta); } return items; } public static void addFruitsFromOreDict(List<ItemStack> list, ItemSeeds seed, int meta, Random rand, int nr) { int counter = 0; List<ItemStack> fruits = getFruitsFromOreDict(seed, meta); if(fruits!=null && fruits.size()>0) { while (counter < nr) { ItemStack newFruit = fruits.get(rand.nextInt(fruits.size())).copy(); newFruit.stackSize = 1; list.add(newFruit); counter++; } } } public static List<ItemStack> getFruitsFromOreDict(ItemSeeds seed, int meta) { for(int id:OreDictionary.getOreIDs(new ItemStack(seed, 1, meta))) { if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) { return OreDictionary.getOres("crop"+OreDictionary.getOreName(id).substring(4)); } } return null; } //check if the seed is valid public static boolean isValidSeed(ItemSeeds seed, int meta) { if(ModIntegration.LoadedMods.thaumicTinkerer && getPlantDomain(seed).equalsIgnoreCase(Names.Mods.thaumicTinkerer)) { LogHelper.debug("Thaumic Tinkerer infused seeds are not supported, sorry"); return false; } for(ItemStack blacklistedSeed:seedBlackList) { if(blacklistedSeed.getItem()==seed && blacklistedSeed.getItemDamage()==meta) { return false; } } return true; } //get the base growth public static int getBaseGrowth(ItemSeeds seed, int meta) { return getBaseGrowth(getSeedTier(seed, meta)); } //define NBT tag public static void setNBT(NBTTagCompound tag, short growth, short gain, short strength, boolean analyzed) { tag.setShort(Names.NBT.growth, growth==0?Constants.defaultGrowth:growth>10?10:growth); tag.setShort(Names.NBT.gain, gain==0?Constants.defaultGain:gain>10?10:gain); tag.setShort(Names.NBT.strength, strength==0?Constants.defaultGain:strength>10?10:strength); tag.setBoolean(Names.NBT.analyzed, analyzed); } //get a string of information about the seed for the journal public static String getSeedInformation(ItemStack seedStack) { if (!(seedStack.getItem() instanceof ItemSeeds)) { return null; } return SeedInformation.getSeedInformation(seedStack); } //get a random seed public static ItemStack getRandomSeed(boolean setTag) { ArrayList<ItemStack> seeds = OreDictionary.getOres(Names.OreDict.listAllseed); ItemStack seed = null; while(seed==null || !(seed.getItem() instanceof ItemSeeds) || !isValidSeed((ItemSeeds) seed.getItem(), seed.getItemDamage())) { seed = seeds.get((int) Math.floor(Math.random()*seeds.size())); } if(setTag) { int gain = (int) Math.ceil(Math.random()*7); int growth = (int) Math.ceil(Math.random()*7); int strength = (int) Math.ceil(Math.random()*7); NBTTagCompound tag = new NBTTagCompound(); setNBT(tag, (short) growth, (short) gain, (short) strength, false); seed.stackTagCompound = tag; } return seed; } public static void addAllToSeedBlacklist(Collection<? extends ItemStack> seeds) { seedBlackList.addAll(seeds); } public static void removeAllFromSeedBlacklist(Collection<? extends ItemStack> seeds) { seedBlackList.removeAll(seeds); } /** @return The previous spread chance of the given seed */ public static int overrideSpreadChance(ItemSeeds seed, int meta, int chance) { int oldChance = (int) (getSpreadChance(seed, meta) * 100); Integer[] chances = spreadChances.get(seed); if (chances == null) { chances = new Integer[16]; spreadChances.put(seed, chances); } chances[meta] = chance; return oldChance; } }
package com.buuz135.industrial.proxy.client; import com.buuz135.industrial.book.IFManual; import com.buuz135.industrial.entity.EntityPinkSlime; import com.buuz135.industrial.proxy.BlockRegistry; import com.buuz135.industrial.proxy.CommonProxy; import com.buuz135.industrial.proxy.ItemRegistry; import com.buuz135.industrial.proxy.block.TileEntityConveyor; import com.buuz135.industrial.proxy.client.entity.RenderPinkSlime; import com.buuz135.industrial.proxy.client.event.IFTextureStichEvent; import com.buuz135.industrial.proxy.client.event.IFTooltipEvent; import com.buuz135.industrial.proxy.client.event.IFWorldRenderLastEvent; import com.buuz135.industrial.proxy.client.render.ContributorsCatEarsRender; import com.buuz135.industrial.utils.Reference; import com.google.gson.GsonBuilder; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.entity.RenderPlayer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.EntityList; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemDye; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.awt.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.Map; public class ClientProxy extends CommonProxy { public static final ResourceLocation beacon = new ResourceLocation("textures/entity/beacon_beam.png"); public static final String CONTRIBUTORS_FILE = "https://raw.githubusercontent.com/Buuz135/Industrial-Foregoing/master/contributors.json"; public static ResourceLocation GUI = new ResourceLocation(Reference.MOD_ID, "textures/gui/machines.png"); public static IBakedModel ears_baked; public static IModel ears_model; public static int TICK = 0; private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } } @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); OBJLoader.INSTANCE.addDomain(Reference.MOD_ID); //MinecraftForge.EVENT_BUS.register(new MobRenderInPrisonHandler()); MinecraftForge.EVENT_BUS.register(new IFTextureStichEvent()); MinecraftForge.EVENT_BUS.register(new IFWorldRenderLastEvent()); MinecraftForge.EVENT_BUS.register(new IFTooltipEvent()); } @Override public void init() { super.init(); try { ears_model = OBJLoader.INSTANCE.loadModel(new ResourceLocation(Reference.MOD_ID, "models/block/catears.obj")); ears_baked = ears_model.bake(TRSRTransformation.identity(), DefaultVertexFormats.BLOCK, ModelLoader.defaultTextureGetter()); } catch (Exception e) { e.printStackTrace(); } RenderManager manager = Minecraft.getMinecraft().getRenderManager(); Map<String, RenderPlayer> map = manager.getSkinMap(); map.get("default").addLayer(new ContributorsCatEarsRender()); map.get("slim").addLayer(new ContributorsCatEarsRender()); try { ContributorsCatEarsRender.contributors = new GsonBuilder().create().fromJson(readUrl(CONTRIBUTORS_FILE), ContributorsCatEarsRender.Contributors.class); } catch (Exception e) { e.printStackTrace(); } manager.entityRenderMap.put(EntityPinkSlime.class, new RenderPinkSlime(manager)); Minecraft.getMinecraft().getItemColors().registerItemColorHandler((stack, tintIndex) -> ItemDye.DYE_COLORS[EnumDyeColor.byMetadata(stack.getMetadata()).getDyeDamage()], ItemRegistry.artificalDye); Minecraft.getMinecraft().getItemColors().registerItemColorHandler((stack, tintIndex) -> { if (tintIndex == 0) return ItemDye.DYE_COLORS[EnumDyeColor.byMetadata(stack.getMetadata()).getDyeDamage()]; return 0xFFFFFFF; }, BlockRegistry.blockConveyor.getItem()); Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler((state, worldIn, pos, tintIndex) -> { if (tintIndex == 0) { TileEntity entity = worldIn.getTileEntity(pos); if (entity instanceof TileEntityConveyor) { if (((TileEntityConveyor) entity).getColor() == -1) { return Color.getHSBColor(TICK / 300f, 0.75f, 0.5f).getRGB(); } return ItemDye.DYE_COLORS[((TileEntityConveyor) entity).getColor()]; } } return 0xFFFFFFF; }, BlockRegistry.blockConveyor); Minecraft.getMinecraft().getItemColors().registerItemColorHandler((stack, tintIndex) -> { if (tintIndex == 1 || tintIndex == 2 || tintIndex == 3) { EntityList.EntityEggInfo info = null; if (stack.hasTagCompound() && stack.getTagCompound().hasKey("entity", Constants.NBT.TAG_STRING)) { ResourceLocation id = new ResourceLocation(stack.getTagCompound().getString("entity")); info = EntityList.ENTITY_EGGS.get(id); } return info == null ? 0x636363 : tintIndex == 3 ? BlockRegistry.mobDuplicatorBlock.blacklistedEntities.contains(info.spawnedID.toString()) ? 0xDB201A : 0x636363 : tintIndex == 1 ? info.primaryColor : info.secondaryColor; } return 0xFFFFFF; }, ItemRegistry.mobImprisonmentToolItem); } @Override public void postInit() { super.postInit(); IFManual.buildManual(); } @Mod.EventBusSubscriber(modid = Reference.MOD_ID) private static class TickHandler { @SubscribeEvent public static void onTick(TickEvent.ClientTickEvent event) { ++TICK; if (TICK > 300) { TICK = 0; } } } }
package com.cflint.plugins.core; import net.htmlparser.jericho.Element; import cfml.parsing.cfscript.script.CFCompDeclStatement; import cfml.parsing.cfscript.script.CFFuncDeclStatement; import cfml.parsing.cfscript.script.CFFunctionParameter; import cfml.parsing.cfscript.script.CFScriptStatement; import com.cflint.BugInfo; import com.cflint.BugList; import com.cflint.plugins.CFLintScannerAdapter; import com.cflint.plugins.Context; import com.cflint.tools.CFTool; public class TooManyFunctionsChecker extends CFLintScannerAdapter { final String severity = "WARNING"; final int FUNCTION_THRESHOLD = 10; protected int functionCount = 0; protected boolean alreadyTooMany = false; @Override public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) { if (expression instanceof CFCompDeclStatement) { functionCount = 0; alreadyTooMany = false; } else if (expression instanceof CFFuncDeclStatement) { final CFFuncDeclStatement function = (CFFuncDeclStatement) expression; if (!trivalFunction(context.getFunctionName())) { functionCount++; if (!alreadyTooMany) { checkNumberFunctions(functionCount, 1, context, bugs); } } } } @Override public void element(final Element element, final Context context, final BugList bugs) { if (element.getName().equals("cfcomponent")) { functionCount = 0; alreadyTooMany = false; } else if (element.getName().equals("cffunction")) { if (!trivalFunction(context.getFunctionName())) { functionCount++; if (!alreadyTooMany) { checkNumberFunctions(functionCount, 1, context, bugs); } } } } protected boolean trivalFunction(String name) { final int length = name.length(); return length >= 3 && name.substring(1,3) == "get" || length >= 3 && name.substring(1,3) == "set" || length >= 2 && name.substring(1,3) == "is"; } protected void checkNumberFunctions(int functionCount, int atLine, Context context, BugList bugs) { String functionThreshold = getParameter("maximum"); int threshold = FUNCTION_THRESHOLD; if (functionThreshold != null) { threshold = Integer.parseInt(functionThreshold); } if (functionCount > threshold) { alreadyTooMany = true; bugs.add(new BugInfo.BugInfoBuilder().setLine(atLine).setMessageCode("EXCESSIVE_FUNCTIONS") .setSeverity(severity).setFilename(context.getFilename()) .setMessage("Function " + context.getFunctionName() + " has too many functions. Should be less than " + Integer.toString(threshold) + ".") .build()); } } }
package com.cflint.plugins.core; import com.cflint.CF; import com.cflint.BugList; import com.cflint.plugins.CFLintScannerAdapter; import com.cflint.plugins.Context; import com.cflint.plugins.Context.ContextType; import cfml.parsing.cfscript.CFExpression; import cfml.parsing.cfscript.script.CFFuncDeclStatement; import cfml.parsing.cfscript.script.CFScriptStatement; import net.htmlparser.jericho.Element; public class TooManyFunctionsChecker extends CFLintScannerAdapter { private static final int FUNCTION_THRESHOLD = 10; protected int functionCount = 0; @Override public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) { if (expression instanceof CFFuncDeclStatement && !trivalFunction(context.getFunctionName())) { functionCount++; checkNumberFunctions(functionCount, 1, 0, context, bugs,context.getFunctionInfo().getName()); } } @Override public void element(final Element element, final Context context, final BugList bugs) { if (element.getName().equals(CF.CFFUNCTION) && !trivalFunction(context.getFunctionName())) { functionCount++; checkNumberFunctions(functionCount, 1, 0, context, bugs, null); } } protected boolean trivalFunction(final String name) { final int length = name==null?0:name.length(); return length >= 3 && "get".equalsIgnoreCase(name.substring(1, 3)) || length >= 3 && "set".equalsIgnoreCase(name.substring(1, 3)) || length >= 2 && "is".equalsIgnoreCase(name.substring(1, 2)); } protected void checkNumberFunctions(final int functionCount, final int atLine, final int atOffset, final Context context, final BugList bugs, final CFExpression cfExpression) { final String functionThreshold = context.getConfiguration().getParameter(this,"maximum"); int threshold = FUNCTION_THRESHOLD; if (functionThreshold != null) { threshold = Integer.parseInt(functionThreshold); } if (functionCount == threshold + 1) { context.getParent(ContextType.COMPONENT).addUniqueMessage("EXCESSIVE_FUNCTIONS", null, this, atLine, atOffset,cfExpression); } } @Override public void startComponent(final Context context, final BugList bugs) { functionCount = 0; } }
package com.clarkparsia.sbol.editor.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.synbiohub.frontend.IdentifiedMetadata; import org.synbiohub.frontend.SearchCriteria; import org.synbiohub.frontend.SearchQuery; import org.synbiohub.frontend.SynBioHubException; import org.synbiohub.frontend.SynBioHubFrontend; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLDocument; import org.sbolstandard.core2.SBOLValidationException; import org.sbolstandard.core2.TopLevel; import com.clarkparsia.sbol.CharSequences; import com.clarkparsia.sbol.editor.Registry; import com.clarkparsia.sbol.editor.SBOLEditorPreferences; import com.clarkparsia.swing.FormBuilder; import com.clarkparsia.versioning.PersonInfo; public class UploadDialog extends JDialog implements ActionListener, DocumentListener, MouseListener { private static final String TITLE = "Upload Design: "; private static String title(Registry registry) { String title = ""; if (registry.getName() != null) { title = title + registry.getName(); } else if (registry.getLocation() != null) { title = title + registry.getLocation(); } return CharSequences.shorten(title, 20).toString(); } private Component parent; private Registry registry; private SBOLDocument toBeUploaded; private final JLabel info = new JLabel( "Submission form for uploading to SynBioHub. The options specify what actions to take for duplicate designs. (*) indicates a required field"); private final JButton uploadButton = new JButton("Upload"); private final JButton cancelButton = new JButton("Cancel"); private final JComboBox<String> options = new JComboBox<>(new String[] { "Prevent Submission", "Overwrite Submission", "Merge and Prevent, if existing", "Merge and Replace, if existing" }); private final JTextField username = new JTextField(""); private final JPasswordField password = new JPasswordField(""); private final JTextField submissionId = new JTextField(""); private final JTextField version = new JTextField(""); private final JTextField name = new JTextField(""); private final JTextField description = new JTextField(""); private final JTextField citations = new JTextField(""); private final JTextField collections = new JTextField(""); public UploadDialog(final Component parent, Registry registry, SBOLDocument toBeUploaded) { super(JOptionPane.getFrameForComponent(parent), TITLE + title(registry), true); this.parent = parent; this.registry = registry; this.toBeUploaded = toBeUploaded; // Remove objects that should already be found in this registry for (TopLevel topLevel : this.toBeUploaded.getTopLevels()) { String identity = topLevel.getIdentity().toString(); String registryPrefix = registry.getUriPrefix(); if ((!registryPrefix.equals("") && identity.startsWith(registryPrefix)) || (registryPrefix.equals("") && identity.startsWith(registry.getLocation()))) { try { this.toBeUploaded.removeTopLevel(topLevel); } catch (SBOLValidationException e) { e.printStackTrace(); } } } // set default values PersonInfo userInfo = SBOLEditorPreferences.INSTANCE.getUserInfo(); String email = userInfo == null || userInfo.getEmail() == null ? null : userInfo.getEmail().getLocalName(); String uri = userInfo == null ? null : userInfo.getURI().stringValue(); if (email == null || email.equals("") || uri == null) { JOptionPane.showMessageDialog(parent, "Make sure your email and URI/namespace are both set and valid in preferences.", "Upload failed", JOptionPane.ERROR_MESSAGE); return; } username.setText(email); password.setEchoChar('*'); ComponentDefinition root = toBeUploaded.getRootComponentDefinitions().iterator().next(); submissionId.setText(root.getDisplayId()); version.setText("1"); name.setText(root.isSetName() ? root.getName() : root.getDisplayId()); description.setText(root.isSetDescription() ? root.getDescription() : ""); cancelButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); cancelButton.addActionListener(this); uploadButton.addActionListener(this); uploadButton.setEnabled(false); getRootPane().setDefaultButton(uploadButton); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalStrut(100)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(uploadButton); JPanel panel = initMainPanel(); Container contentPane = getContentPane(); contentPane.add(info, BorderLayout.PAGE_START); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); ((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); pack(); setLocationRelativeTo(parent); setVisible(true); } private JPanel initMainPanel() { username.getDocument().addDocumentListener(this); password.getDocument().addDocumentListener(this); submissionId.getDocument().addDocumentListener(this); version.getDocument().addDocumentListener(this); name.getDocument().addDocumentListener(this); description.getDocument().addDocumentListener(this); citations.getDocument().addDocumentListener(this); collections.getDocument().addDocumentListener(this); collections.addMouseListener(this); FormBuilder builder = new FormBuilder(); builder.add("Username *", username); builder.add("Password *", password); builder.add("", new JLabel(" ")); builder.add("Submission ID *", submissionId); builder.add("Version *", version); builder.add("Name *", name); builder.add("Description *", description); builder.add("Citations", citations); builder.add("Collections", collections); builder.add("Options", options); JPanel panel = builder.build(); panel.setAlignmentX(LEFT_ALIGNMENT); return panel; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == cancelButton) { setVisible(false); return; } if (e.getSource() == uploadButton) { try { uploadDesign(); JOptionPane.showMessageDialog(parent, "Upload successful!"); setVisible(false); return; } catch (SynBioHubException e1) { MessageDialog.showMessage(parent, "Uploading failed", Arrays.asList(e1.getMessage().split("\"|,"))); toBeUploaded.clearRegistries(); } } } private void uploadDesign() throws SynBioHubException { SynBioHubFrontend stack = toBeUploaded.addRegistry(registry.getLocation(), registry.getUriPrefix()); stack.login(username.getText(), new String(password.getPassword())); String option = Integer.toString(options.getSelectedIndex()); stack.submit(submissionId.getText(), version.getText(), name.getText(), description.getText(), citations.getText(), collections.getText(), option, toBeUploaded); } @Override public void insertUpdate(DocumentEvent e) { enableUpload(); } @Override public void removeUpdate(DocumentEvent e) { enableUpload(); } @Override public void changedUpdate(DocumentEvent e) { enableUpload(); } private void enableUpload() { boolean shouldEnable = !submissionId.getText().equals("") && !version.getText().equals("") && !name.getText().equals("") && !description.getText().equals("") && !username.getText().equals("") && !password.getPassword().equals(""); uploadButton.setEnabled(shouldEnable); } /* * All mouse methods are for collections and collection selection */ @Override public void mouseClicked(MouseEvent e) { SynBioHubFrontend stack = toBeUploaded.addRegistry(registry.getLocation(), registry.getUriPrefix()); try { stack.login(username.getText(), new String(password.getPassword())); } catch (SynBioHubException e1) { JOptionPane.showMessageDialog(parent, "Collection selection requires a valid username and password to be entered", "Collection selection failed", JOptionPane.ERROR_MESSAGE); return; } try { SearchQuery query = new SearchQuery(); SearchCriteria crit = new SearchCriteria(); // TODO what value to get all collections? crit.setKey("collection"); crit.setValue(""); query.addCriteria(crit); List<IdentifiedMetadata> results = stack.search(query); if (results.size() == 0) { return; } List<String> uris = new ArrayList<String>(); results.forEach((metadata) -> uris.add(metadata.getUri())); Object[] options = uris.toArray(); int result = JOptionPane.showOptionDialog(parent, "Select a collection", "Collection selection", JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (result != JOptionPane.CLOSED_OPTION) { String text = collections.getText(); if (text.equals("")) { text = (String) options[result]; } else { text = text + "," + (String) options[result]; } collections.setText(text); } } catch (SynBioHubException e1) { e1.printStackTrace(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
package com.darksci.pardot.api.auth; import java.util.Objects; /** * Used for defining an alternative Authorization Server hostname or end point for SSO OAuth2 authentication. */ public class AuthorizationServer { /** * The default Authorization Server for production salesforce. */ public static final AuthorizationServer DEFAULT_SALESFORCE = new AuthorizationServer( "https://login.salesforce.com", "/services/oauth2/token" ); /** * The default Authorization Server for test/sandbox instances. */ public static final AuthorizationServer SANDBOX_SALESFORCE = new AuthorizationServer( "https://test.salesforce.com", "/services/oauth2/token" ); private final String authServer; /** * URI. * Example: "/services/oauth2/token" */ private final String authUri; public AuthorizationServer(final String authServer, final String authUri) { this.authServer = Objects.requireNonNull(authServer); this.authUri = Objects.requireNonNull(authUri); } public String getAuthServer() { return authServer; } public String getAuthUri() { return authUri; } @Override public String toString() { return "AuthorizationServer{" + "authServer='" + authServer + '\'' + ", authUri='" + authUri + '\'' + '}'; } }
package kr.ac.kookmin.cs.myhello; public class HelloWorld { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello World!!!!34634!!!!!!!!"); } }
package pokemon; public abstract class AbstractType implements IType { @Override public void weakAgainstGrass(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstFire(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstWater(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstElectric(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstGround(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstPsychic(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstFighting(IType o) { // TODO Auto-generated method stub } @Override public void weakAgainstNormal(IType o) { // TODO Auto-generated method stub } }
package com.elmakers.mine.bukkit.utility; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; public class InventoryUtils extends NMSUtils { public static boolean saveTagsToNBT(ConfigurationSection tags, Object node, String[] tagNames) { if (node == null) { Bukkit.getLogger().warning("Trying to save tags to a null node"); return false; } if (!class_NBTTagCompound.isAssignableFrom(node.getClass())) { Bukkit.getLogger().warning("Trying to save tags to a non-CompoundTag"); return false; } for (String tagName : tagNames) { String value = tags.getString(tagName); // This is kinda hacky, but makes for generally cleaner data. if (value == null || value.length() == 0 || value.equals("0") || value.equals("0.0") || value.equals("false")) { removeMeta(node, tagName); } else { setMeta(node, tagName, value); } } return true; } public static boolean loadTagsFromNBT(ConfigurationSection tags, Object node, String[] tagNames) { if (node == null) { Bukkit.getLogger().warning("Trying to load tags from a null node"); return false; } if (!class_NBTTagCompound.isAssignableFrom(node.getClass())) { Bukkit.getLogger().warning("Trying to load tags from a non-CompoundTag"); return false; } for (String tagName : tagNames) { String meta = getMeta(node, tagName); if (meta != null && meta.length() > 0) { ConfigurationUtils.set(tags, tagName, meta); } } return true; } public static boolean inventorySetItem(Inventory inventory, int index, ItemStack item) { try { Method setItemMethod = class_CraftInventoryCustom.getMethod("setItem", Integer.TYPE, ItemStack.class); setItemMethod.invoke(inventory, index, item); return true; } catch(Throwable ex) { ex.printStackTrace(); } return false; } public static boolean setInventoryResults(Inventory inventory, ItemStack item) { try { Method getResultsMethod = inventory.getClass().getMethod("getResultInventory"); Object inv = getResultsMethod.invoke(inventory); Method setItemMethod = inv.getClass().getMethod("setItem", Integer.TYPE, class_ItemStack); setItemMethod.invoke(inv, 0, getHandle(item)); return true; } catch(Throwable ex) { ex.printStackTrace(); } return false; } public static ItemStack getURLSkull(String url) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)0, (byte)3); try { new URL(url); } catch (MalformedURLException e) { Bukkit.getLogger().log(Level.WARNING, "Malformed URL: " + url, e); return skull; } try { skull = makeReal(skull); Object skullOwner = createNode(skull, "SkullOwner"); UUID id = UUID.randomUUID(); setMeta(skullOwner, "Id", id.toString()); Object properties = createNode(skullOwner, "Properties"); setMeta(properties, "Id", id.toString()); // This is here so serialization doesn't cause an NPE setMeta(properties, "Name", "MHF_Question"); Object listMeta = class_NBTTagList.newInstance(); Object textureNode = class_NBTTagCompound.newInstance(); String textureJSON = "{textures:{SKIN:{url:\"" + url + "\"}}}"; String encoded = Base64Coder.encodeString(textureJSON); setMeta(textureNode, "Value", encoded); class_NBTTagList_addMethod.invoke(listMeta, textureNode); class_NBTTagCompound_setMethod.invoke(properties, "textures", listMeta); } catch (Exception ex) { ex.printStackTrace(); return skull; } return skull; } public static ItemStack getPlayerSkull(Player player) { return getPlayerSkull(player, null); } @SuppressWarnings("deprecation") public static ItemStack getPlayerSkull(Player player, String itemName) { ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (short)0, (byte)3); ItemMeta meta = head.getItemMeta(); if (itemName != null) { meta.setDisplayName(itemName); } String ownerName = player.getName(); if (meta instanceof SkullMeta && ownerName != null) { SkullMeta skullData = (SkullMeta)meta; skullData.setOwner(ownerName); } head.setItemMeta(meta); return head; } }
package org.biojava.bio.symbol; import junit.framework.TestCase; /** * Tests IntegerAlphabet to make sure we can get it, that it is * canonical, that symbols it returns are canonical, that finite * ranges are canonical and that symbols in finite ranges are * canonical. * * @since 1.2 */ public class IntegerAlphabetTest extends TestCase { public IntegerAlphabetTest(String name) { super(name); } public void testCanonicalAlphabet() { assertEquals( AlphabetManager.alphabetForName("INTEGER"), IntegerAlphabet.getInstance() ); assertEquals( IntegerAlphabet.getInstance(), IntegerAlphabet.getInstance() ); } public void testCanonicalSymbols() { Symbol[] syms = new Symbol[10]; for(int i = 0; i < syms.length; i++) { syms[i] = IntegerAlphabet.getInstance().getSymbol(i); } for(int i = 0; i < syms.length; i++) { assertEquals( syms[i], IntegerAlphabet.getInstance().getSymbol(i) ); } } public void testCanonicalSubAlphabet() { int min = 200; int max = 300; IntegerAlphabet alpha = IntegerAlphabet.getInstance(); Alphabet a1 = alpha.getSubAlphabet(min, max); Alphabet a2 = alpha.getSubAlphabet(min, max); assertEquals(a1, a2); } public void testSubAlphabetSymbolsCanonical() throws IllegalSymbolException { int min = 400; int max = 500; IntegerAlphabet alpha = IntegerAlphabet.getInstance(); IntegerAlphabet.SubIntegerAlphabet a1 = alpha.getSubAlphabet(min, max); for(int i = min; i <= max; i++) { assertEquals( a1.getSymbol(i), a1.getSymbol(i) ); assertEquals( a1.getSymbol(i), alpha.getSymbol(i) ); } } }