answer
stringlengths 17
10.2M
|
|---|
import nu.xom.Document;
import nz.colin.mathml.Converter;
import nz.colin.mtef.XMLSerialize;
import nz.colin.mtef.exceptions.ParseException;
import nz.colin.mtef.parsers.MTEFParser;
import nz.colin.mtef.records.MTEF;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public class GeneralTest {
@Test
public void testParseQuadratic() throws IOException, ParseException {
InputStream is = GeneralTest.class.getResourceAsStream("/ole/quadratic.bin");
PushbackInputStream pis = new PushbackInputStream(is);
pis.read(new byte[28]);
MTEF mtef = new MTEFParser().parse(pis);
XMLSerialize serializer = new XMLSerialize();
mtef.accept(serializer);
Converter c = new Converter();
Document mathml = c.doConvert(serializer.getRoot());
System.out.println(mathml.toXML().replace("&", "&"));
is.close();
}
}
|
package de.htw.vs.shell;
import org.apache.log4j.Logger;
import java.lang.Thread.UncaughtExceptionHandler;
/**
* An {@link UncaughtExceptionHandler} which logs all uncaught exceptions
* to a Logger.
*/
public class UncaughtExceptionLogger implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable ex) {
if (! (ex instanceof ThreadDeath)) {
logException(t, ex);
}
}
private void logException(Thread t, Throwable ex) {
String errorMessage = String.format("Exception in thread '%s'",t);
Logger.getLogger(getNameOfClassWhichThrowed(ex)).error(errorMessage, ex);
}
private String getNameOfClassWhichThrowed(Throwable ex) {
StackTraceElement[] stacktrace = ex.getStackTrace();
return stacktrace.length > 0 ? stacktrace[0].getClassName() : "Unknown" ;
}
}
|
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.ControllerListener;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Pool;
import com.mygdx.character.Tengu;
import com.mygdx.environment.Plateform;
import com.mygdx.tools.Gravity;
import com.mygdx.tools.XBox360Pad;
import java.util.ArrayList;
public class MyGdxGame extends ApplicationAdapter implements ControllerListener, InputProcessor {
private Controller controller;
private OrthographicCamera camera;
private Gravity gravity;
private Tengu tengu;
private Pool<Rectangle> rectanglePool = new Pool<Rectangle>() {
@Override
protected Rectangle newObject () {
return new Rectangle();
}
};
ArrayList<Plateform> plateformList;
@Override
public void create ()
{
// Listen to all controllers, not just one
Controllers.addListener(this);
Gdx.input.setInputProcessor(this);
if(Controllers.getControllers().size > 0) {
this.controller = Controllers.getControllers().first();
}
this.camera = new OrthographicCamera(1280, 720);
this.camera.setToOrtho(false, 1280, 720);
this.camera.position.set(0, 720f / 2f, 0);
this.camera.update();
this.gravity = new Gravity();
this.tengu = new Tengu(new Vector2(0, 20), 0, 0);
this.gravity.addGravityAffectedElement(this.tengu);
this.plateformList = new ArrayList();
plateformList.add(new Plateform(0, -100, Gdx.graphics.getWidth()*10, 110));
for(int i=0; i<20; i++) {
plateformList.add(new Plateform((i + 1)*800, (float)(Math.random() * ( 500 - 100 )), (float)(Math.random() * ( 500 - 100 )), (float)(Math.random() * ( 500 - 100 ))));
}
}
public void update(float deltaTime)
{
Vector2 oldTenguPosition = new Vector2(this.tengu.getPosition().x, this.tengu.getPosition().y);
//apply gravity
this.gravity.applyGravity();
//TODO Check if on keyboard or controller
this.handleKeyboard();
this.handleController();
//this.tengu.handleKeys();
this.tengu.update(deltaTime);
this.handleCollisions(oldTenguPosition);
//add delta time to position ?
//System.out.println((oldTenguPosition.x - this.tengu.getPosition().x) * deltaTime * 10);
}
@Override
public void render () {
float deltaTime = Gdx.graphics.getDeltaTime() * 10;
update(deltaTime);
//this.camera.position.set(this.tengu.getPosition().x, this.tengu.getPosition().y, 0);
//this.tengu.getSpriteBatch().setProjectionMatrix(this.camera.combined);
GL20 gl20 = Gdx.graphics.getGL20();
gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
gl20.glClearColor(1, 1, 1, 1);
// gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.camera.position.set(this.tengu.getPosition().x, this.camera.position.y, 0);
this.camera.update();
this.tengu.getSpriteBatch().setProjectionMatrix(this.camera.combined);
//TODO set projection matrix on rectangle ?
//plateforms
for(int i=0; i<this.plateformList.size(); i++) {
plateformList.get(i).setProjectionMatrix(this.camera.combined);
plateformList.get(i).render();
}
//this.plateformList.forEach(com.mygdx.environment.Plateform::render);
this.tengu.render();
}
@Override
public void dispose() {}
public void handleCollisions(Vector2 oldTenguPosition)
{
Rectangle tenguRectangle = this.tengu.getRectangle(this.rectanglePool.obtain());
boolean isTenguOnGround = false;
for(Plateform plateform : this.plateformList) {
Rectangle plateformRectangle = plateform.getRectangle(this.rectanglePool.obtain());
if(
tenguRectangle.getY() == plateformRectangle.getY() + plateformRectangle.getHeight()
/*&&
(tenguRectangle.getX() >= plateformRectangle.getX()
||
tenguRectangle.getX() + tenguRectangle.getWidth() <= plateformRectangle.getX() + plateformRectangle.getWidth())*/
)
{
isTenguOnGround = true;
}
if(tenguRectangle.overlaps(plateformRectangle)) {
boolean resetX = false,
resetY = false;
boolean isTenguOverPlateform = plateformRectangle.getY() + plateformRectangle.getHeight() <= oldTenguPosition.y;
boolean isTenguUnderPlateform = plateformRectangle.getY() >= oldTenguPosition.y + tenguRectangle.getHeight();
boolean isTenguOnLeftOrRight = plateformRectangle.getX() >= oldTenguPosition.x + tenguRectangle.getWidth() ||
plateformRectangle.getX() + plateformRectangle.getWidth() <= oldTenguPosition.x;
if(this.tengu.getVelocity().x > 0 && !isTenguOverPlateform && isTenguOnLeftOrRight) {
float velocityX = plateformRectangle.getX() - (tenguRectangle.getX() + tenguRectangle.getWidth()) - this.tengu.getVelocity().x;
this.tengu.applyForce(new Vector2(velocityX, 0));
resetX = true;
} else if(this.tengu.getVelocity().x < 0 && !isTenguOverPlateform && isTenguOnLeftOrRight) {
float velocityX = (plateformRectangle.getX() + plateformRectangle.getWidth()) - tenguRectangle.getX() - this.tengu.getVelocity().x;
this.tengu.applyForce(new Vector2(velocityX, 0));
resetX = true;
}
if(this.tengu.getVelocity().y > 0 && isTenguUnderPlateform) {
float velocityY = plateformRectangle.getY() - (tenguRectangle.getY() + tenguRectangle.getHeight()) - this.tengu.getVelocity().y;
this.tengu.applyForce(new Vector2(0, velocityY));
resetY = true;
} else if(this.tengu.getVelocity().y < 0 && isTenguOverPlateform) {
float velocityY = (plateformRectangle.getY() + plateformRectangle.getHeight()) - tenguRectangle.getY() - this.tengu.getVelocity().y;
this.tengu.applyForce(new Vector2(0, velocityY));
resetY = true;
isTenguOnGround = true;
}
this.tengu.getPosition().add(this.tengu.getVelocity());
this.tengu.setVelocity(new Vector2(resetX ? 0 : this.tengu.getVelocity().x, resetY ? 0 : this.tengu.getVelocity().y));
}
this.rectanglePool.free(plateformRectangle);
}
this.tengu.setIsOnGround(isTenguOnGround);
this.rectanglePool.free(tenguRectangle);
}
public void handleKeyboard()
{
//MOVE LEFT
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
this.tengu.moveLeft();
}
//MOVE RIGHT
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
this.tengu.moveRight();
}
//PARACHUTE
if(Gdx.input.isKeyPressed(Input.Keys.UP)) {
this.tengu.deployParachute();
}
}
public void handleController()
{
if(this.controller != null) {
//MOVE LEFT
if(this.controller.getAxis(XBox360Pad.AXIS_LEFT_X) < -0.2f) {
this.tengu.moveLeft();
}
//MOVE RIGHT
if(this.controller.getAxis(XBox360Pad.AXIS_LEFT_X) > 0.2f ) {
this.tengu.moveRight();
}
//PARACHUTE
if(this.controller.getButton(XBox360Pad.BUTTON_X)) {
this.tengu.deployParachute();
}
}
}
@Override
public void connected(Controller controller) {
}
@Override
public void disconnected(Controller controller) {
}
@Override
public boolean buttonDown(Controller controller, int buttonCode) {
//JUMP
if(buttonCode == XBox360Pad.BUTTON_A) {
this.tengu.jump();
}
return true;
}
@Override
public boolean buttonUp(Controller controller, int buttonCode) {
return false;
}
@Override
public boolean axisMoved(Controller controller, int axisCode, float value) {
//DASH LEFT
if(axisCode == XBox360Pad.AXIS_LEFT_TRIGGER && value > 0.2f) {
this.tengu.dashLeft();
}
//DASH RIGHT
if(axisCode == XBox360Pad.AXIS_RIGHT_TRIGGER && value < -0.2f) {
this.tengu.dashRight();
}
return true;
}
@Override
public boolean povMoved(Controller controller, int povCode, PovDirection value) {
return false;
}
@Override
public boolean xSliderMoved(Controller controller, int sliderCode, boolean value) {
return false;
}
@Override
public boolean ySliderMoved(Controller controller, int sliderCode, boolean value) {
return false;
}
@Override
public boolean accelerometerMoved(Controller controller, int accelerometerCode, Vector3 value) {
return false;
}
@Override
public boolean keyDown(int keycode) {
//JUMP
if(keycode == Input.Keys.SPACE) {
this.tengu.jump();
}
//DASH LEFT
if(keycode == Input.Keys.A) {
this.tengu.dashLeft();
}
//DASH RIGHT
if(keycode == Input.Keys.E) {
this.tengu.dashRight();
}
return true;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
}
|
package hudson.scm;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Launcher;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.security.PermissionGroup;
import hudson.security.Permission;
import hudson.tasks.Builder;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Describable;
import hudson.model.TaskListener;
import hudson.model.Node;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.Hudson;
import hudson.model.Descriptor;
import hudson.model.Api;
import hudson.model.Action;
import hudson.model.AbstractProject.AbstractProjectDescriptor;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.NoSuchMethodException;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
@ExportedBean
public abstract class SCM implements Describable<SCM>, ExtensionPoint {
/**
* Stores {@link AutoBrowserHolder}. Lazily created.
*/
private transient AutoBrowserHolder autoBrowserHolder;
/**
* Expose {@link SCM} to the remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Returns the {@link RepositoryBrowser} for files
* controlled by this {@link SCM}.
*
* @return
* null to indicate that there's no explicitly configured browser
* for this SCM instance.
*
* @see #getEffectiveBrowser()
*/
public RepositoryBrowser<?> getBrowser() {
return null;
}
/**
* Type of this SCM.
*
* Exposed so that the client of the remote API can tell what SCM this is.
*/
@Exported
public String getType() {
return getClass().getName();
}
/**
* Returns the applicable {@link RepositoryBrowser} for files
* controlled by this {@link SCM}.
*
* <p>
* This method attempts to find applicable browser
* from other job configurations.
*/
@Exported(name="browser")
public final RepositoryBrowser<?> getEffectiveBrowser() {
RepositoryBrowser<?> b = getBrowser();
if(b!=null)
return b;
if(autoBrowserHolder==null)
autoBrowserHolder = new AutoBrowserHolder(this);
return autoBrowserHolder.get();
}
/**
* Returns true if this SCM supports
* {@link #poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState) poling}.
*
* @since 1.105
*/
public boolean supportsPolling() {
return true;
}
/**
* Returns true if this SCM requires a checked out workspace for doing polling.
*
* <p>
* This flag affects the behavior of Hudson when a job lost its workspace
* (typically due to a slave outage.) If this method returns false and
* polling is configured, then that would immediately trigger a new build.
*
* <p>
* This flag also affects the mutual exclusion control between builds and polling.
* If this methods returns false, polling will continu asynchronously even
* when a build is in progress, but otherwise the polling activity is blocked
* if a build is currently using a workspace.
*
* <p>
* The default implementation returns true.
*
* <p>
* See issue #1348 for more discussion of this feature.
*
* @since 1.196
*/
public boolean requiresWorkspaceForPolling() {
return true;
}
/**
* Called before a workspace is deleted on the given node, to provide SCM an opportunity to perform clean up.
*
* <p>
* Hudson periodically scans through all the slaves and removes old workspaces that are deemed unnecesasry.
* This behavior is implemented in {@link WorkspaceCleanupThread}, and it is necessary to control the
* disk consumption on slaves. If we don't do this, in a long run, all the slaves will have workspaces
* for all the projects, which will be prohibitive in big Hudson.
*
* <p>
* However, some SCM implementations require that the server be made aware of deletion of the local workspace,
* and this method provides an opportunity for SCMs to perform such a clean-up act.
*
* <p>
* This call back is invoked after Hudson determines that a workspace is unnecessary, but before the actual
* recursive directory deletion happens.
*
* <p>
* Note that this method does not guarantee that such a clean up will happen. For example, slaves can be
* taken offline by being physically removed from the network, and in such a case there's no opporunity
* to perform this clean up. Similarly, when a project is deleted or renamed, SCMs do not get any notifications.
*
* @param project
* The project that owns this {@link SCM}. This is always the same object for a particular instance
* of {@link SCM}. Just passed in here so that {@link SCM} itself doesn't have to remember the value.
* @param workspace
* The workspace which is about to be deleted. Never null. This can be a remote file path.
* @param node
* The node that hosts the workspace. SCM can use this information to determine the course of action.
*
* @return
* true if {@link SCM} is OK to let Hudson proceed with deleting the workspace.
* False to veto the workspace deletion.
*
* @since 1.246
*/
public boolean processWorkspaceBeforeDeletion(AbstractProject<?,?> project, FilePath workspace, Node node) throws IOException, InterruptedException {
return true;
}
/**
* Checks if there has been any changes to this module in the repository.
*
* TODO: we need to figure out a better way to communicate an error back,
* so that we won't keep retrying the same node (for example a slave might be down.)
*
* <p>
* If the SCM doesn't implement polling, have the {@link #supportsPolling()} method
* return false.
*
* @param project
* The project to check for updates
* @param launcher
* Abstraction of the machine where the polling will take place. If SCM declares
* that {@linkplain #requiresWorkspaceForPolling() the polling doesn't require a workspace}, this parameter is null.
* @param workspace
* The workspace directory that contains baseline files. If SCM declares
* that {@linkplain #requiresWorkspaceForPolling() the polling doesn't require a workspace}, this parameter is null.
* @param listener
* Logs during the polling should be sent here.
*
* @return true
* if the change is detected.
*
* @throws InterruptedException
* interruption is usually caused by the user aborting the computation.
* this exception should be simply propagated all the way up.
*
* @see #supportsPolling()
*
* @deprecated as of 1.345
* Override {@link #calcRevisionsFromBuild(AbstractBuild, Launcher, TaskListener)} and
* {@link #compareRemoteRevisionWith(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)} for implementation.
*
* The implementation is now separated in two pieces, one that computes the revision of the current workspace,
* and the other that computes the revision of the remote repository.
*
* Call {@link #poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)} for use instead.
*/
public boolean pollChanges(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
// up until 1.336, this method was abstract, so everyone should have overridden this method
// without calling super.pollChanges. So the compatibility implementation is purely for
// new implementations that doesn't override this method.
// not sure if this can be implemented any better
return false;
}
/**
* Calculates the {@link SCMRevisionState} that represents the state of the workspace of the given build.
*
* <p>
* The returned object is then fed into the
* {@link #compareRemoteRevisionWith(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)} method
* as the baseline {@link SCMRevisionState} to determine if the build is necessary.
*
* <p>
* This method is called after source code is checked out for the given build (that is, after
* {@link SCM#checkout(AbstractBuild, Launcher, FilePath, BuildListener, File)} has finished successfully.)
*
* <p>
* The obtained object is added to the build as an {@link Action} for later retrieval. As an optimization,
* {@link SCM} implementation can choose to compute {@link SCMRevisionState} and add it as an action
* during check out, in which case this method will not called.
*
* @param build
* The calculated {@link SCMRevisionState} is for the files checked out in this build. Never null.
* If {@link #requiresWorkspaceForPolling()} returns true, Hudson makes sure that the workspace of this
* build is available and accessible by the callee.
* @param launcher
* Abstraction of the machine where the polling will take place. If SCM declares
* that {@linkplain #requiresWorkspaceForPolling() the polling doesn't require a workspace},
* this parameter is null. Otherwise never null.
* @param listener
* Logs during the polling should be sent here.
*
* @return can be null.
*
* @throws InterruptedException
* interruption is usually caused by the user aborting the computation.
* this exception should be simply propagated all the way up.
*/
public abstract SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?,?> build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException;
/**
* A pointless function to work around what appears to be a HotSpot problem. See HUDSON-5756 and bug 6933067
* on BugParade for more details.
*/
public SCMRevisionState _calcRevisionsFromBuild(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
return calcRevisionsFromBuild(build, launcher, listener);
}
/**
* Compares the current state of the remote repository against the given baseline {@link SCMRevisionState}.
*
* <p>
* Conceptually, the act of polling is to take two states of the repository and to compare them to see
* if there's any difference. In practice, however, comparing two arbitrary repository states is an expensive
* operation, so in this abstraction, we chose to mix (1) the act of building up a repository state and
* (2) the act of comparing it with the earlier state, so that SCM implementations can implement this
* more easily.
*
* <p>
* Multiple invocations of this method may happen over time to make sure that the remote repository
* is "quiet" before Hudson schedules a new build.
*
* @param project
* The project to check for updates
* @param launcher
* Abstraction of the machine where the polling will take place. If SCM declares
* that {@linkplain #requiresWorkspaceForPolling() the polling doesn't require a workspace}, this parameter is null.
* @param workspace
* The workspace directory that contains baseline files. If SCM declares
* that {@linkplain #requiresWorkspaceForPolling() the polling doesn't require a workspace}, this parameter is null.
* @param listener
* Logs during the polling should be sent here.
* @param baseline
* The baseline of the comparison. This object is the return value from earlier
* {@link #compareRemoteRevisionWith(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)} or
* {@link #calcRevisionsFromBuild(AbstractBuild, Launcher, TaskListener)}.
*
* @return
* This method returns multiple values that are bundled together into the {@link PollingResult} value type.
* {@link PollingResult#baseline} should be the value of the baseline parameter, {@link PollingResult#remote}
* is the current state of the remote repository (this object only needs to be understandable to the future
* invocations of this method),
* and {@link PollingResult#change} that indicates the degree of changes found during the comparison.
*
* @throws InterruptedException
* interruption is usually caused by the user aborting the computation.
* this exception should be simply propagated all the way up.
*/
protected abstract PollingResult compareRemoteRevisionWith(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException;
/**
* A pointless function to work around what appears to be a HotSpot problem. See HUDSON-5756 and bug 6933067
* on BugParade for more details.
*/
private PollingResult _compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline2) throws IOException, InterruptedException {
return compareRemoteRevisionWith(project, launcher, workspace, listener, baseline2);
}
/**
* Convenience method for the caller to handle the backward compatibility between pre 1.345 SCMs.
*/
public final PollingResult poll(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
if (is1_346OrLater()) {
// This is to work around HUDSON-5827 in a general way.
// don't let the SCM.compareRemoteRevisionWith(...) see SCMRevisionState that it didn't produce.
SCMRevisionState baseline2;
if (baseline!=SCMRevisionState.NONE) {
baseline2 = baseline;
} else {
baseline2 = _calcRevisionsFromBuild(project.getLastBuild(), launcher, listener);
}
return _compareRemoteRevisionWith(project, launcher, workspace, listener, baseline2);
} else {
return pollChanges(project,launcher,workspace,listener) ? PollingResult.SIGNIFICANT : PollingResult.NO_CHANGES;
}
}
private boolean is1_346OrLater() {
for (Class<?> c = getClass(); c != SCM.class; c = c.getSuperclass()) {
try {
c.getDeclaredMethod("compareRemoteRevisionWith", AbstractProject.class, Launcher.class, FilePath.class, TaskListener.class, SCMRevisionState.class);
return true;
} catch (NoSuchMethodException e) { }
}
return false;
}
/**
* Obtains a fresh workspace of the module(s) into the specified directory
* of the specified machine.
*
* <p>
* The "update" operation can be performed instead of a fresh checkout if
* feasible.
*
* <p>
* This operation should also capture the information necessary to tag the workspace later.
*
* @param launcher
* Abstracts away the machine that the files will be checked out.
* @param workspace
* a directory to check out the source code. May contain left-over
* from the previous build.
* @param changelogFile
* Upon a successful return, this file should capture the changelog.
* When there's no change, this file should contain an empty entry.
* See {@link #createEmptyChangeLog(File, BuildListener, String)}.
* @return
* false if the operation fails. The error should be reported to the listener.
* Otherwise return the changes included in this update (if this was an update.)
*
* @throws InterruptedException
* interruption is usually caused by the user aborting the build.
* this exception will cause the build to fail.
*/
public abstract boolean checkout(AbstractBuild<?,?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException;
/**
* Adds environmental variables for the builds to the given map.
*
* <p>
* This can be used to propagate information from SCM to builds
* (for example, SVN revision number.)
*
* <p>
* This method is invoked whenever someone does {@link AbstractBuild#getEnvironment(TaskListener)}, which
* can be before/after your checkout method is invoked. So if you are going to provide information about
* check out (like SVN revision number that was checked out), be prepared for the possibility that the
* check out hasn't happened yet.
*/
public void buildEnvVars(AbstractBuild<?,?> build, Map<String, String> env) {
// default implementation is noop.
}
/**
* Gets the top directory of the checked out module.
*
* <p>
* Often SCMs have to create a directory inside a workspace, which
* creates directory layout like this:
*
* <pre>
* workspace <- workspace root
* +- xyz <- directory checked out by SCM
* +- CVS
* +- build.xml <- user file
* </pre>
*
* <p>
* Many builders, like Ant or Maven, works off the specific user file
* at the top of the checked out module (in the above case, that would
* be <tt>xyz/build.xml</tt>), yet the builder doesn't know the "xyz"
* part; that comes from SCM.
*
* <p>
* Collaboration between {@link Builder} and {@link SCM} allows
* Hudson to find build.xml wihout asking the user to enter "xyz" again.
*
* <p>
* This method is for this purpose. It takes the workspace
* root as a parameter, and expected to return the directory
* that was checked out from SCM.
*
* <p>
* If this SCM is configured to create a directory, try to
* return that directory so that builders can work seamlessly.
*
* <p>
* If SCM doesn't need to create any directory inside workspace,
* or in any other tricky cases, it should revert to the default
* implementation, which is to just return the parameter.
*
* @param workspace
* The workspace root directory.
*/
public FilePath getModuleRoot(FilePath workspace) {
return workspace;
}
/**
* Gets the top directories of all the checked out modules.
*
* <p>
* Some SCMs support checking out multiple modules inside a workspace, which
* creates directory layout like this:
*
* <pre>
* workspace <- workspace root
* +- xyz <- directory checked out by SCM
* +- .svn
* +- build.xml <- user file
* +- abc <- second module from different SCM root
* +- .svn
* +- build.xml <- user file
* </pre>
*
* This method takes the workspace root as a parameter, and is expected to return
* all the module roots that were checked out from SCM.
*
* <p>
* For normal SCMs, the array will be of length <code>1</code> and it's contents
* will be identical to calling {@link #getModuleRoot(FilePath)}.
*
* @param workspace The workspace root directory
* @return An array of all module roots.
*/
public FilePath[] getModuleRoots(FilePath workspace) {
return new FilePath[] { getModuleRoot(workspace), };
}
/**
* The returned object will be used to parse <tt>changelog.xml</tt>.
*/
public abstract ChangeLogParser createChangeLogParser();
public SCMDescriptor<?> getDescriptor() {
return (SCMDescriptor)Hudson.getInstance().getDescriptorOrDie(getClass());
}
// convenience methods
protected final boolean createEmptyChangeLog(File changelogFile, BuildListener listener, String rootTag) {
try {
FileWriter w = new FileWriter(changelogFile);
w.write("<"+rootTag +"/>");
w.close();
return true;
} catch (IOException e) {
e.printStackTrace(listener.error(e.getMessage()));
return false;
}
}
protected final String nullify(String s) {
if(s==null) return null;
if(s.trim().length()==0) return null;
return s;
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(SCM.class, Messages._SCM_Permissions_Title());
public static final Permission TAG = new Permission(PERMISSIONS,"Tag",Messages._SCM_TagPermission_Description(),Permission.CREATE);
/**
* Returns all the registered {@link SCMDescriptor}s.
*/
public static DescriptorExtensionList<SCM,SCMDescriptor<?>> all() {
return Hudson.getInstance().getDescriptorList(SCM.class);
}
/**
* Returns the list of {@link SCMDescriptor}s that are applicable to the given project.
*/
public static List<SCMDescriptor<?>> _for(final AbstractProject<?,?> project) {
if(project==null) return all();
@SuppressWarnings("unchecked")
final Descriptor<?> pd = Hudson.getInstance().getDescriptor((Class<? extends Describable<?>>) project.getClass());
List<SCMDescriptor<?>> r = new ArrayList<SCMDescriptor<?>>();
for (SCMDescriptor<?> scmDescriptor : all()) {
if(!scmDescriptor.isApplicable(project)) continue;
if (pd instanceof AbstractProjectDescriptor) {
AbstractProjectDescriptor apd = (AbstractProjectDescriptor) pd;
if(!apd.isApplicable(scmDescriptor)) continue;
}
r.add(scmDescriptor);
}
return r;
}
}
|
package edu.kestrel.netbeans.lisp;
/* Use sockets instead
import com.franz.jlinker.TranStruct;
import com.franz.jlinker.JavaLinkDist;
import com.franz.jlinker.LispConnector;
*/
import java.net.Socket;
import java.lang.reflect.Method;
//hacky stuff:
import org.openide.nodes.Node;
import org.openide.loaders.DataObject;
import org.openide.filesystems.FileObject;
import edu.kestrel.netbeans.MetaSlangDataObject;
import edu.kestrel.netbeans.actions.ProcessUnitAction;
import edu.kestrel.netbeans.parser.ParseSourceRequest;
import edu.kestrel.netbeans.Util;
import java.util.HashSet;
import java.util.Set;
import java.io.*;
import org.openide.TopManager;
import org.openide.filesystems.FileSystem;
import org.openide.filesystems.Repository;
import org.openide.text.CloneableEditor;
import org.openide.text.CloneableEditorSupport;
import org.openide.windows.InputOutput;
import org.openide.windows.OutputWriter;
/**
*
* @author weilyn
*/
public class LispProcessManager {
private static Set machines = new HashSet() ;
private static String lispFile = "";
private static String lispHost = "";
private static int lispPort = 4321;
private static int pollInterval = 1000;
private static int pollCount = 300;
private static int javaTimeout = -1;
private static String javaFile = "";
private static String javaHost = "";
private static int javaPort = 0;
static private ExternalLispProcess lispServer = null;
static private Process lispProcess = null;
static private Socket lispSocket = null;
static private BufferedReader toLispStream = null;
static private OutputStream fromLispStream = null;
static private lispProcessManagerClass = Class.forname("LispProcessManager");
static private stringClass = Class.forname("String");
/** Creates a new instance of LispProcessManager */
public LispProcessManager() {
}
public static boolean connectToLisp() {
if (JavaLinkDist.query(true)) {
//writeToOutput("LispProcessManager.connectToLisp --> Already Connected");
return true;
} else if (JavaLinkDist.connect(lispHost, lispPort, javaHost, javaPort, pollInterval, javaTimeout)) {
//writeToOutput("LispProcessManager.connectToLisp --> New Connection Established");
return true;
} else {
//writeToOutput("LispProcessManager.connectToLisp --> Failed to Connect to LISP " + JavaLinkDist.query());
//writeToOutput("LispServer = "+ lispServer + "\n Lisp Process "+lispProcess + "\n");
if (lispServer == null){
lispServer = new ExternalLispProcess();
try {
lispProcess = lispServer.createProcess();
Thread.sleep(5000);
String s = null;
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(lispProcess.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(lispProcess.getErrorStream()));
// read the output from the command
//System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
//System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
writeToOutput("LispProcessManager.connectToLisp.Exception \""+e+"\" while starting Lisp");
}
// writeToOutput("LispProcessManager.connectToLisp --> Calling Connect to Lisp again");
if (lispProcess != null) {
return connectToLisp();
}
}
return false;
}
}
/* lispSocket = socket(lispHost,lispPort);
toLispStream = new BufferedReader(new InputStreamReader(lispSocket.getInputStream()));
fromLispStream = lispSocket.getOutputStream();
lispSocket.close();
if (toLispStream.ready()){};
*/
public static void lispCallBack() {
String methodName = fromLispStream.readLine();
// Assumes next line is an integer: add catch for NumberFormatException
int numParams = decode(fromLispStream.readLine());
String[] params = new String[numParams];
Class[] paramClasses = new Class[numParams]
for(int i = 0; i < numParams; i++) {
params[i] = fromLispStream.readLine();
paramClasses[i] = stringClass;
};
Method m = lispProcessManagerClass.getMethod(methodName,paramClasses);
try {m.invoke(params)}
catch (Exception _e) {
}
}
public static void destroyLispProcess() {
if (lispProcess != null) {
// writeToOutput("\n Destroying Lisp Process "+lispProcess);
lispProcess.destroy();
lispProcess = null;
lispServer = null;
}
}
public static void processUnit(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::PROCESS-UNIT"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
// This is called from specware
public static void setProcessUnitResults(String results) {
writeToSpecwareStatus(results);
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null)
fileObj.refresh();
}
// Entry point from lisp interface that takes only strings
public static void setProcessUnitResults(String pathName, String fileName,
String lineNum, String colNum, String errorMsg) {
// decode can throw NumberFormatException
setProcessUnitResults(pathName,fileName,decode(lineNum),decode(colNum),errorMsg)
public static void setProcessUnitResults(String pathName, String fileName,
int lineNum, int colNum, String errorMsg) {
FileObject fileObj = Repository.getDefault().find(pathName, fileName, "sw");
if (fileObj != null) {
// SLIGHT HACK: ParseSourceRequest is the same class used for the netbeans parsing stuff...
// should probably create different class for the Specware processing stuff
ParseSourceRequest.pushProcessUnitError(fileObj, lineNum, colNum, errorMsg);
}
}
public static void generateLispCode(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::GENERATE-LISP"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
public static void setGenerateLispResults(String pathName, String fileName, String results) {
writeToSpecwareStatus(results);
// TOTAL HACK: 14 is the length of "Demo_Examples/", which is the path to fileName in Weilyn's setup from the
// mounted local directory C:\Program Files\Specware4\Gui\src
String nonQualifiedFileName = fileName.substring(14);
// Do a refresh of Demo_Examples folder to show the possibly newly created "lisp" folder
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null) fileObj.refresh();
// Do a refresh of lisp folder to show the newly generated file
fileObj = Repository.getDefault().find("Demo_Examples.lisp", null, null);
if (fileObj != null) fileObj.refresh();
// TODO: Open the new lisp file in the editor as a text file
fileObj = Repository.getDefault().find("Demo_Examples.lisp", nonQualifiedFileName, "lisp");
if (fileObj != null) {
// CloneableEditorSupport editSupp = new CloneableEditorSupport(new CloneableEditorSupport.Env(fileObj));
// CloneableEditor editor = new CloneableEditor(editSupp);
}
}
public static void generateJavaCode(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::GENERATE-JAVA"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
public static void setGenerateJavaResults(String pathName, String fileName, String results) {
writeToSpecwareStatus(results);
// TOTAL HACK: 14 is the length of "Demo_Examples/", which is the path to fileName in Weilyn's setup from the
// mounted local directory C:\Program Files\Specware4\Gui\src
String nonQualifiedFileName = fileName.substring(14);
// Do a refresh of Demo_Examples folder to show the possibly newly created "java" folder
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null) fileObj.refresh();
// Do a refresh of java folder to show the newly generated file
fileObj = Repository.getDefault().find("Demo_Examples.java", null, null);
if (fileObj != null) fileObj.refresh();
// TODO: Open the new java file in the editor
fileObj = Repository.getDefault().find("Demo_Examples.java", nonQualifiedFileName, "java");
if (fileObj != null) {
// CloneableEditorSupport editSupp = new CloneableEditorSupport(new CloneableEditorSupport.Env(fileObj));
// CloneableEditor editor = new CloneableEditor(editSupp);
}
}
public static void writeToOutput(String s) {
InputOutput outputStream = TopManager.getDefault().getIO("Debug: LispProcessManager", false);
OutputWriter writer = outputStream.getOut();
writer.println(s);
}
public static void writeToSpecwareStatus(String s) {
InputOutput outputStream = TopManager.getDefault().getIO("Specware Output", false);
outputStream.select();
OutputWriter writer = outputStream.getOut();
writer.println(s);
}
}
|
package au.id.chenery.mapyrus;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* A parsed statement.
* Can be one of several types. An assignment statement, a conditional
* statement, a block of statements making a procedure or just a plain command.
*/
public class Statement
{
/*
* Possible types of statements.
*/
public static final int ASSIGN = 1;
public static final int CONDITIONAL = 2;
public static final int LOOP = 3;
public static final int BLOCK = 4;
public static final int COLOR = 10;
public static final int LINEWIDTH = 11;
public static final int MOVE = 12;
public static final int DRAW = 13;
public static final int ARC = 14;
public static final int CLEARPATH = 15;
public static final int SLICEPATH = 16;
public static final int STRIPEPATH = 17;
public static final int STROKE = 18;
public static final int FILL = 19;
public static final int CLIP = 20;
public static final int SCALE = 21;
public static final int ROTATE = 22;
public static final int WORLDS = 23;
public static final int PROJECT = 24;
public static final int DATASET = 25;
public static final int IMPORT = 26;
public static final int FETCH = 27;
public static final int NEWPAGE = 28;
public static final int PRINT = 29;
/*
* Statement type for call to user defined procedure block.
*/
public static final int CALL = 1000;
private int mType;
/*
* Statements in an if-then-else statement.
*/
private ArrayList mThenStatements;
private ArrayList mElseStatements;
/*
* Statements in a while loop statement.
*/
private ArrayList mLoopStatements;
/*
* Name of procedure block,
* variable names of parameters to this procedure
* and block of statements in a procedure in order of execution
*/
private String mBlockName;
private ArrayList mStatementBlock;
private ArrayList mParameters;
/*
* Name of variable in assignment.
*/
private String mAssignedVariable;
private Expression []mExpressions;
/*
* Filename and line number within file that this
* statement was read from.
*/
private String mFilename;
private int mLineNumber;
/*
* Static statement type lookup table for fast lookup.
*/
private static Hashtable mStatementTypeLookup;
static
{
mStatementTypeLookup = new Hashtable();
mStatementTypeLookup.put("color", new Integer(COLOR));
mStatementTypeLookup.put("colour", new Integer(COLOR));
mStatementTypeLookup.put("linewidth", new Integer(LINEWIDTH));
mStatementTypeLookup.put("move", new Integer(MOVE));
mStatementTypeLookup.put("draw", new Integer(DRAW));
mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH));
mStatementTypeLookup.put("slicepath", new Integer(SLICEPATH));
mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH));
mStatementTypeLookup.put("stroke", new Integer(STROKE));
mStatementTypeLookup.put("fill", new Integer(FILL));
mStatementTypeLookup.put("clip", new Integer(CLIP));
mStatementTypeLookup.put("scale", new Integer(SCALE));
mStatementTypeLookup.put("rotate", new Integer(ROTATE));
mStatementTypeLookup.put("worlds", new Integer(WORLDS));
mStatementTypeLookup.put("project", new Integer(PROJECT));
mStatementTypeLookup.put("dataset", new Integer(DATASET));
mStatementTypeLookup.put("import", new Integer(IMPORT));
mStatementTypeLookup.put("fetch", new Integer(FETCH));
mStatementTypeLookup.put("newpage", new Integer(NEWPAGE));
mStatementTypeLookup.put("print", new Integer(PRINT));
}
/**
* Looks up identifier for a statement name.
* @param s is the name of the statement.
* @returns numeric code for this statement, or -1 if statement
* is unknown.
*/
private int getStatementType(String s)
{
int retval;
Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase());
if (type == null)
retval = CALL;
else
retval = type.intValue();
return(retval);
}
/**
* Creates a plain statement, either a built-in command or
* a call to a procedure block that the user has defined.
* @param keyword is the name statement.
* @param expressions are the arguments for this statement.
*/
public Statement(String keyword, Expression []expressions)
{
mType = getStatementType(keyword);
if (mType == CALL)
mBlockName = keyword;
mExpressions = expressions;
}
/**
* Create an assignment statement.
* @param variableName is the name of the variable being assigned.
* @param value is the value being assigned to this variable.
*/
public Statement(String variableName, Expression value)
{
mType = ASSIGN;
mAssignedVariable = variableName;
mExpressions = new Expression[1];
mExpressions[0] = value;
}
/**
* Creates a procedure, a block of statements to be executed together.
* @param blockName is name of procedure block.
* @param parameters variable names of parameters to this procedure.
* @param statements list of statements that make up this procedure block.
*/
public Statement(String blockName, ArrayList parameters, ArrayList statements)
{
mBlockName = blockName;
mParameters = parameters;
mStatementBlock = statements;
mType = BLOCK;
}
/**
* Create an if, then, else, endif block of statements.
* @param test is expression to test.
* @param thenStatements is statements to execute if expression is true.
* @param elseStatements is statements to execute if expression is false,
* or null if there is no statement to execute.
*/
public Statement(Expression test, ArrayList thenStatements,
ArrayList elseStatements)
{
mType = CONDITIONAL;
mExpressions = new Expression[1];
mExpressions[0] = test;
mThenStatements = thenStatements;
mElseStatements = elseStatements;
}
/**
* Create a while loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
*/
public Statement(Expression test, ArrayList loopStatements)
{
mType = LOOP;
mExpressions = new Expression[1];
mExpressions[0] = test;
mLoopStatements = loopStatements;
}
/**
* Sets the filename and line number that this statement was read from.
* This is for use in any error message for this statement.
* @param filename is name of file this statement was read from.
* @param lineNumber is line number within file containing this statement.
*/
public void setFilenameAndLineNumber(String filename, int lineNumber)
{
mFilename = filename;
mLineNumber = lineNumber;
}
/**
* Returns filename and line number that this statement was read from.
* @return string containing filename and line number.
*/
public String getFilenameAndLineNumber()
{
return(mFilename + ":" + mLineNumber);
}
/**
* Returns the type of this statement.
* @return statement type.
*/
public int getType()
{
return(mType);
}
public Expression []getExpressions()
{
return(mExpressions);
}
public String getAssignedVariable()
{
return(mAssignedVariable);
}
/**
* Returns list of statements in "then" section of "if" statement.
* @return list of statements.
*/
public ArrayList getThenStatements()
{
return(mThenStatements);
}
/**
* Returns list of statements in "else" section of "if" statement.
* @return list of statements.
*/
public ArrayList getElseStatements()
{
return(mElseStatements);
}
/**
* Returns list of statements in while loop statement.
* @return list of statements.
*/
public ArrayList getLoopStatements()
{
return(mLoopStatements);
}
/**
* Return name of procedure block.
* @return name of procedure.
*/
public String getBlockName()
{
return(mBlockName);
}
/**
* Return variable names of parameters to a procedure.
* @return list of parameter names.
*/
public ArrayList getBlockParameters()
{
return(mParameters);
}
/**
* Return statements in a procedure.
* @return ArrayList of statements that make up the procedure.
*/
public ArrayList getStatementBlock()
{
return(mStatementBlock);
}
}
|
package org.nutz.http;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.nutz.json.Json;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.Encoding;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.util.NutMap;
import org.nutz.repo.Base64;
public class Request {
public static enum METHOD {
GET, POST, OPTIONS, PUT, PATCH, DELETE, TRACE, CONNECT, HEAD
}
public static Request get(String url) {
return create(url, METHOD.GET, new HashMap<String, Object>());
}
public static Request get(String url, Header header) {
return Request.create(url, METHOD.GET, new HashMap<String, Object>(), header);
}
public static Request post(String url) {
return create(url, METHOD.POST, new HashMap<String, Object>());
}
public static Request post(String url, Header header) {
return Request.create(url, METHOD.POST, new HashMap<String, Object>(), header);
}
public static Request create(String url, METHOD method) {
return create(url, method, new HashMap<String, Object>());
}
public static Request create(String url, METHOD method, String paramsAsJson, Header header) {
return create(url, method, Json.fromJson(NutMap.class, paramsAsJson), header);
}
public static Request create(String url, METHOD method, String paramsAsJson) {
return create(url, method, Json.fromJson(NutMap.class, paramsAsJson));
}
public static Request create(String url, METHOD method, Map<String, Object> params) {
return Request.create(url, method, params, Header.create());
}
public static Request create(String url,
METHOD method,
Map<String, Object> params,
Header header) {
return new Request().setMethod(method).setParams(params).setUrl(url).setHeader(header);
}
private Request() {}
private String url;
private METHOD method;
private String methodString;
private Header header;
private Map<String, Object> params;
private byte[] data;
private URL cacheUrl;
private InputStream inputStream;
private String enc = Encoding.UTF8;
private boolean offEncode;
public Request offEncode(boolean off) {
this.offEncode = off;
return this;
}
public URL getUrl() {
if (cacheUrl != null) {
return cacheUrl;
}
StringBuilder sb = new StringBuilder(url);
try {
if (this.isGet() && null != params && params.size() > 0) {
sb.append(url.indexOf('?') >= 0 ? '&' : '?');
sb.append(getURLEncodedParams());
}
cacheUrl = new URL(sb.toString());
return cacheUrl;
}
catch (Exception e) {
throw new HttpException(sb.toString(), e);
}
}
public Map<String, Object> getParams() {
return params;
}
public String getURLEncodedParams() {
final StringBuilder sb = new StringBuilder();
if (params != null) {
for (Entry<String, Object> en : params.entrySet()) {
final String key = en.getKey();
Object val = en.getValue();
if (val == null)
val = "";
Lang.each(val, new Each<Object>() {
@Override
public void invoke(int index, Object ele, int length)
throws ExitLoop, ContinueLoop, LoopException {
if (offEncode) {
sb.append(key).append('=').append(ele).append('&');
} else {
sb.append(Http.encode(key, enc))
.append('=')
.append(Http.encode(ele, enc))
.append('&');
}
}
});
}
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
public InputStream getInputStream() {
if (inputStream != null) {
return inputStream;
} else {
if (header.get("Content-Type") == null)
header.asFormContentType(enc);
if (null == data) {
try {
return new ByteArrayInputStream(getURLEncodedParams().getBytes(enc));
}
catch (UnsupportedEncodingException e) {
throw Lang.wrapThrow(e);
}
}
return new ByteArrayInputStream(data);
}
}
public Request setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
return this;
}
public byte[] getData() {
return data;
}
public Request setData(byte[] data) {
this.data = data;
return this;
}
public Request setData(String data) {
try {
this.data = data.getBytes(Encoding.UTF8);
}
catch (UnsupportedEncodingException e) {
}
return this;
}
public Request setParams(Map<String, Object> params) {
this.params = params;
return this;
}
public Request setUrl(String url) {
if (url != null && !url.contains(":
// http
this.url = "http://" + url;
else
this.url = url;
return this;
}
public METHOD getMethod() {
return method;
}
public boolean isGet() {
return METHOD.GET == method;
}
public boolean isPost() {
return METHOD.POST == method;
}
public boolean isDelete() {
return METHOD.DELETE == method;
}
public boolean isPut() {
return METHOD.PUT == method;
}
public Request setMethod(METHOD method) {
this.method = method;
return this;
}
public Header getHeader() {
return header;
}
public Request setHeader(Header header) {
if (header == null)
header = new Header();
this.header = header;
return this;
}
public Request setCookie(Cookie cookie) {
header.set("Cookie", cookie.toString());
return this;
}
public Cookie getCookie() {
String s = header.get("Cookie");
if (null == s)
return new Cookie();
return new Cookie(s);
}
/**
* ,StringMap<String,Object>data
*/
public Request setEnc(String reqEnc) {
if (reqEnc != null)
this.enc = reqEnc;
return this;
}
public String getEnc() {
return enc;
}
public Request header(String key, String value) {
getHeader().set(key, value);
return this;
}
public Request setMethodString(String methodString) {
try {
method = METHOD.valueOf(methodString.toUpperCase());
}
catch (Throwable e) {
this.methodString = methodString;
}
return this;
}
public String getMethodString() {
return methodString;
}
public Request basicAuth(String user, String password) {
header("Authorization",
"Basic " + Base64.encodeToString((user + ":" + password).getBytes(), false));
return this;
}
public boolean hasInputStream() {
return inputStream != null;
}
}
|
package com.squareup.picasso;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;
import com.squareup.picasso.transformations.DeferredResizeTransformation;
import com.squareup.picasso.transformations.ResizeTransformation;
import com.squareup.picasso.transformations.RotationTransformation;
import com.squareup.picasso.transformations.ScaleTransformation;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import static com.squareup.picasso.Utils.checkNotMain;
import static com.squareup.picasso.Utils.createKey;
public class Request implements Runnable {
private static final int DEFAULT_RETRY_COUNT = 2;
enum Type {
CONTENT,
FILE,
STREAM,
RESOURCE
}
final Picasso picasso;
final String path;
final int resourceId;
final String key;
final Type type;
final int errorResId;
final WeakReference<ImageView> target;
final PicassoBitmapOptions bitmapOptions;
final List<Transformation> transformations;
final RequestMetrics metrics;
final Drawable errorDrawable;
Future<?> future;
Bitmap result;
int retryCount;
boolean retryCancelled;
Request(Picasso picasso, String path, int resourceId, ImageView imageView,
PicassoBitmapOptions bitmapOptions, List<Transformation> transformations,
RequestMetrics metrics, Type type, int errorResId, Drawable errorDrawable) {
this.picasso = picasso;
this.path = path;
this.resourceId = resourceId;
this.type = type;
this.errorResId = errorResId;
this.errorDrawable = errorDrawable;
this.target = new WeakReference<ImageView>(imageView);
this.bitmapOptions = bitmapOptions;
this.transformations = transformations;
this.metrics = metrics;
this.retryCount = DEFAULT_RETRY_COUNT;
this.key = createKey(this);
}
Object getTarget() {
return target.get();
}
void complete() {
if (result == null) {
throw new AssertionError(
String.format("Attempted to complete request with no result!\n%s", this));
}
ImageView imageView = target.get();
if (imageView != null) {
imageView.setImageBitmap(result);
}
}
void error() {
ImageView target = this.target.get();
if (target == null) {
return;
}
if (errorResId != 0) {
target.setImageResource(errorResId);
} else if (errorDrawable != null) {
target.setImageDrawable(errorDrawable);
}
}
@Override public void run() {
try {
picasso.run(this);
} catch (final Throwable e) {
// If an unexpected exception happens, we should crash the app instead of letting the
// executor swallow it.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override public void run() {
throw new RuntimeException("An unexpected exception occurred", e);
}
});
}
}
@Override public String toString() {
return "Request["
+ "hashCode="
+ hashCode()
+ ", picasso="
+ picasso
+ ", path="
+ path
+ ", resourceId="
+ resourceId
+ ", target="
+ target
+ ", bitmapOptions="
+ bitmapOptions
+ ", transformations="
+ transformationKeys()
+ ", metrics="
+ metrics
+ ", future="
+ future
+ ", result="
+ result
+ ", retryCount="
+ retryCount
+ ']';
}
String transformationKeys() {
if (transformations.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder(transformations.size() * 16);
sb.append('[');
boolean first = true;
for (Transformation transformation : transformations) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(transformation.key());
}
sb.append(']');
return sb.toString();
}
@SuppressWarnings("UnusedDeclaration") // Public API.
public static class Builder {
private final Picasso picasso;
private final String path;
private final int resourceId;
private final Type type;
private final List<Transformation> transformations;
private boolean deferredResize;
private PicassoBitmapOptions bitmapOptions;
private int placeholderResId;
private Drawable placeholderDrawable;
private int errorResId;
private Drawable errorDrawable;
Builder(Picasso picasso, String path, int resourceId, Type type) {
if (picasso == null) {
throw new AssertionError();
}
boolean hasPath = path != null && path.trim().length() != 0;
boolean hasResource = resourceId != 0;
if (!(hasPath ^ hasResource)) {
throw new IllegalArgumentException("A valid path or valid resource must be provided.");
}
this.picasso = picasso;
this.path = path;
this.resourceId = resourceId;
this.type = type;
this.transformations = new ArrayList<Transformation>(4);
}
public Builder placeholder(int placeholderResId) {
if (placeholderResId == 0) {
throw new IllegalArgumentException("Placeholder image resource invalid.");
}
if (placeholderDrawable != null) {
throw new IllegalStateException("Placeholder image already set.");
}
this.placeholderResId = placeholderResId;
return this;
}
public Builder placeholder(Drawable placeholderDrawable) {
if (placeholderDrawable == null) {
throw new IllegalArgumentException("Placeholder image may not be null.");
}
if (placeholderResId != 0) {
throw new IllegalStateException("Placeholder image already set.");
}
this.placeholderDrawable = placeholderDrawable;
return this;
}
public Builder error(int errorResId) {
if (errorResId == 0) {
throw new IllegalArgumentException("Error image resource invalid.");
}
if (errorDrawable != null) {
throw new IllegalStateException("Error image already set.");
}
this.errorResId = errorResId;
return this;
}
public Builder error(Drawable errorDrawable) {
if (errorDrawable == null) {
throw new IllegalArgumentException("Error image may not be null.");
}
if (this.errorResId != 0) {
throw new IllegalStateException("Error image already set.");
}
this.errorDrawable = errorDrawable;
return this;
}
public Builder fit() {
deferredResize = true;
return this;
}
public Builder resizeDimen(int targetWidthResId, int targetHeightResId) {
Resources resources = picasso.context.getResources();
int targetWidth = resources.getDimensionPixelSize(targetWidthResId);
int targetHeight = resources.getDimensionPixelSize(targetHeightResId);
return resize(targetWidth, targetHeight);
}
public Builder resize(int targetWidth, int targetHeight) {
if (targetWidth <= 0) {
throw new IllegalArgumentException("Width must be positive number.");
}
if (targetHeight <= 0) {
throw new IllegalArgumentException("Height must be positive number.");
}
// When decoding files from local resources, prefer to use bitmap options for better memory
// management.
if (type != Type.STREAM) {
if (bitmapOptions == null) {
bitmapOptions = new PicassoBitmapOptions(targetWidth, targetHeight, 0);
}
bitmapOptions.inJustDecodeBounds = true;
return this;
}
return transform(new ResizeTransformation(targetWidth, targetHeight));
}
public Builder scale(float factor) {
if (factor <= 0) {
throw new IllegalArgumentException("Scale factor must be positive number.");
}
return transform(new ScaleTransformation(factor));
}
public Builder rotate(float degrees) {
return transform(new RotationTransformation(degrees));
}
public Builder rotate(float degrees, float pivotX, float pivotY) {
return transform(new RotationTransformation(degrees, pivotX, pivotY));
}
public Builder transform(Transformation transformation) {
if (transformation == null) {
throw new IllegalArgumentException("Transformation may not be null.");
}
this.transformations.add(transformation);
return this;
}
public Bitmap get() {
checkNotMain();
Request request =
new Request(picasso, path, resourceId, null, bitmapOptions, transformations, null, type,
errorResId, errorDrawable);
return picasso.run(request);
}
public void into(Target target) {
if (target == null) {
throw new IllegalArgumentException("Target cannot be null.");
}
Bitmap bitmap = picasso.quickMemoryCacheCheck(target, createKey(path, transformations, null));
if (bitmap != null) {
target.onSuccess(bitmap);
return;
}
RequestMetrics metrics = createRequestMetrics();
Request request =
new TargetRequest(picasso, path, resourceId, target, bitmapOptions, transformations,
metrics, type, errorResId, errorDrawable);
picasso.submit(request);
}
public void into(ImageView target) {
if (target == null) {
throw new IllegalArgumentException("Target cannot be null.");
}
if (deferredResize) {
transformations.add(new DeferredResizeTransformation(target));
}
Bitmap bitmap = picasso.quickMemoryCacheCheck(target, createKey(path, transformations, null));
if (bitmap != null) {
target.setImageBitmap(bitmap);
return;
}
if (placeholderDrawable != null) {
target.setImageDrawable(placeholderDrawable);
}
if (placeholderResId != 0) {
target.setImageResource(placeholderResId);
}
RequestMetrics metrics = new RequestMetrics();
Request request =
new Request(picasso, path, resourceId, target, bitmapOptions, transformations, metrics,
type, errorResId, errorDrawable);
picasso.submit(request);
}
private RequestMetrics createRequestMetrics() {
RequestMetrics metrics = null;
if (picasso.debugging) {
metrics = new RequestMetrics();
metrics.createdTime = System.nanoTime();
}
return metrics;
}
}
}
|
package com.ternaryop.photoshelf.parsers;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ternaryop.utils.StringUtils;
public class TitleParser {
private static Pattern titleRE = Pattern.compile("^(.*?)\\s(at the|[-\u2013|~@]|attends|arrives|leaves)", Pattern.CASE_INSENSITIVE);
private static String[] months = {"", "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
private static HashMap<String, String> monthsShort = new HashMap<String, String>();
static {
monthsShort.put("jan", "January");
monthsShort.put("feb", "February");
monthsShort.put("mar", "March");
monthsShort.put("apr", "April");
monthsShort.put("may", "May");
monthsShort.put("jun", "June");
monthsShort.put("jul", "July");
monthsShort.put("aug", "August");
monthsShort.put("sep", "September");
monthsShort.put("oct", "October");
monthsShort.put("nov", "November");
monthsShort.put("dec", "December");
}
private static TitleParser instance = new TitleParser();
/**
* Fill parseInfo with day, month, year, matched
*/
protected Map<String, Object> parseDate(String title) {
int day = 0;
String monthStr = null;
int year = 0;
// handle dates in the form Jan 10, 2010 or January 10 2010 or Jan 15
Matcher m = Pattern.compile("[-,]\\s+\\(?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[^0-9]*([0-9]*)[^0-9]*([0-9]*)\\)?.*$", Pattern.CASE_INSENSITIVE).matcher(title);
if (m.find() && m.groupCount() > 1) {
day = m.group(2).length() != 0 ? Integer.parseInt(m.group(2)) : 0;
monthStr = monthsShort.get(m.group(1).toLowerCase(Locale.getDefault()));
if (m.groupCount() == 3 && m.group(3).length() > 0) {
year = Integer.parseInt(m.group(3));
}
} else {
// handle dates in the form dd/dd/dd?? or (dd/dd/??)
m = Pattern.compile("\\(?([0-9]{2}).([0-9]{1,2}).([0-9]{2,4})\\)?").matcher(title);
if (m.find() && m.groupCount() > 1) {
day = Integer.parseInt(m.group(1));
int monthInt = Integer.parseInt(m.group(2));
year = Integer.parseInt(m.group(3));
// we have a two-digits year
if (year < 100) {
year += 2000;
}
if (monthInt > 12) {
int tmp = monthInt;
monthInt = day;
day = tmp;
}
monthStr = months[monthInt];
} else {
m = null;
}
}
HashMap<String, Object> dateComponents = new HashMap<String, Object>();
// day could be not present for example "New York City, January 11"
if (day > 0) {
dateComponents.put("day", day + "");
}
if (monthStr != null) {
dateComponents.put("month", monthStr);
}
if (year < 2000) {
year = Calendar.getInstance().get(Calendar.YEAR);
}
dateComponents.put("year", year + "");
if (m != null) {
dateComponents.put("matched", m);
}
return dateComponents;
}
private TitleParser() {
}
public TitleData parseTitle(String title) {
TitleData titleData = new TitleData();
title = StringUtils.replaceUnicodeWithClosestAscii(title);
Matcher m = titleRE.matcher(title);
if (m.find() && m.groupCount() > 1) {
titleData.setWho(StringUtils.capitalize(m.group(1)));
// remove the 'who' chunk
title = title.substring(m.regionStart() + m.group(0).length());
}
Map<String, Object> dateComponents = parseDate(title);
Matcher dateMatcher = (Matcher) dateComponents.get("matched");
String loc;
if (dateMatcher == null) {
// no date found so use all substring as location
loc = title;
} else {
loc = title.substring(0, dateMatcher.start());
}
// city names can be multi words so allow whitespaces
m = Pattern.compile("\\s*(.*)\\s+in\\s+([a-z.\\s]*).*$", Pattern.CASE_INSENSITIVE).matcher(loc);
if (m.find() && m.groupCount() > 1) {
titleData.setLocation(m.group(1));
titleData.setCity(m.group(2).trim());
} else {
titleData.setLocation(loc);
}
String when = "";
if (dateComponents.get("day") != null) {
when = dateComponents.get("day") + " ";
};
if (dateComponents.get("month") != null) {
when += dateComponents.get("month") + ", ";
}
when += dateComponents.get("year");
titleData.setWhen(when);
titleData.setTags(new String[] {titleData.getWho(), titleData.getLocation()});
return titleData;
}
public static TitleParser instance() {
return instance;
}
}
|
package com.greenyetilab.equiv.core;
import java.util.ArrayList;
/**
* Holds all the data
*/
public class Kernel {
private final Consumer mConsumer = new Consumer();
private final Day mDay = new Day();
private final ProductList mProductList = new ProductList();
private static Kernel sInstance = null;
private int mCurrentTab = -1;
Kernel() {
setupProductList();
setupDay();
setupConsumer();
}
public static Kernel getInstance() {
if (sInstance == null) {
sInstance = new Kernel();
}
return sInstance;
}
public Consumer getConsumer() {
return mConsumer;
}
public Day getDay() {
return mDay;
}
public ProductList getProductList() {
return mProductList;
}
public int getCurrentTab() {
return mCurrentTab;
}
public void setCurrentTab(int currentTab) {
mCurrentTab = currentTab;
}
private void setupProductList() {
ArrayList<Product> products = new ArrayList<>();
products.add(new Product("Pommes de terre", "g", 0.02f));
products.add(new Product("Balisto", "", 1.5f));
mProductList.setItems(products);
}
private void setupDay() {
Meal meal = new Meal("breakfast");
meal.add(new MealItem(mProductList.getItems().get(1), 0.5f));
mDay.add(meal);
meal = new Meal("lunch");
meal.add(new MealItem(mProductList.getItems().get(0), 100));
mDay.add(meal);
meal = new Meal("snack");
meal.add(new MealItem(mProductList.getItems().get(1), 1));
mDay.add(meal);
meal = new Meal("dinner");
meal.add(new MealItem(mProductList.getItems().get(0), 100));
mDay.add(meal);
}
private void setupConsumer() {
mConsumer.setName("Clara");
mConsumer.setMaxProteinPerDay(4f);
}
}
|
package com.honu.giftwise;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
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.ImageView;
import android.widget.TextView;
import com.honu.giftwise.data.Gift;
import com.honu.giftwise.data.GiftImageCache;
import com.honu.giftwise.view.FloatingActionButton;
/**
* Fragment for viewing Gift details
*/
public class ViewGiftFragment extends Fragment {
private static final String LOG_TAG = ViewGiftFragment.class.getSimpleName();
private Gift gift;
private String mContactName;
private GiftImageCache mImageCache;
private ShareActionProvider mShareActionProvider;
/**
* Create Fragment and setup the Bundle arguments
*/
public static ViewGiftFragment getInstance(Gift gift, String contactName) {
ViewGiftFragment fragment = new ViewGiftFragment();
// Attach some data needed to populate our fragment layouts
Bundle args = new Bundle();
args.putParcelable("gift", gift);
args.putString("contactName", contactName);
// Set the arguments on the fragment that will be fetched by the edit activity
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_gift, container, false);
mImageCache = ((GiftwiseApplication)getActivity().getApplicationContext()).getGiftImageCache();
// Get the Id of the raw contact
Bundle args = getArguments();
gift = args.getParcelable("gift");
mContactName = args.getString("contactName");
// gift name
TextView nameTxt = (TextView)rootView.findViewById(R.id.gift_name);
nameTxt.setText(gift.getName());
// recipient name
TextView recipientTV = (TextView)rootView.findViewById(R.id.contact_display_name);
recipientTV.setText(mContactName);
// gift price
TextView priceTxt = (TextView) rootView.findViewById(R.id.gift_price);
priceTxt.setText(gift.getFormattedPrice());
TextView urlTxt = (TextView)rootView.findViewById(R.id.gift_url);
urlTxt.setText(gift.getUrl());
Linkify.addLinks(urlTxt, Linkify.WEB_URLS);
TextView notesTxt = (TextView)rootView.findViewById(R.id.gift_notes);
notesTxt.setText(gift.getNotes());
// set image from cache if exists
ImageView imageView = (ImageView)rootView.findViewById(R.id.gift_image);
BitmapDrawable bitmap = mImageCache.getBitmapFromMemCache(gift.getGiftId() + "");
if (bitmap != null ) {
//imageView.setImageBitmap(bitmap);
Log.i(LOG_TAG, "Bitmap loaded from cache for giftId: " + gift.getGiftId());
imageView.setImageDrawable(bitmap);
} else {
Log.i(LOG_TAG, "No bitmap found in cache for giftId: " + gift.getGiftId());
}
// show options menu
setHasOptionsMenu(true);
// handler for the FAB edit button
FloatingActionButton editButton = (FloatingActionButton) rootView.findViewById(R.id.edit_gift_fab);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//((MainActivity)getActivity()).addContact();
editGift();
}
});
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflate the fragment menu
inflater.inflate(R.menu.menu_view_gift_fragment, menu);
// Retrieve the share menu item
MenuItem shareItem = menu.findItem(R.id.action_share);
// Now get the ShareActionProvider from the item
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareIntent());
//mShareActionProvider.setShareHistoryFileName(null);
} else {
Log.d(LOG_TAG, "Problem finding ShareActionProvider");
//shareActionProvider = new ShareActionProvider(getActivity());
//MenuItemCompat.setActionProvider(shareItem, shareActionProvider);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
// case R.id.action_share:
// newGame();
// return true;
// case R.id.action_browse:
// openUrl();
// return true;
// case R.id.action_edit:
// editGift();
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void editGift() {
Log.i(LOG_TAG, "Open GiftId: " + gift.getGiftId());
// start activity to add/edit gift idea
Intent intent = new Intent(getActivity(), EditGiftActivity.class);
intent.putExtra("gift", gift);
startActivityForResult(intent, 1);
}
private Intent createShareIntent() {
Log.d(LOG_TAG, "Share gift item: " );
Intent intent = new Intent(Intent.ACTION_SEND);
// prevents Activity selected for sharing from being placed on app stack
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getTextDescription());
return intent;
}
private String getTextDescription() {
// View rootView = getView();
// TextView nameEdit = (TextView)rootView.findViewById(R.id.gift_name);
// TextView priceEdit = (TextView) rootView.findViewById(R.id.gift_price);
// TextView urlEdit = (TextView)rootView.findViewById(R.id.gift_url);
// TextView notesEdit = (TextView)rootView.findViewById(R.id.gift_notes);
// String priceTxt = priceEdit.getText().toString();
// if (!TextUtils.isEmpty(priceTxt)) {
// try {
// double price = Double.parseDouble(priceTxt);
// if (price > 0)
// priceTxt = ContactsUtils.formatPrice(getActivity(), "USD", price);
// } catch (NumberFormatException nfe) {
// Log.e(LOG_TAG, "Exception formatting price", nfe);
// priceTxt = "";
// StringBuffer buffer = new StringBuffer();
// buffer.append(String.format("Gift: %s\n", nameEdit.getText().toString()));
// buffer.append(String.format("Price: %s\n", ContactsUtils.formatPrice(getActivity(), "USD", price)));
// buffer.append(String.format("Notes: %s\n", notesEdit.getText().toString()));
// buffer.append(String.format(urlEdit.getText().toString()));
String priceTxt = "";
if (gift.getPrice() > 0)
priceTxt = gift.getFormattedPrice();
StringBuffer buffer = new StringBuffer();
buffer.append(String.format("%s %s\n", gift.getName(), priceTxt));
if (!TextUtils.isEmpty(gift.getNotes()))
buffer.append(String.format("Notes: %s\n", gift.getNotes()));
buffer.append(gift.getUrl());
return buffer.toString();
}
}
|
package com.k3nx.marchingants;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
private final static String TAG = "MainActivity";
private String convert(int i) {
String ret = "";
if (i == 1) ret = "one";
if (i == 2) ret = "two";
if (i == 3) ret = "three";
if (i == 4) ret = "four";
if (i == 5) ret = "five";
if (i == 6) ret = "six";
if (i == 7) ret = "seven";
if (i == 8) ret = "eight";
if (i == 9) ret = "nine";
if (i == 10) ret = "ten";
return ret;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Just Logging some lyrics to the Marching Ants song
// Based on the lyrics provided here:
for (int i = 1; i <= 10; i++) {
Log.d(TAG, "Ants go marching " + convert(i) + " by " + convert(i) + ". Hoorah! Hoorah!");
Log.d(TAG, "Ants go marching " + convert(i) + " by " + convert(i) + ". Hoorah! Hoorah!");
Log.d(TAG, "Ants go marching " + convert(i) + " by " + convert(i) + ",");
if (i == 1) Log.d(TAG, "The little one stops to suck her thumb,");
if (i == 2) Log.d(TAG, "The little one stops to tie his shoe,");
if (i == 3) Log.d(TAG, "The little one stops to climb a tree,");
if (i == 4) Log.d(TAG, "The little one stops to shut the door,");
if (i == 5) Log.d(TAG, "The little one stops to take a dive,");
if (i == 6) Log.d(TAG, "The little one stops to pick up sticks,");
if (i == 7) Log.d(TAG, "The little one stops to pray to heaven,");
if (i == 8) Log.d(TAG, "The little one stops to shut the gate,");
if (i == 9) Log.d(TAG, "The little one stops to check the time,");
if (i == 10) Log.d(TAG, "The little one stops to say \"The End\",");
Log.d(TAG, "And they all go marching down, to the ground to get out of the rain.");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.marverenic.music;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.IdRes;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RemoteViews;
import com.crashlytics.android.Crashlytics;
import com.marverenic.music.activity.LibraryActivity;
import com.marverenic.music.instances.Song;
import java.io.IOException;
import java.util.List;
public class PlayerService extends Service {
private static final String TAG = "PlayerService";
private static final boolean DEBUG = BuildConfig.DEBUG;
public static final int NOTIFICATION_ID = 1;
// Intent Action & Extra names
/**
* Toggle between play and pause
*/
public static final String ACTION_TOGGLE_PLAY = "com.marverenic.music.action.TOGGLE_PLAY";
/**
* Skip to the previous song
*/
public static final String ACTION_PREV = "com.marverenic.music.action.PREVIOUS";
/**
* Skip to the next song
*/
public static final String ACTION_NEXT = "com.marverenic.music.action.NEXT";
/**
* Stop playback and kill service
*/
public static final String ACTION_STOP = "com.marverenic.music.action.STOP";
/**
* The service instance in use (singleton)
*/
private static PlayerService instance;
/**
* Used in binding and unbinding this service to the UI process
*/
private static IBinder binder;
// Instance variables
/**
* The media player for the service instance
*/
private Player player;
private boolean finished = false; // Don't attempt to release resources more than once
@Override
public IBinder onBind(Intent intent) {
if (binder == null) {
binder = new Stub();
}
return binder;
}
/**
* @inheritDoc
*/
@Override
public void onCreate() {
super.onCreate();
if (DEBUG) Log.i(TAG, "onCreate() called");
if (instance == null) {
instance = this;
} else {
if (DEBUG) Log.w(TAG, "Attempted to create a second PlayerService");
stopSelf();
return;
}
if (player == null) {
player = new Player(this);
}
player.reload();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
if (DEBUG) Log.i(TAG, "Called onDestroy()");
try {
player.saveState("");
} catch (Exception ignored) {
}
finish();
super.onDestroy();
}
public static PlayerService getInstance() {
return instance;
}
/**
* Generate and post a notification for the current player status
* Posts the notification by starting the service in the foreground
*/
public void notifyNowPlaying() {
if (DEBUG) Log.i(TAG, "notifyNowPlaying() called");
// Create the compact view
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification);
// Create the expanded view
RemoteViews notificationViewExpanded =
new RemoteViews(getPackageName(), R.layout.notification_expanded);
// Set the artwork for the notification
if (player.getArt() != null) {
notificationView.setImageViewBitmap(R.id.notificationIcon, player.getArt());
notificationViewExpanded.setImageViewBitmap(R.id.notificationIcon, player.getArt());
} else {
notificationView.setImageViewResource(R.id.notificationIcon, R.drawable.art_default);
notificationViewExpanded
.setImageViewResource(R.id.notificationIcon, R.drawable.art_default);
}
// If the player is playing music, set the track info and the button intents
if (player.getNowPlaying() != null) {
// Update the info for the compact view
notificationView.setTextViewText(R.id.notificationContentTitle,
player.getNowPlaying().getSongName());
notificationView.setTextViewText(R.id.notificationContentText,
player.getNowPlaying().getAlbumName());
notificationView.setTextViewText(R.id.notificationSubText,
player.getNowPlaying().getArtistName());
// Update the info for the expanded view
notificationViewExpanded.setTextViewText(R.id.notificationContentTitle,
player.getNowPlaying().getSongName());
notificationViewExpanded.setTextViewText(R.id.notificationContentText,
player.getNowPlaying().getAlbumName());
notificationViewExpanded.setTextViewText(R.id.notificationSubText,
player.getNowPlaying().getArtistName());
}
// Set the button intents for the compact view
setNotificationButton(notificationView, R.id.notificationSkipPrevious, ACTION_PREV);
setNotificationButton(notificationView, R.id.notificationSkipNext, ACTION_NEXT);
setNotificationButton(notificationView, R.id.notificationPause, ACTION_TOGGLE_PLAY);
setNotificationButton(notificationView, R.id.notificationStop, ACTION_STOP);
// Set the button intents for the expanded view
setNotificationButton(notificationViewExpanded, R.id.notificationSkipPrevious, ACTION_PREV);
setNotificationButton(notificationViewExpanded, R.id.notificationSkipNext, ACTION_NEXT);
setNotificationButton(notificationViewExpanded, R.id.notificationPause, ACTION_TOGGLE_PLAY);
setNotificationButton(notificationViewExpanded, R.id.notificationStop, ACTION_STOP);
// Update the play/pause button icon to reflect the player status
if (!(player.isPlaying() || player.isPreparing())) {
notificationView.setImageViewResource(R.id.notificationPause,
R.drawable.ic_play_arrow_36dp);
notificationViewExpanded.setImageViewResource(R.id.notificationPause,
R.drawable.ic_play_arrow_36dp);
} else {
notificationView.setImageViewResource(R.id.notificationPause,
R.drawable.ic_pause_36dp);
notificationViewExpanded.setImageViewResource(R.id.notificationPause,
R.drawable.ic_pause_36dp);
}
// Build the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(
(player.isPlaying() || player.isPreparing())
? R.drawable.ic_play_arrow_24dp
: R.drawable.ic_pause_24dp)
.setOnlyAlertOnce(true)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setContentIntent(PendingIntent.getActivity(this, 0,
new Intent(this, LibraryActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT));
Notification notification = builder.build();
// Manually set the expanded and compact views
notification.contentView = notificationView;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
notification.bigContentView = notificationViewExpanded;
}
startForeground(NOTIFICATION_ID, notification);
}
private void setNotificationButton(RemoteViews notificationView, @IdRes int viewId,
String action) {
notificationView.setOnClickPendingIntent(viewId,
PendingIntent.getBroadcast(this, 1,
new Intent(this, Listener.class).setAction(action), 0));
}
public void stop() {
if (DEBUG) Log.i(TAG, "stop() called");
// If the UI process is still running, don't kill the process, only remove its notification
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> procInfos =
activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfos.size(); i++) {
if (procInfos.get(i).processName.equals(BuildConfig.APPLICATION_ID)) {
player.pause();
stopForeground(true);
return;
}
}
// If the UI process has already ended, kill the service and close the player
finish();
}
public void finish() {
if (DEBUG) Log.i(TAG, "finish() called");
if (!finished) {
player.finish();
player = null;
stopForeground(true);
instance = null;
stopSelf();
finished = true;
}
}
public static class Listener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getAction() == null) {
if (DEBUG) Log.i(TAG, "Intent received (action = null)");
return;
}
if (DEBUG) Log.i(TAG, "Intent received (action = \"" + intent.getAction() + "\")");
if (instance == null) {
if (DEBUG) Log.i(TAG, "Service not initialized");
return;
}
if (instance.player.getNowPlaying() != null) {
try {
instance.player.saveState(intent.getAction());
} catch (IOException e) {
Crashlytics.logException(e);
if (DEBUG) e.printStackTrace();
}
}
switch (intent.getAction()) {
case (ACTION_TOGGLE_PLAY):
instance.player.togglePlay();
instance.player.updateUi();
break;
case (ACTION_PREV):
instance.player.previous();
instance.player.updateUi();
break;
case (ACTION_NEXT):
instance.player.skip();
instance.player.updateUi();
break;
case (ACTION_STOP):
instance.stop();
if (instance != null) {
instance.player.updateUi();
}
break;
}
}
}
/**
* Receives media button presses from in line remotes, input devices, and other sources
*/
public static class RemoteControlReceiver extends BroadcastReceiver {
public RemoteControlReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// Handle Media button Intents
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
instance.player.togglePlay();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
instance.player.play();
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
instance.player.pause();
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
instance.player.skip();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
instance.player.previous();
break;
}
}
}
}
}
public static class Stub extends IPlayerService.Stub {
@Override
public void stop() throws RemoteException {
instance.stop();
}
@Override
public void skip() throws RemoteException {
instance.player.skip();
}
@Override
public void previous() throws RemoteException {
instance.player.previous();
}
@Override
public void begin() throws RemoteException {
instance.player.begin();
}
@Override
public void togglePlay() throws RemoteException {
instance.player.togglePlay();
}
@Override
public void play() throws RemoteException {
instance.player.play();
}
@Override
public void pause() throws RemoteException {
instance.player.play();
}
@Override
public void setPrefs(boolean shuffle, int repeat) throws RemoteException {
instance.player.setPrefs(shuffle, (short) repeat);
}
@Override
public void setQueue(List<Song> newQueue, int newPosition) throws RemoteException {
instance.player.setQueue(newQueue, newPosition);
}
@Override
public void changeSong(int position) throws RemoteException {
instance.player.changeSong(position);
}
@Override
public void editQueue(List<Song> newQueue, int newPosition) throws RemoteException {
instance.player.editQueue(newQueue, newPosition);
}
@Override
public void queueNext(Song song) throws RemoteException {
instance.player.queueNext(song);
}
@Override
public void queueNextList(List<Song> songs) throws RemoteException {
instance.player.queueNext(songs);
}
@Override
public void queueLast(Song song) throws RemoteException {
instance.player.queueLast(song);
}
@Override
public void queueLastList(List<Song> songs) throws RemoteException {
instance.player.queueLast(songs);
}
@Override
public void seek(int position) throws RemoteException {
instance.player.seek(position);
}
@Override
public boolean isPlaying() throws RemoteException {
return instance.player.isPlaying();
}
@Override
public boolean isPreparing() throws RemoteException {
return instance.player.isPreparing();
}
@Override
public Song getNowPlaying() throws RemoteException {
return instance.player.getNowPlaying();
}
@Override
public List<Song> getQueue() throws RemoteException {
return instance.player.getQueue();
}
@Override
public int getQueuePosition() throws RemoteException {
return instance.player.getQueuePosition();
}
@Override
public int getCurrentPosition() throws RemoteException {
return instance.player.getCurrentPosition();
}
@Override
public int getDuration() throws RemoteException {
return instance.player.getDuration();
}
@Override
public int getAudioSessionId() throws RemoteException {
return instance.player.getAudioSessionId();
}
}
}
|
package com.samourai.wallet.api;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.ConnectivityStatus;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.WebUtil;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.R;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.util.encoders.Hex;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class APIFactory {
private static long xpub_balance = 0L;
private static HashMap<String, Long> xpub_amounts = null;
private static HashMap<String,List<Tx>> xpub_txs = null;
private static HashMap<String,Integer> unspentAccounts = null;
private static HashMap<String,String> unspentPaths = null;
private static HashMap<String,UTXO> utxos = null;
private static HashMap<String, Long> bip47_amounts = null;
private static long latest_block_height = -1L;
private static String latest_block_hash = null;
private static APIFactory instance = null;
private static Context context = null;
private static AlertDialog alertDialog = null;
private APIFactory() { ; }
public static APIFactory getInstance(Context ctx) {
context = ctx;
if(instance == null) {
xpub_amounts = new HashMap<String, Long>();
xpub_txs = new HashMap<String,List<Tx>>();
xpub_balance = 0L;
bip47_amounts = new HashMap<String, Long>();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
instance = new APIFactory();
}
return instance;
}
public synchronized void reset() {
xpub_balance = 0L;
xpub_amounts.clear();
bip47_amounts.clear();
xpub_txs.clear();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
}
private synchronized JSONObject getXPUB(String[] xpubs) {
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
// use POST
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "multiaddr?", args.toString());
Log.i("APIFactory", "XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "multiaddr", args);
Log.i("APIFactory", "XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
xpub_txs.put(xpubs[0], new ArrayList<Tx>());
parseXPUB(jsonObject);
xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
if(jsonObject.has("wallet")) {
JSONObject walletObj = (JSONObject)jsonObject.get("wallet");
if(walletObj.has("final_balance")) {
xpub_balance = walletObj.getLong("final_balance");
Log.d("APIFactory", "xpub_balance:" + xpub_balance);
}
}
if(jsonObject.has("info")) {
JSONObject infoObj = (JSONObject)jsonObject.get("info");
if(infoObj.has("latest_block")) {
JSONObject blockObj = (JSONObject)infoObj.get("latest_block");
if(blockObj.has("height")) {
latest_block_height = blockObj.getLong("height");
}
if(blockObj.has("hash")) {
latest_block_hash = blockObj.getString("hash");
}
}
}
if(jsonObject.has("addresses")) {
JSONArray addressesArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressesArray.length(); i++) {
addrObj = (JSONObject)addressesArray.get(i);
if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) {
if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) {
xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance"));
AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0);
AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0);
}
else {
long amount = 0L;
String addr = null;
addr = (String)addrObj.get("address");
amount = addrObj.getLong("final_balance");
String pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
int idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(pcode != null && pcode.length() > 0) {
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
}
if(addr != null) {
bip47_amounts.put(addr, amount);
}
}
}
}
}
if(jsonObject.has("txs")) {
JSONArray txArray = (JSONArray)jsonObject.get("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
long height = 0L;
long amount = 0L;
long ts = 0L;
String hash = null;
String addr = null;
String _addr = null;
if(txObj.has("block_height")) {
height = txObj.getLong("block_height");
}
else {
height = -1L; // 0 confirmations
}
if(txObj.has("hash")) {
hash = (String)txObj.get("hash");
}
if(txObj.has("result")) {
amount = txObj.getLong("result");
}
if(txObj.has("time")) {
ts = txObj.getLong("time");
}
if(txObj.has("inputs")) {
JSONArray inputArray = (JSONArray)txObj.get("inputs");
JSONObject inputObj = null;
for(int j = 0; j < inputArray.length(); j++) {
inputObj = (JSONObject)inputArray.get(j);
if(inputObj.has("prev_out")) {
JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out");
if(prevOutObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) {
_addr = (String)prevOutObj.get("addr");
}
else {
_addr = (String)prevOutObj.get("addr");
}
}
}
}
if(txObj.has("out")) {
JSONArray outArray = (JSONArray)txObj.get("out");
JSONObject outObj = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)outObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else {
_addr = (String)outObj.get("addr");
}
}
}
if(addr != null || _addr != null) {
if(addr == null) {
addr = _addr;
}
Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0);
if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) {
tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr));
}
if(!xpub_txs.containsKey(addr)) {
xpub_txs.put(addr, new ArrayList<Tx>());
}
if(FormatsUtil.getInstance().isValidXpub(addr)) {
xpub_txs.get(addr).add(tx);
}
else {
xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx);
}
if(height > 0L) {
RBFUtil.getInstance().remove(hash);
}
}
}
}
return true;
}
return false;
}
public long getLatestBlockHeight() {
return latest_block_height;
}
public String getLatestBlockHash() {
return latest_block_hash;
}
public JSONObject getNotifTx(String hash, String addr) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.CHAINSO_TX_PREV_OUT_URL);
url.append(hash);
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifTx(jsonObject, addr, hash);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public JSONObject getNotifAddress(String addr) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.CHAINSO_GET_RECEIVE_TX_URL);
url.append(addr);
// Log.i("APIFactory", "Notif address:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif address:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifAddress(jsonObject, addr);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException {
if(jsonObject != null) {
if(jsonObject.has("status") && jsonObject.getString("status").equals("success") && jsonObject.has("data")) {
JSONObject dataObj = jsonObject.getJSONObject("data");
if(dataObj.has("txs")) {
JSONArray txArray = dataObj.getJSONArray("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
if(!txObj.has("confirmations") || (txObj.has("confirmations") && txObj.getLong("confirmations") < 1L)) {
return;
}
String hash = null;
if(txObj.has("txid")) {
hash = (String)txObj.get("txid");
if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) {
getNotifTx(hash, addr);
}
}
}
}
}
}
}
public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException {
if(jsonObject != null) {
byte[] mask = null;
byte[] payload = null;
PaymentCode pcode = null;
if(jsonObject.has("data")) {
JSONObject data = jsonObject.getJSONObject("data");
if(data.has("confirmations") && data.getInt("confirmations") < 1) {
return;
}
if(data.has("inputs")) {
JSONArray inArray = (JSONArray)data.get("inputs");
if(inArray.length() > 0 && ((JSONObject)inArray.get(0)).has("script_hex")) {
String strScript = ((JSONObject)inArray.get(0)).getString("script_hex");
Script script = new Script(Hex.decode(strScript));
// Log.i("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey()));
ECKey pKey = new ECKey(null, script.getPubKey(), true);
// Log.i("APIFactory", "address from script:" + pKey.toAddress(MainNetParams.get()).toString());
// Log.i("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey()));
if(((JSONObject)inArray.get(0)).has("received_from")) {
JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("received_from");
String strHash = received_from.getString("txid");
int idx = received_from.getInt("output_no");
byte[] hashBytes = Hex.decode(strHash);
Sha256Hash txHash = new Sha256Hash(hashBytes);
TransactionOutPoint outPoint = new TransactionOutPoint(MainNetParams.get(), idx, txHash);
byte[] outpoint = outPoint.bitcoinSerialize();
// Log.i("APIFactory", "outpoint:" + Hex.toHexString(outpoint));
try {
mask = BIP47Util.getInstance(context).getIncomingMask(script.getPubKey(), outpoint);
// Log.i("APIFactory", "mask:" + Hex.toHexString(mask));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
if(data.has("outputs")) {
JSONArray outArray = (JSONArray)data.get("outputs");
JSONObject outObj = null;
boolean isIncoming = false;
String _addr = null;
String script = null;
String op_return = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("address")) {
_addr = outObj.getString("address");
if(addr.equals(_addr)) {
isIncoming = true;
}
}
if(outObj.has("script_hex")) {
script = outObj.getString("script_hex");
if(script.startsWith("6a4c50")) {
op_return = script;
}
}
}
if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) {
payload = Hex.decode(op_return.substring(6));
}
}
if(mask != null && payload != null) {
try {
byte[] xlat_payload = PaymentCode.blind(payload, mask);
// Log.i("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload));
pcode = new PaymentCode(xlat_payload);
// Log.i("APIFactory", "incoming payment code:" + pcode.toString());
if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) {
BIP47Meta.getInstance().setLabel(pcode.toString(), "");
BIP47Meta.getInstance().setIncomingStatus(hash);
}
}
catch(AddressFormatException afe) {
afe.printStackTrace();
}
}
}
// get receiving addresses for spends from decoded payment code
if(pcode != null) {
try {
// initial lookup
for(int i = 0; i < 3; i++) {
PaymentAddress receiveAddress = BIP47Util.getInstance(context).getReceiveAddress(pcode, i);
// Log.i("APIFactory", "receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString());
BIP47Meta.getInstance().setIncomingIdx(pcode.toString(), i, receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString());
BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), pcode.toString());
// PaymentAddress sendAddress = BIP47Util.getInstance(context).getSendAddress(pcode, i);
// Log.i("APIFactory", "send to " + i + ":" + sendAddress.getSendECKey().toAddress(MainNetParams.get()).toString());
}
}
catch(Exception e) {
;
}
}
}
}
public synchronized int getNotifTxConfirmations(String hash) {
// Log.i("APIFactory", "Notif tx:" + hash);
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.CHAINSO_TX_PREV_OUT_URL);
url.append(hash);
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
jsonObject = new JSONObject(response);
// Log.i("APIFactory", "Notif tx json:" + jsonObject.toString());
return parseNotifTx(jsonObject);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return 0;
}
public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
if(jsonObject.has("data")) {
JSONObject data = jsonObject.getJSONObject("data");
if(data.has("confirmations")) {
// Log.i("APIFactory", "returning notif tx confirmations:" + data.getInt("confirmations"));
return data.getInt("confirmations");
}
else {
// Log.i("APIFactory", "returning 0 notif tx confirmations");
return 0;
}
}
else if(jsonObject.has("status") && jsonObject.getString("status").equals("fail")) {
return -1;
}
else {
;
}
}
return 0;
}
public synchronized JSONObject getUnspentOutputs(String[] xpubs) {
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString());
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args);
}
parseUnspentOutputs(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseUnspentOutputs(String unspents) {
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return false;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return false;
}
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString();
if(outDict.has("xpub")) {
JSONObject xpubObj = (JSONObject)outDict.get("xpub");
String path = (String)xpubObj.get("path");
String m = (String)xpubObj.get("m");
unspentPaths.put(address, path);
unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m));
}
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxos.containsKey(script)) {
utxos.get(script).getOutpoints().add(outPoint);
}
else {
UTXO utxo = new UTXO();
utxo.getOutpoints().add(outPoint);
utxos.put(script, utxo);
}
}
catch(Exception e) {
;
}
}
return true;
}
catch(JSONException je) {
;
}
}
return false;
}
public synchronized JSONObject getAddressInfo(String addr) {
return getXPUB(new String[] { addr });
}
public synchronized JSONObject getTxInfo(String hash) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("tx/");
url.append(hash);
url.append("?fees=1");
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getBlockHeader(String hash) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("header/");
url.append(hash);
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getDynamicFees() {
JSONObject jsonObject = null;
try {
int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0);
StringBuilder url = new StringBuilder(sel == 0 ? WebUtil._21CO_FEE_URL : WebUtil.BITCOIND_FEE_URL);
// Log.i("APIFactory", "Dynamic fees:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Dynamic fees response:" + response);
try {
jsonObject = new JSONObject(response);
if(sel == 0) {
parseDynamicFees_21(jsonObject);
}
else {
parseDynamicFees_bitcoind(jsonObject);
}
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseDynamicFees_21(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
// 21.co API
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
if(jsonObject.has("fastestFee")) {
long fee = jsonObject.getInt("fastestFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("halfHourFee")) {
long fee = jsonObject.getInt("halfHourFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("hourFee")) {
long fee = jsonObject.getInt("hourFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
// Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString());
}
return true;
}
return false;
}
private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
// bitcoind
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
if(jsonObject.has("2")) {
long fee = jsonObject.getInt("2");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("6")) {
long fee = jsonObject.getInt("6");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("24")) {
long fee = jsonObject.getInt("24");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
// Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString());
}
return true;
}
return false;
}
public synchronized void validateAPIThread() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
if(ConnectivityStatus.hasConnectivity(context)) {
try {
String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK);
JSONObject jsonObject = new JSONObject(response);
if(!jsonObject.has("process")) {
showAlertDialog(context.getString(R.string.api_error), false);
}
}
catch(Exception e) {
showAlertDialog(context.getString(R.string.cannot_reach_api), false);
}
} else {
showAlertDialog(context.getString(R.string.no_internet), false);
}
handler.post(new Runnable() {
@Override
public void run() {
;
}
});
Looper.loop();
}
}).start();
}
private void showAlertDialog(final String message, final boolean forceExit){
if (!((Activity) context).isFinishing()) {
if(alertDialog != null)alertDialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setCancelable(false);
if(!forceExit) {
builder.setPositiveButton(R.string.retry,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
//Retry
validateAPIThread();
}
});
}
builder.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
((Activity) context).finish();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}
public synchronized void initWallet() {
Log.i("APIFactory", "initWallet()");
initWalletAmounts();
}
private synchronized void initWalletAmounts() {
APIFactory.getInstance(context).reset();
List<String> addressStrings = new ArrayList<String>();
String[] s = null;
try {
xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>());
addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false)));
for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) {
for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) {
if(!addressStrings.contains(addr)) {
addressStrings.add(addr);
}
}
}
if(addressStrings.size() > 0) {
s = addressStrings.toArray(new String[0]);
// Log.i("APIFactory", addressStrings.toString());
getUnspentOutputs(s);
}
HD_Wallet hdw = HD_WalletFactory.getInstance(context).get();
if(hdw != null && hdw.getXPUBs() != null) {
String[] all = null;
if(s != null && s.length > 0) {
all = new String[hdw.getXPUBs().length + s.length];
System.arraycopy(hdw.getXPUBs(), 0, all, 0, hdw.getXPUBs().length);
System.arraycopy(s, 0, all, hdw.getXPUBs().length, s.length);
}
else {
all = hdw.getXPUBs();
}
APIFactory.getInstance(context).getXPUB(all);
String[] xs = new String[2];
xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr();
xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr();
getUnspentOutputs(xs);
getDynamicFees();
}
}
catch (IndexOutOfBoundsException ioobe) {
ioobe.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public synchronized int syncBIP47Incoming(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
long amount = 0L;
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("final_balance")) {
amount = addrObj.getLong("final_balance");
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
}
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
// Log.i("APIFactory", "sync receive idx:" + idx + ", " + addr);
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public synchronized int syncBIP47Outgoing(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
int stored = BIP47Meta.getInstance().getOutgoingIdx(pcode);
if(idx >= stored) {
// Log.i("APIFactory", "sync send idx:" + idx + ", " + addr);
BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1);
}
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public long getXpubBalance() {
return xpub_balance;
}
public void setXpubBalance(long value) {
xpub_balance = value;
}
public HashMap<String,Long> getXpubAmounts() {
return xpub_amounts;
}
public HashMap<String,List<Tx>> getXpubTxs() {
return xpub_txs;
}
public HashMap<String, String> getUnspentPaths() {
return unspentPaths;
}
public HashMap<String, Integer> getUnspentAccounts() {
return unspentAccounts;
}
public List<UTXO> getUtxos() {
List<UTXO> unspents = new ArrayList<UTXO>();
unspents.addAll(utxos.values());
return unspents;
}
public void setUtxos(HashMap<String, UTXO> utxos) {
APIFactory.utxos = utxos;
}
public synchronized List<Tx> getAllXpubTxs() {
List<Tx> ret = new ArrayList<Tx>();
for(String key : xpub_txs.keySet()) {
List<Tx> txs = xpub_txs.get(key);
for(Tx tx : txs) {
ret.add(tx);
}
}
Collections.sort(ret, new TxMostRecentDateComparator());
return ret;
}
public synchronized UTXO getUnspentOutputsForSweep(String address) {
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(address);
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString());
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", address);
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args);
}
return parseUnspentOutputsForSweep(response);
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
private synchronized UTXO parseUnspentOutputsForSweep(String unspents) {
UTXO utxo = null;
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return null;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return null;
}
// Log.d("APIFactory", "unspents found:" + outputsRoot.size());
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString();
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxo == null) {
utxo = new UTXO();
}
utxo.getOutpoints().add(outPoint);
}
catch(Exception e) {
;
}
}
}
catch(JSONException je) {
;
}
}
return utxo;
}
public static class TxMostRecentDateComparator implements Comparator<Tx> {
public int compare(Tx t1, Tx t2) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
int ret = 0;
if(t1.getTS() > t2.getTS()) {
ret = BEFORE;
}
else if(t1.getTS() < t2.getTS()) {
ret = AFTER;
}
else {
ret = EQUAL;
}
return ret;
}
}
}
|
package com.tipz.app.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.StrictMode;
import android.util.Log;
import com.tipz.app.BuildConfig;
import com.tipz.app.R;
import com.tipz.app.TipzApplication;
public class LauncherActivity extends Activity {
protected final String TAG = ((Object) this).getClass().getSimpleName();
protected TipzApplication mApp;
@Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.build());
}
super.onCreate(savedInstanceState);
mApp = (TipzApplication) getApplicationContext();
// Update the number of application launches
mApp.getPrefs().applyInt(R.string.pref_app_launch_times,
mApp.getPrefs().getInt(R.string.pref_app_launch_times, 0) + 1);
// Start the main activity
startActivity(new Intent(this, MainActivity.class));
this.finish();
}
}
|
package com.tpb.hn.content;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.androidnetworking.AndroidNetworking;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView;
import com.tpb.hn.Analytics;
import com.tpb.hn.R;
import com.tpb.hn.SettingsActivity;
import com.tpb.hn.data.Formatter;
import com.tpb.hn.data.Item;
import com.tpb.hn.item.FragmentPagerAdapter;
import com.tpb.hn.item.ItemViewActivity;
import com.tpb.hn.network.AdBlocker;
import com.tpb.hn.network.Login;
import com.tpb.hn.storage.SharedPrefsController;
import com.tpb.hn.user.UserViewActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ContentActivity extends AppCompatActivity implements ContentAdapter.ContentManager, Login.LoginListener {
private static final String TAG = ContentActivity.class.getSimpleName();
private Tracker mTracker;
@BindView(R.id.content_toolbar) Toolbar mContentToolbar;
@BindView(R.id.content_appbar) AppBarLayout mAppBar;
@BindView(R.id.nav_spinner) Spinner mNavSpinner;
@BindView(R.id.content_recycler) FastScrollRecyclerView mRecycler;
@BindView(R.id.content_swiper) SwipeRefreshLayout mRefreshSwiper;
@BindView(R.id.content_subtitle) TextView mSubtitle;
private ContentAdapter mAdapter;
public static Item mLaunchItem;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTracker = ((Analytics) getApplication()).getDefaultTracker();
final SharedPrefsController prefs = SharedPrefsController.getInstance(getApplicationContext());
if(prefs.getUseDarkTheme()) {
setTheme(R.style.AppTheme_Dark);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_content);
ButterKnife.bind(this);
AdBlocker.init(getApplicationContext());
AndroidNetworking.initialize(getApplicationContext());
mRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mAdapter = new ContentAdapter(getApplicationContext(), this, mRecycler, (LinearLayoutManager) mRecycler.getLayoutManager(), mRefreshSwiper);
mRecycler.setAdapter(mAdapter);
mNavSpinner.setAdapter(new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.nav_spinner_items)
));
mNavSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mAdapter.loadItems(mNavSpinner.getSelectedItem().toString());
mTracker.send(new HitBuilders.EventBuilder()
.setCategory(Analytics.CATEGORY_NAVIGATION)
.setAction(Analytics.KEY_PAGE + mNavSpinner.getSelectedItem().toString())
.build());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mContentToolbar.setTitle("");
setSupportActionBar(mContentToolbar);
final Handler timeAgoHandler = new Handler();
timeAgoHandler.postDelayed(new Runnable() {
@Override
public void run() {
if(mSubtitle != null) {
mAdapter.getLastUpdate();
timeAgoHandler.postDelayed(this, 1000 * 60);
}
}
}, 1000 * 60);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_content, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
startActivityForResult(new Intent(ContentActivity.this, SettingsActivity.class), 1);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final boolean shouldRestart = data.getBooleanExtra("restart", false);
Log.i(TAG, "onActivityResult: " + shouldRestart);
if(shouldRestart) {
recreate();
}
}
@Override
public void loginResponse(boolean success) {
Log.i(TAG, "loginResponse: Was login successful ? " + success);
}
@Override
public void openItem(Item item) {
final Intent i = new Intent(ContentActivity.this, ItemViewActivity.class);
i.putExtra("item", item);
startActivity(i, getSharedTransition().toBundle());
overridePendingTransition(R.anim.slide_up, R.anim.none);
mAdapter.beginBackgroundLoading();
}
@Override
public void openUser(Item item) {
mLaunchItem = item;
final Intent i = new Intent(ContentActivity.this, UserViewActivity.class);
startActivity(i, getSharedTransition().toBundle());
overridePendingTransition(R.anim.slide_up, R.anim.none);
}
@Override
public void openItem(Item item, FragmentPagerAdapter.PageType type) {
final Intent i = new Intent(ContentActivity.this, ItemViewActivity.class);
mLaunchItem = item;
i.putExtra("type", type);
startActivity(i, getSharedTransition().toBundle());
overridePendingTransition(R.anim.slide_up, R.anim.none);
mAdapter.beginBackgroundLoading();
}
@Override
public void displayLastUpdate(long lastUpdate) {
mSubtitle.setText(String.format(this.getString(R.string.text_last_updated), Formatter.shortTimeAgo(lastUpdate)));
}
private ActivityOptionsCompat getSharedTransition() {
return ActivityOptionsCompat.makeSceneTransitionAnimation(this,
Pair.create((View) mNavSpinner, "button"),
Pair.create((View) mAppBar, "appbar"));
}
@Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(TAG);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
mAdapter.cancelBackgroundLoading();
mAdapter.getLastUpdate();
}
}
|
package io.scrollback.app;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.i("GCM Error", "Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.i("GCM Error", "Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.d("gcm_payload", extras.toString());
Log.d("gcm_title", extras.getString("title", "default title"));
Log.d("gcm_subtitle", extras.getString("subtitle", "default message"));
Log.d("gcm_path", extras.getString("path", "default message"));
Notification notif = new Notification();
notif.setTitle(extras.getString("title", "default"));
notif.setMessage(extras.getString("subtitle", "default message"));
notif.setPath("/"+extras.getString("path", "me"));
// Post notification of received message if application isn't open
if(!Scrollback.appOpen)
sendNotification(notif);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(Notification n) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent i = new Intent(this, MainActivity.class);
i.putExtra("scrollback_path", n.getPath());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(n.getTitle())
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(n.getMessage()))
.setContentText(n.getMessage())
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
|
package io.videtur.ignis.ui;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.ResultCodes;
import com.google.android.gms.common.SignInButton;
import java.util.Collections;
import java.util.List;
import io.videtur.ignis.R;
import static io.videtur.ignis.core.Constants.REQUEST_SIGN_IN;
/**
* Provides a simple interface for Google authentication through Firebase.
*/
public class SignInActivity extends AppCompatActivity {
private static final String TAG = "SignInActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SignInButton googleSignInButton = (SignInButton) findViewById(R.id.google_sign_in_button);
googleSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startGoogleSignIn();
}
});
}
private void startGoogleSignIn() {
// Build and start FirebaseUI authentication flow
List<AuthUI.IdpConfig> providers = Collections.singletonList(
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(providers)
.setIsSmartLockEnabled(false)
.build(),
REQUEST_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Only handle results from FirebaseUI authentication
if (requestCode == REQUEST_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == ResultCodes.OK) {
// Authentication successful, launch MainActivity
startActivity(new Intent(this, MainActivity.class));
finish();
} else {
// Authentication failed, show error in toast
if (response != null) {
Log.d(TAG, "errorCode:" + response.getErrorCode());
if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
showToast(R.string.sign_in_no_network);
} else {
showToast(R.string.sign_in_unknown_error);
}
}
}
}
}
private void showToast(int stringResource) {
Toast.makeText(this, stringResource, Toast.LENGTH_SHORT).show();
}
}
|
package me.jaxbot.wear.leafstatus;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.URLEncoder;
public class Carwings {
static String TAG = "Carwings";
public static String[] PortalURL = {
"https://owners.nissanusa.com/nowners/", // US
"https://carwings.mynissan.ca/", // CA
"http:
};
private String username;
private String password;
private String vin;
public int currentBattery;
public String range;
public String chargeTime;
public boolean currentHvac;
public String lastUpdateTime;
public String chargerType;
public boolean charging;
public boolean autoUpdate;
public boolean showPermanent;
public boolean useMetric;
public boolean noNightUpdates;
public boolean notifyOnlyWhenCharging;
public boolean alwaysShowStartHVAC;
// Endpoint url for this instance
String url;
SharedPreferences settings;
// Disgusting, but we're using the web frontend, and thus will pretend
String UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
public Carwings(Context context)
{
settings = context.getSharedPreferences("U", 0);
this.username = settings.getString("username", "");
this.password = settings.getString("password", "");
this.vin = settings.getString("vin", "");
this.currentBattery = settings.getInt("currentBattery", 0);
this.chargeTime = settings.getString("chargeTime", "");
this.range = settings.getString("range", "");
this.lastUpdateTime = settings.getString("lastupdate", "");
this.url = "https://gdcportalgw.its-mo.com/orchestration_1021/gdc/";
this.chargerType = settings.getString("chargerType", "L1");
this.charging = settings.getBoolean("charging", false);
this.autoUpdate = settings.getBoolean("autoupdate", true);
this.showPermanent = settings.getBoolean("showPermanent", false);
this.useMetric = settings.getBoolean("useMetric", false);
this.noNightUpdates = settings.getBoolean("noNightUpdates", true);
this.notifyOnlyWhenCharging = settings.getBoolean("notifyOnlyWhenCharging", false);
this.alwaysShowStartHVAC = settings.getBoolean("alwaysShowStartHVAC", false);
Configuration.init(context);
}
private CookieStore login() {
DefaultHttpClient httpclient = new DefaultHttpClient();
if (username.equals("")) return null;
try {
String result = getHTTPString(url + "/UserLoginRequest.php?UserId=" + URLEncoder.encode(username, "utf-8") + "&cartype=&tz=&lg=en-US&DCMID=&VIN=&RegionCode=NNA&Password=" + URLEncoder.encode(password, "utf-8"));
JSONObject jObject = new JSONObject(result);
String vin = jObject.getJSONObject("CustomerInfo").getJSONObject("VehicleInfo").getString("VIN");
System.out.println("Your VIN is " + vin);
SharedPreferences.Editor editor = settings.edit();
editor.putString("vin", vin);
editor.commit();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return null;
}
public boolean trylogin() {
return !getCarId(login()).equals("");
}
private String getCarId(CookieStore jar) {
// Check if we have already grabbed this
String cachedCarID = settings.getString("vin", "");
if (!cachedCarID.equals(""))
return cachedCarID;
// This is a particularly bad and non-future-safe operation,
// but so is the entire application, since Nissan's API is internal
String vehicleHTML = getHTTPString(url + "user/home");
System.out.println(vehicleHTML);
Pattern pattern = Pattern.compile("(.*)var vinId = \"([a-zA-Z0-9]+)\"(.*)");
Matcher m = pattern.matcher(vehicleHTML);
if (m.matches()) {
cachedCarID = m.group(2);
// Save it, since it is unlikely to change
SharedPreferences.Editor editor = settings.edit();
editor.putString("vin", cachedCarID);
editor.commit();
return cachedCarID;
} else {
Log.e(TAG, "Failed to find vehicle id");
return "";
}
}
public boolean update() {
try {
String encodedUsername = "";
try {
encodedUsername = URLEncoder.encode(username, "utf-8");
} catch (Exception e) {
}
String request = getHTTPString(url + "BatteryStatusCheckRequest.php?UserId=" + encodedUsername + "&cartype=&VIN=" + vin + "&RegionCode=NNA&tz=America%2FNew_York&lg=en-US");
JSONObject requestResults = new JSONObject(request);
final String resultKey = requestResults.getString("resultKey");
final Timer poller = new Timer();
final String finalEncodedUsername = encodedUsername;
poller.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("checking bat status");
try {
String request = getHTTPString(url + "BatteryStatusCheckResultRequest.php?UserId=" + URLEncoder.encode(username, "utf-8") + "&cartype=&resultKey=" + resultKey + "&tz=America%2FNew_York&lg=en-US&VIN=" + vin + "&RegionCode=NNA");
JSONObject requestResults = new JSONObject(request);
if (requestResults.has("chargeMode")) {
poller.cancel();
System.out.println("We got the data we need. It is: " + request);
String recordsRequest = getHTTPString(url + "BatteryStatusRecordsRequest.php?UserId=" + finalEncodedUsername + "&cartype=&tz=America%2FNew_York&lg=en-US&VIN=" + vin + "&RegionCode=NNA");
System.out.println("records: " + recordsRequest);
JSONObject records = new JSONObject(recordsRequest).getJSONObject("BatteryStatusRecords");
currentBattery = records.getJSONObject("BatteryStatus").getInt("BatteryRemainingAmount");
String l1Time = "null";
String l2Time = "null";
String l3Time = "null";
try {
l1Time = records.getJSONObject("TimeRequiredToFull").getString("HourRequiredToFull");
} catch (Exception e) {}
try {
l2Time = records.getJSONObject("TimeRequiredToFull200").getString("HourRequiredToFull");
} catch (Exception e) {}
try {
l3Time = records.getJSONObject("TimeRequiredToFull200_6kW").getString("HourRequiredToFull");
} catch (Exception e) {}
chargeTime = l1Time;
chargerType = "L1";
int defaultCharger = settings.getInt("defaultChargeLevel", 0);
Log.d(TAG, "def: " + defaultCharger);
if (chargeTime.equals("null") || (!l2Time.equals("null") && defaultCharger == 1)) {
chargeTime = l2Time;
chargerType = "L2";
}
if (chargeTime.equals("null") || (!l3Time.equals("null") && defaultCharger == 2)) {
chargeTime = l3Time;
chargerType = "L2+";
}
if (chargeTime.equals("null")) {
chargeTime = "Unknown";
chargerType = "?";
}
charging = !requestResults.getString("chargeMode").equals("NOT_CHARGING");
int range_km = (int)Float.parseFloat(records.getString("CruisingRangeAcOff")) / 1000;
System.out.println("rangekm: " + range_km);
if (useMetric)
range = Math.round(range_km) + " km";
else
range = Math.round(range_km * 0.621371) + " mi";
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
lastUpdateTime = today.format("%Y-%m-%d %H:%M:%S");
SharedPreferences.Editor editor = settings.edit();
editor.putString("range", range);
editor.putString("chargeTime", chargeTime);
editor.putBoolean("charging", charging);
editor.putString("chargerType", chargerType);
editor.putString("lastupdate", lastUpdateTime);
editor.putInt("currentBattery", currentBattery);
editor.commit();
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}, 0, 10000);
return true;
} catch (Exception e) {
System.out.println("Failure!!!");
System.out.println(e);
}
return false;
}
public boolean startAC(boolean desired) {
String endpoint = desired ? "ACRemoteRequest" : "ACRemoteOffRequest";
try {
String output = getHTTPString(url + endpoint + ".php?UserId=" + URLEncoder.encode(this.username, "utf-8") + "&cartype=&VIN=" + this.vin + "&RegionCode=NNA&tz=America%2FNew_York&lg=en-US");
if (!output.contains("success")) {
Log.e(TAG, "Start AC failed. Output: " + output);
return false;
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return true;
}
private String getHTTPString(String url) {
System.out.println("Starting GET " + url);
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.setHeader("User-Agent", UA);
HttpResponse response = httpclient.execute(httpget);
InputStream inputStream = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
System.out.println("Done GET " + url);
return result;
} catch (Exception e) {
System.out.println(e);
}
return "";
}
}
|
package net.squanchy.search;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import net.squanchy.R;
import net.squanchy.fonts.TypefaceStyleableActivity;
import net.squanchy.navigation.Navigator;
import net.squanchy.schedule.domain.view.Event;
import net.squanchy.search.view.SearchRecyclerView;
import net.squanchy.speaker.domain.view.Speaker;
import io.reactivex.BackpressureStrategy;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import timber.log.Timber;
public class SearchActivity extends TypefaceStyleableActivity implements SearchRecyclerView.OnSearchResultClickListener {
private static final int SPEECH_REQUEST_CODE = 100;
private static final int QUERY_DEBOUNCE_TIMEOUT = 250;
private static final int DELAY_ENOUGH_FOR_FOCUS_TO_HAPPEN_MILLIS = 50;
private static final int MIN_QUERY_LENGTH = 2;
private final CompositeDisposable subscriptions = new CompositeDisposable();
private Navigator navigator;
private SearchTextWatcher searchTextWatcher;
private EditText searchField;
private SearchService searchService;
private SearchRecyclerView searchRecyclerView;
private boolean hasQuery;
private View emptyView;
private TextView emptyViewMessage;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
searchField = (EditText) findViewById(R.id.search_field);
emptyView = findViewById(R.id.empty_view);
emptyViewMessage = (TextView) findViewById(R.id.empty_view_message);
searchRecyclerView = (SearchRecyclerView) findViewById(R.id.speakers_view);
setupToolbar();
SearchComponent component = SearchInjector.obtain(this);
searchService = component.service();
navigator = component.navigator();
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.search_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onStart() {
super.onStart();
PublishSubject<String> querySubject = PublishSubject.create();
searchTextWatcher = new SearchTextWatcher(querySubject);
searchField.addTextChangedListener(searchTextWatcher);
Disposable speakersSubscription = searchService.speakers()
.map(speakers -> SearchResults.create(Collections.emptyList(), speakers))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(searchResults -> searchRecyclerView.updateWith(searchResults, this), Timber::e);
Disposable searchSubscription = querySubject.throttleLast(QUERY_DEBOUNCE_TIMEOUT, TimeUnit.MILLISECONDS)
.doOnNext(this::updateSearchActionIcon)
.flatMap(searchService::find)
.doOnNext(searchResults -> speakersSubscription.dispose())
.toFlowable(BackpressureStrategy.LATEST)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onReceivedSearchResults, Timber::e);
subscriptions.add(speakersSubscription);
subscriptions.add(searchSubscription);
searchField.requestFocus();
searchField.postDelayed(() -> requestShowKeyboard(searchField), DELAY_ENOUGH_FOR_FOCUS_TO_HAPPEN_MILLIS);
}
private void requestShowKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0, new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
}
});
}
private void updateSearchActionIcon(String query) {
hasQuery = !TextUtils.isEmpty(query);
supportInvalidateOptionsMenu();
}
private void onReceivedSearchResults(SearchResults searchResults) {
if (searchResults.isEmpty()) {
searchRecyclerView.setVisibility(View.INVISIBLE);
emptyView.setVisibility(View.VISIBLE);
CharSequence query = searchField.getText();
updateEmptyStateMessageFor(query);
} else {
emptyView.setVisibility(View.INVISIBLE);
searchRecyclerView.setVisibility(View.VISIBLE);
searchRecyclerView.updateWith(searchResults, this);
}
}
private void updateEmptyStateMessageFor(CharSequence query) {
if (query == null || query.length() < MIN_QUERY_LENGTH) {
emptyViewMessage.setText(R.string.start_typing_to_search);
} else {
emptyViewMessage.setText(R.string.no_results);
}
}
@Override
protected void onStop() {
super.onStop();
subscriptions.dispose();
if (searchTextWatcher != null) {
searchField.removeTextChangedListener(searchTextWatcher);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem voiceSearchItem = menu.findItem(R.id.action_voice_search);
voiceSearchItem.setVisible(!hasQuery);
MenuItem clearQueryItem = menu.findItem(R.id.action_clear_query);
clearQueryItem.setVisible(hasQuery);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_voice_search) {
onVoiceSearchClicked();
return true;
} else if (item.getItemId() == R.id.action_clear_query) {
clearSearchQuery();
return true;
} else if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onVoiceSearchClicked() {
Intent voiceSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceSearchIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
voiceSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
try {
startActivityForResult(voiceSearchIntent, SPEECH_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
Timber.e(e);
}
}
private void clearSearchQuery() {
searchField.setText("");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
searchField.setText(results.get(0));
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onSpeakerClicked(Speaker speaker) {
navigate().toSpeakerDetails(speaker.id());
}
@Override
public void onEventClicked(Event event) {
navigate().toEventDetails(event.id());
}
private Navigator navigate() {
return navigator;
}
private static class SearchTextWatcher implements TextWatcher {
private final PublishSubject<String> querySubject;
SearchTextWatcher(PublishSubject<String> querySubject) {
this.querySubject = querySubject;
}
@Override
public void beforeTextChanged(CharSequence query, int start, int count, int after) {
// No-op
}
@Override
public void onTextChanged(CharSequence query, int start, int before, int count) {
if (query == null) {
return;
}
querySubject.onNext(query.toString());
}
@Override
public void afterTextChanged(Editable query) {
// No-op
}
}
}
|
package org.stepic.droid.util;
public class AppConstants {
public static final String USER_LOG_IN = "user_login_clicked";
public static final String KEY_COURSE_BUNDLE = "course";
public static final String KEY_SECTION_BUNDLE = "section";
public static final String KEY_UNIT_BUNDLE = "unit";
public static final String KEY_LESSON_BUNDLE = "lesson";
public static final String KEY_STEP_BUNDLE = "step";
public static final String DEFAULT_QUALITY = "360";
public static final String PRE_BODY = "<html>\n" +
"<head>\n" +
"<title>Step. Stepic.org</title>\n" +
"<script type=\"text/x-mathjax-config\">\n" +
" MathJax.Hub.Config({" +
"messageStyle: \"none\", " +
"tex2jax: {preview: \"none\", inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});\n" +
"</script>\n" +
"<script type=\"text/javascript\"\n" +
" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n" +
"</script>\n" +
"<style>\n" +
"\nimg { max-width: 100%; }" +
"</style>\n" +
"</head>\n" +
"<body>";
public static final String POST_BODY = "</body>\n" +
"</html>";
public static final String KEY_LOAD_TYPE = "KEY_LOAD_TYPE";
public static final String KEY_TABLE_TYPE = "table_type";
//Types of steps:
public static final String TYPE_TEXT = "text";
public static final String TYPE_VIDEO = "video";
public static final String TYPE_MATCHING = "matching";
public static final String TYPE_SORTING = "sorting";
public static final String TYPE_MATH = "math";
public static final String TYPE_FREE_ANSWER = "free-answer";
public static final String TYPE_TABLE = "table";
public static final String TYPE_STRING = "string";
public static final String TYPE_CHOICE = "choice";
public static final String TYPE_NUMBER = "number";
public static final String TYPE_DATASET = "dataset";
public static final String TYPE_ANIMATION = "animation";
public static final String TYPE_CHEMICAL = "chemical";
public static final String TYPE_FILL_BLANKS = "fill-blanks";
public static final String TYPE_PUZZLE = "puzzle";
public static final String TYPE_PYCHARM = "pycharm";
public static final String TYPE_CODE = "code";
//App Metrica:
public static final String METRICA_CLICK_SIGN_IN = "click sign in on launch screen";
public static final String METRICA_CLICK_SIGN_UP = "click sign up";
public static final String METRICA_CLICK_SIGN_IN_ON_SIGN_IN_SCREEN = "click sign in on sign in on sign-in screen";
public static final String METRICA_FAIL_LOGIN = "fail login";
public static final String METRICA_SUCCESS_LOGIN = "success login";
public static final String METRICA_DROP_COURSE = "drop course";
public static final String METRICA_LOAD_SERVICE = "Load Service";
public static final String METRICA_REFRESH_COURSE = "Pull from top to refresh course";
public static final String METRICA_REFRESH_SECTION = "Pull from top to refresh section";
public static final String METRICA_REFRESH_UNIT = "Pull from top to refresh section unit";
public static final String METRICA_LONG_TAP_COURSE = "Long tap on course";
public static final java.lang.String SHOW_DETAILED_INFO_CLICK = "Show detailed info click from context menu of course";
public static final java.lang.String METRICA_CLICK_DELETE_SECTION = "Click delete section from cache";
public static final java.lang.String METRICA_CLICK_CACHE_SECTION = "Click cache section";
public static final java.lang.String METRICA_CLICK_CACHE_UNIT = "Click cache unit";
public static final java.lang.String METRICA_CLICK_DELETE_UNIT = "Click delete unit from cache";
public static final java.lang.String METRICA_CLICK_LOGOUT = "Click logout";
public static final java.lang.String METRICA_CLICK_CLEAR_CACHE = "Click clear cache button";
public static final java.lang.String METRICA_CLICK_YES_CLEAR_CACHE = "Click Accept clear cache";
public static final java.lang.String METRICA_CLICK_YES_LOGOUT = "Click accept logout";
public static final int REQUEST_WIFI = 1;
public static final int REQUEST_EXTERNAL_STORAGE = 13;
public static final java.lang.String METRICA_CANCEL_VIDEO_QUALITY = "Cancel video quality dialog";
public static final String NULL_SHOW_PROFILE = "Null profile is tried to show";
public static final String IMAGE_ON_DISK = "Image on disk";
public static final String METRICA_GET_PROGRESSES = "Get progresses";
public static final String METRICA_GET_ASSIGNMENTS = "Get assignments";
public static final String KEY_ASSIGNMENT_BUNDLE = "key_assignment";
public static final String COURSE_ID_KEY = "course_id";
public static final String ENROLLMENT_KEY = "is_enrolled";
public static final int REQUEST_CODE_DETAIL = 1;
public static final java.lang.String METRICA_YES_CLEAR_VIDEOS = "clear videos from downloads";
public static final String NULL_SECTION = "Null section is not expected";
public static final String NULL_COURSE = "Null course is not expected";
public static final String NOT_VALID_ACCESS_AND_REFRESH = "Not valid access, why?";
public static final String NOT_FOUND_VERSION = "Not found version of app";
public static final String NOT_SIGNIFICANT_ERROR = "Not significant error, app will continue to work";
public static final java.lang.String GET_OLD_ATTEMPT = "get attempt from server db, new is not creating";
public static final java.lang.String SAVE_SESSION_FAIL = "save session was failed because of null attempt or submission";
public static final java.lang.String SEARCH = "search courses";
public static final java.lang.String METRICA_LESSON_IN_STORE_STATE_NULL = "lesson was null in store state manager";
public static final java.lang.String METRICA_UNIT_IN_STORE_STATE_NULL = "unit was null in store state manager";
public static final java.lang.String THUMBNAIL_POSTFIX_EXTENSION= ".png";
public static final java.lang.String DELIMITER_TEXT_SCORE= "/";
}
|
package org.odk.collect.android.tasks;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.util.Pair;
import android.util.Log;
import org.commcare.android.crypt.EncryptionIO;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.logic.GlobalConstants;
import org.commcare.android.tasks.ExceptionReporting;
import org.commcare.android.tasks.templates.CommCareTask;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.odk.provider.FormsProviderAPI;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.instance.InstanceInitializationFactory;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.services.Logger;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.xform.parse.XFormParseException;
import org.javarosa.xform.parse.XFormParser;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.jr.extensions.CalendaredDateFormatHandler;
import org.odk.collect.android.jr.extensions.IntentExtensionParser;
import org.odk.collect.android.jr.extensions.PollSensorExtensionParser;
import org.odk.collect.android.jr.extensions.XFormExtensionUtils;
import org.odk.collect.android.logic.FileReferenceFactory;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.utilities.ApkUtils;
import org.odk.collect.android.utilities.FileUtils;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.spec.SecretKeySpec;
/**
* Background task for loading a form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public abstract class FormLoaderTask<R> extends CommCareTask<Uri, String, FormLoaderTask.FECWrapper, R> {
public static InstanceInitializationFactory iif;
private final SecretKeySpec mSymetricKey;
private final boolean mReadOnly;
private final R activity;
private FECWrapper data;
public static final int FORM_LOADER_TASK_ID = 16;
public FormLoaderTask(SecretKeySpec symetricKey, boolean readOnly, R activity) {
this.mSymetricKey = symetricKey;
this.mReadOnly = readOnly;
this.activity = activity;
this.taskId = FORM_LOADER_TASK_ID;
TAG = FormLoaderTask.class.getSimpleName();
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected FECWrapper doTaskBackground(Uri... form) {
FormDef fd = null;
Pair<String, String> formAndMediaPaths = getFormAndMediaPaths(form[0]);
String formPath = formAndMediaPaths.first;
String formMediaPath = formAndMediaPaths.second;
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = getCachedForm(formHash);
if (formBin.exists()) {
// if we have binary, deserialize binary
Log.i(TAG, "Attempting to load " + formXml.getName() +
" from cached file: " + formBin.getAbsolutePath());
fd = deserializeFormDef((Context)activity, formBin);
if (fd == null) {
Logger.log(AndroidLogger.SOFT_ASSERT,
"Deserialization of " + formXml.getName() + " form failed.");
// Remove the file, and make a new .formdef from xml
formBin.delete();
}
}
// If we couldn't find a cached version, load the form from the XML
if (fd == null) {
fd = loadFormFromFile(formXml);
}
// Try to write the form definition to a cached location
try {
serializeFormDef(fd, formPath);
} catch (Exception e) {
// The cache is a bonus, so if we can't write it, don't crash, but log
// it so we can clean up whatever is preventing the cached version from
// working
Logger.log(AndroidLogger.TYPE_RESOURCES, "XForm could not be serialized. Error trace:\n" + ExceptionReporting.getStackTrace(e));
}
FormEntryController fec = initFormDef(fd);
// Remove previous forms
ReferenceManager._().clearSession();
setupFormMedia(formMediaPath, formXml);
FormController fc = new FormController(fec, mReadOnly);
data = new FECWrapper(fc);
return data;
}
private Pair<String, String> getFormAndMediaPaths(Uri formUri) {
Cursor c = null;
try {
//TODO: Selection=? helper
c = ((Context)activity).getContentResolver().query(formUri, new String[]{FormsProviderAPI.FormsColumns.FORM_FILE_PATH, FormsProviderAPI.FormsColumns.FORM_MEDIA_PATH}, null, null, null);
if (c == null || !c.moveToFirst()) {
throw new IllegalArgumentException("Invalid Form URI Provided! No form content found at URI: " + formUri.toString());
}
return new Pair<>(c.getString(c.getColumnIndex(FormsProviderAPI.FormsColumns.FORM_FILE_PATH)),
c.getString(c.getColumnIndex(FormsProviderAPI.FormsColumns.FORM_MEDIA_PATH)));
} finally {
if (c != null) {
c.close();
}
}
}
private FormDef loadFormFromFile(File formXml) {
FileInputStream fis;
// no binary, read from xml
Log.i(TAG, "Attempting to load from: " + formXml.getAbsolutePath());
try {
fis = new FileInputStream(formXml);
} catch (FileNotFoundException e) {
throw new RuntimeException("Error reading XForm file");
}
XFormParser.registerHandler("intent", new IntentExtensionParser());
XFormParser.registerStructuredAction("pollsensor", new PollSensorExtensionParser());
FormDef fd = XFormExtensionUtils.getFormFromInputStream(fis);
if (fd == null) {
throw new RuntimeException("Error reading XForm file");
}
return fd;
}
private FormEntryController initFormDef(FormDef fd) {
fd.exprEvalContext.addFunctionHandler(new CalendaredDateFormatHandler((Context)activity));
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
FormEntryController fec = new FormEntryController(fem);
//TODO: Get a reasonable IIF object
// import existing data into formdef
if (FormEntryActivity.mInstancePath != null) {
// This order is important. Import data, then initialize.
importData(FormEntryActivity.mInstancePath, fec);
fd.initialize(false, iif);
} else {
fd.initialize(true, iif);
}
if (mReadOnly) {
fd.getInstance().getRoot().setEnabled(false);
}
return fec;
}
private void setupFormMedia(String formMediaPath, File formXmlFile) {
if (formMediaPath != null) {
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://images/", formMediaPath));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://audio/", formMediaPath));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://video/", formMediaPath));
} else {
// This should get moved to the Application Class
if (ReferenceManager._().getFactories().length == 0) {
// this is /sdcard/odk
ReferenceManager._().addReferenceFactory(
new FileReferenceFactory(Environment.getExternalStorageDirectory() + "/odk"));
}
// set paths to /sdcard/odk/forms/formfilename-media/
String formFileName = formXmlFile.getName().substring(0, formXmlFile.getName().lastIndexOf("."));
// Set jr://... to point to /sdcard/odk/forms/filename-media/
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));
}
}
private boolean importData(String filePath, FormEntryController fec) {
// convert files into a byte array
InputStream is;
try {
is = EncryptionIO.getFileInputStream(filePath, mSymetricKey);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to open encrypted form instance file: " + filePath);
}
// get the root of the saved and template instances
TreeElement savedRoot;
try {
savedRoot = XFormParser.restoreDataModel(is, null).getRoot();
} catch (IOException e) {
e.printStackTrace();
throw new XFormParseException("Bad parsing from byte array " + e.getMessage());
}
TreeElement templateRoot = fec.getModel().getForm().getInstance().getRoot().deepCopy(true);
// weak check for matching forms
if (!savedRoot.getName().equals(templateRoot.getName()) || savedRoot.getMult() != 0) {
Log.e(TAG, "Saved form instance does not match template form definition");
return false;
} else {
// populate the data model
TreeReference tr = TreeReference.rootRef();
tr.add(templateRoot.getName(), TreeReference.INDEX_UNBOUND);
templateRoot.populate(savedRoot);
// populated model to current form
fec.getModel().getForm().getInstance().setRoot(templateRoot);
// fix any language issues
if (fec.getModel().getLanguages() != null) {
fec.getModel()
.getForm()
.localeChanged(fec.getModel().getLanguage(),
fec.getModel().getForm().getLocalizer());
}
return true;
}
}
/**
* Read serialized {@link FormDef} from file and recreate as object.
*
* @param formDef serialized FormDef file
* @return {@link FormDef} object
*/
private static FormDef deserializeFormDef(Context context, File formDef) {
FileInputStream fis;
FormDef fd;
try {
// create new form def
fd = new FormDef();
fis = new FileInputStream(formDef);
DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));
// read serialized formdef into new formdef
fd.readExternal(dis, ApkUtils.getPrototypeFactory(context));
dis.close();
} catch (Throwable e) {
e.printStackTrace();
fd = null;
}
return fd;
}
/**
* Write the FormDef to the file system as a binary blob.
*
* @param filepath path to the form file
* @throws IOException
*/
@SuppressWarnings("resource")
public void serializeFormDef(FormDef fd, String filepath) throws IOException {
// calculate unique md5 identifier for this form
String hash = FileUtils.getMd5Hash(new File(filepath));
File formDef = getCachedForm(hash);
// create a serialized form file if there isn't already one at this hash
if (!formDef.exists()) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(formDef);
DataOutputStream dos;
outputStream = dos = new DataOutputStream(outputStream);
fd.writeExternal(dos);
dos.flush();
} finally {
//make sure we clean up the stream
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// Swallow this. If we threw an exception from inside the
// try, this close exception will trump it on the return
// path, and we care a lot more about that exception
// than this one.
}
}
}
}
}
private File getCachedForm(String hash) {
return new File(CommCareApplication._().getCurrentApp().
fsPath(GlobalConstants.FILE_CC_CACHE) + "/" + hash + ".formdef");
}
public void destroy() {
if (data != null) {
data.free();
data = null;
}
}
protected static class FECWrapper {
FormController controller;
protected FECWrapper(FormController controller) {
this.controller = controller;
}
public FormController getController() {
return controller;
}
protected void free() {
controller = null;
}
}
}
|
package com.google.payments;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaWebView;
import com.google.payments.IabHelper.OnConsumeFinishedListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class InAppBillingV3 extends CordovaPlugin {
protected static final String TAG = "google.payments";
public static final int OK = 0;
public static final int INVALID_ARGUMENTS = -1;
public static final int UNABLE_TO_INITIALIZE = -2;
public static final int BILLING_NOT_INITIALIZED = -3;
public static final int UNKNOWN_ERROR = -4;
public static final int USER_CANCELLED = -5;
public static final int BAD_RESPONSE_FROM_SERVER = -6;
public static final int VERIFICATION_FAILED = -7;
public static final int ITEM_UNAVAILABLE = -8;
public static final int ITEM_ALREADY_OWNED = -9;
public static final int ITEM_NOT_OWNED = -10;
public static final int CONSUME_FAILED = -11;
private IabHelper iabHelper = null;
boolean billingInitialized = false;
AtomicInteger orderSerial = new AtomicInteger(0);
private HashMap<String, Purchase> purchaseMap = new HashMap<String, Purchase>();
private JSONObject manifestObject = null;
private JSONObject getManifestContents() {
if (manifestObject != null) return manifestObject;
Context context = this.cordova.getActivity();
InputStream is;
try {
is = context.getAssets().open("www/manifest.json");
Scanner s = new Scanner(is).useDelimiter("\\A");
String manifestString = s.hasNext() ? s.next() : "";
manifestObject = new JSONObject(manifestString);
} catch (IOException e) {
Log.d(TAG, "Unable to read manifest file:" + e.toString());
manifestObject = null;
} catch (JSONException e) {
Log.d(TAG, "Unable to parse manifest file:" + e.toString());
manifestObject = null;
}
return manifestObject;
}
protected String getBase64EncodedPublicKey() {
JSONObject manifestObject = getManifestContents();
if (manifestObject != null) {
return manifestObject.optString("play_store_key");
}
return null;
}
protected boolean shouldSkipPurchaseVerification() {
JSONObject manifestObject = getManifestContents();
if (manifestObject != null) {
return manifestObject.optBoolean("skip_purchase_verification");
}
return false;
}
protected boolean initializeBillingHelper() {
if (iabHelper != null) {
Log.d(TAG, "Billing already initialized");
return true;
}
Context context = this.cordova.getActivity();
String base64EncodedPublicKey = getBase64EncodedPublicKey();
boolean skipPurchaseVerification = shouldSkipPurchaseVerification();
if (base64EncodedPublicKey != null) {
iabHelper = new IabHelper(context, base64EncodedPublicKey);
iabHelper.setSkipPurchaseVerification(skipPurchaseVerification);
billingInitialized = false;
return true;
}
Log.d(TAG, "Unable to initialize billing");
return false;
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
initializeBillingHelper();
}
protected JSONObject makeError(String message) {
return makeError(message, null, null, null);
}
protected JSONObject makeError(String message, Integer resultCode) {
return makeError(message, resultCode, null, null);
}
protected JSONObject makeError(String message, Integer resultCode, IabResult result) {
return makeError(message, resultCode, result.getMessage(), result.getResponse());
}
protected JSONObject makeError(String message, Integer resultCode, String text, Integer response) {
if (message != null) {
Log.d(TAG, "Error: " + message);
}
JSONObject error = new JSONObject();
try {
if (resultCode != null) {
error.put("code", (int)resultCode);
}
if (message != null) {
error.put("message", message);
}
if (text != null) {
error.put("text", text);
}
if (response != null) {
error.put("response", response);
}
} catch (JSONException e) {}
return error;
}
@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) {
if ("init".equals(action)) {
return init(args, callbackContext);
} else if ("buy".equals(action)) {
return buy(args, callbackContext);
} else if ("consumePurchase".equals(action)) {
return consumePurchase(args, callbackContext);
} else if ("getSkuDetails".equals(action)) {
return getSkuDetails(args, callbackContext);
}
return false;
}
protected boolean init(final JSONArray args, final CallbackContext callbackContext) {
if (billingInitialized == true) {
Log.d(TAG, "Billing already initialized");
callbackContext.success();
}
if (iabHelper == null) {
callbackContext.error(makeError("Billing cannot be initialized", UNABLE_TO_INITIALIZE));
}
iabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
callbackContext.error(makeError("Unable to initialize billing: " + result.toString(), UNABLE_TO_INITIALIZE, result));
} else {
Log.d(TAG, "Billing initialized");
billingInitialized = true;
callbackContext.success();
}
}
});
return true;
}
protected boolean buy(final JSONArray args, final CallbackContext callbackContext) {
final String sku;
try {
sku = args.getString(0);
} catch (JSONException e) {
callbackContext.error(makeError("Invalid SKU", INVALID_ARGUMENTS));
return false;
}
if (iabHelper == null || !billingInitialized) {
callbackContext.error(makeError("Billing is not initialized", BILLING_NOT_INITIALIZED));
return false;
}
final Activity cordovaActivity = this.cordova.getActivity();
int newOrder = orderSerial.getAndIncrement();
this.cordova.setActivityResultCallback(this);
iabHelper.launchPurchaseFlow(cordovaActivity, sku, newOrder,
new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// TODO: Add way more info to this
int response = result.getResponse();
if (response == IabHelper.IABHELPER_BAD_RESPONSE || response == IabHelper.IABHELPER_UNKNOWN_ERROR) {
callbackContext.error(makeError("Could not complete purchase", BAD_RESPONSE_FROM_SERVER, result));
}
if (response == IabHelper.IABHELPER_VERIFICATION_FAILED) {
callbackContext.error(makeError("Could not complete purchase", BAD_RESPONSE_FROM_SERVER, result));
}
if (response == IabHelper.IABHELPER_USER_CANCELLED) {
callbackContext.error(makeError("Purchase Cancelled", USER_CANCELLED, result));
}
callbackContext.error(makeError("Error completing purchase", UNKNOWN_ERROR, result));
} else {
purchaseMap.put(purchase.getToken(), purchase);
try {
JSONObject pluginResponse = new JSONObject();
pluginResponse.put("orderId", purchase.getOrderId());
pluginResponse.put("productId", purchase.getSku());
pluginResponse.put("purchaseToken", purchase.getToken());
callbackContext.success(pluginResponse);
} catch (JSONException e) {
callbackContext.error("Purchase succeeded but success handler failed");
}
}
}
}, "");
return true;
}
protected Purchase getPurchase(String purchaseToken) {
return purchaseMap.get(purchaseToken);
}
protected boolean consumePurchase(final JSONArray args, final CallbackContext callbackContext) {
final Purchase purchase;
try {
String purchaseToken = args.getString(0);
purchase = getPurchase(purchaseToken);
} catch (JSONException e) {
callbackContext.error(makeError("Unable to parse purchase token", INVALID_ARGUMENTS));
return false;
}
if (purchase == null) {
callbackContext.error(makeError("Unrecognized purchase token", INVALID_ARGUMENTS));
return false;
}
if (iabHelper == null || !billingInitialized) {
callbackContext.error(makeError("Billing is not initialized", BILLING_NOT_INITIALIZED));
return false;
}
iabHelper.consumeAsync(purchase, new OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isFailure()) {
// TODO: Add way more info to this
callbackContext.error(makeError("Error consuming purchase", CONSUME_FAILED, result));
} else {
try {
JSONObject pluginResponse = new JSONObject();
pluginResponse.put("orderId", purchase.getOrderId());
callbackContext.success(pluginResponse);
} catch (JSONException e) {
callbackContext.error("Consume succeeded but success handler failed");
}
}
}
});
return true;
}
protected boolean getSkuDetails(final JSONArray args, final CallbackContext callbackContext) {
final List<String> moreSkus = new ArrayList<String>();
try {
for (int i = 0; i < args.length(); i++) {
moreSkus.add(args.getString(i));
}
} catch (JSONException e) {
callbackContext.error(makeError("Invalid SKU", INVALID_ARGUMENTS));
return false;
}
if (iabHelper == null || !billingInitialized) {
callbackContext.error(makeError("Billing is not initialized", BILLING_NOT_INITIALIZED));
return false;
}
iabHelper.queryInventoryAsync(true, moreSkus, new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
callbackContext.error("Error retrieving SKU details");
return;
}
JSONArray response = new JSONArray();
try {
for (String sku : moreSkus) {
SkuDetails skuDetails = inventory.getSkuDetails(sku);
if (skuDetails != null) {
JSONObject detailsJson = new JSONObject();
detailsJson.put("productId", skuDetails.getSku());
detailsJson.put("title", skuDetails.getTitle());
detailsJson.put("description", skuDetails.getDescription());
detailsJson.put("price", skuDetails.getPrice());
detailsJson.put("type", skuDetails.getType());
response.put(detailsJson);
}
}
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
callbackContext.success(response);
}
});
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (!iabHelper.handleActivityResult(requestCode, resultCode, intent)) {
super.onActivityResult(requestCode, resultCode, intent);
}
}
@Override
public void onDestroy() {
if (iabHelper != null) iabHelper.dispose();
iabHelper = null;
billingInitialized = false;
}
}
|
package se.sics.mspsim.core;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import se.sics.mspsim.util.MapEntry;
import se.sics.mspsim.util.MapTable;
import se.sics.mspsim.util.Utils;
public class DisAsm implements MSP430Constants {
private boolean step = true; //false;
private MapTable map;
// Idiots solution to single stepping...
private BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
public void setMap(MapTable m) {
map = m;
}
public MapTable getMap() {
return map;
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg) {
return disassemble(pc, memory, reg, 0);
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg,
int interrupt) {
DbgInstruction dbg = disassemble(pc, memory, reg, new DbgInstruction(),
interrupt);
String fkn;
if ((fkn = dbg.getFunction()) != null) {
System.out.println("//// " + fkn);
}
System.out.println(dbg.getASMLine());
return dbg;
}
public DbgInstruction getDbgInstruction(int pc, MSP430 cpu) {
return disassemble(pc, cpu.memory, cpu.reg, new DbgInstruction(),
cpu.servicedInterrupt);
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg,
DbgInstruction dbg, int interrupt) {
int startPC = pc;
int size = 0;
int instruction = memory[pc] + (memory[pc + 1] << 8);
int op = instruction >> 12;
boolean word = (instruction & 0x40) == 0;
String output = " ";
if (interrupt > 0) {
output = "I:" + Integer.toString(interrupt) + ' ';
}
String regs = "";
if (pc < 0x0010) {
output += "000" + Integer.toString(pc, 16);
} else if (pc < 0x0100) {
output += "00" + Integer.toString(pc, 16);
} else if (pc < 0x1000) {
output += "0" + Integer.toString(pc, 16);
} else {
output += Integer.toString(pc, 16);
}
output += ":\t";
pc += 2;
size += 2;
switch (op) {
case 1: // Single operand instructions
{
// Register
int register = instruction & 0xf;
// Adress mode of destination...
int ad = (instruction >> 4) & 3;
// Pick up the destination address based on ad more and regs...
int dstAddress = 0;
String adr = "";
String opstr = "";
switch(ad) {
// Operand in register!
case AM_REG:
adr = "R" + register;
break;
case AM_INDEX:
dstAddress = memory[pc] + (memory[pc + 1] << 8);
adr = "R" + register + "(" + dstAddress + ")";
dstAddress = (register == CG1 ? 0 : reg[register]) + dstAddress;
pc += 2;
size += 2;
break;
// Indirect register
case AM_IND_REG:
adr = "@(R" + register + ")";
dstAddress = reg[register];
break;
case AM_IND_AUTOINC:
if (register == 0) {
// Can this be PC and be incremented only one byte?
int tmp = memory[pc] + (memory[pc + 1] << 8);
MapEntry me;
if (map != null && (me = map.getEntry(tmp)) != null) {
adr = me.getName(); // + " = $" + Utils.hex16(tmp);
} else {
adr = "#$" + Utils.hex16(tmp);
}
size += 2;
} else {
adr = "@(R" + register + "+)";
dstAddress = reg[register];
}
break;
}
switch(instruction & 0xff80) {
case RRC:
opstr = "RRC" + (word ? ".W" : ".B");
break;
case SWPB:
opstr = "SWPB" + (word ? ".W" : ".B");
break;
case RRA:
opstr = "RRA" + (word ? ".W" : ".B");
break;
case SXT:
opstr = "RRA" + (word ? ".W" : ".B");
break;
case PUSH:
opstr = "PUSH" + (word ? ".W" : ".B");
break;
case CALL:
opstr = "CALL";
break;
case RETI:
opstr = "RETI";
break;
default:
System.out.println("Not implemented instruction: " + instruction);
}
output += dumpMem(startPC, size, memory);
output += opstr + " " + adr;
regs = "R" + register + "=" + Utils.hex16(reg[register]);
regs += " SP=" + Utils.hex16(reg[SP]);
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
String opstr = "";
switch(instruction & 0xfc00) {
case JNE:
opstr = "JNE";
break;
case JEQ:
opstr = "JEQ";
break;
case JNC:
opstr = "JNC";
break;
case JC:
opstr = "JC";
break;
case JN:
opstr = "JN";
break;
case JGE:
opstr = "JGE";
break;
case JL:
opstr = "JL";
break;
case JMP:
opstr = "JMP";
break;
default:
System.out.println("Not implemented instruction: " +
Utils.binary16(instruction));
}
output += dumpMem(startPC, size, memory);
output += opstr + " $" + Utils.hex16(jmpOffset);
regs = "\tSR=" + dumpSR(reg[SR]);
break;
default:
// Double operand instructions!
int dstRegister = (instruction & 0xf);
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
boolean dstRegMode = ((instruction >> 7) & 1) == 0;
int dstAddress = 0;
int srcAddress = 0;
int src = 0;
int dst = 0;
boolean write = false;
boolean updateStatus = true;
String srcadr = "";
String dstadr = "";
switch(as) {
// Operand in register!
case AM_REG:
if (srcRegister == CG2) {
srcadr = "
} else if (srcRegister == CG1) {
srcadr = "
} else {
srcadr = getRegName(srcRegister);
}
break;
case AM_INDEX:
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
if (srcRegister == CG1) {
srcAddress = memory[pc] + (memory[pc + 1] << 8);
MapEntry me;
if (map != null && (me = map.getEntry(srcAddress)) != null) {
srcadr = "&" + me.getName(); // + " = $" + Utils.hex16(srcAddress);
} else {
srcadr = "&$" + Utils.hex16(srcAddress);
}
size += 2;
} else if (srcRegister == CG2) {
srcadr = "
} else {
srcAddress = reg[srcRegister] + memory[pc] + (memory[pc + 1] << 8);
srcadr = "$" + Utils.hex16(memory[pc] + (memory[pc + 1] << 8)) + "(R" + srcRegister + ")";
size += 2;
}
break;
// Indirect register
case AM_IND_REG:
if (srcRegister == CG2) {
srcadr = "
} else if (srcRegister == CG1) {
srcadr = "
} else {
srcadr = "@" + getRegName(srcRegister);
}
break;
case AM_IND_AUTOINC:
if (srcRegister == CG2) {
srcadr = "#$ffff";
} else if (srcRegister == CG1) {
srcadr = "
} else if (srcRegister == PC) {
srcadr = "#$" + Utils.hex16(memory[pc] + (memory[pc + 1] << 8));
pc += 2;
size += 2;
} else if (srcRegister == CG2) {
srcadr = "#$ffff";
} else {
srcadr = "@" + getRegName(srcRegister) + "+";
srcAddress = reg[srcRegister];
}
break;
}
if (dstRegMode) {
dstadr = getRegName(dstRegister);
} else {
dstAddress = memory[pc] + (memory[pc + 1] << 8);
MapEntry me = map != null ? map.getEntry(dstAddress) : null;
if (dstRegister == 2) {
if (me != null) {
dstadr = "&" + me.getName(); // + " = $" + Utils.hex16(srcAddress);
} else {
dstadr = "&$" + Utils.hex16(dstAddress);
}
} else {
if (me != null) {
dstadr = me.getName() + "(R" + dstRegister + ")";
} else {
dstadr = "$" + Utils.hex16(dstAddress) + "(R" + dstRegister + ")";
}
}
pc += 2;
size += 2;
}
// If byte mode the source will not contain the full word...
if (!word) {
src = src & 0xff;
dst = dst & 0xff;
}
opstr = "";
switch (op) {
case MOV: // MOV
if (instruction == 0x3041) {
opstr = "RET /emulated: MOV.W ";
} else {
opstr = "MOV" + (word ? ".W" : ".B");
}
break;
case ADD: // ADD
opstr = "ADD" + (word ? ".W" : ".B");
break;
case ADDC: // ADDC
opstr = "ADDC" + (word ? ".W" : ".B");
break;
case SUBC: // SUBC
opstr = "SUBC" + (word ? ".W" : ".B");
break;
case SUB: // SUB
opstr = "SUB" + (word ? ".W" : ".B");
break;
case CMP: // CMP
opstr = "CMP" + (word ? ".W" : ".B");
break;
case DADD: // DADD
opstr = "DADD" + (word ? ".W" : ".B");
break;
case BIT: // BIT
opstr = "BIT" + (word ? ".W" : ".B");
break;
case BIC: // BIC
opstr = "BIC" + (word ? ".W" : ".B");
break;
case BIS: // BIS
opstr = "BIS" + (word ? ".W" : ".B");
break;
case XOR: // XOR
opstr = "XOR" + (word ? ".W" : ".B");
break;
case AND: // AND
opstr = "AND" + (word ? ".W" : ".B");
break;
default:
System.out.println(output + " DoubleOperand not implemented: " +
op + " instruction: " +
Utils.binary16(instruction) + " = " +
Utils.hex16(instruction));
}
output += dumpMem(startPC, size, memory);
output += opstr + " " + srcadr + ", " + dstadr;
regs = "R" + dstRegister + "=" + Utils.hex16(reg[dstRegister]) +
" R" + srcRegister + "=" + Utils.hex16(reg[srcRegister]);
regs += " SR=" + dumpSR(reg[SR]);
regs += " SP=" + Utils.hex16(reg[SP]);
regs += "; as = " + as;
srcAddress &= 0xffff;
if (srcAddress != -1) {
srcAddress &= 0xffff;
regs += " sMem:" + Utils.hex16(memory[srcAddress] +
(memory[(srcAddress + 1) % 0xffff]
<< 8));
}
}
dbg.setASMLine(output);
dbg.setRegs(regs);
dbg.setInstruction(instruction, size);
if (map != null) {
dbg.setFunction(map.getFunctionName(startPC));
}
if (!step) {
String line = "";
try {line = input.readLine();}catch(Exception e){}
if (line != null && line.length() > 0 && line.charAt(0) == 'r') {
System.out.println("Registers:");
for (int i = 0, n = 16; i < n; i++) {
System.out.print("R" + i + "=" + Utils.hex16(reg[i]) + " ");
if (i % 7 == 0 && i != 0) System.out.println();
}
System.out.println();
}
}
return dbg;
}
private String getRegName(int index) {
if (index == 0) return "PC";
if (index == 1) return "SP";
if (index == 2) return "SR";
return "R" + index;
}
public static String getSingleOPStr(int instruction) {
boolean word = (instruction & 0x40) == 0;
switch(instruction & 0xff80) {
case RRC:
return "RRC" + (word ? ".W" : ".B");
case SWPB:
return "SWPB" + (word ? ".W" : ".B");
case RRA:
return "RRA" + (word ? ".W" : ".B");
case SXT:
return "RRA" + (word ? ".W" : ".B");
case PUSH:
return "PUSH" + (word ? ".W" : ".B");
case CALL:
return "CALL";
case RETI:
return "RETI";
default:
return "-";
}
}
private static String dumpSR(int sr) {
return "" +
(((sr & OVERFLOW) != 0) ? 'V' : '-') +
(((sr & NEGATIVE) != 0) ? 'N' : '-') +
(((sr & ZERO) != 0) ? 'Z' : '-') +
(((sr & CARRY) != 0) ? 'C' : '-');
}
private static String dumpMem(int pc, int size, int[] memory) {
String output = "";
for (int i = 0, n = 4; i < n; i++) {
if (size > i) {
output += Utils.hex8(memory[pc + i]) + " ";
} else {
output += " ";
}
}
return output;
}
}
|
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.MouseInputAdapter;
public class Couleur extends JPanel {
private BufferedImage buffer;
private JLabel imageLabel;
private ImageIcon image;
private Color couleur;
private Color gris;
private JLabel couleurLabel;
private JLabel grisLabel;
private int niveauGris;
private MouseInput mouse;
public Couleur () {
try {
buffer = ImageIO.read(this.getClass().getResource("SpectrumBar.jpg"));
} catch (IOException e) {
System.err.println(e.getMessage());
}
image = new ImageIcon(Couleur.class.getResource("SpectrumBar.jpg"));
imageLabel = new JLabel(image);
imageLabel.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
mouse = new MouseInput();
imageLabel.addMouseListener(mouse);
imageLabel.addMouseMotionListener(mouse);
Border border = new LineBorder(Color.BLACK, 3);
gris = new Color(128, 128, 128);
couleur = new Color(255, 255, 255);
couleurLabel = new JLabel();
couleurLabel.setBackground(couleur);
couleurLabel.setOpaque(true);
couleurLabel.setPreferredSize(new Dimension(64, 64));
couleurLabel.setBorder(border);
grisLabel = new JLabel();
grisLabel.setBackground(gris);
grisLabel.setOpaque(true);
grisLabel.setPreferredSize(new Dimension(64, 64));
grisLabel.setBorder(border);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(imageLabel);
add(couleurLabel);
add(grisLabel);
setSize(new Dimension(800, 70));
}
public class MouseInput extends MouseInputAdapter {
@Override
public void mouseDragged(MouseEvent arg0) {
changeCouleur(arg0);
}
@Override
public void mouseClicked(MouseEvent e) {
changeCouleur(e);
}
}
public void changeCouleur(MouseEvent e) {
// ignore les bords noirs
if (e.getX() >= 5 && e.getX() < image.getIconWidth()-5) {
couleur = new Color(buffer.getRGB(e.getX(), 50));
couleurLabel.setBackground(couleur);
// d'apres la formule du sujet
niveauGris = (int) ((0.3 * couleur.getRed()) + (0.56 * couleur.getGreen()) + (0.11 * couleur.getBlue()));
gris = new Color(niveauGris, niveauGris, niveauGris);
grisLabel.setBackground(gris);
repaint();
}
}
}
|
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class DiceBag extends JFrame {
// auto generated this thing, or it would yell at me.
private static final long serialVersionUID = 7345177802546602894L;
public JTextField[] j;
public JTextField cd;
public JTextField dc;
public JTextField add;
public JButton btnRoll;
public JButton statbutt;
private JPanel contentPane;
public JTextField NoteBox;
public DiceBag() {
this.setTitle("Dice Bag");
this.setBounds(100, 100, 230, 305);
this.setMaximumSize(new Dimension(230, 305));
this.setMinimumSize(new Dimension(230, 60));
this.setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.add(contentPane, BorderLayout.CENTER);
contentPane.setLayout(null);
j = new JTextField[7];
String[] labels = {"d100", "d20","d12","d10","d8","d6","d4"};
for (int i =0; i<7; i++) {
j[i] = new JTextField();
j[i].setHorizontalAlignment(SwingConstants.RIGHT);
j[i].setBounds(5, i*24, 86, 20);
j[i].setColumns(10);
contentPane.add(j[i]);
JButton button = new JButton("+");
button.setFocusable(false);
button.setBounds(132, 24 *i, 46, 23);
button.addActionListener(new ButtonListener(j[i], 1));
contentPane.add(button);
button = new JButton("-");
button.setFocusable(false);
button.setBounds(179, 24 * i, 46, 23);
button.addActionListener(new ButtonListener(j[i], -1));
contentPane.add(button);
JLabel lblD = new JLabel(labels[i]);
lblD.setBounds(98, 2+24*i, 46, 14);
contentPane.add(lblD);
}
cd = new JTextField(10);
cd.setHorizontalAlignment(SwingConstants.RIGHT);
cd.setBounds(5, 168, 86, 20);
contentPane.add(cd);
JPanel buttonPane = new JPanel();
buttonPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.add(buttonPane, BorderLayout.SOUTH);
buttonPane.setLayout(new BorderLayout());
btnRoll = new JButton("Roll!");
btnRoll.setFont(new Font("Arial Black", Font.BOLD, 11));
btnRoll.setFocusCycleRoot(true);
btnRoll.setBounds(5, 188, 91, 23);
// the behavior of the roll button is added by the DM / Player programs.
buttonPane.add(btnRoll, BorderLayout.EAST);
this.getRootPane().setDefaultButton(btnRoll);
dc = new JTextField();
dc.setHorizontalAlignment(SwingConstants.LEFT);
dc.setBounds(134, 168, 91, 20);
contentPane.add(dc);
dc.setColumns(10);
JLabel lblD_7 = new JLabel("d");
lblD_7.setBounds(98, 168, 11, 14);
contentPane.add(lblD_7);
add = new JTextField();
add.setHorizontalAlignment(SwingConstants.LEFT);
add.setBounds(134, 192, 86, 20);
contentPane.add(add);
add.setColumns(10);
JLabel label = new JLabel("+");
label.setBounds(121, 192, 11, 14);
contentPane.add(label);
NoteBox = new JTextField();
NoteBox.setText("Description of Bag");
NoteBox.setHorizontalAlignment(SwingConstants.CENTER);
NoteBox.setToolTipText("Put a description of the box here! (eg: Sword Damage)");
NoteBox.setBounds(5, 1, 180, 20);
JTAListener jtalist = e->this.setTitle(NoteBox.getText());
NoteBox.addKeyListener( jtalist);
this.add(NoteBox, BorderLayout.NORTH);
NoteBox.setColumns(10);
statbutt = new JButton("4d6 Best 3");
statbutt.setFocusable(false);
statbutt.setBounds(5, 260, 215, 16);
buttonPane.add(statbutt, BorderLayout.WEST);
}
class ButtonListener implements ActionListener {
JTextField JTF;// where the button should get it's info from.
int increment;// how much it should increment the number in that JTF
public ButtonListener(JTextField JTF, int increment) {
this.JTF = JTF;
this.increment = increment;
}
@Override
public void actionPerformed(ActionEvent e) {
Integer x;
try {
x = new Integer(JTF.getText());
} catch (Exception err) {
x = 0;
}
x += increment;
if (x < 0)
x = 0;
JTF.setText(x.toString());
}
}
interface JTAListener extends KeyListener{
@Override
default public void keyPressed(KeyEvent e){}
@Override
default public void keyTyped(KeyEvent e){}
}
}
|
package com.google.sps.agents;
// Imports the Google Cloud client library
import com.google.protobuf.Value;
import com.google.sps.data.Location;
import com.google.sps.utils.LocationUtils;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
/** Time Agent */
public class Time implements Agent {
private final String intentName;
private String output = null;
private String locationFormatted;
private String locationDisplay;
private String locationToFormatted;
private String locationToDisplay;
private String locationFromFormatted;
private String locationFromDisplay;
private ZonedDateTime timeFrom;
public Time(String intentName, Map<String, Value> parameters) {
this.intentName = intentName;
try {
setParameters(parameters);
} catch (Exception e) {
return;
}
}
@Override
public void setParameters(Map<String, Value> parameters) {
if (intentName.equals("get") || intentName.equals("context:time")) {
this.locationFormatted = LocationUtils.getFormattedAddress("location", parameters);
this.locationDisplay = LocationUtils.getDisplayAddress("location", parameters);
String currentTime = getCurrentTimeString(locationFormatted);
if (!currentTime.isEmpty()) {
output = "It is " + currentTime + " in " + locationDisplay + ".";
}
} else if (intentName.equals("check")) {
this.locationFormatted = LocationUtils.getFormattedAddress("location", parameters);
this.locationDisplay = LocationUtils.getDisplayAddress("location", parameters);
String currentTime = getCurrentTimeString(locationFormatted);
if (!currentTime.isEmpty()) {
output = "In " + locationDisplay + ", it is currently " + currentTime + ".";
}
} else if (intentName.contains("convert")) {
this.locationFromFormatted = LocationUtils.getFormattedAddress("location-from", parameters);
this.locationFromDisplay = LocationUtils.getDisplayAddress("location-from", parameters);
this.locationToFormatted = LocationUtils.getFormattedAddress("location-to", parameters);
this.locationToDisplay = LocationUtils.getDisplayAddress("location-to", parameters);
this.timeFrom = getZonedTime("time-from", locationFromFormatted, parameters);
String timeToString = "";
String timeFromString = "";
if (timeFrom != null) {
// Get time in locationTo based on time given in locationFrom
timeToString = zonedTimeToString(getTimeIn(locationToFormatted, timeFrom));
timeFromString = zonedTimeToString(timeFrom);
output =
"It's "
+ timeToString
+ " in "
+ locationToDisplay
+ " when it's "
+ timeFromString
+ " in "
+ locationFromDisplay
+ ".";
} else {
// Get current time in 2 different timezones
timeFromString = getCurrentTimeString(locationFromFormatted);
timeToString = getCurrentTimeString(locationToFormatted);
output =
"It is currently "
+ timeFromString
+ " in "
+ locationFromDisplay
+ " and "
+ timeToString
+ " in "
+ locationToDisplay
+ ".";
}
if (timeToString.isEmpty() || timeFromString.isEmpty()) {
output = null;
}
} else if (intentName.contains("time_zones")) {
this.locationFormatted = LocationUtils.getFormattedAddress("location", parameters);
this.locationDisplay = LocationUtils.getDisplayAddress("location", parameters);
String timezone = getZone(locationFormatted);
if (!timezone.isEmpty()) {
output = "The timezone in " + locationDisplay + " is " + timezone + ".";
}
} else if (intentName.contains("time_difference")) {
this.locationFromFormatted = LocationUtils.getFormattedAddress("location-1", parameters);
this.locationFromDisplay = LocationUtils.getDisplayAddress("location-1", parameters);
this.locationToFormatted = LocationUtils.getFormattedAddress("location-2", parameters);
this.locationToDisplay = LocationUtils.getDisplayAddress("location-2", parameters);
String timeDiffString = getTimeDiff(locationFromFormatted, locationToFormatted);
if (!timeDiffString.isEmpty()) {
output = locationFromDisplay + " is " + timeDiffString + locationToDisplay + ".";
}
}
}
@Override
public String getOutput() {
return this.output;
}
@Override
public String getDisplay() {
return null;
}
@Override
public String getRedirect() {
return null;
}
public ZonedDateTime getCurrentTime(String locationName) {
ZonedDateTime currentTime = null;
Location place = new Location(locationName);
String timeZoneID = place.getTimeZoneID();
currentTime = ZonedDateTime.now(ZoneId.of(timeZoneID));
return currentTime;
}
public String getZone(String locationName) {
String timeZone = null;
Location place = new Location(locationName);
ZonedDateTime time = getCurrentTime(locationName);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("z");
timeZone = time.format(formatter);
String formattedZone = place.getTimeZoneName() + " (" + timeZone + ")";
return formattedZone;
}
public String getTimeDiff(String firstLocation, String secondLocation) {
ZonedDateTime firstZonedTime = getCurrentTime(firstLocation);
ZonedDateTime secondZonedTime = getTimeIn(secondLocation, firstZonedTime);
LocalDateTime firstLocalTime = firstZonedTime.toLocalDateTime();
LocalDateTime secondLocalTime = secondZonedTime.toLocalDateTime();
Duration duration = Duration.between(secondLocalTime, firstLocalTime);
int hours = (int) duration.toHours();
int minutes = (int) duration.toMinutes() - (hours * 60);
String hourString = String.valueOf(Math.abs(hours));
String timeString = "";
if (Math.abs(hours) == 1) {
timeString += hourString + " hour";
} else {
timeString += hourString + " hours";
}
if (minutes != 0) {
String minuteString = String.valueOf(Math.abs(minutes));
timeString += " and " + minuteString + " minutes";
}
String ret = "";
if (hours < 0) {
ret += timeString + " behind ";
} else if (hours == 0) {
ret += "in the same time zone as ";
} else {
ret += timeString + " ahead of ";
}
return ret;
}
public ZonedDateTime getTimeIn(String locationIn, ZonedDateTime timeFromObject) {
ZonedDateTime timeIn = null;
Location placeTo = new Location(locationIn);
String timeZoneID = placeTo.getTimeZoneID();
timeIn = timeFromObject.withZoneSameInstant(ZoneId.of(timeZoneID));
return timeIn;
}
public String getCurrentTimeString(String location) {
ZonedDateTime time = getCurrentTime(location);
return zonedTimeToString(time);
}
public String zonedTimeToString(ZonedDateTime time) {
String timeString = "";
if (time != null) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
timeString = time.format(formatter);
}
return timeString;
}
public static ZonedDateTime getZonedTime(
String timeName, String locationParameter, Map<String, Value> parameters) {
LocalDateTime localTime = getTimeParameter(timeName, parameters);
ZonedDateTime zonedTime = null;
if (localTime != null) {
Location place = new Location(locationParameter);
String timeZoneID = place.getTimeZoneID();
zonedTime = ZonedDateTime.of(localTime, ZoneId.of(timeZoneID));
}
return zonedTime;
}
public static LocalDateTime getTimeParameter(
String parameterName, Map<String, Value> parameters) {
String time = parameters.get(parameterName).getStringValue();
LocalDateTime timeToCheck = null;
if (!time.isEmpty()) {
// Parses time string: "2020-06-24T16:25:00-04:00"
String[] dateComponents = time.split("T")[0].split("\\-");
int year = Integer.parseInt(dateComponents[0]);
int month = Integer.parseInt(dateComponents[1]);
int day = Integer.parseInt(dateComponents[2]);
String[] timeComponents = time.split("T")[1].split("\\-")[0].split("\\:");
int hour = Integer.parseInt(timeComponents[0]);
int minute = Integer.parseInt(timeComponents[1]);
timeToCheck = LocalDateTime.of(year, month, day, hour, minute);
}
return timeToCheck;
}
}
|
package com.opengamma.util.time;
import javax.time.calendar.Period;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* A tenor.
*/
public class Tenor {
/**
* An overnight tenor.
*/
public static final Tenor OVERNIGHT = new Tenor(Period.ofDays(1));
/**
* A tenor of one day.
*/
public static final Tenor DAY = new Tenor(Period.ofDays(1));
/**
* A tenor of one day.
*/
public static final Tenor ONE_DAY = new Tenor(Period.ofDays(1));
/**
* A tenor of two days.
*/
public static final Tenor TWO_DAYS = new Tenor(Period.ofDays(2));
/**
* A tenor of two days.
*/
public static final Tenor THREE_DAYS = new Tenor(Period.ofDays(3));
/**
* A tenor of 1 week.
*/
public static final Tenor ONE_WEEK = new Tenor(Period.ofDays(7));
/**
* A tenor of 2 week.
*/
public static final Tenor TWO_WEEKS = new Tenor(Period.ofDays(14));
/**
* A tenor of 3 week.
*/
public static final Tenor THREE_WEEKS = new Tenor(Period.ofDays(21));
/**
* A tenor of 1 month.
*/
public static final Tenor ONE_MONTH = new Tenor(Period.ofMonths(1));
/**
* A tenor of 2 month.
*/
public static final Tenor TWO_MONTHS = new Tenor(Period.ofMonths(2));
/**
* A tenor of 3 month.
*/
public static final Tenor THREE_MONTHS = new Tenor(Period.ofMonths(3));
/**
* A tenor of 4 month.
*/
public static final Tenor FOUR_MONTHS = new Tenor(Period.ofMonths(4));
/**
* A tenor of 5 month.
*/
public static final Tenor FIVE_MONTHS = new Tenor(Period.ofMonths(5));
/**
* A tenor of 6 month.
*/
public static final Tenor SIX_MONTHS = new Tenor(Period.ofMonths(6));
/**
* A tenor of 7 months.
*/
public static final Tenor SEVEN_MONTHS = new Tenor(Period.ofMonths(7));
/**
* A tenor of 8 months.
*/
public static final Tenor EIGHT_MONTHS = new Tenor(Period.ofMonths(8));
/**
* A tenor of 9 month.
*/
public static final Tenor NINE_MONTHS = new Tenor(Period.ofMonths(9));
/**
* A tenor of 10 month.
*/
public static final Tenor TEN_MONTHS = new Tenor(Period.ofMonths(10));
/**
* A tenor of 11 month.
*/
public static final Tenor ELEVEN_MONTHS = new Tenor(Period.ofMonths(11));
/**
* A tenor of 12 months.
*/
public static final Tenor TWELVE_MONTHS = new Tenor(Period.ofMonths(12));
/**
* A tenor of 1 year.
*/
public static final Tenor ONE_YEAR = new Tenor(Period.ofYears(1));
/**
* A tenor of 2 years.
*/
public static final Tenor TWO_YEARS = new Tenor(Period.ofYears(2));
/**
* A tenor of 3 year.
*/
public static final Tenor THREE_YEARS = new Tenor(Period.ofYears(3));
/**
* A tenor of 4 year.
*/
public static final Tenor FOUR_YEARS = new Tenor(Period.ofYears(4));
/**
* A tenor of 4 year.
*/
public static final Tenor FIVE_YEARS = new Tenor(Period.ofYears(5));
/**
* A tenor of one working week (5 days).
*/
public static final Tenor WORKING_WEEK = new Tenor(Period.ofDays(5));
/**
* A tenor of the working days in a year measured in hours (250 * 24 hours).
*/
public static final Tenor WORKING_DAYS_IN_YEAR = new Tenor(Period.ofHours(252 * 24)); // TODO: should be days???
/**
* A tenor of the working days in a month measured in hours (250 * 24 / 12 hours).
*/
public static final Tenor WORKING_DAYS_IN_MONTH = new Tenor(WORKING_DAYS_IN_YEAR.getPeriod().dividedBy(12));
/**
* A tenor of one financial year measured in hours (365.25 * 24 hours).
*/
public static final Tenor FINANCIAL_YEAR = new Tenor(Period.ofHours((int) (365.25 * 24)));
/**
* A tenor of the days in a standard year (365 days).
*/
public static final Tenor YEAR = new Tenor(Period.ofDays(365));
/**
* A tenor of the days in a leap year (366 days).
*/
public static final Tenor LEAP_YEAR = new Tenor(Period.ofDays(366));
/**
* A tenor of two financial years measured in hours (365.25 * 24 * 2 hours).
*/
public static final Tenor TWO_FINANCIAL_YEARS = new Tenor(FINANCIAL_YEAR.getPeriod().multipliedBy(2));
/**
* A tenor of the days in a standard year (365 / 12 days).
*/
public static final Tenor MONTH = new Tenor(YEAR.getPeriod().dividedBy(12));
/**
* The period of the tenor.
*/
private final Period _period;
/**
* Creates a tenor.
* @param period the period to represent
*/
public Tenor(final Period period) {
_period = period;
}
/**
* Gets the tenor period.
* @return the period
*/
public Period getPeriod() {
return _period;
}
public static final Tenor ofDays(int days) {
return new Tenor(Period.ofDays(days));
}
public static final Tenor ofWeeks(int weeks) {
return new Tenor(Period.ofDays(weeks * 7));
}
public static final Tenor ofMonths(int months) {
return new Tenor(Period.ofMonths(months)); // TODO: what do we do here
}
public static final Tenor ofYears(int years) {
return new Tenor(Period.ofYears(years)); // TODO: what do we do here
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Tenor)) {
return false;
}
Tenor other = (Tenor) o;
return getPeriod().equals(other.getPeriod());
}
public int hashCode() {
return getPeriod().hashCode();
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package mk.jug.pixmas.protocol;
import com.pi4j.wiringpi.Spi;
public class Main {
public static void main(String[] args) throws InterruptedException {
Main main = new Main();
// for (int f = 20000000; f < 32000000; f+=100000) {
// for (int a1 = 1; a1 < 15; a1++) {
// for (int a2 = 10; a2 < 23; a2++) {
// main.doIt(f, a1, a2);
// main.doIt(500000, 25, 5, 15);
// main.doIt(1000000, 25, 5, 15);
// main.doIt(20000000, 25, 5, 12);
// main.doIt(4000000, 5, 1, 4);
// main.doIt(8000000, 10, 2, 7);
// main.doIt(20000000, 25, 3, 12);
// 18MHz, actual is 15.6MHz. One cycle is 64nS, and smaller is 256nS, bigger is 1024nS
main.doIt(18000000, 20, 4, 16);
// 32MHz, actual is 31.2MHz. One cycle is 32nS, and smaller is 256nS, bigger is 1024nS
// main.doIt(32000000, 40, 8, 32);
}
public synchronized void doIt(int f, int L, int aa1, int aa2) throws InterruptedException {
System.out.println(f + " " + aa1 + " " + aa2);
// GpioController gpioController = GpioFactory.getInstance();
// GpioPinDigitalOutput led = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_00, // PIN
// // NUMBER
// "LED", // PIN FRIENDLY NAME (optional)
// PinState.LOW); // PIN STARTUP STATE (optional)
// int z = 100;
// int t = 100;
// boolean a = true;
// long b = System.nanoTime();
// Gpio.digitalWrite(0, false);
// GpioPinPwmOutput pwmPin = gpioController.provisionPwmOutputPin(RaspiPin.GPIO_01);
// pwmPin.setMode(null);
byte[] data = new byte[4096];
int[] matrix = new int[9];
matrix[0] = 100;
matrix[1] = 0;
matrix[2] = 0;
// matrix[3] = 0;
// matrix[4] = 100;
// matrix[5] = 0;
// matrix[6] = 0;
// matrix[7] = 0;
// matrix[8] = 100;
int xa = 0;
int xb = 0;
int xc = 0;
int a1 = 0;
StringBuffer sb = new StringBuffer();
for (int z = 0; z < 5; z++) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < 8; j++) {
int xz = (matrix[i] & (1 << j));
if (xz == 0) {
a1 = aa1;
} else {
a1 = aa2;
}
for (int k = 0; k < L; k++) {
xa = xa * 2;
xb++;
if (k < a1) {
xa = xa + 1;
}
if (xb == 8 || (i == matrix.length - 1 && j == 7 && k == (L - 1))) {
data[xc] = (byte) xa;
xa = 0;
xb = 0;
xc++;
}
}
}
}
}
// for (int i = 0; i < xc; i++) {
// System.out.printf("%#04x, ", (byte) data[i]);
// String s = Integer.toBinaryString((byte) data[i]);
// while (s.length() < 8) {
// s = "0" + s;
// sb.append(s);
// if (i % 20 == 0) {
// System.out.println();
int u = Spi.wiringPiSPISetup(Spi.CHANNEL_0, f);
System.out.println(u);
u = Spi.wiringPiSPIDataRW(Spi.CHANNEL_0, data, xc);
System.out.println(u);
// for (int i = 0; i < sb.length(); i++) {
// if (i % L == 0) {
// System.out.println("");
// System.out.print("" + ((i / L) + 1) + " ");
// System.out.print(sb.charAt(i));
// System.out.println();
// for (int i = 0; i < xc; i++) {
// System.out.print(data[i]);
// System.out.println();
// System.out.println(System.nanoTime() - b);
// // first 8 bits.
// for (int n = 0; n < 2; n++) {
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 8; j++) {
// int bit = z & (1 << j);
// if (a) {
// System.out.println(System.nanoTime() - b);
// b = System.nanoTime();
// led.high();
// if (bit == 0) {
// this.wait(0, 500 - t);
// } else {
// this.wait(0, 1200 - t);
// if (a) {
// System.out.println(System.nanoTime() - b);
// b = System.nanoTime();
// led.low();
// if (bit == 0) {
// this.wait(0, 2000 - t);
// } else {
// this.wait(0, 1300 - t);
// a = false;
// led.low();
this.wait(1);
}
}
|
package org.openoffice.java.accessibility;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleState;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.accessibility.*;
public class List extends DescendantManager implements javax.accessibility.Accessible {
protected List(XAccessible xAccessible, XAccessibleContext xAccessibleContext) {
super(xAccessible, xAccessibleContext);
}
protected void setActiveDescendant(javax.accessibility.Accessible descendant) {
javax.accessibility.Accessible oldAD = activeDescendant;
activeDescendant = descendant;
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldAD, descendant);
}
protected void setActiveDescendant(Object any) {
javax.accessibility.Accessible descendant = null;
try {
if (AnyConverter.isObject(any)) {
XAccessible unoAccessible = (XAccessible) AnyConverter.toObject(
AccessibleObjectFactory.XAccessibleType, any);
if (unoAccessible != null) {
// FIXME: have to handle non transient objects here ..
descendant = new ListItem(unoAccessible);
if (Build.DEBUG) {
try {
if (Build.DEBUG) {
System.err.println("[List] retrieved active descendant event: new descendant is " +
unoAccessible.getAccessibleContext().getAccessibleName());
}
} catch (java.lang.NullPointerException e) {
System.err.println("*** ERROR *** new active descendant not accessible");
}
}
}
}
setActiveDescendant(descendant);
} catch (com.sun.star.lang.IllegalArgumentException e) {
}
}
protected void add(XAccessible unoAccessible) {
if (unoAccessible != null) {
ListItem item = new ListItem(unoAccessible);
// The AccessBridge for Windows expects an instance of AccessibleContext
// as parameters
firePropertyChange(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
null, item.getAccessibleContext());
}
}
protected void remove(XAccessible unoAccessible) {
if (unoAccessible != null) {
ListItem item = new ListItem(unoAccessible);
// The AccessBridge for Windows expects an instance of AccessibleContext
// as parameters
firePropertyChange(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
item.getAccessibleContext(), null);
}
}
protected void add(Object any) {
try {
add((XAccessible) AnyConverter.toObject(AccessibleObjectFactory.XAccessibleType, any));
} catch (com.sun.star.lang.IllegalArgumentException e) {
}
}
protected void remove(Object any) {
try {
remove((XAccessible) AnyConverter.toObject(AccessibleObjectFactory.XAccessibleType, any));
} catch (com.sun.star.lang.IllegalArgumentException e) {
}
}
/**
* Update the proxy objects appropriatly on property change events
*/
protected class AccessibleListListener extends AccessibleDescendantManagerListener {
protected AccessibleListListener() {
super();
}
/** Called by OpenOffice process to notify property changes */
public void notifyEvent(AccessibleEventObject event) {
switch (event.EventId) {
case AccessibleEventId.ACTIVE_DESCENDANT_CHANGED:
setActiveDescendant(event.NewValue);
break;
case AccessibleEventId.CHILD:
if (AnyConverter.isObject(event.OldValue)) {
remove(event.OldValue);
}
if (AnyConverter.isObject(event.NewValue)) {
add(event.NewValue);
}
break;
case AccessibleEventId.INVALIDATE_ALL_CHILDREN:
// Since List items a transient a child events are mostly used
// to attach/detach listeners, it is save to ignore it here
break;
default:
super.notifyEvent(event);
}
}
}
protected XAccessibleEventListener createEventListener() {
return new AccessibleListListener();
}
/** Creates the AccessibleContext associated with this object */
public javax.accessibility.AccessibleContext createAccessibleContext() {
return new AccessibleList();
}
protected class AccessibleList extends AccessibleDescendantManager {
/** Gets the role of this object */
public javax.accessibility.AccessibleRole getAccessibleRole() {
return javax.accessibility.AccessibleRole.LIST;
}
/** Returns the specified Accessible child of the object */
public javax.accessibility.Accessible getAccessibleChild(int i) {
javax.accessibility.Accessible child = null;
try {
XAccessible xAccessible = unoAccessibleContext.getAccessibleChild(i);
if (xAccessible != null) {
// Re-use the active descandant wrapper if possible
javax.accessibility.Accessible activeDescendant = List.this.activeDescendant;
if ((activeDescendant instanceof ListItem) && xAccessible.equals(((ListItem) activeDescendant).unoAccessible)) {
child = activeDescendant;
} else {
child = new ListItem(xAccessible);
}
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
} catch (com.sun.star.uno.RuntimeException e) {
}
return child;
}
/*
* AccessibleComponent
*/
/** Returns the Accessible child, if one exists, contained at the local coordinate Point */
public javax.accessibility.Accessible getAccessibleAt(java.awt.Point p) {
javax.accessibility.Accessible child = null;
try {
XAccessible xAccessible = unoAccessibleComponent.getAccessibleAtPoint(new com.sun.star.awt.Point(p.x, p.y));
if (xAccessible != null) {
// Re-use the active descandant wrapper if possible
javax.accessibility.Accessible activeDescendant = List.this.activeDescendant;
if ((activeDescendant instanceof ListItem) && xAccessible.equals(((ListItem) activeDescendant).unoAccessible)) {
child = activeDescendant;
} else {
child = new ListItem(xAccessible);
}
}
return child;
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/*
* AccessibleSelection
*/
/** Returns an Accessible representing the specified selected child of the object */
public javax.accessibility.Accessible getAccessibleSelection(int i) {
javax.accessibility.Accessible child = null;
try {
XAccessible xAccessible = unoAccessibleSelection.getSelectedAccessibleChild(i);
if (xAccessible != null) {
// Re-use the active descandant wrapper if possible
javax.accessibility.Accessible activeDescendant = List.this.activeDescendant;
if ((activeDescendant instanceof ListItem) && xAccessible.equals(((ListItem) activeDescendant).unoAccessible)) {
child = activeDescendant;
} else {
child = new ListItem(xAccessible);
}
} else if (Build.DEBUG) {
System.out.println(i + "th selected child is not accessible");
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
if (Build.DEBUG) {
System.err.println("IndexOutOfBoundsException caught for AccessibleList.getAccessibleSelection(" + i + ")");
}
} catch (com.sun.star.uno.RuntimeException e) {
}
return child;
}
}
class ListItem extends java.awt.Component implements javax.accessibility.Accessible {
protected XAccessible unoAccessible;
public ListItem(XAccessible xAccessible) {
unoAccessible = xAccessible;
}
public Object[] create(Object[] targetSet) {
try {
java.util.ArrayList list = new java.util.ArrayList(targetSet.length);
for (int i=0; i < targetSet.length; i++) {
XAccessible xAccessible = (XAccessible) UnoRuntime.queryInterface(
XAccessible.class, targetSet[i]);
if (xAccessible != null) {
list.add(new ListItem(xAccessible));
}
}
list.trimToSize();
return list.toArray();
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
javax.accessibility.AccessibleContext accessibleContext = null;
/** Returns the AccessibleContext associated with this object */
public javax.accessibility.AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
try {
XAccessibleContext xAccessibleContext = unoAccessible.getAccessibleContext();
if (xAccessibleContext != null) {
javax.accessibility.AccessibleContext ac = new AccessibleListItem(xAccessibleContext);
if (ac != null) {
ac.setAccessibleParent(List.this);
accessibleContext = ac;
}
AccessibleStateAdapter.setComponentState(this, xAccessibleContext.getAccessibleStateSet());
}
} catch (com.sun.star.uno.RuntimeException e) {
}
}
return accessibleContext;
}
protected class AccessibleListItem extends javax.accessibility.AccessibleContext {
XAccessibleContext unoAccessibleContext;
public AccessibleListItem(XAccessibleContext xAccessibleContext) {
unoAccessibleContext = xAccessibleContext;
}
/** Returns the accessible name of this object */
public String getAccessibleName() {
try {
return unoAccessibleContext.getAccessibleName();
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Sets the accessible name of this object */
public void setAccessibleName(String name) {
// Not supported
}
/** Returns the accessible name of this object */
public String getAccessibleDescription() {
try {
return unoAccessibleContext.getAccessibleDescription();
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Sets the accessible name of this object */
public void setAccessibleDescription(String name) {
// Not supported
}
/** Returns the accessible role of this object */
public javax.accessibility.AccessibleRole getAccessibleRole() {
try {
javax.accessibility.AccessibleRole role = AccessibleRoleAdapter.getAccessibleRole(
unoAccessibleContext.getAccessibleRole());
return (role != null) ? role : javax.accessibility.AccessibleRole.LABEL;
} catch(com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Gets the locale of the component */
public java.util.Locale getLocale() throws java.awt.IllegalComponentStateException {
try {
com.sun.star.lang.Locale unoLocale = unoAccessibleContext.getLocale();
return new java.util.Locale(unoLocale.Language, unoLocale.Country);
} catch (IllegalAccessibleComponentStateException e) {
throw new java.awt.IllegalComponentStateException(e.getMessage());
} catch (com.sun.star.uno.RuntimeException e) {
return List.this.getLocale();
}
}
/** Gets the 0-based index of this object in its accessible parent */
public int getAccessibleIndexInParent() {
try {
return unoAccessibleContext.getAccessibleIndexInParent();
} catch (com.sun.star.uno.RuntimeException e) {
return -1;
}
}
/** Returns the number of accessible children of the object. */
public int getAccessibleChildrenCount() {
try {
return unoAccessibleContext.getAccessibleChildCount();
} catch (com.sun.star.uno.RuntimeException e) {
return 0;
}
}
/** Returns the specified Accessible child of the object. */
public javax.accessibility.Accessible getAccessibleChild(int i) {
javax.accessibility.Accessible child = null;
try {
XAccessible xAccessible = unoAccessibleContext.getAccessibleChild(i);
// Re-use the active descandant wrapper if possible
javax.accessibility.Accessible activeDescendant = List.this.activeDescendant;
if ((activeDescendant instanceof ListItem) && ((ListItem) activeDescendant).unoAccessible.equals(xAccessible)) {
child = activeDescendant;
} else if (xAccessible != null) {
child = new ListItem(xAccessible);
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
} catch (com.sun.star.uno.RuntimeException e) {
}
return child;
}
/** Returns the state set of this object */
public javax.accessibility.AccessibleStateSet getAccessibleStateSet() {
try {
return AccessibleStateAdapter.getAccessibleStateSet(ListItem.this,
unoAccessibleContext.getAccessibleStateSet());
} catch (com.sun.star.uno.RuntimeException e) {
return AccessibleStateAdapter.getDefunctStateSet();
}
}
/** Gets the AccessibleComponent associated with this object that has a graphical representation */
public javax.accessibility.AccessibleComponent getAccessibleComponent() {
try {
XAccessibleComponent unoAccessibleComponent = (XAccessibleComponent)
UnoRuntime.queryInterface(XAccessibleComponent.class, unoAccessibleContext);
return (unoAccessibleComponent != null) ?
new AccessibleComponentImpl(unoAccessibleComponent) : null;
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Gets the AccessibleAction associated with this object that has a graphical representation */
public javax.accessibility.AccessibleAction getAccessibleAction() {
try {
XAccessibleAction unoAccessibleAction = (XAccessibleAction)
UnoRuntime.queryInterface(XAccessibleAction.class, unoAccessibleContext);
return (unoAccessibleAction != null) ?
new AccessibleActionImpl(unoAccessibleAction) : null;
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Gets the AccessibleText associated with this object that has a graphical representation */
public javax.accessibility.AccessibleText getAccessibleText() {
if (disposed)
return null;
try {
XAccessibleText unoAccessibleText = (XAccessibleText)
UnoRuntime.queryInterface(XAccessibleText.class, unoAccessibleContext);
return (unoAccessibleText != null) ?
new AccessibleTextImpl(unoAccessibleText) : null;
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Gets the AccessibleValue associated with this object that has a graphical representation */
public javax.accessibility.AccessibleValue getAccessibleValue() {
try {
XAccessibleValue unoAccessibleValue = (XAccessibleValue)
UnoRuntime.queryInterface(XAccessibleValue.class, unoAccessibleContext);
return (unoAccessibleValue != null) ?
new AccessibleValueImpl(unoAccessibleValue) : null;
} catch (com.sun.star.uno.RuntimeException e) {
return null;
}
}
/** Gets the AccessibleText associated with this object presenting text on the display */
public javax.accessibility.AccessibleIcon[] getAccessibleIcon() {
try {
XAccessibleImage unoAccessibleImage = (XAccessibleImage)
UnoRuntime.queryInterface(XAccessibleImage.class, unoAccessibleContext);
if (unoAccessibleImage != null) {
javax.accessibility.AccessibleIcon[] icons = { new AccessibleIconImpl(unoAccessibleImage) };
return icons;
}
} catch (com.sun.star.uno.RuntimeException e) {
}
return null;
}
}
}
}
|
package com.arrow.acn.client.api;
import org.apache.commons.lang3.Validate;
import com.arrow.acs.client.api.ApiConfig;
public final class AcnClient {
private ApiConfig apiConfig;
private final AccountApi accountApi;
private final CoreEventApi coreEventApi;
private final CoreUserApi coreUserApi;
private final DeviceActionApi deviceActionApi;
private final DeviceApi deviceApi;
private final DeviceStateApi deviceStateApi;
private final GatewayApi gatewayApi;
private final NodeApi nodeApi;
private final NodeTypeApi nodeTypeApi;
private final SoftwareReleaseScheduleApi softwareReleaseScheduleApi;
private final SoftwareReleaseTransApi softwareReleaseTransApi;
private final TelemetryApi telemetryApi;
public AcnClient(ApiConfig apiConfig) {
Validate.notNull(apiConfig, "apiConfig is not set");
this.apiConfig = apiConfig;
accountApi = new AccountApi(apiConfig);
coreEventApi = new CoreEventApi(apiConfig);
coreUserApi = new CoreUserApi(apiConfig);
deviceActionApi = new DeviceActionApi(apiConfig);
deviceApi = new DeviceApi(apiConfig);
deviceStateApi = new DeviceStateApi(apiConfig);
gatewayApi = new GatewayApi(apiConfig);
nodeApi = new NodeApi(apiConfig);
nodeTypeApi = new NodeTypeApi(apiConfig);
softwareReleaseScheduleApi = new SoftwareReleaseScheduleApi(apiConfig);
softwareReleaseTransApi = new SoftwareReleaseTransApi(apiConfig);
telemetryApi = new TelemetryApi(apiConfig);
}
public void setApiConfig(ApiConfig apiConfig) {
this.apiConfig = apiConfig;
accountApi.setApiConfig(apiConfig);
coreEventApi.setApiConfig(apiConfig);
coreUserApi.setApiConfig(apiConfig);
deviceActionApi.setApiConfig(apiConfig);
deviceApi.setApiConfig(apiConfig);
gatewayApi.setApiConfig(apiConfig);
nodeApi.setApiConfig(apiConfig);
softwareReleaseScheduleApi.setApiConfig(apiConfig);
telemetryApi.setApiConfig(apiConfig);
deviceActionApi.setApiConfig(apiConfig);
}
public ApiConfig getApiConfig() {
return apiConfig;
}
public AccountApi getAccountApi() {
return accountApi;
}
public CoreEventApi getCoreEventApi() {
return coreEventApi;
}
public CoreUserApi getCoreUserApi() {
return coreUserApi;
}
public DeviceActionApi getDeviceActionApi() {
return deviceActionApi;
}
public DeviceApi getDeviceApi() {
return deviceApi;
}
public DeviceStateApi getDeviceStateApi() {
return deviceStateApi;
}
public GatewayApi getGatewayApi() {
return gatewayApi;
}
public NodeApi getNodeApi() {
return nodeApi;
}
public NodeTypeApi getNodeTypeApi() {
return nodeTypeApi;
}
public SoftwareReleaseScheduleApi getSoftwareReleaseScheduleApi() {
return softwareReleaseScheduleApi;
}
public SoftwareReleaseTransApi getSoftwareReleaseTransApi() {
return softwareReleaseTransApi;
}
public TelemetryApi getTelemetryApi() {
return telemetryApi;
}
}
|
package alien4cloud.it;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = {
"classpath:alien/rest/cloud"
}, format = { "pretty", "html:target/cucumber/cloud", "json:target/cucumber/cucumber-cloud.json" })
public class RunCloudIT {
}
|
package org.edx.mobile.logger;
import android.content.Context;
import java.io.Serializable;
public class Logger implements Serializable {
private String tag;
/**
* Initializes logger. Logs are disabled for release builds
* during initialization.
* @param context
*/
public static void init(Context context) {
LogUtil.init(context);
}
private Logger() {}
public Logger(Class<?> cls) {
this.tag = cls.getName();
}
public Logger(String tag) {
this.tag = tag;
}
public void error(Throwable ex) {
LogUtil.error(this.tag, "", ex);
}
public void warn(String log) {
LogUtil.warn(this.tag, log);
}
public void debug(String log) {
LogUtil.debug(this.tag, log);
}
}
|
package cn.crap.controller.user;
import cn.crap.adapter.ArticleAdapter;
import cn.crap.dto.ArticleDto;
import cn.crap.dto.SearchDto;
import cn.crap.enu.*;
import cn.crap.framework.JsonResult;
import cn.crap.framework.MyException;
import cn.crap.framework.base.BaseController;
import cn.crap.framework.interceptor.AuthPassport;
import cn.crap.model.Article;
import cn.crap.model.ArticleWithBLOBs;
import cn.crap.model.Module;
import cn.crap.model.Project;
import cn.crap.query.ArticleQuery;
import cn.crap.query.CommentQuery;
import cn.crap.service.ArticleService;
import cn.crap.service.CommentService;
import cn.crap.service.ISearchService;
import cn.crap.service.tool.ModuleCache;
import cn.crap.service.tool.ProjectCache;
import cn.crap.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
// TODO
// TODO setting IDMD5version
// TODO
@Controller
@RequestMapping("/user/article")
public class ArticleController extends BaseController{
@Autowired
private ArticleService articleService;
@Autowired
private ISearchService luceneService;
@Autowired
private CommentService commentService;
@Autowired
private ProjectCache projectCache;
@Autowired
private ModuleCache moduleCache;
@RequestMapping("/list.do")
@ResponseBody
@AuthPassport
public JsonResult list(@ModelAttribute ArticleQuery query) throws MyException{
Project project = getProject(query);
Module module = getModule(query);
checkPermission(project, READ);
Page page = new Page(query);
page.setAllRow(articleService.count(query));
List<Article> models = articleService.query(query);
List<ArticleDto> dtos = ArticleAdapter.getDto(models, module, project);
return new JsonResult().success().data(dtos).page(page)
.others(Tools.getMap("type", ArticleType.getByEnumName(query.getType()), "category", query.getCategory()));
}
@RequestMapping("/detail.do")
@ResponseBody
@AuthPassport
public JsonResult detail(String id, @ModelAttribute ArticleQuery query) throws MyException{
Project project = getProject(query);
Module module = getModule(query);
ArticleWithBLOBs article = new ArticleWithBLOBs();
if (id != null){
article = articleService.getById(id);
project = projectCache.get(article.getProjectId());
module = moduleCache.get(article.getModuleId());
}else {
article.setType(query.getType());
article.setModuleId(module == null ? null : module.getId());
article.setStatus(ArticleStatus.COMMON.getStatus());
article.setCanDelete(CanDeleteEnum.CAN.getCanDelete());
article.setCanComment(CommonEnum.TRUE.getByteValue());
article.setProjectId(project.getId());
}
checkPermission(project, READ);
return new JsonResult(1, ArticleAdapter.getDtoWithBLOBs(article, module, project));
}
@RequestMapping("/addOrUpdate.do")
@ResponseBody
public JsonResult addOrUpdate(@ModelAttribute ArticleDto dto) throws Exception{
Assert.notNull(dto.getProjectId(), "projectId can't be null");
if (ArticleStatus.PAGE.getStatus().equals(dto.getStatus()) && MyString.isEmpty(dto.getMkey())){
throw new MyException(MyError.E000066);
}
String id = dto.getId();
String newProjectId = getProjectId(dto.getProjectId(), dto.getModuleId());
Project newProject = projectCache.get(newProjectId);
dto.setProjectId(newProjectId);
ArticleWithBLOBs article = ArticleAdapter.getModel(dto);
// keystatus ARTICLE
if (!LoginUserHelper.checkAuthPassport(DataType.ARTICLE.name())){
article.setMkey(null);
article.setStatus(null);
}
if(id != null){
String oldProjectId = articleService.getById(article.getId()).getProjectId();
checkPermission(newProjectId, article.getType().equals(ArticleType.ARTICLE.name())? MOD_ARTICLE : MOD_DICT);
checkPermission(oldProjectId, article.getType().equals(ArticleType.ARTICLE.name())? MOD_ARTICLE : MOD_DICT);
if (!LoginUserHelper.isAdminOrProjectOwner(newProject)){
article.setCanDelete(null);
}
articleService.update(article, ArticleType.getByEnumName(article.getType()), "");
} else{
checkPermission(newProject, article.getType().equals(ArticleType.ARTICLE.name())? ADD_ARTICLE : ADD_DICT);
articleService.insert(article);
id = article.getId();
}
if (dto.getUseMarkdown() != null && dto.getUseMarkdown()){
articleService.updateAttribute(id, IAttributeConst.MARK_DOWN, IAttributeConst.TRUE);
} else {
articleService.deleteAttribute(id, IAttributeConst.MARK_DOWN);
}
luceneService.add(ArticleAdapter.getSearchDto(articleService.getById(id)));
return new JsonResult(1, article);
}
@RequestMapping("/delete.do")
@ResponseBody
public JsonResult delete(String id, String ids) throws MyException, IOException{
if( MyString.isEmpty(id) && MyString.isEmpty(ids)){
throw new MyException(MyError.E000029);
}
if( MyString.isEmpty(ids) ){
ids = id;
}
for(String tempId : ids.split(",")){
if(MyString.isEmpty(tempId)){
continue;
}
Article model = articleService.getById(tempId);
Project project = projectCache.get(model.getProjectId());
checkPermission(project , model.getType().equals(ArticleType.ARTICLE.name())? DEL_ARTICLE : DEL_DICT);
if(model.getCanDelete().equals(CanDeleteEnum.CAN_NOT.getCanDelete()) && !LoginUserHelper.isAdminOrProjectOwner(project)){
throw new MyException(MyError.E000009);
}
if (commentService.count(new CommentQuery().setArticleId(model.getId())) > 0){
throw new MyException(MyError.E000037);
}
// PAGE
if (ArticleStatus.PAGE.getStatus().equals(model.getStatus()) && !LoginUserHelper.isSuperAdmin()){
throw new MyException(MyError.E000009);
}
luceneService.delete(new SearchDto(model.getId()));
articleService.delete(tempId, ArticleType.getByEnumName(model.getType()) , "");
}
return new JsonResult(1,null);
}
@RequestMapping("/dictionary/importFromSql.do")
@ResponseBody
@AuthPassport
public JsonResult importFromSql(@RequestParam String sql, @RequestParam(defaultValue="") String brief, @RequestParam String moduleId, String name,
@RequestParam(defaultValue="") boolean isMysql) throws MyException {
ArticleWithBLOBs article = null;
if(isMysql){
article = SqlToDictionaryUtil.mysqlToDictionary(sql, brief, moduleId, name);
}else{
article = SqlToDictionaryUtil.sqlserviceToDictionary(sql, brief, moduleId, name);
}
Module module = moduleCache.get(moduleId);
checkPermission(projectCache.get(module.getProjectId()), READ);
article.setProjectId(module.getProjectId());
articleService.insert(article);
return new JsonResult(1, new Article());
}
@RequestMapping("/markdown.do")
public String markdown(@ModelAttribute Article article, HttpServletRequest request) throws Exception {
ArticleWithBLOBs model;
if(article.getId() != null){
model= articleService.getById(article.getId());
}else{
model= new ArticleWithBLOBs();
model.setType(article.getType());
model.setModuleId(article.getModuleId());
}
request.setAttribute("markdownPreview", model.getContent());
request.setAttribute("markdownText", model.getMarkdown());
return "/WEB-INF/views/markdown.jsp";
}
}
|
package org.sagebionetworks.bridge.dynamodb;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.sagebionetworks.bridge.BridgeConstants.API_MAXIMUM_PAGE_SIZE;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.BEGINS_WITH;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.GE;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.LT;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NOT_NULL;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NULL;
import static com.amazonaws.services.dynamodbv2.model.ConditionalOperator.AND;
import static com.amazonaws.services.dynamodbv2.model.ConditionalOperator.OR;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.amazonaws.services.dynamodbv2.datamodeling.QueryResultPage;
import com.google.common.util.concurrent.RateLimiter;
import org.joda.time.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.config.Config;
import org.sagebionetworks.bridge.dao.ExternalIdDao;
import org.sagebionetworks.bridge.exceptions.BadRequestException;
import org.sagebionetworks.bridge.exceptions.EntityAlreadyExistsException;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.json.DateUtils;
import org.sagebionetworks.bridge.models.ForwardCursorPagedResourceList;
import org.sagebionetworks.bridge.models.accounts.ExternalIdentifier;
import org.sagebionetworks.bridge.models.accounts.ExternalIdentifierInfo;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.ConditionalOperator;
import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@Component
public class DynamoExternalIdDao implements ExternalIdDao {
static final String PAGE_SIZE_ERROR = "pageSize must be from 1-"+API_MAXIMUM_PAGE_SIZE+" records";
private static final String RESERVATION = "reservation";
private static final String HEALTH_CODE = "healthCode";
static final String IDENTIFIER = "identifier";
private static final String STUDY_ID = "studyId";
private static final String ASSIGNMENT_FILTER = "assignmentFilter";
private static final String ID_FILTER = "idFilter";
private int addLimit;
private int lockDuration;
private RateLimiter getExternalIdRateLimiter;
private DynamoDBMapper mapper;
/** Gets the add limit and lock duration from Config. */
@Autowired
public final void setConfig(Config config) {
addLimit = config.getInt(CONFIG_KEY_ADD_LIMIT);
lockDuration = config.getInt(CONFIG_KEY_LOCK_DURATION);
setGetExternalIdRateLimiter(RateLimiter.create(config.getInt(CONFIG_KEY_GET_LIMIT)));
}
// allow unit test to mock this
void setGetExternalIdRateLimiter(RateLimiter getExternalIdRateLimiter) {
this.getExternalIdRateLimiter = getExternalIdRateLimiter;
}
@Resource(name = "externalIdDdbMapper")
public final void setMapper(DynamoDBMapper mapper) {
this.mapper = mapper;
}
@Override
public ForwardCursorPagedResourceList<ExternalIdentifierInfo> getExternalIds(StudyIdentifier studyId,
String offsetKey,
int pageSize, String idFilter, Boolean assignmentFilter) {
checkNotNull(studyId);
// Just set a sane upper limit on this.
// pageSize is used here to determine limit the number of results to be returned, as well as amount of records
// to scan per call to dynamo
if (pageSize < 1 || pageSize > API_MAXIMUM_PAGE_SIZE) {
throw new BadRequestException(PAGE_SIZE_ERROR);
}
// The offset key is applied after the idFilter. If the offsetKey doesn't match the beginning
// of the idFilter, the AWS SDK throws a validation exception. So when providing an idFilter and
// a paging offset, clear the offset (go back to the first page) if they don't match.
if (offsetKey != null && idFilter != null && !offsetKey.startsWith(idFilter)) {
offsetKey = null;
}
QueryResultPage<DynamoExternalIdentifier> list;
List<ExternalIdentifierInfo> identifiers = Lists.newArrayListWithCapacity(pageSize);
do {
getExternalIdRateLimiter.acquire(pageSize);
list = mapper.queryPage(DynamoExternalIdentifier.class,
createGetQuery(studyId, offsetKey, pageSize, idFilter, assignmentFilter));
for (ExternalIdentifier id : list.getResults()) {
if (identifiers.size() == pageSize) {
// return no more than pageSize externalIdentifiers
break;
}
identifiers.add(createInfo(id, lockDuration));
}
// This is the last key, not the next key of the next page of records. It only exists if there's a record
// beyond the records we've converted to a page. Then get the last key in the list.
Map<String, AttributeValue> lastEvaluated = list.getLastEvaluatedKey();
offsetKey = lastEvaluated != null ? lastEvaluated.get(IDENTIFIER).getS() : null;
} while ((identifiers.size() < pageSize) && (offsetKey != null));
ForwardCursorPagedResourceList<ExternalIdentifierInfo> resourceList = new ForwardCursorPagedResourceList<>(
identifiers, offsetKey, pageSize)
.withFilter(ID_FILTER, idFilter);
if (assignmentFilter != null) {
resourceList = resourceList.withFilter(ASSIGNMENT_FILTER, assignmentFilter.toString());
}
return resourceList;
}
@Override
public void addExternalIds(StudyIdentifier studyId, List<String> externalIds) {
checkNotNull(studyId);
checkNotNull(externalIds);
// We validate a wider range of issues in the service, but check size again because this is
// specifically a database capacity issue.
if (externalIds.size() > addLimit) {
throw new BadRequestException("List of externalIds is too large; size=" + externalIds.size() + ", limit=" + addLimit);
}
List<DynamoExternalIdentifier> idsToSave = externalIds.stream().map(id -> {
return new DynamoExternalIdentifier(studyId, id);
}).filter(externalId -> {
return mapper.load(externalId) == null;
}).collect(Collectors.toList());
if (!idsToSave.isEmpty()) {
List<FailedBatch> failures = mapper.batchSave(idsToSave);
BridgeUtils.ifFailuresThrowException(failures);
}
}
@Override
public void reserveExternalId(StudyIdentifier studyId, String externalId) throws EntityAlreadyExistsException {
checkNotNull(studyId);
checkArgument(isNotBlank(externalId));
DynamoExternalIdentifier keyObject = new DynamoExternalIdentifier(studyId, externalId);
DynamoExternalIdentifier identifier = mapper.load(keyObject);
if (identifier == null) {
throw new EntityNotFoundException(ExternalIdentifier.class);
}
try {
long newReservation = DateUtils.getCurrentMillisFromEpoch();
identifier.setReservation(newReservation);
mapper.save(identifier, getReservationExpression(newReservation));
} catch(ConditionalCheckFailedException e) {
// The timeout is in effect or the healthCode is set, either way, code is "taken"
throw new EntityAlreadyExistsException(ExternalIdentifier.class, "identifier", identifier.getIdentifier());
}
}
@Override
public void assignExternalId(StudyIdentifier studyId, String externalId, String healthCode) {
checkNotNull(studyId);
checkArgument(isNotBlank(externalId));
checkArgument(isNotBlank(healthCode));
DynamoExternalIdentifier keyObject = new DynamoExternalIdentifier(studyId, externalId);
DynamoExternalIdentifier identifier = mapper.load(keyObject);
if (identifier == null) {
throw new EntityNotFoundException(ExternalIdentifier.class);
}
// If the same code has already been set, do nothing, do not throw an error.
if (!healthCode.equals(identifier.getHealthCode())) {
try {
identifier.setReservation(0L);
identifier.setHealthCode(healthCode);
mapper.save(identifier, getAssignmentExpression());
} catch(ConditionalCheckFailedException e) {
// The timeout is in effect or the healthCode is set, either way, code is "taken"
throw new EntityAlreadyExistsException(ExternalIdentifier.class, "identifier", identifier.getIdentifier());
}
}
}
@Override
public void unassignExternalId(StudyIdentifier studyId, String externalId) {
checkNotNull(studyId);
checkArgument(isNotBlank(externalId));
DynamoExternalIdentifier keyObject = new DynamoExternalIdentifier(studyId, externalId);
// Don't throw an exception if the identifier doesn't exist, we don't care.
DynamoExternalIdentifier identifier = mapper.load(keyObject);
if (identifier != null) {
identifier.setHealthCode(null);
identifier.setReservation(0L);
mapper.save(identifier);
}
}
/**
* This is intended for testing. Deleting a large number of identifiers will cause DynamoDB capacity exceptions.
*/
@Override
public void deleteExternalIds(StudyIdentifier studyId, List<String> externalIds) {
checkNotNull(studyId);
checkNotNull(externalIds);
if (!externalIds.isEmpty()) {
List<DynamoExternalIdentifier> idsToDelete = externalIds.stream().map(id -> {
return new DynamoExternalIdentifier(studyId, id);
}).collect(Collectors.toList());
List<FailedBatch> failures = mapper.batchDelete(idsToDelete);
BridgeUtils.ifFailuresThrowException(failures);
}
}
/**
* Get the count query (applies filters) and then sets an offset key and the limit to a page of records,
* plus one, to determine if there are records beyond the current page.
*/
private DynamoDBQueryExpression<DynamoExternalIdentifier> createGetQuery(StudyIdentifier studyId,
String offsetKey, int pageSize, String idFilter, Boolean assignmentFilter) {
DynamoDBQueryExpression<DynamoExternalIdentifier> query =
new DynamoDBQueryExpression<DynamoExternalIdentifier>();
if (idFilter != null) {
query.withRangeKeyCondition(IDENTIFIER, new Condition()
.withAttributeValueList(new AttributeValue().withS(idFilter))
.withComparisonOperator(BEGINS_WITH));
}
if (assignmentFilter != null) {
addAssignmentFilter(query, assignmentFilter.booleanValue());
}
query.withHashKeyValues(new DynamoExternalIdentifier(studyId, null)); // no healthCode.
if (offsetKey != null) {
Map<String, AttributeValue> map = new HashMap<>();
map.put(STUDY_ID, new AttributeValue().withS(studyId.getIdentifier()));
map.put(IDENTIFIER, new AttributeValue().withS(offsetKey));
query.withExclusiveStartKey(map);
}
query.withLimit(pageSize);
return query;
}
private void addAssignmentFilter(DynamoDBQueryExpression<DynamoExternalIdentifier> query, boolean isAssigned) {
String reservationStartTime = Long.toString(DateTimeUtils.currentTimeMillis()-lockDuration);
ComparisonOperator healthCodeOp = (isAssigned) ? NOT_NULL : NULL;
ComparisonOperator reservationOp = (isAssigned) ? GE : LT;
ConditionalOperator op = (isAssigned) ? OR : AND;
AttributeValue attrValue = new AttributeValue().withN(reservationStartTime);
Condition healthCodeCondition = new Condition().withComparisonOperator(healthCodeOp);
Condition reservationCondition = new Condition().withAttributeValueList(attrValue).withComparisonOperator(reservationOp);
query.withQueryFilterEntry(HEALTH_CODE, healthCodeCondition);
query.withQueryFilterEntry(RESERVATION, reservationCondition);
query.withConditionalOperator(op);
}
/**
* Save the record with a new timestamp IF the healthCode is empty and the reservation timestamp in the
* existing record was not set in the recent past (during the lockDuration).
*/
private DynamoDBSaveExpression getReservationExpression(long newReservation) {
AttributeValue reservationStartTime = new AttributeValue().withN(Long.toString(newReservation-lockDuration));
ExpectedAttributeValue beforeReservation = new ExpectedAttributeValue()
.withValue(reservationStartTime).withComparisonOperator(LT);
ExpectedAttributeValue healthCodeNull = new ExpectedAttributeValue().withExists(false);
Map<String, ExpectedAttributeValue> map = Maps.newHashMap();
map.put(RESERVATION, beforeReservation);
map.put(HEALTH_CODE, healthCodeNull);
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
saveExpression.withConditionalOperator(AND);
saveExpression.setExpected(map);
return saveExpression;
}
/**
* Save the record with the user's healthCode IF the healthCode is not yet set. If calling code calls
* the reservation method first, this should not happen, but we do not prevent it.
*/
private DynamoDBSaveExpression getAssignmentExpression() {
Map<String, ExpectedAttributeValue> map = Maps.newHashMap();
map.put(HEALTH_CODE, new ExpectedAttributeValue().withExists(false));
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
saveExpression.setExpected(map);
return saveExpression;
}
private ExternalIdentifierInfo createInfo(ExternalIdentifier id, long lockDuration) {
// This calculation is done a couple of times, it does not need to be accurate to the millisecond
long reservationStartTime = DateTimeUtils.currentTimeMillis() - lockDuration;
boolean isAssigned = (id.getHealthCode() != null || id.getReservation() >= reservationStartTime);
return new ExternalIdentifierInfo(id.getIdentifier(), isAssigned);
}
private <T> T last(List<T> items) {
if (items != null && !items.isEmpty()) {
return items.get(items.size()-1);
}
return null;
}
}
|
package com.bookbase.app.model.api;
import android.support.annotation.NonNull;
import com.bookbase.app.BuildConfig;
import com.bookbase.app.model.entity.Book;
import com.crashlytics.android.Crashlytics;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public final class GoogleBooksApi {
private static final OkHttpClient client = new OkHttpClient();
private static final String API_URL = "https:
private static final String GOOGLE_BOOKS_API_KEY = String.format("&key=%s", BuildConfig.GOOGLE_BOOKS_API_KEY);
private static final String FILTERS = "&fields=items(volumeInfo/title,volumeInfo/authors,volumeInfo/description," +
"volumeInfo/averageRating,volumeInfo/imageLinks/thumbnail)";
private GoogleBooksApi(){}
private enum SearchType {
ISBN ("isbn:");
private final String queryParam;
SearchType(String type){
this.queryParam = type;
}
String queryParam(){
return queryParam;
}
}
private static void query(String endpoint, UUID requestId, Callback callback){
Request request = new Request.Builder().url(endpoint).tag(requestId).build();
client.newCall(request).enqueue(callback);
}
public static void queryByIsbn(String isbn, final UUID requestId, final BooksApiCallback booksApiCallback){
booksApiCallback.inProgress();
String url = buildEndpointUrl(SearchType.ISBN, isbn);
Callback callback = new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
booksApiCallback.onError();
// TODO: Log to crash reporting.
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
booksApiCallback.onComplete(jsonToBookCollection(response));
}
};
query(url, requestId, callback);
}
@SuppressWarnings("unused")
public static void cancelRequest(UUID requestId){
for(Call call : client.dispatcher().queuedCalls()) {
if(call.request().tag().equals(requestId))
call.cancel();
}
}
private static String buildEndpointUrl(SearchType searchType, String searchTerm){
return API_URL + searchType.queryParam() + searchTerm + GOOGLE_BOOKS_API_KEY + FILTERS;
}
@SuppressWarnings("ConstantConditions")
private static List<Book> jsonToBookCollection(Response response){
String responseBody;
JSONObject json;
JSONArray jsonArray;
Moshi moshi = new Moshi.Builder().add(new BookJsonAdapter()).build();
Type type = Types.newParameterizedType(List.class, Book.class);
JsonAdapter<List<Book>> jsonAdapter = moshi.adapter(type);
List<Book> books = null;
try{
// Convert response body to JSON Array.
responseBody = response.body().string();
if(isResponseValid(responseBody)){
json = new JSONObject(responseBody);
jsonArray = json.getJSONArray("items");
books = jsonAdapter.fromJson(jsonArray.toString());
} else{
// TODO: Log to crash reporting.
return Collections.emptyList();
}
} catch (IOException e){
Crashlytics.logException(e);
} catch(JSONException e){
Crashlytics.logException(e);
}
return books;
}
private static boolean isResponseValid(String response){
return response.contains("items");
}
}
|
package com.chrisahn.popularmovies;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class FetchMovieTask extends AsyncTask<String, Void, ArrayList<MovieData> > {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
// Interface to send data back to Fragment/Activity
public interface AsyncResultCallBack {
void processData(ArrayList<MovieData> arrMovieData);
}
@Override
protected ArrayList<MovieData> doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
String jsonResponseStr;
try {
final String BASE_URL = "https://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_KEY_PARAM = "api_key";
// Build URI
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM, params[0])
.appendQueryParameter(API_KEY_PARAM, BuildConfig.MOVIE_DB_KEY)
.build();
// Convert to URL and Log current URL
URL url = new URL(uri.toString());
Log.v(LOG_TAG, "Final URL: " + uri.toString());
// Create request to Movie DB API and open connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Gather InputStream data and read into the BufferedReader
InputStream inputStream = urlConnection.getInputStream();
StringBuffer jsonStringBuffer = new StringBuffer();
// Check for a response from connection
if (inputStream == null)
{
Log.e(LOG_TAG, "Empty InputStream, no response");
return null;
}
// Read InputStream into BufferedReader
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// Read each line of bufferedReader and append into jsonStringBuffer
String line;
while ((line = bufferedReader.readLine()) != null) {
// Append with new-line for readability
jsonStringBuffer.append(line + "\n");
}
if (jsonStringBuffer.length() == 0) {
// Empty Stream
Log.e(LOG_TAG, "Empty StringBuffer");
return null;
}
jsonResponseStr = jsonStringBuffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
// Close connections
if (urlConnection != null) {
urlConnection.disconnect();
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(ArrayList<MovieData> movieDatas) {
super.onPostExecute(movieDatas);
}
}
|
package com.performancetweaker.app.utils;
import com.performancetweaker.app.R;
import android.content.Context;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
public class GpuUtils {
private static GpuUtils gpuUtils;
public static GpuUtils getInstance() {
if (gpuUtils == null) {
gpuUtils = new GpuUtils();
}
return gpuUtils;
}
private GpuUtils() {
}
private String[] GPU_GOVS_AVAIL_PATH = new String[]{
"/sys/class/kgsl/kgsl-3d0/devfreq/available_governors",
"/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor_list",
"/sys/devices/platform/dfrgx/devfreq/dfrgx/available_governors"
};
private String[] GPU_FREQS_AVAIL = new String[]{
"/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpu_available_frequencies",
"/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpu_available_frequencies",
"/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies",
"/sys/devices/platform/dfrgx/devfreq/dfrgx/available_frequencies",
"/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_list"
};
private String[] GPU_FREQS_MIN = new String[]{
"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq",
"/sys/kernel/tegra_gpu/gpu_floor_rate",
"/sys/devices/platform/dfrgx/devfreq/dfrgx/min_freq"
};
private String[] GPU_FREQS_MAX = new String[]{
"/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk",
"/sys/class/kgsl/kgsl-3d0/max_gpuclk",
"/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_limit",
"/sys/kernel/tegra_gpu/gpu_cap_rate",
"/sys/devices/platform/dfrgx/devfreq/dfrgx/max_freq"
};
private String[] GPU_GOVERNOR_PATH = new String[]{
"/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor",
"/sys/class/kgsl/kgsl-3d0/devfreq/governor",
"/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor",
"/sys/devices/platform/dfrgx/devfreq/dfrgx/governor"
};
public String[] getAvailableGpuFrequencies() {
String[] possiblePath = GPU_FREQS_AVAIL;
String gpuFrequencies[] = new String[]{};
for (String path : possiblePath) {
if (new File(path).exists()) {
gpuFrequencies = SysUtils.readOutputFromFile(path).split(" ");
}
}
for (int i = 0; i < gpuFrequencies.length; i++) {
if (gpuFrequencies[i] == "") {
return new String[]{};
}
}
return gpuFrequencies;
}
public String[] getAvailableGpuGovernors() {
String[] possiblePath = GPU_GOVS_AVAIL_PATH;
for (String s : possiblePath) {
if (new File(s).exists()) {
return SysUtils.readOutputFromFile(s).split(" ");
}
}
return new String[]{};
}
public String getCurrentGpuGovernor() {
String governorPath = null;
for (String path : GPU_GOVERNOR_PATH) {
if (new File(path).exists()) {
governorPath = path;
break;
}
}
if (governorPath != null) {
return SysUtils.readOutputFromFile(governorPath);
} else {
return "";
}
}
public void setGpuFrequencyScalingGovernor(String governor, Context context) {
ArrayList<String> commands = new ArrayList<>();
String governorPath = null;
for (String path : GPU_GOVERNOR_PATH) {
if (new File(path).exists()) {
governorPath = path;
break;
}
}
if (governorPath != null) {
commands.add("chmod 0664 " + governorPath);
commands.add("echo " + governor + " > " + governorPath);
boolean success = SysUtils.executeRootCommand(commands);
if (success) {
String msg = context.getString(R.string.ok_message);
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
}
public String getMaxGpuFrequency() {
String possiblePath[] = GPU_FREQS_MAX;
for (String s : possiblePath) {
if (new File(s).exists()) {
return SysUtils.readOutputFromFile(s);
}
}
return "";
}
public void setMaxGpuFrequency(String maxFrequency, Context context) {
ArrayList<String> commands = new ArrayList<>();
if (maxFrequency != null) {
String maxFrequencyPath = null;
for (String s : GPU_FREQS_MAX) {
if (new File(s).exists()) {
maxFrequencyPath = s;
break;
}
}
commands.add("chmod 0664 " + maxFrequencyPath);
commands.add("echo " + maxFrequency + " > " + maxFrequencyPath);
boolean success = SysUtils.executeRootCommand(commands);
if (success) {
String msg = context.getString(R.string.ok_message);
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
}
public String getMinGpuFrequency() {
String possiblePath[] = GPU_FREQS_MIN;
for (String s : possiblePath) {
if (new File(s).exists()) {
return SysUtils.readOutputFromFile(s);
}
}
return "";
}
public void setMinFrequency(String minFrequency, Context context) {
ArrayList<String> commands = new ArrayList<>();
if (minFrequency != null) {
String minFrequencyPath = null;
for (String s : GPU_FREQS_MIN) {
if (new File(s).exists()) {
minFrequencyPath = s;
}
}
commands.add("chmod 0664 " + minFrequencyPath);
commands.add("echo " + minFrequency + " > " + minFrequencyPath);
boolean success = SysUtils.executeRootCommand(commands);
if (success) {
String msg = context.getString(R.string.ok_message);
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
}
public boolean isGpuFrequencyScalingSupported() {
String possiblePath[] = GPU_FREQS_AVAIL;
for (String s : possiblePath) {
if (new File(s).exists()) {
return true;
}
}
return false;
}
public static String[] toMhz(String... values) {
String[] frequency = new String[values.length];
for (int i = 0; i < values.length; i++) {
try {
frequency[i] = (Integer.parseInt(values[i].trim()) / (1000 * 1000)) + " Mhz";
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
return frequency;
}
}
|
package com.siteshot.siteshot;
import android.app.Fragment;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseGeoPoint;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseUser;
import com.siteshot.siteshot.activities.TabActivity;
import com.siteshot.siteshot.models.UserPhoto;
import com.siteshot.siteshot.utils.PhotoUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
//import java.text.ParseException;
public class SiteShotMapFragment extends Fragment implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private final String TAG = TabActivity.class.getName();
MapView mapFragment;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
private static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// A fast interval ceiling
private static final int FAST_CEILING_IN_SECONDS = 1;
// A fast ceiling of update intervals, used when the app is visible
private static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
// Update interval in milliseconds
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// Represents the circle around a map
private Circle mapCircle;
// Fields for the map radius in feet
private float radius = 50;
private float lastRadius;
// Fields for helping process map and location changes
private final Map<String, Marker> mapMarkers = new HashMap<String, Marker>();
private final Map<Marker, UserPhoto> markerPhotos = new HashMap<Marker, UserPhoto>();
private int mostRecentMapUpdate;
private boolean hasSetUpInitialLocation;
private String selectedPostObjectId;
private Location lastLocation;
private Location currentLocation;
private LocationRequest locationRequest;
private LocationClient locationClient;
/*
* Constants for handling location results
*/
// Conversion from feet to meters
private static final float METERS_PER_FEET = 0.3048f;
// Conversion from kilometers to meters
private static final int METERS_PER_KILOMETER = 1000;
// Initial offset for calculating the map bounds
private static final double OFFSET_CALCULATION_INIT_DIFF = 1.0;
// Accuracy for calculating the map bounds
private static final float OFFSET_CALCULATION_ACCURACY = 0.01f;
// Maximum results returned from a Parse query
private static final int MAX_POST_SEARCH_RESULTS = 20;
// Maximum post search radius for map in kilometers
private static final int MAX_POST_SEARCH_DISTANCE = 100;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "Map";
// Adapter for the Parse query
//private ParseQueryAdapter<SiteShotMapData> postsQueryAdapter;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static SiteShotMapFragment newInstance(int sectionNumber) {
SiteShotMapFragment fragment = new SiteShotMapFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public SiteShotMapFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Set up location services.
View rootView = inflater.inflate(R.layout.siteshot_map_fragment, container, false);
MapsInitializer.initialize(getActivity());
// Set up the Map fragment.
mapFragment = (MapView) rootView.findViewById(R.id.mapView);
mapFragment.onCreate(savedInstanceState);
mapFragment.onResume();
// Enable the current location "blue dot"
mapFragment.getMap().setMyLocationEnabled(true);
// Set up the camera change handler
mapFragment.getMap().setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
// When the camera changes, update the query
doMapQuery();
}
});
mapFragment.getMap().setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
double latitude = marker.getPosition().latitude;
double longitude = marker.getPosition().longitude;
ParseGeoPoint markerPoint = new ParseGeoPoint(latitude, longitude);
ParseGeoPoint myPoint = geoPointFromLocation(currentLocation);
// Unlock the marker if it's within range.
if (markerPoint.distanceInKilometersTo(myPoint) <= radius * METERS_PER_FEET
/ METERS_PER_KILOMETER) {
UserPhoto phoot = markerPhotos.get(marker);
String username = ParseUser.getCurrentUser().getUsername();
ArrayList<String> unlocked = (ArrayList) phoot.getList("unlocked");
if (unlocked == null) {
unlocked = new ArrayList<String>();
}
// TODO: re-query UserPhoto in case it changed in the meantime
if (!unlocked.contains(username)) {
unlocked.add(username);
}
phoot.put("unlocked", unlocked);
phoot.saveInBackground();
marker.setTitle("Just Unlocked");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
// Center on the tapped marker and show its info window.
return false;
}
});
return rootView;
}
// Set up a customized query
ParseQueryAdapter.QueryFactory<UserPhoto> factory =
new ParseQueryAdapter.QueryFactory<UserPhoto>() {
public ParseQuery<UserPhoto> create() {
Location myLoc = (currentLocation == null) ? lastLocation : currentLocation;
ParseQuery<UserPhoto> query = UserPhoto.getQuery();
query.include("user");
query.orderByDescending("createdAt");
query.whereWithinKilometers("location", geoPointFromLocation(myLoc), radius
* METERS_PER_FEET / METERS_PER_KILOMETER);
query.setLimit(MAX_POST_SEARCH_RESULTS);
return query;
}
};
public Location getCurrentLocation() {
return currentLocation;
}
/*
* Called when the Activity is no longer visible at all. Stop updates and disconnect.
*/
@Override
public void onStop() {
// If the client is connected
if (locationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
locationClient.disconnect();
super.onStop();
}
/*
* Called when the Activity is restarted, even before it becomes visible.
*/
@Override
public void onStart() {
super.onStart();
locationRequest = LocationRequest.create();
locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
locationClient = new LocationClient(TabActivity.c, this, this);
// Connect to the location services client
locationClient.connect();
}
private void startPeriodicUpdates() {
locationClient.requestLocationUpdates(locationRequest, this);
}
private void stopPeriodicUpdates() {
locationClient.removeLocationUpdates((LocationListener) this);
}
private Location getLocation() {
if (servicesConnected()) {
Log.d(TAG, locationClient.getLastLocation().toString());
return locationClient.getLastLocation();
} else {
return null;
}
}
public void onConnected(Bundle bundle) {
currentLocation = getLocation();
startPeriodicUpdates();
}
public void onDisconnected() {
Log.d(TAG, "disconnected from location services");
}
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
}
} else {
Log.e(TAG, "onConnectionFailed: " + connectionResult.getErrorCode());
}
}
public void onLocationChanged(Location location) {
currentLocation = location;
if (lastLocation != null
&& geoPointFromLocation(location)
.distanceInKilometersTo(geoPointFromLocation(lastLocation)) < 0.01) {
return;
}
lastLocation = location;
LatLng myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
if (!hasSetUpInitialLocation) {
// Zoom to the current location.
updateZoom(myLatLng);
hasSetUpInitialLocation = true;
}
// Update map radius indicator
updateCircle(myLatLng);
doMapQuery();
//doListQuery();
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Display an error dialog
Log.e(TAG, "could not get Google Play services");
return false;
}
}
private ParseGeoPoint geoPointFromLocation(Location loc) {
return new ParseGeoPoint(loc.getLatitude(), loc.getLongitude());
}
/*
* Displays a circle on the map representing the search radius
*/
private void updateCircle(LatLng myLatLng) {
if (mapCircle == null) {
mapCircle =
mapFragment.getMap().addCircle(
new CircleOptions().center(myLatLng).radius(radius * METERS_PER_FEET));
int baseColor = Color.DKGRAY;
mapCircle.setStrokeColor(baseColor);
mapCircle.setStrokeWidth(2);
mapCircle.setFillColor(Color.argb(50, Color.red(baseColor), Color.green(baseColor),
Color.blue(baseColor)));
}
mapCircle.setCenter(myLatLng);
mapCircle.setRadius(radius * METERS_PER_FEET); // Convert radius in feet to meters.
}
/*
* Zooms the map to show the area of interest based on the search radius
*/
private void updateZoom(LatLng myLatLng) {
// Get the bounds to zoom to
LatLngBounds bounds = calculateBoundsWithCenter(myLatLng);
/*
* Zoom to the given bounds (old bound method)
* mapFragment.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 5));
*/
// new method not in max zoom
mapFragment.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 5));
}
/*
* Helper method to calculate the offset for the bounds used in map zooming
*/
private double calculateLatLngOffset(LatLng myLatLng, boolean bLatOffset) {
// The return offset, initialized to the default difference
double latLngOffset = OFFSET_CALCULATION_INIT_DIFF;
// Set up the desired offset distance in meters
float desiredOffsetInMeters = radius * METERS_PER_FEET;
// Variables for the distance calculation
float[] distance = new float[1];
boolean foundMax = false;
double foundMinDiff = 0;
// Loop through and get the offset
do {
// Calculate the distance between the point of interest
// and the current offset in the latitude or longitude direction
if (bLatOffset) {
Location.distanceBetween(myLatLng.latitude, myLatLng.longitude, myLatLng.latitude
+ latLngOffset, myLatLng.longitude, distance);
} else {
Location.distanceBetween(myLatLng.latitude, myLatLng.longitude, myLatLng.latitude,
myLatLng.longitude + latLngOffset, distance);
}
// Compare the current difference with the desired one
float distanceDiff = distance[0] - desiredOffsetInMeters;
if (distanceDiff < 0) {
// Need to catch up to the desired distance
if (!foundMax) {
foundMinDiff = latLngOffset;
// Increase the calculated offset
latLngOffset *= 2;
} else {
double tmp = latLngOffset;
// Increase the calculated offset, at a slower pace
latLngOffset += (latLngOffset - foundMinDiff) / 2;
foundMinDiff = tmp;
}
} else {
// Overshot the desired distance
// Decrease the calculated offset
latLngOffset -= (latLngOffset - foundMinDiff) / 2;
foundMax = true;
}
} while (Math.abs(distance[0] - desiredOffsetInMeters) > OFFSET_CALCULATION_ACCURACY);
return latLngOffset;
}
/*
* Helper method to calculate the bounds for map zooming
*/
LatLngBounds calculateBoundsWithCenter(LatLng myLatLng) {
// Create a bounds
LatLngBounds.Builder builder = LatLngBounds.builder();
// Calculate east/west points that should to be included
// in the bounds
double lngDifference = calculateLatLngOffset(myLatLng, false);
LatLng east = new LatLng(myLatLng.latitude, myLatLng.longitude + lngDifference);
builder.include(east);
LatLng west = new LatLng(myLatLng.latitude, myLatLng.longitude - lngDifference);
builder.include(west);
// Calculate north/south points that should to be included
// in the bounds
double latDifference = calculateLatLngOffset(myLatLng, true);
LatLng north = new LatLng(myLatLng.latitude + latDifference, myLatLng.longitude);
builder.include(north);
LatLng south = new LatLng(myLatLng.latitude - latDifference, myLatLng.longitude);
builder.include(south);
return builder.build();
}
/*
* Set up the query to update the map view
*/
public void doMapQuery() {
final int myUpdateNumber = ++mostRecentMapUpdate;
Location myLoc = (currentLocation == null) ? lastLocation : currentLocation;
// If location info isn't available, clean up any existing markers
if (myLoc == null) {
cleanUpMarkers(new HashSet<String>());
return;
}
final ParseGeoPoint myPoint = geoPointFromLocation(myLoc);
List<UserPhoto> objects = PhotoUtils.getInstance().updateUserPhotos();
if (myUpdateNumber != mostRecentMapUpdate) {
return;
}
// Posts to show on the map
Set<String> toKeep = new HashSet<String>();
// Loop through the results of the search
for (UserPhoto photo : objects) {
// Add this post to the list of map pins to keep
toKeep.add(photo.getObjectId());
// Check for an existing marker for this post
Marker oldMarker = mapMarkers.get(photo.getObjectId());
// Set up the map marker's location
MarkerOptions markerOpts =
new MarkerOptions().position(new LatLng(photo.getLocation().getLatitude(), photo
.getLocation().getLongitude()));
// Set up the marker properties based on if it is within the search radius
if (photo.getLocation().distanceInKilometersTo(myPoint) > radius * METERS_PER_FEET
/ METERS_PER_KILOMETER) {
// Check for an existing out of range marker
if (oldMarker != null) {
if (oldMarker.getSnippet() == null) {
// Out of range marker already exists, skip adding it
continue;
} else {
// Marker now out of range, needs to be refreshed
oldMarker.remove();
}
}
// Display a red marker with a predefined title and no snippet
markerOpts =
markerOpts.title(getResources().getString(R.string.post_out_of_range)).icon(
BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
} else {
// Check for an existing in range marker
if (oldMarker != null) {
if (oldMarker.getSnippet() != null) {
// In range marker already exists, skip adding it
continue;
} else {
// Marker now in range, needs to be refreshed
oldMarker.remove();
}
}
// Display a green marker with the post information
markerOpts =
markerOpts.title("TODO: Image thumbnail")//.snippet(photo.getUser().getUsername())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Set unlocked markers to green.
ArrayList<String> unlocked = (ArrayList) photo.getList("unlocked");
String username = ParseUser.getCurrentUser().getUsername();
if (unlocked != null && unlocked.contains(username)) {
markerOpts =
markerOpts.title("Unlocked")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
// Add a new marker
Marker marker = mapFragment.getMap().addMarker(markerOpts);
mapMarkers.put(photo.getObjectId(), marker);
markerPhotos.put(marker, photo);
if (photo.getObjectId().equals(selectedPostObjectId)) {
marker.showInfoWindow();
selectedPostObjectId = null;
}
}
// Clean up old markers.
cleanUpMarkers(toKeep);
}
/*
* Helper method to clean up old markers
*/
private void cleanUpMarkers(Set<String> markersToKeep) {
for (String objId : new HashSet<String>(mapMarkers.keySet())) {
if (!markersToKeep.contains(objId)) {
Marker marker = mapMarkers.get(objId);
marker.remove();
mapMarkers.get(objId).remove();
mapMarkers.remove(objId);
}
}
}
}
|
package com.zfdang.zsmth_android;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.zfdang.SMTHApplication;
import com.zfdang.zsmth_android.helpers.RecyclerViewUtil;
import com.zfdang.zsmth_android.models.Attachment;
import com.zfdang.zsmth_android.models.Board;
import com.zfdang.zsmth_android.models.ComposePostContext;
import com.zfdang.zsmth_android.models.Post;
import com.zfdang.zsmth_android.models.PostActionAlertDialogItem;
import com.zfdang.zsmth_android.models.PostListContent;
import com.zfdang.zsmth_android.models.Topic;
import com.zfdang.zsmth_android.newsmth.AjaxResponse;
import com.zfdang.zsmth_android.newsmth.SMTHHelper;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import java.util.HashMap;
import java.util.List;
import okhttp3.ResponseBody;
/**
* An activity representing a single Topic detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {@link BoardTopicActivity}.
*/
public class PostListActivity extends SMTHBaseActivity
implements View.OnClickListener, OnTouchListener, RecyclerViewGestureListener.OnItemLongClickListener, PopupLikeWindow.OnLikeInterface,
PopupForwardWindow.OnForwardInterface {
private static final String TAG = "PostListActivity";
public RecyclerView mRecyclerView = null;
private TextView mTitle = null;
private EditText mPageNo = null;
public int mCurrentPageNo = 1;
private String mFilterUser = null;
private Topic mTopic = null;
private SwipyRefreshLayout mSwipeRefreshLayout;
private String mFrom;
private GestureDetector mGestureDetector;
private LinearLayoutManager linearLayoutManager;
@Override protected void onDestroy() {
super.onDestroy();
SwipeBackHelper.onDestroy(this);
}
@Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
SwipeBackHelper.onPostCreate(this);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ComposePostActivity.COMPOSE_ACTIVITY_REQUEST_CODE) {
// returned from Compose activity, refresh current post
// TODO: check resultCode
reloadPostList();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SwipeBackHelper.onCreate(this);
setContentView(R.layout.activity_post_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.post_list_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
mTitle = (TextView) findViewById(R.id.post_list_title);
assert mTitle != null;
mPageNo = (EditText) findViewById(R.id.post_list_page_no);
assert mPageNo != null;
// define swipe refresh function
mSwipeRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.post_list_swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
@Override public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.TOP) {
// reload current page
reloadPostListWithoutAlert();
} else {
// load next page if available
goToNextPage();
}
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.post_list);
assert mRecyclerView != null;
mRecyclerView.addItemDecoration(
new DividerItemDecoration(this, LinearLayoutManager.VERTICAL, R.drawable.recyclerview_divider_gradient));
linearLayoutManager = new WrapContentLinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(new PostRecyclerViewAdapter(PostListContent.POSTS, this));
// holder.mView.setOnTouchListener(this); so the event will be sent from holder.mView
mGestureDetector = new GestureDetector(SMTHApplication.getAppContext(), new RecyclerViewGestureListener(this, mRecyclerView));
// get Board information from launcher
Intent intent = getIntent();
Topic topic = intent.getParcelableExtra(SMTHApplication.TOPIC_OBJECT);
assert topic != null;
mFrom = intent.getStringExtra(SMTHApplication.FROM_BOARD);
// now onCreateOptionsMenu(...) is called again
// invalidateOptionsMenu();
// Log.d(TAG, String.format("Load post list for topic = %s, source = %s", topic.toString(), mFrom));
// set onClick Lisetner for page navigator buttons
findViewById(R.id.post_list_first_page).setOnClickListener(this);
findViewById(R.id.post_list_pre_page).setOnClickListener(this);
findViewById(R.id.post_list_next_page).setOnClickListener(this);
findViewById(R.id.post_list_last_page).setOnClickListener(this);
findViewById(R.id.post_list_go_page).setOnClickListener(this);
LinearLayout navLayout = (LinearLayout) findViewById(R.id.post_list_action_layout);
if (Settings.getInstance().hasPostNavBar()) {
navLayout.setVisibility(View.VISIBLE);
} else {
navLayout.setVisibility(View.GONE);
}
initPostNavigationButtons();
if (mTopic == null || !mTopic.getTopicID().equals(topic.getTopicID()) || PostListContent.POSTS.size() == 0) {
// new topic, different topic, or no post loaded
mTopic = topic;
mFilterUser = null;
reloadPostList();
setTitle(mTopic.getBoardChsName() + " - ");
}
}
public void initPostNavigationButtons() {
int alphaValue = 50;
ImageButton imageButton;
imageButton = (ImageButton) findViewById(R.id.post_list_action_top);
imageButton.setAlpha(alphaValue);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.post_list_action_up);
imageButton.setAlpha(alphaValue);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.post_list_action_down);
imageButton.setAlpha(alphaValue);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.post_list_action_bottom);
imageButton.setAlpha(alphaValue);
imageButton.setOnClickListener(this);
}
public void clearLoadingHints() {
dismissProgress();
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
public void reloadPostListWithoutAlert() {
PostListContent.clear();
mRecyclerView.getAdapter().notifyDataSetChanged();
loadPostListByPages();
}
public void reloadPostList() {
showProgress(", ...");
reloadPostListWithoutAlert();
}
public void loadPostListByPages() {
final SMTHHelper helper = SMTHHelper.getInstance();
helper.wService.getPostListByPage(mTopic.getTopicURL(), mTopic.getTopicID(), mCurrentPageNo, mFilterUser)
.flatMap(new Function<ResponseBody, Observable<Post>>() {
@Override public Observable<Post> apply(@NonNull ResponseBody responseBody) throws Exception {
try {
String response = responseBody.string();
List<Post> posts = SMTHHelper.ParsePostListFromWWW(response, mTopic);
return Observable.fromIterable(posts);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Post>() {
@Override public void onSubscribe(@NonNull Disposable disposable) {
}
@Override public void onNext(@NonNull Post post) {
// Log.d(TAG, post.toString());
PostListContent.addItem(post);
mRecyclerView.getAdapter().notifyItemInserted(PostListContent.POSTS.size() - 1);
}
@Override public void onError(@NonNull Throwable e) {
clearLoadingHints();
Toast.makeText(SMTHApplication.getAppContext(), "\n" + e.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onComplete() {
String title = String.format("[%d/%d] %s", mCurrentPageNo, mTopic.getTotalPageNo(), mTopic.getTitle());
mTitle.setText(title);
mPageNo.setText(String.format("%d", mCurrentPageNo));
clearLoadingHints();
}
});
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_list_menu, menu);
MenuItem item = menu.findItem(R.id.post_list_action_enter_board);
if (SMTHApplication.FROM_BOARD_BOARD.equals(mFrom)) {
// from BoardTopicActivity
item.setVisible(false);
} else if (SMTHApplication.FROM_BOARD_HOT.equals(mFrom)) {
// from HotTopicFragment
item.setVisible(true);
}
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
onBackPressed();
return true;
} else if (id == R.id.post_list_action_refresh) {
reloadPostList();
} else if (id == R.id.post_list_action_enter_board) {
Board board = new Board("", mTopic.getBoardChsName(), mTopic.getBoardEngName());
Intent intent = new Intent(this, BoardTopicActivity.class);
intent.putExtra(SMTHApplication.BOARD_OBJECT, (Parcelable) board);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override public void onClick(View v) {
// page navigation buttons
switch (v.getId()) {
case R.id.post_list_first_page:
if (mCurrentPageNo == 1) {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
} else {
mCurrentPageNo = 1;
reloadPostList();
}
break;
case R.id.post_list_pre_page:
if (mCurrentPageNo == 1) {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
} else {
mCurrentPageNo -= 1;
reloadPostList();
}
break;
case R.id.post_list_next_page:
goToNextPage();
break;
case R.id.post_list_last_page:
if (mCurrentPageNo == mTopic.getTotalPageNo()) {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
} else {
mCurrentPageNo = mTopic.getTotalPageNo();
reloadPostList();
}
break;
case R.id.post_list_go_page:
int pageNo;
try {
pageNo = Integer.parseInt(mPageNo.getText().toString());
if (mCurrentPageNo == pageNo) {
Toast.makeText(PostListActivity.this, String.format("%d", pageNo), Toast.LENGTH_SHORT).show();
} else if (pageNo >= 1 && pageNo <= mTopic.getTotalPageNo()) {
mCurrentPageNo = pageNo;
// turn off keyboard
mPageNo.clearFocus();
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(mPageNo.getWindowToken(), 0);
// jump now
reloadPostList();
} else {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
}
break;
case R.id.post_list_action_top:
mRecyclerView.scrollToPosition(0);
break;
case R.id.post_list_action_up:
int prevPos = linearLayoutManager.findFirstVisibleItemPosition() - 1;
if (prevPos >= 0) {
mRecyclerView.smoothScrollToPosition(prevPos);
}
break;
case R.id.post_list_action_down:
int nextPos = linearLayoutManager.findLastVisibleItemPosition() + 1;
if (nextPos < mRecyclerView.getAdapter().getItemCount()) {
mRecyclerView.smoothScrollToPosition(nextPos);
}
break;
case R.id.post_list_action_bottom:
mRecyclerView.scrollToPosition(mRecyclerView.getAdapter().getItemCount() - 1);
break;
}
}
public void goToNextPage() {
if (mCurrentPageNo == mTopic.getTotalPageNo()) {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
clearLoadingHints();
} else {
mCurrentPageNo += 1;
reloadPostList();
}
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Settings.getInstance().isVolumeKeyScroll() && (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
RecyclerViewUtil.ScrollRecyclerViewByKey(mRecyclerView, keyCode);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
// disable the beep sound when volume up/down is pressed
if (Settings.getInstance().isVolumeKeyScroll() && (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override public boolean onItemLongClicked(final int position, View v) {
if (position == RecyclerView.NO_POSITION || position >= PostListContent.POSTS.size()) return false;
Log.d(TAG, String.format("Post by %s is long clicked", PostListContent.POSTS.get(position).getAuthor()));
final PostActionAlertDialogItem[] menuItems = {
new PostActionAlertDialogItem(getString(R.string.post_reply_post), R.drawable.ic_reply_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_like_post), R.drawable.like_black),
new PostActionAlertDialogItem(getString(R.string.post_reply_mail), R.drawable.ic_email_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_query_author), R.drawable.ic_person_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_filter_author), R.drawable.ic_find_in_page_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_copy_content), R.drawable.ic_content_copy_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_foward), R.drawable.ic_send_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_view_in_browser), R.drawable.ic_open_in_browser_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_share), R.drawable.ic_share_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_delete_post), R.drawable.ic_delete_black_48dp),
new PostActionAlertDialogItem(getString(R.string.post_edit_post), R.drawable.ic_edit_black_48dp),
};
ListAdapter adapter = new ArrayAdapter<PostActionAlertDialogItem>(getApplicationContext(), R.layout.post_popup_menu_item, menuItems) {
ViewHolder holder;
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.post_popup_menu_item, null);
holder = new ViewHolder();
holder.mIcon = (ImageView) convertView.findViewById(R.id.post_popupmenu_icon);
holder.mTitle = (TextView) convertView.findViewById(R.id.post_popupmenu_title);
convertView.setTag(holder);
} else {
// view already defined, retrieve view holder
holder = (ViewHolder) convertView.getTag();
}
holder.mTitle.setText(menuItems[position].text);
holder.mIcon.setImageResource(menuItems[position].icon);
return convertView;
}
class ViewHolder {
ImageView mIcon;
TextView mTitle;
}
};
AlertDialog dialog = new AlertDialog.Builder(this).setTitle(getString(R.string.post_alert_title))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onPostPopupMenuItem(position, which);
}
})
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
dialog.show();
return true;
}
private void onPostPopupMenuItem(int position, int which) {
// Log.d(TAG, String.format("MenuItem %d was clicked", which));
if (position >= PostListContent.POSTS.size()) {
Log.e(TAG, "onPostPopupMenuItem: " + "Invalid Post index" + position);
return;
}
Post post = PostListContent.POSTS.get(position);
if (which == 0) {
// post_reply_post
ComposePostContext postContext = new ComposePostContext();
postContext.setBoardEngName(mTopic.getBoardEngName());
postContext.setPostId(post.getPostID());
postContext.setPostTitle(mTopic.getTitle());
postContext.setPostAuthor(post.getRawAuthor());
postContext.setPostContent(post.getRawContent());
postContext.setComposingMode(ComposePostContext.MODE_REPLY_POST);
Intent intent = new Intent(this, ComposePostActivity.class);
intent.putExtra(SMTHApplication.COMPOSE_POST_CONTEXT, postContext);
startActivityForResult(intent, ComposePostActivity.COMPOSE_ACTIVITY_REQUEST_CODE);
} else if (which == 1) {
// like
// Toast.makeText(PostListActivity.this, "Like:TBD", Toast.LENGTH_SHORT).show();
PopupLikeWindow popup = new PopupLikeWindow();
popup.initPopupWindow(this);
popup.showAtLocation(mRecyclerView, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 100);
} else if (which == 2) {
// post_reply_mail
// Toast.makeText(PostListActivity.this, ":TBD", Toast.LENGTH_SHORT).show();
ComposePostContext postContext = new ComposePostContext();
postContext.setBoardEngName(mTopic.getBoardEngName());
postContext.setPostId(post.getPostID());
postContext.setPostTitle(mTopic.getTitle());
postContext.setPostAuthor(post.getRawAuthor());
postContext.setPostContent(post.getRawContent());
postContext.setComposingMode(ComposePostContext.MODE_REPLY_MAIL);
Intent intent = new Intent(this, ComposePostActivity.class);
intent.putExtra(SMTHApplication.COMPOSE_POST_CONTEXT, postContext);
startActivity(intent);
} else if (which == 3) {
// post_query_author
Intent intent = new Intent(this, QueryUserActivity.class);
intent.putExtra(SMTHApplication.QUERY_USER_INFO, post.getRawAuthor());
startActivity(intent);
} else if (which == 4) {
// read posts from current users only
if (mFilterUser == null) {
Toast.makeText(PostListActivity.this, "ID! .", Toast.LENGTH_SHORT).show();
mFilterUser = post.getRawAuthor();
} else {
Toast.makeText(PostListActivity.this, "!", Toast.LENGTH_SHORT).show();
mFilterUser = null;
}
mCurrentPageNo = 1;
reloadPostList();
} else if (which == 5) {
// copy post content
String content;
if (post != null) {
content = post.getRawContent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final android.content.ClipboardManager clipboardManager =
(android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
final android.content.ClipData clipData = android.content.ClipData.newPlainText("PostContent", content);
clipboardManager.setPrimaryClip(clipData);
} else {
final android.text.ClipboardManager clipboardManager =
(android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(content);
}
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(PostListActivity.this, "", Toast.LENGTH_SHORT).show();
}
} else if (which == 6) {
// post_foward_self
// Toast.makeText(PostListActivity.this, ":TBD", Toast.LENGTH_SHORT).show();
PopupForwardWindow popup = new PopupForwardWindow();
popup.initPopupWindow(this, post);
popup.showAtLocation(mRecyclerView, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 100);
} else if (which == 7) {
// open post in browser
String url = String.format("http://m.newsmth.net/article/%s/%s?p=%d", mTopic.getBoardEngName(), mTopic.getTopicID(), mCurrentPageNo);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} else if (which == 8) {
// post_share
// Toast.makeText(PostListActivity.this, ":TBD", Toast.LENGTH_SHORT).show();
sharePost(post);
} else if (which == 9) {
// delete post
deletePost(post);
} else if (which == 10) {
// edit post
ComposePostContext postContext = new ComposePostContext();
postContext.setBoardEngName(mTopic.getBoardEngName());
postContext.setPostId(post.getPostID());
postContext.setPostTitle(mTopic.getTitle());
postContext.setPostAuthor(post.getRawAuthor());
postContext.setPostContent(post.getRawContent());
postContext.setComposingMode(ComposePostContext.MODE_EDIT_POST);
Intent intent = new Intent(this, ComposePostActivity.class);
intent.putExtra(SMTHApplication.COMPOSE_POST_CONTEXT, postContext);
startActivity(intent);
}
}
public void deletePost(Post post) {
SMTHHelper helper = SMTHHelper.getInstance();
helper.wService.deletePost(mTopic.getBoardEngName(), post.getPostID()).map(new Function<ResponseBody, String>() {
@Override public String apply(@NonNull ResponseBody responseBody) throws Exception {
try {
String response = SMTHHelper.DecodeResponseFromWWW(responseBody.bytes());
return SMTHHelper.parseDeleteResponse(response);
} catch (Exception e) {
Log.e(TAG, "call: " + Log.getStackTraceString(e));
}
return null;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
@Override public void onSubscribe(@NonNull Disposable disposable) {
}
@Override public void onNext(@NonNull String s) {
Toast.makeText(PostListActivity.this, s, Toast.LENGTH_LONG).show();
}
@Override public void onError(@NonNull Throwable e) {
Toast.makeText(PostListActivity.this, "\n" + e.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onComplete() {
}
});
}
public void sharePost(Post post) {
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
//sso
oks.disableSSOWhenAuthorize();
// prepare information from the post
String title = String.format("[%s] %s @ ", mTopic.getBoardChsName(), mTopic.getTitle());
String postURL =
String.format("http://m.newsmth.net/article/%s/%s?p=%d", mTopic.getBoardEngName(), mTopic.getTopicID(), mCurrentPageNo);
String content = String.format("[%s]: %s", post.getAuthor(), post.getRawContent());
// the max length of webo is 140
if (content.length() > 110) {
content = content.substring(0, 110);
}
content += String.format("...\nLink:%s", postURL);
// default: use zSMTH logo
String imageURL = "http://zsmth-android.zfdang.com/zsmth.png";
List<Attachment> attaches = post.getAttachFiles();
if (attaches != null && attaches.size() > 0) {
// use the first attached image
imageURL = attaches.get(0).getResizedImageSource();
}
// more information about OnekeyShare
// titleQQQQ
oks.setTitle(title);
// titleUrlLinked-in,QQQQ
// text
oks.setText(content);
// imageUrlQQLinked-In
oks.setImageUrl(imageURL);
// imagePathLinked-In
//oks.setImagePath("/sdcard/test.jpg");//SDcard
// url
oks.setUrl(postURL);
// commentQQ
// oks.setComment("");
// siteQQ
// oks.setSite("ShareSDK");
// siteUrlQQ
// set callback functions
oks.setCallback(new PlatformActionListener() {
@Override public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
Toast.makeText(PostListActivity.this, "!", Toast.LENGTH_SHORT).show();
}
@Override public void onError(Platform platform, int i, Throwable throwable) {
Toast.makeText(PostListActivity.this, ":\n" + throwable.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onCancel(Platform platform, int i) {
}
});
// GUI
oks.show(this);
}
@Override public boolean onTouch(View v, MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return false;
}
@Override public void OnLikeAction(String score, String msg) {
// Log.d(TAG, "OnLikeAction: " + score + msg);
SMTHHelper helper = SMTHHelper.getInstance();
helper.wService.addLike(mTopic.getBoardEngName(), mTopic.getTopicID(), score, msg, "")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<AjaxResponse>() {
@Override public void onSubscribe(@NonNull Disposable disposable) {
}
@Override public void onNext(@NonNull AjaxResponse ajaxResponse) {
// Log.d(TAG, "onNext: " + ajaxResponse.toString());
if (ajaxResponse.getAjax_st() == AjaxResponse.AJAX_RESULT_OK) {
Toast.makeText(PostListActivity.this, ajaxResponse.getAjax_msg(), Toast.LENGTH_SHORT).show();
reloadPostList();
} else {
Toast.makeText(PostListActivity.this, ajaxResponse.toString(), Toast.LENGTH_LONG).show();
}
}
@Override public void onError(@NonNull Throwable e) {
Toast.makeText(PostListActivity.this, "Like!\n" + e.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onComplete() {
}
});
}
@Override public void OnForwardAction(Post post, String target, boolean threads, boolean noref, boolean noatt) {
// Log.d(TAG, "OnForwardAction: ");
String strThreads = null;
if (threads) strThreads = "on";
String strNoref = null;
if (noref) strNoref = "on";
String strNoatt = null;
if (noatt) strNoatt = "on";
String strNoansi = null;
if (target != null && target.contains("@")) strNoansi = "on";
SMTHHelper helper = SMTHHelper.getInstance();
helper.wService.forwardPost(mTopic.getBoardEngName(), post.getPostID(), target, strThreads, strNoref, strNoatt, strNoansi)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<AjaxResponse>() {
@Override public void onSubscribe(@NonNull Disposable disposable) {
}
@Override public void onNext(@NonNull AjaxResponse ajaxResponse) {
// Log.d(TAG, "onNext: " + ajaxResponse.toString());
if (ajaxResponse.getAjax_st() == AjaxResponse.AJAX_RESULT_OK) {
Toast.makeText(PostListActivity.this, ajaxResponse.getAjax_msg(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(PostListActivity.this, ajaxResponse.toString(), Toast.LENGTH_LONG).show();
}
}
@Override public void onError(@NonNull Throwable e) {
Toast.makeText(PostListActivity.this, "\n" + e.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onComplete() {
}
});
}
@Override public void OnRePostAction(Post post, String target, String outgo) {
SMTHHelper helper = SMTHHelper.getInstance();
helper.wService.repostPost(mTopic.getBoardEngName(), post.getPostID(), target, outgo).map(new Function<ResponseBody, String>() {
@Override public String apply(@NonNull ResponseBody responseBody) throws Exception {
try {
String response = SMTHHelper.DecodeResponseFromWWW(responseBody.bytes());
return SMTHHelper.parseRepostResponse(response);
} catch (Exception e) {
Log.e(TAG, "call: " + Log.getStackTraceString(e));
}
return null;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
@Override public void onSubscribe(@NonNull Disposable disposable) {
}
@Override public void onNext(@NonNull String s) {
Toast.makeText(SMTHApplication.getAppContext(), s, Toast.LENGTH_SHORT).show();
}
@Override public void onError(@NonNull Throwable e) {
Toast.makeText(SMTHApplication.getAppContext(), e.toString(), Toast.LENGTH_LONG).show();
}
@Override public void onComplete() {
}
});
}
}
|
package corp.mahisan.medicinastore;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter2 extends BaseAdapter{
String [] result,desc;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter2(ListView2 mainActivity, String[] prgmNameList, int[] prgmImages ,String[] prgmDesc) {
// TODO Auto-generated constructor stub
result=prgmNameList;
desc =prgmDesc;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv,desc;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list1, null);
holder.desc=(TextView) rowView.findViewById(R.id.desc);
holder.tv=(TextView) rowView.findViewById(R.id.title);
holder.img=(ImageView) rowView.findViewById(R.id.imageView2);
holder.tv.setText(result[position]);
holder.desc.setText(desc[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int i = position;
if(i==0){
context.startActivity(new Intent(context,Fetch_Medicine.class));
}
if(i==1){
context.startActivity(new Intent(context,Disease_info.class));
}
if(i==2){
context.startActivity(new Intent(context,Medicine_info.class));
}
if(i==3){
context.startActivity(new Intent(context,Theraphy.class));
}
if(i==4){
context.startActivity(new Intent(context,Quit_Smoking.class));
}
if(i==5){
context.startActivity(new Intent(context,Mood_Scanner.class));
}
if(i==6){
context.startActivity(new Intent(context,Hypnotize.class));
}
if(i==7){
context.startActivity(new Intent(context,Fringe.class));
}
}
});
return rowView;
}
}
|
package de.klaushackner.breathalyzer.model;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Recipe {
private MixtureImage image;
private String name;
private String text;
private Ingredient[] ingredients;
public Recipe(MixtureImage image, String name, String text, Ingredient[] ingredients) {
this.image = image;
this.text = text;
this.name = name;
this.ingredients = ingredients;
}
public Recipe(JSONObject recipeAsJSON) {
try {
this.image = MixtureImage.fromString(recipeAsJSON.getString("image"));
this.name = recipeAsJSON.getString("name");
this.text = recipeAsJSON.getString("text");
JSONArray ingr = recipeAsJSON.getJSONArray("ingredients");
ingredients = new Ingredient[ingr.length()];
for (int i = 0; i < ingr.length(); i++) {
this.ingredients[i] = new Ingredient(new JSONObject(ingr.get(i).toString()));
}
for (int i = 0; i < ingr.length(); i++) {
ingredients[i] = new Ingredient(new JSONObject(ingr.get(i).toString()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.toJSON().toString();
}
public JSONObject toJSON() {
JSONObject j = new JSONObject();
try {
j.put("image", image.toString());
j.put("name", name);
j.put("text", text);
JSONArray ingr = new JSONArray();
for (Ingredient i : ingredients) {
ingr.put(i.toString());
}
j.put("ingredients", ingr);
} catch (JSONException e) {
e.printStackTrace();
}
return j;
}
public MixtureImage getImage() {
return image;
}
public void setImage(MixtureImage image) {
this.image = image;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public double getAmount() {
double amount = 0;
for (Ingredient ingr : ingredients) {
if (ingr.getPercentage() != 0) {
amount += ingr.getAmount();
}
}
return amount;
}
public double getPercentage() {
double a = 0;
for (Ingredient ingr : ingredients) {
a += (ingr.getAmount() * ingr.getPercentage());
}
if (getAmount() > 0) {
return a / getAmount();
} else {
return 0;
}
}
public static Recipe[] getRecipeArray(Context c) {
try {
JSONArray customRecipe = getCustomRecipes(c);
//Add new recipes here!
JSONArray recipes = new JSONArray("[]");
recipes.put(new Recipe(
MixtureImage.cocktail2,
"Sex On The Beach",
"Zutaten mit Eiswürfeln shaken\n\nGlas: Longdrinkglas\nDekoration mit ½ Orangenscheibe, Ananas, Kirsche",
new Ingredient[]{
new Ingredient("Wodka Gorbatschow (37,5%)", 0.375, 40),
new Ingredient("Pfirsichlikör (17%)", 0.17, 20),
new Ingredient("Orangensaft", 0, 40),
new Ingredient("Cranberrysaft", 0, 40)}));
recipes.put(new Recipe(
MixtureImage.cocktail,
"Mojito",
"Ein Rum-Cocktail mit kubanischer Note.\n1.\tMinze, Limettensaft und Zucker in ein Glas geben\n" +
"2.\tMit Stößel leicht andrücken.\n" +
"3.\tGlas mit Eiswürfeln auffüllen und Rum hinzugeben.\n" +
"4.\tGut verrühren und mit Soda auffüllen.\n\nGlas: Longdrinkglas\nDekoration mit Minzzweig, Limetten",
new Ingredient[]{
new Ingredient("Rum, weiß (37,5%)", 0.375, 40),
new Ingredient("Limettensaft", 0, 20),
new Ingredient("Rohrzucker (2 Löffel)", 0, 10),
new Ingredient("Minzblätter, frisch", 0, 2),
new Ingredient("Soda/Wasser congas", 0, 330)}));
recipes.put(new Recipe(
MixtureImage.cocktail2,
"Island Mule",
"Ein Rum-Cocktail mit original kubanischer Note.\nZutaten mit Eiswürfel in den Kupferbecher geben\n\nGlas: Kupfertasse\nDekoration mit Vanille, Orangenzeste",
new Ingredient[]{
new Ingredient("Pott Rum (54%)", 0.54, 50),
new Ingredient("Limette", 0, 10),
new Ingredient("Vanillesirup", 0, 20),
new Ingredient("Bitterorangen-Likör (Spritzer)", 0, 1),
new Ingredient("Ginger Beer", 0, 100)}));
recipes.put(new Recipe(
MixtureImage.cocktail2,
"Touch Down",
"1.\tZutaten außer Grenadine mit Eis shaken und in das Glas geben.\n" +
"2.\tGrenadine ins Glas geben und vorsichtig umrühren.\n\nGlas: Lang, dünn (Fancy)\nDekoration mit ½ Maracujascheibe",
new Ingredient[]{
new Ingredient("Wodka Gorbatschow (37,5%)", 0.375, 40),
new Ingredient("Apricot Brandy (24%)", 0.24, 20),
new Ingredient("Zitronensaft", 0, 20),
new Ingredient("Grenadine", 0, 1),
new Ingredient("Maracujasaft", 0, 80)}));
recipes.put(new Recipe(
MixtureImage.cocktail,
"Pina Colada",
"Zutaten erst ohne, nach 10 Sekunden mit Eiswürfeln shaken\n\nGlas: Lang, dünn (Fancy)\nDekoration mit Ananasstück, Trinkhalm",
new Ingredient[]{
new Ingredient("Eiswürfel", 0, 4),
new Ingredient("Rum, weiß (37,5%)", 0.375, 60),
new Ingredient("Sahne", 0, 20),
new Ingredient("Kokoslikör/Malibu (21%)", 0.21, 40),
new Ingredient("Ananassaft", 0, 120),
new Ingredient("Crushed-Ice (2 EL)", 0, 2),
new Ingredient("frische Ananas", 0, 1)}));
for (int i = 0; i < customRecipe.length(); i++) {
recipes.put(customRecipe.get(i).toString());
}
final Recipe[] recipeArray = new Recipe[recipes.length()];
for (int i = 0; i < recipes.length(); i++) {
recipeArray[i] = new Recipe(new JSONObject(recipes.get(i).toString()));
}
return recipeArray;
} catch (JSONException e) {
e.printStackTrace();
}
return new Recipe[0];
}
public static JSONArray getCustomRecipes(Context c) {
try {
SharedPreferences sharedPref = c.getSharedPreferences("data", 0);
return new JSONArray(sharedPref.getString("customRecipes", "[]"));
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONArray();
}
public static void addCustomRecipe(Context c, Recipe r) {
try {
SharedPreferences sharedPref = c.getSharedPreferences("data", 0);
SharedPreferences.Editor editor = sharedPref.edit();
JSONArray recipes = new JSONArray(sharedPref.getString("customRecipes", "[]"));
recipes.put(r.toString());
editor.putString("customRecipes", recipes.toString());
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void removeCustomRecipe(Context c, Recipe r) {
try {
SharedPreferences sharedPref = c.getSharedPreferences("data", 0);
SharedPreferences.Editor editor = sharedPref.edit();
JSONArray recipes = new JSONArray(sharedPref.getString("customRecipes", "[]"));
for (int i = 0; i < recipes.length(); i++) {
if (recipes.get(i).toString().compareTo(r.toString()) == 0) {
recipes.remove(i);
break; //break prevents removing every recipe matching to the given recipe (helpful if you addCustomRecipe the same recipe two times and want to remove it)
}
}
editor.putString("customRecipes", recipes.toString());
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
public Ingredient[] getIngredients() {
return ingredients;
}
}
|
package fr.free.nrw.commons.nearby;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.theme.NavigationBaseActivity;
import fr.free.nrw.commons.utils.UriSerializer;
import timber.log.Timber;
public class NearbyActivity extends NavigationBaseActivity {
@BindView(R.id.progressBar)
ProgressBar progressBar;
private boolean isMapViewActive = false;
private static final int LOCATION_REQUEST = 1;
private LocationServiceManager locationManager;
private LatLng curLatLang;
private Bundle bundle;
private NearbyAsyncTask nearbyAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
ButterKnife.bind(this);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
checkLocationPermission();
bundle = new Bundle();
initDrawer();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_nearby, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_refresh:
refreshView();
return true;
case R.id.action_map:
showMapView();
if (isMapViewActive) {
item.setIcon(R.drawable.ic_list_white_24dp);
} else {
item.setIcon(R.drawable.ic_map_white_24dp);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startLookingForNearby() {
locationManager = new LocationServiceManager(this);
locationManager.registerLocationManager();
curLatLang = locationManager.getLatestLocation();
nearbyAsyncTask = new NearbyAsyncTask(this);
nearbyAsyncTask.execute();
}
private void checkLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
startLookingForNearby();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST);
}
} else {
startLookingForNearby();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLookingForNearby();
} else {
if (nearbyAsyncTask != null) {
nearbyAsyncTask.cancel(true);
}
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment noPermissionsFragment = new NoPermissionsFragment();
fragmentTransaction.replace(R.id.container, noPermissionsFragment);
fragmentTransaction.commit();
}
}
}
}
protected void checkGps() {
LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Timber.d("GPS is not enabled");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(R.string.gps_disabled)
.setCancelable(false)
.setPositiveButton(R.string.enable_gps,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Timber.d("Loaded settings page");
startActivityForResult(callGPSSettingIntent, 1);
}
});
alertDialogBuilder.setNegativeButton(R.string.menu_cancel_upload,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
} else {
Timber.d("GPS is enabled");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
Timber.d("User is back from Settings page");
refreshView();
}
}
private void showMapView() {
if (!isMapViewActive) {
isMapViewActive = true;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setMapFragment();
}
} else {
isMapViewActive = false;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setListFragment();
}
}
}
@Override
protected void onResume() {
super.onResume();
checkGps();
}
@Override
protected void onPause() {
super.onPause();
if (nearbyAsyncTask != null) {
nearbyAsyncTask.cancel(true);
}
}
protected void refreshView() {
nearbyAsyncTask = new NearbyAsyncTask(this);
nearbyAsyncTask.execute();
}
public LocationServiceManager getLocationManager() {
return locationManager;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.unregisterLocationManager();
}
}
private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
private Context mContext;
private NearbyAsyncTask (Context context) {
mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected List<Place> doInBackground(Void... params) {
return NearbyController
.loadAttractionsFromLocation(curLatLang, CommonsApplication.getInstance()
);
}
@Override
protected void onPostExecute(List<Place> placeList) {
super.onPostExecute(placeList);
if (isCancelled()) {
return;
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriSerializer())
.create();
String gsonPlaceList = gson.toJson(placeList);
String gsonCurLatLng = gson.toJson(curLatLang);
if (placeList.size() == 0) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, R.string.no_nearby, duration);
toast.show();
}
bundle.clear();
bundle.putString("PlaceList", gsonPlaceList);
bundle.putString("CurLatLng", gsonCurLatLng);
// Begin the transaction
if (isMapViewActive) {
setMapFragment();
} else {
setListFragment();
}
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
}
/**
* Calls fragment for map view.
*/
public void setMapFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyMapFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
/**
* Calls fragment for list view.
*/
public void setListFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyListFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
public static void startYourself(Context context) {
Intent settingsIntent = new Intent(context, NearbyActivity.class);
context.startActivity(settingsIntent);
}
}
|
package g0v.ly.android.legislator;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import g0v.ly.android.R;
import g0v.ly.android.rest.RESTMethods;
import g0v.ly.android.utility.FontManager;
import g0v.ly.android.utility.androidcharts.SpiderWebChart;
import g0v.ly.android.utility.androidcharts.TitleValueEntity;
public class FragmentProfile extends Fragment implements RESTMethods.RestApiCallback {
private static final Logger logger = LoggerFactory.getLogger(FragmentProfile.class);
// Legislators' profile info title
private static final int PROFILE_INFO_COUNT = 7;
private static final int PROFILE_INFO_AD = 0;
private static final int PROFILE_INFO_GENDER = 1;
private static final int PROFILE_INFO_PARTY = 2;
private static final int PROFILE_INFO_COUNTY = 3;
private static final int PROFILE_INFO_EDUCATION = 4;
private static final int PROFILE_INFO_EXPERIENCE = 5;
private static final int PROFILE_INFO_PHOTO = 6;
// RadarChart number
private static final int ABSENT_COUNT = 5;
private static final int NOT_VOTE_COUNT = 0;
private static final int CONSCIENCE_VOTE_COUNT = 1;
private static final int PRIMARY_PROPOSER_COUNT = 2;
private static final int LY_ABSENT_COUNT = 3;
private static final int COMMITTEE_ABSENT_COUNT = 4;
private TextView tvResponse;
private TextView tvProfileAd;
private TextView tvProfileGender;
private TextView tvProfileParty;
private TextView tvProfileCounty;
private TextView tvProfileEducation;
private TextView tvProfileExperience;
private ImageView imgProfile;
private Spinner legislatorNameSpinner;
List<TitleValueEntity> red_own = new ArrayList<TitleValueEntity>();
List<TitleValueEntity> blue_ave = new ArrayList<TitleValueEntity>();
List<List<TitleValueEntity>> data = new ArrayList<List<TitleValueEntity>>();
private RESTMethods restMethods;
private long totalSpendTime = 0;
private String[] legislatorNameArray;
private String[] legislatorProfileArray;
private String[] legislatorAbsentArray;
private boolean hasNextPage = true;
private SpiderWebChart spiderWebChart;
private Resources resources;
String[] webChartTitle;
// Key => legislator's name, Value => legislator's profile
private Map<String, String[]> legislatorListWithProfile = new HashMap<String, String[]>();
private Map<String, String[]> legislatorListWithAbsent = new HashMap<String, String[]>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resources = getResources();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
assert view != null;
setupUiComponents(view);
/* TODO ad selectable */
restMethods = new RESTMethods();
String getUrl = "https://twly.herokuapp.com/api/legislator_terms/?page=1&ad=8";
restMethods.restGet(getUrl, FragmentProfile.this);
setupOnclickListeners();
return view;
}
@Override
public void getDone(final String response, final long spendTime, int page) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject apiResponse = new JSONObject(response);
if (apiResponse.getString("next").equals("null")) {
hasNextPage = false;
}
JSONArray results = apiResponse.getJSONArray("results");
legislatorNameArray = new String[results.length()];
String[] legislatorProfileInfoApiKey =
resources.getStringArray(R.array.legislator_profile_info_api_key);
//Iris
String[] legislatorProfileRadarChartApiKey =
resources.getStringArray(R.array.legislator_profile_radar_chart_api_key);
for (int i = 0; i < results.length(); i++) {
// get legislator's name
JSONObject legislator = results.getJSONObject(i);
legislatorNameArray[i] = legislator.getString("name");
legislatorProfileArray = new String[PROFILE_INFO_COUNT];
legislatorAbsentArray = new String[ABSENT_COUNT];
// get legislator's profile
for (int j = 0; j < legislatorProfileArray.length; j++) {
switch (j) {
case 0:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_AD]);
break;
case 1:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_GENDER]);
break;
case 2:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_PARTY]);
break;
case 3:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_COUNTY]);
break;
case 4:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_EDUCATION]);
break;
case 5:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_EXPERIENCE]);
break;
case 6:
legislatorProfileArray[j] =
legislator.getString(legislatorProfileInfoApiKey[PROFILE_INFO_PHOTO]);
break;
}
}
// get legislator's absent counts
for (int j = 0; j < legislatorAbsentArray.length; j++) {
switch (j) {
case 0:
legislatorAbsentArray[j] =
legislator.getString(legislatorProfileRadarChartApiKey[NOT_VOTE_COUNT]);
break;
case 1:
legislatorAbsentArray[j] =
legislator.getString(legislatorProfileRadarChartApiKey[CONSCIENCE_VOTE_COUNT]);
break;
case 2:
legislatorAbsentArray[j] =
legislator.getString(legislatorProfileRadarChartApiKey[PRIMARY_PROPOSER_COUNT]);
break;
case 3:
legislatorAbsentArray[j] =
legislator.getString(legislatorProfileRadarChartApiKey[LY_ABSENT_COUNT]);
break;
case 4:
legislatorAbsentArray[j] =
legislator.getString(legislatorProfileRadarChartApiKey[COMMITTEE_ABSENT_COUNT]);
break;
}
}
legislatorListWithProfile.put(legislatorNameArray[i], legislatorProfileArray);
legislatorListWithAbsent.put(legislatorNameArray[i], legislatorAbsentArray);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
totalSpendTime += spendTime;
int legislatorCount = legislatorListWithProfile.keySet().size();
logger.debug("[Profile] getDone legislatorCount= " + legislatorCount);
updateTextView(tvResponse, "Legislator count = " + legislatorCount, TvUpdateType.OVERWRITE);
updateTextView(tvResponse, "Spend " + totalSpendTime / 1000 + "." + totalSpendTime % 1000 +
"s", TvUpdateType.APPEND);
Object[] NameObjArray = legislatorListWithProfile.keySet().toArray();
legislatorNameArray = new String[legislatorListWithProfile.size()]; // XXX, new 12 times
int nameArraySize = NameObjArray.length;
for (int i = 0; i < nameArraySize; i++) {
legislatorNameArray[i] = NameObjArray[i].toString();
}
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, legislatorNameArray);
legislatorNameSpinner.setAdapter(arrayAdapter);
// get rest profiles
if (hasNextPage) {
restMethods.restGet(
"https://twly.herokuapp.com/api/legislator_terms/?page=" + (page + 1) +
"&ad=8", FragmentProfile.this
);
} else {
logger.debug("[Profile] getDone hasNextPage = false");
}
}
private void setupOnclickListeners() {
legislatorNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position,
long l) {
Toast.makeText(getActivity(),
" " + legislatorNameArray[position], Toast.LENGTH_SHORT).show();
if (legislatorListWithProfile.containsKey(legislatorNameArray[position])) {
updateTextView(tvProfileAd, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_AD], TvUpdateType.OVERWRITE);
updateTextView(tvProfileGender, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_GENDER], TvUpdateType.OVERWRITE);
updateTextView(tvProfileParty, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_PARTY], TvUpdateType.OVERWRITE);
updateTextView(tvProfileCounty, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_COUNTY], TvUpdateType.OVERWRITE);
updateTextView(tvProfileEducation, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_EDUCATION], TvUpdateType.OVERWRITE);
updateTextView(tvProfileExperience, legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_EXPERIENCE], TvUpdateType.OVERWRITE);
updateSpiderWebChart(legislatorListWithAbsent.get(legislatorNameArray[position])[NOT_VOTE_COUNT],
legislatorListWithAbsent.get(legislatorNameArray[position])[CONSCIENCE_VOTE_COUNT],
legislatorListWithAbsent.get(legislatorNameArray[position])[PRIMARY_PROPOSER_COUNT],
legislatorListWithAbsent.get(legislatorNameArray[position])[LY_ABSENT_COUNT],
legislatorListWithAbsent.get(legislatorNameArray[position])[COMMITTEE_ABSENT_COUNT] );
GetImageFromUrl getImageFromUrl = new GetImageFromUrl();
getImageFromUrl.execute(legislatorListWithProfile.get(legislatorNameArray[position])[PROFILE_INFO_PHOTO]);
} else {
logger.warn("[onItemSelected] legislator profile not found");
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
// do nothing
}
});
}
private void updateTextView(TextView tv, String msg, TvUpdateType updateType) {
switch (updateType) {
case OVERWRITE:
tv.setText(msg);
break;
case APPEND:
CharSequence tempMsg = tv.getText();
tv.setText(msg + "\n");
if (tempMsg != null) {
tv.append(tempMsg);
}
break;
}
}
private void updateSpiderWebChart(String nvc, String cvc, String pbc, String lac, String cac){
// tvProfileAd.setText("hi " + msg);
red_own.set(0,new TitleValueEntity(webChartTitle[0], Float.parseFloat(nvc)/10)); // not_vote_count
red_own.set(1,new TitleValueEntity(webChartTitle[1], Float.parseFloat(cvc))); // conscience_vote_count
red_own.set(2,new TitleValueEntity(webChartTitle[2], Float.parseFloat(pbc)/10)); // primary_biller_count
red_own.set(3,new TitleValueEntity(webChartTitle[3], Float.parseFloat(lac))); // ly_absent_count
red_own.set(4,new TitleValueEntity(webChartTitle[4], Float.parseFloat(cac))); // committee_absent_count
//data.add(red_own);
data.set(0,red_own);
addRadarChartData(data);
spiderWebChart.setLatitudeNum(5);
spiderWebChart.refreshDrawableState();
spiderWebChart.invalidate();
//spiderWebChart = (SpiderWebChart) view.findViewById(R.id.profile_radar_chart);
}
// Put data in SpiderWebChart.
public void initSpiderWebChart() {
webChartTitle = resources.getStringArray(R.array.legislator_profile_radar_chart_title);
// TODO create with class
red_own.add(new TitleValueEntity(webChartTitle[0], 2)); // not_vote_count
red_own.add(new TitleValueEntity(webChartTitle[1], 4)); // conscience_vote_count
red_own.add(new TitleValueEntity(webChartTitle[2], 1)); // primary_biller_count
red_own.add(new TitleValueEntity(webChartTitle[3], 5)); // ly_absent_count
red_own.add(new TitleValueEntity(webChartTitle[4], 8)); // committee_absent_count
blue_ave.add(new TitleValueEntity(webChartTitle[0], 3));
blue_ave.add(new TitleValueEntity(webChartTitle[1], 4));
blue_ave.add(new TitleValueEntity(webChartTitle[2], 5));
blue_ave.add(new TitleValueEntity(webChartTitle[3], 6));
blue_ave.add(new TitleValueEntity(webChartTitle[4], 7));
data.add(red_own);
data.add(blue_ave);
addRadarChartData(data);
spiderWebChart.setLatitudeNum(5);//XXX method useless, check lib
}
//TODO check is data added before init chart
private void addRadarChartData(List<List<TitleValueEntity>> newData) {
List<List<TitleValueEntity>> radarChartData = new ArrayList<List<TitleValueEntity>>();
for (List<TitleValueEntity> aData : newData) {
radarChartData.add(aData);
}
spiderWebChart.setData(radarChartData);
}
private void setupUiComponents(View view) {
TextView tvProfileAdTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_ad_title);
TextView tvProfileGenderTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_gender_title);
TextView tvProfilePartyTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_party_title);
TextView tvProfileCountyTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_county_title);
TextView tvProfileEducationTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_education_title);
TextView tvProfileExperienceTitle =
(TextView) view.findViewById(R.id.legislator_profile_info_experience_title);
tvProfileAd = (TextView) view.findViewById(R.id.legislator_profile_info_ad);
tvProfileGender = (TextView) view.findViewById(R.id.legislator_profile_info_gender);
tvProfileParty = (TextView) view.findViewById(R.id.legislator_profile_info_party);
tvProfileCounty = (TextView) view.findViewById(R.id.legislator_profile_info_county);
tvProfileEducation = (TextView) view.findViewById(R.id.legislator_profile_info_education);
tvProfileExperience = (TextView) view.findViewById(R.id.legislator_profile_info_experience);
tvResponse = (TextView) view.findViewById(R.id.tv_response);
imgProfile = (ImageView) view.findViewById(R.id.profile_img);
legislatorNameSpinner = (Spinner) view.findViewById(R.id.spinner_legislator_name);
spiderWebChart = (SpiderWebChart) view.findViewById(R.id.profile_radar_chart);
initSpiderWebChart( );
view.setBackgroundColor(Color.WHITE);
// setup titles
String[] legislatorProfileInfo = resources.getStringArray(R.array.legislator_profile_info);
tvProfileAdTitle.setText(legislatorProfileInfo[PROFILE_INFO_AD]);
tvProfileGenderTitle.setText(legislatorProfileInfo[PROFILE_INFO_GENDER]);
tvProfilePartyTitle.setText(legislatorProfileInfo[PROFILE_INFO_PARTY]);
tvProfileCountyTitle.setText(legislatorProfileInfo[PROFILE_INFO_COUNTY]);
tvProfileEducationTitle.setText(legislatorProfileInfo[PROFILE_INFO_EDUCATION]);
tvProfileExperienceTitle.setText(legislatorProfileInfo[PROFILE_INFO_EXPERIENCE]);
}
public enum TvUpdateType {
APPEND,
OVERWRITE
}
private class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
@Override
protected void onPostExecute(Bitmap result) {
imgProfile.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
|
package it.playfellas.superapp.network;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
import com.squareup.otto.Subscribe;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import it.playfellas.superapp.events.NetEvent;
import it.playfellas.superapp.events.bt.BTDisconnectedEvent;
class MasterPeer extends Peer {
private Map<String, BTMasterThread> threadMap;
private static final String TAG = MasterPeer.class.getSimpleName();
private int iterationStep;
public MasterPeer() {
super();
threadMap = new LinkedHashMap<>(); // preserve insert order
iterationStep = 0;
TenBus.get().register(this);
}
@Subscribe
public synchronized void onDeviceDisconnected(BTDisconnectedEvent event) {
closeConnection(event.getDevice());
}
@Override
public synchronized void obtainConnection(BluetoothDevice device) {
if (threadMap.containsKey(device.getAddress())) {
Log.w(TAG, "Already connected to " + device.getName());
return;
}
try {
BTMasterThread btMasterThread = new BTMasterThread(device);
btMasterThread.start();
threadMap.put(device.getAddress(), btMasterThread);
} catch (IOException e) {
Log.e(TAG, "Error in instantiating master thread", e);
}
}
@Override
public synchronized void closeConnection(BluetoothDevice device) {
BTMasterThread removed = threadMap.remove(device.getAddress());
if (removed != null) {
removed.deactivate();
} else {
Log.w(TAG, "Non existing thread removed: " + device.getName());
}
int size = threadMap.size();
if (size > 0 && iterationStep >= size) {
iterationStep = size - 1;
}
}
@Override
public synchronized void close() {
for (Map.Entry<String, BTMasterThread> btMasterThread : threadMap.entrySet()) {
btMasterThread.getValue().deactivate();
}
}
@Override
public synchronized void sendMessage(NetEvent netEvent) throws IOException {
for (Map.Entry<String, BTMasterThread> btMasterThread : threadMap.entrySet()) {
btMasterThread.getValue().write(netEvent);
}
}
@Override
public synchronized int noDevices() {
return threadMap.size();
}
@Override
public boolean hasNext() {
return true;
}
@Override
public synchronized BluetoothDevice next() {
BluetoothDevice dev = (new ArrayList<>(threadMap.values())).get(iterationStep).getDevice();
iterationStep++;
int size = threadMap.size();
if (iterationStep >= size) {
iterationStep = 0; // circularity
}
return dev;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
package org.bobstuff.bobball.Menus;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import org.bobstuff.bobball.R;
import org.bobstuff.bobball.Statistics;
public class menuStatistics extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu_statistics);
String gamesPlayedText = getString(R.string.gamesPlayedText, Statistics.getPlayedGames());
String highestLevelText = getString(R.string.highestLevelText, Statistics.getTopLevel());
String levelSeriesText = getString(R.string.levelSeriesText, Statistics.getLongestSeries());
String highestLevelScoreText = getString(R.string.highestLevelScoreText, Statistics.getHighestLevelScore());
String topScoreText = getString(R.string.topScoreText, Statistics.getTopScore());
String timeLeftRecordText = getString(R.string.timeLeftRecordText, Statistics.getTimeLeftRecord());
String percentageClearedRecordText = getString(R.string.percentageClearedText, Statistics.getPercentageClearedRecord() + "%");
String livesLeftRecordText = getString(R.string.livesLeftRecordText, Statistics.getLivesLeftRecord());
String leastTimeLeftText = getString(R.string.leastTimeLeftText, Statistics.getLeastTimeLeft());
setTextViewText(R.id.gamesPlayed, gamesPlayedText);
setTextViewText(R.id.highestLevel, highestLevelText);
setTextViewText(R.id.levelSeries, levelSeriesText);
setTextViewText(R.id.highestLevelScore, highestLevelScoreText);
setTextViewText(R.id.topScore, topScoreText);
setTextViewText(R.id.timeLeftRecord, timeLeftRecordText);
setTextViewText(R.id.percentageClearedRecord, percentageClearedRecordText);
setTextViewText(R.id.livesLeftRecord,livesLeftRecordText);
setTextViewText(R.id.leastTimeLeft,leastTimeLeftText);
}
protected void setTextViewText (int textViewId, String text){
TextView textView = (TextView) findViewById(textViewId);
textView.setText(text);
}
public void goBack (View view) {
finish();
}
}
|
package ru.furry.furview2.drivers.e926;
import android.os.AsyncTask;
import android.util.Log;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import ru.furry.furview2.images.FurImage;
import ru.furry.furview2.images.FurImageBuilder;
import ru.furry.furview2.images.Rating;
import ru.furry.furview2.images.RemoteFurImage;
import ru.furry.furview2.system.Files;
import ru.furry.furview2.system.Utils;
public class DriverE926 {
private static final String SEARCH_PATH = "https://e926.net/post/index.xml";
private static final String CHARSET = "UTF-8";
protected static final int SEARCH_LIMIT = 50;
protected final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
protected final DateTimeFormatter formatter = DateTimeFormat.forPattern("EEE MMM DD kk:mm:ss Z yyyy");
protected final ImageLoader imageLoader = ImageLoader.getInstance();
protected final DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
protected String permanentStorage;
protected int previewWidth;
protected int previewHeight;
protected Proxy proxy;
public DriverE926(String permanentStorage, Utils.Tuple<Integer, Integer> preview) {
this.permanentStorage = permanentStorage;
this.previewHeight = preview.x;
this.previewWidth = preview.y;
checkPathStructure(permanentStorage);
}
public DriverE926(String permanentStorage, int previewWidth, int previewHeight) {
this.permanentStorage = permanentStorage;
this.previewHeight = previewHeight;
this.previewWidth = previewWidth;
checkPathStructure(permanentStorage);
}
public void setProxy(Proxy proxy) {
this.proxy = proxy;
// FOR DEBUG
Log.d("fgsfds", "Proxy used: " + Utils.getIP(proxy));
}
class IteratorE926 implements Iterator {
private String searchUrl;
private int currentPage = 1;
private HttpsURLConnection page;
private String searchQuery;
private AsyncTask<HttpsURLConnection, Void, List<RemoteFurImageE926>> readImagesTask;
private List<RemoteFurImageE926> readedImages = null;
public IteratorE926(String searchUrl, String searchQuery) throws IOException, SAXException, ParserConfigurationException {
this.searchUrl = searchUrl;
this.searchQuery = searchQuery;
URL query = makeURL(searchUrl, searchQuery, currentPage, SEARCH_LIMIT);
page = openPage(query);
startReadingImages(page);
}
private Rating makeRating(String sRating) {
Rating rating;
switch (sRating) {
case "s":
rating = Rating.SAFE;
break;
case "q":
rating = Rating.QUESTIONABLE;
break;
case "e":
rating = Rating.EXPLICIT;
break;
default:
rating = Rating.NA;
break;
}
return rating;
}
class ReadImages extends AsyncTask<HttpsURLConnection, Void, List<RemoteFurImageE926>> {
@Override
protected List<RemoteFurImageE926> doInBackground(HttpsURLConnection... httpsURLConnections) {
HttpsURLConnection connection = httpsURLConnections[0];
Document doc = null;
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(connection.getInputStream());
} catch (ParserConfigurationException | IOException | SAXException e) {
Utils.printError(e);
}
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("post");
ArrayList<RemoteFurImageE926> images = new ArrayList<>(SEARCH_LIMIT);
for (int postNumber = 0; postNumber < nList.getLength(); postNumber++) {
Node post = nList.item(postNumber);
Element element = (Element) post;
// Let's ignore swf and webm
if (element.getAttribute("file_ext").equals("webm") ||
element.getAttribute("file_ext").equals("swf"))
continue;
else
images.add(new RemoteFurImageE926Builder()
.setSearchQuery(searchQuery)
.setDescription(element.getAttribute("description"))
.setScore(Integer.parseInt(element.getAttribute("score")))
.setRating(makeRating(element.getAttribute("rating")))
.setFileUrl(element.getAttribute("file_url"))
.setFileExt(element.getAttribute("file_ext"))
.setPageUrl(null)
.setIdE926(Integer.parseInt(element.getAttribute("id")))
.setAuthor(element.getAttribute("author"))
.setCreatedAt(formatter.parseDateTime(element.getAttribute("created_at").replace(" 00", " 24")))
.setSources(Arrays.asList(element.getAttribute("sources").replace("["", "").replace(""]", "").split("","")))
.setTags(Arrays.asList(element.getAttribute("tags").split(" ")))
.setArtists(Arrays.asList(element.getAttribute("artist").replace("["", "").replace(""]", "").split("","")))
.setMd5(new BigInteger(element.getAttribute("md5"), 16))
.setFileSize(Integer.parseInt(element.getAttribute("file_size")))
.setFileWidth(Integer.parseInt(element.getAttribute("width")))
.setFileHeight(Integer.parseInt(element.getAttribute("height")))
.createRemoteFurImageE926());
}
return images;
}
}
private URL makeURL(String searchURL, String searchQuery, int page, int limit) throws MalformedURLException {
URL url = null;
try {
String query = String.format("%s?tags=%s&page=%s&limit=%s",
searchURL,
URLEncoder.encode(searchQuery, CHARSET),
page,
limit);
url = new URL(query);
} catch (UnsupportedEncodingException e) {
Utils.printError(e);
}
return url;
}
private void startReadingImages(HttpsURLConnection page) {
readImagesTask = new ReadImages().execute(page);
readedImages = null;
}
private List<RemoteFurImageE926> readImages() {
readImagesTask = null;
readedImages = null;
try {
startReadingImages(openPage(makeURL(searchUrl, searchQuery, currentPage, SEARCH_LIMIT)));
} catch (IOException e) {
Utils.printError(e);
}
try {
readedImages = readImagesTask.get();
} catch (InterruptedException | ExecutionException e) {
Utils.printError(e);
}
return readedImages;
}
private List<RemoteFurImageE926> getReadedImages() {
if (readedImages == null) {
return readImages();
} else {
return readedImages;
}
}
@Override
public boolean hasNext() {
RemoteFurImage image = null;
if (getReadedImages().size() > 0) {
image = getReadedImages().get(0);
} else {
currentPage += 1;
if (getReadedImages().size() > 0) {
image = getReadedImages().get(0);
}
}
return image != null;
}
@Override
public RemoteFurImage next() {
RemoteFurImageE926 image = getReadedImages().get(0);
getReadedImages().remove(0);
return image;
}
@Override
public void remove() {
getReadedImages().remove(0);
}
}
private FurImage remoteFurImagetoFurImageE926(RemoteFurImageE926 remoteImage) {
return new FurImageBuilder()
.makeFromRemoteFurImage(remoteImage)
.setScore(remoteImage.getScore())
.setAuthor(remoteImage.getAuthor())
.setCreatedAt(remoteImage.getCreatedAt())
.setSources(remoteImage.getSources())
.setTags(remoteImage.getTags())
.setArtists(remoteImage.getArtists())
.setMd5(remoteImage.getMd5())
.setFileSize(remoteImage.getFileSize())
.setFileWidth(remoteImage.getFileWidth())
.setFileHeight(remoteImage.getFileHeight())
.setDownloadedAt(new DateTime())
.createFurImage();
}
HttpsURLConnection openPage(URL url) throws IOException {
if (proxy != null) {
return (HttpsURLConnection) url.openConnection(proxy);
} else {
return (HttpsURLConnection) url.openConnection();
}
}
private void checkPathStructure(String path) {
try {
checkDir(new File(path));
checkDir(new File(String.format("%s/%s", path, Files.IMAGES)));
checkDir(new File(String.format("%s/%s", path, Files.THUMBS)));
} catch (IOException e) {
Utils.printError(e);
}
}
private void checkDir(File path) throws IOException {
if (!path.exists()) {
path.mkdirs();
} else if (!path.isDirectory()) {
path.delete();
path.mkdir();
}
}
private FurImage downloadImage(RemoteFurImageE926 remoteImage, ImageAware listener) throws IOException {
Log.d("fgsfds", remoteImage.getFileUrl());
imageLoader.displayImage(remoteImage.getFileUrl(), listener, displayOptions);
return remoteFurImagetoFurImageE926(remoteImage);
}
public Iterator<RemoteFurImageE926> search(String searchQuery) throws IOException, ParserConfigurationException, SAXException {
return new IteratorE926(SEARCH_PATH, searchQuery);
}
public List<FurImage> download(List<RemoteFurImageE926> images, List<? extends ImageAware> listeners) throws IOException {
List<FurImage> downloadedImages = new ArrayList<>(images.size());
for (int i = 0; i < images.size(); i++) {
downloadedImages.add(downloadImage(images.get(i), listeners.get(i)));
}
return downloadedImages;
}
}
|
package se.chalmers.pd.device;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import se.chalmers.pd.device.MqttWorker.MQTTCallback;
import se.chalmers.pd.device.SpotifyController.PlaylistCallback;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Patrik Thituson
*
*/
public class ApplicationController implements MQTTCallback, PlaylistCallback {
/**
* Callbacks that is used for the main activity to be able to update the
* view
*/
interface Callbacks {
void onPlayerLoggedIn();
void onPlayerPlay();
void onPlayerNext();
void onPlayerPause();
void onStartedApplication(String status);
void onInstalledApplication(boolean show);
void onConnectedMQTT(boolean connected);
void onDisconnectedMQTT(boolean success);
void onUpdateSeekbar(float position);
void onUpdatedPlaylist();
}
private Context context;
private MqttWorker mqttWorker;
private SpotifyController spotifyController;
private Callbacks callbacks;
private final String TOPIC_PLAYLIST = "/playlist",
TOPIC_PLAYLIST_1 = "/playlist/1",
TOPIC_INFOTAINMENT = "/sensor/infotainment",
TOPIC_SYSTEM = "/system",
PLAYLIST_ZIP = "Playlist.zip",
PLAYLIST_NAME = "playlist",
DATA = "data",
ARTIST = "artist",
TRACK = "track",
TRACK_LENGTH = "tracklength",
URI = "uri";
public ApplicationController(Context context) {
this.context = context;
this.callbacks = (Callbacks) context;
spotifyController = new SpotifyController(this, context);
mqttWorker = new MqttWorker(this);
}
/**
* Helper method that publish the playlist to the topic "/playlist" for
* testing purposes
*/
private void sendPlayList() {
List<Track> newPlaylist = new ArrayList<Track>();
String[] artists = { "Foo Fighters", "Nirvana", "Avicii" };
String[] tracks = { "The Pretender", "Rape me", "X You" };
String[] uris = { "spotify:track:3ZsjgLDSvusBgxGWrTAVto", "spotify:track:47KVHb6cOVBZbmXQweE5p7",
"spotify:track:330r0K82tIDVr6f1GezAd8" };
int[] lengths = { 270, 170, 200};
for (int i = 0; i < 3; i++) {
Track track = new Track(tracks[i], artists[i], uris[i], lengths[i]);
newPlaylist.add(track);
}
sendAllTracks(TOPIC_PLAYLIST, newPlaylist);
}
/**
* Forwards he login calls to the spotifycontroller
*/
public void login() {
spotifyController.login();
}
/**
* Callback that let us know we have succesfully logged in to spotify
*/
public void onLoginSuccess() {
callbacks.onPlayerLoggedIn();
}
/**
* Callback that let us know an error occured when logging in to spotify
*/
public void onLoginFailed(String message) {
}
/**
* Callback that is called when a song has succesfully started playing
*/
public void onPlay(boolean success) {
if (success) {
callbacks.onPlayerPlay();
}
}
/**
* Callback that is called when a song has succesfully paused playing
*/
public void onPause(boolean success) {
callbacks.onPlayerPause();
}
/**
* Callback that is called when a song has ended and calls the functon next
*/
public void onEndOfTrack() {
createAndPublishPlayerActions(Action.next);
callbacks.onPlayerNext();
}
/**
* Destroys the spotifycontroller and disconenct the broker to prevent any
* threads from crashing
*/
public void onDestroy() {
spotifyController.destroy();
mqttWorker.disconnect();
}
/**
* Connects to the mqtt broker
*/
public void connect(String url) {
mqttWorker = new MqttWorker(this);
mqttWorker.setBrokerURL(url);
mqttWorker.start();
}
/**
* Disconnects from the mqtt broker
*/
public void disconnect() {
mqttWorker.disconnect();
mqttWorker.interrupt();
}
/**
* Returns the current track selected in the playlist if
* existing, the string "No tracks available" otherwise
* @return
*/
public String getCurrentTrack() {
Track track = spotifyController.getCurrentTrack();
if (track != null) {
return track.getArtist() + " - " + track.getName();
} else
return context.getString(R.string.no_tracks_available);
}
/**
* Publish a seek message to the 'playlist' topic
* @param position
*/
public void seek(float position) {
JSONObject json = createJson(Action.seek, String.valueOf(position));
mqttWorker.publish(TOPIC_PLAYLIST, json.toString());
}
/**
* Callback from spotifycontroller that allows us to simulate
* timer.
* @param position
*/
public void onPositionChanged(float position) {
callbacks.onUpdateSeekbar(position);
}
/**
* Callback from Mqttworker thath handles all action-messages and performs
* the corresponding actions. Uses callbacks to notify the main activity that
* the state of the application has changed and an update of the UI could be
* required.
* and perform the corresponding action.
*/
public void onMessage(String topic, String payload) {
JSONObject json;
try {
json = new JSONObject(payload);
String action = json.optString(Action.action.toString());
String data = json.optString(ActionResponse.data.toString());
boolean success = data.equals(ActionResponse.success.toString());
switch (Action.valueOf(action)) {
case add:
addJsonTrackToPlaylist(json);
break;
case play:
spotifyController.play();
break;
case pause:
spotifyController.pause();
break;
case next:
spotifyController.playNext();
callbacks.onPlayerNext();
break;
case prev:
spotifyController.playPrevious();
callbacks.onPlayerNext();
break;
case install:
if (success) {
callbacks.onInstalledApplication(true);
} else if (data.equals(ActionResponse.error.toString())) {
callbacks.onInstalledApplication(false);
}
break;
case start:
if (success) {
sendPlayList();
}
callbacks.onStartedApplication(data);
break;
case stop:
spotifyController.pause();
spotifyController.clearPlaylist();
callbacks.onStartedApplication(action);
break;
case uninstall:
callbacks.onInstalledApplication(!success);
break;
case exist:
callbacks.onInstalledApplication(success);
break;
case get_all:
sendAllTracks(data, spotifyController.getPlaylist());
break;
case add_all:
JSONArray playlistArray = new JSONArray(data);
JSONObject jsonTrack;
for (int i = 0; i < playlistArray.length(); i++){
jsonTrack = new JSONObject(playlistArray.get(i).toString());
addJsonTrackToPlaylist(jsonTrack);
}
break;
case seek:
spotifyController.seek(Float.parseFloat(data));
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Helper method for adding a track to the playlist based
* on the json object.
* @param jsonTrack
*/
private void addJsonTrackToPlaylist(JSONObject jsonTrack){
String name = jsonTrack.optString(TRACK);
String artist = jsonTrack.optString(ARTIST);
String spotifyUri = jsonTrack.optString(URI);
int length = jsonTrack.optInt(TRACK_LENGTH);
Track newTrack = new Track(name, artist, spotifyUri, length);
spotifyController.addTrackToPlaylist(newTrack);
callbacks.onUpdatedPlaylist();
}
/**
* Creates a system action message and publish it on the private topic
* with the application name in the data field except for 'install' where
* the web application as a base64 string will be stored instead.
* @param action
*/
public void createAndPublishSystemActions(Action action){
String data = PLAYLIST_NAME;
if(action.equals(Action.install)){
StreamToBase64String streamToBase64String = StreamToBase64String.getInstance(context);
data = streamToBase64String.getBase64StringFromAssets(PLAYLIST_ZIP);
}
JSONObject json = createJson(action, data);
mqttWorker.publish(TOPIC_SYSTEM, json.toString());
}
/**
* Creates a JSONObject based on the action and the data
* @param action
* @param data
* @return
*/
public JSONObject createJson(Action action, String data)
{
JSONObject json = new JSONObject();
try {
json.put(Action.action.toString(), action.toString());
json.put(ActionResponse.data.toString(), data);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
/**
* Creates a player action message and publish it on the private channel
* @param action
*/
public void createAndPublishPlayerActions(Action action){
JSONObject json = createJson(action, "");
mqttWorker.publish(TOPIC_PLAYLIST, json.toString());
}
/**
* Publish All tracks present in the Playlist of the spotifycontroller to the specified topic.
* Gets the playlist and convert the tracks to Json objects and put them in a Json array.
* @param topic
* the topic to which the message should be published
*/
public void sendAllTracks(String topic, List<Track> tracks){
JSONObject payload = new JSONObject();
JSONArray playlistArray = new JSONArray();
try {
payload.put(Action.action.toString(), Action.add_all.toString());
for(Track track: tracks){
JSONObject jsonTrack = new JSONObject();
jsonTrack.put(TRACK, track.getName());
jsonTrack.put(ARTIST, track.getArtist());
jsonTrack.put(URI, track.getUri());
jsonTrack.put(TRACK_LENGTH, track.getLength());
playlistArray.put(jsonTrack);
}
payload.put(DATA, playlistArray);
mqttWorker.publish(topic, payload.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* When the application is connected to the broker this callback is called
* and then an exist message is published to see if there is an application
* installed.
*/
public void onConnected(boolean connected) {
callbacks.onConnectedMQTT(connected);
if(connected){
mqttWorker.subscribe(TOPIC_PLAYLIST);
mqttWorker.subscribe(TOPIC_PLAYLIST_1);
mqttWorker.subscribe(TOPIC_INFOTAINMENT);
createAndPublishSystemActions(Action.exist);
}
}
/**
* When a disconnect from the broker has been tried this callback method is
* called with the result and notifies the view (activity).
* @param success
*/
@Override
public void onDisconnected(boolean success) {
callbacks.onDisconnectedMQTT(success);
}
}
|
package nl.mpi.arbil.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import nl.mpi.arbil.ArbilMetadataException;
import nl.mpi.arbil.clarin.CmdiComponentLinkReader;
import nl.mpi.arbil.clarin.CmdiComponentLinkReader.CmdiResourceLink;
import nl.mpi.arbil.clarin.profiles.CmdiTemplate;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.BugCatcher;
import nl.mpi.arbil.util.MessageDialogHandler;
import org.apache.xmlbeans.SchemaProperty;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ArbilComponentBuilder {
public static final String RESOURCE_ID_PREFIX = "res_";
private static MessageDialogHandler messageDialogHandler;
public static void setMessageDialogHandler(MessageDialogHandler handler) {
messageDialogHandler = handler;
}
private static BugCatcher bugCatcher;
public static void setBugCatcher(BugCatcher bugCatcherInstance) {
bugCatcher = bugCatcherInstance;
}
private static SessionStorage sessionStorage;
public static void setSessionStorage(SessionStorage sessionStorageInstance) {
sessionStorage = sessionStorageInstance;
}
private static DataNodeLoader dataNodeLoader;
public static void setDataNodeLoader(DataNodeLoader dataNodeLoaderInstance) {
dataNodeLoader = dataNodeLoaderInstance;
}
public static Document getDocument(URI inputUri) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document;
if (inputUri == null) {
document = documentBuilder.newDocument();
} else {
String decodeUrlString = URLDecoder.decode(inputUri.toString(), "UTF-8");
document = documentBuilder.parse(decodeUrlString);
}
return document;
}
// private Document createDocument(File inputFile) throws ParserConfigurationException, SAXException, IOException {
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// documentBuilderFactory.setValidating(false);
// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Document document = documentBuilder.newDocument();
// return document;
public static void savePrettyFormatting(Document document, File outputFile) {
try {
if (outputFile.getPath().endsWith(".imdi")) {
removeImdiDomIds(document); // remove any dom id attributes left over by the imdi api
}
// set up input and output
DOMSource dOMSource = new DOMSource(document);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
StreamResult xmlOutput = new StreamResult(fileOutputStream);
// configure transformer
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(dOMSource, xmlOutput);
xmlOutput.getOutputStream().close();
// todo: this maybe excessive to do every time
// this schema check has been moved to the point of loading the file rather than saving the file
// XsdChecker xsdChecker = new XsdChecker();
// String checkerResult;
// checkerResult = xsdChecker.simpleCheck(outputFile, outputFile.toURI());
// if (checkerResult != null) {
// hasSchemaError = true;
//// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(checkerResult, "Schema Check");
//System.out.println(xmlOutput.getWriter().toString());
} catch (IllegalArgumentException illegalArgumentException) {
bugCatcher.logError(illegalArgumentException);
} catch (TransformerException transformerException) {
bugCatcher.logError(transformerException);
} catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
System.out.println(transformerFactoryConfigurationError.getMessage());
} catch (FileNotFoundException notFoundException) {
bugCatcher.logError(notFoundException);
} catch (IOException iOException) {
bugCatcher.logError(iOException);
}
}
public URI insertResourceProxy(ArbilDataNode arbilDataNode, ArbilDataNode resourceNode) {
// there is no need to save the node at this point because metadatabuilder has already done so
synchronized (arbilDataNode.getParentDomLockObject()) {
String targetXmlPath = getTargetXmlPath(arbilDataNode);
System.out.println("insertResourceProxy: " + targetXmlPath);
// File cmdiNodeFile = imdiTreeObject.getFile();
// String nodeFragment = "";
String resourceProxyId = null;
CmdiComponentLinkReader linkReader = arbilDataNode.getParentDomNode().cmdiComponentLinkReader;
if (linkReader != null) {
resourceProxyId = linkReader.getProxyId(resourceNode.getUrlString());
}
boolean newResourceProxy = (resourceProxyId == null);
if (newResourceProxy) {
// generate a uuid for new resource
resourceProxyId = RESOURCE_ID_PREFIX + UUID.randomUUID().toString();
}
try {
// load the dom
Document targetDocument = getDocument(arbilDataNode.getURI());
// insert the new section
try {
try {
insertResourceProxyReference(targetDocument, targetXmlPath, resourceProxyId);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
return null;
}
// printoutDocument(targetDocument);
if (newResourceProxy) {
// load the schema
SchemaType schemaType = getFirstSchemaType(arbilDataNode.getNodeTemplate().templateFile);
addNewResourceProxy(targetDocument, schemaType, resourceProxyId, resourceNode);
} else {
// Increase counter for referencing nodes
linkReader.getResourceLink(resourceProxyId).addReferencingNode();
}
} catch (Exception exception) {
bugCatcher.logError(exception);
return null;
}
// bump the history
arbilDataNode.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, arbilDataNode.getFile()); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
} catch (IOException exception) {
bugCatcher.logError(exception);
return null;
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
return null;
} catch (SAXException exception) {
bugCatcher.logError(exception);
return null;
}
return arbilDataNode.getURI();
}
}
private String getTargetXmlPath(ArbilDataNode arbilDataNode) {
String targetXmlPath = arbilDataNode.getURI().getFragment();
if (targetXmlPath == null) {
// Get the root CMD Component
targetXmlPath = ".CMD.Components.*[1]";
}
return targetXmlPath;
}
private void insertResourceProxyReference(Document targetDocument, String targetXmlPath, String resourceProxyId) throws TransformerException, DOMException {
// if (targetXmlPath == null) {
// targetXmlPath = ".CMD.Components";
Node documentNode = selectSingleNode(targetDocument, targetXmlPath);
Node previousRefNode = documentNode.getAttributes().getNamedItem(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE);
if (previousRefNode != null) {
// Element already has resource proxy reference(s)
String previousRefValue = documentNode.getAttributes().getNamedItem(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE).getNodeValue();
// Append new id to previous value(s)
((Element) documentNode).setAttribute(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE, previousRefValue + " " + resourceProxyId);
} else {
// Just set new id as reference
((Element) documentNode).setAttribute(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE, resourceProxyId);
}
}
private void addNewResourceProxy(Document targetDocument, SchemaType schemaType, String resourceProxyId, ArbilDataNode resourceNode) throws ArbilMetadataException, DOMException {
Node addedResourceNode = insertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, ".CMD.Resources.ResourceProxyList", ".CMD.Resources.ResourceProxyList.ResourceProxy");
addedResourceNode.getAttributes().getNamedItem("id").setNodeValue(resourceProxyId);
for (Node childNode = addedResourceNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {
String localName = childNode.getNodeName();
if ("ResourceType".equals(localName)) {
if (resourceNode.isCmdiMetaDataNode()) {
childNode.setTextContent("Metadata");
} else {
((Element) childNode).setAttribute("mimetype", resourceNode.mpiMimeType);
childNode.setTextContent("Resource");
}
}
if ("ResourceRef".equals(localName)) {
childNode.setTextContent(resourceNode.getUrlString());
}
}
}
public boolean removeResourceProxyReferences(ArbilDataNode parent, Collection<String> resourceProxyReferences) {
synchronized (parent.getParentDomLockObject()) {
CmdiComponentLinkReader linkReader = parent.getCmdiComponentLinkReader();
if (linkReader == null) {
// We do need (and expect) and link reader here...
return false;
}
HashSet<String> resourceProxyIds = new HashSet<String>(resourceProxyReferences.size());
for (String reference : resourceProxyReferences) {
resourceProxyIds.add(linkReader.getProxyId(reference));
}
String targetXmlPath = getTargetXmlPath(parent);
System.out.println("removeResourceProxyReferences: " + targetXmlPath);
try {
Document targetDocument = getDocument(parent.getURI());
// insert the new section
try {
Node documentNode = selectSingleNode(targetDocument, targetXmlPath);
if (documentNode != null) { // Node is not there, nothing to check
Node previousRefNode = documentNode.getAttributes().getNamedItem(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE);
if (previousRefNode != null) {
// Get old references
String previousRefsValue = documentNode.getAttributes().getNamedItem(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE).getNodeValue();
// Create new reference set excluding the ones to be removed
StringBuilder newRefsValueSB = new StringBuilder();
for (String ref : previousRefsValue.split(" ")) {
ref = ref.trim();
if (ref.length() > 0 && !resourceProxyIds.contains(ref)) {
newRefsValueSB.append(ref).append(" ");
}
}
String newRefsValue = newRefsValueSB.toString().trim();
if (newRefsValue.length() == 0) {
// No remaining references, remove ref attribute
((Element) documentNode).removeAttribute(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE);
} else {
((Element) documentNode).setAttribute(CmdiTemplate.RESOURCE_REFERENCE_ATTRIBUTE, newRefsValue);
}
}
}
} catch (TransformerException exception) {
bugCatcher.logError(exception);
return false;
}
// Check whether proxy can be deleted
for (String id : resourceProxyIds) {
CmdiResourceLink link = linkReader.getResourceLink(id);
link.removeReferencingNode();
if (link.getReferencingNodesCount() == 0) {
// There was only one reference to this proxy and we deleted it, so remove the proxy
if (!removeResourceProxy(targetDocument, id)) {
messageDialogHandler.addMessageDialogToQueue("Failed to remove ", "Warning");
}
}
}
// bump the history
parent.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, parent.getFile()); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
return true;
} catch (IOException exception) {
bugCatcher.logError(exception);
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
} catch (SAXException exception) {
bugCatcher.logError(exception);
}
}
return false;
}
/**
* Removes the resource proxy with the specified id from the document.
* Note: THIS DOES NOT CHECK WHETHER THERE ARE ANY REFERENCES LEFT
* @param document Document to remove resource proxy from
* @param resourceProxyId Unique id (id="xyz") of resource proxy element
* @return Whether resource proxy was removed successfully
*/
private boolean removeResourceProxy(Document document, String resourceProxyId) {
// Look for ResourceProxy node with specified id
Node proxyNode = getResourceProxyNode(document, resourceProxyId);
if (proxyNode != null) {
// Node found. Remove from parent
proxyNode.getParentNode().removeChild(proxyNode);
return true;
} else {
return false;
}
}
public boolean updateResourceProxyReference(Document document, String resourceProxyId, URI referenceURI) {
return updateResourceProxyReference(document, resourceProxyId, referenceURI.toString());
}
public boolean updateResourceProxyReference(Document document, String resourceProxyId, String reference) {
try {
// Look for ResourceProxy node with specified id
Node resourceRefNode = selectSingleNode(document, getPathForResourceProxynode(resourceProxyId) + ".ResourceRef");
if (resourceRefNode != null) {
resourceRefNode.setTextContent(reference);
return true;
}
} catch (TransformerException ex) {
bugCatcher.logError(ex);
}
return false;
}
public boolean removeChildNodes(ArbilDataNode arbilDataNode, String nodePaths[]) {
if (arbilDataNode.getNeedsSaveToDisk(false)) {
arbilDataNode.saveChangesToCache(true);
}
synchronized (arbilDataNode.getParentDomLockObject()) {
System.out.println("remove from parent nodes: " + arbilDataNode);
File cmdiNodeFile = arbilDataNode.getFile();
try {
Document targetDocument = getDocument(arbilDataNode.getURI());
// collect up all the nodes to be deleted without changing the xpath
ArrayList<Node> selectedNodes = new ArrayList<Node>();
for (String currentNodePath : nodePaths) {
System.out.println("removeChildNodes: " + currentNodePath);
// todo: search for and remove any reource links referenced by this node or its sub nodes
Node documentNode = selectSingleNode(targetDocument, currentNodePath);
if (documentNode != null) {
//System.out.println("documentNode: " + documentNode);
System.out.println("documentNodeName: " + documentNode != null ? documentNode.getNodeName() : "<null>");
selectedNodes.add(documentNode);
}
}
// delete all the nodes now that the xpath is no longer relevant
System.out.println(selectedNodes.size());
for (Node currentNode : selectedNodes) {
Node parentNode = currentNode.getParentNode();
if (parentNode != null) {
parentNode.removeChild(currentNode);
}
}
// bump the history
arbilDataNode.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, cmdiNodeFile);
for (String currentNodePath : nodePaths) {
// todo log to jornal file
}
return true;
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
} catch (SAXException exception) {
bugCatcher.logError(exception);
} catch (IOException exception) {
bugCatcher.logError(exception);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
}
return false;
}
}
public boolean setFieldValues(ArbilDataNode arbilDataNode, FieldUpdateRequest[] fieldUpdates) {
synchronized (arbilDataNode.getParentDomLockObject()) {
//new ImdiUtils().addDomIds(imdiTreeObject.getURI()); // testing only
System.out.println("setFieldValues: " + arbilDataNode);
File cmdiNodeFile = arbilDataNode.getFile();
try {
Document targetDocument = getDocument(arbilDataNode.getURI());
for (FieldUpdateRequest currentFieldUpdate : fieldUpdates) {
System.out.println("currentFieldUpdate: " + currentFieldUpdate.fieldPath);
// todo: search for and remove any reource links referenced by this node or its sub nodes
Node documentNode = selectSingleNode(targetDocument, currentFieldUpdate.fieldPath);
NamedNodeMap attributesMap = documentNode.getAttributes();
if (currentFieldUpdate.fieldOldValue.equals(documentNode.getTextContent())) {
documentNode.setTextContent(currentFieldUpdate.fieldNewValue);
} else {
bugCatcher.logError(new Exception("expecting \'" + currentFieldUpdate.fieldOldValue + "\' not \'" + documentNode.getTextContent() + "\' in " + currentFieldUpdate.fieldPath));
return false;
}
Node keyNameNode = attributesMap.getNamedItem("Name");
if (keyNameNode != null && currentFieldUpdate.keyNameValue != null) {
keyNameNode.setNodeValue(currentFieldUpdate.keyNameValue);
}
Node languageNode = attributesMap.getNamedItem("LanguageId");
if (languageNode == null) {
languageNode = attributesMap.getNamedItem("xml:lang");
}
if (languageNode != null && currentFieldUpdate.fieldLanguageId != null) {
languageNode.setNodeValue(currentFieldUpdate.fieldLanguageId);
}
}
// bump the history
arbilDataNode.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, cmdiNodeFile);
for (FieldUpdateRequest currentFieldUpdate : fieldUpdates) {
// log to jornal file
ArbilJournal.getSingleInstance().saveJournalEntry(arbilDataNode.getUrlString(), currentFieldUpdate.fieldPath, currentFieldUpdate.fieldOldValue, currentFieldUpdate.fieldNewValue, "save");
if (currentFieldUpdate.fieldLanguageId != null) {
ArbilJournal.getSingleInstance().saveJournalEntry(arbilDataNode.getUrlString(), currentFieldUpdate.fieldPath + ":LanguageId", currentFieldUpdate.fieldLanguageId, "", "save");
}
if (currentFieldUpdate.keyNameValue != null) {
ArbilJournal.getSingleInstance().saveJournalEntry(arbilDataNode.getUrlString(), currentFieldUpdate.fieldPath + ":Name", currentFieldUpdate.keyNameValue, "", "save");
}
}
return true;
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
} catch (SAXException exception) {
bugCatcher.logError(exception);
} catch (IOException exception) {
bugCatcher.logError(exception);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
}
return false;
}
}
public void testInsertFavouriteComponent() {
try {
ArbilDataNode favouriteArbilDataNode1 = dataNodeLoader.getArbilDataNodeWithoutLoading(new URI("file:/Users/petwit/.arbil/favourites/fav-784841449583527834.imdi#.METATRANSCRIPT.Session.MDGroup.Actors.Actor"));
ArbilDataNode favouriteArbilDataNode2 = dataNodeLoader.getArbilDataNodeWithoutLoading(new URI("file:/Users/petwit/.arbil/favourites/fav-784841449583527834.imdi#.METATRANSCRIPT.Session.MDGroup.Actors.Actor(2)"));
ArbilDataNode destinationArbilDataNode = dataNodeLoader.getArbilDataNodeWithoutLoading(new URI("file:/Users/petwit/.arbil/imdicache/20100527141926/20100527141926.imdi"));
insertFavouriteComponent(destinationArbilDataNode, favouriteArbilDataNode1);
insertFavouriteComponent(destinationArbilDataNode, favouriteArbilDataNode2);
} catch (URISyntaxException exception) {
bugCatcher.logError(exception);
} catch (ArbilMetadataException exception) {
bugCatcher.logError(exception);
}
}
public URI insertFavouriteComponent(ArbilDataNode destinationArbilDataNode, ArbilDataNode favouriteArbilDataNode) throws ArbilMetadataException {
URI returnUri = null;
// this node has already been saved in the metadatabuilder which called this
// but lets check this again in case this gets called elsewhere and to make things consistant
String elementName = favouriteArbilDataNode.getURI().getFragment();
//String insertBefore = destinationArbilDataNode.nodeTemplate.getInsertBeforeOfTemplate(elementName);
String insertBefore = destinationArbilDataNode.getNodeTemplate().getInsertBeforeOfTemplate(elementName);
System.out.println("insertBefore: " + insertBefore);
int maxOccurs = destinationArbilDataNode.getNodeTemplate().getMaxOccursForTemplate(elementName);
System.out.println("maxOccurs: " + maxOccurs);
if (destinationArbilDataNode.getNeedsSaveToDisk(false)) {
destinationArbilDataNode.saveChangesToCache(true);
}
try {
Document favouriteDocument;
synchronized (favouriteArbilDataNode.getParentDomLockObject()) {
favouriteDocument = getDocument(favouriteArbilDataNode.getURI());
}
synchronized (destinationArbilDataNode.getParentDomLockObject()) {
Document destinationDocument = getDocument(destinationArbilDataNode.getURI());
String favouriteXpath = favouriteArbilDataNode.getURI().getFragment();
String favouriteXpathTrimmed = favouriteXpath.replaceFirst("\\.[^(^.]+$", "");
boolean onlySubNodes = !favouriteXpathTrimmed.equals(favouriteXpath);
System.out.println("favouriteXpath: " + favouriteXpathTrimmed);
String destinationXpath;
if (onlySubNodes) {
destinationXpath = favouriteXpathTrimmed;
} else {
destinationXpath = favouriteXpathTrimmed.replaceFirst("\\.[^.]+$", "");
}
System.out.println("destinationXpath: " + destinationXpath);
destinationXpath = alignDestinationPathWithTarget(destinationXpath, destinationArbilDataNode);
Node destinationNode = selectSingleNode(destinationDocument, destinationXpath);
Node selectedNode = selectSingleNode(favouriteDocument, favouriteXpathTrimmed);
Node importedNode = destinationDocument.importNode(selectedNode, true);
Node[] favouriteNodes;
if (onlySubNodes) {
NodeList selectedNodeList = importedNode.getChildNodes();
favouriteNodes = new Node[selectedNodeList.getLength()];
for (int nodeCounter = 0; nodeCounter < selectedNodeList.getLength(); nodeCounter++) {
favouriteNodes[nodeCounter] = selectedNodeList.item(nodeCounter);
}
} else {
favouriteNodes = new Node[]{importedNode};
}
for (Node singleFavouriteNode : favouriteNodes) {
if (singleFavouriteNode.getNodeType() != Node.TEXT_NODE) {
insertNodeInOrder(destinationNode, singleFavouriteNode, insertBefore, maxOccurs);
// destinationNode.appendChild(singleFavouriteNode);
System.out.println("inserting favouriteNode: " + singleFavouriteNode.getLocalName());
}
}
savePrettyFormatting(destinationDocument, destinationArbilDataNode.getFile());
try {
String nodeFragment;
if (favouriteNodes.length != 1) {
nodeFragment = destinationXpath; // in this case show the target node
} else {
nodeFragment = convertNodeToNodePath(destinationDocument, favouriteNodes[0], destinationXpath);
}
System.out.println("nodeFragment: " + nodeFragment);
// return the child node url and path in the xml
// first strip off any fragment then add the full node fragment
returnUri = new URI(destinationArbilDataNode.getURI().toString().split("#")[0] + "#" + nodeFragment);
} catch (URISyntaxException exception) {
bugCatcher.logError(exception);
}
}
} catch (IOException exception) {
bugCatcher.logError(exception);
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
} catch (SAXException exception) {
bugCatcher.logError(exception);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
}
return returnUri;
}
private String alignDestinationPathWithTarget(String destinationXpath, ArbilDataNode destinationArbilDataNode) {
String targetFragment = destinationArbilDataNode.getURI().getFragment();
if (targetFragment != null) { // If null, it's the document root
// If container node, we want to know the actual level to add to, so remove container part from path
if (destinationArbilDataNode.isContainerNode()) {
targetFragment = targetFragment.substring(0, targetFragment.lastIndexOf("."));
}
// Canonicalize both destination path and target fragment
String destinationXpathGeneric = destinationXpath.replaceAll("\\(\\d+\\)", "(x)");
String targetFragmentGeneric = targetFragment.replaceAll("\\(\\d+\\)", "(x)");
// Do they match up? Destination should begin with target
if (destinationXpathGeneric.startsWith(targetFragmentGeneric)) {
// Convert target fragment back into regular expression for matching with destination path
final String commonPartRegEx = targetFragmentGeneric.replaceAll("\\(x\\)", "\\\\(\\\\d+\\\\)");
String[] destinationXpathParts = destinationXpath.split(commonPartRegEx);
if (destinationXpathParts.length == 0) {
// Complete match
destinationXpath = targetFragment;
} else if (destinationXpathParts.length == 2) {
// Combine targetFragment with remainder from destination path
destinationXpath = targetFragment + destinationXpathParts[1];
} else {
// Should not happen, either exact match or remainder
messageDialogHandler.addMessageDialogToQueue("Unexpected relation between source and target paths. See error log for details.", "Insert node");
bugCatcher.logError("destinationXpath: " + destinationXpath + "\ntargetFragment: " + targetFragment, null);
}
}
}
return destinationXpath;
}
public static boolean canInsertNode(Node destinationNode, Node addableNode, int maxOccurs) {
if (maxOccurs > 0) {
String addableName = addableNode.getLocalName();
if (addableName == null) {
addableName = addableNode.getNodeName();
}
NodeList childNodes = destinationNode.getChildNodes();
int duplicateNodeCounter = 0;
for (int childCounter = 0; childCounter < childNodes.getLength(); childCounter++) {
String childsName = childNodes.item(childCounter).getLocalName();
if (addableName.equals(childsName)) {
duplicateNodeCounter++;
if (duplicateNodeCounter >= maxOccurs) {
return false;
}
}
}
}
return true;
}
public static Node insertNodeInOrder(Node destinationNode, Node addableNode, String insertBefore, int maxOccurs) throws TransformerException, ArbilMetadataException {
if (!canInsertNode(destinationNode, addableNode, maxOccurs)) {
throw new ArbilMetadataException("The maximum nodes of this type have already been added.\n");
}
// todo: read the template for max occurs values and use them here and for all inserts
Node insertBeforeNode = null;
if (insertBefore != null && insertBefore.length() > 0) {
String[] insertBeforeArray = insertBefore.split(",");
// find the node to add the new section before
NodeList childNodes = destinationNode.getChildNodes();
outerloop:
for (int childCounter = 0; childCounter < childNodes.getLength(); childCounter++) {
String childsName = childNodes.item(childCounter).getLocalName();
for (String currentInsertBefore : insertBeforeArray) {
if (currentInsertBefore.equals(childsName)) {
System.out.println("insertbefore: " + childsName);
insertBeforeNode = childNodes.item(childCounter);
break outerloop;
}
}
}
}
// find the node to add the new section to
Node addedNode;
if (insertBeforeNode != null) {
System.out.println("inserting before: " + insertBeforeNode.getNodeName());
addedNode = destinationNode.insertBefore(addableNode, insertBeforeNode);
} else {
System.out.println("inserting");
if (addableNode instanceof Attr) {
if (destinationNode instanceof Element) {
addedNode = ((Element) destinationNode).setAttributeNode((Attr) addableNode);
} else {
throw new ArbilMetadataException("Cannot insert attribute in node of this type: " + destinationNode.getNodeName());
}
} else {
addedNode = destinationNode.appendChild(addableNode);
}
}
return addedNode;
}
private String checkTargetXmlPath(String targetXmlPath, String cmdiComponentId) {
// check for issues with the path
if (targetXmlPath == null) {
targetXmlPath = cmdiComponentId.replaceAll("\\.[^.]+$", "");
} else if (targetXmlPath.replaceAll("\\(\\d+\\)", "").length() == cmdiComponentId.length()) {
// trim the last path component if the destination equals the new node path
// i.e. xsdPath: .CMD.Components.Session.Resources.MediaFile.Keys.Key into .CMD.Components.Session.Resources.MediaFile(1).Keys.Key
targetXmlPath = targetXmlPath.replaceAll("\\.[^.]+$", "");
}
// make sure the target xpath has all the required parts
String[] cmdiComponentArray = cmdiComponentId.split("\\.");
String[] targetXmlPathArray = targetXmlPath.replaceAll("\\(\\d+\\)", "").split("\\.");
StringBuilder arrayPathParts = new StringBuilder();
for (int pathPartCounter = targetXmlPathArray.length; pathPartCounter < cmdiComponentArray.length - 1; pathPartCounter++) {
System.out.println("adding missing path component: " + cmdiComponentArray[pathPartCounter]);
arrayPathParts.append('.');
arrayPathParts.append(cmdiComponentArray[pathPartCounter]);
}
// end path corrections
return targetXmlPath + arrayPathParts.toString();
}
/**
* Adds a CMD component to a datanode
* @param arbilDataNode
* @param targetXmlPath
* @param cmdiComponentId
* @return
*/
public URI insertChildComponent(ArbilDataNode arbilDataNode, String targetXmlPath, String cmdiComponentId) {
if (arbilDataNode.getNeedsSaveToDisk(false)) {
arbilDataNode.saveChangesToCache(true);
}
synchronized (arbilDataNode.getParentDomLockObject()) {
System.out.println("insertChildComponent: " + cmdiComponentId);
System.out.println("targetXmlPath: " + targetXmlPath);
targetXmlPath = checkTargetXmlPath(targetXmlPath, cmdiComponentId);
System.out.println("trimmed targetXmlPath: " + targetXmlPath);
//String targetXpath = targetNode.getURI().getFragment();
//System.out.println("targetXpath: " + targetXpath);
// File cmdiNodeFile = imdiTreeObject.getFile();
String nodeFragment = "";
try {
// load the schema
SchemaType schemaType = getFirstSchemaType(arbilDataNode.getNodeTemplate().templateFile);
// load the dom
Document targetDocument = getDocument(arbilDataNode.getURI());
// insert the new section
try {
// printoutDocument(targetDocument);
Node AddedNode = insertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, targetXmlPath, cmdiComponentId);
nodeFragment = convertNodeToNodePath(targetDocument, AddedNode, targetXmlPath);
} catch (ArbilMetadataException exception) {
messageDialogHandler.addMessageDialogToQueue(exception.getLocalizedMessage(), "Insert node error");
return null;
}
// bump the history
arbilDataNode.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, arbilDataNode.getFile()); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
} catch (IOException exception) {
bugCatcher.logError(exception);
return null;
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
return null;
} catch (SAXException exception) {
bugCatcher.logError(exception);
return null;
}
// diff_match_patch diffTool= new diff_match_patch();
// diffTool.diff_main(targetXpath, targetXpath);
try {
System.out.println("nodeFragment: " + nodeFragment);
// return the child node url and path in the xml
// first strip off any fragment then add the full node fragment
return new URI(arbilDataNode.getURI().toString().split("#")[0] + "#" + nodeFragment);
} catch (URISyntaxException exception) {
bugCatcher.logError(exception);
return null;
}
}
}
/**
* Tests whether the specified CMD component can be added to the specified datanode
* @param arbilDataNode
* @param targetXmlPath
* @param cmdiComponentId
* @return
*/
public boolean canInsertChildComponent(ArbilDataNode arbilDataNode, String targetXmlPath, String cmdiComponentId) {
synchronized (arbilDataNode.getParentDomLockObject()) {
targetXmlPath = checkTargetXmlPath(targetXmlPath, cmdiComponentId);
try {
// load the schema
SchemaType schemaType = getFirstSchemaType(arbilDataNode);
// load the dom
Document targetDocument = getDocument(arbilDataNode.getURI());
// insert the new section
try {
return canInsertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, targetXmlPath, cmdiComponentId);
} catch (ArbilMetadataException exception) {
bugCatcher.logError(exception);
messageDialogHandler.addMessageDialogToQueue(exception.getLocalizedMessage(), "Insert node error");
return false;
}
} catch (IOException exception) {
bugCatcher.logError(exception);
return false;
} catch (ParserConfigurationException exception) {
bugCatcher.logError(exception);
return false;
} catch (SAXException exception) {
bugCatcher.logError(exception);
return false;
} catch (DOMException exception) {
bugCatcher.logError(exception);
return false;
}
}
}
public void testRemoveArchiveHandles() {
try {
Document workingDocument = getDocument(new URI("http://corpus1.mpi.nl/qfs1/media-archive/Corpusstructure/MPI.imdi"));
removeArchiveHandles(workingDocument);
printoutDocument(workingDocument);
} catch (Exception exception) {
bugCatcher.logError(exception);
}
}
public void removeArchiveHandles(ArbilDataNode arbilDataNode) {
synchronized (arbilDataNode.getParentDomLockObject()) {
try {
Document workingDocument = getDocument(arbilDataNode.getURI());
removeArchiveHandles(workingDocument);
savePrettyFormatting(workingDocument, arbilDataNode.getFile());
} catch (Exception exception) {
bugCatcher.logError(exception);
}
}
}
private static void removeImdiDomIds(Document targetDocument) {
/**
* Looks up CMD/Resources/ResourceProxyList/ResourceProxy node with resourceProxyId
* @param document
* @param resourceProxyId
* @return ProxyNode, if found (first if multiple found (should not occur)); otherwise null
*/
private Node getResourceProxyNode(Document document, String resourceProxyId) {
try {
return selectSingleNode(document, getPathForResourceProxynode(resourceProxyId));
} catch (TransformerException ex) {
bugCatcher.logError("Exception while finding for removal resource proxy with id " + resourceProxyId, ex);
}
return null;
}
private String getPathForResourceProxynode(String resourceProxyId) {
return ".CMD.Resources.ResourceProxyList.ResourceProxy[@id='" + resourceProxyId + "']";
}
private Node selectSingleNode(Document targetDocument, String targetXpath) throws TransformerException {
String tempXpathArray[] = convertImdiPathToXPathOptions(targetXpath);
if (tempXpathArray != null) {
for (String tempXpath : tempXpathArray) {
tempXpath = tempXpath.replaceAll("\\(", "[");
tempXpath = tempXpath.replaceAll("\\)", "]");
// tempXpath = "/CMD/Components/Session/MDGroup/Actors";
System.out.println("tempXpath: " + tempXpath);
// find the target node of the xml
Node returnNode = XPathAPI.selectSingleNode(targetDocument, tempXpath);
if (returnNode != null) {
return returnNode;
}
}
}
bugCatcher.logError(new Exception("Xpath issue, no node found for: " + targetXpath));
return null;
}
private String[] convertImdiPathToXPathOptions(String targetXpath) {
if (targetXpath == null) {
return null;
} else {
// convert the syntax inherited from the imdi api into xpath
// Because most imdi files use a name space syntax we need to try both queries
return new String[]{targetXpath.replaceAll("\\.", "/"), targetXpath.replaceAll("\\.", "/:")};
}
}
private Node insertSectionToXpath(Document targetDocument, Node documentNode, SchemaType schemaType, String targetXpath, String xsdPath) throws ArbilMetadataException {
System.out.println("insertSectionToXpath");
System.out.println("xsdPath: " + xsdPath);
System.out.println("targetXpath: " + targetXpath);
SchemaProperty foundProperty = null;
String insertBefore = "";
String strippedXpath = null;
if (targetXpath == null) {
documentNode = documentNode.getParentNode();
} else {
try {
// test profile book is a good sample to test for errors; if you add Authors description from the root of the node it will cause a schema error but if you add from the author it is valid
documentNode = selectSingleNode(targetDocument, targetXpath);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
return null;
}
strippedXpath = targetXpath.replaceAll("\\(\\d+\\)", "");
}
// at this point we have the xml node that the user acted on but next must get any additional nodes with the next section
System.out.println("strippedXpath: " + strippedXpath);
for (String currentPathComponent : xsdPath.split("\\.")) {
if (currentPathComponent.length() > 0) {
foundProperty = null;
for (SchemaProperty schemaProperty : schemaType.getProperties()) {
String currentName;
if (schemaProperty.isAttribute()) {
currentName = CmdiTemplate.getAttributePathSection(schemaProperty.getName().getNamespaceURI(), schemaProperty.getName().getLocalPart());
} else {
currentName = schemaProperty.getName().getLocalPart();
}
//System.out.println("currentName: " + currentName);
if (foundProperty == null) {
if (schemaProperty.isAttribute()
? currentPathComponent.equals("@" + currentName)
: currentPathComponent.equals(currentName)) {
foundProperty = schemaProperty;
insertBefore = "";
}
} else {
if (!schemaProperty.isAttribute()) {
if (insertBefore.length() < 1) {
insertBefore = currentName;
} else {
insertBefore = insertBefore + "," + currentName;
}
}
}
}
if (foundProperty == null) {
throw new ArbilMetadataException("failed to find the path in the schema: " + currentPathComponent);
} else {
schemaType = foundProperty.getType();
}
}
}
// System.out.println("Adding marker node");
// Element currentElement = targetDocument.createElement("MarkerNode");
// currentElement.setTextContent(xsdPath);
// documentNode.appendChild(currentElement);
System.out.println("Adding destination sub nodes node to: " + documentNode.getLocalName());
Node addedNode = constructXml(foundProperty, xsdPath, targetDocument, null, documentNode, false);
System.out.println("insertBefore: " + insertBefore);
int maxOccurs;
if (foundProperty.getMaxOccurs() != null) {
maxOccurs = foundProperty.getMaxOccurs().intValue();
} else {
maxOccurs = -1;
}
System.out.println("maxOccurs: " + maxOccurs);
if (insertBefore.length() > 0 || maxOccurs != -1) {
if (addedNode instanceof Attr) {
((Element) documentNode).removeAttributeNode((Attr) addedNode);
} else {
documentNode.removeChild(addedNode);
}
try {
insertNodeInOrder(documentNode, addedNode, insertBefore, maxOccurs);
} catch (TransformerException exception) {
throw new ArbilMetadataException(exception.getMessage());
}
}
return addedNode;
}
private boolean canInsertSectionToXpath(Document targetDocument, Node documentNode, SchemaType schemaType, String targetXpath, String xsdPath) throws ArbilMetadataException {
System.out.println("insertSectionToXpath");
System.out.println("xsdPath: " + xsdPath);
System.out.println("targetXpath: " + targetXpath);
SchemaProperty foundProperty = null;
String insertBefore = "";
if (targetXpath == null) {
documentNode = documentNode.getParentNode();
} else {
try {
documentNode = selectSingleNode(targetDocument, targetXpath);
} catch (TransformerException exception) {
bugCatcher.logError(exception);
return false;
}
}
// at this point we have the xml node that the user acted on but next must get any additional nodes with the next section
for (String currentPathComponent : xsdPath.split("\\.")) {
if (currentPathComponent.length() > 0) {
foundProperty = null;
for (SchemaProperty schemaProperty : schemaType.getProperties()) {
String currentName;
if (schemaProperty.isAttribute()) {
currentName = CmdiTemplate.getAttributePathSection(schemaProperty.getName().getNamespaceURI(), schemaProperty.getName().getLocalPart());
} else {
currentName = schemaProperty.getName().getLocalPart();
}
//System.out.println("currentName: " + currentName);
if (foundProperty == null) {
if (schemaProperty.isAttribute()
? currentPathComponent.equals("@" + currentName)
: currentPathComponent.equals(currentName)) {
foundProperty = schemaProperty;
insertBefore = "";
}
} else {
if (!schemaProperty.isAttribute()) {
if (insertBefore.length() < 1) {
insertBefore = currentName;
} else {
insertBefore = insertBefore + "," + currentName;
}
}
}
}
if (foundProperty == null) {
throw new ArbilMetadataException("failed to find the path in the schema: " + currentPathComponent);
} else {
schemaType = foundProperty.getType();
}
}
}
System.out.println("Adding destination sub nodes node to: " + documentNode.getLocalName());
Node addedNode = constructXml(foundProperty, xsdPath, targetDocument, null, documentNode, false);
System.out.println("insertBefore: " + insertBefore);
int maxOccurs;
if (foundProperty.getMaxOccurs() != null) {
maxOccurs = foundProperty.getMaxOccurs().intValue();
} else {
maxOccurs = -1;
}
System.out.println("maxOccurs: " + maxOccurs);
if (insertBefore.length() > 0 || maxOccurs != -1) {
if (addedNode instanceof Attr) {
((Element) documentNode).removeAttributeNode((Attr) addedNode);
} else {
documentNode.removeChild(addedNode);
}
return canInsertNode(documentNode, addedNode, maxOccurs);
}
return true;
}
public static String convertNodeToNodePath(Document targetDocument, Node documentNode, String targetXmlPath) {
System.out.println("Calculating the added fragment");
// count siblings to get the correct child index for the fragment
int siblingCouter = 1;
Node siblingNode = documentNode.getPreviousSibling();
while (siblingNode != null) {
if (documentNode.getNodeName().equals(siblingNode.getNodeName())) {
siblingCouter++;
}
siblingNode = siblingNode.getPreviousSibling();
}
// get the current node name
String nodeFragment = documentNode.getNodeName();
if (documentNode instanceof Attr) {
nodeFragment = "@" + nodeFragment;
}
String nodePathString = targetXmlPath + "." + nodeFragment + "(" + siblingCouter + ")";
// String nodePathString = "";
// Node parentNode = documentNode;
// while (parentNode != null) {
// // count siblings to get the correct child index for the fragment
// int siblingCouter = 1;
// Node siblingNode = parentNode.getPreviousSibling();
// while (siblingNode != null) {
// if (parentNode.getLocalName().equals(siblingNode.getLocalName())) {
// siblingCouter++;
// siblingNode = siblingNode.getPreviousSibling();
// // get the current node name
// String nodeFragment = parentNode.getNodeName();
// nodePathString = "." + nodeFragment + "(" + siblingCouter + ")" + nodePathString;
// //System.out.println("nodePathString: " + nodePathString);
// if (parentNode.isSameNode(targetDocument.getDocumentElement())) {
// break;
// parentNode = parentNode.getParentNode();
// nodeFragment = "." + nodeFragment;
System.out.println("nodeFragment: " + nodePathString);
System.out.println("targetXmlPath: " + targetXmlPath);
return nodePathString;
//return childStartElement.
}
public URI createComponentFile(URI cmdiNodeFile, URI xsdFile, boolean addDummyData) {
System.out.println("createComponentFile: " + cmdiNodeFile + " : " + xsdFile);
try {
Document workingDocument = getDocument(null);
readSchema(workingDocument, xsdFile, addDummyData);
savePrettyFormatting(workingDocument, new File(cmdiNodeFile));
} catch (IOException e) {
bugCatcher.logError(e);
} catch (ParserConfigurationException e) {
bugCatcher.logError(e);
} catch (SAXException e) {
bugCatcher.logError(e);
}
return cmdiNodeFile;
}
private HashMap<ArbilDataNode, SchemaType> nodeSchemaTypeMap = new HashMap<ArbilDataNode, SchemaType>();
/**
* Caches schema type for data nodes as fetching the schema type is rather expensive.
* This is not static, so only as long as this component builder lives (e.g. during series of canInsertChildComponent calls)
* @param arbilDataNode
* @return
*/
private SchemaType getFirstSchemaType(ArbilDataNode arbilDataNode) {
if (nodeSchemaTypeMap.containsKey(arbilDataNode)) {
return nodeSchemaTypeMap.get(arbilDataNode);
} else {
SchemaType schemaType = getFirstSchemaType(arbilDataNode.getNodeTemplate().templateFile);
nodeSchemaTypeMap.put(arbilDataNode, schemaType);
return schemaType;
}
}
private SchemaType getFirstSchemaType(File schemaFile) {
try {
InputStream inputStream = new FileInputStream(schemaFile);
try {
//Since we're dealing with xml schema files here the character encoding is assumed to be UTF-8
XmlOptions xmlOptions = new XmlOptions();
xmlOptions.setCharacterEncoding("UTF-8");
// CatalogDocument catalogDoc = CatalogDocument.Factory.newInstance();
xmlOptions.setEntityResolver(new ArbilEntityResolver(sessionStorage.getOriginatingUri(schemaFile.toURI()))); // this schema file is in the cache and must be resolved back to the origin in order to get unresolved imports within the schema file
//xmlOptions.setCompileDownloadUrls();
SchemaTypeSystem sts = XmlBeans.compileXsd(new XmlObject[]{XmlObject.Factory.parse(inputStream, xmlOptions)}, XmlBeans.getBuiltinTypeSystem(), xmlOptions);
// there can only be a single root node so we just get the first one, note that the IMDI schema specifies two (METATRANSCRIPT and VocabularyDef)
return sts.documentTypes()[0];
} catch (IOException e) {
bugCatcher.logError(e);
} finally {
inputStream.close();
}
} catch (IOException e) {
bugCatcher.logError(e);
} catch (XmlException e) {
// TODO: this is not really a good place to message this so modify to throw
messageDialogHandler.addMessageDialogToQueue("Could not read the XML Schema", "Error inserting node");
bugCatcher.logError(e);
}
return null;
}
private void readSchema(Document workingDocument, URI xsdFile, boolean addDummyData) {
File schemaFile;
if (xsdFile.getScheme() == null || xsdFile.getScheme().length() == 0 || xsdFile.getScheme().toLowerCase().equals("file")) {
// do not cache local xsd files
schemaFile = new File(xsdFile);
} else {
schemaFile = sessionStorage.updateCache(xsdFile.toString(), 5);
}
SchemaType schemaType = getFirstSchemaType(schemaFile);
constructXml(schemaType.getElementProperties()[0], "documentTypes", workingDocument, xsdFile.toString(), null, addDummyData);
}
private Node appendNode(Document workingDocument, String nameSpaceUri, Node parentElement, SchemaProperty schemaProperty, boolean addDummyData) {
if (schemaProperty.isAttribute()) {
return appendAttributeNode(workingDocument, nameSpaceUri, (Element) parentElement, schemaProperty, addDummyData);
} else {
return appendElementNode(workingDocument, nameSpaceUri, parentElement, schemaProperty, addDummyData);
}
}
private Attr appendAttributeNode(Document workingDocument, String nameSpaceUri, Element parentElement, SchemaProperty schemaProperty, boolean addDummyData) {
Attr currentAttribute = workingDocument.createAttributeNS(schemaProperty.getName().getNamespaceURI(), schemaProperty.getName().getLocalPart());
if (schemaProperty.getDefaultText() != null) {
currentAttribute.setNodeValue(schemaProperty.getDefaultText());
}
parentElement.setAttributeNode(currentAttribute);
return currentAttribute;
}
private Element appendElementNode(Document workingDocument, String nameSpaceUri, Node parentElement, SchemaProperty schemaProperty, boolean addDummyData) {
Element currentElement = workingDocument.createElementNS("http:
SchemaType currentSchemaType = schemaProperty.getType();
for (SchemaProperty attributesProperty : currentSchemaType.getAttributeProperties()) {
if (attributesProperty.getMinOccurs() != null && !attributesProperty.getMinOccurs().equals(BigInteger.ZERO)) {
currentElement.setAttribute(attributesProperty.getName().getLocalPart(), attributesProperty.getDefaultText());
}
}
if (parentElement == null) {
// this is probably not the way to set these, however this will do for now (many other methods have been tested and all failed to function correctly)
currentElement.setAttribute("CMDVersion", "1.1");
currentElement.setAttribute("xmlns:xsi", "http:
currentElement.setAttribute("xsi:schemaLocation", "http:
// currentElement.setAttribute("xsi:schemaLocation", "cmd " + nameSpaceUri);
workingDocument.appendChild(currentElement);
} else {
parentElement.appendChild(currentElement);
}
//currentElement.setTextContent(schemaProperty.getMinOccurs() + ":" + schemaProperty.getMinOccurs());
return currentElement;
}
private Node constructXml(SchemaProperty currentSchemaProperty, String pathString, Document workingDocument, String nameSpaceUri, Node parentElement, boolean addDummyData) {
Node returnNode = null;
// this must be tested against getting the actor description not the actor of an imdi profile instance
String currentPathString = pathString + "." + currentSchemaProperty.getName().getLocalPart();
System.out.println("Found Element: " + currentPathString);
SchemaType currentSchemaType = currentSchemaProperty.getType();
Node currentElement = appendNode(workingDocument, nameSpaceUri, parentElement, currentSchemaProperty, addDummyData);
returnNode = currentElement;
//System.out.println("printSchemaType " + schemaType.toString());
// for (SchemaType schemaSubType : schemaType.getAnonymousTypes()) {
// System.out.println("getAnonymousTypes:");
// constructXml(schemaSubType, pathString + ".*getAnonymousTypes*", workingDocument, parentElement);
// for (SchemaType schemaSubType : schemaType.getUnionConstituentTypes()) {
// System.out.println("getUnionConstituentTypes:");
// printSchemaType(schemaSubType);
// for (SchemaType schemaSubType : schemaType.getUnionMemberTypes()) {
// System.out.println("getUnionMemberTypes:");
// constructXml(schemaSubType, pathString + ".*getUnionMemberTypes*", workingDocument, parentElement);
// for (SchemaType schemaSubType : schemaType.getUnionSubTypes()) {
// System.out.println("getUnionSubTypes:");
// printSchemaType(schemaSubType);
//SchemaType childType =schemaType.
for (SchemaProperty schemaProperty : currentSchemaType.getElementProperties()) {
//for (int childCounter = 0; childCounter < schemaProperty.getMinOccurs().intValue(); childCounter++) {
// if the searched element is a child node of the given node return
// its SchemaType
//if (properties[i].getName().toString().equals(element)) {
// if the searched element was not a child of the given Node
// then again for each of these child nodes search recursively in
// their child nodes, in the case they are a complex type, because
// only complex types have child nodes
//currentSchemaType.getAttributeProperties();
// if ((schemaProperty.getType() != null) && (!(currentSchemaType.isSimpleType()))) {
// System.out.println("node name: " + schemaProperty.getName().getLocalPart());
// System.out.println("node.getMinOccurs(): " + schemaProperty.getMinOccurs());
// System.out.println("node.getMaxOccurs(): " + schemaProperty.getMaxOccurs());
BigInteger maxNumberToAdd;
if (addDummyData) {
maxNumberToAdd = schemaProperty.getMaxOccurs();
BigInteger dummyNumberToAdd = BigInteger.ONE.add(BigInteger.ONE).add(BigInteger.ONE);
if (maxNumberToAdd == null) {
maxNumberToAdd = dummyNumberToAdd;
} else {
if (dummyNumberToAdd.compareTo(maxNumberToAdd) == -1) {
// limit the number added and make sure it is less than the max number to add
maxNumberToAdd = dummyNumberToAdd;
}
}
} else {
maxNumberToAdd = schemaProperty.getMinOccurs();
if (maxNumberToAdd == null) {
maxNumberToAdd = BigInteger.ZERO;
}
}
for (BigInteger addNodeCounter = BigInteger.ZERO; addNodeCounter.compareTo(maxNumberToAdd) < 0; addNodeCounter = addNodeCounter.add(BigInteger.ONE)) {
constructXml(schemaProperty, currentPathString, workingDocument, nameSpaceUri, currentElement, addDummyData);
}
}
return returnNode;
}
private void printoutDocument(Document workingDocument) {
try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer transformer = tranFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Source src = new DOMSource(workingDocument);
Result dest = new StreamResult(System.out);
transformer.transform(src, dest);
} catch (Exception e) {
bugCatcher.logError(e);
}
}
public void testWalk() {
try {
//new CmdiComponentBuilder().readSchema();
Document workingDocument = getDocument(null);
//Create instance of DocumentBuilderFactory
//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
//DocumentBuilder docBuilder = factory.newDocumentBuilder();
//Create blank DOM Document
//Document doc = docBuilder.newDocument();
//create the root element
// Element root = workingDocument.createElement("root");
// //all it to the xml tree
// workingDocument.appendChild(root);
// //create a comment
// Comment comment = workingDocument.createComment("This is comment");
// //add in the root element
// root.appendChild(comment);
// //create child element
// Element childElement = workingDocument.createElement("Child");
// //Add the atribute to the child
// childElement.setAttribute("attribute1", "The value of Attribute 1");
// root.appendChild(childElement);
readSchema(workingDocument, new URI("http://catalog.clarin.eu/ds/ComponentRegistry/rest/registry/profiles/clarin.eu:cr1:p_1264769926773/xsd"), true);
printoutDocument(workingDocument);
} catch (Exception e) {
bugCatcher.logError(e);
}
}
// public static void main(String args[]) {
// //new CmdiComponentBuilder().testWalk();
// //new CmdiComponentBuilder().testRemoveArchiveHandles();
// new ArbilComponentBuilder().testInsertFavouriteComponent();
}
|
package org.jbehave.core;
import org.jbehave.core.mock.UsingMatchers;
public class UsingMatchersBehaviour {
Block EXCEPTION_BLOCK = new Block() {
public void run() throws Exception {
throw new NumberFormatException();
}
};
Block EMPTY_BLOCK = new Block() {
public void run() throws Exception {}
};
public void shouldProvideMatchersForDoubles() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that(5.0, m.eq(5.0));
Ensure.that(5.0, m.not(m.eq(5.1)));
Ensure.that(5.0, m.eq(5.0), "message");
}
public void shouldProvideMatchersForLongsAndInts() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that(5, m.eq(5));
Ensure.that(5, m.not(m.eq(4)));
Ensure.that(5, m.eq(5), "message");
}
public void shouldProvideMatchersForChars() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that('a', m.eq('a'));
Ensure.that('a', m.not(m.eq('A')));
Ensure.that('a', m.eq('a'), "message");
}
public void shouldProvideMatchersForBooleans() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that(true, m.eq(true));
Ensure.that(true, m.not(m.eq(false)));
Ensure.that(true, m.eq(true), "message");
}
public void shouldProvideMatchersToCheckForNull() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that(null, m.isNull());
Ensure.that(new Object(), m.not(m.isNull()));
Ensure.that(new Object(), m.isNotNull());
Ensure.that(null, m.not(m.isNotNull()));
}
public void shouldProvideMatchersToCheckForAnything() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that(null, m.not(m.nothing()));
Ensure.that(new Object(), m.not(m.nothing()));
Ensure.that(new Object(), m.anything());
Ensure.that(null, m.anything());
}
public void shouldProvideCommonStringMatchers() {
UsingMatchers m = new UsingMatchers() {};
Ensure.that("octopus", m.contains("top"));
Ensure.that("octopus", m.not(m.contains("eight")));
Ensure.that("octopus", m.startsWith("octo"));
Ensure.that("octopus", m.not(m.startsWith("eight")));
Ensure.that("octopus", m.endsWith("pus"));
Ensure.that("octopus", m.not(m.endsWith("eight")));
}
public void shouldProvideInstanceMatchers() {
UsingMatchers m = new UsingMatchers() {};
String a = "a";
String b = "b";
Ensure.that(a, m.is(a));
Ensure.that(a, m.not(m.is(b)));
Ensure.that(a, m.sameInstanceAs(a));
Ensure.that(a, m.not(m.sameInstanceAs(b)));
}
public void shouldCatchAndReturnAThrownException() throws Exception {
UsingMatchers m = new UsingMatchers() {};
Exception exception = m.runAndCatch(IllegalArgumentException.class, EXCEPTION_BLOCK);
Ensure.that(exception, m.isNotNull());
}
public void shouldReturnNullIfNoExceptionThrown() throws Exception {
UsingMatchers m = new UsingMatchers() {};
Exception exception = m.runAndCatch(IllegalArgumentException.class, EMPTY_BLOCK);
Ensure.that(exception, m.isNull());
}
public void shouldPropagateExceptionOfAnUnexpectedType() throws Exception {
UsingMatchers m = new UsingMatchers() {};
try {
Exception exception = m.runAndCatch(UnsupportedOperationException.class, EXCEPTION_BLOCK);
m.fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
public void shouldProvideConditionalMatchers() throws Exception {
UsingMatchers m = new UsingMatchers() {};
String horse = "horse";
String cow = "cow";
Ensure.that(horse, m.or(m.eq(horse), m.eq(cow)));
Ensure.that(cow, m.either(m.eq(horse), m.eq(cow)));
Ensure.that(horse, m.and(m.eq(horse), m.contains("ors")));
Ensure.that(cow, m.both(m.eq(cow), m.endsWith("ow")));
}
}
|
package org.pentaho.cdf.comments;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_XML;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.pentaho.cdf.util.Parameter;
import org.pentaho.cdf.utils.CorsUtil;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.security.SecurityHelper;
import pt.webdetails.cpf.utils.PluginIOUtils;
/**
*
* @author diogomariano
*/
@Path( "/pentaho-cdf/api/comments" )
public class CommentsApi {
private static final Log logger = LogFactory.getLog( CommentsApi.class );
@GET
@Path( "/add" )
@Consumes( { APPLICATION_XML, APPLICATION_JSON, APPLICATION_FORM_URLENCODED } )
public void add( @DefaultValue( "" ) @QueryParam( Parameter.PAGE ) String page,
@DefaultValue( "" ) @QueryParam( Parameter.COMMENT ) String comment,
@Context HttpServletResponse servletResponse, @Context HttpServletRequest servletRequest ) {
JSONObject json;
String result = "";
try {
json = CommentsEngine.getInstance().add( page, comment, getUserName() );
result = json.toString( 2 );
} catch ( Exception e ) {
logger.error( "Error processing comment: " + e );
}
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), result );
CorsUtil.getInstance().setCorsHeaders( servletRequest, servletResponse );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
}
@GET
@Path( "/list" )
@Consumes( { APPLICATION_XML, APPLICATION_JSON, APPLICATION_FORM_URLENCODED } )
public void list( @DefaultValue( "" ) @QueryParam( Parameter.PAGE ) String page,
@DefaultValue( "0" ) @QueryParam( Parameter.FIRST_RESULT ) int firstResult,
@DefaultValue( "20" ) @QueryParam( Parameter.MAX_RESULTS ) int maxResults,
@DefaultValue( "false" ) @QueryParam( Parameter.DELETED ) boolean deleted,
@DefaultValue( "false" ) @QueryParam( Parameter.ARCHIVED ) boolean archived,
@Context HttpServletResponse servletResponse, @Context HttpServletRequest servletRequest ) {
JSONObject json;
String result = "";
boolean isAdministrator = SecurityHelper.getInstance().isPentahoAdministrator( PentahoSessionHolder.getSession() );
if ( deleted && !isAdministrator ) {
deleted = false;
logger.warn( "only admin users are allowed to see deleted comments" );
}
if ( archived && !isAdministrator ) {
archived = false;
logger.warn( "only admin users are allowed to see archived comments" );
}
try {
json = CommentsEngine.getInstance().list( page, firstResult, maxResults, deleted, archived, getUserName() );
result = json.toString( 2 );
} catch ( Exception e ) {
logger.error( "Error processing comment: " + e );
}
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), result );
CorsUtil.getInstance().setCorsHeaders( servletRequest, servletResponse );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
}
@GET
@Path( "/archive" )
@Consumes( { APPLICATION_XML, APPLICATION_JSON, APPLICATION_FORM_URLENCODED } )
public void archive( @DefaultValue( "0" ) @QueryParam( Parameter.COMMENT_ID ) int commentId,
@DefaultValue( "true" ) @QueryParam( Parameter.VALUE ) boolean value,
@Context HttpServletResponse servletResponse, @Context HttpServletRequest servletRequest ) {
JSONObject json;
String result = "";
boolean isAdministrator = SecurityHelper.getInstance().isPentahoAdministrator( PentahoSessionHolder.getSession() );
boolean isAuthenticated = PentahoSessionHolder.getSession().isAuthenticated();
if ( !isAuthenticated ) {
String msg = "Operation not authorized: requires authentication";
logger.error( msg );
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), msg );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
return;
}
try {
json = CommentsEngine.getInstance().archive( commentId, value, getUserName(), isAdministrator );
result = json.toString( 2 );
} catch ( Exception e ) {
logger.error( "Error processing comment: " + e );
}
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), result );
CorsUtil.getInstance().setCorsHeaders( servletRequest, servletResponse );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
}
@GET
@Path( "/delete" )
@Consumes( { APPLICATION_XML, APPLICATION_JSON, APPLICATION_FORM_URLENCODED } )
public void delete( @DefaultValue( "0" ) @QueryParam( "commentId" ) int commentId,
@DefaultValue( "true" ) @QueryParam( Parameter.VALUE ) boolean value,
@Context HttpServletResponse servletResponse, @Context HttpServletRequest servletRequest ) {
JSONObject json;
String result = "";
boolean isAdministrator = SecurityHelper.getInstance().isPentahoAdministrator( PentahoSessionHolder.getSession() );
boolean isAuthenticated = PentahoSessionHolder.getSession().isAuthenticated();
if ( !isAuthenticated ) {
String msg = "Operation not authorized: requires authentication";
logger.error( msg );
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), msg );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
return;
}
try {
json = CommentsEngine.getInstance().delete( commentId, value, getUserName(), isAdministrator );
result = json.toString( 2 );
} catch ( Exception ex ) {
logger.error( "Error processing comment: " + ex );
}
try {
PluginIOUtils.writeOutAndFlush( servletResponse.getOutputStream(), result );
CorsUtil.getInstance().setCorsHeaders( servletRequest, servletResponse );
} catch ( IOException ex ) {
logger.error( "Error while outputing result", ex );
}
}
private String getUserName() {
return PentahoSessionHolder.getSession().getName();
}
}
|
package org.tigris.subversion.subclipse.ui.history;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;
import org.eclipse.team.ui.history.HistoryPage;
import org.eclipse.team.ui.history.IHistoryPageSite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.tigris.subversion.subclipse.core.ISVNLocalFile;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.ISVNRemoteFile;
import org.tigris.subversion.subclipse.core.ISVNRemoteResource;
import org.tigris.subversion.subclipse.core.ISVNResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.SVNStatus;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.ChangeCommitPropertiesCommand;
import org.tigris.subversion.subclipse.core.history.AliasManager;
import org.tigris.subversion.subclipse.core.history.ILogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntryChangePath;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.ISVNUIConstants;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.subclipse.ui.SVNUIPlugin;
import org.tigris.subversion.subclipse.ui.actions.OpenRemoteFileAction;
import org.tigris.subversion.subclipse.ui.actions.WorkspaceAction;
import org.tigris.subversion.subclipse.ui.console.TextViewerAction;
import org.tigris.subversion.subclipse.ui.dialogs.BranchTagDialog;
import org.tigris.subversion.subclipse.ui.dialogs.SetCommitPropertiesDialog;
import org.tigris.subversion.subclipse.ui.internal.Utils;
import org.tigris.subversion.subclipse.ui.operations.BranchTagOperation;
import org.tigris.subversion.subclipse.ui.operations.MergeOperation;
import org.tigris.subversion.subclipse.ui.operations.ReplaceOperation;
import org.tigris.subversion.subclipse.ui.settings.ProjectProperties;
import org.tigris.subversion.subclipse.ui.util.LinkList;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
/**
* <code>IHistoryPage</code> for generic history view
*
* @author Euegene Kuleshov (migration from legacy HistoryView)
*/
public class SVNHistoryPage extends HistoryPage {
private SashForm svnHistoryPageControl;
private SashForm innerSashForm;
HistoryTableProvider historyTableProvider;
TableViewer tableHistoryViewer;
StructuredViewer changePathsViewer;
TextViewer textViewer;
private boolean showComments;
private boolean showAffectedPaths;
private boolean wrapCommentsText;
boolean shutdown = false;
private ProjectProperties projectProperties;
// cached for efficiency
ILogEntry[] entries;
LogEntryChangePath[] currentLogEntryChangePath;
ILogEntry lastEntry;
SVNRevision revisionStart = SVNRevision.HEAD;
FetchLogEntriesJob fetchLogEntriesJob = null;
FetchAllLogEntriesJob fetchAllLogEntriesJob = null;
FetchNextLogEntriesJob fetchNextLogEntriesJob = null;
FetchChangePathJob fetchChangePathJob = null;
AliasManager tagManager;
public IResource resource;
public ISVNRemoteResource remoteResource;
private ISelection selection;
private IAction getNextAction;
private IAction getAllAction;
private IAction toggleStopOnCopyAction;
private IAction toggleShowComments;
private IAction toggleWrapCommentsAction;
private IAction toggleShowAffectedPathsAction;
private IAction openAction;
private IAction getContentsAction;
private IAction updateToRevisionAction;
private IAction openChangedPathAction;
private IAction showDifferencesAsUnifiedDiffAction;
private IAction createTagFromRevisionAction;
private IAction setCommitPropertiesAction;
private IAction revertChangesAction;
private IAction refreshAction;
private ToggleAffectedPathsLayoutAction[] toggleAffectedPathsLayoutActions;
private TextViewerAction copyAction;
private TextViewerAction selectAllAction;
private LinkList linkList;
private boolean mouseDown = false;
private boolean dragEvent = false;
private Cursor handCursor;
private Cursor busyCursor;
public SVNHistoryPage(Object object) {
// TODO Auto-generated constructor stub
}
public Control getControl() {
return svnHistoryPageControl;
}
public void setFocus() {
// TODO Auto-generated method stub
}
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return remoteResource == null ? null : remoteResource.getRepositoryRelativePath() + " in "
+ remoteResource.getRepository();
}
public boolean isValidInput(Object object) {
if(object instanceof IResource) {
RepositoryProvider provider = RepositoryProvider.getProvider(((IResource) object).getProject());
return provider instanceof SVNTeamProvider;
} else if(object instanceof ISVNRemoteResource) {
return true;
}
// TODO
// } else if(object instanceof CVSFileRevision) {
// return true;
// } else if(object instanceof CVSLocalFileRevision) {
// return true;
return false;
}
public void refresh() {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
// show a Busy Cursor during refresh
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
if(resource != null) {
try {
projectProperties = ProjectProperties.getProjectProperties(resource);
} catch(SVNException e) {
}
}
tableHistoryViewer.refresh();
}
});
}
public Object getAdapter(Class adapter) {
// TODO Auto-generated method stub
return null;
}
public boolean inputSet() {
Object input = getInput();
if(input instanceof IResource) {
IResource res = (IResource) input;
RepositoryProvider teamProvider = RepositoryProvider.getProvider(res.getProject(), SVNProviderPlugin.getTypeId());
if(teamProvider != null) {
try {
ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(res);
if(localResource != null && !localResource.getStatus().isAdded() && localResource.getStatus().isManaged()) {
this.resource = res;
this.remoteResource = localResource.getBaseResource();
this.projectProperties = ProjectProperties.getProjectProperties(res);
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setResource(res);
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// baseResource.getName())); //$NON-NLS-1$
// setTitleToolTip(baseResource.getRepositoryRelativePath());
return true;
}
} catch(TeamException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e);
}
}
} else if(input instanceof ISVNRemoteResource) {
this.resource = null;
this.remoteResource = (ISVNRemoteResource) input;
this.projectProperties = ProjectProperties.getProjectProperties(this.remoteResource);
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setResource(null);
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// remoteResource.getName())); //$NON-NLS-1$
// setTitleToolTip(remoteResource.getRepositoryRelativePath());
return true;
}
return false;
}
public void createControl(Composite parent) {
this.busyCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_WAIT);
this.handCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
this.showComments = store.getBoolean(ISVNUIConstants.PREF_SHOW_COMMENTS);
this.wrapCommentsText = store.getBoolean(ISVNUIConstants.PREF_WRAP_COMMENTS);
this.showAffectedPaths = store.getBoolean(ISVNUIConstants.PREF_SHOW_PATHS);
this.svnHistoryPageControl = new SashForm(parent, SWT.VERTICAL);
this.svnHistoryPageControl.setLayoutData(new GridData(GridData.FILL_BOTH));
this.toggleAffectedPathsLayoutActions = new ToggleAffectedPathsLayoutAction[] {
new ToggleAffectedPathsLayoutAction(this, ISVNUIConstants.LAYOUT_FLAT),
new ToggleAffectedPathsLayoutAction(this, ISVNUIConstants.LAYOUT_COMPRESSED),
};
createTableHistory(svnHistoryPageControl);
createAffectedPathsViewer(store.getInt(ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT));
contributeActions();
svnHistoryPageControl.setWeights(new int[] { 70, 30});
// set F1 help
// PlatformUI.getWorkbench().getHelpSystem().setHelp(svnHistoryPageControl,
// IHelpContextIds.RESOURCE_HISTORY_VIEW);
// initDragAndDrop();
// add listener for editor page activation - this is to support editor
// linking
// getSite().getPage().addPartListener(partListener);
// getSite().getPage().addPartListener(partListener2);
}
protected void createTableHistory(Composite parent) {
this.historyTableProvider = new HistoryTableProvider();
this.tableHistoryViewer = historyTableProvider.createTable(parent);
// set the content provider for the table
this.tableHistoryViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
// Short-circuit to optimize
if(entries != null)
return entries;
if( !(inputElement instanceof ISVNRemoteResource))
return null;
final ISVNRemoteResource remoteResource = (ISVNRemoteResource) inputElement;
if(fetchLogEntriesJob == null) {
fetchLogEntriesJob = new FetchLogEntriesJob();
}
if(fetchLogEntriesJob.getState() != Job.NONE) {
fetchLogEntriesJob.cancel();
try {
fetchLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(
Policy.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchLogEntriesJob, SVNUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActivePart().getSite());
return new Object[ 0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
}
});
// set the selectionchanged listener for the table
// updates the comments and affected paths when selection changes
this.tableHistoryViewer.addSelectionChangedListener(new ISelectionChangedListener() {
private ILogEntry currentLogEntry;
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
ILogEntry logEntry = getLogEntry((IStructuredSelection) selection);
if(logEntry != currentLogEntry) {
this.currentLogEntry = logEntry;
updatePanels(selection);
}
SVNHistoryPage.this.selection = selection;
}
});
// Double click open action
this.tableHistoryViewer.getTable().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenRemoteFileAction().run();
}
});
// Contribute actions to popup menu for the table
{
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(tableHistoryViewer.getTable());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
tableHistoryViewer.getTable().setMenu(menu);
getHistoryPageSite().getPart().getSite().registerContextMenu(menuMgr, tableHistoryViewer);
}
}
private void fillTableMenu(IMenuManager manager) {
// file actions go first (view file)
manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE));
// Add the "Add to Workspace" action if 1 revision is selected.
ISelection sel = tableHistoryViewer.getSelection();
if( !sel.isEmpty()) {
if(sel instanceof IStructuredSelection) {
if(((IStructuredSelection) sel).size() == 1) {
if(resource != null && resource instanceof IFile) {
manager.add(getGetContentsAction());
manager.add(getUpdateToRevisionAction());
}
manager.add(getShowDifferencesAsUnifiedDiffAction());
// if (resource != null) {
manager.add(getCreateTagFromRevisionAction());
manager.add(getSetCommitPropertiesAction());
}
if(resource != null)
manager.add(getRevertChangesAction());
}
}
manager.add(new Separator("additions")); //$NON-NLS-1$
manager.add(getRefreshAction());
manager.add(new Separator("additions-end")); //$NON-NLS-1$
}
public void createAffectedPathsViewer(int layout) {
for(int i = 0; i < toggleAffectedPathsLayoutActions.length; i++) {
ToggleAffectedPathsLayoutAction action = toggleAffectedPathsLayoutActions[ i];
action.setChecked(layout == action.getLayout());
}
if(innerSashForm != null) {
innerSashForm.dispose();
}
if(changePathsViewer != null) {
changePathsViewer.getControl().dispose();
}
innerSashForm = new SashForm(svnHistoryPageControl, SWT.HORIZONTAL);
switch(layout) {
case ISVNUIConstants.LAYOUT_COMPRESSED:
changePathsViewer = new ChangePathsTreeViewer(innerSashForm);
changePathsViewer.setContentProvider(new ChangePathsTreeContentProvider());
break;
default:
changePathsViewer = new ChangePathsTableProvider(innerSashForm);
changePathsViewer.setContentProvider(new ChangePathsTableContentProvider());
break;
}
changePathsViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
SVNHistoryPage.this.selection = changePathsViewer.getSelection();
}
});
changePathsViewer.getControl().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenChangedPathAction().run();
}
});
createText(innerSashForm);
setViewerVisibility();
innerSashForm.layout();
svnHistoryPageControl.layout();
updatePanels(tableHistoryViewer.getSelection());
}
/**
* Create the TextViewer for the logEntry comments
*/
protected void createText(Composite parent) {
this.textViewer = new TextViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY);
this.textViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
copyAction.update();
}
});
Font font = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry().get(
ISVNUIConstants.SVN_COMMENT_FONT);
if(font != null) {
this.textViewer.getTextWidget().setFont(font);
}
this.textViewer.getTextWidget().addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
if(e.button != 1) {
return;
}
mouseDown = true;
}
public void mouseUp(MouseEvent e) {
mouseDown = false;
StyledText text = (StyledText) e.widget;
int offset = text.getCaretOffset();
if(dragEvent) {
// don't activate a link during a drag/mouse up operation
dragEvent = false;
if(linkList != null && linkList.isLinkAt(offset)) {
text.setCursor(handCursor);
}
} else {
if(linkList != null && linkList.isLinkAt(offset)) {
text.setCursor(busyCursor);
try {
URL url = new URL(linkList.getLinkAt(offset));
PlatformUI.getWorkbench().getBrowserSupport().createBrowser("Subclipse").openURL(url);
} catch (Exception e1) {
Program.launch(linkList.getLinkAt(offset));
}
// Program.launch(linkList.getLinkAt(offset));
text.setCursor(null);
}
}
}
});
this.textViewer.getTextWidget().addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent e) {
// Do not change cursor on drag events
if(mouseDown) {
if( !dragEvent) {
StyledText text = (StyledText) e.widget;
text.setCursor(null);
}
dragEvent = true;
return;
}
StyledText text = (StyledText) e.widget;
int offset = -1;
try {
offset = text.getOffsetAtLocation(new Point(e.x, e.y));
} catch(IllegalArgumentException ex) {
}
if(offset == -1) {
text.setCursor(null);
} else if(linkList != null && linkList.isLinkAt(offset)) {
text.setCursor(handCursor);
} else {
text.setCursor(null);
}
}
});
// Create actions for the text editor (copy and select all)
copyAction = new TextViewerAction(this.textViewer, ITextOperationTarget.COPY);
copyAction.setText(Policy.bind("HistoryView.copy")); //$NON-NLS-1$
selectAllAction = new TextViewerAction(this.textViewer, ITextOperationTarget.SELECT_ALL);
selectAllAction.setText(Policy.bind("HistoryView.selectAll")); //$NON-NLS-1$
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, copyAction);
actionBars.setGlobalActionHandler(ITextEditorActionConstants.SELECT_ALL, selectAllAction);
actionBars.updateActionBars();
// Contribute actions to popup menu for the comments area
{
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
menuMgr.add(copyAction);
menuMgr.add(selectAllAction);
}
});
StyledText text = this.textViewer.getTextWidget();
Menu menu = menuMgr.createContextMenu(text);
text.setMenu(menu);
}
}
private void contributeActions() {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
final IPreferenceStore store = plugin.getPreferenceStore();
toggleShowComments = new Action(Policy.bind("HistoryView.showComments")) { //$NON-NLS-1$
public void run() {
showComments = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_COMMENTS, showComments);
}
};
toggleShowComments.setChecked(showComments);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextAction,
// IHelpContextIds.SHOW_COMMENT_IN_HISTORY_ACTION);
// Toggle wrap comments action
toggleWrapCommentsAction = new Action(Policy.bind("HistoryView.wrapComments")) { //$NON-NLS-1$
public void run() {
wrapCommentsText = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_WRAP_COMMENTS, wrapCommentsText);
}
};
toggleWrapCommentsAction.setChecked(wrapCommentsText);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextWrapAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle path visible action
toggleShowAffectedPathsAction = new Action(Policy.bind("HistoryView.showAffectedPaths")) { //$NON-NLS-1$
public void run() {
showAffectedPaths = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_PATHS, showAffectedPaths);
}
};
toggleShowAffectedPathsAction.setChecked(showAffectedPaths);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleListAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle stop on copy action
toggleStopOnCopyAction = new Action(Policy.bind("HistoryView.stopOnCopy")) { //$NON-NLS-1$
public void run() {
refresh();
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(ISVNUIConstants.PREF_STOP_ON_COPY,
toggleStopOnCopyAction.isChecked());
}
};
toggleStopOnCopyAction.setChecked(store.getBoolean(ISVNUIConstants.PREF_STOP_ON_COPY));
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
actionBarsMenu.add(toggleWrapCommentsAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleShowComments);
actionBarsMenu.add(toggleShowAffectedPathsAction);
actionBarsMenu.add(toggleStopOnCopyAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleAffectedPathsLayoutActions[0]);
actionBarsMenu.add(toggleAffectedPathsLayoutActions[1]);
// Create the local tool bar
IToolBarManager tbm = actionBars.getToolBarManager();
// tbm.add(getRefreshAction());
tbm.add(new Separator());
tbm.add(getGetNextAction());
tbm.add(getGetAllAction());
// tbm.add(getLinkWithEditorAction());
tbm.update(false);
actionBars.updateActionBars();
}
ILogEntry getLogEntry(IStructuredSelection ss) {
if(ss.getFirstElement() instanceof LogEntryChangePath) {
return ((LogEntryChangePath) ss.getFirstElement()).getLogEntry();
}
return (ILogEntry) ss.getFirstElement();
}
void updatePanels(ISelection selection) {
if(selection == null || !(selection instanceof IStructuredSelection)) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() != 1) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
LogEntry entry = (LogEntry) ss.getFirstElement();
textViewer.setDocument(new Document(entry.getComment()));
StyledText text = textViewer.getTextWidget();
if(projectProperties == null) {
linkList = ProjectProperties.getUrls(entry.getComment());
} else {
linkList = projectProperties.getLinkList(entry.getComment());
}
if(linkList != null) {
int[][] linkRanges = linkList.getLinkRanges();
// String[] urls = linkList.getUrls();
for(int i = 0; i < linkRanges.length; i++) {
text.setStyleRange(new StyleRange(linkRanges[ i][ 0], linkRanges[ i][ 1],
JFaceColors.getHyperlinkText(Display.getCurrent()), null));
}
}
changePathsViewer.setInput(entry);
}
void setViewerVisibility() {
if(showComments && showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(null);
} else if(showComments) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(textViewer.getTextWidget());
} else if(showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(changePathsViewer.getControl());
} else {
svnHistoryPageControl.setMaximizedControl(tableHistoryViewer.getControl());
}
changePathsViewer.refresh();
textViewer.getTextWidget().setWordWrap(wrapCommentsText);
}
void setCurrentLogEntryChangePath(final LogEntryChangePath[] currentLogEntryChangePath) {
this.currentLogEntryChangePath = currentLogEntryChangePath;
if( !shutdown) {
// Getting the changePaths
/*
* final SVNRevision.Number revisionId =
* remoteResource.getLastChangedRevision();
*/
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(currentLogEntryChangePath != null && changePathsViewer != null
&& !changePathsViewer.getControl().isDisposed()) {
// once we got the changePath, we refresh the table
changePathsViewer.refresh();
// selectRevision(revisionId);
}
}
});
}
}
/**
* Select the revision in the receiver.
*/
public void selectRevision(SVNRevision.Number revision) {
if(entries == null) {
return;
}
ILogEntry entry = null;
for(int i = 0; i < entries.length; i++) {
if(entries[ i].getRevision().equals(revision)) {
entry = entries[ i];
break;
}
}
if(entry != null) {
IStructuredSelection selection = new StructuredSelection(entry);
tableHistoryViewer.setSelection(selection, true);
}
}
public void scheduleFetchChangePathJob(ILogEntry logEntry) {
if(fetchChangePathJob == null) {
fetchChangePathJob = new FetchChangePathJob();
}
if(fetchChangePathJob.getState() != Job.NONE) {
fetchChangePathJob.cancel();
try {
fetchChangePathJob.join();
} catch(InterruptedException e) {
e.printStackTrace();
// SVNUIPlugin.log(new
// SVNException(Policy.bind("HistoryView.errorFetchingEntries",
// remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchChangePathJob.setLogEntry(logEntry);
Utils.schedule(fetchChangePathJob, getSite());
}
public boolean isShowChangePaths() {
// return toggleShowAffectedPathsAction.isChecked();
return true;
}
private IAction getOpenRemoteFileAction() {
if(openAction == null) {
openAction = new Action() {
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.init(this);
delegate.selectionChanged(this, tableHistoryViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
return openAction;
}
// open changed Path (double-click)
private IAction getOpenChangedPathAction() {
if(openChangedPathAction == null) {
openChangedPathAction = new Action() {
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.init(this);
delegate.selectionChanged(this, changePathsViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
return openChangedPathAction;
}
// get contents Action (context menu)
private IAction getGetContentsAction() {
if(getContentsAction == null) {
getContentsAction = getContextMenuAction(Policy.bind("HistoryView.getContentsAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
monitor.beginTask(null, 100);
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
InputStream in = ((IResourceVariant) remoteFile).getStorage(new SubProgressMonitor(monitor, 50))
.getContents();
IFile file = (IFile) resource;
file.setContents(in, false, true, new SubProgressMonitor(monitor, 50));
}
}
} catch(TeamException e) {
throw new CoreException(e.getStatus());
} finally {
monitor.done();
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION);
}
return getContentsAction;
}
// get differences as unified diff action (context menu)
private IAction getShowDifferencesAsUnifiedDiffAction() {
if(showDifferencesAsUnifiedDiffAction == null) {
showDifferencesAsUnifiedDiffAction = new Action(
Policy.bind("HistoryView.showDifferences"), SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_DIFF)) { //$NON-NLS-1$
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
ILogEntry currentSelection = getLogEntry((IStructuredSelection) selection);
FileDialog dialog = new FileDialog(getSite().getShell(), SWT.SAVE);
dialog.setText("Select Unified Diff Output File");
dialog.setFileName("revision" + currentSelection.getRevision().getNumber() + ".diff"); //$NON-NLS-1$
String outFile = dialog.open();
if(outFile != null) {
final SVNUrl url = currentSelection.getResource().getUrl();
final SVNRevision oldUrlRevision = new SVNRevision.Number(currentSelection.getRevision().getNumber() - 1);
final SVNRevision newUrlRevision = currentSelection.getRevision();
final File file = new File(outFile);
if(file.exists()) {
if( !MessageDialog.openQuestion(getSite().getShell(), Policy.bind("HistoryView.showDifferences"), Policy
.bind("HistoryView.overwriteOutfile", file.getName())))
return;
}
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
client.diff(url, oldUrlRevision, newUrlRevision, file, true);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.showDifferences"), e
.getMessage());
}
}
});
}
}
};
}
return showDifferencesAsUnifiedDiffAction;
}
// update to the selected revision (context menu)
private IAction getUpdateToRevisionAction() {
if(updateToRevisionAction == null) {
updateToRevisionAction = getContextMenuAction(
Policy.bind("HistoryView.getRevisionAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
IFile file = (IFile) resource;
new ReplaceOperation(getSite().getPage().getActivePart(), file, remoteFile.getLastChangedRevision())
.run(monitor);
historyTableProvider.setRemoteResource(remoteFile);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
}
});
}
}
} catch(InvocationTargetException e) {
throw new CoreException(new SVNStatus(IStatus.ERROR, 0, e.getMessage()));
} catch(InterruptedException e) {
// Cancelled by user
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(updateToRevisionAction,
IHelpContextIds.GET_FILE_REVISION_ACTION);
}
return updateToRevisionAction;
}
// get create tag from revision action (context menu)
private IAction getCreateTagFromRevisionAction() {
if(createTagFromRevisionAction == null) {
createTagFromRevisionAction = new Action(
Policy.bind("HistoryView.createTagFromRevision"), SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_TAG)) { //$NON-NLS-1$
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
ILogEntry currentSelection = getLogEntry((IStructuredSelection) selection);
BranchTagDialog dialog;
if(resource == null)
dialog = new BranchTagDialog(getSite().getShell(), historyTableProvider.getRemoteResource());
else
dialog = new BranchTagDialog(getSite().getShell(), resource);
dialog.setRevisionNumber(currentSelection.getRevision().getNumber());
if(dialog.open() == BranchTagDialog.CANCEL)
return;
final SVNUrl sourceUrl = dialog.getUrl();
final SVNUrl destinationUrl = dialog.getToUrl();
final String message = dialog.getComment();
final SVNRevision revision = dialog.getRevision();
boolean createOnServer = dialog.isCreateOnServer();
IResource[] resources = { resource};
try {
if(resource == null) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
client.copy(sourceUrl, destinationUrl, message, revision);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
});
} else {
new BranchTagOperation(getSite().getPage().getActivePart(), resources, sourceUrl, destinationUrl,
createOnServer, dialog.getRevision(), message).run();
}
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
};
}
return createTagFromRevisionAction;
}
private IAction getSetCommitPropertiesAction() {
// set Action (context menu)
if(setCommitPropertiesAction == null) {
setCommitPropertiesAction = new Action(Policy.bind("HistoryView.setCommitProperties")) {
public void run() {
try {
final ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final ILogEntry ourSelection = getLogEntry((IStructuredSelection) selection);
// Failing that, try the resource originally selected by the user if
// from the Team menu
// TODO: Search all paths from currentSelection and find the
// shortest path and
// get the resources for that instance (in order to get the 'best'
// "bugtraq" properties)
final ProjectProperties projectProperties = (resource != null) ? ProjectProperties
.getProjectProperties(resource) : ProjectProperties.getProjectProperties(ourSelection
.getRemoteResource()); // will return null!
final ISVNResource svnResource = ourSelection.getRemoteResource() != null ? ourSelection
.getRemoteResource() : ourSelection.getResource();
SetCommitPropertiesDialog dialog = new SetCommitPropertiesDialog(getSite().getShell(), ourSelection
.getRevision(), resource, projectProperties);
// Set previous text - the text to edit
dialog.setOldAuthor(ourSelection.getAuthor());
dialog.setOldComment(ourSelection.getComment());
boolean doCommit = (dialog.open() == Window.OK);
if(doCommit) {
final String author;
final String commitComment;
if(ourSelection.getAuthor().equals(dialog.getAuthor()))
author = null;
else
author = dialog.getAuthor();
if(ourSelection.getComment().equals(dialog.getComment()))
commitComment = null;
else
commitComment = dialog.getComment();
final ChangeCommitPropertiesCommand command = new ChangeCommitPropertiesCommand(svnResource
.getRepository(), ourSelection.getRevision(), commitComment, author);
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
command.run(monitor);
if(ourSelection instanceof LogEntry) {
LogEntry logEntry = (LogEntry) ourSelection;
logEntry.setComment(commitComment);
logEntry.setAuthor(author);
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection, true);
}
});
} catch(SVNException e) {
throw new InvocationTargetException(e);
}
}
});
}
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
} catch(SVNException e) {
// TODO Auto-generated catch block
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_TEAM_EXCEPTIONS);
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
return setCommitPropertiesAction;
}
// get revert changes action (context menu)
private IAction getRevertChangesAction() {
if(revertChangesAction == null) {
revertChangesAction = new Action() {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevision", resource.getFullPath().toString())))
return;
} else {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevisions", resource.getFullPath().toString())))
return;
}
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
final SVNUrl path1 = firstElement.getResource().getUrl();
final SVNRevision revision1 = firstElement.getRevision();
final SVNUrl path2 = lastElement.getResource().getUrl();
final SVNRevision revision2 = new SVNRevision.Number(lastElement.getRevision().getNumber() - 1);
final IResource[] resources = { resource};
try {
WorkspaceAction mergeAction = new WorkspaceAction() {
protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
new MergeOperation(getSite().getPage().getActivePart(), resources, path1, revision1, path2,
revision2).run();
}
};
mergeAction.run(null);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), revertChangesAction.getText(), e.getMessage());
}
}
});
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevision", ""
+ currentSelection.getRevision().getNumber()));
}
if(ss.size() > 1) {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevisions", ""
+ lastElement.getRevision().getNumber(), "" + firstElement.getRevision().getNumber()));
}
}
revertChangesAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MERGE));
return revertChangesAction;
}
// Refresh action (toolbar)
private IAction getRefreshAction() {
if(refreshAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
refreshAction = new Action(
Policy.bind("HistoryView.refreshLabel"), plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_ENABLED)) { //$NON-NLS-1$
public void run() {
refresh();
}
};
refreshAction.setToolTipText(Policy.bind("HistoryView.refresh")); //$NON-NLS-1$
refreshAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_DISABLED));
refreshAction.setHoverImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH));
}
return refreshAction;
}
// Get Get All action (toolbar)
private IAction getGetAllAction() {
if(getAllAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
getAllAction = new Action(
Policy.bind("HistoryView.getAll"), plugin.getImageDescriptor(ISVNUIConstants.IMG_GET_ALL)) { //$NON-NLS-1$
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
try {
fetchAllLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
}
};
getAllAction.setToolTipText(Policy.bind("HistoryView.getAll")); //$NON-NLS-1$
}
return getAllAction;
}
// Get Get Next action (toolbar)
public IAction getGetNextAction() {
if(getNextAction == null) {
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
getNextAction = new Action(
Policy.bind("HistoryView.getNext"), plugin.getImageDescriptor(ISVNUIConstants.IMG_GET_NEXT)) { //$NON-NLS-1$
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchNextLogEntriesJob == null) {
fetchNextLogEntriesJob = new FetchNextLogEntriesJob();
}
if(fetchNextLogEntriesJob.getState() != Job.NONE) {
fetchNextLogEntriesJob.cancel();
try {
fetchNextLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchNextLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchNextLogEntriesJob, getSite());
}
};
getNextAction.setToolTipText(Policy.bind("HistoryView.getNext") + " " + entriesToFetch); //$NON-NLS-1$
if(entriesToFetch <= 0)
getNextAction.setEnabled(false);
}
return getNextAction;
}
/**
* All context menu actions use this class This action : - updates
* currentSelection - action.run
*/
private Action getContextMenuAction(String title, final IWorkspaceRunnable action) {
return new Action(title) {
public void run() {
try {
if(resource == null)
return;
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
action.run(monitor);
} catch(CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
/**
* Ask the user to confirm the overwrite of the file if the file has been
* modified since last commit
*/
private boolean confirmOverwrite() {
IFile file = (IFile) resource;
if(file != null && file.exists()) {
ISVNLocalFile svnFile = SVNWorkspaceRoot.getSVNFileFor(file);
try {
if(svnFile.isDirty()) {
String title = Policy.bind("HistoryView.overwriteTitle"); //$NON-NLS-1$
String msg = Policy.bind("HistoryView.overwriteMsg"); //$NON-NLS-1$
final MessageDialog dialog = new MessageDialog(getSite().getShell(), title, null, msg,
MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
final int[] result = new int[ 1];
getSite().getShell().getDisplay().syncExec(new Runnable() {
public void run() {
result[ 0] = dialog.open();
}
});
if(result[ 0] != 0) {
// cancel
return false;
}
}
} catch(SVNException e) {
SVNUIPlugin.log(e.getStatus());
}
}
return true;
}
private ISelection getSelection() {
return selection;
}
private ILogEntry getFirstElement() {
ILogEntry firstElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(firstElement == null || element.getRevision().getNumber() > firstElement.getRevision().getNumber())
firstElement = element;
}
}
return firstElement;
}
private ILogEntry getLastElement() {
ILogEntry lastElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(lastElement == null || element.getRevision().getNumber() < lastElement.getRevision().getNumber())
lastElement = element;
}
}
return lastElement;
}
private class FetchLogEntriesJob extends Job {
public ISVNRemoteResource remoteResource;
public FetchLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE)) {
tagManager = null;
} else {
tagManager = new AliasManager(remoteResource.getUrl());
}
} else {
tagManager = new AliasManager(resource);
}
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
entries = remoteResource.getLogEntries(monitor, pegRevision, revisionStart, revisionEnd, stopOnCopy,
limit + 1, tagManager);
long entriesLength = entries.length;
if(entriesLength > limit) {
ILogEntry[] fetchedEntries = new ILogEntry[ entries.length - 1];
for(int i = 0; i < entries.length - 1; i++) {
fetchedEntries[ i] = entries[ i];
}
entries = fetchedEntries;
getNextAction.setEnabled(true);
} else {
getNextAction.setEnabled(false);
}
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class FetchNextLogEntriesJob extends Job {
public ISVNRemoteResource remoteResource;
public FetchNextLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
ILogEntry[] nextEntries = remoteResource.getLogEntries(monitor, pegRevision, revisionStart, revisionEnd,
stopOnCopy, limit + 1, tagManager);
long entriesLength = nextEntries.length;
if(entriesLength > limit) {
ILogEntry[] fetchedEntries = new ILogEntry[ nextEntries.length - 1];
for(int i = 0; i < nextEntries.length - 1; i++)
fetchedEntries[ i] = nextEntries[ i];
getNextAction.setEnabled(true);
} else {
getNextAction.setEnabled(false);
}
ArrayList entryArray = new ArrayList();
if(entries == null)
entries = new ILogEntry[ 0];
for(int i = 0; i < entries.length; i++)
entryArray.add(entries[ i]);
for(int i = 0; i < nextEntries.length; i++)
entryArray.add(nextEntries[ i]);
entries = new ILogEntry[ entryArray.size()];
entryArray.toArray(entries);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
ISelection selection = tableHistoryViewer.getSelection();
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection);
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class FetchAllLogEntriesJob extends Job {
public ISVNRemoteResource remoteResource;
public FetchAllLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE))
tagManager = null;
else
tagManager = new AliasManager(remoteResource.getUrl());
} else
tagManager = new AliasManager(resource);
SVNRevision pegRevision = remoteResource.getRevision();
revisionStart = SVNRevision.HEAD;
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
long limit = 0;
entries = remoteResource.getLogEntries(monitor, pegRevision, revisionStart, revisionEnd, stopOnCopy, limit,
tagManager);
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
class FetchChangePathJob extends Job {
public ILogEntry logEntry;
public FetchChangePathJob() {
super(Policy.bind("HistoryView.fetchChangePathJob")); //$NON-NLS-1$;
}
public void setLogEntry(ILogEntry logEntry) {
this.logEntry = logEntry;
}
public IStatus run(IProgressMonitor monitor) {
if(logEntry.getResource() != null) {
setCurrentLogEntryChangePath(logEntry.getLogEntryChangePaths());
}
return Status.OK_STATUS;
}
}
static final LogEntryChangePath[] EMPTY_CHANGE_PATHS = new LogEntryChangePath[ 0];
class ChangePathsTableContentProvider implements IStructuredContentProvider {
public Object[] getElements(Object inputElement) {
if( !isShowChangePaths() || !(inputElement instanceof ILogEntry)) {
return EMPTY_CHANGE_PATHS;
}
ILogEntry logEntry = (ILogEntry) inputElement;
if(SVNProviderPlugin.getPlugin().getSVNClientManager().isFetchChangePathOnDemand()) {
if(currentLogEntryChangePath != null) {
return currentLogEntryChangePath;
}
scheduleFetchChangePathJob(logEntry);
return EMPTY_CHANGE_PATHS;
}
return logEntry.getLogEntryChangePaths();
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
currentLogEntryChangePath = null;
}
}
class ChangePathsTreeContentProvider implements ITreeContentProvider {
public Object[] getChildren(Object parentElement) {
if(parentElement instanceof HistoryFolder) {
return ((HistoryFolder) parentElement).getChildren();
}
return null;
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
if(element instanceof HistoryFolder) {
HistoryFolder folder = (HistoryFolder) element;
return folder.getChildren().length > 0;
}
return false;
}
public Object[] getElements(Object inputElement) {
if( !isShowChangePaths() || !(inputElement instanceof ILogEntry)) {
return EMPTY_CHANGE_PATHS;
}
if(currentLogEntryChangePath != null) {
}
ILogEntry logEntry = (ILogEntry) inputElement;
if(SVNProviderPlugin.getPlugin().getSVNClientManager().isFetchChangePathOnDemand()) {
if(currentLogEntryChangePath != null) {
return getGroups(currentLogEntryChangePath);
}
scheduleFetchChangePathJob(logEntry);
return EMPTY_CHANGE_PATHS;
}
return getGroups(logEntry.getLogEntryChangePaths());
}
private Object[] getGroups(LogEntryChangePath[] changePaths) {
// 1st pass. Collect folder names
Set folderNames = new HashSet();
for(int i = 0; i < changePaths.length; i++) {
folderNames.add(getFolderName(changePaths[ i]));
}
// 2nd pass. Sorting out explicitly changed folders
TreeMap folders = new TreeMap();
for(int i = 0; i < changePaths.length; i++) {
LogEntryChangePath changePath = changePaths[ i];
String path = changePath.getPath();
if(folderNames.contains(path)) {
// changed folder
HistoryFolder folder = (HistoryFolder) folders.get(path);
if(folder == null) {
folder = new HistoryFolder(changePath);
folders.put(path, folder);
}
} else {
// changed resource
path = getFolderName(changePath);
HistoryFolder folder = (HistoryFolder) folders.get(path);
if(folder == null) {
folder = new HistoryFolder(path);
folders.put(path, folder);
}
folder.add(changePath);
}
}
// 3rd pass. Optimize folders with one or no children
ArrayList groups = new ArrayList();
for(Iterator it = folders.values().iterator(); it.hasNext();) {
HistoryFolder folder = (HistoryFolder) it.next();
Object[] children = folder.getChildren();
if(children.length == 1) {
LogEntryChangePath changePath = (LogEntryChangePath) children[ 0];
groups.add(new HistoryFolder(changePath));
} else if(children.length > 1) {
groups.add(folder);
}
}
return groups.toArray();
}
private String getFolderName(LogEntryChangePath changePath) {
String path = changePath.getPath();
int n = path.lastIndexOf('/');
return n > -1 ? path.substring(0, n) : path;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
currentLogEntryChangePath = null;
}
}
public static class ToggleAffectedPathsLayoutAction extends Action {
private final SVNHistoryPage page;
private final int layout;
public ToggleAffectedPathsLayoutAction( SVNHistoryPage page, int layout) {
super("", AS_RADIO_BUTTON);
this.page = page;
this.layout = layout;
String id = null;
switch(layout) {
case ISVNUIConstants.LAYOUT_FLAT:
setText(Policy.bind("HistoryView.affectedPathsFlatLayout")); //$NON-NLS-1$
id = ISVNUIConstants.IMG_AFFECTED_PATHS_FLAT_LAYOUT;
break;
case ISVNUIConstants.LAYOUT_COMPRESSED:
setText(Policy.bind("HistoryView.affectedPathsCompressedLayout")); //$NON-NLS-1$
id = ISVNUIConstants.IMG_AFFECTED_PATHS_COMPRESSED_LAYOUT;
break;
}
setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(id));
}
public int getLayout() {
return this.layout;
}
public void run() {
if (isChecked()) {
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT, layout);
page.createAffectedPathsViewer(layout);
}
}
}
}
|
package no.priv.bang.ukelonn.impl;
import static no.priv.bang.ukelonn.impl.CommonDatabaseMethods.*;
import java.security.Principal;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
public class UkelonnUI extends UI {
private static final long serialVersionUID = 1388525490129647161L;
@Override
protected void init(VaadinRequest request) {
Principal currentUser = request.getUserPrincipal();
Account account = getAccountInfoFromDatabase(getClass(), (String) currentUser.getName());
// Create the content root layout for the UI
VerticalLayout content = new VerticalLayout();
setContent(content);
// Display the greeting
Component greeting = new Label("Hello " + account.getFirstName());
greeting.setStyleName("h1");
content.addComponent(greeting);
// Have a clickable button
content.addComponent(new Button("Registrer jobb",
new Button.ClickListener() {
private static final long serialVersionUID = 2723190031041985566L;
@Override
public void buttonClick(ClickEvent e) {
Notification.show("Pushed!");
}
}));
}
}
|
package md2k.mCerebrum.cStress.Features;
import md2k.mCerebrum.cStress.SensorConfiguration;
import md2k.mCerebrum.cStress.Structs.DataPoint;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.ArrayList;
public class RIPFeatures {
//ripfeature_extraction.m
public DescriptiveStatistics InspDuration;
public DescriptiveStatistics ExprDuration;
public DescriptiveStatistics RespDuration;
public DescriptiveStatistics Stretch;
//public DescriptiveStatistics StretchUp;
//public DescriptiveStatistics StretchDown;
public DescriptiveStatistics IERatio;
public DescriptiveStatistics RSA;
//ripfeature_extraction_by_window
private SensorConfiguration sensorConfig;
public RIPFeatures(DataPoint[] rip, ECGFeatures ecg, SensorConfiguration sc) {
//Initialize statistics
InspDuration = new DescriptiveStatistics();
ExprDuration = new DescriptiveStatistics();
RespDuration = new DescriptiveStatistics();
Stretch = new DescriptiveStatistics();
//StretchUp = new DescriptiveStatistics();
//StretchDown = new DescriptiveStatistics();
IERatio = new DescriptiveStatistics();
RSA = new DescriptiveStatistics();
sensorConfig = sc;
ArrayList<DataPoint[]> windowedData = window(rip);
for (DataPoint[] darray : windowedData) {
DescriptiveStatistics statsSeg = new DescriptiveStatistics();
for (DataPoint d : darray) {
statsSeg.addValue(d.value);
}
double min = statsSeg.getMin();
double max = statsSeg.getMax();
//double median = ripMedian; //TODO: Is this the correct way to get median? Currently it is using mean from a daily stats tracker.
//TODO: This doesn't appear to be correct. See peakvalley_v2.m
int peakindex = 0;
double peakValue = -1e9;
for (int i = 0; i < darray.length; i++) {
if (darray[i].value > peakValue) {
peakindex = i;
}
}
InspDuration.addValue(darray[peakindex].timestamp - darray[0].timestamp);
ExprDuration.addValue(darray[darray.length].timestamp - darray[peakindex].timestamp);
RespDuration.addValue(darray[darray.length].timestamp - darray[0].timestamp);
Stretch.addValue(max - min); //TODO: Verify what this is: BreathStretchCalculate.m
//StretchUp.addValue(max - median);
//StretchDown.addValue(median - min);
IERatio.addValue( (darray[peakindex].timestamp - darray[0].timestamp) / (darray[darray.length].timestamp - darray[peakindex].timestamp) );
//RSA.addValue(rsaCalculateCycle(darray, ecg) );
}
}
private ArrayList<DataPoint[]> window(DataPoint[] rip) {
ArrayList<DataPoint[]> result = new ArrayList<>();
//TODO: Windowing code here
return result;
}
private PeakValley peakvalley_v2(DataPoint[] rip) {
DataPoint[] sample = smooth(rip, 5);
int windowLength= (int) Math.round(8.0 * sensorConfig.getFrequency("RIP"));
DataPoint[] MAC = smooth(sample, windowLength); //TODO: Verify the purpose the MATLAB's moving average and the difference between smooth
ArrayList<Integer> upInterceptIndex = new ArrayList<>();
ArrayList<Integer> downInterceptIndex = new ArrayList<>();
for(int i=1; i<MAC.length; i++) {
if (sample[i-1].value <= MAC[i-1].value && sample[i].value > MAC[i].value) {
upInterceptIndex.add(i-1);
} else if (sample[i-1].value >= MAC[i-1].value && sample[i].value < MAC[i].value) {
downInterceptIndex.add(i-1);
}
}
Intercepts UIDI = InterceptOutlierDetectorRIPLamia(upInterceptIndex,downInterceptIndex,sample,windowLength);
int[] UI = UIDI.UI;
int[] DI = UIDI.DI;
ArrayList<Integer> peakIndex = new ArrayList<>();
ArrayList<Integer> valleyIndex = new ArrayList<>();
for(int i=0; i<UI.length; i++) {
int peakindex = 0;
double peakValue = -1e9;
for (int j = UI[i]; j < DI[i+1]; j++) {
if (sample[j].value > peakValue) {
peakindex = j;
}
}
peakIndex.add(peakindex);
DataPoint[] temp = new DataPoint[UI[i]-DI[i]];
System.arraycopy(sample,DI[i],temp,0,UI[i]-DI[i]);
MaxMin maxMinTab = localMaxMin(temp, 1);
if (maxMinTab.mintab.length == 0) {
int valleyindex = 0;
double valleyValue = 1e9;
for (int j = DI[i]; j < UI[i]; j++) {
if (sample[j].value < valleyValue) {
valleyindex = j;
}
}
valleyIndex.add(valleyindex);
} else {
valleyIndex.add(DI[i]+(int)maxMinTab.mintab[maxMinTab.mintab.length-1].timestamp - 1); //timestamp is index in this case
}
}
double[] inspirationAmplitude = new double[valleyIndex.size()];
double[] expirationAmplitude = new double[valleyIndex.size()];
double meanInspirationAmplitude = 0.0;
double meanExpirationAmplitude = 0.0;
for(int i=0; i<valleyIndex.size()-1; i++) {
inspirationAmplitude[i] = sample[peakIndex.get(i)].value - sample[valleyIndex.get(i)].value;
expirationAmplitude[i] = Math.abs(sample[valleyIndex.get(i+1)].value - sample[peakIndex.get(i)].value);
meanInspirationAmplitude += inspirationAmplitude[i];
meanExpirationAmplitude += expirationAmplitude[i];
}
meanInspirationAmplitude /= (valleyIndex.size()-1);
meanExpirationAmplitude /= (valleyIndex.size()-1);
ArrayList<Integer> finalPeakIndex = new ArrayList<>();
ArrayList<Integer> finalValleyIndex = new ArrayList<>();
for(int i=0; i<inspirationAmplitude.length; i++) {
if( inspirationAmplitude[i] > 0.15*meanInspirationAmplitude ) {
finalPeakIndex.add(peakIndex.get(i));
finalValleyIndex.add(valleyIndex.get(i));
}
}
ArrayList<Integer> resultPeakIndex = new ArrayList<>();
ArrayList<Integer> resultValleyIndex = new ArrayList<>();
resultValleyIndex.add(finalValleyIndex.get(0));
for(int i=0; i<expirationAmplitude.length; i++) {
if( expirationAmplitude[i] > 0.15*meanExpirationAmplitude ) {
resultValleyIndex.add(finalValleyIndex.get(i+1));
resultPeakIndex.add(finalPeakIndex.get(i));
}
}
resultPeakIndex.add(finalPeakIndex.get(finalPeakIndex.size()-1));
PeakValley result = new PeakValley();
result.valleyIndex = resultValleyIndex;
result.peakIndex = resultPeakIndex;
return result;
}
private class MaxMin {
public DataPoint[] maxtab;
public DataPoint[] mintab;
public MaxMin() {
maxtab = new DataPoint[0];
mintab = new DataPoint[0];
}
}
private MaxMin localMaxMin(DataPoint[] temp, int delta) {
MaxMin result = new MaxMin();
ArrayList<DataPoint> maxtab = new ArrayList<>();
ArrayList<DataPoint> mintab = new ArrayList<>();
double mn = 1e9;
double mx = -1e9;
boolean lookformax = true;
double tempvalue;
int mxpos = -1;
int mnpos = -1;
for(int x=0; x<temp.length; x++) {
tempvalue = temp[x].value;
if (tempvalue > mx) {
mx = tempvalue;
mxpos = x;
}
if (tempvalue < mn) {
mn = tempvalue;
mnpos = x;
}
if (lookformax) {
if ( tempvalue < mx-delta ) {
DataPoint d = new DataPoint(mx, mxpos);
maxtab.add(d);
mn = tempvalue;
mnpos = x;
lookformax = false;
}
} else {
if ( tempvalue > mn+delta ) {
DataPoint d = new DataPoint(mn, mnpos);
mintab.add(d);
mx = tempvalue;
mxpos = x;
lookformax = true;
}
}
}
maxtab.toArray(result.maxtab);
mintab.toArray(result.mintab);
return result;
}
private Intercepts InterceptOutlierDetectorRIPLamia(ArrayList<Integer> upInterceptIndex, ArrayList<Integer> downInterceptIndex, DataPoint[] sample, int windowLength) {
//TODO: Intercept_outlier_detector_RIP_lamia.m
Intercepts result = new Intercepts();
int minimumLength = Math.min(upInterceptIndex.size(), downInterceptIndex.size());
if(upInterceptIndex.size() < minimumLength) {
upInterceptIndex = (ArrayList<Integer>) upInterceptIndex.subList(0,minimumLength-1);
}
if(downInterceptIndex.size() < minimumLength) {
downInterceptIndex = (ArrayList<Integer>) downInterceptIndex.subList(0,minimumLength-1);
}
//TODO: Needs work from Rummana
return result;
}
private DataPoint[] smooth(DataPoint[] rip, int n) {
DataPoint[] result = new DataPoint[rip.length];
DataPoint output;
double[] buffer = new double[n];
double sum = 0.0;
for(int i=0; i < rip.length; i++) {
sum -= buffer[i % n];
buffer[i % n] = rip[i].value;
sum += rip[i].value;
if (i > n) {
output = new DataPoint(buffer[i%n]/(i+1), rip[i].timestamp);
} else {
output = new DataPoint(buffer[i%n]/n, rip[i].timestamp);
}
result[i] = output;
}
return result;
}
// private double rsaCalculateCycle(DataPoint[] seg, ECGFeatures ecgFeatures) {
// //TODO: Fix me
// DataPoint[] ecg_rr = ecgFeatures.computeRR();
// return 0;
private class Intercepts {
public int[] UI;
public int[] DI;
}
private class PeakValley {
public ArrayList<Integer> peakIndex;
public ArrayList<Integer> valleyIndex;
}
}
|
package org.unipop.integration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
import org.unipop.controllerprovider.ControllerManagerFactory;
import org.unipop.elastic.helpers.ElasticClientFactory;
import org.unipop.elastic.helpers.ElasticHelper;
import org.unipop.integration.controllermanagers.IntegrationControllerManager;
import org.unipop.integration.controllermanagers.IntegrationStrategyRegistrar;
import org.unipop.process.strategy.DefaultStrategyRegistrar;
import org.unipop.structure.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
public class IntegrationGraphProvider extends AbstractGraphProvider {
private static String CLUSTER_NAME = "test";
private static final Set<Class> IMPLEMENTATION = new HashSet<Class>() {{
add(BaseEdge.class);
add(BaseElement.class);
add(UniGraph.class);
add(BaseProperty.class);
add(BaseVertex.class);
add(BaseVertexProperty.class);
}};
private final Client client;
private final Connection jdbcConnection;
public IntegrationGraphProvider() throws IOException, ExecutionException, InterruptedException, SQLException, ClassNotFoundException {
//patch for failing IO tests that wrute to disk
System.setProperty("build.dir", System.getProperty("user.dir") + "\\build");
//Delete elasticsearch 'data' directory
String path = new java.io.File( "." ).getCanonicalPath() + "\\data";
File file = new File(path);
FileUtils.deleteQuietly(file);
Node node = ElasticClientFactory.createNode(CLUSTER_NAME, false, 0);
client = node.client();
Class.forName("org.h2.Driver");
this.jdbcConnection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
this.jdbcConnection.createStatement().execute("CREATE TABLE IF NOT EXISTS PERSON(id int NOT NULL PRIMARY KEY, name varchar(100), age int, known_by int, known_weight float);");
}
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, LoadGraphWith.GraphData loadGraphWith) {
return new HashMap<String, Object>() {{
put(Graph.GRAPH, UniGraph.class.getName());
put("graphName",graphName.toLowerCase());
put("elasticsearch.client", ElasticClientFactory.ClientType.TRANSPORT_CLIENT);
put("elasticsearch.cluster.name", CLUSTER_NAME);
put("elasticsearch.cluster.address", "127.0.0.1:" + client.settings().get("transport.tcp.port"));
put("controllerManagerFactory", (ControllerManagerFactory) IntegrationControllerManager::new);
put("strategyRegistrar", new IntegrationStrategyRegistrar());
}};
}
@Override
public void clear(final Graph g, final Configuration configuration) throws Exception {
if (g != null) {
String indexName = configuration.getString("graphName");
ElasticHelper.clearIndex(client, indexName);
g.close();
}
jdbcConnection.createStatement().execute("TRUNCATE TABLE PERSON;");
}
@Override
public Set<Class> getImplementations() {
return IMPLEMENTATION;
}
@Override
public Object convertId(Object id, Class<? extends Element> c) {
return id.toString();
}
}
|
package org.qsardb.validation;
import java.util.*;
import java.util.regex.*;
import org.qsardb.model.*;
public class CompoundValidator extends ContainerValidator<Compound> {
public CompoundValidator(Scope scope){
super(scope);
}
@Override
protected Iterator<CompoundRegistry> selectContainerRegistries(Qdb qdb){
return new SingletonIterator<CompoundRegistry>(qdb.getCompoundRegistry());
}
@Override
public void validate(){
Scope scope = getScope();
if((Scope.LOCAL).equals(scope)){
validateCas();
validateInChI();
} else
if((Scope.GLOBAL).equals(scope)){
requireInChI();
}
}
private void validateCas(){
Compound compound = getEntity();
String cas = compound.getCas();
if(cas != null && !cas.isEmpty() && !validateCas(cas)){
error("Invalid Cas \'" + cas + "\'");
}
}
private void validateInChI(){
Compound compound = getEntity();
String inChI = compound.getInChI();
if(inChI != null && !inChI.isEmpty() && !validateInChI(inChI)){
error("Invalid InChI \'" + inChI + "\'");
}
}
private void requireInChI(){
Compound compound = getEntity();
String inChI = compound.getInChI();
if(isMissing(inChI)){
error("Missing InChI");
}
}
static
private boolean validateCas(String string){
Matcher matcher = cas_pattern.matcher(string);
if(matcher.matches()){
int sum = 0;
String digits = (matcher.group(1) + matcher.group(2) + matcher.group(3));
for(int i = 1, j = (digits.length() - 1) - 1; j > -1; i++, j
sum += i * digitAt(digits, j);
}
return (sum % 10) == digitAt(digits, digits.length() - 1);
}
return false;
}
static
private int digitAt(String digits, int index){
char c = digits.charAt(index);
return (c - '0');
}
static
private boolean validateInChI(String string){
Matcher matcher = inchi_pattern.matcher(string);
return matcher.matches();
}
private static final Pattern cas_pattern = Pattern.compile("([0-9]{2,7})\\-([0-9]{2})\\-([0-9])");
private static final Pattern inchi_pattern = Pattern.compile("InChI=1[S]?(?:\\/[^\\/]+)+");
}
|
package nl.b3p.viewer.stripes;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.security.Principal;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.util.HtmlUtil;
import net.sourceforge.stripes.util.StringUtil;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.components.ComponentRegistry;
import nl.b3p.viewer.components.ComponentRegistryInitializer;
import nl.b3p.viewer.config.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.ConfiguredComponent;
import nl.b3p.viewer.config.metadata.Metadata;
import nl.b3p.viewer.config.security.Authorizations;
import nl.b3p.viewer.config.security.User;
import nl.b3p.viewer.util.SelectedContentCache;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/app/{name}/v{version}")
@StrictBinding
public class ApplicationActionBean implements ActionBean {
private ActionBeanContext context;
@Validate
private String name;
@Validate
private boolean unknown;
@Validate
private String version;
// <editor-fold desc="bookmark variables" defaultstate="collapsed">
@Validate
private String bookmark;
@Validate
private String extent;
@Validate
private String layers;
@Validate
private String levelOrder;
// </editor-fold>
@Validate
private boolean debug;
@Validate(on = "retrieveAppConfigJSON")
private Application application;
private String componentSourceHTML;
private String appConfigJSON;
private String viewerType;
private String title;
private JSONObject user;
private String loginUrl;
private HashMap<String,Object> globalLayout;
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ActionBeanContext getContext() {
return context;
}
public String getComponentSourceHTML() {
return componentSourceHTML;
}
public void setComponentSourceHTML(String componentSourceHTML) {
this.componentSourceHTML = componentSourceHTML;
}
public String getAppConfigJSON() {
return appConfigJSON;
}
public void setAppConfigJSON(String appConfigJSON) {
this.appConfigJSON = appConfigJSON;
}
public String getViewerType(){
return viewerType;
}
public void setViewerType(String viewerType){
this.viewerType = viewerType;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public JSONObject getUser() {
return user;
}
public void setUser(JSONObject user) {
this.user = user;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public HashMap getGlobalLayout() {
return globalLayout;
}
public void setGlobalLayout(HashMap globalLayout) {
this.globalLayout = globalLayout;
}
public boolean isUnknown() {
return unknown;
}
public void setUnknown(boolean unknown) {
this.unknown = unknown;
}
public String getBookmark() {
return bookmark;
}
public void setBookmark(String bookmark) {
this.bookmark = bookmark;
}
public String getExtent() {
return extent;
}
public void setExtent(String extent) {
this.extent = extent;
}
public String getLayers() {
return layers;
}
public void setLayers(String layers) {
this.layers = layers;
}
public String getLevelOrder() {
return levelOrder;
}
public void setLevelOrder(String levelOrder) {
this.levelOrder = levelOrder;
}
//</editor-fold>
static Application findApplication(String name, String version) {
EntityManager em = Stripersist.getEntityManager();
if(name != null) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery(Application.class);
Root<Application> root = q.from(Application.class);
Predicate namePredicate = cb.equal(root.get("name"), name);
Predicate versionPredicate = version != null
? cb.equal(root.get("version"), version)
: cb.isNull(root.get("version"));
q.where(cb.and(namePredicate, versionPredicate));
try {
return (Application) em.createQuery(q).getSingleResult();
} catch(NoResultException nre) {
String decodedName = StringUtil.urlDecode(name);
if(!decodedName.equals(name)){
return findApplication(decodedName, version);
}
}
}
return null;
}
public Resolution saveCache() throws JSONException, IOException{
Resolution view = view();
EntityManager em = Stripersist.getEntityManager();
Resolution r = checkRestriction(context, application, em);
if (r != null) {
return r;
}
SelectedContentCache cache = new SelectedContentCache();
JSONObject sc = cache.createSelectedContent(application, false,false, false,em);
application.getDetails().put("selected_content_cache", new ClobElement(sc.toString()));
em.getTransaction().commit();
return view;
}
public Resolution retrieveCache() throws JSONException, IOException{
Resolution view = view();
EntityManager em = Stripersist.getEntityManager();
Resolution r = checkRestriction(context, application, em);
if (r != null) {
return r;
}
ClobElement el = application.getDetails().get("selected_content_cache");
appConfigJSON = el.getValue();
return view;
}
public Resolution retrieveAppConfigJSON(){
EntityManager em = Stripersist.getEntityManager();
JSONObject response = new JSONObject();
response.put("success", false);
appConfigJSON = application.toJSON(context.getRequest(),false, false,em);
response.put("config", appConfigJSON);
response.put("success", true);
return new StreamingResolution("application/json", new StringReader(response.toString()));
}
@DefaultHandler
public Resolution view() throws JSONException, IOException {
if(unknown){
getDefaultViewer();
/* Redirected here from /index.jsp: further redirect to app with
* name and version parameters of default app in URL and
* unknown=false. This makes sure that links in URL always include
* the app name. Required for compact bookmark links for default app
* to work.
*/
return new RedirectResolution(ApplicationActionBean.class)
.addParameter("name", name)
.addParameter("version", version)
.addParameter("debug", debug);
}
application = findApplication(name, version);
if(application == null) {
getContext().getValidationErrors().addGlobalError(new LocalizableError("app.notfound", name + (version != null ? " v" + version : "")));
return new ForwardResolution("/WEB-INF/jsp/error.jsp");
}
RedirectResolution login = new RedirectResolution(ApplicationActionBean.class)
.addParameter("name", name) // binded parameters not included ?
.addParameter("version", version)
.addParameter("debug", debug)
.addParameter("uitloggen", true)
.includeRequestParameters(true);
addBookmarkParameters(login);
loginUrl = login.getUrl(context.getLocale());
String username = context.getRequest().getRemoteUser();
if(application.isAuthenticatedRequired() && username == null) {
return login;
}
EntityManager em = Stripersist.getEntityManager();
Resolution r = checkRestriction(context, application, em);
if(r != null){
return r;
}
if(username != null) {
user = new JSONObject();
user.put("name", username);
JSONObject roles = new JSONObject();
user.put("roles", roles);
for(String role: Authorizations.getRoles(context.getRequest(),em)) {
roles.put(role, Boolean.TRUE);
}
}
buildComponentSourceHTML(em);
appConfigJSON = application.toJSON(context.getRequest(),false, false,em);
this.viewerType = retrieveViewerType();
this.title = application.getTitle();
if(StringUtils.isBlank(title)) {
this.title = application.getName();
}
//make hashmap for jsonobject.
this.globalLayout = new HashMap<String,Object>();
JSONObject layout = application.getGlobalLayout();
Iterator<String> keys = layout.keys();
while (keys.hasNext()){
String key = keys.next();
this.globalLayout.put(key, layout.get(key));
}
context.getResponse().addHeader("X-UA-Compatible", "IE=edge");
return new ForwardResolution("/WEB-INF/jsp/app.jsp");
}
public static Resolution checkRestriction(ActionBeanContext context, Application application, EntityManager em){
String username = context.getRequest().getRemoteUser();
User u = null;
if(username != null){
Principal p = context.getRequest().getUserPrincipal();
if( p instanceof User){
u = (User)p;
}else{
u = em.find(User.class, p.getName());
}
}
if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && (username == null || u != null && u.isAuthenticatedByIp())) {
RedirectResolution login = new RedirectResolution(LoginActionBean.class)
.addParameter("name", application.getName()) // binded parameters not included ?
.addParameter("version", application.getVersion())
.includeRequestParameters(true);
context.getRequest().getSession().invalidate();
return login;
} else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em) && username != null) {
context.getValidationErrors().addGlobalError(new SimpleError("Niet genoeg rechten"));
context.getRequest().getSession().invalidate();
return new ForwardResolution("/WEB-INF/jsp/error_retry.jsp");
}
return null;
}
/**
* Build a hash key to make the single component source for all components
* cacheable but updateable when the roles of the user change. This is not
* meant to be a secure hash, the roles of a user are not secret.
*
* @param request servlet request with user credential
* @param em the entitymanahger to use for database access
* @return a key to use as a cache identifyer
*/
public static int getRolesCachekey(HttpServletRequest request, EntityManager em) {
Set<String> roles = Authorizations.getRoles(request, em);
if(roles.isEmpty()) {
return 0;
}
List<String> sorted = new ArrayList<String>(roles);
Collections.sort(sorted);
int hash = 0;
for(String role: sorted) {
hash = hash ^ role.hashCode();
}
return hash;
}
public Resolution uitloggen(){
application = findApplication(name, version);
context.getRequest().getSession().invalidate();
if("true".equals(context.getRequest().getParameter("logout"))
&& "true".equals(context.getRequest().getParameter("returnAfterLogout"))) {
RedirectResolution r = new RedirectResolution(ApplicationActionBean.class)
.addParameter("name", application.getName())
.addParameter("version", application.getVersion());
addBookmarkParameters(r);
return r;
} else {
RedirectResolution r = new RedirectResolution(LoginActionBean.class)
.addParameter("name", application.getName())
.addParameter("version", application.getVersion());
addBookmarkParameters(r);
return r;
}
}
private void addBookmarkParameters(RedirectResolution r) {
if (bookmark != null) {
r.addParameter("bookmark", bookmark);
}
if(extent != null){
r.addParameter("extent", extent);
}
if(layers != null){
r.addParameter("layers", layers);
}
if(levelOrder != null){
r.addParameter("levelOrder", levelOrder);
}
}
private void buildComponentSourceHTML(EntityManager em) throws IOException {
StringBuilder sb = new StringBuilder();
// Sort components by classNames, so order is always the same for debugging
ComponentRegistry cr = ComponentRegistryInitializer.getInstance();
List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents());
Collections.sort(comps);
if(isDebug()) {
Set<String> classNamesDone = new HashSet<String>();
for(ConfiguredComponent cc: comps) {
if(!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) {
continue;
}
if(!classNamesDone.contains(cc.getClassName())) {
classNamesDone.add(cc.getClassName());
if(cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) {
for(File f: cc.getViewerComponent().getSources()) {
String url = new ForwardResolution(ComponentActionBean.class, "source")
.addParameter("app", name)
.addParameter("version", version)
.addParameter("className", cc.getClassName())
.addParameter("file", f.getName())
.getUrl(context.getLocale());
sb.append(" <script type=\"text/javascript\" src=\"");
sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url));
sb.append("\"></script>\n");
}
}
}
}
} else {
// If not debugging, create a single script tag with all source
// for all components for the application for a minimal number of HTTP requests
// The ComponentActionBean supports conditional HTTP requests using
// Last-Modified.
// Create a hash value that will change when the classNames used
// in the application change, so that a browser will not use a
// previous version from cache with other contents.
int hash = 0;
Set<String> classNamesDone = new HashSet<String>();
for (ConfiguredComponent cc : comps) {
if (!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest(), em)) {
continue;
}
if(!classNamesDone.contains(cc.getClassName())) {
hash = hash ^ cc.getClassName().hashCode();
} else {
classNamesDone.add(cc.getClassName());
}
}
if(user != null) {
// Update component sources when roles of user change
hash = hash ^ getRolesCachekey(context.getRequest(), em);
// Update component sources when roles of configured components
// may have changed
hash = hash ^ (int)application.getAuthorizationsModified().getTime();
}
String url = new ForwardResolution(ComponentActionBean.class, "source")
.addParameter("app", name)
.addParameter("version", version)
.addParameter("minified", true)
.addParameter("hash", hash)
.getUrl(context.getLocale());
sb.append(" <script type=\"text/javascript\" src=\"");
sb.append(HtmlUtil.encode(context.getServletContext().getContextPath() + url));
sb.append("\"></script>\n");
}
componentSourceHTML = sb.toString();
}
private String retrieveViewerType (){
String type = "FlamingoMap";
String typePrefix = "viewer.mapcomponents";
Set<ConfiguredComponent> components = application.getComponents();
for (ConfiguredComponent component : components) {
String className = component.getClassName();
if(className.startsWith(typePrefix)){
type = className.substring(typePrefix.length() +1).toLowerCase().replace("map", "");
break;
}
}
return type;
}
private void getDefaultViewer(){
EntityManager em = Stripersist.getEntityManager();
try {
Metadata md = em.createQuery("from Metadata where configKey = :key", Metadata.class).setParameter("key", Metadata.DEFAULT_APPLICATION).getSingleResult();
String appId = md.getConfigValue();
Long id = Long.parseLong(appId);
Application app = em.find(Application.class, id);
name = app.getName();
version = app.getVersion();
} catch (NoResultException | NullPointerException e) {
name = "default";
version = null;
}
}
}
|
package hudson.plugins.warnings;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.plugins.analysis.core.AnnotationsClassifier;
import hudson.plugins.analysis.core.FilesParser;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.util.ModuleDetector;
import hudson.plugins.analysis.util.NullModuleDetector;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.warnings.parser.FileWarningsParser;
import hudson.plugins.warnings.parser.ParserRegistry;
import hudson.plugins.warnings.parser.ParsingCanceledException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Publishes the results of the warnings analysis (freestyle project type).
*
* @author Ulli Hafner
*/
// CHECKSTYLE:COUPLING-OFF
public class WarningsPublisher extends HealthAwarePublisher {
private static final String PLUGIN_NAME = "WARNINGS";
private static final long serialVersionUID = -5936973521277401764L;
/** Ant file-set pattern of files to include to report. */
private final String includePattern;
/** Ant file-set pattern of files to exclude from report. */
private final String excludePattern;
/** File pattern and parser configurations. @since 3.19 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE")
private final List<ParserConfiguration> parserConfigurations = Lists.newArrayList();
/** Parser configurations of the console. @since 4.6 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE")
private List<ConsoleParser> consoleParsers = Lists.newArrayList();
/**
* Creates a new instance of <code>WarningPublisher</code>.
*
* @param healthy
* Report health as 100% when the number of annotations is less
* than this value
* @param unHealthy
* Report health as 0% when the number of annotations is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
* @param unstableTotalAll
* annotation threshold
* @param unstableTotalHigh
* annotation threshold
* @param unstableTotalNormal
* annotation threshold
* @param unstableTotalLow
* annotation threshold
* @param unstableNewAll
* annotation threshold
* @param unstableNewHigh
* annotation threshold
* @param unstableNewNormal
* annotation threshold
* @param unstableNewLow
* annotation threshold
* @param failedTotalAll
* annotation threshold
* @param failedTotalHigh
* annotation threshold
* @param failedTotalNormal
* annotation threshold
* @param failedTotalLow
* annotation threshold
* @param failedNewAll
* annotation threshold
* @param failedNewHigh
* annotation threshold
* @param failedNewNormal
* annotation threshold
* @param failedNewLow
* annotation threshold
* @param canRunOnFailed
* determines whether the plug-in can run for failed builds, too
* @param shouldDetectModules
* determines whether module names should be derived from Maven POM or Ant build files
* @param includePattern
* Ant file-set pattern of files to include in report
* @param excludePattern
* Ant file-set pattern of files to exclude from report
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public WarningsPublisher(final String healthy, final String unHealthy, final String thresholdLimit,
final String defaultEncoding, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final boolean shouldDetectModules, final boolean canComputeNew,
final String includePattern, final String excludePattern,
final List<ParserConfiguration> parserConfigurations, final List<ConsoleParser> consoleParsers) {
super(healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues,
unstableTotalAll, unstableTotalHigh, unstableTotalNormal, unstableTotalLow,
unstableNewAll, unstableNewHigh, unstableNewNormal, unstableNewLow,
failedTotalAll, failedTotalHigh, failedTotalNormal, failedTotalLow,
failedNewAll, failedNewHigh, failedNewNormal, failedNewLow,
canRunOnFailed, shouldDetectModules, canComputeNew, PLUGIN_NAME);
this.includePattern = StringUtils.stripToNull(includePattern);
this.excludePattern = StringUtils.stripToNull(excludePattern);
if (consoleParsers != null) {
this.consoleParsers.addAll(consoleParsers);
}
if (parserConfigurations != null) {
this.parserConfigurations.addAll(parserConfigurations);
}
}
// CHECKSTYLE:ON
/**
* Returns the names of the configured parsers for the console log.
*
* @return the parser names
*/
public ConsoleParser[] getConsoleParsers() {
return ConsoleParser.filterExisting(consoleParsers);
}
/**
* Returns the parserConfigurations.
*
* @return the parserConfigurations
*/
public ParserConfiguration[] getParserConfigurations() {
return ParserConfiguration.filterExisting(parserConfigurations);
}
/**
* Upgrade for release 4.5 or older.
*
* @return this
*/
@Override
protected Object readResolve() {
super.readResolve();
if (consoleParsers == null) {
consoleParsers = Lists.newArrayList();
for (String parser : consoleLogParsers) {
consoleParsers.add(new ConsoleParser(parser));
}
}
return this;
}
/**
* Returns the Ant file-set pattern of files to include in report.
*
* @return Ant file-set pattern of files to include in report
*/
public String getIncludePattern() {
return includePattern;
}
/**
* Returns the Ant file-set pattern of files to exclude from report.
*
* @return Ant file-set pattern of files to exclude from report
*/
public String getExcludePattern() {
return excludePattern;
}
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
throw new IllegalStateException("Not available since release 4.0.");
}
@Override
public Collection<? extends Action> getProjectActions(final AbstractProject<?, ?> project) {
List<Action> actions = Lists.newArrayList();
for (String parserName : getParsers()) {
actions.add(new WarningsProjectAction(project, parserName));
}
return actions;
}
private Set<String> getParsers() {
Set<String> parsers = Sets.newHashSet();
for (ConsoleParser configuration : getConsoleParsers()) {
parsers.add(configuration.getParserName());
}
for (ParserConfiguration configuration : getParserConfigurations()) {
parsers.add(configuration.getParserName());
}
return parsers;
}
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger)
throws InterruptedException, IOException {
try {
if (!hasConsoleParsers() && !hasFileParsers()) {
throw new IOException("Error: No warning parsers defined in the job configuration.");
}
List<ParserResult> fileResults = parseFiles(build, logger);
List<ParserResult> consoleResults = parseConsoleLog(build, logger);
ParserResult totals = new ParserResult();
add(totals, consoleResults);
add(totals, fileResults);
return new WarningsResult(build, new WarningsBuildHistory(build, null), totals, getDefaultEncoding(), null);
}
catch (ParsingCanceledException exception) {
throw createInterruptedException();
}
}
@Override
protected void updateBuildResult(final BuildResult result, final PluginLogger logger) {
for (WarningsResultAction action : result.getOwner().getActions(WarningsResultAction.class)) {
action.getResult().evaluateStatus(getThresholds(), getUseDeltaValues(), canComputeNew(), logger,
action.getUrlName());
}
}
private boolean hasFileParsers() {
return getParserConfigurations().length > 0;
}
private boolean hasConsoleParsers() {
return getConsoleParsers().length > 0;
}
private void add(final ParserResult totals, final List<ParserResult> results) {
for (ParserResult result : results) {
totals.addProject(result);
}
}
private InterruptedException createInterruptedException() {
return new InterruptedException("Canceling parsing since build has been aborted.");
}
private void returnIfCanceled() throws InterruptedException {
if (Thread.interrupted()) {
throw createInterruptedException();
}
}
private List<ParserResult> parseConsoleLog(final AbstractBuild<?, ?> build,
final PluginLogger logger) throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ConsoleParser parser : getConsoleParsers()) {
String parserName = parser.getParserName();
logger.log("Parsing warnings in console log with parser " + parserName);
Collection<FileAnnotation> warnings = new ParserRegistry(
ParserRegistry.getParsers(parserName),
getDefaultEncoding(), getIncludePattern(), getExcludePattern()).parse(build
.getLogFile());
if (!build.getWorkspace().isRemote()) {
guessModuleNames(build, warnings);
}
ParserResult project = new ParserResult(build.getWorkspace());
project.addAnnotations(warnings);
results.add(annotate(build, project, parserName));
}
return results;
}
private void guessModuleNames(final AbstractBuild<?, ?> build, final Collection<FileAnnotation> warnings) {
String workspace = build.getWorkspace().getRemote();
ModuleDetector detector = createModuleDetector(workspace);
for (FileAnnotation annotation : warnings) {
String module = detector.guessModuleName(annotation.getFileName());
annotation.setModuleName(module);
}
}
private List<ParserResult> parseFiles(final AbstractBuild<?, ?> build, final PluginLogger logger)
throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ParserConfiguration configuration : getParserConfigurations()) {
String filePattern = configuration.getPattern();
String parserName = configuration.getParserName();
logger.log("Parsing warnings in files '" + filePattern + "' with parser " + parserName);
FilesParser parser = new FilesParser(PLUGIN_NAME, filePattern,
new FileWarningsParser(ParserRegistry.getParsers(parserName), getDefaultEncoding(), getIncludePattern(), getExcludePattern()),
shouldDetectModules(), isMavenBuild(build));
ParserResult project = build.getWorkspace().act(parser);
logger.logLines(project.getLogMessages());
returnIfCanceled();
results.add(annotate(build, project, configuration.getParserName()));
}
return results;
}
private ParserResult annotate(final AbstractBuild<?, ?> build, final ParserResult input, final String parserName)
throws IOException, InterruptedException {
ParserResult output = build.getWorkspace().act(
new AnnotationsClassifier(input, getDefaultEncoding()));
for (FileAnnotation annotation : output.getAnnotations()) {
annotation.setPathName(build.getWorkspace().getRemote());
}
WarningsResult result = new WarningsResult(build, new WarningsBuildHistory(build, parserName),
output, getDefaultEncoding(), parserName);
build.getActions().add(new WarningsResultAction(build, this, result, parserName));
return output;
}
private ModuleDetector createModuleDetector(final String workspace) {
if (shouldDetectModules()) {
return new ModuleDetector(new File(workspace));
}
else {
return new NullModuleDetector();
}
}
@Override
public WarningsDescriptor getDescriptor() {
return (WarningsDescriptor)super.getDescriptor();
}
/** {@inheritDoc} */
public MatrixAggregator createAggregator(final MatrixBuild build, final Launcher launcher, final BuildListener listener) {
return new WarningsAnnotationsAggregator(build, launcher, listener, this, getDefaultEncoding());
}
/** Name of parsers to use for scanning the logs. */
@SuppressWarnings({"unused", "PMD"})
private transient Set<String> parserNames;
/** Determines whether the console should be ignored. */
@SuppressWarnings({"unused", "PMD"})
private transient boolean ignoreConsole;
/** Ant file-set pattern of files to work with. */
@SuppressWarnings({"unused", "PMD"})
private transient String pattern;
/** Parser to scan the console log. @since 3.19 */
private transient Set<String> consoleLogParsers;
}
|
package io.spine.validate.option;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Range;
import com.google.errorprone.annotations.Immutable;
import io.spine.code.proto.FieldContext;
import io.spine.code.proto.FieldDeclaration;
import io.spine.validate.ComparableNumber;
import io.spine.validate.ConstraintTranslator;
import io.spine.validate.NumberText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Range.closed;
import static com.google.common.collect.Range.closedOpen;
import static com.google.common.collect.Range.open;
import static com.google.common.collect.Range.openClosed;
import static java.lang.String.format;
/**
* A constraint that checks whether a value fits the ranged described by expressions such as
* {@code int32 value = 5 [(range) = "[3..5)]}, describing a value that is at least 3 and less
* than 5.
*/
@Immutable
public final class RangeConstraint extends RangedConstraint<String> {
/**
* The regular expression for parsing number ranges.
*
* <p>Defines four groups:
* <ol>
* <li>The opening bracket (a {@code [} or a {@code (}).
* <li>The lower numerical bound.
* <li>The higher numerical bound.
* <li>The closing bracket (a {@code ]} or a {@code )}).
* </ol>
*
* <p>All the groups as well as a {@code ..} divider between the numerical bounds must be
* matched. Extra spaces among the groups and the divider are allowed.
*
* <p>Examples of a valid number range:
* <ul>
* <li>{@code [0..1]}
* <li>{@code ( -17.3 .. +146.0 ]}
* <li>{@code [+1..+100)}
* </ul>
*
* <p>Examples of an invalid number range:
* <ul>
* <li>{@code 1..5} - missing brackets.
* <li>{@code [0 - 1]} - wrong divider.
* <li>{@code [0 . . 1]} - divider cannot be split with spaces.
* <li>{@code ( .. 0)} - missing lower bound.
* </ul>
*/
private static final Pattern NUMBER_RANGE =
Pattern.compile("([\\[(])\\s*([+\\-]?[\\d.]+)\\s*\\.\\.\\s*([+\\-]?[\\d.]+)\\s*([])])");
RangeConstraint(String optionValue, FieldDeclaration field) {
super(optionValue, rangeFromOption(optionValue, field), field);
}
@VisibleForTesting
static Range<ComparableNumber> rangeFromOption(String rangeOption, FieldDeclaration field) {
Matcher rangeMatcher = NUMBER_RANGE.matcher(rangeOption.trim());
if (!rangeOption.isEmpty()) {
checkState(rangeMatcher.matches(),
"Malformed range `%s` on field `%s`. " +
"Must have a form of `[a..b]` " +
"where `a` and `b` are valid literals of type %s. " +
"See doc of `(range)` for more details.",
rangeOption, field, field.javaTypeName());
boolean minInclusive = rangeMatcher.group(1).equals("[");
ComparableNumber minValue = new NumberText(rangeMatcher.group(2)).toNumber();
ComparableNumber maxValue = new NumberText(rangeMatcher.group(3)).toNumber();
boolean maxInclusive = rangeMatcher.group(4).equals("]");
if (minInclusive) {
return maxInclusive ? closed(minValue, maxValue) : closedOpen(minValue, maxValue);
} else {
return maxInclusive ? openClosed(minValue, maxValue) : open(minValue, maxValue);
}
} else {
return Range.all();
}
}
@Override
public String errorMessage(FieldContext field) {
return format("Field %s is out of range.", field());
}
@Override
protected String compileErrorMessage(Range<ComparableNumber> range) {
return new StringBuilder(format("Value of `%s`", field()))
.append(forLowerBound())
.append(range().lowerEndpoint())
.append(" and ")
.append(forUpperBound())
.append(range().upperEndpoint())
.append('.')
.toString();
}
private String forLowerBound() {
String greaterThan = "greater than %s";
return format(greaterThan, orEqualTo(range().lowerBoundType()));
}
private String forUpperBound() {
String lessThan = "less than %s";
return format(lessThan, orEqualTo(range().lowerBoundType()));
}
@Override
public void accept(ConstraintTranslator<?> visitor) {
visitor.visitRange(this);
}
}
|
package etomica.simulation;
import etomica.config.Configuration;
import etomica.config.ConfigurationResourceFile;
import etomica.data.AccumulatorAverage;
import etomica.data.AccumulatorAverageFixed;
import etomica.data.DataPumpListener;
import etomica.data.meter.MeterPotentialEnergyFromIntegrator;
import etomica.data.meter.MeterPotentialEnergyFromIntegratorFasterer;
import etomica.data.meter.MeterPressureHard;
import etomica.data.meter.MeterPressureHardFasterer;
import etomica.space3d.Space3D;
import etomica.tests.TestSWChain;
import etomica.tests.TestSWChainSlow;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@Fork(1)
public class BenchSimSWChain {
@Param({"500", "4000"})
public int numMolecules;
@Param({"100000"})
public int numSteps;
private TestSWChain sim;
private TestSWChainSlow simSlow;
@Setup(Level.Iteration)
public void setUp() {
double simTime = numSteps / numMolecules;
Configuration config = new ConfigurationResourceFile(
String.format("SWChain%d.pos", numMolecules),
TestSWChain.class
);
{
simSlow = new TestSWChainSlow(Space3D.getInstance(), numMolecules, config);
MeterPressureHard pMeter = new MeterPressureHard(simSlow.integrator);
MeterPotentialEnergyFromIntegrator energyMeter = new MeterPotentialEnergyFromIntegrator(simSlow.integrator);
AccumulatorAverage energyAccumulator = new AccumulatorAverageFixed();
DataPumpListener energyPump = new DataPumpListener(energyMeter, energyAccumulator);
energyAccumulator.setBlockSize(50);
simSlow.integrator.getEventManager().addListener(energyPump);
simSlow.integrator.reset();
}
{
sim = new TestSWChain(Space3D.getInstance(), numMolecules, config);
MeterPressureHardFasterer pMeter = new MeterPressureHardFasterer(sim.integrator);
MeterPotentialEnergyFromIntegratorFasterer energyMeter = new MeterPotentialEnergyFromIntegratorFasterer(sim.integrator);
AccumulatorAverage energyAccumulator = new AccumulatorAverageFixed();
DataPumpListener energyPump = new DataPumpListener(energyMeter, energyAccumulator);
energyAccumulator.setBlockSize(50);
sim.integrator.getEventManager().addListener(energyPump);
sim.integrator.reset();
}
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(time = 3, iterations = 3)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
public long integratorStepSlow() {
simSlow.integrator.doStep();
return simSlow.integrator.getStepCount();
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(time = 3, iterations = 3)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
public long integratorStep() {
sim.integrator.doStep();
return sim.integrator.getStepCount();
}
public static void main(String[] args) throws RunnerException {
Options opts = new OptionsBuilder()
.include(BenchSimSWChain.class.getSimpleName())
.build();
new Runner(opts).run();
}
}
|
package org.intermine.bio.webservice;
import org.apache.commons.lang.StringUtils;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.webservice.server.exceptions.BadRequestException;
/**
* Export a List as GFF3.
* @author Alex Kalderimis
*
*/
public class GFF3ListService extends GFFQueryService
{
private static final String LIST_PARAM = "list";
public GFF3ListService(InterMineAPI im) {
super(im);
}
@Override
protected PathQuery getQuery() {
InterMineBag list = getList();
PathQuery pq = new PathQuery(im.getModel());
pq.addView(list.getType() + ".primaryIdentifier");
pq.addConstraint(Constraints.in(list.getType(), list.getName()));
return pq;
}
private InterMineBag getList() {
String listName = request.getParameter(LIST_PARAM);
if (StringUtils.isEmpty(listName)) {
throw new BadRequestException("missing list name parameter");
}
InterMineBag list = null;
if (this.isAuthenticated()) {
Profile p = SessionMethods.getProfile(request.getSession());
list = im.getBagManager().getBag(p, listName);
} else {
list = im.getBagManager().getGlobalBag(listName);
}
if (list == null) {
throw new BadRequestException("Cannot access a list called" + listName);
}
return list;
}
}
|
package org.intermine.bio.webservice;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.PathQueryExecutor;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.bio.web.export.GFF3Exporter;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.export.Exporter;
import org.intermine.web.logic.export.ResponseUtil;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.webservice.server.WebServiceRequestParser;
import org.intermine.webservice.server.exceptions.BadRequestException;
import org.intermine.webservice.server.exceptions.InternalErrorException;
import org.intermine.webservice.server.output.Output;
import org.intermine.webservice.server.output.StreamedOutput;
import org.intermine.webservice.server.output.TabFormatter;
import org.intermine.webservice.server.query.AbstractQueryService;
import org.intermine.webservice.server.query.result.PathQueryBuilder;
/**
* A service for exporting query results as gff3.
* @author Alexis Kalderimis.
*
*/
public class GFFQueryService extends AbstractQueryService
{
private static final String XML_PARAM = "query";
/**
* Constructor.
* @param im A reference to an InterMine API settings bundle.
*/
public GFFQueryService(InterMineAPI im) {
super(im);
}
@Override
protected String getDefaultFileName() {
return "results" + StringUtil.uniqueString() + ".gff3";
}
protected PrintWriter pw;
@Override
protected Output getDefaultOutput(PrintWriter out, OutputStream os) {
this.pw = out;
output = new StreamedOutput(out, new TabFormatter());
if (isUncompressed()) {
ResponseUtil.setPlainTextHeader(response,
getDefaultFileName());
}
return output;
}
@Override
public int getFormat() {
return UNKNOWN_FORMAT;
}
@Override
protected void execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
// get the project title to be written in GFF3 records
Properties props = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES);
String sourceName = props.getProperty("project.title");
Set<Integer> organisms = null;
PathQuery pathQuery = getQuery();
Exporter exporter;
try {
List<Integer> indexes = new ArrayList<Integer>();
List<String> viewColumns = new ArrayList<String>(pathQuery.getView());
for (int i = 0; i < viewColumns.size(); i++) {
indexes.add(Integer.valueOf(i));
}
removeFirstItemInPaths(viewColumns);
exporter = new GFF3Exporter(pw, indexes,
getSoClassNames(servletContext), viewColumns,
sourceName, organisms, false);
ExportResultsIterator iter = null;
try {
Profile profile = SessionMethods.getProfile(session);
PathQueryExecutor executor = this.im.getPathQueryExecutor(profile);
iter = executor.execute(pathQuery, 0, WebServiceRequestParser.DEFAULT_MAX_COUNT);
iter.goFaster();
exporter.export(iter);
} finally {
if (iter != null) {
iter.releaseGoFaster();
}
}
} catch (Exception e) {
throw new InternalErrorException("Service failed:" + e, e);
}
}
/**
* Read the SO term name to class name mapping file and return it as a Map from class name to
* SO term name. The Map is cached as the SO_CLASS_NAMES attribute in the servlet context.
*
* @throws ServletException if the SO class names properties file cannot be found
* @param servletContext the ServletContext
* @return a map
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, String> getSoClassNames(ServletContext servletContext)
throws ServletException {
final String soClassNames = "SO_CLASS_NAMES";
Properties soNameProperties;
if (servletContext.getAttribute(soClassNames) == null) {
soNameProperties = new Properties();
try {
InputStream is =
servletContext.getResourceAsStream("/WEB-INF/soClassName.properties");
soNameProperties.load(is);
} catch (Exception e) {
throw new ServletException("Error loading so class name mapping file", e);
}
servletContext.setAttribute(soClassNames, soNameProperties);
} else {
soNameProperties = (Properties) servletContext.getAttribute(soClassNames);
}
return new HashMap<String, String>((Map) soNameProperties);
}
/**
*
* @param paths list of path views
*/
public static void removeFirstItemInPaths(List<String> paths) {
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
paths.set(i, path.substring(path.indexOf(".") + 1, path.length()));
}
}
/**
* Return the query specified in the request, shorn of all duplicate
* classes in the view. Note, it is the users responsibility to ensure
* that there are only SequenceFeatures in the view.
*
* @return A suitable pathquery for getting GFF3 data from.
*/
protected PathQuery getQuery() {
String xml = request.getParameter(XML_PARAM);
if (StringUtils.isEmpty(xml)) {
throw new BadRequestException("query is blank");
}
PathQueryBuilder builder = getQueryBuilder(xml, request);
PathQuery pq = builder.getQuery();
List<String> newView = new ArrayList<String>();
Set<ClassDescriptor> seenTypes = new HashSet<ClassDescriptor>();
for (String viewPath: pq.getView()) {
Path p;
try {
p = new Path(pq.getModel(), viewPath);
} catch (PathException e) {
throw new BadRequestException("Query is invalid", e);
}
ClassDescriptor cd = p.getLastClassDescriptor();
if (!seenTypes.contains(cd)) {
newView.add(viewPath);
}
seenTypes.add(cd);
}
if (!newView.equals(pq.getView())) {
pq.clearView();
pq.addViews(newView);
}
return pq;
}
}
|
package org.builditbreakit.seada.common.data;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.builditbreakit.seada.common.exceptions.IntegrityViolationException;
public class GalleryState implements Serializable {
private static final long serialVersionUID = 6928424752159836102L;
private transient int lastTimestamp = 0;
private transient final Map<String, Visitor> visitorMap;
public GalleryState() {
this.visitorMap = new HashMap<>();
}
private GalleryState(Collection<? extends Visitor> visitors) {
ValidationUtil.assertNotNull(visitors, "Imported data");
final float load_factor = 0.75f;
final int default_capacity = 16;
final int extra_space = 10;
final int initial_capacity = Math.max(
(int) (visitors.size() / load_factor) + extra_space,
default_capacity);
this.visitorMap = new HashMap<>(initial_capacity, load_factor);
if (!visitors.isEmpty()) {
visitors.forEach((visitor) -> {
if (visitorMap.put(visitor.getName(), visitor) != null) {
throw new IntegrityViolationException("Duplicate visitor: "
+ visitor.getName());
}
List<LocationRecord> history = visitor.getHistory();
if (!history.isEmpty()) {
int lastVisitTime = history.get(history.size() - 1)
.getArrivalTime();
if (lastVisitTime > lastTimestamp) {
lastTimestamp = lastVisitTime;
}
}
});
}
}
public Collection<Visitor> getVisitors() {
return Collections.unmodifiableCollection(visitorMap.values());
}
public Visitor getVisitor(String name, VisitorType visitorType) {
ValidationUtil.assertValidVisitorType(visitorType);
ValidationUtil.assertValidVisitorName(name);
Visitor visitor = visitorMap.get(name);
if (visitor == null) {
throw new IllegalStateException("Visitor does not exist");
}
assertMatchingVisitorType(visitor, visitorType);
return visitor;
}
public int getLastTimestamp() {
return lastTimestamp;
}
public boolean containsVisitor(String name, VisitorType visitorType) {
Visitor visitor = visitorMap.get(name);
if (visitor == null) {
return false;
}
return visitor.getVisitorType() == visitorType;
}
public void arriveAtBuilding(int timestamp, String name,
VisitorType visitorType) {
ValidationUtil.assertValidVisitorType(visitorType);
ValidationUtil.assertValidVisitorName(name);
assertValidTimestamp(timestamp);
Visitor visitor = visitorMap.get(name);
if (visitor == null) {
visitor = new Visitor(name, visitorType);
visitorMap.put(name, visitor);
} else {
assertMatchingVisitorType(visitor, visitorType);
}
if(!visitor.getCurrentLocation().isOffPremises()) {
throw new IllegalStateException("Visitor is already in the gallery");
}
visitor.moveTo(timestamp, Location.IN_GALLERY);
lastTimestamp = timestamp;
}
public void arriveAtRoom(int timestamp, String name,
VisitorType visitorType, int roomNumber) {
ValidationUtil.assertValidVisitorType(visitorType);
ValidationUtil.assertValidVisitorName(name);
ValidationUtil.assertValidRoomNumber(roomNumber);
assertValidTimestamp(timestamp);
Visitor visitor = getVisitor(name, visitorType);
if (visitor == null) {
throw new IllegalStateException("Visitor does not exist");
}
visitor.moveTo(timestamp, Location.locationOfRoom(roomNumber));
lastTimestamp = timestamp;
}
public void departRoom(int timestamp, String name, VisitorType visitorType, int roomNumber) {
ValidationUtil.assertValidVisitorType(visitorType);
ValidationUtil.assertValidVisitorName(name);
ValidationUtil.assertValidRoomNumber(roomNumber);
assertValidTimestamp(timestamp);
Visitor visitor = getVisitor(name, visitorType);
Location currentLocation = visitor.getCurrentLocation();
if (!currentLocation.equals(Location.locationOfRoom(roomNumber))) {
throw new IllegalStateException("Visitor is not in that room");
}
visitor.moveTo(timestamp, Location.IN_GALLERY);
lastTimestamp = timestamp;
}
public void departBuilding(int timestamp, String name, VisitorType visitorType) {
ValidationUtil.assertValidVisitorType(visitorType);
ValidationUtil.assertValidVisitorName(name);
assertValidTimestamp(timestamp);
Visitor visitor = getVisitor(name, visitorType);
Location currentLocation = visitor.getCurrentLocation();
if (!currentLocation.isInGallery()) {
throw new IllegalStateException("Visitor is not in the lobby");
}
visitor.moveTo(timestamp, Location.OFF_PREMISES);
lastTimestamp = timestamp;
}
private void assertValidTimestamp(int timestamp) {
ValidationUtil.assertValidUINT32(timestamp, "Timestamp");
if (timestamp <= lastTimestamp) {
throw new IllegalStateException("Timestamp " + timestamp
+ " does not follow the current timestamp: " + lastTimestamp);
}
}
private void assertMatchingVisitorType(Visitor visitor,
VisitorType visitorType) {
if (visitor.getVisitorType() != visitorType) {
throw new IllegalStateException("Incorrect visitor type");
}
}
private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 8768461134732556971L;
private final Collection<Visitor> visitors;
SerializationProxy(GalleryState galleryState) {
// Need to make a copy. Map values are not serializable
this.visitors = new ArrayList<>(galleryState.visitorMap.values());
}
private Object readResolve() {
return new GalleryState(visitors);
}
}
private Object writeReplace() {
return new SerializationProxy(this);
}
private void readObject(ObjectInputStream ois)
throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
}
|
package org.devocative.ares.web.panel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;
import org.devocative.adroit.vo.KeyValueVO;
import org.devocative.ares.AresPrivilegeKey;
import org.devocative.ares.cmd.CommandOutput;
import org.devocative.ares.entity.command.Command;
import org.devocative.ares.entity.command.PrepCommand;
import org.devocative.ares.entity.oservice.OServiceInstance;
import org.devocative.ares.iservice.IOServerService;
import org.devocative.ares.iservice.command.ICommandService;
import org.devocative.ares.iservice.command.IPrepCommandService;
import org.devocative.ares.iservice.oservice.IOServiceInstanceService;
import org.devocative.ares.vo.CommandQVO;
import org.devocative.ares.vo.TabularVO;
import org.devocative.ares.vo.xml.XCommand;
import org.devocative.ares.vo.xml.XParam;
import org.devocative.ares.vo.xml.XParamType;
import org.devocative.ares.web.AresIcon;
import org.devocative.ares.web.dpage.command.PrepCommandFormDPage;
import org.devocative.demeter.web.DPanel;
import org.devocative.demeter.web.DTaskBehavior;
import org.devocative.demeter.web.component.DAjaxButton;
import org.devocative.demeter.web.panel.FileStoreUploadPanel;
import org.devocative.wickomp.WebUtil;
import org.devocative.wickomp.async.IAsyncResponse;
import org.devocative.wickomp.form.WBooleanInput;
import org.devocative.wickomp.form.WSelectionInput;
import org.devocative.wickomp.form.WSelectionInputAjaxUpdatingBehavior;
import org.devocative.wickomp.form.WTextInput;
import org.devocative.wickomp.html.WFloatTable;
import org.devocative.wickomp.html.window.WModalWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandExecPanel extends DPanel implements IAsyncResponse {
private static final long serialVersionUID = 6094381569285095361L;
private static final Logger logger = LoggerFactory.getLogger(CommandExecPanel.class);
private Long commandId;
private Long prepCommandId;
private Map<String, Object> params = new HashMap<>();
private Map<String, String> paramsAsStr = new HashMap<>();
private List<OServiceInstance> targetServiceInstances = new ArrayList<>();
private Long targetServiceInstanceId;
private Long osiUserId;
private DTaskBehavior taskBehavior;
private WebMarkupContainer tabs, log, tabular;
private List<WSelectionInput> guestInputList = new ArrayList<>();
@Inject
private ICommandService commandService;
@Inject
private IOServiceInstanceService serviceInstanceService;
@Inject
private IOServerService serverService;
@Inject
private IPrepCommandService prepCommandService;
public CommandExecPanel(String id, Long commandId) {
super(id);
this.commandId = commandId;
}
public CommandExecPanel(String id, PrepCommand prepCommand) {
super(id);
this.prepCommandId = prepCommand.getId();
this.commandId = prepCommand.getCommandId();
this.targetServiceInstanceId = prepCommand.getServiceInstanceId();
if (prepCommand.getParams() != null) {
this.paramsAsStr.putAll(prepCommandService.convertParamsFromString(prepCommand.getParams()));
}
}
public CommandExecPanel setTargetServiceInstanceId(Long targetServiceInstanceId) {
this.targetServiceInstanceId = targetServiceInstanceId;
return this;
}
public CommandExecPanel setOsiUserId(Long osiUserId) {
this.osiUserId = osiUserId;
return this;
}
@Override
public void onAsyncResult(IPartialPageRequestHandler handler, Object result) {
logger.debug("onAsyncResult: {}", result);
CommandOutput line = (CommandOutput) result;
if (line.getType() != CommandOutput.Type.TABULAR) {
String str = Strings.escapeMarkup(line.getOutput().toString().trim(), false, true).toString();
str = str.replaceAll("[\n]", "<br/>");
str = str.replaceAll("[\r]", "");
String script = String.format("$('#%s').append(\"<div class='ars-cmd-%s'>%s</div>\");",
log.getMarkupId(),
line.getType().name().toLowerCase(),
str);
handler.appendJavaScript(script);
handler.appendJavaScript(String.format("$('#%1$s').scrollTop($('#%1$s')[0].scrollHeight);", log.getMarkupId()));
} else {
renderTabular((TabularVO) line.getOutput(), handler);
}
}
@Override
public void onAsyncError(IPartialPageRequestHandler handler, Exception error) {
StringWriter out = new StringWriter();
error.printStackTrace(new PrintWriter(out));
String script = String.format("$('#%s').append('<div>%s</div>');", log.getMarkupId(), out.toString());
handler.appendJavaScript(script);
}
@Override
protected void onInitialize() {
super.onInitialize();
WModalWindow window = new WModalWindow("window");
add(window);
taskBehavior = new DTaskBehavior(this);
add(taskBehavior);
Command command = commandService.load(commandId);
if (targetServiceInstanceId != null) {
OServiceInstance target = serviceInstanceService.load(targetServiceInstanceId);
params.put("target", target);
targetServiceInstances.add(target);
} else {
targetServiceInstances.addAll(serviceInstanceService.findListForCommandExecution(command.getServiceId()));
}
XCommand xCommand = command.getXCommand();
final boolean hasGuest = xCommand.checkHasGuest();
List<XParam> xParams = new ArrayList<>();
xParams.add(
new XParam()
.setName("target")
.setType(XParamType.Service)
.setRequired(true)
);
xParams.addAll(xCommand.getParams());
WFloatTable floatTable = new WFloatTable("floatTable");
floatTable.add(new ListView<XParam>("fields", xParams) {
private static final long serialVersionUID = -5561490679744721872L;
@Override
protected void populateItem(ListItem<XParam> item) {
RepeatingView view = new RepeatingView("field");
XParam xParam = item.getModelObject();
String xParamName = xParam.getName();
FormComponent fieldFormItem;
switch (xParam.getType()) {
case Guest:
WSelectionInput guestSelectionInput = new WSelectionInput(xParamName, new ArrayList(), false);
guestInputList.add(guestSelectionInput);
fieldFormItem = guestSelectionInput;
//TODO defaultValue
/*TODO if(paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, ?);
fieldFormItem.setEnabled(false);
}*/
break;
case Server:
fieldFormItem = new WSelectionInput(xParamName, serverService.findServersAsVM(), false);
/*TODO if(paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, ?);
fieldFormItem.setEnabled(false);
}*/
break;
case Service:
//WSelectionInput selectionInput = new WSelectionInput(xParam.getName(), serviceInstanceService.findListForCommandExecution(targetServiceId), false);
//TODO only work for target param
WSelectionInput selectionInput = new WSelectionInput(xParamName, targetServiceInstances, false);
if (hasGuest) {
selectionInput.addToChoices(new WSelectionInputAjaxUpdatingBehavior() {
private static final long serialVersionUID = -2226097679754487094L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
OServiceInstance serviceInstance = (OServiceInstance) getComponent().getDefaultModelObject();
List<KeyValueVO<String, String>> guestsOf = serverService.findGuestsOf(serviceInstance.getServerId());
for (WSelectionInput guestInput : guestInputList) {
guestInput.updateChoices(target, guestsOf);
}
}
});
}
fieldFormItem = selectionInput;
//TODO defaultValue
/*TODO if(paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, ?);
fieldFormItem.setEnabled(false);
}*/
break;
case File:
fieldFormItem = new FileStoreUploadPanel(xParamName, false);
/*TODO if(paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, ?);
fieldFormItem.setEnabled(false);
}*/
break;
case Boolean:
fieldFormItem = new WBooleanInput(xParamName);
if (paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, Boolean.valueOf(paramsAsStr.get(xParamName)));
fieldFormItem.setEnabled(false);
} else if (xParam.getDefaultValue() != null) {
params.put(xParamName, xParam.getDefaultValueObject());
}
break;
default:
fieldFormItem = new WTextInput(xParamName);
if (paramsAsStr.containsKey(xParamName)) {
params.put(xParamName, paramsAsStr.get(xParamName));
fieldFormItem.setEnabled(false);
}
}
view.add(fieldFormItem.setRequired(xParam.getRequired()).setLabel(new Model<>(xParamName)));
item.add(view);
}
});
Form<Map<String, Object>> form = new Form<>("form", new CompoundPropertyModel<>(params));
form.add(floatTable);
form.add(new DAjaxButton("execute", new ResourceModel("label.execute", "Exec"), AresIcon.EXECUTE) {
private static final long serialVersionUID = 8306959811796741L;
@Override
protected void onSubmit(AjaxRequestTarget target) {
OServiceInstance serviceInstance = (OServiceInstance) params.remove("target");
if (serviceInstance == null) {
error("'target' is required");
}
Map<String, Object> cmdParams = new HashMap<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() instanceof KeyValueVO) {
KeyValueVO vo = (KeyValueVO) entry.getValue();
cmdParams.put(entry.getKey(), vo.getKey());
} else {
cmdParams.put(entry.getKey(), entry.getValue());
}
}
commandService.executeCommandTask(
new CommandQVO(commandId, serviceInstance, cmdParams, prepCommandId).setOsiUserId(osiUserId),
taskBehavior);
}
});
form.add(new DAjaxButton("saveAsPrepCommand", new Model<>("Save as PrepCommand"), AresIcon.SAVE) {
private static final long serialVersionUID = -8824681522137817872L;
@Override
protected void onSubmit(AjaxRequestTarget target) {
OServiceInstance serviceInstance = (OServiceInstance) params.remove("target");
Map<String, Object> cmdParams = new HashMap<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() instanceof KeyValueVO) {
KeyValueVO vo = (KeyValueVO) entry.getValue();
cmdParams.put(entry.getKey(), vo.getKey());
} else {
cmdParams.put(entry.getKey(), entry.getValue());
}
}
window.setContent(new PrepCommandFormDPage(window.getContentId(), commandId, serviceInstance.getId(), cmdParams));
window.show(target);
}
}.setVisible(hasPermission(AresPrivilegeKey.PrepCommandAdd)));
add(form);
tabs = new WebMarkupContainer("tabs");
tabs.setOutputMarkupId(true);
add(tabs);
log = new WebMarkupContainer("log");
log.setOutputMarkupId(true);
tabs.add(log);
tabular = new WebMarkupContainer("tabular");
tabular.setOutputMarkupId(true);
tabs.add(tabular);
}
@Override
protected void onAfterRender() {
super.onAfterRender();
WebUtil.writeJQueryCall(String.format("$('#%s').tabs();", tabs.getMarkupId()), false);
}
private void renderTabular(TabularVO<?> tabularVO, IPartialPageRequestHandler handler) {
String tabId = tabular.getMarkupId() + "-tab";
StringBuilder builder = new StringBuilder();
builder.append(String.format("<table id='%s' border='1' style='width:100%%;'><thead><tr>", tabId));
for (String col : tabularVO.getColumns()) {
//builder.append(String.format("<th data-options=\\\"field:'%s'\\\">", col.replaceAll("\\W",""))).append(col).append("</th>");
builder.append("<th>").append(col).append("</th>");
}
builder.append("</tr></thead><tbody>");
for (Map<String, ?> row : tabularVO.getRows()) {
builder.append("<tr>");
for (Object cell : row.values()) {
builder.append("<td>").append(cell != null ? cell : "").append("</td>");
}
builder.append("</tr>");
}
builder.append("</tbody></table>");
handler.appendJavaScript(String.format("$('#%s').remove();", tabId));
handler.appendJavaScript(String.format("$('#%s').html(\"%s\");", tabular.getMarkupId(), builder.toString()));
//handler.appendJavaScript(String.format("$('#%s').datagrid();", tabId));
handler.appendJavaScript(String.format("$('#%s').tabs('select', 'Tabular');", tabs.getMarkupId()));
}
}
|
package org.sirix.api;
import java.util.List;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.xml.namespace.QName;
import org.sirix.access.Move;
import org.sirix.exception.SirixException;
import org.sirix.exception.SirixIOException;
import org.sirix.node.EKind;
import org.sirix.service.xml.xpath.AtomicValue;
/**
* <h1>IReadTransaction</h1>
*
* <h2>Description</h2>
*
* <p>
* Interface to access nodes based on the
* Key/ParentKey/FirstChildKey/LeftSiblingKey
* /RightSiblingKey/ChildCount/DescendantCount encoding. This encoding keeps the
* children ordered but has no knowledge of the global node ordering. The
* underlying tree is accessed in a cursor-like fashion.
* </p>
*
* <h2>Convention</h2>
*
* <p>
* <ol>
* <li>Only a single thread accesses each INodeReadTransaction instance.</li>
* <li><strong>Precondition</strong> before moving cursor:
* <code>INodeReadTransaction.getNodeKey() == n</code>.</li>
* <li><strong>Postcondition</strong> after moving cursor:
* <code>(INodeReadTransaction.moveToX().hasMoved() &&
* INodeReadTransaction.getNodeKey() == m) ||
* (!INodeReadTransaction.moveToX().hasMoved() &&
* INodeReadTransaction.getNodeKey() == n)</code>.</li>
* </ol>
* </p>
*
* <h2>User Example</h2>
*
* <p>
*
* <pre>
* try(final IReadTransaction rtx = session.beginNodeReadTrx()) {
* // Either test before moving...
* if (rtx.hasFirstChild()) {
* rtx.moveToFirstChild();
* ...
* }
*
* // Or test after moving. Whatever, do the test!
* if (rtx.moveToFirstChild().hasMoved()) {
* ...
* }
*
* // Access local part of element.
* if (rtx.isElement() && "foo".equalsIgnoreCase(rtx.getQName().getLocalName()) {
* ...
* }
*
* // Access value of first attribute of element.
* if (rtx.isElement() && (rtx.getAttributeCount() > 0)) {
* rtx.moveToAttribute(0);
* LOGGER.info(rtx.getValue());
* }
* }
* </pre>
*
* </p>
*
* <h2>Developer Example</h2>
*
* <p>
* <pre>
* public void someIReadTransactionMethod() {
* // This must be called to make sure the transaction is not closed.
* assertNotClosed();
* ...
* }
* </pre>
* </p>
*/
public interface INodeReadTrx extends INodeCursor {
/** String constants used by XPath. */
String[] XPATHCONSTANTS = { "xs:anyType", "xs:anySimpleType",
"xs:anyAtomicType", "xs:untypedAtomic", "xs:untyped", "xs:string",
"xs:duration", "xs:yearMonthDuration", "xs:dayTimeDuration",
"xs:dateTime", "xs:time", "xs:date", "xs:gYearMonth", "xs:gYear",
"xs:gMonthDay", "xs:gDay", "xs:gMonth", "xs:boolean", "xs:base64Binary",
"xs:hexBinary", "xs:anyURI", "xs:QName", "xs:NOTATION", "xs:float",
"xs:double", "xs:pDecimal", "xs:decimal", "xs:integer", "xs:long",
"xs:int", "xs:short", "xs:byte", "xs:nonPositiveInteger",
"xs:negativeInteger", "xs:nonNegativeInteger", "xs:positiveInteger",
"xs:unsignedLong", "xs:unsignedInt", "xs:unsignedShort",
"xs:unsignedByte", "xs:normalizedString", "xs:token", "xs:language",
"xs:name", "xs:NCName", "xs:ID", "xs:IDREF", "xs:ENTITY", "xs:IDREFS",
"xs:NMTOKEN", "xs:NMTOKENS", };
/**
* Get ID of transaction.
*
* @return ID of transaction
*/
long getTransactionID();
/**
* Get the revision number of this transaction.
*
* @return immutable revision number of this IReadTransaction
* @throws SirixIOException
* if can't get revision number
*/
int getRevisionNumber() throws SirixIOException;
/**
* UNIX-style timestamp of the commit of the revision.
*
* @throws SirixIOException
* if can't get timestamp
* @return timestamp of revision commit
*/
long getRevisionTimestamp() throws SirixIOException;
/**
* Getting the maximum nodekey available in this revision.
*
* @return the maximum nodekey
* @throws SirixIOException
* if can't get maxNodKey
*/
long getMaxNodeKey() throws SirixIOException;
/**
* Move cursor to attribute by its index.
*
* @param pIndex
* index of attribute to move to
* @return {@link Moved} instance if the attribute node is selected,
* {@code NotMoved} instance otherwise
*/
Move<? extends INodeReadTrx> moveToAttribute(@Nonnegative int pIndex);
/**
* Move cursor to attribute by its name key.
*
* @param pName
* {@link QName} of attribute
* @return {@link Moved} instance if the attribute node is selected,
* {@code NotMoved} instance otherwise
*/
Move<? extends INodeReadTrx> moveToAttributeByName(@Nonnull QName pName);
/**
* Move cursor to namespace declaration by its index.
*
* @param pIndex
* index of attribute to move to
* @return {@link Moved} instance if the attribute node is selected,
* {@code NotMoved} instance otherwise
*/
Move<? extends INodeReadTrx> moveToNamespace(@Nonnegative int pIndex);
/**
* Move to the next following node, that is the next node on the XPath
* {@code following::-axis}, that is the next node which is not a descendant
* of the current node.
*
* @return {@link Moved} instance if the attribute node is selected,
* {@code NotMoved} instance otherwise
*/
Move<? extends INodeReadTrx> moveToNextFollowing();
/**
* Getting the value of the current node.
*
* @return the current value of the node
*/
String getValue();
/**
* Getting the name of a current node.
*
* @return the {@link QName} of the node
*/
QName getName();
/**
* Getting the type of the current node.
*
* @return the type of the node
*/
String getType();
/**
* Get key for given name. This is used for efficient name testing.
*
* @param pName
* name, i.e., local part, URI, or prefix
* @return internal key assigned to given name
*/
int keyForName(@Nonnull String pName);
/**
* Get name for key. This is used for efficient key testing.
*
* @param pKey
* key, i.e., local part key, URI key, or prefix key.
* @return String containing name for given key
*/
String nameForKey(int pKey);
/**
* Get raw name for key. This is used for efficient key testing.
*
* @param pKey
* key, i.e., local part key, URI key, or prefix key.
* @return byte array containing name for given key
*/
byte[] rawNameForKey(int pKey);
/**
* Get item list containing volatile items such as atoms or fragments.
*
* @return item list
*/
IItemList<AtomicValue> getItemList();
/**
* Close shared read transaction and immediately release all resources.
*
* This is an idempotent operation and does nothing if the transaction is
* already closed.
*
* @throws SirixException
* if can't close {@link INodeReadTrx}
*/
@Override
void close() throws SirixException;
/**
* Is this transaction closed?
*
* @return {@code true} if closed, {@code false} otherwise
*/
boolean isClosed();
/**
* Get the node key of the currently selected node.
*
* @return node key of the currently selected node
*/
long getNodeKey();
/**
* Get the left sibling node key of the currently selected node.
*
* @return left sibling node key of the currently selected node
*/
long getLeftSiblingKey();
/**
* Get the right sibling node key of the currently selected node.
*
* @return right sibling node key of the currently selected node
*/
long getRightSiblingKey();
/**
* Get the first child key of the currently selected node.
*
* @return first child key of the currently selected node
*/
long getFirstChildKey();
/**
* Get the last child key of the currently selected node.
*
* @return last child key of the currently selected node
*/
long getLastChildKey();
/**
* Get the parent key of the currently selected node.
*
* @return parent key of the currently selected node
*/
long getParentKey();
/**
* Get the number of attributes the currently selected node has.
*
* @return number of attributes of the currently selected node
*/
int getAttributeCount();
/**
* Get the number of namespaces the currently selected node has.
*
* @return number of namespaces of the currently selected node
*/
int getNamespaceCount();
/**
* Determines if the current node is a node with a name (element-, attribute-,
* namespace- and processing instruction).
*
* @return {@code true}, if it is, {@code false} otherwise
*/
boolean isNameNode();
/**
* Name key of currently selected node.
*
* @return name key of currently selected node, or 0 if it is not a node with
* a name
*/
int getNameKey();
/**
* Get the {@link ISession} this instance is bound to.
*
* @return session instance
*/
ISession getSession();
/**
* Clone an instance, that is just create a new instance and move the new
* {@link INodeReadTrx} to the current node.
*
* @return new instance
* @throws SirixException
* if Sirix fails
*/
INodeReadTrx cloneInstance() throws SirixException;
/**
* Get the number of nodes which reference to the name.
*
* @param pName
* name to lookup
* @return number of nodes with the same name and node kind
*/
int getNameCount(@Nonnull String pName, @Nonnull EKind pKind);
/**
* Get the type key of the node.
*
* @return type key
*/
int getTypeKey();
/**
* Get the attribute key of the index (for element nodes).
*
* @return attribute key for index or {@code -1} if no attribute with the
* given index is available
*/
long getAttributeKey(@Nonnegative int pIndex);
/**
* Get the path node key of the currently selected node. Make sure to check if
* the node has a name through calling {@link #isNameNode()} at first.
*
* @return the path node key if the currently selected node is a name node,
* {@code -1} else
*/
long getPathNodeKey();
/**
* Get the type of path. Make sure to check if the node has a name through
* calling {@link #isNameNode()} at first.
*
* @return the path kind of the currently selected node or {@code null} if the
* node isn't a node with a name
*/
EKind getPathKind();
/**
* Determines if current node is a structural node (element-, text-, comment-
* and processing instruction)
*
* @return {@code true} if it is a structural node, {@code false} otherwise
*/
boolean isStructuralNode();
/**
* Get the URI-key of a node.
*
* @return URI-key of the currently selected node, or {@code -1} if it is not
* a node with a name (element, attribute, namespace, processing
* instruction)
*/
int getURIKey();
/**
* Get the hash of the currently selected node.
*
* @return hash value
*/
long getHash();
/**
* Get all attributes of currently selected node (only for elements useful,
* otherwise returns an empty list).
*
* @return all attribute keys
*/
List<Long> getAttributeKeys();
/**
* Get all namespaces of currently selected node (only for elements useful,
* otherwise returns an empty list).
*
* @return all namespace keys
*/
List<Long> getNamespaceKeys();
/**
* Get raw value byte-array of currently selected node
*
* @return value of node
*/
byte[] getRawValue();
/**
* Number of children of current node.
*
* @return number of children of current node
*/
long getChildCount();
/**
* Number of descendants of current node.
*
* @return number of descendants of current node
*/
long getDescendantCount();
/**
* Get the namespace URI of the current node.
*
* @return namespace URI
*/
String getNamespaceURI();
@Override
public Move<? extends INodeReadTrx> moveTo(long pKey);
@Override
public Move<? extends INodeReadTrx> moveToDocumentRoot();
@Override
public Move<? extends INodeReadTrx> moveToFirstChild();
@Override
public Move<? extends INodeReadTrx> moveToLastChild();
@Override
public Move<? extends INodeReadTrx> moveToLeftSibling();
@Override
public Move<? extends INodeReadTrx> moveToParent();
@Override
public Move<? extends INodeReadTrx> moveToRightSibling();
/**
* Determines if current node is an {@link ElementNode}.
*
* @return {@code true}, if it is an element node, {@code false} otherwise
*/
public boolean isElement();
/**
* Determines if current node is a {@link TextNode}.
*
* @return {@code true}, if it is an text node, {@code false} otherwise
*/
public boolean isText();
/**
* Determines if current node is the {@link DocumentRootNode}.
*
* @return {@code true}, if it is the document root node, {@code false}
* otherwise
*/
public boolean isDocumentRoot();
/**
* Determines if current node is a {@link CommentNode}.
*
* @return {@code true}, if it is a comment node, {@code false} otherwise
*/
public boolean isComment();
/**
* Determines if current node is an {@link AttributeNode}.
*
* @return {@code true}, if it is an attribute node, {@code false} otherwise
*/
public boolean isAttribute();
/**
* Determines if current node is a {@link NamespaceNode}.
*
* @return {@code true}, if it is a namespace node, {@code false} otherwise
*/
public boolean isNamespace();
/**
* Determines if current node is a {@link PINode}.
*
* @return {@code true}, if it is a processing instruction node, {@code false}
* otherwise
*/
public boolean isPI();
}
|
package com.dianping.cat;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.helper.Files;
import org.unidal.helper.Splitters;
import org.unidal.tuple.Pair;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.configuration.server.entity.ConsoleConfig;
import com.dianping.cat.configuration.server.entity.Domain;
import com.dianping.cat.configuration.server.entity.HdfsConfig;
import com.dianping.cat.configuration.server.entity.LongConfig;
import com.dianping.cat.configuration.server.entity.Property;
import com.dianping.cat.configuration.server.entity.ServerConfig;
import com.dianping.cat.configuration.server.entity.StorageConfig;
import com.dianping.cat.configuration.server.transform.DefaultSaxParser;
import com.dianping.cat.message.Transaction;
public class ServerConfigManager implements Initializable, LogEnabled {
private static final long DEFAULT_HDFS_FILE_MAX_SIZE = 128 * 1024 * 1024L; // 128M
private ServerConfig m_config;
private Logger m_logger;
private Set<String> m_unusedTypes = new HashSet<String>();
private Set<String> m_unusedNames = new HashSet<String>();
public boolean discardTransaction(Transaction t) {
// pigeon default heartbeat is no use
String type = t.getType();
String name = t.getName();
if (m_unusedTypes.contains(type) && m_unusedNames.contains(name)) {
return true;
}
return false;
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
public String getBindHost() {
return null; // any IP address
}
public int getBindPort() {
return 2280;
}
public String getConsoleDefaultDomain() {
if (m_config != null) {
return m_config.getConsole().getDefaultDomain();
} else {
return "Cat";
}
}
public List<Pair<String, Integer>> getConsoleEndpoints() {
if (m_config != null) {
ConsoleConfig console = m_config.getConsole();
String remoteServers = console.getRemoteServers();
List<String> endpoints = Splitters.by(',').noEmptyItem().trim().split(remoteServers);
List<Pair<String, Integer>> pairs = new ArrayList<Pair<String, Integer>>(endpoints.size());
for (String endpoint : endpoints) {
int pos = endpoint.indexOf(':');
String host = (pos > 0 ? endpoint.substring(0, pos) : endpoint);
int port = (pos > 0 ? Integer.parseInt(endpoint.substring(pos + 1)) : 2281);
pairs.add(new Pair<String, Integer>(host, port));
}
return pairs;
} else {
return Collections.emptyList();
}
}
public String getConsoleRemoteServers() {
if (m_config != null) {
ConsoleConfig console = m_config.getConsole();
String remoteServers = console.getRemoteServers();
if (remoteServers != null && remoteServers.length() > 0) {
return remoteServers;
}
}
return "";
}
public String getEmailAccount() {
return "book.robot.dianping@gmail.com";
}
public String getEmailPassword() {
return "xudgtsnoxivwclna";
}
public String getHdfsBaseDir(String id) {
if (m_config != null) {
HdfsConfig hdfsConfig = m_config.getStorage().findHdfs(id);
if (hdfsConfig != null) {
String baseDir = hdfsConfig.getBaseDir();
if (baseDir != null && baseDir.trim().length() > 0) {
return baseDir;
}
}
}
return null;
}
public long getHdfsFileMaxSize(String id) {
if (m_config != null) {
StorageConfig storage = m_config.getStorage();
HdfsConfig hdfsConfig = storage.findHdfs(id);
return toLong(hdfsConfig == null ? null : hdfsConfig.getMaxSize(), DEFAULT_HDFS_FILE_MAX_SIZE);
} else {
return DEFAULT_HDFS_FILE_MAX_SIZE;
}
}
public String getHdfsLocalBaseDir(String id) {
if (m_config != null) {
StorageConfig storage = m_config.getStorage();
return new File(storage.getLocalBaseDir(), id).getPath();
} else if (id == null) {
return "target/bucket";
} else {
return "target/bucket/" + id;
}
}
public Map<String, String> getHdfsProperties() {
if (m_config != null) {
Map<String, String> properties = new HashMap<String, String>();
for (Property p : m_config.getStorage().getProperties().values()) {
properties.put(p.getName(), p.getValue());
}
return properties;
} else {
return Collections.emptyMap();
}
}
public String getHdfsServerUri(String id) {
if (m_config != null) {
HdfsConfig hdfsConfig = m_config.getStorage().findHdfs(id);
if (hdfsConfig != null) {
String serverUri = hdfsConfig.getServerUri();
if (serverUri != null && serverUri.trim().length() > 0) {
return serverUri;
}
}
}
return null;
}
public Map<String, Domain> getLongConfigDomains() {
if (m_config != null) {
LongConfig longConfig = m_config.getConsumer().getLongConfig();
if (longConfig != null) {
return longConfig.getDomains();
}
}
return Collections.emptyMap();
}
public int getLongSqlDefaultThreshold() {
if (m_config != null) {
LongConfig longConfig = m_config.getConsumer().getLongConfig();
if (longConfig != null && longConfig.getDefaultUrlThreshold() != null) {
return longConfig.getDefaultUrlThreshold();
}
}
return 1000; // 1 second
}
public int getLongUrlDefaultThreshold() {
if (m_config != null) {
LongConfig longConfig = m_config.getConsumer().getLongConfig();
if (longConfig != null && longConfig.getDefaultSqlThreshold() != null) {
return longConfig.getDefaultSqlThreshold();
}
}
return 1000; // 1 second
}
public ServerConfig getServerConfig() {
return m_config;
}
public String getStorageLocalBaseDir() {
if (m_config != null) {
StorageConfig storage = m_config.getStorage();
return storage.getLocalBaseDir();
} else {
return "target/bucket";
}
}
@Override
public void initialize() throws InitializationException {
m_unusedTypes.add("Service");
m_unusedTypes.add("PigeonService");
m_unusedNames.add("piegonService:heartTaskService:heartBeat");
m_unusedNames.add("piegonService:heartTaskService:heartBeat()");
m_unusedNames.add("pigeon:HeartBeatService:null");
}
public void initialize(File configFile) throws Exception {
if (configFile != null && configFile.canRead()) {
m_logger.info(String.format("Loading configuration file(%s) ...", configFile.getCanonicalPath()));
String xml = Files.forIO().readFrom(configFile, "utf-8");
ServerConfig config = DefaultSaxParser.parse(xml);
// do validation
config.accept(new ServerConfigValidator());
m_config = config;
} else {
if (configFile != null) {
m_logger.warn(String.format("Configuration file(%s) not found, IGNORED.", configFile.getCanonicalPath()));
}
ServerConfig config = new ServerConfig();
// do validation
config.accept(new ServerConfigValidator());
m_config = config;
}
if (m_config.isLocalMode()) {
m_logger.warn("CAT server is running in LOCAL mode! No HDFS or MySQL will be accessed!");
}
}
public boolean isClientCall(String type) {
return "PigeonCall".equals(type) || "Call".equals(type);
}
public boolean isHdfsOn() {
return !m_config.getStorage().isHdfsDisabled();
}
public boolean isInitialized() {
return m_config != null;
}
public boolean isJobMachine() {
if (m_config != null) {
return m_config.isJobMachine();
} else {
return true;
}
}
public boolean isAlertMachine() {
if (m_config != null) {
String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
// TODO
if ("10.1.6.128".equals(ip)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public boolean isLocalMode() {
if (m_config != null) {
return m_config.isLocalMode();
} else {
return true;
}
}
public boolean isServerService(String type) {
return "PigeonService".equals(type) || "Service".equals(type);
}
private long toLong(String str, long defaultValue) {
long value = 0;
int len = str == null ? 0 : str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
value = value * 10L + (ch - '0');
} else if (ch == 'm' || ch == 'M') {
value *= 1024 * 1024L;
} else if (ch == 'k' || ch == 'K') {
value *= 1024L;
}
}
if (value > 0) {
return value;
} else {
return defaultValue;
}
}
public boolean validateDomain(String domain) {
return !domain.equals("PhoenixAgent") && !domain.equals(Constants.FRONT_END) && !domain.equals(Constants.ALL);
}
}
|
package ru.job4j;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class IteratorPrimeNumberArray implements Iterator {
private final int[] value;
private int index = 0;
private int currentIndexEventNumber = 0;
public IteratorPrimeNumberArray(int[] value) {
this.value = value;
}
@Override
public boolean hasNext() {
for (int i = index; i < value.length; i++) {
boolean markerCheckPrime = true;
if (value[i] == 1) {
markerCheckPrime = false;
}
for (int d = 2; d * d <= value[i]; d++) {
if (value[i] % d == 0) {
markerCheckPrime = false;
break;
}
}
if(markerCheckPrime) {
index = i;
currentIndexEventNumber = i;
return true;
}
}
return false;
}
@Override
public Object next() {
if (hasNext()) {
index++;
return value[currentIndexEventNumber];
} else {
throw new NoSuchElementException();
}
}
}
|
package x2x.translator.xcodeml.xelement;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* The XexprModel represents the exprModel (9.4) element in XcodeML
* intermediate representation.
*
* Elements:
* - Required: on of the followings elements:
* - FintConstant (XintConstant), FrealConstant (XrealConstant),
* FcomplexConstant (XcomplexConstant), FcharacterConstant
* (XcharacterConstant), FlogicalConstant (XlogicalConstant)
* - FarrayConstructor TODO, FstructConstructor TODO
* - Var (Xvar)
* - FarrayRef (XarrayRef), FcharacterRef TODO, FmemberRef TODO,
* FcoArrayRef TODO, varRef (XvarRef)
* - functionCall (XfctCall)
* - plusExpr, minusExpr, mulExpr, divExpr, FpowerExpr, FconcatExpr
* - logEQExpr, logNEQExpr, logGEExpr, logGTExpr, logLEExpr, logLTExpr,
* logAndExpr, logOrExpr, logEQVExpr, logNEQVExpr, logNotExpr TODO ALL
* - unaryMinusExpr, userBinaryExpr, userUnaryExpr TODO
* - FdoLoop (Xdo)
*/
public class XexprModel {
private XbaseElement _element = null;
public XexprModel(XbaseElement element){
_element = element;
}
public XbaseElement getElement(){
return _element;
}
public void setElement(XbaseElement element){
_element = element;
}
public boolean isVar(){
if(_element != null && _element instanceof Xvar){
return true;
}
return false;
}
public Xvar getVar(){
if(isVar()){
return (Xvar)_element;
}
return null;
}
public boolean isIntConst(){
return isOfType(XintConstant.class);
}
public boolean isRealConst(){
return isOfType(XrealConstant.class);
}
public boolean isCharConst(){
return isOfType(XcharacterConstant.class);
}
public boolean isLogicalConst(){
return isOfType(XlogicalConstant.class);
}
public boolean isComplexConst(){
return isOfType(XcomplexConstant.class);
}
public XintConstant getIntConstant(){
if(isIntConst()){
return (XintConstant)_element;
}
return null;
}
private boolean isOfType(Class type){
if(_element != null && type.isInstance(_element)){
return true;
}
return false;
}
}
|
package com.thoughtworks.acceptance;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import java.text.DecimalFormat;
import java.text.ParseException;
public class CustomConverterTest extends AbstractAcceptanceTest {
private final class DoubleConverter implements SingleValueConverter {
private final DecimalFormat formatter;
private DoubleConverter() {
formatter = new DecimalFormat("
}
public boolean canConvert(Class type) {
return type == double.class || type == Double.class;
}
public String toString(Object obj) {
return this.formatter.format(obj);
}
public Object fromString(String str) {
try {
// the formatter will chose the most appropriate format ... Long
return this.formatter.parseObject(str);
} catch (ParseException e) {
throw new ConversionException(e);
}
}
}
public static class DoubleWrapper {
Double d;
public DoubleWrapper(double d) {
this.d = new Double(d);
}
protected DoubleWrapper() {
// JDK 1.3 issue
}
}
public void testWrongObjectTypeReturned() {
xstream.alias("dw", DoubleWrapper.class);
xstream.registerConverter(new DoubleConverter());
String xml = "" +
"<dw>\n" +
" <d>-92.000.000</d>\n" +
"</dw>";
try {
xstream.fromXML(xml);
fail("Thrown " + ConversionException.class.getName() + " expected");
} catch (final ConversionException e) {
assertTrue(e.getMessage().indexOf(Long.class.getName()) > 0);
}
}
}
|
package com.xpn.xwiki.xmlrpc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.Attachment;
import org.codehaus.swizzle.confluence.Comment;
import org.codehaus.swizzle.confluence.ServerInfo;
import org.codehaus.swizzle.confluence.Space;
import org.suigeneris.jrcs.rcs.Version;
import org.xwiki.xmlrpc.model.XWikiExtendedId;
import org.xwiki.xmlrpc.model.XWikiObject;
import org.xwiki.xmlrpc.model.XWikiPage;
import org.xwiki.xmlrpc.model.XWikiPageSummary;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.api.XWiki;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.render.VelocityManager;
import com.xpn.xwiki.web.Utils;
/**
* The class containing the implementation of the XML-RPC API. Methods tagged with the ConfluenceAPI
* are compatible with Confluence.
*/
public class XWikiXmlRpcHandler
{
private XWikiXmlRpcHttpRequestConfig xwikiXmlRpcHttpRequestConfig;
private static final Log LOG = LogFactory.getLog(XWikiXmlRpcHandler.class);
/**
* Initialize the XML-RPC handler with respect to the current HTTP request.
*
* @param servlet The servlet requesting the XML-RPC call handling.
* @param httpRequest The current HTTP request.
*/
public void init(XWikiXmlRpcHttpRequestConfig requestConfig)
{
this.xwikiXmlRpcHttpRequestConfig = requestConfig;
}
/**
* Login.
*
* @return A token to be used in subsequent calls as an identification.
* @throws XmlRpcException If authentication fails.
* @category ConfluenceAPI
*/
public String login(String userName, String password) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
com.xpn.xwiki.XWiki xwiki = xwikiXmlRpcContext.getBaseXWiki();
String token;
if (xwikiXmlRpcContext.getBaseXWiki().getAuthService().authenticate(userName, password,
xwikiXmlRpcContext.getXWikiContext()) != null) {
// Generate "unique" token using a random number
token = xwiki.generateValidationKey(128);
String ip = xwikiXmlRpcContext.getXWikiContext().getRequest().getRemoteAddr();
XWikiUtils.getTokens(xwikiXmlRpcContext.getXWikiContext()).put(token,
new XWikiXmlRpcUser(String.format("XWiki.%s", userName), ip));
return token;
} else {
throw new XmlRpcException(String.format("[Authentication failed for user %s.]",
userName));
}
}
/**
* Logout.
*
* @param token The authentication token.
* @return True is logout was successful.
* @throws XmlRpcException An invalid token is provided.
* @category ConfluenceAPI
*/
public Boolean logout(String token) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
return XWikiUtils.getTokens(xwikiXmlRpcContext.getXWikiContext()).remove(token) != null;
}
/**
* Get server information.
*
* @param token The authentication token.
* @return The server information
* @throws XmlRpcException An invalid token is provided.
* @category ConfluenceAPI
*/
public Map getServerInfo(String token) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getServerInfo()", user.getName()));
String version = xwiki.getVersion();
Integer majorVersion = null;
Integer minorVersion = null;
ServerInfo serverInfo = new ServerInfo();
if (version != null) {
serverInfo.setBuildId(version);
if (version.indexOf('.') != -1) {
String[] components = version.split("\\.");
majorVersion = new Integer(components[0]);
serverInfo.setMajorVersion(majorVersion);
if (components[1].indexOf('-') != -1) {
// Removing possible suffixes (-SNAPSHOT for example)
minorVersion =
new Integer(components[1].substring(0, components[1].indexOf('-')));
} else {
minorVersion = new Integer(components[1]);
}
serverInfo.setMinorVersion(minorVersion);
}
} else {
serverInfo.setMajorVersion(0);
serverInfo.setMinorVersion(0);
}
serverInfo.setPatchLevel(0);
serverInfo.setBaseUrl(xwiki.getURL(""));
return serverInfo.toMap();
}
/**
* @param token The authentication token.
* @return A list of Maps that represents SpaceSummary objects.
* @throws XmlRpcException An invalid token is provided.
* @category ConfluenceAPI
*/
public List getSpaces(String token) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getSpaces()", user.getName()));
List result = new ArrayList();
List<String> spaceKeys = xwiki.getSpaces();
for (String spaceKey : spaceKeys) {
String spaceWebHomeId = String.format("%s.WebHome", spaceKey);
if (!xwiki.exists(spaceWebHomeId)) {
result.add(DomainObjectFactory.createSpaceSummary(spaceKey).toRawMap());
} else {
Document spaceWebHome = xwiki.getDocument(spaceWebHomeId);
/*
* If doc is null, then we don't have the rights to access the document, and
* therefore to the space.
*/
if (spaceWebHome != null) {
result.add(DomainObjectFactory.createSpaceSummary(spaceWebHome).toRawMap());
}
}
}
return result;
}
/**
* @param token The authentication token.
* @return A map representing a Space object.
* @throws XmlRpcException An invalid token is provided or the user doesn't have enough rights
* to access the space.
* @category ConfluenceAPI
*/
public Map getSpace(String token, String spaceKey) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getSpace()", user.getName()));
if (!xwiki.getSpaces().contains(spaceKey)) {
throw new XmlRpcException(String.format("[Space '%s' does not exist]", spaceKey));
}
String spaceWebHomeId = String.format("%s.WebHome", spaceKey);
if (!xwiki.exists(spaceWebHomeId)) {
return DomainObjectFactory.createSpace(spaceKey).toRawMap();
} else {
Document spaceWebHome = xwiki.getDocument(spaceWebHomeId);
/*
* If doc is null, then we don't have the rights to access the document
*/
if (spaceWebHome != null) {
return DomainObjectFactory.createSpace(spaceWebHome).toRawMap();
} else {
throw new XmlRpcException(String.format("[Space '%s' cannot be accessed]",
spaceKey));
}
}
}
/**
* Add a new space. It basically creates a SpaceKey.WebHome page with no content and the space
* title as its title.
*
* @param token The authentication token.
* @param spaceMap The map representing a Space object.
* @return The newly created space as a Space object.
* @throws XmlRpcException Space cannot be created or it already exists and the user has not the
* rights to modify it
* @category ConfluenceAPI
*/
public Map addSpace(String token, Map spaceMap) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called addSpace()", user.getName()));
Space space = new Space(spaceMap);
if (xwiki.getSpaces().contains(space.getKey())) {
throw new XmlRpcException(String
.format("[Space '%s' already exists]", space.getKey()));
}
String spaceWebHomeId = String.format("%s.WebHome", space.getKey());
Document spaceWebHome = xwiki.getDocument(spaceWebHomeId);
if (spaceWebHome != null) {
spaceWebHome.setContent("");
spaceWebHome.setTitle(space.getName());
spaceWebHome.save();
return DomainObjectFactory.createSpace(spaceWebHome).toRawMap();
} else {
throw new XmlRpcException(String
.format(
"[Space cannot be created or it already exists and user '%s' has not the right to modify it]",
user.getName()));
}
}
/**
* Removes a space by deleting every page in it.
*
* @param token The authentication token.
* @return True if the space has been successfully deleted.
* @category ConfluenceAPI
*/
public Boolean removeSpace(String token, String spaceKey) throws XWikiException,
XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called removeSpace()", user.getName()));
if (!xwiki.getSpaces().contains(spaceKey)) {
throw new XmlRpcException(String.format("[Space '%s' does not exist.]", spaceKey));
}
boolean spaceDeleted = true;
List<String> pageNames = xwiki.getSpaceDocsName(spaceKey);
for (String pageName : pageNames) {
String pageFullName = String.format("%s.%s", spaceKey, pageName);
if (xwiki.exists(pageFullName)) {
Document doc = xwiki.getDocument(pageFullName);
if (doc != null) {
try {
if (!doc.getLocked()) {
doc.delete();
} else {
/*
* We cannot delete a locked page, so the space is not fully deleted.
*/
spaceDeleted = false;
}
} catch (XWikiException e) {
/*
* An exception here means that we haven't succeeded in deleting a page, so
* there might be some pages that still belong to the space, so the space is
* not fully deleted
*/
System.out.format("%s\n", e.getMessage());
spaceDeleted = false;
}
} else {
spaceDeleted = false;
}
}
}
return spaceDeleted;
}
/**
* @param token The authentication token.
* @return A list containing PageSummary objects.
* @category ConfluenceAPI
*/
public List getPages(String token, String spaceKey) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getPages()", user.getName()));
List result = new ArrayList();
List<String> pageNames = xwiki.getSpaceDocsName(spaceKey);
for (String pageName : pageNames) {
String pageFullName = String.format("%s.%s", spaceKey, pageName);
if (!xwiki.exists(pageFullName)) {
LOG.warn(String.format(
"[Page '%s' appears to be in space '%s' but no information is available.]",
pageName));
} else {
Document doc = xwiki.getDocument(pageFullName);
/* We only add pages we have the right to access */
if (doc != null) {
XWikiPageSummary pageSummary =
DomainObjectFactory.createXWikiPageSummary(doc);
result.add(pageSummary.toRawMap());
}
}
}
return result;
}
/**
* Retrieves a page.
*
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @param language The language id for the translation
* @param version The desired version. If version == 0 then the latest version is returned.
* @param minorVersion The desired minor version (ignored if version == 0).
* @return A map representing a Page object containing information about the page at version
* 'version.minorVersion'
* @throws XmlRpcException If the user has not the right to access the page or the page does not
* exist at version 'version.minorVersion'.
*/
public Map getPage(String token, String pageId) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getPage()", user.getName()));
/* Extract all needed information from the extended xwiki id */
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
String versionString = extendedId.getParameter("version");
int version = versionString != null ? Integer.parseInt(versionString) : 0;
String minorVersionString = extendedId.getParameter("minorVersion");
int minorVersion = minorVersionString != null ? Integer.parseInt(minorVersionString) : 1;
String language =
extendedId.getParameter("language") != null ? extendedId.getParameter("language")
: "";
if (!xwiki.exists(extendedId.getBasePageId())) {
throw new XmlRpcException(String.format("Unable to get page %s", extendedId
.getBasePageId()));
}
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (language.equals("") || !doc.getTranslationList().contains(language)) {
language = doc.getDefaultLanguage();
}
/*
* If version == 0 then don't get a specific version and keep the latest version
* returned by the previous call of getDocument().
*/
if (version != 0) {
doc = xwiki.getDocument(doc, String.format("%d.%d", version, minorVersion));
}
if (doc != null) {
doc = doc.getTranslatedDocument(language);
if (doc != null) {
if (version != 0) {
/*
* If a specific page version has been requested, encode it it the page id
* using extended page id version
*/
return DomainObjectFactory.createXWikiPage(doc, true).toRawMap();
} else {
return DomainObjectFactory.createXWikiPage(doc, false).toRawMap();
}
} else {
throw new XmlRpcException(String.format(
"Page '%s' does not have an '%s' translation",
extendedId.getBasePageId(), language));
}
} else {
throw new XmlRpcException(String.format(
"Page '%s' does not exist at version %d.%d", extendedId.getBasePageId(),
version, minorVersion));
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed", extendedId
.getBasePageId()));
}
}
/**
* Store a page or create it if it doesn't exist.
*
* @param token The authentication token.
* @param pageMap A map representing the Page object to be stored.
* @return A map representing a Page object with the updated information.
* @category ConfluenceAPI
*/
public Map storePage(String token, Map pageMap) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called storePage()", user.getName()));
XWikiPage page = new XWikiPage(pageMap);
/*
* Confluence semantics compatibility. In order to say to create a page, Confluence sets the
* id to null.
*/
if (page.getId() == null) {
if (page.getTitle() == null) {
throw new XmlRpcException(String
.format("[Neither page title, nor page id is specified!]"));
}
page
.setId(String.format("%s.%s", page.getSpace(), page.getTitle().replace(' ', '_')));
}
if (page.getLanguage() == null) {
page.setLanguage("");
}
XWikiExtendedId extendedId = new XWikiExtendedId(page.getId());
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to store document. Document locked by %s", doc.getLockingUser()));
}
if (!page.getLanguage().equals("")
&& !page.getLanguage().equals(doc.getDefaultLanguage())) {
/*
* Try to get the document in the translation specified in the page parameter...
*/
doc = doc.getTranslatedDocument(page.getLanguage());
if (!doc.getLanguage().equals(page.getLanguage())) {
/*
* If we are here, then the document returned by getTranslatedDocument is the
* same of the default translation, i.e., the page in the current translation
* does not exist. So we have to create it. Here we have to use the low-level
* XWiki API because it is not possible to set the language of a Document.
*/
XWikiDocument xwikiDocument =
new XWikiDocument(page.getSpace(), extendedId.getBasePageId());
xwikiDocument.setLanguage(page.getLanguage());
doc = new Document(xwikiDocument, xwikiXmlRpcContext.getXWikiContext());
}
}
doc.setContent(page.getContent());
doc.setTitle(page.getTitle());
doc.setParent(page.getParentId()); /* Allow reparenting */
doc.save();
return DomainObjectFactory.createXWikiPage(doc, false).toRawMap();
} else {
throw new XmlRpcException(String.format("Cannot get document for page '%s'",
extendedId.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public Boolean removePage(String token, String pageId) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called removePage()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to remove attachment. Document '%s' locked by '%s'", doc
.getName(), doc.getLockingUser()));
}
doc.delete();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return true;
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return A list of maps representing PageHistorySummary objects.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public List getPageHistory(String token, String pageId) throws XWikiException,
XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getPageHistory()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
List result = new ArrayList();
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
Version[] versions = doc.getRevisions();
for (Version version : versions) {
Document docRevision = xwiki.getDocument(doc, version.toString());
/*
* The returned document has the right content but the wrong content update
* date, that is always equals to the current date. Don't know why.
*/
result.add(DomainObjectFactory.createXWikiPageHistorySummary(docRevision)
.toRawMap());
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return result;
}
/**
* Render a page or content in HTML.
*
* @param token The authentication token.
* @param space Ignored
* @param pageId The page id in the form of Space.Page
* @param content The content to be rendered. If content == "" then the page content is
* rendered.
* @return The rendered content.
* @throws XmlRpcException XmlRpcException If the page does not exist or the user has not the
* right to access it.
* @category ConfluenceAPI
*/
public String renderContent(String token, String space, String pageId, String content)
throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called renderContent()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
List result = new ArrayList();
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
/*
* This is the old implementation. TODO: Check if it can be made more lightweight...
* xwiki.renderText() doesn't work fine as the following.
*/
XWikiContext context = xwikiXmlRpcContext.getXWikiContext();
com.xpn.xwiki.XWiki baseXWiki = context.getWiki();
context.setAction("view");
XWikiDocument baseDocument =
baseXWiki.getDocument(extendedId.getBasePageId(), context);
context.setDoc(baseDocument);
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
baseXWiki.prepareDocuments(context.getRequest(), context, vcontext);
if (content.length() == 0) {
// If content is not provided, then the existing content of
// the page is used
content = doc.getContent();
}
return baseXWiki.getRenderingEngine().renderText(content, baseDocument, context);
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return A list of maps representing Comment objects.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public List getComments(String token, String pageId) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getComments()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
List result = new ArrayList();
/* Here we are interested only in the page id without any extended information */
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
Vector<com.xpn.xwiki.api.Object> comments = doc.getComments();
if (comments != null) {
for (com.xpn.xwiki.api.Object commentObject : comments) {
result.add(DomainObjectFactory.createComment(doc, commentObject)
.toRawMap());
}
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return result;
}
public Map getComment(String token, String commentId) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getComment()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(commentId);
int commentNumericalId = Integer.parseInt(extendedId.getParameter("commentId"));
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to remove attachment. Document '%s' locked by '%s'", doc
.getName(), doc.getLockingUser()));
}
com.xpn.xwiki.api.Object commentObject =
doc.getObject("XWiki.XWikiComments", commentNumericalId);
return DomainObjectFactory.createComment(doc, commentObject).toRawMap();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @param commentMap A map representing a Comment object.
* @return A map representing a Comment object with updated information.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public Map addComment(String token, Map commentMap) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called addComment()", user.getName()));
Comment comment = new Comment((Map<String, Object>) commentMap);
XWikiExtendedId extendedId = new XWikiExtendedId(comment.getPageId());
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
int id = doc.createNewObject("XWiki.XWikiComments");
com.xpn.xwiki.api.Object commentObject = doc.getObject("XWiki.XWikiComments", id);
commentObject.set("author", user.getName());
commentObject.set("date", new Date());
commentObject.set("comment", comment.getContent());
doc.save();
return DomainObjectFactory.createComment(doc, commentObject).toRawMap();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return True if the comment has been successfully removed.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public Boolean removeComment(String token, String commentId) throws XWikiException,
XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called removeComment()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(commentId);
int commentNumericalId = Integer.parseInt(extendedId.getParameter("commentId"));
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to remove attachment. Document '%s' locked by '%s'", doc
.getName(), doc.getLockingUser()));
}
com.xpn.xwiki.api.Object commentObject =
doc.getObject("XWiki.XWikiComments", commentNumericalId);
doc.removeObject(commentObject);
doc.save();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return true;
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return A list of maps representing Attachment objects.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public List getAttachments(String token, String pageId) throws XWikiException,
XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getAttachments()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
List result = new ArrayList();
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
List<com.xpn.xwiki.api.Attachment> attachments = doc.getAttachmentList();
for (com.xpn.xwiki.api.Attachment xwikiAttachment : attachments) {
result.add(DomainObjectFactory.createAttachment(xwikiAttachment).toRawMap());
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return result;
}
/**
* @param token The authentication token.
* @param contentId Ignored
* @param attachment The Attachment object used to identify the page id, and attachment
* metadata.
* @param attachmentData The actual attachment data.
* @return An Attachment object describing the newly added attachment.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
* @category ConfluenceAPI
*/
public Map addAttachment(String token, Integer contentId, Map attachmentMap,
byte[] attachmentData) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called addAttachment()", user.getName()));
Attachment attachment = new Attachment((Map) attachmentMap);
XWikiExtendedId extendedId = new XWikiExtendedId(attachment.getPageId());
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to add attachment. Document locked by %s", doc.getLockingUser()));
}
/*
* Here we need to switch to the low-level API because the user's API support for
* attachment is not very well understandable.
*/
/*
* FIXME: CHECK THE FOLLOWING if it's ok!
*/
com.xpn.xwiki.XWiki baseXWiki = xwikiXmlRpcContext.getBaseXWiki();
XWikiDocument xwikiDocument =
baseXWiki.getDocument(extendedId.getBasePageId(), xwikiXmlRpcContext
.getXWikiContext());
XWikiAttachment xwikiBaseAttachment =
xwikiDocument.getAttachment(attachment.getFileName());
if (xwikiBaseAttachment == null) {
xwikiBaseAttachment = new XWikiAttachment();
xwikiDocument.getAttachmentList().add(xwikiBaseAttachment);
}
xwikiBaseAttachment.setContent(attachmentData);
xwikiBaseAttachment.setFilename(attachment.getFileName());
xwikiBaseAttachment.setAuthor(user.getName());
xwikiBaseAttachment.setDoc(xwikiDocument);
xwikiDocument.saveAttachmentContent(xwikiBaseAttachment, xwikiXmlRpcContext
.getXWikiContext());
xwikiXmlRpcContext.getBaseXWiki().saveDocument(xwikiDocument,
xwikiXmlRpcContext.getXWikiContext());
com.xpn.xwiki.api.Attachment xwikiAttachment =
doc.getAttachment(attachment.getFileName());
return DomainObjectFactory.createAttachment(xwikiAttachment).toRawMap();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @param versionNumber (Ignored)
* @return An array of bytes with the actual attachment content.
* @throws XmlRpcException If the page does not exist or the user has not the right to access it
* or the attachment with the given fileName does not exist on the given page.
* @category ConfluenceAPI
*/
public byte[] getAttachmentData(String token, String pageId, String fileName,
String versionNumber) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getAttachmentData()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
com.xpn.xwiki.api.Attachment xwikiAttachment = doc.getAttachment(fileName);
if (xwikiAttachment != null) {
return xwikiAttachment.getContent();
} else {
throw new XmlRpcException(String.format(
"Attachment '%s' does not exist on page '%s'", fileName, extendedId
.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return True if the attachment has been removed.
* @throws XmlRpcException If the page does not exist or the user has not the right to access it
* or the attachment with the given fileName does not exist on the given page.
* @category ConfluenceAPI
*/
public Boolean removeAttachment(String token, String pageId, String fileName)
throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called removeAttachment()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to remove attachment. Document '%s' locked by '%s'", doc
.getName(), doc.getLockingUser()));
}
com.xpn.xwiki.api.Attachment xwikiAttachment = doc.getAttachment(fileName);
if (xwikiAttachment != null) {
/*
* Here we must use low-level XWiki API because there is no way for removing an
* attachment through the XWiki User's API. Basically we use the
* com.xpn.xwiki.XWiki object to re-do all the steps that we have already done
* so far by using the API. It is safe because if we are here, we know that
* everything exists and we have the proper rights to do things. So nothing
* should fail.
*/
com.xpn.xwiki.XWiki baseXWiki = xwikiXmlRpcContext.getBaseXWiki();
XWikiContext xwikiContext = xwikiXmlRpcContext.getXWikiContext();
XWikiDocument baseXWikiDocument =
baseXWiki.getDocument(extendedId.getBasePageId(), xwikiContext);
XWikiAttachment baseXWikiAttachment =
baseXWikiDocument.getAttachment(fileName);
baseXWikiDocument.deleteAttachment(baseXWikiAttachment, xwikiContext);
} else {
throw new XmlRpcException(String.format(
"Attachment '%s' does not exist on page '%s'", fileName, extendedId
.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return true;
}
/**
* @param token The authentication token.
* @return A list of maps representing XWikiClass objects
*/
public List getClasses(String token) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getClasses()", user.getName()));
List result = new ArrayList();
List<String> classNames = xwiki.getClassList();
for (String className : classNames) {
result.add(DomainObjectFactory.createXWikiClassSummary(className).toRawMap());
}
return result;
}
/**
* @param token The authentication token.
* @return A map representing a XWikiClass object.
* @throws XmlRpcException If the given class does not exist.
*/
public Map getClass(String token, String className) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getClass()", user.getName()));
if (!xwiki.exists(className)) {
throw new XmlRpcException(String.format("Class '%s' does not exist", className));
}
com.xpn.xwiki.api.Class userClass = xwiki.getClass(className);
Map map = DomainObjectFactory.createXWikiClass(userClass).toRawMap();
return map; // DomainObjectFactory.createXWikiClass(userClass).toRawMap();
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @return A list of maps representing XWikiObject objects.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
*/
public List getObjects(String token, String pageId) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getObjects()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
List result = new ArrayList();
Map<String, Vector<com.xpn.xwiki.api.Object>> classToObjectsMap =
doc.getxWikiObjects();
for (String className : classToObjectsMap.keySet()) {
Vector<com.xpn.xwiki.api.Object> objects = classToObjectsMap.get(className);
for (com.xpn.xwiki.api.Object object : objects) {
result.add(DomainObjectFactory.createXWikiObjectSummary(doc, object)
.toRawMap());
}
}
return result;
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Unable to get page %s", extendedId
.getBasePageId()));
}
}
/**
* The getObject function will return an XWikiObject where only non-null properties are included
* in the mapping 'field' -> 'value' In order to know all the available fields and their
* respective types and attributes, clients should refer to the object's class.
*
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @param className The class of the object.
* @param id The id (number) of the object.
* @return The XWikiObject containing the information about all the properties contained in the
* selected object.
* @throws XmlRpcException If the page does not exist or the user has not the right to access it
* or no object with the given id exist in the page.
*/
public Map getObject(String token, String pageId, String className, Integer id)
throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called getObject()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
XWikiObject xwikiObject = null;
com.xpn.xwiki.api.Object object = doc.getObject(className, id);
if (object != null) {
return DomainObjectFactory.createXWikiObject(doc, object).toRawMap();
} else {
throw new XmlRpcException(String.format("Unable to find object id %d", id));
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Unable to get page %s", extendedId
.getBasePageId()));
}
}
/**
* Update the object or create a new one if it doesn't exist.
*
* @param token The authentication token.
* @param objectMap A map representing the XWikiObject to be updated/created.
* @return A map representing the XWikiObject with the updated information.
* @throws XmlRpcException If the page does not exist or the user has not the right to access
* it.
*/
public Map storeObject(String token, Map objectMap) throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called storeObject()", user.getName()));
XWikiObject object = new XWikiObject(objectMap);
XWikiExtendedId extendedId = new XWikiExtendedId(object.getPageId());
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to store object. Document locked by %s", doc.getLockingUser()));
}
com.xpn.xwiki.api.Object xwikiObject =
doc.getObject(object.getClassName(), object.getId());
/* If the object does not exist create it */
if (xwikiObject == null) {
int id = doc.createNewObject(object.getClassName());
/* Get the newly created object for update */
xwikiObject = doc.getObject(object.getClassName(), id);
}
/*
* We iterate on the XWikiObject-passed-as-a-parameter's properties instead of the
* one retrieved through the API because, a newly created object has no properties,
* and they should be added via set. Apparently setting properties that do not
* belong to the object's class is harmless.
*/
for (String propertyName : object.getProperties()) {
/*
* Object values are always sent as strings (or arrays/maps of strings)... let
* the actual object perform the conversion
*/
xwikiObject.set(propertyName, object.getProperty(propertyName));
}
doc.save();
return DomainObjectFactory.createXWikiObject(doc, xwikiObject).toRawMap();
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Unable to get page %s", extendedId
.getBasePageId()));
}
}
/**
* @param token The authentication token.
* @param pageId The pageId in the 'Space.Page' format.
* @param id The object's id.
* @return True if the object has been successfully deleted.
* @throws XmlRpcException If the page does not exist or the user has not the right to access it
* or no object with the given id exist in the page.
*/
public Boolean removeObject(String token, String pageId, String className, Integer id)
throws XWikiException, XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called removeObject()", user.getName()));
XWikiExtendedId extendedId = new XWikiExtendedId(pageId);
if (xwiki.exists(extendedId.getBasePageId())) {
Document doc = xwiki.getDocument(extendedId.getBasePageId());
if (doc != null) {
if (doc.getLocked()) {
throw new XmlRpcException(String.format(
"Unable to remove attachment. Document '%s' locked by '%s'", doc
.getName(), doc.getLockingUser()));
}
com.xpn.xwiki.api.Object commentObject = doc.getObject(className, id);
if (commentObject != null) {
doc.removeObject(commentObject);
doc.save();
} else {
throw new XmlRpcException(String.format(
"Object %s[%d] on page '%s' does not exist", className, id, extendedId
.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' cannot be accessed",
extendedId.getBasePageId()));
}
} else {
throw new XmlRpcException(String.format("Page '%s' doesn't exist", extendedId
.getBasePageId()));
}
return true;
}
/**
* @param token The authentication token.
* @param query The string to be looked for. If it is "__ALL_PAGES__" the search will return all
* the page ids available in the Wiki.
* @return A list of SearchResults
*/
public List search(String token, String query, int maxResults) throws XWikiException,
XmlRpcException
{
XWikiXmlRpcContext xwikiXmlRpcContext = xwikiXmlRpcHttpRequestConfig.getXmlRpcContext();
XWikiXmlRpcUser user = XWikiUtils.checkToken(token, xwikiXmlRpcContext.getXWikiContext());
XWiki xwiki = xwikiXmlRpcContext.getXWiki();
LOG.debug(String.format("User %s has called search()", user.getName()));
com.xpn.xwiki.XWiki baseXWiki = xwikiXmlRpcContext.getBaseXWiki();
List result = new ArrayList();
if (query.equals("__ALL_PAGES__")) {
List<String> spaceKeys = xwiki.getSpaces();
for (String spaceKey : spaceKeys) {
List<String> pageNames = xwiki.getSpaceDocsName(spaceKey);
for (String pageName : pageNames) {
result.add(DomainObjectFactory.createSearchResult(
String.format("%s.%s", spaceKey, pageName)).toMap());
}
}
} else {
List<String> searchResults =
baseXWiki.getStore().searchDocumentsNames(
"where doc.content like '%" + com.xpn.xwiki.web.Utils.SQLFilter(query)
+ "%' or doc.name like '%" + com.xpn.xwiki.web.Utils.SQLFilter(query)
+ "%'", xwikiXmlRpcContext.getXWikiContext());
int i = 0;
for (String pageId : searchResults) {
if (maxResults > 0 && i < maxResults) {
result.add(DomainObjectFactory.createSearchResult(pageId).toMap());
} else {
break;
}
i++;
}
}
return result;
}
}
|
import capsule.DependencyManagerImpl;
import capsule.DependencyManager;
import capsule.PomReader;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Capsule implements Runnable, FileVisitor<Path> {
/*
* This class contains several strange hacks to avoid creating more classes,
* as we'd like this file to compile to a single .class file.
*
* Also, the code is not meant to be the most efficient, but methods should be as independent and stateless as possible.
* Other than those few, methods called in the constructor, all others are can be called in any order, and don't rely on any state.
*
* We do a lot of data transformations that would have really benefitted from Java 8's lambdas and streams,
* but we want Capsule to support Java 7.
*/
private static final String VERSION = "0.6.0";
//<editor-fold defaultstate="collapsed" desc="Constants">
/////////// Constants ///////////////////////////////////
private static final String PROP_RESET = "capsule.reset";
private static final String PROP_VERSION = "capsule.version";
private static final String PROP_LOG = "capsule.log";
private static final String PROP_TREE = "capsule.tree";
private static final String PROP_APP_ID = "capsule.app.id";
private static final String PROP_PRINT_JRES = "capsule.jvms";
private static final String PROP_CAPSULE_JAVA_HOME = "capsule.java.home";
private static final String PROP_MODE = "capsule.mode";
private static final String PROP_USE_LOCAL_REPO = "capsule.local";
private static final String PROP_OFFLINE = "capsule.offline";
private static final String PROP_RESOLVE = "capsule.resolve";
private static final String PROP_JAVA_VERSION = "java.version";
private static final String PROP_JAVA_HOME = "java.home";
private static final String PROP_OS_NAME = "os.name";
private static final String PROP_USER_HOME = "user.home";
private static final String PROP_JAVA_LIBRARY_PATH = "java.library.path";
private static final String PROP_FILE_SEPARATOR = "file.separator";
private static final String PROP_PATH_SEPARATOR = "path.separator";
private static final String PROP_JAVA_SECURITY_POLICY = "java.security.policy";
private static final String PROP_JAVA_SECURITY_MANAGER = "java.security.manager";
private static final String ENV_CAPSULE_REPOS = "CAPSULE_REPOS";
private static final String ATTR_APP_NAME = "Application-Name";
private static final String ATTR_APP_VERSION = "Application-Version";
private static final String ATTR_APP_CLASS = "Application-Class";
private static final String ATTR_APP_ARTIFACT = "Application";
private static final String ATTR_UNIX_SCRIPT = "Unix-Script";
private static final String ATTR_WINDOWS_SCRIPT = "Windows-Script";
private static final String ATTR_EXTRACT = "Extract-Capsule";
private static final String ATTR_MIN_JAVA_VERSION = "Min-Java-Version";
private static final String ATTR_JAVA_VERSION = "Java-Version";
private static final String ATTR_MIN_UPDATE_VERSION = "Min-Update-Version";
private static final String ATTR_JDK_REQUIRED = "JDK-Required";
private static final String ATTR_JVM_ARGS = "JVM-Args";
private static final String ATTR_ARGS = "Args";
private static final String ATTR_ENV = "Environment-Variables";
private static final String ATTR_SYSTEM_PROPERTIES = "System-Properties";
private static final String ATTR_APP_CLASS_PATH = "App-Class-Path";
private static final String ATTR_CAPSULE_IN_CLASS_PATH = "Capsule-In-Class-Path";
private static final String ATTR_BOOT_CLASS_PATH = "Boot-Class-Path";
private static final String ATTR_BOOT_CLASS_PATH_A = "Boot-Class-Path-A";
private static final String ATTR_BOOT_CLASS_PATH_P = "Boot-Class-Path-P";
private static final String ATTR_LIBRARY_PATH_A = "Library-Path-A";
private static final String ATTR_LIBRARY_PATH_P = "Library-Path-P";
private static final String ATTR_SECURITY_MANAGER = "Security-Manager";
private static final String ATTR_SECURITY_POLICY = "Security-Policy";
private static final String ATTR_SECURITY_POLICY_A = "Security-Policy-A";
private static final String ATTR_JAVA_AGENTS = "Java-Agents";
private static final String ATTR_REPOSITORIES = "Repositories";
private static final String ATTR_DEPENDENCIES = "Dependencies";
private static final String ATTR_NATIVE_DEPENDENCIES_LINUX = "Native-Dependencies-Linux";
private static final String ATTR_NATIVE_DEPENDENCIES_WIN = "Native-Dependencies-Win";
private static final String ATTR_NATIVE_DEPENDENCIES_MAC = "Native-Dependencies-Mac";
private static final String ATTR_IMPLEMENTATION_VERSION = "Implementation-Version";
// outgoing
private static final String VAR_CAPSULE_DIR = "CAPSULE_DIR";
private static final String VAR_CAPSULE_JAR = "CAPSULE_JAR";
private static final String VAR_JAVA_HOME = "JAVA_HOME";
private static final String ENV_CACHE_DIR = "CAPSULE_CACHE_DIR";
private static final String ENV_CACHE_NAME = "CAPSULE_CACHE_NAME";
private static final String PROP_CAPSULE_JAR = "capsule.jar";
private static final String PROP_CAPSULE_DIR = "capsule.dir";
private static final String PROP_CAPSULE_APP = "capsule.app";
// misc
private static final String CACHE_DEFAULT_NAME = "capsule";
private static final String DEPS_CACHE_NAME = "deps";
private static final String APP_CACHE_NAME = "apps";
private static final String POM_FILE = "pom.xml";
private static final String DOT = "\\.";
private static final String CUSTOM_CAPSULE_CLASS_NAME = "CustomCapsule";
private static final String FILE_SEPARATOR = System.getProperty(PROP_FILE_SEPARATOR);
private static final String PATH_SEPARATOR = System.getProperty(PROP_PATH_SEPARATOR);
private static final Path DEFAULT_LOCAL_MAVEN = Paths.get(System.getProperty(PROP_USER_HOME), ".m2", "repository");
//</editor-fold> /////////////////////////////////////////////////////////////////////////////////////////////////
private static final boolean debug = "debug".equals(System.getProperty(PROP_LOG, "quiet"));
private static final boolean verbose = debug || "verbose".equals(System.getProperty(PROP_LOG, "quiet"));
private final Path cacheDir;
private final JarFile jar; // null only in tests
private final byte[] jarBuffer; // non-null only in tests
private final Path jarFile; // never null
private final Manifest manifest; // never null
private final String javaHome;
private final String appId; // null iff isEmptyCapsule()
private final Path appCache; // non-null iff capsule is extracted
private final boolean cacheUpToDate;
private final String mode;
private final Object pom; // non-null iff jar has pom AND manifest doesn't have ATTR_DEPENDENCIES
private final Object dependencyManager; // non-null iff needsDependencyManager is true
private Process child;
//<editor-fold defaultstate="collapsed" desc="Main">
/////////// Main ///////////////////////////////////
/**
* Launches the application
*
* @param args the program's command-line arguments
*/
@SuppressWarnings({"BroadCatchBlock", "CallToPrintStackTrace"})
public static final void main(String[] args) {
try {
final Capsule capsule = newCapsule(getJarFile());
if (anyPropertyDefined(PROP_VERSION, PROP_PRINT_JRES, PROP_TREE, PROP_RESOLVE)) {
if (anyPropertyDefined(PROP_VERSION))
capsule.printVersion(args);
if (anyPropertyDefined(PROP_PRINT_JRES))
capsule.printJVMs();
if (anyPropertyDefined(PROP_TREE))
capsule.printDependencyTree(args);
if (anyPropertyDefined(PROP_RESOLVE))
capsule.resolve(args);
return;
}
final Process p = capsule.launch(ManagementFactory.getRuntimeMXBean().getInputArguments(), args);
if (p != null)
System.exit(p.waitFor());
} catch (Throwable t) {
System.err.println("CAPSULE EXCEPTION: " + t.getMessage()
+ (!verbose ? " (for stack trace, run with -D" + PROP_LOG + "=verbose)" : ""));
if (verbose)
t.printStackTrace(System.err);
System.exit(1);
}
}
private static Capsule newCapsule(Path jarFile) {
try {
final Class<?> clazz = Class.forName(CUSTOM_CAPSULE_CLASS_NAME);
try {
Constructor<?> ctor = clazz.getConstructor(Path.class);
ctor.setAccessible(true);
return (Capsule) ctor.newInstance(jarFile);
} catch (Exception e) {
throw new RuntimeException("Could not launch custom capsule.", e);
}
} catch (ClassNotFoundException e) {
return new Capsule(jarFile);
}
}
private static Path getJarFile() {
final URL url = Capsule.class.getClassLoader().getResource(Capsule.class.getName().replace('.', '/') + ".class");
if (!"jar".equals(url.getProtocol()))
throw new IllegalStateException("The Capsule class must be in a JAR file, but was loaded from: " + url);
final String path = url.getPath();
if (path == null || !path.startsWith("file:"))
throw new IllegalStateException("The Capsule class must be in a local JAR file, but was loaded from: " + url);
try {
final URI jarUri = new URI(path.substring(0, path.indexOf('!')));
return Paths.get(jarUri);
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
}
private static boolean anyPropertyDefined(String... props) {
for (String prop : props) {
if (System.getProperty(prop) != null)
return true;
}
return false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructors">
/////////// Constructors ///////////////////////////////////
/**
* Constructs a capsule from the given JAR file
*
* @param jarFile the path to the JAR file
*/
protected Capsule(Path jarFile) {
this(jarFile, null, null, null);
}
/**
* Constructs a capsule from the given byte array
*
* @param jarBuffer a byte array containing the capsule JAR
*/
protected Capsule(byte[] jarBuffer) {
this(null, jarBuffer, null, null);
}
// Used directly by tests
private Capsule(Path jarFile, byte[] jarBuffer, Path cacheDir, Object dependencyManager) {
final boolean test = jarBuffer != null;
this.jarFile = jarFile;
try {
this.jar = jarBuffer == null ? new JarFile(jarFile.toFile()) : null; // only use of old File API;
this.jarBuffer = jarBuffer;
this.manifest = jar != null ? jar.getManifest() : getJarInputStream().getManifest();
if (manifest == null)
throw new RuntimeException("JAR file " + jarFile + " does not have a manifest");
} catch (IOException e) {
throw new RuntimeException("Could not read JAR file " + jarFile + " manifest");
}
this.cacheDir = initCacheDir(cacheDir != null ? cacheDir : getCacheDir());
this.javaHome = getJavaHome();
this.mode = System.getProperty(PROP_MODE);
this.pom = (!hasAttribute(ATTR_DEPENDENCIES) && hasPom()) ? createPomReader() : null;
if (test || dependencyManager != null)
this.dependencyManager = dependencyManager;
else
this.dependencyManager = needsDependencyManager() ? createDependencyManager(getRepositories()) : null;
this.appId = getAppId();
this.appCache = needsAppCache() ? getAppCacheDir() : null;
this.cacheUpToDate = appCache != null ? isUpToDate() : false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Properties">
/////////// Properties ///////////////////////////////////
private boolean isEmptyCapsule() {
return !hasAttribute(ATTR_APP_ARTIFACT) && !hasAttribute(ATTR_APP_CLASS) && getScript() == null;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Capsule JAR">
/////////// Capsule JAR ///////////////////////////////////
private JarInputStream getJarInputStream() throws IOException {
return new JarInputStream(new ByteArrayInputStream(jarBuffer));
}
private String getJarPath() {
return jarFile.toAbsolutePath().getParent().toString();
}
private String toJarUrl(String relPath) {
return "jar:file:" + getJarPath() + "!/" + relPath;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Main Operations">
/////////// Main Operations ///////////////////////////////////
private void printVersion(String[] args) {
System.out.println("CAPSULE: Application " + appId(args));
System.out.println("CAPSULE: Capsule Version " + VERSION);
}
private void printJVMs() {
final Map<String, Path> jres = getJavaHomes(false);
if (jres == null)
println("No detected Java installations");
else {
System.out.println("CAPSULE: Detected Java installations:");
for (Map.Entry<String, Path> j : jres.entrySet())
System.out.println(j.getKey() + (j.getKey().length() < 8 ? "\t\t" : "\t") + j.getValue());
}
System.out.println("CAPSULE: selected " + (javaHome != null ? javaHome : (System.getProperty(PROP_JAVA_HOME) + " (current)")));
}
private void printDependencyTree(String[] args) {
System.out.println("Dependencies for " + appId(args));
if (dependencyManager == null)
System.out.println("No dependencies declared.");
else if (hasAttribute(ATTR_APP_ARTIFACT) || isEmptyCapsule()) {
final String appArtifact = isEmptyCapsule() ? getCommandLineArtifact(args) : getAttribute(ATTR_APP_ARTIFACT);
if (appArtifact == null)
throw new IllegalStateException("capsule " + jarFile + " has nothing to run");
printDependencyTree(appArtifact);
} else
printDependencyTree(getDependencies(), "jar");
final List<String> nativeDeps = getNativeDependencies();
if (nativeDeps != null) {
System.out.println("\nNative Dependencies:");
printDependencyTree(nativeDeps, getNativeLibExtension());
}
}
private void resolve(String[] args) throws IOException, InterruptedException {
ensureExtractedIfNecessary();
getPath(getListAttribute(ATTR_BOOT_CLASS_PATH));
getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_P));
getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_A));
resolveAppArtifact(getAppArtifact(args));
resolveDependencies(getDependencies(), "jar");
resolveNativeDependencies();
}
private Process launch(List<String> cmdLine, String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = launchCapsuleArtifact(cmdLine, args);
if (pb == null)
pb = prepareForLaunch(cmdLine, args);
Runtime.getRuntime().addShutdownHook(new Thread(this));
if (!isInheritIoBug())
pb.inheritIO();
this.child = pb.start();
if (isInheritIoBug())
pipeIoStreams();
return child;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Launch">
/////////// Launch ///////////////////////////////////
// directly used by CapsuleLauncher as well as by the tests
final ProcessBuilder prepareForLaunch(List<String> cmdLine, String[] args) {
ensureExtractedIfNecessary();
final ProcessBuilder pb = buildProcess(cmdLine, args);
if (appCache != null && !cacheUpToDate)
markCache();
verbose("Launching app " + appId(args));
return pb;
}
private void ensureExtractedIfNecessary() {
if (appCache != null && !cacheUpToDate) {
resetAppCache();
if (shouldExtract())
extractCapsule();
}
}
private ProcessBuilder buildProcess(List<String> cmdLine, String[] args) {
final ProcessBuilder pb = new ProcessBuilder();
if (!buildScriptProcess(pb))
buildJavaProcess(pb, cmdLine);
final List<String> command = pb.command();
command.addAll(buildArgs(args));
buildEnvironmentVariables(pb.environment());
verbose(join(command, " "));
return pb;
}
/**
* Returns a list of command line arguments to pass to the application.
*
* @param args The command line arguments passed to the capsule at launch
*/
protected List<String> buildArgs(String[] args) {
final List<String> args0 = new ArrayList<String>();
args0.addAll(nullToEmpty(expand(getListAttribute(ATTR_ARGS))));
args0.addAll(Arrays.asList(args));
return args0;
}
/**
* Returns a map of environment variables (property-value pairs).
*
* @param env the current environment
*/
private void buildEnvironmentVariables(Map<String, String> env) {
final List<String> jarEnv = getListAttribute(ATTR_ENV);
if (jarEnv != null) {
for (String e : jarEnv) {
String var = getBefore(e, '=');
String value = getAfter(e, '=');
if (var == null)
throw new IllegalArgumentException("Malformed env variable definition: " + e);
boolean overwrite = false;
if (var.endsWith(":")) {
overwrite = true;
var = var.substring(0, var.length() - 1);
}
if (overwrite || !env.containsKey(var))
env.put(var, value != null ? value : "");
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Script">
/////////// Script ///////////////////////////////////
private String getScript() {
return getAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT);
}
private boolean buildScriptProcess(ProcessBuilder pb) {
final String script = getScript();
if (script == null)
return false;
if (appCache == null)
throw new IllegalStateException("Cannot run the startup script " + script + " when the "
+ ATTR_EXTRACT + " attribute is set to false");
final Path scriptPath = appCache.resolve(sanitize(script)).toAbsolutePath();
ensureExecutable(scriptPath);
pb.command().add(scriptPath.toString());
return true;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Capsule Artifact">
/////////// Capsule Artifact ///////////////////////////////////
private ProcessBuilder launchCapsuleArtifact(List<String> cmdLine, String[] args) {
if (getScript() == null) {
final String appArtifact = getAppArtifact(args);
if (appArtifact != null) {
try {
final List<Path> jars = resolveAppArtifact(appArtifact);
if (jars == null)
return null;
if (isCapsule(jars.get(0))) {
verbose("Running capsule " + jars.get(0));
return launchCapsule(jars.get(0),
cmdLine,
isEmptyCapsule() ? Arrays.copyOfRange(args, 1, args.length) : buildArgs(args).toArray(new String[0]));
} else if (isEmptyCapsule())
throw new IllegalArgumentException("Artifact " + appArtifact + " is not a capsule.");
} catch (RuntimeException e) {
if (isEmptyCapsule())
throw new RuntimeException("Usage: java -jar capsule.jar CAPSULE_ARTIFACT_COORDINATES", e);
else
throw e;
}
}
}
return null;
}
private static boolean isCapsule(Path path) {
if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(".jar")) {
try (final JarInputStream jar = new JarInputStream(Files.newInputStream(path))) {
return isCapsule(jar);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
private static boolean isCapsule(JarInputStream jar) {
return "Capsule".equals(getMainClass(jar.getManifest()));
}
private static ProcessBuilder launchCapsule(Path path, List<String> cmdLine, String[] args) {
try {
final ClassLoader cl = new URLClassLoader(new URL[]{path.toUri().toURL()}, null);
Class clazz;
try {
clazz = cl.loadClass(CUSTOM_CAPSULE_CLASS_NAME);
} catch (ClassNotFoundException e) {
clazz = cl.loadClass(Capsule.class.getName());
}
final Object capsule;
try {
Constructor<?> ctor = clazz.getConstructor(Path.class);
ctor.setAccessible(true);
capsule = ctor.newInstance(path);
} catch (Exception e) {
throw new RuntimeException("Could not launch custom capsule.", e);
}
final Method launch = clazz.getMethod("prepareForLaunch", List.class, String[].class);
launch.setAccessible(true);
return (ProcessBuilder) launch.invoke(capsule, cmdLine, args);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException | NoSuchMethodException e) {
throw new RuntimeException(path + " does not appear to be a valid capsule.", e);
} catch (IllegalAccessException e) {
throw new AssertionError();
} catch (InvocationTargetException e) {
final Throwable t = e.getTargetException();
if (t instanceof RuntimeException)
throw (RuntimeException) t;
if (t instanceof Error)
throw (Error) t;
throw new RuntimeException(t);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="App ID">
/////////// App ID ///////////////////////////////////
private String getAppId() {
if (isEmptyCapsule())
return null;
String appName = System.getProperty(PROP_APP_ID);
if (appName == null)
appName = getAttribute(ATTR_APP_NAME);
if (appName == null) {
final String appArtifact = getAppArtifact(null);
if (appArtifact != null)
return getAppArtifactId(getAppArtifactLatestVersion(appArtifact));
}
if (appName == null) {
if (pom != null)
return getPomAppName();
appName = getAttribute(ATTR_APP_CLASS);
}
if (appName == null) {
if (isEmptyCapsule())
return null;
throw new RuntimeException("Capsule jar " + jarFile + " must either have the " + ATTR_APP_NAME + " manifest attribute, "
+ "the " + ATTR_APP_CLASS + " attribute, or contain a " + POM_FILE + " file.");
}
final String version = hasAttribute(ATTR_APP_VERSION) ? getAttribute(ATTR_APP_VERSION) : getAttribute(ATTR_IMPLEMENTATION_VERSION);
return appName + (version != null ? "_" + version : "");
}
private String appId(String[] args) {
if (appId != null)
return appId;
assert isEmptyCapsule();
String appArtifact = getAppArtifact(args);
if (appArtifact == null)
throw new RuntimeException("No application to run");
return getAppArtifactId(getAppArtifactLatestVersion(appArtifact));
}
private static String getAppArtifactId(String coords) {
if (coords == null)
return null;
final String[] cs = coords.split(":");
if (cs.length < 2)
throw new IllegalArgumentException("Illegal main artifact coordinates: " + coords);
String id = cs[0] + "_" + cs[1];
if (cs.length > 2)
id += "_" + cs[2];
return id;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Capsule Cache">
/////////// Capsule Cache ///////////////////////////////////
private static Path getCacheDir() {
final Path cache;
final String cacheDirEnv = System.getenv(ENV_CACHE_DIR);
if (cacheDirEnv != null)
cache = Paths.get(cacheDirEnv);
else {
final String cacheNameEnv = System.getenv(ENV_CACHE_NAME);
final String cacheName = cacheNameEnv != null ? cacheNameEnv : CACHE_DEFAULT_NAME;
cache = getCacheHome().resolve((isWindows() ? "" : ".") + cacheName);
}
return cache;
}
private static Path initCacheDir(Path cache) {
try {
if (!Files.exists(cache))
Files.createDirectory(cache);
if (!Files.exists(cache.resolve(APP_CACHE_NAME)))
Files.createDirectory(cache.resolve(APP_CACHE_NAME));
if (!Files.exists(cache.resolve(DEPS_CACHE_NAME)))
Files.createDirectory(cache.resolve(DEPS_CACHE_NAME));
return cache;
} catch (IOException e) {
throw new RuntimeException("Error opening cache directory " + cache.toAbsolutePath(), e);
}
}
private static Path getCacheHome() {
final Path userHome = Paths.get(System.getProperty(PROP_USER_HOME));
if (!isWindows())
return userHome;
Path localData;
final String localAppData = System.getenv("LOCALAPPDATA");
if (localAppData != null) {
localData = Paths.get(localAppData);
if (!Files.isDirectory(localData))
throw new RuntimeException("%LOCALAPPDATA% set to nonexistent directory " + localData);
} else {
localData = userHome.resolve(Paths.get("AppData", "Local"));
if (!Files.isDirectory(localData))
localData = userHome.resolve(Paths.get("Local Settings", "Application Data"));
if (!Files.isDirectory(localData))
throw new RuntimeException("%LOCALAPPDATA% is undefined, and neither "
+ userHome.resolve(Paths.get("AppData", "Local")) + " nor "
+ userHome.resolve(Paths.get("Local Settings", "Application Data")) + " have been found");
}
return localData;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="App Cache">
/////////// App Cache ///////////////////////////////////
private Path getAppCacheDir() {
assert appId != null;
Path appDir = cacheDir.resolve(APP_CACHE_NAME).resolve(appId);
try {
if (!Files.exists(appDir))
Files.createDirectory(appDir);
return appDir;
} catch (IOException e) {
throw new RuntimeException("Application cache directory " + appDir.toAbsolutePath() + " could not be created.");
}
}
private boolean needsAppCache() {
if (isEmptyCapsule())
return false;
if (hasRenamedNativeDependencies())
return true;
if (hasAttribute(ATTR_APP_ARTIFACT))
return false;
return shouldExtract();
}
private boolean shouldExtract() {
final String extract = getAttribute(ATTR_EXTRACT);
return extract == null || Boolean.parseBoolean(extract);
}
private List<Path> getDefaultCacheClassPath() {
final List<Path> cp = new ArrayList<Path>();
cp.add(appCache);
for (Path f : listDir(appCache)) {
if (Files.isRegularFile(f) && f.getFileName().toString().endsWith(".jar"))
cp.add(f.toAbsolutePath());
}
return cp;
}
private void resetAppCache() {
try {
debug("Creating cache for " + jarFile + " in " + appCache.toAbsolutePath());
delete(appCache);
Files.createDirectory(appCache);
} catch (IOException e) {
throw new RuntimeException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e);
}
}
private boolean isUpToDate() {
if (Boolean.parseBoolean(System.getProperty(PROP_RESET, "false")))
return false;
try {
Path extractedFile = appCache.resolve(".extracted");
if (!Files.exists(extractedFile))
return false;
FileTime extractedTime = Files.getLastModifiedTime(extractedFile);
FileTime jarTime = Files.getLastModifiedTime(jarFile);
return extractedTime.compareTo(jarTime) >= 0;
} catch (IOException e) {
throw new AssertionError(e);
}
}
private void extractCapsule() {
try {
verbose("Extracting " + jarFile + " to app cache directory " + appCache.toAbsolutePath());
if (jar != null)
extractJar(jar, appCache);
else
extractJar(getJarInputStream(), appCache);
} catch (IOException e) {
throw new RuntimeException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e);
}
}
private void markCache() {
try {
Files.createFile(appCache.resolve(".extracted"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Build Java Process">
/////////// Build Java Process ///////////////////////////////////
private boolean buildJavaProcess(ProcessBuilder pb, List<String> cmdLine) {
if (javaHome != null)
pb.environment().put("JAVA_HOME", javaHome);
final List<String> command = pb.command();
command.add(getJavaProcessName());
command.addAll(buildJVMArgs(cmdLine));
command.addAll(compileSystemProperties(buildSystemProperties(cmdLine)));
addOption(command, "-Xbootclasspath:", compileClassPath(buildBootClassPath(cmdLine)));
addOption(command, "-Xbootclasspath/p:", compileClassPath(buildClassPath(ATTR_BOOT_CLASS_PATH_P)));
addOption(command, "-Xbootclasspath/a:", compileClassPath(buildClassPath(ATTR_BOOT_CLASS_PATH_A)));
final List<Path> classPath = buildClassPath();
command.add("-classpath");
command.add(compileClassPath(classPath));
for (String jagent : nullToEmpty(buildJavaAgents()))
command.add("-javaagent:" + jagent);
command.add(getMainClass(classPath));
return true;
}
private static List<String> compileSystemProperties(Map<String, String> ps) {
final List<String> command = new ArrayList<String>();
for (Map.Entry<String, String> entry : ps.entrySet())
command.add("-D" + entry.getKey() + (entry.getValue() != null && !entry.getValue().isEmpty() ? "=" + entry.getValue() : ""));
return command;
}
private static String compileClassPath(List<Path> cp) {
return join(cp, PATH_SEPARATOR);
}
private static void addOption(List<String> cmdLine, String prefix, String value) {
if (value == null)
return;
cmdLine.add(prefix + value);
}
private List<Path> buildClassPath() {
final List<Path> classPath = new ArrayList<Path>();
if (!isEmptyCapsule() && !hasAttribute(ATTR_APP_ARTIFACT)) {
// the capsule jar
final String isCapsuleInClassPath = getAttribute(ATTR_CAPSULE_IN_CLASS_PATH);
if (isCapsuleInClassPath == null || Boolean.parseBoolean(isCapsuleInClassPath))
classPath.add(jarFile);
else if (appCache == null)
throw new IllegalStateException("Cannot set the " + ATTR_CAPSULE_IN_CLASS_PATH + " attribute to false when the "
+ ATTR_EXTRACT + " attribute is also set to false");
}
if (hasAttribute(ATTR_APP_ARTIFACT)) {
assert dependencyManager != null;
classPath.addAll(nullToEmpty(resolveAppArtifact(getAttribute(ATTR_APP_ARTIFACT))));
}
if (hasAttribute(ATTR_APP_CLASS_PATH)) {
for (String sp : getListAttribute(ATTR_APP_CLASS_PATH)) {
Path p = path(expand(sanitize(sp)));
if (appCache == null && (!p.isAbsolute() || p.startsWith(appCache)))
throw new IllegalStateException("Cannot resolve " + sp + " in " + ATTR_APP_CLASS_PATH + " attribute when the "
+ ATTR_EXTRACT + " attribute is set to false");
p = appCache.resolve(p);
classPath.add(p);
}
}
if (appCache != null)
classPath.addAll(nullToEmpty(getDefaultCacheClassPath()));
classPath.addAll(nullToEmpty(resolveDependencies(getDependencies(), "jar")));
return classPath;
}
/**
* Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier]} (classifier is optional)
*/
protected List<String> getDependencies() {
List<String> deps = getListAttribute(ATTR_DEPENDENCIES);
if (deps == null && pom != null)
deps = getPomDependencies();
return deps != null ? Collections.unmodifiableList(deps) : null;
}
private List<Path> buildBootClassPath(List<String> cmdLine) {
String option = null;
for (String o : cmdLine) {
if (o.startsWith("-Xbootclasspath:"))
option = o.substring("-Xbootclasspath:".length());
}
if (option != null)
return toPath(Arrays.asList(option.split(PATH_SEPARATOR)));
return getPath(getListAttribute(ATTR_BOOT_CLASS_PATH));
}
private List<Path> buildClassPath(String attr) {
return getPath(getListAttribute(attr));
}
/**
* Returns a map of system properties (property-value pairs).
*
* @param cmdLine the list of JVM arguments passed to the capsule at launch
*/
protected Map<String, String> buildSystemProperties(List<String> cmdLine) {
final Map<String, String> systemProperties = new HashMap<String, String>();
// attribute
for (Map.Entry<String, String> pv : nullToEmpty(getMapAttribute(ATTR_SYSTEM_PROPERTIES, "")).entrySet())
systemProperties.put(pv.getKey(), expand(pv.getValue()));
// library path
if (appCache != null) {
final List<Path> libraryPath = buildNativeLibraryPath();
libraryPath.add(appCache);
systemProperties.put(PROP_JAVA_LIBRARY_PATH, compileClassPath(libraryPath));
} else if (hasAttribute(ATTR_LIBRARY_PATH_P) || hasAttribute(ATTR_LIBRARY_PATH_A))
throw new IllegalStateException("Cannot use the " + ATTR_LIBRARY_PATH_P + " or the " + ATTR_LIBRARY_PATH_A
+ " attributes when the " + ATTR_EXTRACT + " attribute is set to false");
if (hasAttribute(ATTR_SECURITY_POLICY) || hasAttribute(ATTR_SECURITY_POLICY_A)) {
systemProperties.put(PROP_JAVA_SECURITY_MANAGER, "");
if (hasAttribute(ATTR_SECURITY_POLICY_A))
systemProperties.put(PROP_JAVA_SECURITY_POLICY, toJarUrl(getAttribute(ATTR_SECURITY_POLICY_A)));
if (hasAttribute(ATTR_SECURITY_POLICY))
systemProperties.put(PROP_JAVA_SECURITY_POLICY, "=" + toJarUrl(getAttribute(ATTR_SECURITY_POLICY)));
}
if (hasAttribute(ATTR_SECURITY_MANAGER))
systemProperties.put(PROP_JAVA_SECURITY_MANAGER, getAttribute(ATTR_SECURITY_MANAGER));
// Capsule properties
if (appCache != null)
systemProperties.put(PROP_CAPSULE_DIR, appCache.toAbsolutePath().toString());
systemProperties.put(PROP_CAPSULE_JAR, getJarPath());
systemProperties.put(PROP_CAPSULE_APP, appId);
// command line
for (String option : cmdLine) {
if (option.startsWith("-D"))
addSystemProperty(option.substring(2), systemProperties);
}
return systemProperties;
}
private static void addSystemProperty(String p, Map<String, String> ps) {
try {
String name = getBefore(p, '=');
String value = getAfter(p, '=');
ps.put(name, value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Illegal system property definition: " + p);
}
}
//<editor-fold desc="Native Dependencies">
/////////// Native Dependencies ///////////////////////////////////
private List<Path> buildNativeLibraryPath() {
final List<Path> libraryPath = new ArrayList<Path>();
resolveNativeDependencies();
libraryPath.addAll(nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_P))));
libraryPath.addAll(toPath(Arrays.asList(System.getProperty(PROP_JAVA_LIBRARY_PATH).split(PATH_SEPARATOR))));
libraryPath.addAll(nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_A))));
libraryPath.add(appCache);
return libraryPath;
}
private void resolveNativeDependencies() {
if (appCache == null)
throw new IllegalStateException("Cannot set " + ATTR_EXTRACT + " to false if there are native dependencies.");
final List<String> depsAndRename = getNativeDependenciesAndRename();
if (depsAndRename == null || depsAndRename.isEmpty())
return;
final List<String> deps = new ArrayList<String>(depsAndRename.size());
final List<String> renames = new ArrayList<String>(depsAndRename.size());
for (String depAndRename : depsAndRename) {
String[] dna = depAndRename.split(",");
deps.add(dna[0]);
renames.add(dna.length > 1 ? dna[1] : null);
}
verbose("Resolving native libs " + deps);
final List<Path> resolved = resolveDependencies(deps, getNativeLibExtension());
if (resolved.size() != deps.size())
throw new RuntimeException("One of the native artifacts " + deps + " reolved to more than a single file");
assert appCache != null;
if (!cacheUpToDate) {
if (debug)
System.err.println("Copying native libs to " + appCache);
try {
for (int i = 0; i < deps.size(); i++) {
final Path lib = resolved.get(i);
final String rename = sanitize(renames.get(i));
Files.copy(lib, appCache.resolve(rename != null ? rename : lib.getFileName().toString()));
}
} catch (IOException e) {
throw new RuntimeException("Exception while copying native libs");
}
}
}
/**
* Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier][,renameTo]}
* (classifier and renameTo are optional)
*/
protected List<String> getNativeDependenciesAndRename() {
if (isWindows())
return getListAttribute(ATTR_NATIVE_DEPENDENCIES_WIN);
if (isMac())
return getListAttribute(ATTR_NATIVE_DEPENDENCIES_MAC);
if (isUnix())
return getListAttribute(ATTR_NATIVE_DEPENDENCIES_LINUX);
return null;
}
private List<String> getNativeDependencies() {
return stripNativeDependencies(getNativeDependenciesAndRename());
}
protected final List<String> stripNativeDependencies(List<String> nativeDepsAndRename) {
if (nativeDepsAndRename == null)
return null;
final List<String> deps = new ArrayList<String>(nativeDepsAndRename.size());
for (String depAndRename : nativeDepsAndRename) {
String[] dna = depAndRename.split(",");
deps.add(dna[0]);
}
return deps;
}
private boolean hasRenamedNativeDependencies() {
final List<String> depsAndRename = getNativeDependenciesAndRename();
if (depsAndRename == null)
return false;
for (String depAndRename : depsAndRename) {
if (depAndRename.contains(","))
return true;
}
return false;
}
//</editor-fold>
/**
* Returns a list of JVM arguments.
*
* @param cmdLine the list of JVM arguments passed to the capsule at launch
*/
protected List<String> buildJVMArgs(List<String> cmdLine) {
final Map<String, String> jvmArgs = new LinkedHashMap<String, String>();
for (String a : nullToEmpty(getListAttribute(ATTR_JVM_ARGS))) {
a = a.trim();
if (!a.isEmpty() && !a.startsWith("-Xbootclasspath:") && !a.startsWith("-javaagent:"))
addJvmArg(expand(a), jvmArgs);
}
for (String option : cmdLine) {
if (!option.startsWith("-D") && !option.startsWith("-Xbootclasspath:"))
addJvmArg(option, jvmArgs);
}
return new ArrayList<String>(jvmArgs.values());
}
private static void addJvmArg(String a, Map<String, String> args) {
args.put(getJvmArgKey(a), a);
}
private static String getJvmArgKey(String a) {
if (a.equals("-client") || a.equals("-server"))
return "compiler";
if (a.equals("-enablesystemassertions") || a.equals("-esa")
|| a.equals("-disablesystemassertions") || a.equals("-dsa"))
return "systemassertions";
if (a.equals("-jre-restrict-search") || a.equals("-no-jre-restrict-search"))
return "-jre-restrict-search";
if (a.startsWith("-Xloggc:"))
return "-Xloggc";
if (a.startsWith("-Xloggc:"))
return "-Xloggc";
if (a.startsWith("-Xss"))
return "-Xss";
if (a.startsWith("-XX:+") || a.startsWith("-XX:-"))
return "-XX:" + a.substring("-XX:+".length());
if (a.contains("="))
return a.substring(0, a.indexOf("="));
return a;
}
private List<String> buildJavaAgents() {
final Map<String, String> agents0 = getMapAttribute(ATTR_JAVA_AGENTS, "");
if (agents0 == null)
return null;
final List<String> agents = new ArrayList<String>(agents0.size());
for (Map.Entry<String, String> agent : agents0.entrySet()) {
final String agentJar = agent.getKey();
final String agentOptions = agent.getValue();
try {
final Path agentPath = getPath(agent.getKey());
agents.add(agentPath + ((agentOptions != null && !agentOptions.isEmpty()) ? "=" + agentOptions : ""));
} catch (IllegalStateException e) {
if (appCache == null)
throw new RuntimeException("Cannot run the embedded Java agent " + agentJar + " when the " + ATTR_EXTRACT + " attribute is set to false");
throw e;
}
}
return agents;
}
private String getMainClass(List<Path> classPath) {
try {
String mainClass = getAttribute(ATTR_APP_CLASS);
if (mainClass == null && hasAttribute(ATTR_APP_ARTIFACT))
mainClass = getMainClass(classPath.get(0).toAbsolutePath());
if (mainClass == null)
throw new RuntimeException("Jar " + classPath.get(0).toAbsolutePath() + " does not have a main class defined in the manifest.");
return mainClass;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String getAppArtifact(String[] args) {
String appArtifact = null;
if (isEmptyCapsule()) {
if (args == null)
return null;
appArtifact = getCommandLineArtifact(args);
if (appArtifact == null)
throw new IllegalStateException("Capsule " + jarFile + " has nothing to run");
}
if (appArtifact == null)
appArtifact = getAttribute(ATTR_APP_ARTIFACT);
return appArtifact;
}
private String getCommandLineArtifact(String[] args) {
if (args.length > 0)
return args[0];
return null;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Get Java Home">
/////////// Get Java Home ///////////////////////////////////
private String getJavaHome() {
String jhome = System.getProperty(PROP_CAPSULE_JAVA_HOME);
if (jhome == null && !isMatchingJavaVersion(System.getProperty(PROP_JAVA_VERSION))) {
final boolean jdk = hasAttribute(ATTR_JDK_REQUIRED) && Boolean.parseBoolean(getAttribute(ATTR_JDK_REQUIRED));
final Path javaHomePath = findJavaHome(jdk);
if (javaHomePath == null) {
throw new RuntimeException("Could not find Java installation for requested version "
+ '[' + "Min. Java version: " + getAttribute(ATTR_MIN_JAVA_VERSION)
+ " JavaVersion: " + getAttribute(ATTR_JAVA_VERSION)
+ " Min. update version: " + getAttribute(ATTR_MIN_UPDATE_VERSION) + ']'
+ " (JDK required: " + jdk + ")"
+ ". You can override the used Java version with the -D" + PROP_CAPSULE_JAVA_HOME + " flag.");
}
jhome = javaHomePath.toAbsolutePath().toString();
}
return jhome;
}
private Path findJavaHome(boolean jdk) {
final Map<String, Path> homes = getJavaHomes(jdk);
if (homes == null)
return null;
Path best = null;
String bestVersion = null;
for (Map.Entry<String, Path> e : homes.entrySet()) {
final String v = e.getKey();
debug("Trying JVM: " + e.getValue() + " (version " + e.getKey() + ")");
if (isMatchingJavaVersion(v)) {
debug("JVM " + e.getValue() + " (version " + e.getKey() + ") matches");
if (bestVersion == null || compareVersions(v, bestVersion) > 0) {
debug("JVM " + e.getValue() + " (version " + e.getKey() + ") is best so far");
bestVersion = v;
best = e.getValue();
}
}
}
return best;
}
private boolean isMatchingJavaVersion(String javaVersion) {
try {
if (hasAttribute(ATTR_MIN_JAVA_VERSION) && compareVersions(javaVersion, getAttribute(ATTR_MIN_JAVA_VERSION)) < 0) {
debug("Java version " + javaVersion + " fails to match due to " + ATTR_MIN_JAVA_VERSION + ": " + getAttribute(ATTR_MIN_JAVA_VERSION));
return false;
}
if (hasAttribute(ATTR_JAVA_VERSION) && compareVersions(javaVersion, shortJavaVersion(getAttribute(ATTR_JAVA_VERSION)), 3) > 0) {
debug("Java version " + javaVersion + " fails to match due to " + ATTR_JAVA_VERSION + ": " + getAttribute(ATTR_JAVA_VERSION));
return false;
}
if (getMinUpdateFor(javaVersion) > parseJavaVersion(javaVersion)[3]) {
debug("Java version " + javaVersion + " fails to match due to " + ATTR_MIN_UPDATE_VERSION + ": " + getAttribute(ATTR_MIN_UPDATE_VERSION) + " (" + getMinUpdateFor(javaVersion) + ")");
return false;
}
debug("Java version " + javaVersion + " matches");
return true;
} catch (IllegalArgumentException ex) {
verbose("Error parsing Java version " + javaVersion);
return false;
}
}
private int getMinUpdateFor(String version) {
final Map<String, String> m = getMapAttribute(ATTR_MIN_UPDATE_VERSION, null);
if (m == null)
return 0;
final int[] ver = parseJavaVersion(version);
for (Map.Entry<String, String> entry : m.entrySet()) {
if (equals(ver, toInt(shortJavaVersion(entry.getKey()).split(DOT)), 3))
return Integer.parseInt(entry.getValue());
}
return 0;
}
private String getJavaProcessName() {
final String javaHome1 = javaHome != null ? javaHome : System.getProperty(PROP_JAVA_HOME);
verbose("Using JVM: " + javaHome1 + (javaHome == null ? " (current)" : ""));
return getJavaProcessName(javaHome1);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="POM">
/////////// POM ///////////////////////////////////
private boolean hasPom() {
return hasEntry(POM_FILE);
}
private Object createPomReader() {
try {
return new PomReader(getEntry(POM_FILE));
} catch (NoClassDefFoundError e) {
throw new RuntimeException("Jar " + jarFile
+ " contains a pom.xml file, while the necessary dependency management classes are not found in the jar");
} catch (IOException e) {
throw new RuntimeException("Failed reading pom", e);
}
}
private List<String> getPomRepositories() {
return ((PomReader) pom).getRepositories();
}
private List<String> getPomDependencies() {
return ((PomReader) pom).getDependencies();
}
private String getPomAppName() {
final PomReader pr = (PomReader) pom;
return pr.getGroupId() + "_" + pr.getArtifactId() + "_" + pr.getVersion();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Dependency Manager">
/////////// Dependency Manager ///////////////////////////////////
private boolean needsDependencyManager() {
return hasAttribute(ATTR_APP_ARTIFACT)
|| isEmptyCapsule()
|| pom != null
|| getDependencies() != null
|| getNativeDependencies() != null;
}
private List<String> getRepositories() {
List<String> repos = new ArrayList<String>();
List<String> attrRepos = split(System.getenv(ENV_CAPSULE_REPOS), ":");
if (attrRepos == null)
attrRepos = getListAttribute(ATTR_REPOSITORIES);
if (attrRepos != null)
repos.addAll(attrRepos);
if (pom != null) {
for (String repo : nullToEmpty(getPomRepositories())) {
if (!repos.contains(repo))
repos.add(repo);
}
}
return !repos.isEmpty() ? Collections.unmodifiableList(repos) : null;
}
private Object createDependencyManager(List<String> repositories) {
try {
final Path depsCache = cacheDir.resolve(DEPS_CACHE_NAME);
final boolean reset = Boolean.parseBoolean(System.getProperty(PROP_RESET, "false"));
final String local = expandCommandLinePath(System.getProperty(PROP_USE_LOCAL_REPO));
Path localRepo = depsCache;
if (local != null)
localRepo = !local.isEmpty() ? Paths.get(local) : DEFAULT_LOCAL_MAVEN;
debug("Local repo: " + localRepo);
final boolean offline = "".equals(System.getProperty(PROP_OFFLINE)) || Boolean.parseBoolean(System.getProperty(PROP_OFFLINE));
debug("Offline: " + offline);
final DependencyManager dm = new DependencyManagerImpl(localRepo.toAbsolutePath(), repositories, reset, offline);
return dm;
} catch (NoClassDefFoundError e) {
throw new RuntimeException("Jar " + jarFile
+ " specifies dependencies, while the necessary dependency management classes are not found in the jar");
}
}
private void printDependencyTree(String root) {
final DependencyManager dm = (DependencyManager) dependencyManager;
dm.printDependencyTree(root);
}
private void printDependencyTree(List<String> dependencies, String type) {
if (dependencies == null)
return;
final DependencyManager dm = (DependencyManager) dependencyManager;
dm.printDependencyTree(dependencies, type);
}
private List<Path> resolveDependencies(List<String> dependencies, String type) {
if (dependencies == null)
return null;
return ((DependencyManager) dependencyManager).resolveDependencies(dependencies, type);
}
private String getAppArtifactLatestVersion(String coords) {
if (coords == null)
return null;
final DependencyManager dm = (DependencyManager) dependencyManager;
return dm.getLatestVersion(coords);
}
private List<Path> resolveAppArtifact(String coords) {
if (coords == null)
return null;
final DependencyManager dm = (DependencyManager) dependencyManager;
return dm.resolveRoot(coords);
}
private static Path getDependencyPath(Object dependencyManager, String p) {
if (dependencyManager == null)
throw new RuntimeException("No dependencies specified in the capsule. Cannot resolve dependency " + p);
final DependencyManager dm = (DependencyManager) dependencyManager;
List<Path> depsJars = dm.resolveDependency(p, "jar");
if (depsJars == null || depsJars.isEmpty())
throw new RuntimeException("Dependency " + p + " was not found.");
return depsJars.iterator().next().toAbsolutePath();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Attributes">
/////////// Attributes ///////////////////////////////////
private String getAttribute(String attr) {
String value = null;
Attributes atts;
if (mode != null) {
atts = manifest.getAttributes(mode);
if (atts == null)
throw new IllegalArgumentException("Mode " + mode + " not defined in manifest");
value = atts.getValue(attr);
}
if (value == null) {
atts = manifest.getMainAttributes();
value = atts.getValue(attr);
}
return value;
}
private boolean hasAttribute(String attr) {
final Attributes.Name key = new Attributes.Name(attr);
Attributes atts;
if (mode != null) {
atts = manifest.getAttributes(mode);
if (atts != null && atts.containsKey(key))
return true;
}
atts = manifest.getMainAttributes();
return atts.containsKey(new Attributes.Name(attr));
}
private List<String> getListAttribute(String attr) {
return split(getAttribute(attr), "\\s+");
}
private Map<String, String> getMapAttribute(String attr, String defaultValue) {
return mapSplit(getAttribute(attr), '=', "\\s+", defaultValue);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Dependency Utils">
/////////// Dependency Utils ///////////////////////////////////
private static boolean isDependency(String lib) {
return lib.contains(":");
}
private String dependencyToLocalJar(boolean withGroupId, String p) {
String[] coords = p.split(":");
StringBuilder sb = new StringBuilder();
if (withGroupId)
sb.append(coords[0]).append('-');
sb.append(coords[1]).append('-');
sb.append(coords[2]);
if (coords.length > 3)
sb.append('-').append(coords[3]);
sb.append(".jar");
return sb.toString();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Paths">
/////////// Paths ///////////////////////////////////
private Path getPath(String p) {
if (isDependency(p) && dependencyManager != null)
return getDependencyPath(dependencyManager, p);
if (appCache == null)
throw new IllegalStateException(
(isDependency(p) ? "Dependency manager not found. Cannot resolve" : "Capsule not extracted. Cannot obtain path")
+ " " + p);
if (isDependency(p)) {
Path f = appCache.resolve(dependencyToLocalJar(true, p));
if (Files.isRegularFile(f))
return f;
f = appCache.resolve(dependencyToLocalJar(false, p));
if (Files.isRegularFile(f))
return f;
throw new IllegalArgumentException("Dependency manager not found, and could not locate artifact " + p + " in capsule");
} else
return toAbsolutePath(appCache, p);
}
private List<Path> getPath(List<String> ps) {
if (ps == null)
return null;
final List<Path> res = new ArrayList<Path>(ps.size());
for (String p : ps)
res.add(getPath(p));
return res;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="JAR Extraction">
/////////// JAR Extraction ///////////////////////////////////
private static void extractJar(JarFile jar, Path targetDir) throws IOException {
for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
final JarEntry entry = (JarEntry) entries.nextElement();
if (entry.isDirectory() || !shouldExtractFile(entry.getName()))
continue;
try (InputStream is = jar.getInputStream(entry)) {
writeFile(targetDir, entry.getName(), is);
}
}
}
private static void extractJar(JarInputStream jar, Path targetDir) throws IOException {
for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) {
if (entry.isDirectory() || !shouldExtractFile(entry.getName()))
continue;
writeFile(targetDir, entry.getName(), jar);
}
}
private static boolean shouldExtractFile(String fileName) {
if (fileName.equals(Capsule.class.getName().replace('.', '/') + ".class")
|| (fileName.startsWith(Capsule.class.getName().replace('.', '/') + "$") && fileName.endsWith(".class")))
return false;
if (fileName.endsWith(".class"))
return false;
if (fileName.startsWith("capsule/"))
return false;
final String dir = getDirectory(fileName);
if (dir != null && dir.startsWith("META-INF"))
return false;
return true;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Path Utils">
/////////// Path Utils ///////////////////////////////////
private Path path(String p, String... more) {
return cacheDir.getFileSystem().getPath(p, more);
}
private List<Path> toPath(List<String> ps) {
if (ps == null)
return null;
final List<Path> aps = new ArrayList<Path>(ps.size());
for (String p : ps)
aps.add(path(p));
return aps;
}
private static List<Path> toAbsolutePath(Path root, List<String> ps) {
if (ps == null)
return null;
final List<Path> aps = new ArrayList<Path>(ps.size());
for (String p : ps)
aps.add(toAbsolutePath(root, p));
return aps;
}
private static Path toAbsolutePath(Path root, String p) {
return root.resolve(sanitize(p)).toAbsolutePath();
}
private static String sanitize(String path) {
if (path.startsWith("/") || path.startsWith("../") || path.contains("/../"))
throw new IllegalArgumentException("Path " + path + " is not local");
return path;
}
private static String expandCommandLinePath(String str) {
if (str == null)
return null;
// if (isWindows())
// return str;
// else
return str.startsWith("~/") ? str.replace("~", System.getProperty(PROP_USER_HOME)) : str;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="OS">
protected static final boolean isWindows() {
return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows");
}
protected static final boolean isMac() {
return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("mac");
}
protected static final boolean isUnix() {
return System.getProperty(PROP_OS_NAME).toLowerCase().contains("nux")
|| System.getProperty(PROP_OS_NAME).toLowerCase().contains("solaris")
|| System.getProperty(PROP_OS_NAME).toLowerCase().contains("aix");
}
private String getNativeLibExtension() {
if (isWindows())
return "dll";
if (isMac())
return "dylib";
if (isUnix())
return "so";
throw new RuntimeException("Unsupported operating system: " + System.getProperty(PROP_OS_NAME));
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="JAR Utils">
/////////// JAR Utils ///////////////////////////////////
private static String getMainClass(Path jar) throws IOException {
try (final JarInputStream jis = new JarInputStream(Files.newInputStream(jar))) {
return getMainClass(jis.getManifest());
}
}
private static String getMainClass(Manifest manifest) {
if (manifest != null)
return manifest.getMainAttributes().getValue("Main-Class");
return null;
}
private boolean hasEntry(String name) {
try {
return getEntry(name) != null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private InputStream getEntry(String name) throws IOException {
if (jar != null) {
final JarEntry entry = jar.getJarEntry(name);
if (entry == null)
return null;
return jar.getInputStream(entry);
}
// test
final JarInputStream jis = getJarInputStream();
for (JarEntry entry; (entry = jis.getNextJarEntry()) != null;) {
if (name.equals(entry.getName()))
return jis;
}
return null;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="File Utils">
/////////// File Utils ///////////////////////////////////
private static void writeFile(Path targetDir, String fileName, InputStream is) throws IOException {
final String dir = getDirectory(fileName);
if (dir != null)
Files.createDirectories(targetDir.resolve(dir));
final Path targetFile = targetDir.resolve(fileName);
Files.copy(is, targetFile);
}
private static String getDirectory(String filename) {
final int index = filename.lastIndexOf('/');
if (index < 0)
return null;
return filename.substring(0, index);
}
private void delete(Path dir) throws IOException {
// we don't use Files.walkFileTree because we'd like to avoid creating more classes (Capsule$1.class etc.)
for (Path f : listDir(dir, FILE_VISITOR_MODE_POSTORDER))
Files.delete(f);
}
private static void ensureExecutable(Path file) {
if (!Files.isExecutable(file)) {
try {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
if (!perms.contains(PosixFilePermission.OWNER_EXECUTE)) {
Set<PosixFilePermission> newPerms = EnumSet.copyOf(perms);
newPerms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(file, newPerms);
}
} catch (UnsupportedOperationException e) {
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="JRE Installations">
/////////// JRE Installations ///////////////////////////////////
private Map<String, Path> getJavaHomes(boolean jdk) {
Path dir = Paths.get(System.getProperty(PROP_JAVA_HOME)).getParent();
while (dir != null) {
Map<String, Path> homes = getJavaHomes(dir, jdk);
if (homes != null)
return homes;
dir = dir.getParent();
}
return null;
}
private Map<String, Path> getJavaHomes(Path dir, boolean jdk) {
if (!Files.isDirectory(dir))
return null;
Map<String, Path> dirs = new HashMap<String, Path>();
for (Path f : listDir(dir)) {
if (Files.isDirectory(f)) {
String dirName = f.getFileName().toString();
String ver = isJavaDir(dirName);
if (ver != null && (!jdk || isJDK(dirName))) {
final Path home = searchJavaHomeInDir(f);
if (home != null) {
if (parseJavaVersion(ver)[3] == 0)
ver = getActualJavaVersion(home.toString());
dirs.put(ver, home);
}
}
}
}
return !dirs.isEmpty() ? dirs : null;
}
private static String isJavaDir(String fileName) {
fileName = fileName.toLowerCase();
if (fileName.startsWith("jdk") || fileName.startsWith("jre") || fileName.endsWith(".jdk") || fileName.endsWith(".jre")) {
if (fileName.startsWith("jdk") || fileName.startsWith("jre"))
fileName = fileName.substring(3);
if (fileName.endsWith(".jdk") || fileName.endsWith(".jre"))
fileName = fileName.substring(0, fileName.length() - 4);
return shortJavaVersion(fileName);
} else
return null;
}
private static boolean isJDK(String filename) {
return filename.toLowerCase().contains("jdk");
}
private Path searchJavaHomeInDir(Path dir) {
if (!Files.isDirectory(dir))
return null;
for (Path f : listDir(dir)) {
if (isJavaHome(f))
return f;
Path home = searchJavaHomeInDir(f);
if (home != null)
return home;
}
return null;
}
private boolean isJavaHome(Path dir) {
if (Files.isDirectory(dir)) {
for (Path f : listDir(dir)) {
if (Files.isDirectory(f) && f.getFileName().toString().equals("bin")) {
for (Path f0 : listDir(f)) {
if (Files.isRegularFile(f0)) {
String fname = f0.getFileName().toString().toLowerCase();
if (fname.equals("java") || fname.equals("java.exe"))
return true;
}
}
break;
}
}
}
return false;
}
private static String getJavaProcessName(String javaHome) {
return javaHome + FILE_SEPARATOR + "bin" + FILE_SEPARATOR + "java" + (isWindows() ? ".exe" : "");
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Version Strings">
/////////// Version Strings ///////////////////////////////////
private static final Pattern PAT_JAVA_VERSION_LINE = Pattern.compile(".*?\"(.+?)\"");
private static String getActualJavaVersion(String javaHome) {
try {
final ProcessBuilder pb = new ProcessBuilder(getJavaProcessName(javaHome), "-version");
if (javaHome != null)
pb.environment().put("JAVA_HOME", javaHome);
final Process p = pb.start();
final String version;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
final String versionLine = reader.readLine();
final Matcher m = PAT_JAVA_VERSION_LINE.matcher(versionLine);
if (!m.matches())
throw new IllegalArgumentException("Could not parse version line: " + versionLine);
version = m.group(1);
}
// p.waitFor();
return version;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// visible for testing
static String shortJavaVersion(String v) {
try {
final String[] vs = v.split(DOT);
if (vs.length == 1) {
if (Integer.parseInt(vs[0]) < 5)
throw new RuntimeException("Unrecognized major Java version: " + v);
v = "1." + v + ".0";
}
if (vs.length == 2)
v += ".0";
return v;
} catch (NumberFormatException e) {
return null;
}
}
static final int compareVersions(String a, String b, int n) {
return compareVersions(parseJavaVersion(a), parseJavaVersion(b), n);
}
static final int compareVersions(String a, String b) {
return compareVersions(parseJavaVersion(a), parseJavaVersion(b));
}
private static int compareVersions(int[] a, int[] b) {
return compareVersions(a, b, 5);
}
private static int compareVersions(int[] a, int[] b, int n) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i])
return a[i] - b[i];
}
return 0;
}
private static boolean equals(int[] a, int[] b, int n) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
private static final Pattern PAT_JAVA_VERSION = Pattern.compile("(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(_(?<update>\\d+))?(-(?<pre>[^-]+))?(-(?<build>.+))?");
// visible for testing
static int[] parseJavaVersion(String v) {
final Matcher m = PAT_JAVA_VERSION.matcher(v);
if (!m.matches())
throw new IllegalArgumentException("Could not parse version: " + v);
final int[] ver = new int[5];
ver[0] = toInt(m.group("major"));
ver[1] = toInt(m.group("minor"));
ver[2] = toInt(m.group("patch"));
ver[3] = toInt(m.group("update"));
final String pre = m.group("pre");
if (pre != null) {
if (pre.startsWith("rc"))
ver[4] = -1;
else if (pre.startsWith("beta"))
ver[4] = -2;
else if (pre.startsWith("ea"))
ver[4] = -3;
}
return ver;
}
// visible for testing
static String toJavaVersionString(int[] version) {
final StringBuilder sb = new StringBuilder();
sb.append(version[0]).append('.');
sb.append(version[1]).append('.');
sb.append(version[2]);
if (version.length > 3 && version[3] > 0)
sb.append('_').append(version[3]);
if (version.length > 4 && version[4] != 0) {
final String pre;
switch (version[4]) {
case -1:
pre = "rc";
break;
case -2:
pre = "beta";
break;
case -3:
pre = "ea";
break;
default:
pre = "?";
}
sb.append('-').append(pre);
}
return sb.toString();
}
private static int toInt(String s) {
return s != null ? Integer.parseInt(s) : 0;
}
private static int[] toInt(String[] ss) {
int[] res = new int[ss.length];
for (int i = 0; i < ss.length; i++)
res[i] = ss[i] != null ? Integer.parseInt(ss[i]) : 0;
return res;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="String Expansion">
/////////// String Expansion ///////////////////////////////////
private List<String> expand(List<String> strs) {
if (strs == null)
return null;
final List<String> res = new ArrayList<String>(strs.size());
for (String s : strs)
res.add(expand(s));
return res;
}
private String expand(String str) {
if (appCache != null)
str = str.replaceAll("\\$" + VAR_CAPSULE_DIR, appCache.toAbsolutePath().toString());
else if (str.contains("$" + VAR_CAPSULE_DIR))
throw new IllegalStateException("The $" + VAR_CAPSULE_DIR + " variable cannot be expanded when the "
+ ATTR_EXTRACT + " attribute is set to false");
str = expandCommandLinePath(str);
str = str.replaceAll("\\$" + VAR_CAPSULE_JAR, getJarPath());
str = str.replaceAll("\\$" + VAR_JAVA_HOME, javaHome != null ? javaHome : System.getProperty(PROP_JAVA_HOME));
str = str.replace('/', FILE_SEPARATOR.charAt(0));
return str;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="String Utils">
/////////// String Utils ///////////////////////////////////
private static List<String> split(String str, String separator) {
if (str == null)
return null;
String[] es = str.split(separator);
final List<String> list = new ArrayList<>(es.length);
for (String e : es) {
e = e.trim();
if (!e.isEmpty())
list.add(e);
}
return list;
}
private static Map<String, String> mapSplit(String map, char kvSeparator, String separator, String defaultValue) {
if (map == null)
return null;
Map<String, String> m = new HashMap<>();
for (String entry : split(map, separator)) {
final String key = getBefore(entry, kvSeparator);
String value = getAfter(entry, kvSeparator);
if (value == null) {
if (defaultValue != null)
value = defaultValue;
else
throw new IllegalArgumentException("Element " + entry + " in \"" + map + "\" is not a key-value entry separated with " + kvSeparator + " and no default value provided");
}
m.put(key.trim(), value.trim());
}
return m;
}
private static String join(Collection<?> coll, String separator) {
if (coll == null)
return null;
StringBuilder sb = new StringBuilder();
for (Object e : coll) {
if (e != null)
sb.append(e).append(separator);
}
sb.delete(sb.length() - separator.length(), sb.length());
return sb.toString();
}
// private static String globToRegex(String line) {
// line = line.trim();
// int strLen = line.length();
// StringBuilder sb = new StringBuilder(strLen);
// // Remove beginning and ending * globs because they're useless
// if (line.startsWith("*")) {
// line = line.substring(1);
// strLen--;
// if (line.endsWith("*")) {
// line = line.substring(0, strLen - 1);
// strLen--;
// boolean escaping = false;
// int inCurlies = 0;
// for (char currentChar : line.toCharArray()) {
// switch (currentChar) {
// case '*':
// if (escaping)
// sb.append("\\*");
// else
// sb.append(".*");
// escaping = false;
// break;
// case '?':
// if (escaping)
// sb.append("\\?");
// else
// sb.append('.');
// escaping = false;
// break;
// case '.':
// case '(':
// case ')':
// case '+':
// case '|':
// case '^':
// case '$':
// case '@':
// case '%':
// sb.append('\\');
// sb.append(currentChar);
// escaping = false;
// break;
// case '\\':
// if (escaping) {
// sb.append("\\\\");
// escaping = false;
// } else
// escaping = true;
// break;
// case '{':
// if (escaping)
// sb.append("\\{");
// else {
// sb.append('(');
// inCurlies++;
// escaping = false;
// break;
// case '}':
// if (inCurlies > 0 && !escaping) {
// sb.append(')');
// inCurlies--;
// } else if (escaping)
// sb.append("\\}");
// else
// sb.append("}");
// escaping = false;
// break;
// case ',':
// if (inCurlies > 0 && !escaping)
// sb.append('|');
// else if (escaping)
// sb.append("\\,");
// else
// sb.append(",");
// break;
// default:
// escaping = false;
// sb.append(currentChar);
// return sb.toString();
private static String getBefore(String s, char separator) {
final int i = s.indexOf(separator);
if (i < 0)
return s;
return s.substring(0, i);
}
private static String getAfter(String s, char separator) {
final int i = s.indexOf(separator);
if (i < 0)
return null;
return s.substring(i + 1);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Collection Utils">
/////////// Collection Utils ///////////////////////////////////
private static <T> List<T> nullToEmpty(List<T> list) {
if (list == null)
return Collections.emptyList();
return list;
}
private static <K, V> Map<K, V> nullToEmpty(Map<K, V> map) {
if (map == null)
return Collections.emptyMap();
return map;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Logging">
/////////// Logging ///////////////////////////////////
private static void println(String str) {
System.err.println("CAPSULE: " + str);
}
private static void verbose(String str) {
if (verbose)
System.err.println("CAPSULE: " + str);
}
private static void debug(String str) {
if (debug)
System.err.println("CAPSULE: " + str);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Pipe Streams (workaround for inheritIO bug)">
/////////// Pipe Streams (workaround for inheritIO bug) ///////////////////////////////////
private static boolean isInheritIoBug() {
return isWindows() && compareVersions(System.getProperty(PROP_JAVA_VERSION), "1.8.0") < 0;
}
private void pipeIoStreams() {
new Thread(this, "pipe-out").start();
new Thread(this, "pipe-err").start();
new Thread(this, "pipe-in").start();
}
@Override
public final void run() {
if (isInheritIoBug()) {
switch (Thread.currentThread().getName()) {
case "pipe-out":
pipe(child.getInputStream(), System.out);
return;
case "pipe-err":
pipe(child.getErrorStream(), System.err);
return;
case "pipe-in":
pipe(System.in, child.getOutputStream());
return;
default: // shutdown hook
}
}
if (child != null)
child.destroy();
}
private static void pipe(InputStream in, OutputStream out) {
try {
int read;
byte[] buf = new byte[1024];
while (-1 != (read = in.read(buf))) {
out.write(buf, 0, read);
out.flush();
}
} catch (IOException e) {
if (verbose)
e.printStackTrace(System.err);
} finally {
try {
out.close();
} catch (IOException e2) {
if (verbose)
e2.printStackTrace(System.err);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="File Visitor">
/////////// File Visitor ///////////////////////////////////
/*
* This is written in a funny way because we don't want to create any classes, even anonymous ones, so that this file will compile
* to a single class file.
*/
private final Object fileVisitorLock = new Object();
private int fileVisitorMode;
private Path fileVisitorStart;
private List<Path> fileVisitorResult;
private static final int FILE_VISITOR_MODE_NO_RECURSE = 0;
private static final int FILE_VISITOR_MODE_PREORDER = 1;
private static final int FILE_VISITOR_MODE_POSTORDER = 2;
protected final List<Path> listDir(Path dir) {
return listDir(dir, FILE_VISITOR_MODE_NO_RECURSE);
}
protected final List<Path> listDir(Path dir, int fileVisitorMode) {
synchronized (fileVisitorLock) {
this.fileVisitorMode = fileVisitorMode;
List<Path> res = new ArrayList<>();
this.fileVisitorStart = dir;
this.fileVisitorResult = res;
try {
Files.walkFileTree(dir, this);
return res;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
this.fileVisitorStart = null;
this.fileVisitorResult = null;
this.fileVisitorMode = -1;
}
}
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (fileVisitorStart.equals(dir))
return FileVisitResult.CONTINUE;
if (fileVisitorMode == FILE_VISITOR_MODE_PREORDER)
fileVisitorResult.add(dir);
else if (fileVisitorMode == FILE_VISITOR_MODE_NO_RECURSE) {
fileVisitorResult.add(dir);
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null)
throw exc;
if (fileVisitorMode == FILE_VISITOR_MODE_POSTORDER)
fileVisitorResult.add(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
fileVisitorResult.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
throw exc;
}
//</editor-fold>
}
|
package org.glob3.mobile.specific;
import org.glob3.mobile.generated.IImage;
import org.glob3.mobile.generated.Vector2I;
import android.graphics.Bitmap;
public final class Image_Android
extends
IImage {
// private static String createCallStackString() {
// final Exception e = new Exception();
// final StringWriter wr = new StringWriter();
// final PrintWriter err = new PrintWriter(wr);
// e.printStackTrace(err);
// err.flush();
// return wr.toString() //
// .replace("org.glob3.mobile.specific.", "") //
// .replace("org.glob3.mobile.generated.", "") //
// .replace("android.opengl.", "") //
// .replace("at", "") //
// .replace("java.lang.Exception\n", "");
private static class BitmapHolder {
private Bitmap _bitmap;
private int _referencesCount;
// private final String _createdAt;
// private final List<String> _retainedAt = new ArrayList<String>();
// private final List<String> _releasedAt = new ArrayList<String>();
private BitmapHolder(final Bitmap bitmap) {
_bitmap = bitmap;
_referencesCount = 1;
// _createdAt = createCallStackString();
}
private void _retain() {
synchronized (this) {
_referencesCount++;
// _retainedAt.add(createCallStackString());
}
}
private void _release() {
synchronized (this) {
_referencesCount
if (_referencesCount == 0) {
_bitmap.recycle();
_bitmap = null;
}
// _releasedAt.add(createCallStackString());
}
}
// @Override
// protected void finalize() throws Throwable {
// if (_referencesCount != 0) {
// synchronized (ILogger.instance()) {
// final StringBuffer msg = new StringBuffer();
// msg.append("Created At:\n");
// msg.append(_createdAt);
// msg.append("Retained At:\n");
// for (final String e : _retainedAt) {
// msg.append(e);
// msg.append("Released At:\n");
// for (final String e : _releasedAt) {
// msg.append(e);
// ILogger.instance().logError(msg.toString());
// super.finalize();
}
final private BitmapHolder _bitmapHolder;
private byte[] _source;
// private boolean _bitmapHolderReleased = false;
// private final String _createdAt;
Image_Android(final Bitmap bitmap,
final byte[] source) {
// _createdAt = createCallStackString();
if (bitmap == null) {
throw new RuntimeException("Can't create an Image_Android with a null bitmap");
}
_bitmapHolder = new BitmapHolder(bitmap);
_source = source;
}
private Image_Android(final BitmapHolder bitmapHolder,
final byte[] source) {
// _createdAt = createCallStackString();
if (bitmapHolder == null) {
throw new RuntimeException("Can't create an Image_Android with a null bitmap");
}
bitmapHolder._retain();
_bitmapHolder = bitmapHolder;
_source = source;
}
public Bitmap getBitmap() {
return _bitmapHolder._bitmap;
}
@Override
public int getWidth() {
return (_bitmapHolder._bitmap == null) ? 0 : _bitmapHolder._bitmap.getWidth();
}
@Override
public int getHeight() {
return (_bitmapHolder._bitmap == null) ? 0 : _bitmapHolder._bitmap.getHeight();
}
@Override
public Vector2I getExtent() {
return new Vector2I(getWidth(), getHeight());
}
@Override
public String description() {
return "Image_Android " + getWidth() + " x " + getHeight() + ", _image=(" + _bitmapHolder._bitmap.describeContents() + ")";
}
public byte[] getSourceBuffer() {
return _source;
}
public void releaseSourceBuffer() {
_source = null;
}
@Override
public Image_Android shallowCopy() {
return new Image_Android(_bitmapHolder, _source);
}
@Override
public void dispose() {
synchronized (this) {
// _bitmapHolderReleased = true;
_bitmapHolder._release();
}
super.dispose();
}
// @Override
// protected void finalize() throws Throwable {
// if (!_bitmapHolderReleased) {
// synchronized (ILogger.instance()) {
// final StringBuffer msg = new StringBuffer();
// msg.append("Image_Android finalized without releasing the _bitmapHolder created at: \n");
// msg.append(_createdAt);
// ILogger.instance().logError(msg.toString());
// super.finalize();
}
|
package org.usfirst.frc4915.ArcadeDriveRobot;
public class Version {
private static final String VERSION = "v4.9.15-competition code";
// Should be ready for practice
// Implements safety changes
// --Safety enabled for both Harvester a:nd launcher motors
// --Removed delay on drive straight command
// --Added debug info for the WindingMotor's Safety
// Adds default behaviors for Winding and Harvester motors.
public static String getVersion() {
return VERSION;
}
}
|
package com.rehivetech.beeeon.menu;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.rehivetech.beeeon.Constants;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.activity.AdapterUsersActivity;
import com.rehivetech.beeeon.activity.MainActivity;
import com.rehivetech.beeeon.activity.SettingsMainActivity;
import com.rehivetech.beeeon.activity.dialog.InfoDialogFragment;
import com.rehivetech.beeeon.activity.menuItem.AdapterMenuItem;
import com.rehivetech.beeeon.activity.menuItem.EmptyMenuItem;
import com.rehivetech.beeeon.activity.menuItem.GroupMenuItem;
import com.rehivetech.beeeon.activity.menuItem.LocationMenuItem;
import com.rehivetech.beeeon.activity.menuItem.MenuItem;
import com.rehivetech.beeeon.activity.menuItem.ProfileMenuItem;
import com.rehivetech.beeeon.activity.menuItem.SeparatorMenuItem;
import com.rehivetech.beeeon.activity.menuItem.SettingMenuItem;
import com.rehivetech.beeeon.adapter.Adapter;
import com.rehivetech.beeeon.arrayadapter.MenuListAdapter;
import com.rehivetech.beeeon.asynctask.CallbackTask.CallbackTaskListener;
import com.rehivetech.beeeon.asynctask.SwitchAdapterTask;
import com.rehivetech.beeeon.asynctask.UnregisterAdapterTask;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.household.User;
import com.rehivetech.beeeon.persistence.Persistence;
import com.rehivetech.beeeon.util.Log;
import java.util.List;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
import static android.support.v7.view.ActionMode.*;
public class NavDrawerMenu {
private static final String TAG = "NavDrawerMenu";
private final static String TAG_INFO = "tag_info";
public static final String FRG_TAG_PRO = "PRO";
private final Toolbar mToolbar;
private MainActivity mActivity;
private Controller mController;
private DrawerLayout mDrawerLayout;
private StickyListHeadersListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String mDrawerTitle = "BeeeOn";
private String mActiveItem;
private String mActiveAdapterId;
private String mAdaterIdUnregist;
private boolean mIsDrawerOpen;
private boolean backPressed = false;
private SwitchAdapterTask mSwitchAdapterTask;
private UnregisterAdapterTask mUnregisterAdapterTask;
private MenuListAdapter mMenuAdapter;
private ActionMode mMode;
private MenuItem mSelectedMenuItem;
private RelativeLayout mDrawerRelLay;
public NavDrawerMenu(MainActivity activity, Toolbar toolbar) {
// Set activity
mActivity = activity;
mToolbar = toolbar;
backPressed = mActivity.getBackPressed();
// Get controller
mController = Controller.getInstance(mActivity);
// Get GUI element for menu
getGUIElements();
// Set all of listener for (listview) menu items
settingsMenu();
}
private void getGUIElements() {
// Locate DrawerLayout in activity_location_screen.xml
mDrawerLayout = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout);
// Locate ListView in activity_location_screen.xml
mDrawerList = (StickyListHeadersListView) mActivity.findViewById(R.id.listview_drawer);
// Locate relative layout
mDrawerRelLay = (RelativeLayout) mActivity.findViewById(R.id.relative_layout_drawer);
}
private void settingsMenu() {
mDrawerLayout.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
backPressed = ((MainActivity) mActivity).getBackPressed();
Log.d(TAG, "BackPressed = " + String.valueOf(backPressed));
if (mDrawerLayout == null) {
return false;
}
if (mDrawerLayout.isDrawerOpen(mDrawerRelLay) && !backPressed) {
firstTapBack();
return true;
} else if (mDrawerLayout.isDrawerOpen(mDrawerRelLay) && backPressed) {
secondTapBack();
return true;
}
}
return false;
}
});
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedMenuItem = (MenuItem) mMenuAdapter.getItem(position);
Adapter adapter = mController.getActiveAdapter();
switch (mSelectedMenuItem.getType()) {
case ADAPTER:
if(adapter == null)
break;
// if it is not chosen, switch to selected adapter
if (!adapter.getId().equals(mSelectedMenuItem.getId())) {
doSwitchAdapterTask(mSelectedMenuItem.getId());
}
break;
case LOCATION:
// Get the title followed by the position
if (adapter != null) {
changeMenuItem(mSelectedMenuItem.getId(), true);
redrawMenu();
}
break;
case SETTING:
if (mSelectedMenuItem.getId().equals(com.rehivetech.beeeon.activity.menuItem.MenuItem.ID_ABOUT)) {
InfoDialogFragment dialog = new InfoDialogFragment();
dialog.show(mActivity.getSupportFragmentManager(), TAG_INFO);
} else if (mSelectedMenuItem.getId().equals(com.rehivetech.beeeon.activity.menuItem.MenuItem.ID_SETTINGS)) {
Intent intent = new Intent(mActivity, SettingsMainActivity.class);
mActivity.startActivity(intent);
} else if (mSelectedMenuItem.getId().equals(MenuItem.ID_LOGOUT)) {
mActivity.logout();
}
break;
default:
Log.d(TAG,"other");
break;
}
}
});
mDrawerList.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mMode != null) {
// Action Mode is active and I want change
mSelectedMenuItem.setNotSelected();
mMode = null;
}
Log.d(TAG, "Item Long press");
mSelectedMenuItem = (MenuItem) mMenuAdapter.getItem(position);
switch (mSelectedMenuItem.getType()) {
case LOCATION:
break;
case ADAPTER:
Log.i(TAG, "Long press - adapter");
mMode = mActivity.startSupportActionMode(new ActionModeAdapters());
mSelectedMenuItem.setIsSelected();
break;
default:
// do nothing
break;
}
return true;
}
});
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(mActivity,mDrawerLayout,mToolbar,R.string.drawer_open,R.string.drawer_close) {
public void onDrawerClosed(View view) {
backPressed = mActivity.getBackPressed();
if (backPressed)
mActivity.onBackPressed();
// Set the title on the action when drawer closed
Adapter adapter = mController.getActiveAdapter();
if (adapter != null && mActiveItem != null) {
if(mActiveItem.equals(Constants.GUI_MENU_CONTROL)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_control));
}
else if (mActiveItem.equals(Constants.GUI_MENU_DASHBOARD)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_dashboard));
}
else if(mActiveItem.equals(Constants.GUI_MENU_WATCHDOG)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_watchdog));
}
else if(mActiveItem.equals(Constants.GUI_MENU_PROFILE)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_profile));
}
} else {
setDefaultTitle();
}
super.onDrawerClosed(view);
Log.d(TAG, "BackPressed - onDrawerClosed " + String.valueOf(backPressed));
mIsDrawerOpen = false;
finishActinMode();
}
public void onDrawerOpened(View drawerView) {
// Set the title on the action when drawer open
mActivity.getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
mIsDrawerOpen = true;
// backPressed = true;
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mActivity.setSupportProgressBarIndeterminateVisibility(false);
openMenu();
}
public void openMenu() {
mIsDrawerOpen = true;
mDrawerLayout.openDrawer(mDrawerRelLay);
}
public void closeMenu() {
mIsDrawerOpen = false;
mDrawerLayout.closeDrawer(mDrawerRelLay);
if (mMode != null) {
mMode.finish();
}
}
public void redrawMenu() {
mMenuAdapter = getMenuAdapter();
mDrawerList.setAdapter(mMenuAdapter);
Adapter adapter = mController.getActiveAdapter();
if (adapter != null && mActiveItem !=null ) {
if(mActiveItem.equals(Constants.GUI_MENU_CONTROL)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_control));
}
else if (mActiveItem.equals(Constants.GUI_MENU_DASHBOARD)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_dashboard));
}
else if(mActiveItem.equals(Constants.GUI_MENU_WATCHDOG)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_watchdog));
}
else if(mActiveItem.equals(Constants.GUI_MENU_PROFILE)) {
mActivity.getSupportActionBar().setTitle(mActivity.getString(R.string.menu_profile));
}
} else {
setDefaultTitle();
}
if (!mIsDrawerOpen) {
// Close drawer
closeMenu();
Log.d(TAG, "LifeCycle: onOrientation");
}
}
private void changeMenuItem(String ID, boolean closeDrawer) {
mActiveItem = ID;
// TODO
mActivity.setActiveAdapterID(mActiveAdapterId);
mActivity.setActiveMenuID(mActiveItem);
mActivity.redrawMainFragment();
// Close drawer
if (closeDrawer) {
closeMenu();
}
}
private void doSwitchAdapterTask(String adapterId) {
mSwitchAdapterTask = new SwitchAdapterTask(mActivity, false);
mSwitchAdapterTask.setListener(new CallbackTaskListener() {
@Override
public void onExecute(boolean success) {
if (success) {
mActivity.setActiveAdapterAndMenu();
mActivity.redrawMainFragment();
redrawMenu();
}
mActivity.setSupportProgressBarIndeterminateVisibility(false);
}
});
mActivity.setSupportProgressBarIndeterminateVisibility(true);
mSwitchAdapterTask.execute(adapterId);
}
private void doUnregisterAdapterTask(String adapterId) {
mUnregisterAdapterTask = new UnregisterAdapterTask(mActivity);
mUnregisterAdapterTask.setListener(new CallbackTaskListener() {
@Override
public void onExecute(boolean success) {
if (success) {
Toast.makeText(mActivity, R.string.toast_adapter_removed, Toast.LENGTH_LONG).show();
mActivity.setActiveAdapterAndMenu();
mActivity.redraw();
}
mActivity.setSupportProgressBarIndeterminateVisibility(false);
}
});
mActivity.setSupportProgressBarIndeterminateVisibility(true);
mUnregisterAdapterTask.execute(adapterId);
}
public MenuListAdapter getMenuAdapter() {
mMenuAdapter = new MenuListAdapter(mActivity);
// Adding profile header
User actUser = mController.getActualUser();
Bitmap picture = actUser.getPicture();
if (picture == null)
picture = actUser.getDefaultPicture(mActivity);
mMenuAdapter.addHeader(new ProfileMenuItem(actUser.getFullName(), actUser.getEmail(), picture, new OnClickListener() {
@Override
public void onClick(View v) {
changeMenuItem(Constants.GUI_MENU_PROFILE,true);
}
}));
List<Adapter> adapters = mController.getAdapters();
// Adding separator as item (we don't want to let it float as header)
mMenuAdapter.addItem(new SeparatorMenuItem());
mMenuAdapter.addHeader(new GroupMenuItem(mActivity.getResources().getString(R.string.adapter)));
if (!adapters.isEmpty()) {
Adapter activeAdapter = mController.getActiveAdapter();
if(activeAdapter == null)
return mMenuAdapter;
// Adding adapters
for (Adapter actAdapter : adapters) {
mMenuAdapter.addItem(new AdapterMenuItem(actAdapter.getName(), actAdapter.getRole().name(), activeAdapter.getId().equals(actAdapter.getId()), actAdapter.getId()));
}
// Adding separator as item (we don't want to let it float as header)
mMenuAdapter.addItem(new SeparatorMenuItem());
// MANAGMENT
mMenuAdapter.addHeader(new GroupMenuItem(mActivity.getResources().getString(R.string.menu_managment)));
mMenuAdapter.addItem(new LocationMenuItem(mActivity.getString(R.string.menu_control), R.drawable.ic_overview, false, Constants.GUI_MENU_CONTROL, (mActiveItem != null)? mActiveItem.equals(Constants.GUI_MENU_CONTROL):true));
mMenuAdapter.addItem(new LocationMenuItem(mActivity.getString(R.string.menu_dashboard),R.drawable.ic_dashboard,false,Constants.GUI_MENU_DASHBOARD,(mActiveItem != null)? mActiveItem.equals(Constants.GUI_MENU_DASHBOARD):false));
mMenuAdapter.addItem( new SeparatorMenuItem());
// APPLICATIONS
mMenuAdapter.addHeader(new GroupMenuItem(mActivity.getResources().getString(R.string.menu_applications)));
mMenuAdapter.addItem(new LocationMenuItem(mActivity.getString(R.string.menu_watchdog), R.drawable.ic_app_watchdog, false, Constants.GUI_MENU_WATCHDOG, (mActiveItem != null)?mActiveItem.equals(Constants.GUI_MENU_WATCHDOG):false));
} else {
mMenuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_adapters)));
}
// Adding separator as header
mMenuAdapter.addItem(new SeparatorMenuItem());
// Adding settings, about etc.
mMenuAdapter.addItem(new SettingMenuItem(mActivity.getResources().getString(R.string.action_settings), R.drawable.settings, com.rehivetech.beeeon.activity.menuItem.MenuItem.ID_SETTINGS));
mMenuAdapter.addItem(new SettingMenuItem(mActivity.getResources().getString(R.string.action_about), R.drawable.info, com.rehivetech.beeeon.activity.menuItem.MenuItem.ID_ABOUT));
mMenuAdapter.addItem(new SettingMenuItem(mActivity.getString(R.string.action_logout), R.drawable.logout,MenuItem.ID_LOGOUT));
return mMenuAdapter;
}
public void clickOnHome() {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
closeMenu();
} else {
openMenu();
}
}
/**
* Handling first tap back button
*/
public void firstTapBack() {
Log.d(TAG, "firtstTap");
Toast.makeText(mActivity, mActivity.getString(R.string.toast_tap_again_exit), Toast.LENGTH_SHORT).show();
// backPressed = true;
((MainActivity) mActivity).setBackPressed(true);
openMenu();
}
/**
* Handling second tap back button - exiting
*/
public void secondTapBack() {
Log.d(TAG, "secondTap");
mActivity.finish();
}
public void onConfigurationChanged(Configuration newConfig) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setDefaultTitle() {
mDrawerTitle = "BeeeOn";
}
public void setIsDrawerOpen(boolean value) {
mIsDrawerOpen = value;
}
public boolean getIsDrawerOpen() {
return mIsDrawerOpen;
}
public void setActiveMenuID(String id) {
mActiveItem = id;
}
public void setAdapterID(String adaID) {
mActiveAdapterId = adaID;
}
public void cancelAllTasks() {
if (mSwitchAdapterTask != null) {
mSwitchAdapterTask.cancel(true);
}
if (mUnregisterAdapterTask != null) {
mUnregisterAdapterTask.cancel(true);
}
}
class ActionModeAdapters implements Callback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.adapter_menu, menu);
if(!mController.isUserAllowed(mController.getAdapter(mSelectedMenuItem.getId()).getRole()) ) {
menu.getItem(0).setVisible(false);// EDIT
menu.getItem(1).setVisible(false);// USERS
}
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
Log.d(TAG,"ActionMode Adapter - item id: "+ item.getItemId());
if (item.getItemId() == R.id.ada_menu_del) { // UNREGIST ADAPTER
doUnregisterAdapterTask(mSelectedMenuItem.getId());
} else if (item.getItemId() == R.id.ada_menu_users) { // GO TO USERS OF ADAPTER
Intent intent = new Intent(mActivity, AdapterUsersActivity.class);
intent.putExtra(Constants.GUI_SELECTED_ADAPTER_ID, mSelectedMenuItem.getId());
mActivity.startActivity(intent);
} else if (item.getItemId() == R.id.ada_menu_edit) { // RENAME ADAPTER
Toast.makeText(mActivity, R.string.toast_not_implemented, Toast.LENGTH_LONG).show();
}
mode.finish();
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mMode = null;
mSelectedMenuItem.setNotSelected();
}
}
public void finishActinMode() {
Log.d(TAG, "Close action mode");
if (mMode != null)
mMode.finish();
}
}
|
package org.glob3.mobile.generated;
// CartoCSSLexer.cpp
// G3MiOSSDK
// CartoCSSLexer.hpp
// G3MiOSSDK
//class IStringUtils;
//class CartoCSSToken;
public class CartoCSSLexer
{
private final String _source;
private final int _sourceSize;
private int _cursor;
private CartoCSSToken _lastToken;
// bool _returnPreviousToken;
private final IStringUtils _su;
private boolean skipComments()
{
if (_cursor < _sourceSize-1)
{
final char c = _source.charAt(_cursor);
final char nextC = _source.charAt(_cursor+1);
if (c == '/')
{
if (nextC == '/')
{
final int eolPosition = _su.indexOf(_source, "\n", _cursor+2);
_cursor = (eolPosition < 0) ? _sourceSize : eolPosition + 1;
return true;
}
else if (nextC == '*')
{
final int eocPosition = _su.indexOf(_source, "*/", _cursor+2);
_cursor = (eocPosition < 0) ? _sourceSize : eocPosition + 3;
return true;
}
}
}
return false;
}
private boolean skipBlanks()
{
final int cursor = _su.indexOfFirstNonBlank(_source, _cursor);
if (cursor < 0)
{
_cursor = _sourceSize;
return false;
}
final boolean changedCursor = (cursor != _cursor);
if (changedCursor)
{
_cursor = cursor;
}
return changedCursor;
}
private void skipCommentsAndBlanks()
{
boolean skipedBlanks;
boolean skipedCommment;
do
{
skipedBlanks = skipBlanks();
skipedCommment = skipComments();
}
while (skipedBlanks || skipedCommment);
}
private CartoCSSLexer(String source)
// _previousToken(NULL),
// _returnPreviousToken(false),
{
_source = source;
_sourceSize = source.length();
_cursor = 0;
_su = IStringUtils.instance();
_lastToken = null;
}
// void revert() {
// _returnPreviousToken = true;
private CartoCSSToken getNextToken()
{
// if (_returnPreviousToken) {
// _returnPreviousToken = false;
// return _previousToken;
skipCommentsAndBlanks();
if (_cursor >= _sourceSize)
{
return null;
}
CartoCSSToken token;
final char c = _source.charAt(_cursor);
switch (c)
{
case '{':
{
token = new OpenBraceCartoCSSToken(_cursor);
_cursor++;
break;
}
case '}':
{
token = new CloseBraceCartoCSSToken(_cursor);
_cursor++;
break;
}
case ':':
{
if ((_cursor + 1 < _sourceSize) && (_source.charAt(_cursor + 1) == ':'))
{
token = new StringCartoCSSToken("::", _cursor);
_cursor += 2;
}
else
{
token = new ColonCartoCSSToken(_cursor);
_cursor++;
}
break;
}
case ';':
{
token = new SemicolonCartoCSSToken(_cursor);
_cursor++;
break;
}
case '[':
{
final int closeBraquetPosition = _su.indexOf(_source, "]", _cursor+1);
if (closeBraquetPosition < 0)
{
token = new ErrorCartoCSSToken("Unbalanced braquet", _cursor);
}
else
{
token = new ExpressionCartoCSSToken(_su.substring(_source, _cursor+1, closeBraquetPosition), _cursor);
_cursor = closeBraquetPosition+1;
}
break;
}
default:
{
final int cursor = _su.indexOfFirstNonChar(_source, "{}:;[]\n\r", _cursor);
if (cursor < 0)
{
token = new ErrorCartoCSSToken("Unknown token", _cursor);
}
else
{
final String str = _su.substring(_source, _cursor, cursor);
if ((_lastToken != null) && (_lastToken._type == CartoCSSTokenType.STRING))
{
((StringCartoCSSToken) _lastToken).appendString(str);
token = new SkipCartoCSSToken(_cursor);
}
else
{
token = new StringCartoCSSToken(str, _cursor);
}
_cursor = cursor;
}
break;
}
}
// h [0-9a-f]
// unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])?
// escape {unicode}|\\[^\r\n\f0-9a-f]
// nonascii [\240-\377]
// nmchar [_a-z0-9-]|{nonascii}|{escape}
// name {nmchar}+
// _previousToken = token;
_lastToken = token;
return token;
}
public static java.util.ArrayList<CartoCSSToken> tokenize(String source)
{
CartoCSSLexer lexer = new CartoCSSLexer(source);
final java.util.ArrayList<CartoCSSToken> result = new java.util.ArrayList<CartoCSSToken>();
boolean finish = false;
while (!finish)
{
final CartoCSSToken token = lexer.getNextToken();
if (token == null)
{
finish = true;
}
else
{
if (token._type == CartoCSSTokenType.ERROR)
{
finish = true;
}
if (token._type == CartoCSSTokenType.SKIP)
{
if (token != null)
token.dispose();
}
else
{
result.add(token);
}
}
}
return result;
}
}
|
package info.justaway.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import java.util.ArrayList;
import info.justaway.JustawayApplication;
import info.justaway.ScaleImageActivity;
import info.justaway.VideoActivity;
import info.justaway.display.FadeInRoundedBitmapDisplayer;
import info.justaway.settings.BasicSettings;
import twitter4j.Status;
public class ImageUtil {
private static DisplayImageOptions sRoundedDisplayImageOptions;
public static void init() {
DisplayImageOptions defaultOptions = new DisplayImageOptions
.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(JustawayApplication.getApplication())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public static void displayImage(String url, ImageView view) {
String tag = (String) view.getTag();
if (tag != null && tag.equals(url)) {
return;
}
view.setTag(url);
ImageLoader.getInstance().displayImage(url, view);
}
public static void displayImageForCrop(String url, ImageView view, final Context context) {
String tag = (String) view.getTag();
if (tag != null && tag.equals(url)) {
return;
}
view.setTag(url);
ImageLoadingListener listener = new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap image) {
ImageView imageView = (ImageView) view;
if (imageView != null) {
// CROP
float w = image.getWidth();
float h = image.getHeight();
if (h > 0 && h / w > 3.9f / 3.0f) {
// Bitmap
Bitmap resized = Bitmap.createBitmap(image, 0, 0, (int)w, (int)(h * 0.6f));
imageView.setImageBitmap(resized);
}
}
}
};
ImageLoader.getInstance().displayImage(url, view, listener);
}
public static void displayImage(String url, ImageView view, boolean cropByAspect) {
String tag = (String) view.getTag();
if (tag != null && tag.equals(url)) {
return;
}
view.setTag(url);
ImageLoadingListener listener = new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
ImageView imageView = (ImageView) view;
float w = loadedImage.getWidth();
float h = loadedImage.getHeight();
if (h > 0 && w/h > 3.9f/3.0f) {
imageView.setAdjustViewBounds(false);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
}
};
ImageLoader.getInstance().displayImage(url, view, cropByAspect ? listener : null);
}
public static void displayRoundedImage(String url, ImageView view) {
String tag = (String) view.getTag();
if (tag != null && tag.equals(url)) {
return;
}
view.setTag(url);
if (BasicSettings.getUserIconRoundedOn()) {
if (sRoundedDisplayImageOptions == null) {
sRoundedDisplayImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.resetViewBeforeLoading(true)
.displayer(new FadeInRoundedBitmapDisplayer(15))
.build();
}
ImageLoader.getInstance().displayImage(url, view, sRoundedDisplayImageOptions);
} else {
ImageLoader.getInstance().displayImage(url, view);
}
}
/**
*
*
* @param context Activity
* @param viewGroup View
* @param status
*/
public static void displayThumbnailImages(final Context context, ViewGroup viewGroup, ViewGroup wrapperViewGroup, TextView play, final Status status) {
// URL
final String videoUrl = StatusUtil.getVideoUrl(status);
// URL
ArrayList<String> imageUrls = StatusUtil.getImageUrls(status);
if (imageUrls.size() > 0) {
viewGroup.setVisibility(View.INVISIBLE);
wrapperViewGroup.setVisibility(View.INVISIBLE);
boolean viaGranblueFantasy = StatusUtil.viaGranblueFantasy(status);
int imageHeight = viaGranblueFantasy ? 300 : 400;
viewGroup.removeAllViews();
int index = 0;
for (final String url : imageUrls) {
RoundedImageView image = new RoundedImageView(context);
image.setMinimumHeight(150);
image.setCornerRadius(25.0f);
image.setBorderWidth(2.0f);
image.setBorderColor(Color.DKGRAY);
LinearLayout.LayoutParams layoutParams =
new LinearLayout.LayoutParams(0, imageHeight, 1.0f);
if (imageUrls.size() == 1) {
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
} else {
if (index == 0) {
layoutParams.setMargins(0, 0, 5, 0);
} else if (index == imageUrls.size() - 1) {
layoutParams.setMargins(5, 0, 0, 0);
} else {
layoutParams.setMargins(5, 0, 5, 0);
}
}
boolean fitByAspect = false;
if (imageUrls.size() > 3) {
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
image.setMaxHeight(imageHeight);
image.setAdjustViewBounds(true);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
layoutParams.gravity = Gravity.CENTER_VERTICAL;
fitByAspect = true;
} else {
if (viaGranblueFantasy) {
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
} else {
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
}
if (imageUrls.size() == 1) {
Space space = new Space(context);
LinearLayout.LayoutParams dummyParams =
new LinearLayout.LayoutParams(20, imageHeight, 0.15f);
viewGroup.addView(image, layoutParams);
viewGroup.addView(space, dummyParams);
} else {
viewGroup.addView(image, layoutParams);
}
if (image.getScaleType() == ImageView.ScaleType.CENTER_CROP) {
displayImageForCrop(url, image, context);
} else {
displayImage(url, image, fitByAspect);
}
if (videoUrl.isEmpty()) {
final int openIndex = index;
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ScaleImageActivity.class);
intent.putExtra("status", status);
intent.putExtra("index", openIndex);
context.startActivity(intent);
}
});
} else {
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), VideoActivity.class);
intent.putExtra("videoUrl", videoUrl);
context.startActivity(intent);
}
});
}
index++;
}
viewGroup.setVisibility(View.VISIBLE);
wrapperViewGroup.setVisibility(View.VISIBLE);
} else {
viewGroup.setVisibility(View.GONE);
wrapperViewGroup.setVisibility(View.GONE);
}
play.setVisibility(videoUrl.isEmpty() ? View.GONE : View.VISIBLE);
}
private static int getDp(Context context, int sizeInDp) {
float scale = context.getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp * scale + 0.5f);
return dpAsPixels;
}
}
|
package makeconnections;
import java.awt.*;
import javax.swing.JComponent;
import javax.swing.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Patrick
*/
public class MakeConnections extends JPanel{
/**
* @param args the command line arguments
*/
public FindConnections fc = new FindConnections();
public static Scanner scan = new Scanner(System.in);
//create the connect 4 game board with 7 columns and 6 rows
public static int[][] board = new int[6][7];
public static boolean running = true;
public static void main(String[] args) {
//initiate the frame and draw the game board
drawBoard();
System.out.println("Welcome to MakeConnections!");
System.out.println("Use the numbers 0-6 to play a chip");
System.out.println("First to four wins!\n");
//print the game board
printBoard();
boolean player1 = true;
while(running){
//get player1 choice
int column = scan.nextInt();
scan.nextLine();
dropChip(player1, column);
player1 = !player1;
}
}
public static void drawBoard(){
//create the canvas
Canvas canv1 = new Canvas();
canv1.setSize(800,800);
canv1.setBackground(Color.BLUE);
Frame frame1 = new Frame();
frame1.add(canv1);
frame1.setLayout(new FlowLayout());
frame1.setSize(800,800);
frame1.setLocationRelativeTo(null);
//frame1.setVisible(true);
//set the mouse to the game board
//requestFocus();
}
public static void printBoard(){
System.out.println("0 1 2 3 4 5 6");
System.out.println("
for(int a = 0; a < 6; a++){
for(int b = 0; b < 7; b++){
System.out.print(board[a][b] + " ");
}
System.out.println("");
}
}
public static void dropChip(boolean player1, int column){
//Checking the height of the board and setting the first empty spot in the collumn to the player's number
for(int r = 5; r >= 0; r
if(board[r][column] == 0){
board[r][column] = (player1) ? 1 : 2;
r = 0;
checkBoard(player1);
}
}
if(running) {printBoard();}
}
public static void checkBoard(boolean player1){
int player = player1 ? 1 : 2;
//System.out.println("player: " + player);
//check vertical chips starting with a (vertical) 0
for(int a = 5; a > 2; a
for(int b = 0; b < 7; b++){
if(board[a][b] == player){
System.out.println("checking vertical board position: " + a + " " + b);
checkVertical(a, b, 0, player);
}
}
}
//check horizontal chips starting with a (vertical) 0
for(int a = 5; a >= 0; a
for(int b = 0; b < 4; b++){
if(board[a][b] == player){
System.out.println("checking horizontal board position: " + a + " " + b);
checkHorizontal(a, b, 0, player);
}
}
}
}
public static void checkVertical(int a, int b, int count, int player){
if(a >= 0){
if(board[a][b] == player){
count++;
if(count == 4){
printBoard();
System.out.println("Connection made! Player " + board[a][b] + " wins!");
running = false;
} else {
a
checkVertical(a, b, count, player);
}
}
} else if(a < 0){
System.out.println("No connection made " + b);
}
}
public static void checkHorizontal(int a, int b, int count, int player){
if(b < 7){
if(board[a][b] == player){
count++;
if(count == 4){
printBoard();
System.out.println("Connection made! Player " + board[a][b] + " wins!");
running = false;
} else {
b++;
checkHorizontal(a, b, count, player);
}
}
} else if(b > 7){
System.out.println("No horizontal connection made " + a);
}
}
private boolean updateBoard() {
repaint();
return true;
}
@Override
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.drawOval(5, 5, 10, 10);
}
}
|
package com.enigmabridge.create;
import com.enigmabridge.*;
import com.enigmabridge.comm.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class EBCreateUOCall extends EBAPICall implements EBResponseParser {
private static final Logger LOG = LoggerFactory.getLogger(EBCreateUOCall.class);
public static final String FIELD_DATA = "data";
protected EBCreateUORequest pkRequest;
protected EBCreateUOResponse pkResponse;
/**
* Separate abstract builder, chain from EBApiCall broken on purpose, restrict setters of this builder, e.g. callFunction.
* @param <T>
* @param <B>
*/
public static abstract class AbstractBuilder<T extends EBCreateUOCall, B extends EBCreateUOCall.AbstractBuilder> {
public B setEndpoint(EBEndpointInfo a) {
getObj().setEndpoint(a);
return getThisBuilder();
}
public B setSettings(EBConnectionSettings b) {
getObj().setSettings(b);
return getThisBuilder();
}
public B setSettings(EBSettings settings) {
if (settings.getApiKey() != null){
getObj().setApiKey(settings.getApiKey());
}
if (settings.getEndpointInfo() != null){
getObj().setEndpoint(settings.getEndpointInfo());
}
if (settings.getConnectionSettings() != null){
getObj().setSettings(settings.getConnectionSettings());
}
return getThisBuilder();
}
public B setApiKey(String apiKey){
getObj().setApiKey(apiKey);
return getThisBuilder();
}
public B setEngine(EBEngine engine){
getObj().setEngine(engine);
final EBSettings settings = engine == null ? null : engine.getDefaultSettings();
if (settings != null){
if (settings.getApiKey() != null && getObj().getApiKey() == null){
getObj().setApiKey(settings.getApiKey());
}
if (settings.getEndpointInfo() != null && getObj().getEndpoint() == null){
getObj().setEndpoint(settings.getEndpointInfo());
}
if(settings.getConnectionSettings() != null && getObj().getSettings() == null){
getObj().setSettings(settings.getConnectionSettings());
}
}
return getThisBuilder();
}
public B setNonce(byte[] nonce){
getObj().setNonce(nonce);
return getThisBuilder();
}
public abstract T build();
public abstract B getThisBuilder();
public abstract T getObj();
}
public static class Builder extends EBCreateUOCall.AbstractBuilder<EBCreateUOCall, EBCreateUOCall.Builder> {
private final EBCreateUOCall child = new EBCreateUOCall();
@Override
public EBCreateUOCall getObj() {
return child;
}
@Override
public EBCreateUOCall build() {
if (child.getApiKey() == null){
throw new NullPointerException("ApiKey is null");
}
if (child.getEndpoint() == null){
throw new NullPointerException("Endpoint info is null");
}
child.setCallFunction("CreateUserObject");
return child;
}
@Override
public EBCreateUOCall.Builder getThisBuilder() {
return this;
}
}
/**
* Builds request data.
*/
public void build(EBCreateUORequest request) throws IOException {
this.buildApiBlock(getApiKey(), (int) request.getObjectId());
// Build raw request.
rawRequest = new EBRawRequest();
if (settings != null) {
rawRequest.setMethod(settings.getMethod());
}
this.pkRequest = request;
// Build request - body.
final JSONObject jreq = new JSONObject();
final JSONObject jdat = new JSONObject();
jreq.put("data", jdat);
jdat.put("objectid", String.format("%08x", request.getObjectId()));
jdat.put("object", EBUtils.byte2hex(request.getObject()));
jdat.put("authorization", request.getAuthorization());
jdat.put("importkey", request.getImportKeyId());
jdat.put("contextparams", request.getContextparams());
// Build the rest of the request - headers.
rawRequest.setBody(jreq.toString());
rawRequest.setQuery(String.format("%s/%s/%s/%s",
this.apiVersion,
this.apiBlock,
this.callFunction,
EBUtils.byte2hex(this.getNonce())
));
}
/**
* Performs request to the remote endpoint with built request.
* @throws IOException
* @throws EBCorruptedException
*/
public EBCreateUOResponse doRequest(EBCreateUORequest request) throws IOException, EBCorruptedException {
if (apiBlock == null || request != null){
build(request);
}
this.connector = engine.getConMgr().getConnector(this.endpoint);
this.connector.setEndpoint(this.endpoint);
this.connector.setSettings(this.settings);
this.connector.setRawRequest(rawRequest);
LOG.trace("Going to call request...");
this.rawResponse = this.connector.request();
// Empty response to parse data to.
final EBCreateUOResponse.Builder builder = new EBCreateUOResponse.Builder();
builder.setRawResponse(rawResponse);
if (!rawResponse.isSuccessful()){
LOG.info("Response was not successful: " + rawResponse.toString());
pkResponse = builder.build();
return pkResponse;
}
// Parse process data response.
final EBResponseParserBase parser = new EBResponseParserBase();
parser.setSubParser(this);
parser.parseResponse(new JSONObject(rawResponse.getBody()), builder, null);
// Return connector.
engine.getConMgr().doneWithConnector(connector);
this.connector = null;
pkResponse = builder.build();
return pkResponse;
}
@Override
public EBResponse.ABuilder parseResponse(JSONObject data, EBResponse.ABuilder resp, EBResponseParserOptions options) throws EBCorruptedException {
if (data == null || !data.has(FIELD_DATA)){
throw new EBCorruptedException("Message corrupted");
}
if (resp == null){
resp = new EBGetPubKeyResponse.Builder();
}
if (!resp.getObj().isCodeOk()){
LOG.debug(String.format("Error in processing, status: %04X, message: %s",
(long)resp.getObj().getStatusCode(), resp.getObj().getStatusDetail()));
return resp;
}
final EBCreateUOResponse.ABuilder resp2ret = (EBCreateUOResponse.ABuilder) resp;
final JSONObject res = data.getJSONObject(FIELD_DATA);
resp2ret.setHandle(res.getString("uoid"));
// TODO: process public key.
// Certificate?
if (res.has("certificate")){
resp2ret.setCertificate(EBUtils.hex2byte(res.getString("certificate"), true));
}
// TODO: certificate chain processing.
return resp2ret;
}
@Override
public EBResponseParser getSubParser() {
return null;
}
}
|
public class abacazi {
public static void main(String[] args) {
String h;
String g;
String i;
System.out.println("Deu certo!");
System.out.println("No deu certo!!");
}
}
|
package uno.perwironegoro.boardgames;
public abstract class Board {
//The squares are pivoted from (1,1)!
protected Square[][] squares;
public Board(int width, int height) {
squares = new Square[width][height];
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
squares[x][y] = new Square(x + 1, y + 1);
}
}
}
public void applyMove(Move move) {
copyOntoBoard(move.from);
copyOntoBoard(move.to);
}
//Override to replace the taken piece
public void unapplyMove(Move move) {
getBoardSquare(move.from).setOccupier(move.to.getOccupier());
getBoardSquare(move.to).setOccupier(Colour.NONE);
}
public Square getSquare(int x, int y) {
return squares[x - 1][y - 1];
}
public Square getBoardSquareRelative(Square s, int xo, int yo) {
return getSquare(s.getX() + xo, s.getY() + yo);
}
public Square getBoardSquare(Square s) {
return getSquare(s.getX(), s.getY());
}
public void copyOntoBoard(Square s) {
getBoardSquare(s).setOccupier(s.getOccupier());
}
public void display(Symbols sym) {
int marginSize = UtilsDisplay.digits(getHeight()) + 1;
String alphaIndex = UtilsDisplay.fitInMargin(marginSize, "", ' ');
for(int x = 0; x < getWidth(); x++) {
alphaIndex += UtilsBoard.indexToStringUpper(x) + " ";
}
System.out.println(alphaIndex);
System.out.println("");
for(int y = getHeight() - 1; y >= 0; y
System.out.print(UtilsDisplay.fitInMargin(marginSize, String.valueOf(y + 1), ' '));
for(int x = 0; x < getWidth(); x++) {
System.out.print(sym.symbolOf(squares[x][y].getOccupier()) + " ");
}
System.out.println(y + 1);
}
System.out.println("");
System.out.println(alphaIndex);
System.out.println("");
}
public int getWidth() {
return squares.length;
}
public int getHeight() {
return squares[0].length;
}
}
|
package net.thegreshams.firebase4j.service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.thegreshams.firebase4j.error.FirebaseException;
import net.thegreshams.firebase4j.error.JacksonUtilityException;
import net.thegreshams.firebase4j.model.FirebaseResponse;
import net.thegreshams.firebase4j.util.JacksonUtility;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
public class Firebase {
protected static final Logger LOGGER = Logger.getRootLogger();
public static final String FIREBASE_API_JSON_EXTENSION
= ".json";
// PROPERTIES & CONSTRUCTORS
private final String baseUrl;
private String secureToken = null;
private List<NameValuePair> query;
private Boolean useJsonExt = true;
public Firebase( String baseUrl ) throws FirebaseException {
if( baseUrl == null || baseUrl.trim().isEmpty() ) {
String msg = "baseUrl cannot be null or empty; was: '" + baseUrl + "'";
LOGGER.error( msg );
throw new FirebaseException( msg );
}
this.baseUrl = baseUrl.trim();
query = new ArrayList<NameValuePair>();
LOGGER.info( "intialized with base-url: " + this.baseUrl );
}
/**
* Overloaded constructor for cases where you need to prevent adding the json extension to the url.
* @param baseUrl
* @param useJsonExtension include the json extension to the URL?
* @throws FirebaseException
*/
public Firebase( String baseUrl, Boolean useJsonExtension ) throws FirebaseException {
this(baseUrl);
useJsonExt = useJsonExtension;
}
public Firebase(String baseUrl, String secureToken) throws FirebaseException {
if( baseUrl == null || baseUrl.trim().isEmpty() ) {
String msg = "baseUrl cannot be null or empty; was: '" + baseUrl + "'";
LOGGER.error( msg );
throw new FirebaseException( msg );
}
this.secureToken = secureToken;
this.baseUrl = baseUrl.trim();
query = new ArrayList<NameValuePair>();
LOGGER.info( "intialized with base-url: " + this.baseUrl );
}
// PUBLIC API
/**
* GETs data from the base-url.
*
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse get() throws FirebaseException, UnsupportedEncodingException {
return this.get( null );
}
/**
* GETs data from the provided-path relative to the base-url.
*
* @param path -- if null/empty, refers to the base-url
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse get( String path ) throws FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpGet request = new HttpGet( url );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.GET, httpResponse );
return response;
}
/**
* PATCHs data to the base-url
*
* @param data -- can be null/empty
* @return
* @throws {@link FirebaseException}
* @throws {@link JacksonUtilityException}
* @throws UnsupportedEncodingException
*/
public FirebaseResponse patch(Map<String, Object> data) throws FirebaseException, JacksonUtilityException, UnsupportedEncodingException {
return this.patch(null, data);
}
/**
* PATCHs data on the provided-path relative to the base-url.
*
* @param path -- if null/empty, refers to the base-url
* @param data -- can be null/empty
* @return {@link FirebaseResponse}
* @throws {@link FirebaseException}
* @throws {@link JacksonUtilityException}
* @throws UnsupportedEncodingException
*/
public FirebaseResponse patch(String path, Map<String, Object> data) throws FirebaseException, JacksonUtilityException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
//HttpPut request = new HttpPut( url );
HttpPatch request = new HttpPatch(url);
request.setEntity( this.buildEntityFromDataMap( data ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.PATCH, httpResponse );
return response;
}
/**
*
* @param jsonData
* @return
* @throws UnsupportedEncodingException
* @throws FirebaseException
*/
public FirebaseResponse patch(String jsonData) throws UnsupportedEncodingException, FirebaseException {
return this.patch(null, jsonData);
}
/**
*
* @param path
* @param jsonData
* @return
* @throws UnsupportedEncodingException
* @throws FirebaseException
*/
public FirebaseResponse patch(String path, String jsonData) throws UnsupportedEncodingException, FirebaseException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpPatch request = new HttpPatch( url );
request.setEntity( this.buildEntityFromJsonData( jsonData ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.PATCH, httpResponse );
return response;
}
/**
* PUTs data to the base-url (ie: creates or overwrites).
* If there is already data at the base-url, this data overwrites it.
* If data is null/empty, any data existing at the base-url is deleted.
*
* @param data -- can be null/empty
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link JacksonUtilityException}
* @throws {@link FirebaseException}
*/
public FirebaseResponse put( Map<String, Object> data ) throws JacksonUtilityException, FirebaseException, UnsupportedEncodingException {
return this.put( null, data );
}
/**
* PUTs data to the provided-path relative to the base-url (ie: creates or overwrites).
* If there is already data at the path, this data overwrites it.
* If data is null/empty, any data existing at the path is deleted.
*
* @param path -- if null/empty, refers to base-url
* @param data -- can be null/empty
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link JacksonUtilityException}
* @throws {@link FirebaseException}
*/
public FirebaseResponse put( String path, Map<String, Object> data ) throws JacksonUtilityException, FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpPut request = new HttpPut( url );
request.setEntity( this.buildEntityFromDataMap( data ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.PUT, httpResponse );
return response;
}
/**
* PUTs data to the provided-path relative to the base-url (ie: creates or overwrites).
* If there is already data at the path, this data overwrites it.
* If data is null/empty, any data existing at the path is deleted.
*
* @param jsonData -- can be null/empty
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse put( String jsonData ) throws FirebaseException, UnsupportedEncodingException {
return this.put( null, jsonData );
}
/**
* PUTs data to the provided-path relative to the base-url (ie: creates or overwrites).
* If there is already data at the path, this data overwrites it.
* If data is null/empty, any data existing at the path is deleted.
*
* @param path -- if null/empty, refers to base-url
* @param jsonData -- can be null/empty
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse put( String path, String jsonData ) throws FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpPut request = new HttpPut( url );
request.setEntity( this.buildEntityFromJsonData( jsonData ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.PUT, httpResponse );
return response;
}
/**
* POSTs data to the base-url (ie: creates).
*
* NOTE: the Firebase API does not treat this method in the conventional way, but instead defines it
* as 'PUSH'; the API will insert this data under the base-url but associated with a Firebase-
* generated key; thus, every use of this method will result in a new insert even if the data already
* exists.
*
* @param data -- can be null/empty but will result in no data being POSTed
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link JacksonUtilityException}
* @throws {@link FirebaseException}
*/
public FirebaseResponse post( Map<String, Object> data ) throws JacksonUtilityException, FirebaseException, UnsupportedEncodingException {
return this.post( null, data );
}
/**
* POSTs data to the provided-path relative to the base-url (ie: creates).
*
* NOTE: the Firebase API does not treat this method in the conventional way, but instead defines it
* as 'PUSH'; the API will insert this data under the provided path but associated with a Firebase-
* generated key; thus, every use of this method will result in a new insert even if the provided path
* and data already exist.
*
* @param path -- if null/empty, refers to base-url
* @param data -- can be null/empty but will result in no data being POSTed
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link JacksonUtilityException}
* @throws {@link FirebaseException}
*/
public FirebaseResponse post( String path, Map<String, Object> data ) throws JacksonUtilityException, FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpPost request = new HttpPost( url );
request.setEntity( this.buildEntityFromDataMap( data ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.POST, httpResponse );
return response;
}
/**
* POSTs data to the base-url (ie: creates).
*
* NOTE: the Firebase API does not treat this method in the conventional way, but instead defines it
* as 'PUSH'; the API will insert this data under the base-url but associated with a Firebase-
* generated key; thus, every use of this method will result in a new insert even if the provided data
* already exists.
*
* @param jsonData -- can be null/empty but will result in no data being POSTed
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse post( String jsonData ) throws FirebaseException, UnsupportedEncodingException {
return this.post( null, jsonData );
}
/**
* POSTs data to the provided-path relative to the base-url (ie: creates).
*
* NOTE: the Firebase API does not treat this method in the conventional way, but instead defines it
* as 'PUSH'; the API will insert this data under the provided path but associated with a Firebase-
* generated key; thus, every use of this method will result in a new insert even if the provided path
* and data already exist.
*
* @param path -- if null/empty, refers to base-url
* @param jsonData -- can be null/empty but will result in no data being POSTed
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse post( String path, String jsonData ) throws FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpPost request = new HttpPost( url );
request.setEntity( this.buildEntityFromJsonData( jsonData ) );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.POST, httpResponse );
return response;
}
/**
* Append a query to the request.
*
* @param query -- Query string based on Firebase REST API
* @param parameter -- Query parameter
* @return Firebase -- return this Firebase object
*/
public Firebase addQuery(String query, String parameter) {
this.query.add(new BasicNameValuePair(query, parameter));
return this;
}
/**
* DELETEs data from the base-url.
*
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse delete() throws FirebaseException, UnsupportedEncodingException {
return this.delete( null );
}
/**
* DELETEs data from the provided-path relative to the base-url.
*
* @param path -- if null/empty, refers to the base-url
* @return {@link FirebaseResponse}
* @throws UnsupportedEncodingException
* @throws {@link FirebaseException}
*/
public FirebaseResponse delete( String path ) throws FirebaseException, UnsupportedEncodingException {
// make the request
String url = this.buildFullUrlFromRelativePath( path );
HttpDelete request = new HttpDelete( url );
HttpResponse httpResponse = this.makeRequest( request );
// process the response
FirebaseResponse response = this.processResponse( FirebaseRestMethod.DELETE, httpResponse );
return response;
}
// PRIVATE API
private StringEntity buildEntityFromDataMap( Map<String, Object> dataMap ) throws FirebaseException, JacksonUtilityException {
String jsonData = JacksonUtility.GET_JSON_STRING_FROM_MAP( dataMap );
return this.buildEntityFromJsonData( jsonData );
}
private StringEntity buildEntityFromJsonData( String jsonData ) throws FirebaseException {
StringEntity result = null;
try {
result = new StringEntity( jsonData , "UTF-8" );
} catch( Throwable t ) {
String msg = "unable to create entity from data; data was: " + jsonData;
LOGGER.error( msg );
throw new FirebaseException( msg, t );
}
return result;
}
private String buildFullUrlFromRelativePath( String path ) throws UnsupportedEncodingException {
// massage the path (whether it's null, empty, or not) into a full URL
if( path == null ) {
path = "";
}
path = path.trim();
if( !path.isEmpty() && !path.startsWith( "/" ) ) {
path = "/" + path;
}
String url = this.baseUrl + path;
if(useJsonExt) url += Firebase.FIREBASE_API_JSON_EXTENSION;
if(query != null) {
url += "?";
Iterator<NameValuePair> it = query.iterator();
NameValuePair e;
while(it.hasNext()) {
e = it.next();
url += e.getName() + "=" + URLEncoder.encode(e.getValue(), "UTF-8") + "&";
}
}
if(secureToken != null) {
if(query != null) {
url += "access_token=" + secureToken;
} else {
url += "?access_token=" + secureToken;
}
}
if(url.lastIndexOf("&") == url.length()) {
StringBuilder str = new StringBuilder(url);
str.deleteCharAt(str.length());
url = str.toString();
}
LOGGER.info( "built full url to '" + url + "' using relative-path of '" + path + "'" );
return url;
}
private HttpResponse makeRequest( HttpRequestBase request ) throws FirebaseException {
HttpResponse response = null;
// sanity-check
if( request == null ) {
String msg = "request cannot be null";
LOGGER.error( msg );
throw new FirebaseException( msg );
}
try {
HttpClient client = new DefaultHttpClient();
response = client.execute( request );
} catch( Throwable t ) {
String msg = "unable to receive response from request(" + request.getMethod() + ") @ " + request.getURI();
LOGGER.error( msg );
throw new FirebaseException( msg, t );
}
return response;
}
private FirebaseResponse processResponse( FirebaseRestMethod method, HttpResponse httpResponse ) throws FirebaseException {
FirebaseResponse response = null;
// sanity-checks
if( method == null ) {
String msg = "method cannot be null";
LOGGER.error( msg );
throw new FirebaseException( msg );
}
if( httpResponse == null ) {
String msg = "httpResponse cannot be null";
LOGGER.error( msg );
throw new FirebaseException( msg );
}
// get the response-entity
HttpEntity entity = httpResponse.getEntity();
// get the response-code
int code = httpResponse.getStatusLine().getStatusCode();
// set the response-success
boolean success = false;
switch( method ) {
case DELETE:
if( httpResponse.getStatusLine().getStatusCode() == 204
&& "No Content".equalsIgnoreCase( httpResponse.getStatusLine().getReasonPhrase() ) )
{
success = true;
}
break;
case PATCH:
case PUT:
case POST:
case GET:
if( httpResponse.getStatusLine().getStatusCode() == 200
&& "OK".equalsIgnoreCase( httpResponse.getStatusLine().getReasonPhrase() ) )
{
success = true;
}
break;
default:
break;
}
// get the response-body
Writer writer = new StringWriter();
if( entity != null ) {
try {
InputStream is = entity.getContent();
char[] buffer = new char[1024];
Reader reader = new BufferedReader( new InputStreamReader( is, "UTF-8" ) );
int n;
while( (n=reader.read(buffer)) != -1 ) {
writer.write( buffer, 0, n );
}
} catch( Throwable t ) {
String msg = "unable to read response-content; read up to this point: '" + writer.toString() + "'";
writer = new StringWriter(); // don't want to later give jackson partial JSON it might choke on
LOGGER.error( msg );
throw new FirebaseException( msg, t );
}
}
// convert response-body to map
Map<String, Object> body = null;
try {
body = JacksonUtility.GET_JSON_STRING_AS_MAP( writer.toString() );
} catch( JacksonUtilityException jue ) {
String msg = "unable to convert response-body into map; response-body was: '" + writer.toString() + "'";
LOGGER.error( msg );
throw new FirebaseException( msg, jue );
}
// build the response
response = new FirebaseResponse( success, code, body, writer.toString() );
//clear the query
query = null;
return response;
}
// INTERNAL CLASSES
public enum FirebaseRestMethod {
GET,
PATCH,
PUT,
POST,
DELETE;
}
}
|
package lighthouse.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.protobuf.ByteString;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import lighthouse.LighthouseBackend;
import lighthouse.files.AppDirectory;
import lighthouse.files.DiskManager;
import lighthouse.protocol.Ex;
import lighthouse.protocol.LHProtos;
import lighthouse.protocol.Project;
import lighthouse.protocol.TestUtils;
import lighthouse.threading.AffinityExecutor;
import lighthouse.wallet.PledgingWallet;
import org.bitcoinj.core.*;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.testing.FakeTxBuilder;
import org.bitcoinj.testing.InboundMessageQueuer;
import org.bitcoinj.testing.TestWithPeerGroup;
import org.bitcoinj.utils.BriefLogFormatter;
import org.javatuples.Triplet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.ECPrivateKeyParameters;
import org.spongycastle.crypto.signers.ECDSASigner;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.net.HttpURLConnection.HTTP_OK;
import static lighthouse.LighthouseBackend.Mode.CLIENT;
import static lighthouse.LighthouseBackend.Mode.SERVER;
import static lighthouse.protocol.LHUtils.*;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock;
import static org.junit.Assert.*;
public class LighthouseBackendTest extends TestWithPeerGroup {
private LighthouseBackend backend;
private Path tmpDir;
private AffinityExecutor.Gate gate;
private Project project;
private LinkedBlockingQueue<HttpExchange> httpReqs;
private ProjectModel projectModel;
private HttpServer localServer;
private Address to;
private VersionMessage supportingVer;
private PledgingWallet pledgingWallet;
private AffinityExecutor.ServiceAffinityExecutor executor;
private DiskManager diskManager;
private LHProtos.Pledge injectedPledge;
public LighthouseBackendTest() {
super(ClientType.BLOCKING_CLIENT_MANAGER);
}
@Override
@Before
public void setUp() throws Exception {
pledgingWallet = new PledgingWallet(params) {
@Nullable
@Override
public LHProtos.Pledge getPledgeFor(Project project) {
if (injectedPledge != null) {
return injectedPledge;
} else {
return super.getPledgeFor(project);
}
}
@Override
public Set<LHProtos.Pledge> getPledges() {
if (injectedPledge != null)
return ImmutableSet.<LHProtos.Pledge>builder().addAll(super.getPledges()).add(injectedPledge).build();
else
return super.getPledges();
}
};
wallet = pledgingWallet;
super.setUp();
BriefLogFormatter.init();
tmpDir = Files.createTempDirectory("lighthouse-dmtest");
AppDirectory.overrideAppDir(tmpDir);
AppDirectory.initAppDir("lhtests");
// Give data backend its own thread. The "gate" lets us just run commands in the context of the unit test thread.
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
fail("Uncaught exception");
});
gate = new AffinityExecutor.Gate();
executor = new AffinityExecutor.ServiceAffinityExecutor("test thread");
diskManager = new DiskManager(executor, true);
backend = new LighthouseBackend(CLIENT, peerGroup, blockChain, pledgingWallet, diskManager, executor);
backend.setMinPeersForUTXOQuery(1);
backend.setMaxJitterSeconds(0);
// Wait to start up.
backend.executor.fetchFrom(() -> null);
projectModel = new ProjectModel(pledgingWallet);
to = new ECKey().toAddress(params);
projectModel.address.set(to.toString());
projectModel.title.set("Foo");
projectModel.memo.set("Bar");
projectModel.goalAmount.set(Coin.COIN.value);
project = projectModel.getProject();
supportingVer = new VersionMessage(params, 1);
supportingVer.localServices = VersionMessage.NODE_NETWORK | VersionMessage.NODE_GETUTXOS;
supportingVer.clientVersion = GetUTXOsMessage.MIN_PROTOCOL_VERSION;
httpReqs = new LinkedBlockingQueue<>();
localServer = HttpServer.create(new InetSocketAddress("localhost", HTTP_LOCAL_TEST_PORT), 100);
localServer.createContext(HTTP_PATH_PREFIX, exchange -> {
gate.checkOnThread();
Uninterruptibles.putUninterruptibly(httpReqs, exchange);
});
localServer.setExecutor(gate);
localServer.start();
// Make peers selected for tx broadcast deterministic.
TransactionBroadcast.random = new Random(1);
}
@After
public void tearDown() {
super.tearDown();
executor.service.shutdown();
localServer.stop(Integer.MAX_VALUE);
}
private void sendServerStatus(HttpExchange exchange, LHProtos.Pledge... scrubbedPledges) throws IOException {
LHProtos.ProjectStatus.Builder status = LHProtos.ProjectStatus.newBuilder();
status.setId(project.getID());
status.setTimestamp(Instant.now().getEpochSecond());
status.setValuePledgedSoFar(Coin.COIN.value);
for (LHProtos.Pledge pledge : scrubbedPledges) {
status.addPledges(pledge);
}
byte[] bits = status.build().toByteArray();
exchange.sendResponseHeaders(HTTP_OK, bits.length);
exchange.getResponseBody().write(bits);
exchange.close();
}
private LHProtos.Pledge makeScrubbedPledge() {
final LHProtos.Pledge pledge = LHProtos.Pledge.newBuilder()
.setTotalInputValue(Coin.COIN.value)
.setProjectId(project.getID())
.setTimestamp(Utils.currentTimeSeconds())
.addTransactions(ByteString.copyFromUtf8("not a real tx"))
.setPledgeDetails(LHProtos.PledgeDetails.newBuilder().build())
.build();
final Sha256Hash origHash = Sha256Hash.create(pledge.toByteArray());
return pledge.toBuilder()
.clearTransactions()
.setOrigHash(ByteString.copyFrom(origHash.getBytes()))
.build();
}
private Path writeProjectToDisk() throws IOException {
return writeProjectToDisk(AppDirectory.dir());
}
private Path writeProjectToDisk(Path dir) throws IOException {
Path file = dir.resolve("test-project" + DiskManager.PROJECT_FILE_EXTENSION);
try (OutputStream stream = Files.newOutputStream(file)) {
project.getProto().writeTo(stream);
}
// Backend should now notice the new project in the app dir.
return file;
}
@Test
public void projectAddedWithServer() throws Exception {
// Check that if we add a path containing a project, it's noticed and the projects set is updated.
// Also check that the status is queried from the HTTP server it's linked to.
projectModel.serverName.set("localhost");
project = projectModel.getProject();
final LHProtos.Pledge scrubbedPledge = makeScrubbedPledge();
ObservableList<Project> projects = backend.mirrorProjects(gate);
assertEquals(0, projects.size());
writeProjectToDisk();
assertEquals(0, projects.size());
gate.waitAndRun();
// Is now loaded from disk.
assertEquals(1, projects.size());
final Project project1 = projects.iterator().next();
assertEquals("Foo", project1.getTitle());
// Let's watch out for pledges from the server.
ObservableSet<LHProtos.Pledge> pledges = backend.mirrorOpenPledges(project1, gate);
// HTTP request was made to server to learn about existing pledges.
gate.waitAndRun();
HttpExchange exchange = httpReqs.take();
sendServerStatus(exchange, scrubbedPledge);
// We got a pledge list update relayed into our thread.
pledges.addListener((SetChangeListener<LHProtos.Pledge>) c -> {
assertTrue(c.wasAdded());
});
gate.waitAndRun();
assertEquals(1, pledges.size());
assertEquals(Coin.COIN.value, pledges.iterator().next().getTotalInputValue());
}
@Test
public void projectCreated() throws Exception {
// Check that if we save a project, we get a set change mirrored back into our own thread and the file is
// stored to disk correctly.
ObservableList<Project> projects = backend.mirrorProjects(gate);
assertEquals(0, projects.size());
backend.saveProject(project);
assertEquals(0, projects.size());
gate.waitAndRun();
assertEquals(1, projects.size());
assertEquals("Foo", projects.iterator().next().getTitle());
assertTrue(Files.exists(tmpDir.resolve("Foo" + DiskManager.PROJECT_FILE_EXTENSION)));
}
@Test
public void serverCheckStatus() throws Exception {
// Check that the server status map is updated correctly.
projectModel.serverName.set("localhost");
project = projectModel.getProject();
final LHProtos.Pledge scrubbedPledge = makeScrubbedPledge();
ObservableMap<Project, LighthouseBackend.CheckStatus> statuses = backend.mirrorCheckStatuses(gate);
assertEquals(0, statuses.size());
writeProjectToDisk();
gate.waitAndRun();
// Is now loaded from disk.
assertEquals(1, statuses.size());
assertNotNull(statuses.get(project));
assertTrue(statuses.get(project).inProgress);
assertNull(statuses.get(project).error);
// Doing request to server.
gate.waitAndRun();
HttpExchange exchange = httpReqs.take();
exchange.sendResponseHeaders(404, -1); // not found!
gate.waitAndRun();
// Error shows up in map.
assertEquals(1, statuses.size());
assertFalse(statuses.get(project).inProgress);
final Throwable error = statuses.get(project).error;
assertNotNull(error);
assertEquals(java.io.FileNotFoundException.class, error.getClass());
// Try again ...
backend.refreshProjectStatusFromServer(project);
gate.waitAndRun();
assertEquals(1, statuses.size());
assertTrue(statuses.get(project).inProgress);
gate.waitAndRun();
exchange = httpReqs.take();
sendServerStatus(exchange, scrubbedPledge);
gate.waitAndRun();
assertEquals(0, statuses.size());
}
@Test
public void serverAndLocalAreDeduped() throws Exception {
// Verify that if the backend knows about a pledge, and receives the same pledge back in scrubbed form,
// it knows they are the same and doesn't duplicate.
projectModel.serverName.set("localhost");
project = projectModel.getProject();
final LHProtos.Pledge pledge = LHProtos.Pledge.newBuilder()
.setTotalInputValue(Coin.COIN.value)
.setProjectId(project.getID())
.setTimestamp(Utils.currentTimeSeconds())
.addTransactions(ByteString.copyFromUtf8("not a real tx"))
.setPledgeDetails(LHProtos.PledgeDetails.newBuilder().build())
.build();
final Sha256Hash origHash = Sha256Hash.create(pledge.toByteArray());
final LHProtos.Pledge scrubbedPledge = pledge.toBuilder()
.clearTransactions()
.setOrigHash(ByteString.copyFrom(origHash.getBytes()))
.build();
// Make the wallet return the above pledge without having to screw around with actually using the wallet.
injectedPledge = pledge;
backend.shutdown();
executor.service.shutdown();
executor.service.awaitTermination(5, TimeUnit.SECONDS);
executor = new AffinityExecutor.ServiceAffinityExecutor("test thread 2");
diskManager = new DiskManager(executor, true);
writeProjectToDisk();
backend = new LighthouseBackend(CLIENT, peerGroup, blockChain, pledgingWallet, diskManager, executor);
// Let's watch out for pledges from the server.
ObservableSet<LHProtos.Pledge> pledges = backend.mirrorOpenPledges(project, gate);
assertEquals(1, pledges.size());
assertEquals(pledge, pledges.iterator().next());
// HTTP request was made to server to learn about existing pledges.
gate.waitAndRun();
sendServerStatus(httpReqs.take(), scrubbedPledge);
// Because we want to test the absence of action in an async process, we forcibly repeat the server lookup
// that just occurred so we can wait for it, and be sure that the scrubbed version of our own pledge was not
// mistakenly added. Attempting to just test here without waiting would race, as the backend is processing
// the reply we have above in parallel.
CompletableFuture future = backend.refreshProjectStatusFromServer(project);
gate.waitAndRun();
sendServerStatus(httpReqs.take(), scrubbedPledge);
future.get();
assertEquals(0, gate.getTaskQueueSize()); // No pending set changes now.
assertEquals(1, pledges.size());
assertEquals(pledge, pledges.iterator().next());
}
@Test
public void projectAddedP2P() throws Exception {
peerGroup.startAsync();
peerGroup.awaitRunning();
// Check that if we add an path containing a project, it's noticed and the projects set is updated.
// Also check that pledges are loaded from disk and checked against the P2P network.
ObservableList<Project> projects = backend.mirrorProjects(gate);
Path dropDir = Files.createTempDirectory("lh-droptest");
Path downloadedFile = writeProjectToDisk(dropDir);
backend.importProjectFrom(downloadedFile);
gate.waitAndRun();
// Is now loaded from disk.
assertEquals(1, projects.size());
// P2P getutxo message was used to find out if the pledge was already revoked.
Triplet<Transaction, Transaction, LHProtos.Pledge> data = TestUtils.makePledge(project, to, project.getGoalAmount());
Transaction stubTx = data.getValue0();
Transaction pledgeTx = data.getValue1();
LHProtos.Pledge pledge = data.getValue2();
// Let's watch out for pledges as they are loaded from disk and checked.
ObservableSet<LHProtos.Pledge> pledges = backend.mirrorOpenPledges(project, gate);
// The user drops the pledge.
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge.writeTo(stream);
}
// App finds a peer that supports getutxo.
InboundMessageQueuer p1 = connectPeer(1);
assertNull(outbound(p1));
InboundMessageQueuer p2 = connectPeer(2, supportingVer);
GetUTXOsMessage getutxos = (GetUTXOsMessage) waitForOutbound(p2);
assertNotNull(getutxos);
assertEquals(pledgeTx.getInput(0).getOutpoint(), getutxos.getOutPoints().get(0));
// We reply with the data it expects.
inbound(p2, new UTXOsMessage(params,
ImmutableList.of(stubTx.getOutput(0)),
new long[]{UTXOsMessage.MEMPOOL_HEIGHT},
blockStore.getChainHead().getHeader().getHash(),
blockStore.getChainHead().getHeight()));
// App sets a new Bloom filter so it finds out about revocations. Filter contains the outpoint of the stub.
BloomFilter filter = (BloomFilter) waitForOutbound(p2);
assertEquals(filter, waitForOutbound(p1));
assertTrue(filter.contains(stubTx.getOutput(0).getOutPointFor().bitcoinSerialize()));
assertFalse(filter.contains(pledgeTx.bitcoinSerialize()));
assertFalse(filter.contains(pledgeTx.getHash().getBytes()));
assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass());
assertEquals(MemoryPoolMessage.class, waitForOutbound(p2).getClass());
// We got a pledge list update relayed into our thread.
AtomicBoolean flag = new AtomicBoolean(false);
pledges.addListener((SetChangeListener<LHProtos.Pledge>) c -> {
flag.set(c.wasAdded());
});
gate.waitAndRun();
assertTrue(flag.get());
assertEquals(1, pledges.size());
final LHProtos.Pledge pledge2 = pledges.iterator().next();
assertEquals(Coin.COIN.value / 2, pledge2.getTotalInputValue());
// New block: let's pretend this block contains a revocation transaction. LighthouseBackend should recheck.
Transaction revocation = new Transaction(params);
revocation.addInput(stubTx.getOutput(0));
revocation.addOutput(stubTx.getOutput(0).getValue(), new ECKey().toAddress(params));
Block newBlock = FakeTxBuilder.makeSolvedTestBlock(blockChain.getChainHead().getHeader(), revocation);
FilteredBlock filteredBlock = filter.applyAndUpdate(newBlock);
inbound(p1, filteredBlock);
for (Transaction transaction : filteredBlock.getAssociatedTransactions().values()) {
inbound(p1, transaction);
}
inbound(p1, new Ping(123)); // Force processing of the filtered merkle block.
gate.waitAndRun();
assertEquals(0, pledges.size()); // was revoked
peerGroup.stopAsync();
peerGroup.awaitTerminated();
}
@Test
public void mergePeerAnswers() throws Exception {
// Check that we throw an exception if peers disagree on the state of the UTXO set. Such a pledge would
// be considered invalid.
peerGroup.startAsync();
peerGroup.awaitRunning();
InboundMessageQueuer p1 = connectPeer(1, supportingVer);
InboundMessageQueuer p2 = connectPeer(2, supportingVer);
InboundMessageQueuer p3 = connectPeer(3, supportingVer);
// Set ourselves up to check a pledge.
ObservableList<Project> projects = backend.mirrorProjects(gate);
ObservableMap<Project, LighthouseBackend.CheckStatus> statuses = backend.mirrorCheckStatuses(gate);
Path dropDir = Files.createTempDirectory("lh-droptest");
Path downloadedFile = writeProjectToDisk(dropDir);
backend.importProjectFrom(downloadedFile);
gate.waitAndRun();
assertEquals(1, projects.size());
// This triggers a Bloom filter update so we can spot claims.
checkBloomFilter(p1, p2, p3);
Triplet<Transaction, Transaction, LHProtos.Pledge> data = TestUtils.makePledge(project, to, project.getGoalAmount());
Transaction stubTx = data.getValue0();
Transaction pledgeTx = data.getValue1();
LHProtos.Pledge pledge = data.getValue2();
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge.writeTo(stream);
}
gate.waitAndRun();
assertEquals(1, statuses.size());
assertTrue(statuses.get(project).inProgress);
// App finds a few peers that support getutxos and queries all of them.
GetUTXOsMessage getutxos1, getutxos2, getutxos3;
getutxos1 = (GetUTXOsMessage) waitForOutbound(p1);
getutxos2 = (GetUTXOsMessage) waitForOutbound(p2);
getutxos3 = (GetUTXOsMessage) waitForOutbound(p3);
assertNotNull(getutxos1);
assertNotNull(getutxos2);
assertNotNull(getutxos3);
assertEquals(getutxos1, getutxos2);
assertEquals(getutxos2, getutxos3);
assertEquals(pledgeTx.getInput(0).getOutpoint(), getutxos1.getOutPoints().get(0));
// Two peers reply with the data it expects, one replies with a lie (claiming unspent when really spent).
UTXOsMessage lie = new UTXOsMessage(params,
ImmutableList.of(stubTx.getOutput(0)),
new long[]{UTXOsMessage.MEMPOOL_HEIGHT},
blockStore.getChainHead().getHeader().getHash(),
blockStore.getChainHead().getHeight());
UTXOsMessage correct = new UTXOsMessage(params,
ImmutableList.of(),
new long[]{},
blockStore.getChainHead().getHeader().getHash(),
blockStore.getChainHead().getHeight());
inbound(p1, correct);
inbound(p2, lie);
inbound(p3, correct);
gate.waitAndRun();
assertEquals(1, statuses.size());
assertFalse(statuses.get(project).inProgress);
assertTrue(statuses.get(project).error instanceof Ex.InconsistentUTXOAnswers);
}
private BloomFilter checkBloomFilter(InboundMessageQueuer... peers) throws InterruptedException {
BloomFilter result = null;
for (InboundMessageQueuer peer : peers) {
result = (BloomFilter) waitForOutbound(peer);
assertTrue(waitForOutbound(peer) instanceof MemoryPoolMessage);
}
return result;
}
@Test
public void pledgeAddedViaWallet() throws Exception {
ObservableList<Project> projects = backend.mirrorProjects(gate);
writeProjectToDisk();
gate.waitAndRun();
// Is now loaded from disk.
assertEquals(1, projects.size());
Transaction payment = FakeTxBuilder.createFakeTx(params, Coin.COIN, pledgingWallet.currentReceiveAddress());
FakeTxBuilder.BlockPair bp = createFakeBlock(blockStore, payment);
wallet.receiveFromBlock(payment, bp.storedBlock, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
wallet.notifyNewBestBlock(bp.storedBlock);
PledgingWallet.PendingPledge pendingPledge = pledgingWallet.createPledge(project, Coin.COIN.value / 2, null);
ObservableSet<LHProtos.Pledge> pledges = backend.mirrorOpenPledges(project, gate);
assertEquals(0, pledges.size());
LHProtos.Pledge proto = pendingPledge.commit(true);
gate.waitAndRun();
assertEquals(1, pledges.size());
assertEquals(proto, pledges.iterator().next());
}
@Test
public void submitPledgeViaHTTP() throws Exception {
backend = new LighthouseBackend(SERVER, peerGroup, blockChain, pledgingWallet, diskManager, executor);
backend.setMinPeersForUTXOQuery(1);
backend.setMaxJitterSeconds(0);
// Test the process of broadcasting a pledge's dependencies, then checking the UTXO set to see if it was
// revoked already. If all is OK then it should show up in the verified pledges set.
peerGroup.setMinBroadcastConnections(2);
peerGroup.startAsync();
peerGroup.awaitRunning();
Triplet<Transaction, Transaction, LHProtos.Pledge> data = TestUtils.makePledge(project, to, project.getGoalAmount());
Transaction stubTx = data.getValue0();
Transaction pledgeTx = data.getValue1();
LHProtos.Pledge pledge = data.getValue2();
writeProjectToDisk();
ObservableSet<LHProtos.Pledge> pledges = backend.mirrorOpenPledges(project, gate);
// The dependency TX doesn't really have to be a dependency at the moment, it could be anything so we lazily
// just make an unrelated fake tx to check the ordering of things.
Transaction depTx = FakeTxBuilder.createFakeTx(params, Coin.COIN, address);
pledge = pledge.toBuilder().setTransactions(0, ByteString.copyFrom(depTx.bitcoinSerialize()))
.addTransactions(ByteString.copyFrom(pledgeTx.bitcoinSerialize()))
.build();
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2, supportingVer);
// Pledge is submitted to the server via HTTP.
CompletableFuture<LHProtos.Pledge> future = backend.submitPledge(project, pledge);
assertFalse(future.isDone());
// Broadcast happens.
Transaction broadcast = (Transaction) waitForOutbound(p1);
assertEquals(depTx, broadcast);
assertNull(outbound(p2));
InventoryMessage inv = new InventoryMessage(params);
inv.addTransaction(depTx);
inbound(p2, inv);
// Broadcast is now complete, so query.
GetUTXOsMessage getutxos = (GetUTXOsMessage) waitForOutbound(p2);
assertNotNull(getutxos);
assertEquals(pledgeTx.getInput(0).getOutpoint(), getutxos.getOutPoints().get(0));
// We reply with the data it expects.
inbound(p2, new UTXOsMessage(params,
ImmutableList.of(stubTx.getOutput(0)),
new long[]{UTXOsMessage.MEMPOOL_HEIGHT},
blockStore.getChainHead().getHeader().getHash(),
blockStore.getChainHead().getHeight()));
// We got a pledge list update relayed into our thread.
AtomicBoolean flag = new AtomicBoolean(false);
pledges.addListener((SetChangeListener<LHProtos.Pledge>) c -> {
flag.set(c.wasAdded());
});
gate.waitAndRun();
assertTrue(flag.get());
assertEquals(1, pledges.size());
final LHProtos.Pledge pledge2 = pledges.iterator().next();
assertEquals(Coin.COIN.value / 2, pledge2.getTotalInputValue());
future.get();
// And the pledge was saved to disk named after the hash of the pledge contents.
final Sha256Hash pledgeHash = Sha256Hash.create(pledge.toByteArray());
final List<Path> dirFiles = mapList(listDir(AppDirectory.dir()), Path::getFileName);
assertTrue(dirFiles.contains(Paths.get(pledgeHash.toString() + DiskManager.PLEDGE_FILE_EXTENSION)));
peerGroup.stopAsync();
peerGroup.awaitTerminated();
}
@Test
public void claimServerless() throws Exception {
// Create enough pledges to satisfy the project, broadcast the claim transaction, make sure the backend
// spots the claim and understands the current state of the project.
peerGroup.setMinBroadcastConnections(2);
peerGroup.setDownloadTxDependencies(false);
peerGroup.startAsync();
peerGroup.awaitRunning();
Path dropDir = Files.createTempDirectory("lh-droptest");
Path downloadedFile = writeProjectToDisk(dropDir);
backend.importProjectFrom(downloadedFile);
ObservableSet<LHProtos.Pledge> openPledges = backend.mirrorOpenPledges(project, gate);
ObservableSet<LHProtos.Pledge> claimedPledges = backend.mirrorClaimedPledges(project, gate);
assertEquals(0, claimedPledges.size());
assertEquals(0, openPledges.size());
Triplet<Transaction, Transaction, LHProtos.Pledge> data = TestUtils.makePledge(project, to, project.getGoalAmount());
LHProtos.Pledge pledge1 = data.getValue2();
Triplet<Transaction, Transaction, LHProtos.Pledge> data2 = TestUtils.makePledge(project, to, project.getGoalAmount());
LHProtos.Pledge pledge2 = data2.getValue2();
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2, supportingVer);
// The user drops the pledges.
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge1" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge1.writeTo(stream);
}
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge2" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge2.writeTo(stream);
}
int q = 0;
for (int i = 0; i < 6; i++) {
Message m = waitForOutbound(p2);
if (m instanceof GetUTXOsMessage) {
doGetUTXOAnswer(q++ == 0 ? data.getValue0().getOutput(0) : data2.getValue0().getOutput(0), p2);
}
}
gate.waitAndRun();
gate.waitAndRun();
assertEquals(2, openPledges.size());
ObservableMap<String, LighthouseBackend.ProjectStateInfo> states = backend.mirrorProjectStates(gate);
assertEquals(LighthouseBackend.ProjectState.OPEN, states.get(project.getID()).state);
Transaction contract = project.completeContract(ImmutableSet.of(pledge1, pledge2));
inbound(p1, InventoryMessage.with(contract));
waitForOutbound(p1); // getdata for the contract.
inbound(p2, InventoryMessage.with(contract));
inbound(p1, contract);
for (int i = 0; i < 2; i++) {
Message m = waitForOutbound(p1);
assertTrue(m instanceof MemoryPoolMessage || m instanceof BloomFilter);
}
for (int i = 0; i < 5; i++) {
gate.waitAndRun(); // updates to lists and things.
}
assertEquals(LighthouseBackend.ProjectState.CLAIMED, states.get(project.getID()).state);
assertEquals(contract.getHash(), states.get(project.getID()).claimedBy);
assertTrue(Files.exists(AppDirectory.dir().resolve(DiskManager.PROJECT_STATUS_FILENAME)));
assertEquals(2, claimedPledges.size());
assertTrue(claimedPledges.contains(pledge1));
assertTrue(claimedPledges.contains(pledge2));
// TODO: Craft a test that verifies double spending of the claim is handled properly.
peerGroup.stopAsync();
peerGroup.awaitTerminated();
}
@Test
public void duplicatePledgesNotAllowed() throws Exception {
// Pledges should not share outputs, otherwise someone could pledge the same money twice either by accident
// or maliciously. Note that in the case where two pledges have two different dependencies that both double
// spend the same output, this will be caught by the backend trying to broadcast the dependencies itself
// (in the server case), and then observing that the second pledge has a dependency that's failing to propagate.
Path dropDir = Files.createTempDirectory("lh-droptest");
Path downloadedFile = writeProjectToDisk(dropDir);
backend.importProjectFrom(downloadedFile);
ObservableSet<LHProtos.Pledge> openPledges = backend.mirrorOpenPledges(project, gate);
peerGroup.setMinBroadcastConnections(2);
peerGroup.startAsync();
peerGroup.awaitRunning();
Transaction doubleSpentTx = new Transaction(params);
doubleSpentTx.addInput(TestUtils.makeRandomInput());
// Make a key that doesn't use deterministic signing, to make it easy for us to double spend with bitwise
// different pledges.
ECKey signingKey = new ECKey() {
@Override
protected ECDSASignature doSign(Sha256Hash input, BigInteger privateKeyForSigning) {
ECDSASigner signer = new ECDSASigner();
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(input.getBytes());
return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
};
TransactionOutput output = doubleSpentTx.addOutput(Coin.COIN.divide(2), signingKey.toAddress(params));
LHProtos.Pledge.Builder pledge1 = makeSimpleHalfPledge(signingKey, output);
LHProtos.Pledge.Builder pledge2 = makeSimpleHalfPledge(signingKey, output);
assertNotEquals(pledge1.getTransactions(0), pledge2.getTransactions(0));
ObservableMap<Project, LighthouseBackend.CheckStatus> statuses = backend.mirrorCheckStatuses(gate);
InboundMessageQueuer p1 = connectPeer(1, supportingVer);
InboundMessageQueuer p2 = connectPeer(2, supportingVer);
// User drops pledge 1
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge1" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge1.build().writeTo(stream);
}
for (int i = 0; i < 3; i++) {
Message m = waitForOutbound(p1);
if (m instanceof GetUTXOsMessage)
doGetUTXOAnswer(output, p1);
m = waitForOutbound(p2);
if (m instanceof GetUTXOsMessage)
doGetUTXOAnswer(output, p2);
}
gate.waitAndRun(); // statuses (start lookup)
gate.waitAndRun(); // openPledges
gate.waitAndRun(); // statuses (end lookup)
// First pledge is accepted.
assertEquals(1, openPledges.size());
assertEquals(pledge1.build(), openPledges.iterator().next());
// User drops pledge 2
try (OutputStream stream = Files.newOutputStream(dropDir.resolve("dropped-pledge2" + DiskManager.PLEDGE_FILE_EXTENSION))) {
pledge2.build().writeTo(stream);
}
for (int i = 0; i < 3; i++) {
Message m = waitForOutbound(p1);
if (m instanceof GetUTXOsMessage)
doGetUTXOAnswer(output, p1);
m = waitForOutbound(p2);
if (m instanceof GetUTXOsMessage)
doGetUTXOAnswer(output, p2);
}
// Wait for check status to update.
gate.waitAndRun(); // statuses (start lookup)
gate.waitAndRun(); // statuses (error result)
//noinspection ConstantConditions
assertEquals(VerificationException.DuplicatedOutPoint.class, statuses.get(project).error.getClass());
peerGroup.stopAsync();
peerGroup.awaitTerminated();
}
@Test
public void serverPledgeSync() throws Exception {
// Test that the client backend stays in sync with the server as pledges are added and revoked.
projectModel.serverName.set("localhost");
project = projectModel.getProject();
ObservableSet<LHProtos.Pledge> openPledges = backend.mirrorOpenPledges(project, gate);
final LHProtos.Pledge scrubbedPledge = makeScrubbedPledge();
writeProjectToDisk();
gate.waitAndRun();
// Is now loaded from disk and doing request to server.
HttpExchange exchange = httpReqs.take();
sendServerStatus(exchange, scrubbedPledge);
gate.waitAndRun();
assertEquals(1, openPledges.size());
// Pledge gets revoked.
backend.refreshProjectStatusFromServer(project);
gate.waitAndRun();
sendServerStatus(httpReqs.take());
gate.waitAndRun();
assertEquals(0, openPledges.size());
}
private LHProtos.Pledge.Builder makeSimpleHalfPledge(ECKey signingKey, TransactionOutput output) {
LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
Transaction tx = new Transaction(params);
tx.addOutput(project.getOutputs().get(0)); // Project output.
tx.addSignedInput(output, signingKey, Transaction.SigHash.ALL, true);
pledge.addTransactions(ByteString.copyFrom(tx.bitcoinSerialize()));
pledge.setTotalInputValue(Coin.COIN.divide(2).value);
pledge.setProjectId(project.getID());
pledge.setTimestamp(Utils.currentTimeSeconds());
pledge.getPledgeDetailsBuilder();
return pledge;
}
private void doGetUTXOAnswer(TransactionOutput output, InboundMessageQueuer p) throws InterruptedException, BlockStoreException {
inbound(p, new UTXOsMessage(params,
ImmutableList.of(output),
new long[]{UTXOsMessage.MEMPOOL_HEIGHT},
blockStore.getChainHead().getHeader().getHash(),
blockStore.getChainHead().getHeight()));
}
}
|
package arez;
import arez.spy.ActionCompletedEvent;
import arez.spy.ActionStartedEvent;
import arez.spy.ComponentCreateStartedEvent;
import arez.spy.ComputedValueCreatedEvent;
import arez.spy.ObservableValueCreatedEvent;
import arez.spy.ObserverCreatedEvent;
import arez.spy.ObserverErrorEvent;
import arez.spy.PropertyAccessor;
import arez.spy.PropertyMutator;
import arez.spy.ReactionScheduledEvent;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* The ArezContext defines the top level container of interconnected observables and observers.
* The context also provides the mechanism for creating transactions to read and write state
* within the system.
*/
@SuppressWarnings( "Duplicates" )
public final class ArezContext
{
/**
* Id of next node to be created.
* This is only used if {@link Arez#areNamesEnabled()} returns true but no name has been supplied.
*/
private int _nextNodeId = 1;
/**
* Id of next transaction to be created.
*
* This needs to start at 1 as {@link ObservableValue#NOT_IN_CURRENT_TRACKING} is used
* to optimize dependency tracking in transactions.
*/
private int _nextTransactionId = 1;
/**
* Reaction Scheduler.
* Currently hard-coded, in the future potentially configurable.
*/
private final ReactionScheduler _scheduler = new ReactionScheduler( Arez.areZonesEnabled() ? this : null );
/**
* Support infrastructure for propagating observer errors.
*/
@Nullable
private final ObserverErrorHandlerSupport _observerErrorHandlerSupport =
Arez.areObserverErrorHandlersEnabled() ? new ObserverErrorHandlerSupport() : null;
/**
* Support infrastructure for spy events.
*/
@Nullable
private final SpyImpl _spy = Arez.areSpiesEnabled() ? new SpyImpl( Arez.areZonesEnabled() ? this : null ) : null;
/**
* Support infrastructure for components.
*/
@Nullable
private final HashMap<String, HashMap<Object, Component>> _components =
Arez.areNativeComponentsEnabled() ? new HashMap<>() : null;
/**
* Registry of top level observables.
* These are all the Observables instances not contained within a component.
*/
@Nullable
private final HashMap<String, ObservableValue<?>> _observables = Arez.areRegistriesEnabled() ? new HashMap<>() : null;
/**
* Registry of top level computed values.
* These are all the ComputedValue instances not contained within a component.
*/
@Nullable
private final HashMap<String, ComputedValue<?>> _computedValues =
Arez.areRegistriesEnabled() ? new HashMap<>() : null;
/**
* Registry of top level observers.
* These are all the Observer instances not contained within a component.
*/
@Nullable
private final HashMap<String, Observer> _observers = Arez.areRegistriesEnabled() ? new HashMap<>() : null;
/**
* Locator used to resolve references.
*/
@Nullable
private final AggregateLocator _locator = Arez.areReferencesEnabled() ? new AggregateLocator() : null;
/**
* Flag indicating whether the scheduler should run next time it is triggered.
* This should be active only when there is no uncommitted transaction for context.
*/
private boolean _schedulerEnabled = true;
/**
* The number of un-released locks on the scheduler.
*/
private int _schedulerLockCount;
/**
* Optional environment in which reactions are executed.
*/
@Nullable
private ReactionEnvironment _environment;
/**
* Flag indicating whether the scheduler is currently active.
*/
private boolean _schedulerActive;
/**
* Arez context should not be created directly but only accessed via Arez.
*/
ArezContext()
{
}
/**
* Return the map for components of specified type.
*
* @param type the component type.
* @return the map for components of specified type.
*/
@Nonnull
private HashMap<Object, Component> getComponentByTypeMap( @Nonnull final String type )
{
assert null != _components;
return _components.computeIfAbsent( type, t -> new HashMap<>() );
}
/**
* Return true if the component identified by type and id has been defined in context.
*
* @param type the component type.
* @param id the component id.
* @return true if component is defined in context.
*/
public boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id )
{
apiInvariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0135: ArezContext.isComponentPresent() invoked when Arez.areNativeComponentsEnabled() returns false." );
return getComponentByTypeMap( type ).containsKey( id );
}
/**
* Create a component with the specified parameters and return it.
* This method should only be invoked if {@link Arez#areNativeComponentsEnabled()} returns true.
* This method should not be invoked if {@link #isComponentPresent(String, Object)} returns true for
* the parameters. The caller should invoke {@link Component#complete()} on the returned component as
* soon as the component definition has completed.
*
* @param type the component type.
* @param id the component id.
* @return true if component is defined in context.
*/
@Nonnull
public Component component( @Nonnull final String type, @Nonnull final Object id )
{
return component( type, id, Arez.areNamesEnabled() ? type + "@" + id : null );
}
/**
* Create a component with the specified parameters and return it.
* This method should only be invoked if {@link Arez#areNativeComponentsEnabled()} returns true.
* This method should not be invoked if {@link #isComponentPresent(String, Object)} returns true for
* the parameters. The caller should invoke {@link Component#complete()} on the returned component as
* soon as the component definition has completed.
*
* @param type the component type.
* @param id the component id.
* @param name the name of the component. Should be null if {@link Arez#areNamesEnabled()} returns false.
* @return true if component is defined in context.
*/
@Nonnull
public Component component( @Nonnull final String type, @Nonnull final Object id, @Nullable final String name )
{
return component( type, id, name, null );
}
/**
* Create a component with the specified parameters and return it.
* This method should only be invoked if {@link Arez#areNativeComponentsEnabled()} returns true.
* This method should not be invoked if {@link #isComponentPresent(String, Object)} returns true for
* the parameters. The caller should invoke {@link Component#complete()} on the returned component as
* soon as the component definition has completed.
*
* @param type the component type.
* @param id the component id.
* @param name the name of the component. Should be null if {@link Arez#areNamesEnabled()} returns false.
* @param preDispose the hook action called just before the Component is disposed. The hook method is called from within the dispose transaction.
* @return true if component is defined in context.
*/
@Nonnull
public Component component( @Nonnull final String type,
@Nonnull final Object id,
@Nullable final String name,
@Nullable final SafeProcedure preDispose )
{
return component( type, id, name, preDispose, null );
}
/**
* Create a component with the specified parameters and return it.
* This method should only be invoked if {@link Arez#areNativeComponentsEnabled()} returns true.
* This method should not be invoked if {@link #isComponentPresent(String, Object)} returns true for
* the parameters. The caller should invoke {@link Component#complete()} on the returned component as
* soon as the component definition has completed.
*
* @param type the component type.
* @param id the component id.
* @param name the name of the component. Should be null if {@link Arez#areNamesEnabled()} returns false.
* @param preDispose the hook action called just before the Component is disposed. The hook method is called from within the dispose transaction.
* @param postDispose the hook action called just after the Component is disposed. The hook method is called from within the dispose transaction.
* @return true if component is defined in context.
*/
@Nonnull
public Component component( @Nonnull final String type,
@Nonnull final Object id,
@Nullable final String name,
@Nullable final SafeProcedure preDispose,
@Nullable final SafeProcedure postDispose )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0008: ArezContext.component() invoked when Arez.areNativeComponentsEnabled() returns false." );
}
final HashMap<Object, Component> map = getComponentByTypeMap( type );
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( () -> !map.containsKey( id ),
() -> "Arez-0009: ArezContext.component() invoked for type '" + type + "' and id '" +
id + "' but a component already exists for specified type+id." );
}
final Component component =
new Component( Arez.areZonesEnabled() ? this : null, type, id, name, preDispose, postDispose );
map.put( id, component );
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ComponentCreateStartedEvent( getSpy().asComponentInfo( component ) ) );
}
return component;
}
/**
* Invoked by the component during it's dispose to release resources associated with the component.
*
* @param component the component.
*/
void deregisterComponent( @Nonnull final Component component )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0006: ArezContext.deregisterComponent() invoked when Arez.areNativeComponentsEnabled() returns false." );
}
final String type = component.getType();
final HashMap<Object, Component> map = getComponentByTypeMap( type );
final Component removed = map.remove( component.getId() );
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> component == removed,
() -> "Arez-0007: ArezContext.deregisterComponent() invoked for '" + component + "' but was " +
"unable to remove specified component from registry. Actual component removed: " + removed );
}
if ( map.isEmpty() )
{
assert _components != null;
_components.remove( type );
}
}
/**
* Return component with specified type and id if component exists.
*
* @param type the component type.
* @param id the component id.
* @return the component or null.
*/
@Nullable
Component findComponent( @Nonnull final String type, @Nonnull final Object id )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0010: ArezContext.findComponent() invoked when Arez.areNativeComponentsEnabled() returns false." );
}
assert null != _components;
final HashMap<Object, Component> map = _components.get( type );
if ( null != map )
{
return map.get( id );
}
else
{
return null;
}
}
/**
* Return all the components with specified type.
*
* @param type the component type.
* @return the components for type.
*/
@Nonnull
Collection<Component> findAllComponentsByType( @Nonnull final String type )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0011: ArezContext.findAllComponentsByType() invoked when Arez.areNativeComponentsEnabled() returns false." );
}
assert null != _components;
final HashMap<Object, Component> map = _components.get( type );
if ( null != map )
{
return map.values();
}
else
{
return Collections.emptyList();
}
}
/**
* Return all the component types as a collection.
*
* @return the component types.
*/
@Nonnull
Collection<String> findAllComponentTypes()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areNativeComponentsEnabled,
() -> "Arez-0012: ArezContext.findAllComponentTypes() invoked when Arez.areNativeComponentsEnabled() returns false." );
}
assert null != _components;
return _components.keySet();
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param function the function that computes the value.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nonnull final SafeFunction<T> function )
{
return computed( null, function );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param name the name of the ComputedValue. Should be non-null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param function the function that computes the value.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final String name, @Nonnull final SafeFunction<T> function )
{
return computed( null, name, function );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param component the component that contains the ComputedValue if any. Must be null unless {@link Arez#areNativeComponentsEnabled()} returns true.
* @param name the name of the ComputedValue. Should be non-null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param function the function that computes the value.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final Component component,
@Nullable final String name,
@Nonnull final SafeFunction<T> function )
{
return computed( component, name, function, null, null, null, null );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param name the name of the ComputedValue.
* @param function the function that computes the value.
* @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDispose the procedure to invoke when the ComputedValue is disposed.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final String name,
@Nonnull final SafeFunction<T> function,
@Nullable final Procedure onActivate,
@Nullable final Procedure onDeactivate,
@Nullable final Procedure onStale,
@Nullable final Procedure onDispose )
{
return computed( null, name, function, onActivate, onDeactivate, onStale, onDispose );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param component the component that contains the ComputedValue if any. Must be null unless {@link Arez#areNativeComponentsEnabled()} returns true.
* @param name the name of the ComputedValue.
* @param function the function that computes the value.
* @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDispose the procedure to invoke when the ComputedValue is disposed.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final Component component,
@Nullable final String name,
@Nonnull final SafeFunction<T> function,
@Nullable final Procedure onActivate,
@Nullable final Procedure onDeactivate,
@Nullable final Procedure onStale,
@Nullable final Procedure onDispose )
{
return computed( component, name, function, onActivate, onDeactivate, onStale, onDispose, Priority.NORMAL );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param component the component that contains the ComputedValue if any. Must be null unless {@link Arez#areNativeComponentsEnabled()} returns true.
* @param name the name of the ComputedValue.
* @param function the function that computes the value.
* @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDispose the procedure to invoke when the ComputedValue is disposed.
* @param priority the priority of the associated observer.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final Component component,
@Nullable final String name,
@Nonnull final SafeFunction<T> function,
@Nullable final Procedure onActivate,
@Nullable final Procedure onDeactivate,
@Nullable final Procedure onStale,
@Nullable final Procedure onDispose,
@Nonnull final Priority priority )
{
return computed( component, name, function, onActivate, onDeactivate, onStale, onDispose, priority, false, false );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param component the component that contains the ComputedValue if any. Must be null unless {@link Arez#areNativeComponentsEnabled()} returns true.
* @param name the name of the ComputedValue.
* @param function the function that computes the value.
* @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDispose the procedure to invoke when the ComputedValue is disposed.
* @param priority the priority of the associated observer.
* @param keepAlive true if the ComputedValue should be activated when it is created and never deactivated. If this is true then the onActivate and onDeactivate parameters should be null.
* @param runImmediately ignored unless keepAlive is true. true to compute the value immediately, false to schedule compute for next reaction cycle.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final Component component,
@Nullable final String name,
@Nonnull final SafeFunction<T> function,
@Nullable final Procedure onActivate,
@Nullable final Procedure onDeactivate,
@Nullable final Procedure onStale,
@Nullable final Procedure onDispose,
@Nonnull final Priority priority,
final boolean keepAlive,
final boolean runImmediately )
{
return computed( component,
name,
function,
onActivate,
onDeactivate,
onStale,
onDispose,
priority,
keepAlive,
runImmediately,
false );
}
/**
* Create a ComputedValue with specified parameters.
*
* @param <T> the type of the computed value.
* @param component the component that contains the ComputedValue if any. Must be null unless {@link Arez#areNativeComponentsEnabled()} returns true.
* @param name the name of the ComputedValue.
* @param function the function that computes the value.
* @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change.
* @param onDispose the procedure to invoke when the ComputedValue is disposed.
* @param priority the priority of the associated observer.
* @param keepAlive true if the ComputedValue should be activated when it is created and never deactivated. If this is true then the onActivate and onDeactivate parameters should be null.
* @param runImmediately ignored unless keepAlive is true. true to compute the value immediately, false to schedule compute for next reaction cycle.
* @param observeLowerPriorityDependencies true if the computed can observe lower priority dependencies.
* @return the ComputedValue instance.
*/
@Nonnull
public <T> ComputedValue<T> computed( @Nullable final Component component,
@Nullable final String name,
@Nonnull final SafeFunction<T> function,
@Nullable final Procedure onActivate,
@Nullable final Procedure onDeactivate,
@Nullable final Procedure onStale,
@Nullable final Procedure onDispose,
@Nonnull final Priority priority,
final boolean keepAlive,
final boolean runImmediately,
final boolean observeLowerPriorityDependencies )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( () -> !keepAlive || null == onActivate,
() -> "Arez-0039: ArezContext.computed() specified keepAlive = true and did not pass a null for onActivate." );
apiInvariant( () -> !keepAlive || null == onDeactivate,
() -> "Arez-0045: ArezContext.computed() specified keepAlive = true and did not pass a null for onDeactivate." );
}
final ComputedValue<T> computedValue =
new ComputedValue<>( Arez.areZonesEnabled() ? this : null,
component,
generateNodeName( "ComputedValue", name ),
function,
priority,
keepAlive,
observeLowerPriorityDependencies );
final Observer observer = computedValue.getObserver();
// Null check before setting hook fields. It seems that this decreases runtime memory pressure
// in some environments with the penalty of a slight increase in code size. This will need to be
// rechecked once we move off GWT2.x/ES3 and onto J2CL and preferably added to an automated performance
// test. This is possibly only due to the way ES3 is optimized. It should be noted that in several
// applications it did not have an impact on code-size and could actually decrease code-size in J2CL
// if these hook methods were unused
if ( null != onActivate )
{
computedValue.setOnActivate( onActivate );
}
if ( null != onDeactivate )
{
computedValue.setOnDeactivate( onDeactivate );
}
if ( null != onStale )
{
computedValue.setOnStale( onStale );
}
if ( null != onDispose )
{
observer.setOnDispose( onDispose );
}
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ComputedValueCreatedEvent( new ComputedValueInfoImpl( getSpy(), computedValue ) ) );
}
if ( keepAlive )
{
if ( runImmediately )
{
computedValue.getObserver().invokeReaction();
}
else
{
scheduleReaction( computedValue.getObserver() );
}
}
return computedValue;
}
/**
* Build name for node.
* If {@link Arez#areNamesEnabled()} returns false then this method will return null, otherwise the specified
* name will be returned or a name synthesized from the prefix and a running number if no name is specified.
*
* @param prefix the prefix used if this method needs to generate name.
* @param name the name specified by the user.
* @return the name.
*/
@Nullable
String generateNodeName( @Nonnull final String prefix, @Nullable final String name )
{
return Arez.areNamesEnabled() ?
null != name ? name : prefix + "@" + _nextNodeId++ :
null;
}
/**
* Create a read-only autorun observer and run immediately.
*
* @param executable the executable defining the observer.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nonnull final Procedure executable )
{
return autorun( null, executable );
}
/**
* Create a read-only autorun observer and run immediately.
*
* @param name the name of the observer.
* @param executable the executable defining the observer.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final String name, @Nonnull final Procedure executable )
{
return autorun( name, false, executable );
}
/**
* Create an autorun observer and run immediately.
*
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( final boolean mutation, @Nonnull final Procedure executable )
{
return autorun( null, mutation, executable );
}
/**
* Create an autorun observer and run immediately.
*
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable )
{
return autorun( name, mutation, executable, true );
}
/**
* Create an autorun observer.
*
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
final boolean runImmediately )
{
return autorun( name, mutation, executable, Priority.NORMAL, runImmediately );
}
/**
* Create an autorun observer.
*
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param priority the priority of the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean runImmediately )
{
return autorun( null, name, mutation, executable, priority, runImmediately );
}
/**
* Create an autorun observer.
*
* @param component the component containing autorun observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable )
{
return autorun( component, name, mutation, executable, Priority.NORMAL, false );
}
/**
* Create an autorun observer.
*
* @param component the component containing autorun observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param priority the priority of the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean runImmediately )
{
return autorun( component, name, mutation, executable, priority, runImmediately, false );
}
/**
* Create an autorun observer.
*
* @param component the component containing autorun observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param priority the priority of the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @param observeLowerPriorityDependencies true if the observer can observe lower priority dependencies.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean runImmediately,
final boolean observeLowerPriorityDependencies )
{
return autorun( component,
name,
mutation,
executable,
priority,
runImmediately,
observeLowerPriorityDependencies,
false );
}
/**
* Create an autorun observer.
*
* @param component the component containing autorun observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param priority the priority of the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @param observeLowerPriorityDependencies true if the observer can observe lower priority dependencies.
* @param canNestActions true if the observer can start actions from autorun.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean runImmediately,
final boolean observeLowerPriorityDependencies,
final boolean canNestActions )
{
return autorun( component,
name,
mutation,
executable,
priority,
runImmediately,
observeLowerPriorityDependencies,
canNestActions,
null );
}
/**
* Create an autorun observer.
*
* @param component the component containing autorun observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the executable may modify state, false otherwise.
* @param executable the executable defining the observer.
* @param priority the priority of the observer.
* @param runImmediately true to invoke executable immediately, false to schedule for next reaction cycle.
* @param observeLowerPriorityDependencies true if the observer can observe lower priority dependencies.
* @param canNestActions true if the observer can start actions from autorun.
* @param onDispose the hook function invoked when the autroun is disposed, if any.
* @return the new Observer.
*/
@Nonnull
public Observer autorun( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean runImmediately,
final boolean observeLowerPriorityDependencies,
final boolean canNestActions,
@Nullable final Procedure onDispose )
{
final Observer observer =
observer( component,
name,
mutation,
new RunProcedureAsActionReaction( executable ),
priority,
false,
observeLowerPriorityDependencies,
canNestActions );
// See similar code in computed(...) implementation for explanation of this code
if ( null != onDispose )
{
observer.setOnDispose( onDispose );
}
if ( runImmediately )
{
observer.invokeReaction();
}
else
{
scheduleReaction( observer );
}
return observer;
}
/**
* Create a "tracker" observer that tracks code using a read-only transaction.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param executable the executable invoked as the reaction.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nonnull final Procedure executable )
{
return tracker( false, executable );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param executable the executable invoked as the reaction.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( final boolean mutation, @Nonnull final Procedure executable )
{
return tracker( null, mutation, executable );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param name the name of the observer.
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param executable the executable invoked as the reaction.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable )
{
return tracker( null, name, mutation, executable );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param component the component containing tracker if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param executable the executable invoked as the reaction.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable )
{
return tracker( component, name, mutation, executable, Priority.NORMAL );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param component the component containing tracker if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param priority the priority of the observer.
* @param executable the executable invoked as the reaction.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority )
{
return tracker( component, name, mutation, executable, priority, false );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param component the component containing tracker if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param priority the priority of the observer.
* @param executable the executable invoked as the reaction.
* @param observeLowerPriorityDependencies true if the observer can observe lower priority dependencies.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean observeLowerPriorityDependencies )
{
return tracker( component, name, mutation, executable, priority, observeLowerPriorityDependencies, false );
}
/**
* Create a "tracker" observer.
* The "tracker" observer triggers the specified executable any time any of the observers dependencies are updated.
* To track dependencies, this returned observer must be passed as the tracker to an track method like {@link #track(Observer, Function, Object...)}.
*
* @param component the component containing tracker if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the observer may modify state during tracking, false otherwise.
* @param priority the priority of the observer.
* @param executable the executable invoked as the reaction.
* @param observeLowerPriorityDependencies true if the observer can observe lower priority dependencies.
* @param canNestActions true if the observer can start actions from tracker action.
* @return the new Observer.
*/
@Nonnull
public Observer tracker( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Priority priority,
final boolean observeLowerPriorityDependencies,
final boolean canNestActions )
{
return observer( component,
name,
mutation,
new RunProcedureReaction( executable ),
priority,
true,
observeLowerPriorityDependencies,
canNestActions );
}
/**
* Create an observer with specified parameters.
*
* @param component the component containing observer if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observer.
* @param mutation true if the reaction may modify state, false otherwise.
* @param reaction the reaction defining observer.
* @param priority the priority of the observer.
* @return the new Observer.
*/
@Nonnull
Observer observer( @Nullable final Component component,
@Nullable final String name,
final boolean mutation,
@Nonnull final Reaction reaction,
@Nonnull final Priority priority,
final boolean canTrackExplicitly,
final boolean observeLowerPriorityDependencies,
final boolean canNestActions )
{
final TransactionMode mode = mutationToTransactionMode( mutation );
final Observer observer =
new Observer( Arez.areZonesEnabled() ? this : null,
component,
generateNodeName( "Observer", name ),
null,
mode,
reaction,
priority,
canTrackExplicitly,
observeLowerPriorityDependencies,
canNestActions );
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ObserverCreatedEvent( new ObserverInfoImpl( getSpy(), observer ) ) );
}
return observer;
}
/**
* Create an ObservableValue synthesizing name if required.
*
* @param <T> the type of observable.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable()
{
return observable( null );
}
/**
* Create an ObservableValue with the specified name.
*
* @param name the name of the ObservableValue. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param <T> the type of observable.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable( @Nullable final String name )
{
return observable( name, null, null );
}
/**
* Create an ObservableValue.
*
* @param name the name of the observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param accessor the accessor for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise.
* @param mutator the mutator for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise.
* @param <T> the type of observable.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable( @Nullable final String name,
@Nullable final PropertyAccessor<T> accessor,
@Nullable final PropertyMutator<T> mutator )
{
return observable( null, name, accessor, mutator );
}
/**
* Create an ObservableValue.
*
* @param <T> The type of the value that is observable.
* @param component the component containing observable if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable( @Nullable final Component component,
@Nullable final String name )
{
return observable( component, name, null );
}
/**
* Create an ObservableValue.
*
* @param <T> The type of the value that is observable.
* @param component the component containing observable if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param accessor the accessor for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable( @Nullable final Component component,
@Nullable final String name,
@Nullable final PropertyAccessor<T> accessor )
{
return observable( component, name, accessor, null );
}
/**
* Create an ObservableValue.
*
* @param <T> The type of the value that is observable.
* @param component the component containing observable if any. Should be null if {@link Arez#areNativeComponentsEnabled()} returns false.
* @param name the name of the observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise.
* @param accessor the accessor for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise.
* @param mutator the mutator for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise.
* @return the new ObservableValue.
*/
@Nonnull
public <T> ObservableValue<T> observable( @Nullable final Component component,
@Nullable final String name,
@Nullable final PropertyAccessor<T> accessor,
@Nullable final PropertyMutator<T> mutator )
{
final ObservableValue<T> observableValue =
new ObservableValue<>( Arez.areZonesEnabled() ? this : null,
component,
generateNodeName( "ObservableValue", name ),
null,
accessor,
mutator );
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ObservableValueCreatedEvent( new ObservableValueInfoImpl( getSpy(),
observableValue ) ) );
}
return observableValue;
}
/**
* Pass the supplied observer to the scheduler.
* The observer should NOT be already pending execution.
*
* @param observer the reaction to schedule.
*/
void scheduleReaction( @Nonnull final Observer observer )
{
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ReactionScheduledEvent( new ObserverInfoImpl( getSpy(), observer ) ) );
}
if ( Arez.shouldEnforceTransactionType() && isTransactionActive() && Arez.shouldCheckInvariants() )
{
final TransactionMode mode = getTransaction().getMode();
invariant( () -> mode != TransactionMode.READ_ONLY,
() -> "Arez-0013: Observer named '" + observer.getName() + "' attempted to be scheduled during " +
"read-only transaction." );
invariant( () -> getTransaction().getTracker() != observer ||
mode == TransactionMode.READ_WRITE,
() -> "Arez-0014: Observer named '" + observer.getName() + "' attempted to schedule itself during " +
"read-only tracking transaction. Observers that are supporting ComputedValue instances " +
"must not schedule self." );
}
_scheduler.scheduleReaction( observer );
}
/**
* Return true if there is a transaction in progress.
*
* @return true if there is a transaction in progress.
*/
public boolean isTransactionActive()
{
return Transaction.isTransactionActive( this );
}
public boolean isTrackingTransactionActive()
{
return Transaction.isTransactionActive( this ) && null != Transaction.current().getTracker();
}
/**
* Return true if there is a read-write transaction in progress.
*
* @return true if there is a read-write transaction in progress.
*/
public boolean isWriteTransactionActive()
{
return Transaction.isTransactionActive( this ) &&
( !Arez.shouldEnforceTransactionType() || TransactionMode.READ_WRITE == Transaction.current().getMode() );
}
/**
* Return the current transaction.
* This method should not be invoked unless a transaction active and will throw an
* exception if invariant checks are enabled.
*
* @return the current transaction.
*/
@Nonnull
Transaction getTransaction()
{
final Transaction current = Transaction.current();
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> !Arez.areZonesEnabled() || current.getContext() == this,
() -> "Arez-0015: Attempting to get current transaction but current transaction is for different context." );
}
return current;
}
/**
* Enable scheduler so that it will run pending observers next time it is triggered.
*/
void enableScheduler()
{
_schedulerEnabled = true;
}
/**
* Disable scheduler so that it will not run pending observers next time it is triggered.
*/
void disableScheduler()
{
_schedulerEnabled = false;
}
/**
* Return true if the scheduler enabled flag is true.
* It is still possible that the scheduler has un-released locks so this
* does not necessarily imply that the schedule will run.
*
* @return true if the scheduler enabled flag is true.
*/
boolean isSchedulerEnabled()
{
return _schedulerEnabled;
}
/**
* Release a scheduler lock to enable scheduler to run again.
* Trigger reactions if lock reaches 0 and no current transaction.
*/
void releaseSchedulerLock()
{
_schedulerLockCount
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> _schedulerLockCount >= 0,
() -> "Arez-0016: releaseSchedulerLock() reduced schedulerLockCount below 0." );
}
triggerScheduler();
}
/**
* Return true if the scheduler is paused.
* True means that {@link #pauseScheduler()} has been called one or more times and the lock not disposed.
*
* @return true if the scheduler is paused, false otherwise.
*/
public boolean isSchedulerPaused()
{
return _schedulerLockCount != 0;
}
/**
* Pause scheduler so that it will not run any reactions next time {@link #triggerScheduler()} is invoked.
* The scheduler will not resume scheduling reactions until the lock returned from this method is disposed.
*
* <p>The intention of this method is to allow the user to manually batch multiple actions, before
* disposing the lock and allowing reactions to flow through the system. A typical use-case is when
* a large network packet is received and processed over multiple ticks but you only want the
* application to react once.</p>
*
* <p>If this is invoked from within a reaction then the current behaviour will continue to process any
* pending reactions until there is none left. However this behaviour should not be relied upon as it may
* result in an abort in the future.</p>
*
* <p>It should be noted that this is the one way where inconsistent state can creep into an Arez application.
* If an external action can trigger while the scheduler is paused. i.e. In the browser when an
* event-handler calls back from UI when the reactions have not run. Thus the event handler could be
* based on stale data. If this can occur the developer should </p>
*
* @return a lock on scheduler.
*/
@Nonnull
public Disposable pauseScheduler()
{
_schedulerLockCount++;
return new SchedulerLock( Arez.areZonesEnabled() ? this : null );
}
/**
* Specify the environment in which reactions are invoked.
*
* @param environment the environment in which to execute reactions.
*/
public void setEnvironment( @Nullable final ReactionEnvironment environment )
{
_environment = environment;
}
/**
* Method invoked to trigger the scheduler to run any pending reactions. The scheduler will only be
* triggered if there is no transaction active. This method is typically used after one or more Observers
* have been created outside a transaction with the runImmediately flag set to false and the caller wants
* to force the observers to react. Otherwise the Observers will not be schedule until the next top-level
* transaction completes. Pending reactions are run in the environment specified by {@link #setEnvironment(ReactionEnvironment)}
* if any has been specified.
*/
public void triggerScheduler()
{
if ( isSchedulerEnabled() && !isSchedulerPaused() )
{
// Each reaction creates a top level transaction that attempts to run call
// this method when it completes. Rather than allow this if it is detected
// that we are running reactions already then just abort and assume the top
// most invocation of runPendingTasks will handle scheduling
if ( !_schedulerActive )
{
_schedulerActive = true;
try
{
if ( null != _environment )
{
// The environment wrapper can perform actions that trigger the need for the Arez
// scheduler to re-run so we keep checking until there is no more work to be done.
// This is typically used when the environment reacts to changes that Arez triggered
// (i.e. via @Track callbacks) which in turn reschedules Arez changes. This happens
// in frameworks like react4j which have only scheduler that responds to changes and
// feeds back into Arez.
do
{
_environment.run( _scheduler::runPendingTasks );
}
while ( _scheduler.hasTasksToSchedule() );
}
else
{
_scheduler.runPendingTasks();
}
}
finally
{
_schedulerActive = false;
}
}
}
}
/**
* Add the specified disposable to the list of pending disposables.
* The disposable must not already be in the list of pending observers.
* The disposable will be processed before the next top-level reaction.
*
* @param disposable the disposable.
*/
public void scheduleDispose( @Nonnull final Disposable disposable )
{
_scheduler.scheduleDispose( disposable );
}
/**
* Execute the supplied executable in a read-write transaction.
* The name is synthesized if {@link Arez#areNamesEnabled()} returns true.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( @Nonnull final Function<T> executable, @Nonnull final Object... parameters )
throws Throwable
{
return action( true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The name is synthesized if {@link Arez#areNamesEnabled()} returns true.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the function to execute.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( final boolean mutation,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
return action( null, mutation, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( @Nullable final String name,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
return action( name, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( @Nullable final String name,
final boolean mutation,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
return action( name, mutation, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
return action( name, mutation, verifyActionRequired, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param requireNewTransaction true if a new transaction should be created, false if can use the current transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
* @throws Exception if the executable throws an an exception.
*/
public <T> T action( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
return action( generateNodeName( "Transaction", name ),
mutationToTransactionMode( mutation ),
verifyActionRequired,
requireNewTransaction,
executable,
null,
parameters );
}
public <T> T track( @Nonnull final Observer tracker,
@Nonnull final Function<T> executable,
@Nonnull final Object... parameters )
throws Throwable
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( tracker::canTrackExplicitly,
() -> "Arez-0017: Attempted to track Observer named '" + tracker.getName() + "' but " +
"observer is not a tracker." );
}
return action( generateNodeName( tracker ),
Arez.shouldEnforceTransactionType() ? tracker.getMode() : null,
false,
true,
executable,
tracker,
parameters );
}
private <T> T action( @Nullable final String name,
@Nullable final TransactionMode mode,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final Function<T> executable,
@Nullable final Observer tracker,
@Nonnull final Object... parameters )
throws Throwable
{
final boolean tracked = null != tracker;
Throwable t = null;
boolean completed = false;
long startedAt = 0L;
T result;
try
{
if ( willPropagateSpyEvents() )
{
startedAt = System.currentTimeMillis();
assert null != name;
getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) );
}
verifyActionNestingAllowed( name, mode );
if ( canImmediatelyInvokeAction( mode, requireNewTransaction ) )
{
result = executable.call();
}
else
{
final Transaction transaction =
Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker );
try
{
result = executable.call();
verifyActionRequired( transaction, name, verifyActionRequired );
}
finally
{
Transaction.commit( transaction );
}
}
if ( willPropagateSpyEvents() )
{
completed = true;
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, result, null, duration ) );
}
return result;
}
catch ( final Throwable e )
{
t = e;
throw e;
}
finally
{
if ( willPropagateSpyEvents() )
{
if ( !completed )
{
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, null, t, duration ) );
}
}
triggerScheduler();
}
}
/**
* Execute the supplied executable in a read-write transaction.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( @Nonnull final SafeFunction<T> executable, @Nonnull final Object... parameters )
{
return safeAction( true, executable, parameters );
}
/**
* Execute the supplied function in a transaction.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( final boolean mutation,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
return safeAction( null, mutation, executable, parameters );
}
/**
* Execute the supplied executable in a read-write transaction.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( @Nullable final String name,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
return safeAction( name, true, executable, parameters );
}
/**
* Execute the supplied executable.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( @Nullable final String name,
final boolean mutation,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
return safeAction( name, mutation, true, executable, parameters );
}
/**
* Execute the supplied executable.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
return safeAction( name, mutation, verifyActionRequired, true, executable, parameters );
}
/**
* Execute the supplied executable.
* The executable is should not throw an exception.
*
* @param <T> the type of return value.
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param requireNewTransaction true if a new transaction should be created, false if can use the current transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @return the value returned from the executable.
*/
public <T> T safeAction( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
return safeAction( generateNodeName( "Transaction", name ),
mutationToTransactionMode( mutation ),
verifyActionRequired,
requireNewTransaction,
executable,
null,
parameters );
}
public <T> T safeTrack( @Nonnull final Observer tracker,
@Nonnull final SafeFunction<T> executable,
@Nonnull final Object... parameters )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( tracker::canTrackExplicitly,
() -> "Arez-0018: Attempted to track Observer named '" + tracker.getName() + "' but " +
"observer is not a tracker." );
}
return safeAction( generateNodeName( tracker ),
Arez.shouldEnforceTransactionType() ? tracker.getMode() : null,
false,
true,
executable,
tracker,
parameters );
}
private <T> T safeAction( @Nullable final String name,
@Nullable final TransactionMode mode,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final SafeFunction<T> executable,
@Nullable final Observer tracker,
@Nonnull final Object... parameters )
{
final boolean tracked = null != tracker;
Throwable t = null;
boolean completed = false;
long startedAt = 0L;
T result;
try
{
if ( willPropagateSpyEvents() )
{
startedAt = System.currentTimeMillis();
assert null != name;
getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) );
}
verifyActionNestingAllowed( name, mode );
if ( canImmediatelyInvokeAction( mode, requireNewTransaction ) )
{
result = executable.call();
}
else
{
final Transaction transaction =
Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker );
try
{
result = executable.call();
verifyActionRequired( transaction, name, verifyActionRequired );
}
finally
{
Transaction.commit( transaction );
}
}
if ( willPropagateSpyEvents() )
{
completed = true;
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, result, null, duration ) );
}
return result;
}
catch ( final Throwable e )
{
t = e;
throw e;
}
finally
{
if ( willPropagateSpyEvents() )
{
if ( !completed )
{
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, null, t, duration ) );
}
}
triggerScheduler();
}
}
/**
* Execute the supplied executable in a read-write transaction.
* The procedure may throw an exception.
*
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( @Nonnull final Procedure executable, @Nonnull final Object... parameters )
throws Throwable
{
action( true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( final boolean mutation, @Nonnull final Procedure executable, @Nonnull final Object... parameters )
throws Throwable
{
action( null, mutation, executable, parameters );
}
/**
* Execute the supplied executable in a read-write transaction.
* The executable may throw an exception.
*
* @param name the name of the transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( @Nullable final String name,
@Nonnull final Procedure executable,
@Nonnull final Object... parameters )
throws Throwable
{
action( name, true, executable, true, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( @Nullable final String name,
final boolean mutation,
@Nonnull final Procedure executable,
@Nonnull final Object... parameters )
throws Throwable
{
action( name, mutation, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
@Nonnull final Procedure executable,
@Nonnull final Object... parameters )
throws Throwable
{
action( name, mutation, verifyActionRequired, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable may throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param requireNewTransaction true if a new transaction should be created, false if can use the current transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
* @throws Throwable if the procedure throws an an exception.
*/
public void action( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final Procedure executable,
@Nonnull final Object... parameters )
throws Throwable
{
action( generateNodeName( "Transaction", name ),
mutationToTransactionMode( mutation ),
verifyActionRequired,
requireNewTransaction,
executable,
true,
null,
parameters );
}
public void track( @Nonnull final Observer tracker,
@Nonnull final Procedure executable,
@Nonnull final Object... parameters )
throws Throwable
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( tracker::canTrackExplicitly,
() -> "Arez-0019: Attempted to track Observer named '" + tracker.getName() + "' but " +
"observer is not a tracker." );
}
action( generateNodeName( tracker ),
Arez.shouldEnforceTransactionType() ? tracker.getMode() : null,
false,
true,
executable,
true,
tracker,
parameters );
}
@Nullable
private String generateNodeName( @Nonnull final Observer tracker )
{
return Arez.areNamesEnabled() ? tracker.getName() : null;
}
void action( @Nullable final String name,
@Nullable final TransactionMode mode,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final Procedure executable,
final boolean reportAction,
@Nullable final Observer tracker,
@Nonnull final Object... parameters )
throws Throwable
{
final boolean tracked = null != tracker;
Throwable t = null;
boolean completed = false;
long startedAt = 0L;
try
{
if ( willPropagateSpyEvents() && reportAction )
{
startedAt = System.currentTimeMillis();
assert null != name;
getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) );
}
verifyActionNestingAllowed( name, mode );
if ( canImmediatelyInvokeAction( mode, requireNewTransaction ) )
{
executable.call();
}
else
{
final Transaction transaction =
Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker );
try
{
executable.call();
verifyActionRequired( transaction, name, verifyActionRequired );
}
finally
{
Transaction.commit( transaction );
}
}
if ( willPropagateSpyEvents() && reportAction )
{
completed = true;
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, null, duration ) );
}
}
catch ( final Throwable e )
{
t = e;
throw e;
}
finally
{
if ( willPropagateSpyEvents() && reportAction )
{
if ( !completed )
{
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, t, duration ) );
}
}
triggerScheduler();
}
}
/**
* Execute the supplied executable in a read-write transaction.
* The executable is should not throw an exception.
*
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( @Nonnull final SafeProcedure executable, @Nonnull final Object... parameters )
{
safeAction( true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable is should not throw an exception.
*
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( final boolean mutation,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
safeAction( null, mutation, executable, parameters );
}
/**
* Execute the supplied executable in a read-write transaction.
* The executable is should not throw an exception.
*
* @param name the name of the transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( @Nullable final String name,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
safeAction( name, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable is should not throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( @Nullable final String name,
final boolean mutation,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
safeAction( name, mutation, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable is should not throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
safeAction( name, mutation, verifyActionRequired, true, executable, parameters );
}
/**
* Execute the supplied executable in a transaction.
* The executable is should not throw an exception.
*
* @param name the name of the transaction.
* @param mutation true if the action may modify state, false otherwise.
* @param verifyActionRequired true if the action will add invariant checks to ensure reads or writes occur within
* the scope of the action. If no reads or writes occur, the action need not be an
* action.
* @param requireNewTransaction true if a new transaction should be created, false if can use the current transaction.
* @param executable the executable.
* @param parameters the parameters if any. The parameters are only used to generate a spy event.
*/
public void safeAction( @Nullable final String name,
final boolean mutation,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
safeAction( generateNodeName( "Transaction", name ),
mutationToTransactionMode( mutation ),
verifyActionRequired,
requireNewTransaction,
executable,
null,
parameters );
}
public void safeTrack( @Nonnull final Observer tracker,
@Nonnull final SafeProcedure executable,
@Nonnull final Object... parameters )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( tracker::canTrackExplicitly,
() -> "Arez-0020: Attempted to track Observer named '" + tracker.getName() + "' but " +
"observer is not a tracker." );
}
safeAction( generateNodeName( tracker ),
Arez.shouldEnforceTransactionType() ? tracker.getMode() : null,
false,
true,
executable,
tracker,
parameters );
}
void safeAction( @Nullable final String name,
@Nullable final TransactionMode mode,
final boolean verifyActionRequired,
final boolean requireNewTransaction,
@Nonnull final SafeProcedure executable,
@Nullable final Observer tracker,
@Nonnull final Object... parameters )
{
final boolean tracked = null != tracker;
Throwable t = null;
boolean completed = false;
long startedAt = 0L;
try
{
if ( willPropagateSpyEvents() )
{
startedAt = System.currentTimeMillis();
assert null != name;
getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) );
}
verifyActionNestingAllowed( name, mode );
if ( canImmediatelyInvokeAction( mode, requireNewTransaction ) )
{
executable.call();
}
else
{
final Transaction transaction =
Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker );
try
{
executable.call();
verifyActionRequired( transaction, name, verifyActionRequired );
}
finally
{
Transaction.commit( transaction );
}
}
if ( willPropagateSpyEvents() )
{
completed = true;
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, null, duration ) );
}
}
catch ( final Throwable e )
{
t = e;
throw e;
}
finally
{
if ( willPropagateSpyEvents() )
{
if ( !completed )
{
final long duration = System.currentTimeMillis() - startedAt;
assert null != name;
getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, t, duration ) );
}
}
triggerScheduler();
}
}
private void verifyActionNestingAllowed( @Nullable final String name, @Nullable final TransactionMode mode )
{
if ( Arez.shouldEnforceTransactionType() )
{
final Transaction parentTransaction = Transaction.isTransactionActive( this ) ? Transaction.current() : null;
if ( null != parentTransaction )
{
final Observer parent = parentTransaction.getTracker();
apiInvariant( () -> null == parent || parent.canNestActions() || TransactionMode.READ_WRITE_OWNED == mode,
() -> "Arez-0187: Attempting to nest " + mode + " action named '" + name + "' " +
"inside transaction named '" + parentTransaction.getName() + "' created by an " +
"observer that does not allow nested actions." );
}
}
}
/**
* Return true if action can immediately invoked, false if a transaction needs to be created.
*/
private boolean canImmediatelyInvokeAction( @Nullable final TransactionMode mode,
final boolean requireNewTransaction )
{
return !requireNewTransaction &&
( Arez.shouldEnforceTransactionType() && TransactionMode.READ_WRITE == mode ?
isWriteTransactionActive() :
isTransactionActive() );
}
/**
* Execute the specified action outside of a transaction.
* The transaction is suspended for the duration of the action and the action must not
* attempt to create a nested transaction.
* The executable may throw an exception.
*
* @param executable the executable.
* @throws Throwable if the action throws an an exception.
*/
public void noTxAction( @Nonnull final Procedure executable )
throws Throwable
{
final Transaction current = Transaction.current();
Transaction.suspend( current );
try
{
executable.call();
}
finally
{
Transaction.resume( current );
}
}
/**
* Execute the specified action outside of a transaction.
* The transaction is suspended for the duration of the action and the action must not
* attempt to create a nested transaction.
* The executable may throw an exception.
*
* @param <T> the type of return value.
* @param executable the executable.
* @return the value returned from the executable.
* @throws Throwable if the action throws an an exception.
*/
public <T> T noTxAction( @Nonnull final Function<T> executable )
throws Throwable
{
final Transaction current = Transaction.current();
Transaction.suspend( current );
try
{
return executable.call();
}
finally
{
Transaction.resume( current );
}
}
/**
* Execute the specified action outside of a transaction.
* The transaction is suspended for the duration of the action and the action must not
* attempt to create a nested transaction.
*
* @param executable the executable.
*/
public void safeNoTxAction( @Nonnull final SafeProcedure executable )
{
final Transaction current = Transaction.current();
Transaction.suspend( current );
try
{
executable.call();
}
finally
{
Transaction.resume( current );
}
}
/**
* Execute the specified action outside of a transaction.
* The transaction is suspended for the duration of the action and the action must not
* attempt to create a nested transaction.
*
* @param <T> the type of return value.
* @param executable the executable.
* @return the value returned from the executable.
*/
public <T> T safeNoTxAction( @Nonnull final SafeFunction<T> executable )
{
final Transaction current = Transaction.current();
Transaction.suspend( current );
try
{
return executable.call();
}
finally
{
Transaction.resume( current );
}
}
/**
* Return next transaction id and increment internal counter.
* The id is a monotonically increasing number starting at 1.
*
* @return the next transaction id.
*/
int nextTransactionId()
{
return _nextTransactionId++;
}
/**
* Register an entity locator to use to resolve references.
* The Locator must not already be registered.
* This should not be invoked unless Arez.areReferencesEnabled() returns true.
*
* @param locator the Locator to register.
* @return the disposable to dispose to deregister locator.
*/
@Nonnull
public Disposable registerLocator( @Nonnull final Locator locator )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( Arez::areReferencesEnabled,
() -> "Arez-0191: ArezContext.registerLocator invoked but Arez.areReferencesEnabled() returned false." );
}
assert null != _locator;
return _locator.registerLocator( Objects.requireNonNull( locator ) );
}
/**
* Return the locator that can be used to resolve references.
* This should not be invoked unless Arez.areReferencesEnabled() returns true.
*
* @return the Locator.
*/
@Nonnull
public Locator locator()
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( Arez::areReferencesEnabled,
() -> "Arez-0192: ArezContext.locator() invoked but Arez.areReferencesEnabled() returned false." );
}
assert null != _locator;
return _locator;
}
/**
* Add error handler to the list of error handlers called.
* The handler should not already be in the list. This method should NOT be called if
* {@link Arez#areObserverErrorHandlersEnabled()} returns false.
*
* @param handler the error handler.
*/
public void addObserverErrorHandler( @Nonnull final ObserverErrorHandler handler )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areObserverErrorHandlersEnabled,
() -> "Arez-0182: ArezContext.addObserverErrorHandler() invoked when Arez.areObserverErrorHandlersEnabled() returns false." );
}
assert null != _observerErrorHandlerSupport;
_observerErrorHandlerSupport.addObserverErrorHandler( handler );
}
/**
* Remove error handler from list of existing error handlers.
* The handler should already be in the list. This method should NOT be called if
* {@link Arez#areObserverErrorHandlersEnabled()} returns false.
*
* @param handler the error handler.
*/
public void removeObserverErrorHandler( @Nonnull final ObserverErrorHandler handler )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areObserverErrorHandlersEnabled,
() -> "Arez-0181: ArezContext.removeObserverErrorHandler() invoked when Arez.areObserverErrorHandlersEnabled() returns false." );
}
assert null != _observerErrorHandlerSupport;
_observerErrorHandlerSupport.removeObserverErrorHandler( handler );
}
/**
* Report an error in observer.
*
* @param observer the observer that generated error.
* @param error the type of the error.
* @param throwable the exception that caused error if any.
*/
void reportObserverError( @Nonnull final Observer observer,
@Nonnull final ObserverError error,
@Nullable final Throwable throwable )
{
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ObserverErrorEvent( new ObserverInfoImpl( getSpy(), observer ), error, throwable ) );
}
if ( Arez.areObserverErrorHandlersEnabled() )
{
assert null != _observerErrorHandlerSupport;
_observerErrorHandlerSupport.onObserverError( observer, error, throwable );
}
}
/**
* Return true if spy events will be propagated.
* This means spies are enabled and there is at least one spy event handler present.
*
* @return true if spy events will be propagated, false otherwise.
*/
boolean willPropagateSpyEvents()
{
return Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents();
}
/**
* Return the spy associated with context.
* This method should not be invoked unless {@link Arez#areSpiesEnabled()} returns true.
*
* @return the spy associated with context.
*/
@Nonnull
public Spy getSpy()
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( Arez::areSpiesEnabled, () -> "Arez-0021: Attempting to get Spy but spies are not enabled." );
}
assert null != _spy;
return _spy;
}
/**
* Verify the action reads or writes to observables occur within scope of
* action if the verifyActionRequired parameter is true.
*
* @param transaction the associated transaction.
* @param name the action name.
* @param verifyActionRequired if true then attempt validation.
*/
private void verifyActionRequired( @Nonnull final Transaction transaction,
@Nullable final String name,
final boolean verifyActionRequired )
{
if ( Arez.shouldCheckInvariants() && verifyActionRequired )
{
invariant( transaction::hasReadOrWriteOccurred,
() -> "Arez-0185: Action named '" + name + "' completed but no reads or writes " +
"occurred within the scope of the action." );
}
}
/**
* Convert flag to appropriate transaction mode.
*
* @param mutation true if the transaction may modify state, false otherwise.
* @return the READ_WRITE transaction mode if mutation is true else READ_ONLY.
*/
@Nullable
private TransactionMode mutationToTransactionMode( final boolean mutation )
{
return Arez.shouldEnforceTransactionType() ?
( mutation ? TransactionMode.READ_WRITE : TransactionMode.READ_ONLY ) :
null;
}
void registerObservableValue( @Nonnull final ObservableValue observableValue )
{
final String name = observableValue.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0022: ArezContext.registerObservableValue invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _observables;
invariant( () -> !_observables.containsKey( name ),
() -> "Arez-0023: ArezContext.registerObservableValue invoked with observableValue named '" + name +
"' but an existing observableValue with that name is already registered." );
}
assert null != _observables;
_observables.put( name, observableValue );
}
void deregisterObservableValue( @Nonnull final ObservableValue observableValue )
{
final String name = observableValue.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0024: ArezContext.deregisterObservableValue invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _observables;
invariant( () -> _observables.containsKey( name ),
() -> "Arez-0025: ArezContext.deregisterObservableValue invoked with observableValue named '" + name +
"' but no observableValue with that name is registered." );
}
assert null != _observables;
_observables.remove( name );
}
@Nonnull
HashMap<String, ObservableValue<?>> getTopLevelObservables()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0026: ArezContext.getTopLevelObservables() invoked when Arez.areRegistriesEnabled() returns false." );
}
assert null != _observables;
return _observables;
}
void registerObserver( @Nonnull final Observer observer )
{
final String name = observer.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0027: ArezContext.registerObserver invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _observers;
invariant( () -> !_observers.containsKey( name ),
() -> "Arez-0028: ArezContext.registerObserver invoked with observer named '" + name +
"' but an existing observer with that name is already registered." );
}
assert null != _observers;
_observers.put( name, observer );
}
void deregisterObserver( @Nonnull final Observer observer )
{
final String name = observer.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0029: ArezContext.deregisterObserver invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _observers;
invariant( () -> _observers.containsKey( name ),
() -> "Arez-0030: ArezContext.deregisterObserver invoked with observer named '" + name +
"' but no observer with that name is registered." );
}
assert null != _observers;
_observers.remove( name );
}
@Nonnull
HashMap<String, Observer> getTopLevelObservers()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0031: ArezContext.getTopLevelObservers() invoked when Arez.areRegistriesEnabled() returns false." );
}
assert null != _observers;
return _observers;
}
void registerComputedValue( @Nonnull final ComputedValue computedValue )
{
final String name = computedValue.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0032: ArezContext.registerComputedValue invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _computedValues;
invariant( () -> !_computedValues.containsKey( name ),
() -> "Arez-0033: ArezContext.registerComputedValue invoked with computed value named '" + name +
"' but an existing computed value with that name is already registered." );
}
assert null != _computedValues;
_computedValues.put( name, computedValue );
}
void deregisterComputedValue( @Nonnull final ComputedValue computedValue )
{
final String name = computedValue.getName();
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0034: ArezContext.deregisterComputedValue invoked when Arez.areRegistriesEnabled() returns false." );
assert null != _computedValues;
invariant( () -> _computedValues.containsKey( name ),
() -> "Arez-0035: ArezContext.deregisterComputedValue invoked with computed value named '" + name +
"' but no computed value with that name is registered." );
}
assert null != _computedValues;
_computedValues.remove( name );
}
@Nonnull
HashMap<String, ComputedValue<?>> getTopLevelComputedValues()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areRegistriesEnabled,
() -> "Arez-0036: ArezContext.getTopLevelComputedValues() invoked when Arez.areRegistriesEnabled() returns false." );
}
assert null != _computedValues;
return _computedValues;
}
@Nonnull
ObserverErrorHandlerSupport getObserverErrorHandlerSupport()
{
assert null != _observerErrorHandlerSupport;
return _observerErrorHandlerSupport;
}
int currentNextTransactionId()
{
return _nextTransactionId;
}
@Nonnull
ReactionScheduler getScheduler()
{
return _scheduler;
}
void setNextNodeId( final int nextNodeId )
{
_nextNodeId = nextNodeId;
}
int getNextNodeId()
{
return _nextNodeId;
}
int getSchedulerLockCount()
{
return _schedulerLockCount;
}
@SuppressWarnings( "SameParameterValue" )
void setSchedulerLockCount( final int schedulerLockCount )
{
_schedulerLockCount = schedulerLockCount;
}
void markSchedulerAsActive()
{
_schedulerActive = true;
}
}
|
package mars.auvtree.nodes;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import java.awt.Image;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.AbstractAction;
import javax.swing.Action;
import static javax.swing.Action.NAME;
import javax.swing.GrayFilter;
import mars.MARS_Main;
import mars.PhysicalExchange.AUVObject;
import mars.PhysicalExchange.Manipulating;
import mars.PhysicalExchange.PhysicalExchanger;
import mars.accumulators.Accumulator;
import mars.actuators.Actuator;
import mars.actuators.Lamp;
import mars.actuators.Teleporter;
import mars.actuators.servos.Servo;
import mars.actuators.thruster.Thruster;
import mars.actuators.visualizer.VectorVisualizer;
import mars.auv.AUV_Parameters;
import mars.auvtree.TreeUtil;
import mars.core.CentralLookup;
import mars.core.MARSChartTopComponent;
import mars.core.MARSUnderwaterModemTopComponent;
import mars.core.MARSVideoCameraTopComponent;
import mars.core.RayBasedSensorTopComponent;
import mars.gui.PropertyEditors.ColorPropertyEditor;
import mars.gui.PropertyEditors.Vector3fPropertyEditor;
import mars.gui.sonarview.PlanarView;
import mars.gui.sonarview.PolarView;
import mars.misc.PropertyChangeListenerSupport;
import mars.sensors.AmpereMeter;
import mars.sensors.CommunicationDevice;
import mars.sensors.FlowMeter;
import mars.sensors.GPSReceiver;
import mars.sensors.Gyroscope;
import mars.sensors.IMU;
import mars.sensors.PingDetector;
import mars.sensors.PollutionMeter;
import mars.sensors.PressureSensor;
import mars.sensors.RayBasedSensor;
import mars.sensors.Sensor;
import mars.sensors.TemperatureSensor;
import mars.sensors.TerrainSender;
import mars.sensors.UnderwaterModem;
import mars.sensors.VideoCamera;
import mars.sensors.VoltageMeter;
import mars.sensors.WiFi;
import mars.sensors.sonar.Sonar;
import org.openide.ErrorManager;
import org.openide.actions.CopyAction;
import org.openide.actions.DeleteAction;
import org.openide.actions.RenameAction;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.Exceptions;
import org.openide.util.HelpCtx;
import org.openide.util.actions.SystemAction;
import org.openide.util.datatransfer.ExTransferable;
import org.openide.util.datatransfer.PasteType;
import org.openide.util.lookup.Lookups;
/**
* This class is the presentation for actuators, accumulators and sensors of an
* auv.
*
* @author Christian Friedrich
* @author Thomas Tosik
*/
public class PhysicalExchangerNode extends AbstractNode implements PropertyChangeListener {
/**
* Object which is representated by the node
*/
private Object obj;
/**
* Hashmap with paramaeters of object.
*/
private HashMap params;
/**
* Hashmap with noise paramaeters of object.
*/
private HashMap noise;
private ArrayList slavesNames;
/**
* Name of the image file on the harddisk.
*/
private String icon = "question-white.png";
/**
* Displayname of the node.
*/
private String nodeName;
/**
* This is constructor is called to create a node for an attachement.
*
* @param obj This can be an accumulator, actuator or a sensor
* @param nodeName
*/
public PhysicalExchangerNode(Object obj, String nodeName) {
// initially this node is asumed to be a leaf
super(Children.LEAF, Lookups.singleton(obj));
this.nodeName = nodeName;
this.obj = obj;
// depending on type of object cast it and get its variables
if (obj instanceof Accumulator) {
params = ((Accumulator) (obj)).getAllVariables();
icon = "battery_charge.png";
} else if (obj instanceof Actuator) {
params = ((Actuator) (obj)).getAllVariables();
noise = ((Actuator) (obj)).getAllNoiseVariables();
if (obj instanceof Manipulating) {
slavesNames = ((Manipulating) (obj)).getSlavesNames();
}
icon = ((Actuator) (obj)).getIcon();
} else if (obj instanceof Sensor) {
params = ((Sensor) (obj)).getAllVariables();
noise = ((Sensor) (obj)).getAllNoiseVariables();
if (obj instanceof AmpereMeter) {
}
if (obj instanceof Manipulating) {
slavesNames = ((Manipulating) (obj)).getSlavesNames();
}
icon = ((Sensor) (obj)).getIcon();
} else if (obj instanceof AUV_Parameters) {
params = ((AUV_Parameters) (obj)).getAllVariables();
}
//no icon set, use default one
if (icon == null) {
if (obj instanceof Sonar) {
icon = "radar.png";
} else if (obj instanceof VideoCamera) {
icon = "cctv_camera.png";
} else if (obj instanceof PingDetector) {
icon = "microphone.png";
} else if (obj instanceof IMU) {
icon = "compass.png";
} else if (obj instanceof TemperatureSensor) {
icon = "thermometer.png";
} else if (obj instanceof Gyroscope) {
icon = "transform_rotate.png";
} else if (obj instanceof PressureSensor) {
icon = "transform_perspective.png";
} else if (obj instanceof TerrainSender) {
icon = "soil_layers.png";
} else if (obj instanceof Thruster) {
icon = "thruster_seabotix.png";
} else if (obj instanceof VectorVisualizer) {
icon = "arrow_up.png";
} else if (obj instanceof Servo) {
icon = "AX-12.png";
} else if (obj instanceof UnderwaterModem) {
icon = "speaker-volume.png";
} else if (obj instanceof WiFi) {
icon = "radio_2.png";
} else if (obj instanceof Lamp) {
icon = "flashlight-shine.png";
} else if (obj instanceof GPSReceiver) {
icon = "satellite.png";
} else if (obj instanceof Lamp) {
icon = "flashlight-shine.png";
} else if (obj instanceof VoltageMeter) {
icon = "battery_charge.png";
} else if (obj instanceof AmpereMeter) {
icon = "battery_charge.png";
} else if (obj instanceof FlowMeter) {
icon = "breeze_small.png";
} else if (obj instanceof Teleporter) {
icon = "transform_move.png";
} else if (obj instanceof PollutionMeter) {
icon = "oil-barrel.png";
} else {//last resort
icon = "question-white.png";
}
}
// create subchilds
// don't show them currently, because one has to use the property window
//when you want to activate it you need addtional code:
/*if (params != null && !params.isEmpty()) {
setChildren(Children.create(new ParamChildNodeFactory(params), true));
}*/
setDisplayName(nodeName);
setShortDescription(obj.getClass().toString());
}
/**
* This method returns the image icon.
*
* @param type
* @return Icon which will be displayed.
*/
@Override
public Image getIcon(int type) {
AUVObject auvObject = getLookup().lookup(AUVObject.class);
if (auvObject == null || auvObject.getEnabled()) {
return TreeUtil.getImage(icon);
} else {
return GrayFilter.createDisabledImage(TreeUtil.getImage(icon));
}
}
/**
* Loads image which is displayed next to a opened node.
*
* @param type
* @return Returns image which is loaded with getImage()
* @see also TreeUtil.getImage()
*/
@Override
public Image getOpenedIcon(int type) {
AUVObject auvObject = getLookup().lookup(AUVObject.class);
if (auvObject == null || auvObject.getEnabled()) {
return TreeUtil.getImage(icon);
} else {
return GrayFilter.createDisabledImage(TreeUtil.getImage(icon));
}
}
/**
* Returns the string which is displayed in the tree. Node name is used
* here.
*
* @return Returns node name.
*/
@Override
public String getDisplayName() {
return nodeName;
}
/**
*
* @return
*/
@Override
public boolean canDestroy() {
return true;
}
/**
*
* @return
*/
@Override
public boolean canRename() {
return true;
}
/**
*
* @return
*/
@Override
public boolean canCopy() {
return true;
}
@Override
public void setName(String s) {
final String oldName = this.nodeName;
this.nodeName = s;
PhysicalExchanger pe = getLookup().lookup(PhysicalExchanger.class);
pe.getAuv().updatePhysicalExchangerName(oldName, s);
fireDisplayNameChange(oldName, s);
fireNameChange(oldName, s);
}
/**
* This method generates the properties for the property sheet. It adds an
* property change listener for each displayed property. This is used to
* update the property sheet when values in an external editor are adjusted.
*
* @return Returns instance of sheet.
*/
@Override
protected Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
obj = getLookup().lookup(PhysicalExchanger.class);
if (obj == null) {//i know, its hacky at the moment. should use multiple lookup. or an common interface for all interesting objects
obj = getLookup().lookup(Accumulator.class);
}
if (obj == null) {//i know, its hacky at the moment. should use multiple lookup. or an common interface for all interesting objects
obj = getLookup().lookup(Manipulating.class);
}
if (obj == null) {//i know, its hacky at the moment. should use multiple lookup. or an common interface for all interesting objects
obj = getLookup().lookup(AUV_Parameters.class);
}
if (obj == null) {//i know, its hacky at the moment. should use multiple lookup. or an common interface for all interesting objects
obj = getLookup().lookup(HashMap.class);
}
if (params != null) {
createPropertiesSet(obj, params, "Properties", false, sheet);
}
if (noise != null) {
createPropertiesSet(obj, noise, "Noise", true, sheet);
}
if (slavesNames != null) {
sheet.put(createPropertiesSet(obj, slavesNames, "Slaves", true));
}
// add listener to react of changes from external editors (AUVEditor)
if (params != null) {
((PropertyChangeListenerSupport) (obj)).addPropertyChangeListener(this);
}
return sheet;
}
private void createPropertiesSet(Object obj, HashMap params, String displayName, boolean expert, Sheet sheet) {
Sheet.Set set;
if (expert) {
set = Sheet.createExpertSet();
} else {
set = Sheet.createPropertiesSet();
}
set.setDisplayName(displayName);
set.setName(displayName);
sheet.put(set);
Property prop;
String name;
SortedSet<String> sortedset = new TreeSet<String>(params.keySet());
for (Iterator<String> it2 = sortedset.iterator(); it2.hasNext();) {
String key = it2.next();
Object value = params.get(key);
if (value instanceof HashMap) {//make a new set
Sheet.Set setHM = Sheet.createExpertSet();
HashMap hasher = (HashMap) value;
SortedSet<String> sortedset2 = new TreeSet<String>(hasher.keySet());
for (Iterator<String> it3 = sortedset2.iterator(); it3.hasNext();) {
String key2 = it3.next();
Object value2 = hasher.get(key2);
String namehm = key + key2.substring(0, 1).toUpperCase() + key2.substring(1);
try {
Property prophm = new PropertySupport.Reflection(obj, value2.getClass(), namehm);
// set custom property editor for position and rotation params
if (value2 instanceof Vector3f) {
((PropertySupport.Reflection) (prophm)).setPropertyEditorClass(Vector3fPropertyEditor.class);
} else if (value2 instanceof ColorRGBA) {
((PropertySupport.Reflection) (prophm)).setPropertyEditorClass(ColorPropertyEditor.class);
}
prophm.setName(key2);
setHM.put(prophm);
} catch (NoSuchMethodException ex) {
ErrorManager.getDefault();
}
}
setHM.setDisplayName(key);
setHM.setName(key);
sheet.put(setHM);
} else {//ueber set (properties)
name = key.substring(0, 1).toUpperCase() + key.substring(1);
try {
prop = new PropertySupport.Reflection(obj, value.getClass(), name);
// set custom property editor for position and rotation params
if (value instanceof Vector3f) {
((PropertySupport.Reflection) (prop)).setPropertyEditorClass(Vector3fPropertyEditor.class);
} else if (value instanceof ColorRGBA) {
((PropertySupport.Reflection) (prop)).setPropertyEditorClass(ColorPropertyEditor.class);
}
prop.setName(name);
prop.setShortDescription("test lirum ipsum");
set.put(prop);
} catch (NoSuchMethodException ex) {
ErrorManager.getDefault();
}
}
}
}
private Sheet.Set createPropertiesSet(Object obj, ArrayList params, String displayName, boolean expert) {
Sheet.Set set;
if (expert) {
set = Sheet.createExpertSet();
} else {
set = Sheet.createPropertiesSet();
}
Property prop;
String name;
for (Iterator it = params.iterator(); it.hasNext();) {
String slaveName = (String) it.next();
try {
prop = new PropertySupport.Reflection(obj, String.class, "SlavesNames");
prop.setName(slaveName);
set.put(prop);
} catch (NoSuchMethodException ex) {
Exceptions.printStackTrace(ex);
}
}
/*Iterator<Map.Entry<String, Object>> i = params.entrySet().iterator();
for (; i.hasNext();) {
Map.Entry<String, Object> mE = i.next();
if (!mE.getKey().isEmpty()) {
name = mE.getKey().substring(0, 1).toUpperCase() + mE.getKey().substring(1);
try {
prop = new PropertySupport.Reflection(obj, mE.getValue().getClass(), "getSlavesNames");
// set custom property editor for position and rotation params
if (mE.getValue() instanceof Vector3f) {
((PropertySupport.Reflection) (prop)).setPropertyEditorClass(Vector3fPropertyEditor.class);
} else if (mE.getValue() instanceof ColorRGBA) {
((PropertySupport.Reflection) (prop)).setPropertyEditorClass(ColorPropertyEditor.class);
}
prop.setName(name);
set.put(prop);
} catch (NoSuchMethodException ex) {
ErrorManager.getDefault();
}
}
}*/
set.setDisplayName(displayName);
return set;
}
/**
* This listerner is called on property changes. It updates the Property
* Sheet to display adjusted values.
*
* @param evt
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
this.fireDisplayNameChange(null, getDisplayName());
this.fireIconChange();
if ("Position".equals(evt.getPropertyName()) || "Rotation".equals(evt.getPropertyName())) {
setSheet(getSheet());
} else if ("enabled".equals(evt.getPropertyName())) {
AUVNode parentNode = (AUVNode) getParentNode().getParentNode();
parentNode.updateName();
}
}
/**
*
* @throws IOException
*/
@Override
public void destroy() throws IOException {
PhysicalExchanger pe = getLookup().lookup(PhysicalExchanger.class);
pe.getAuv().deregisterPhysicalExchanger(pe);
fireNodeDestroyed();
}
/**
*
* @return
* @throws IOException
*/
@Override
public Transferable clipboardCopy() throws IOException {
Transferable deflt = super.clipboardCopy();
ExTransferable added = ExTransferable.create(deflt);
added.put(new ExTransferable.Single(PhysicalExchangerFlavor.CUSTOMER_FLAVOR) {
@Override
protected PhysicalExchanger getData() {
return getLookup().lookup(PhysicalExchanger.class);
}
});
return added;
}
/**
* This one is overridden to define left click actions.
*
* @param popup
*
* @return Returns array of Actions.
*/
@Override
public Action[] getActions(boolean popup) {
if (obj instanceof VideoCamera) {
return new Action[]{new ViewCameraAction(this), new EnableAction(), SystemAction.get(RenameAction.class), SystemAction.get(DeleteAction.class),SystemAction.get(CopyAction.class)};
} else if (obj instanceof RayBasedSensor) {
return new Action[]{new SonarPlanarAction(), new SonarPolarAction(), new EnableAction(), SystemAction.get(RenameAction.class), SystemAction.get(DeleteAction.class),SystemAction.get(CopyAction.class)};
} else if (obj instanceof CommunicationDevice) {
return new Action[]{new ViewCommunicationAction(), new EnableAction(), SystemAction.get(RenameAction.class), SystemAction.get(DeleteAction.class),SystemAction.get(CopyAction.class)};
} else if (obj instanceof Sensor) {
return new Action[]{new DataChartAction(), new EnableAction(), SystemAction.get(RenameAction.class), SystemAction.get(DeleteAction.class),SystemAction.get(CopyAction.class)};
} else {
return new Action[]{new EnableAction(), SystemAction.get(RenameAction.class), SystemAction.get(DeleteAction.class),SystemAction.get(CopyAction.class)};
}
}
/**
*
* @return
*/
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(obj.getClass().getCanonicalName());
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class EnableAction extends AbstractAction {
public EnableAction() {
super();
if (obj instanceof AUVObject) {
AUVObject auvObject = (AUVObject) obj;
if (auvObject.getEnabled()) {
putValue(NAME, "Disable");
} else {
putValue(NAME, "Enable");
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
AUVObject auvObject = getLookup().lookup(AUVObject.class);
boolean peEnabled = auvObject.getEnabled();
auvObject.setEnabled(!peEnabled);
propertyChange(new PropertyChangeEvent(this, "enabled", !peEnabled, peEnabled));
//JOptionPane.showMessageDialog(null, "Done!");
}
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class SonarPolarAction extends AbstractAction {
public SonarPolarAction() {
super();
putValue(NAME, "View Sonar Data [Polar]");
}
@Override
public void actionPerformed(ActionEvent e) {
RayBasedSensor lookup = getLookup().lookup(RayBasedSensor.class);
if (lookup != null) {
//propertyChange(new PropertyChangeEvent(this, "enabled", !auvEnabled, auvEnabled));
RayBasedSensorTopComponent win = new RayBasedSensorTopComponent();
//sonarFrame.setSize(2*252+300, 2*252);
final PolarView imgP = new PolarView(lookup);
win.addRayBasedView(imgP);
win.setName("Polar View");
win.open();
win.requestActive();
win.repaint();
//rayBasedSensorList.put(lookup.getName(), imgP);
win.setName("Polar View of: " + lookup.getName());
}
}
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class SonarPlanarAction extends AbstractAction {
public SonarPlanarAction() {
super();
putValue(NAME, "View Sonar Data [Planar]");
}
@Override
public void actionPerformed(ActionEvent e) {
RayBasedSensor lookup = getLookup().lookup(RayBasedSensor.class);
if (lookup != null) {
//propertyChange(new PropertyChangeEvent(this, "enabled", !auvEnabled, auvEnabled));
RayBasedSensorTopComponent win = new RayBasedSensorTopComponent();
//sonarFrame.setSize(400+300, 252);
final PlanarView imgP = new PlanarView(lookup);
win.addRayBasedView(imgP);
win.setName("Planar View");
win.open();
win.requestActive();
win.repaint();
//rayBasedSensorList.put(lookup.getName(), imgP);
win.setName("Planar View of: " + lookup.getName());
}
}
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class DataChartAction extends AbstractAction {
public DataChartAction() {
super();
putValue(NAME, "Add Data to Chart");
}
@Override
public void actionPerformed(ActionEvent e) {
//propertyChange(new PropertyChangeEvent(this, "enabled", !auvEnabled, auvEnabled));
Sensor sens = getLookup().lookup(Sensor.class);
if (sens != null) {
MARSChartTopComponent chart = new MARSChartTopComponent(sens);
chart.setName("Chart of: " + "...");
chart.open();
chart.requestActive();
chart.repaint();
}
}
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class ViewCameraAction extends AbstractAction {
private PhysicalExchangerNode pen;
public ViewCameraAction(PhysicalExchangerNode pen) {
super();
this.pen = pen;
putValue(NAME, "View Camera Data");
}
@Override
public void actionPerformed(ActionEvent e) {
//propertyChange(new PropertyChangeEvent(this, "enabled", !auvEnabled, auvEnabled));
VideoCamera lookup = getLookup().lookup(VideoCamera.class);
CentralLookup cl = CentralLookup.getDefault();
MARS_Main mars = cl.lookup(MARS_Main.class);
if (lookup != null) {
MARSVideoCameraTopComponent video = new MARSVideoCameraTopComponent(lookup, mars);
pen.addNodeListener(video);
video.setName("Video of: " + lookup.getName());
video.open();
video.requestActive();
video.repaint();
}
}
}
/**
* Inner class for the actions on right click. Provides action to enable and
* disable an auv.
*/
private class ViewCommunicationAction extends AbstractAction {
public ViewCommunicationAction() {
super();
putValue(NAME, "View Communication Device");
}
@Override
public void actionPerformed(ActionEvent e) {
//propertyChange(new PropertyChangeEvent(this, "enabled", !auvEnabled, auvEnabled));
CommunicationDevice lookup = getLookup().lookup(CommunicationDevice.class);
if (lookup != null) {
MARSUnderwaterModemTopComponent uw = new MARSUnderwaterModemTopComponent(lookup);
uw.setName("Data of: " + lookup.getAuv().getName() + "/" + lookup.getName());
uw.open();
uw.requestActive();
uw.repaint();
}
}
}
}
|
package org.jetel.data.parser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.StringDataField;
import org.jetel.data.formatter.BinaryDataFormatter;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.IParserExceptionHandler;
import org.jetel.exception.JetelException;
import org.jetel.exception.PolicyType;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.bytes.ByteBufferUtils;
public class BinaryDataParser implements Parser {
ReadableByteChannel reader;
/*
* just remember the inputstream we used to create "reader" channel
*/
InputStream backendStream;
DataRecordMetadata metaData;
ByteBuffer buffer;
IParserExceptionHandler exceptionHandler;
/*
* aux variable
*/
int recordSize;
/*
* Size of read buffer
*/
int bufferLimit = -1;
/*
* Charset name of serialized string field
*/
String stringCharset;
/*
* Decoder instance
*/
CharsetDecoder stringDecoder;
/*
* temp char buffer
*/
CharBuffer charBuffer;
/*
* Whether an attempt to delete file from the underlying should be made on close()
*/
File deleteOnClose;
boolean useDirectBuffers = true;
private final static int LEN_SIZE_SPECIFIER = 4;
private boolean eofReached;
public BinaryDataParser() {
}
public BinaryDataParser(int bufferLimit) {
setBufferLimit(bufferLimit);
}
public int getBufferLimit() {
return bufferLimit;
}
public void setBufferLimit(int bufferLimit) {
this.bufferLimit = bufferLimit;
}
public BinaryDataParser(InputStream inputStream) {
try {
setDataSource(inputStream);
} catch (ComponentNotReadyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public BinaryDataParser(InputStream inputStream, int bufferLimit) {
this(inputStream);
this.bufferLimit = bufferLimit;
}
public BinaryDataParser(File file) {
try {
setDataSource(file);
} catch (ComponentNotReadyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close() {
if (reader != null && reader.isOpen()) {
try {
reader.close();
if (backendStream != null) {
backendStream.close();
}
if (deleteOnClose != null) {
deleteOnClose.delete();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
buffer.clear();
buffer.limit(0);
}
public IParserExceptionHandler getExceptionHandler() {
return this.exceptionHandler;
}
public DataRecord getNext() throws JetelException {
DataRecord record = new DataRecord(metaData);
record.init();
return getNext(record);
}
public DataRecord getNext(DataRecord record) throws JetelException {
try {
if (LEN_SIZE_SPECIFIER > buffer.remaining()) {
reloadBuffer(LEN_SIZE_SPECIFIER);
if (buffer.remaining() == 0) {
return null; //correct end of stream
}
}
recordSize = ByteBufferUtils.decodeLength(buffer);
// check that internal buffer has enough data to read data record
if (recordSize > buffer.remaining()) {
reloadBuffer(recordSize);
if (recordSize > buffer.remaining()) {
throw new JetelException("Invalid end of data stream.");
}
}
if (stringCharset == null) {
record.deserialize(buffer);
} else {
deserialize(record, buffer);
}
return record;
} catch (IOException e) {
throw new JetelException("IO exception", e);
} catch (BufferUnderflowException e) {
throw new JetelException("Invalid end of stream.", e);
}
}
public void deserialize(DataRecord record, ByteBuffer buffer) {
DataField field;
for(int i = 0; i < record.getNumFields(); i++) {
field = record.getField(i);
if (field instanceof StringDataField) {
deserialize((StringDataField) field, buffer);
} else {
field.deserialize(buffer);
}
}
}
public void deserialize(StringDataField field, ByteBuffer buffer) {
final int length=ByteBufferUtils.decodeLength(buffer);
StringBuilder value = (StringBuilder) field.getValue();
value.setLength(0);
if (length == 0) {
field.setNull(true);
} else {
field.setNull(false);
int curLimit = buffer.limit();
buffer.limit(buffer.position() + length);
charBuffer.clear();
stringDecoder.decode(buffer, charBuffer, true);
buffer.limit(curLimit);
charBuffer.flip();
value.append(charBuffer);
}
}
private void reloadBuffer(int requiredSize) throws IOException {
if (eofReached) {
return;
}
int size;
buffer.compact();
do {
size = reader.read(buffer);
if (buffer.position() > requiredSize) {
break;
}
//data are not available, so let the other thread work now, we need to wait for a while
//unfortunately, the read() method is non-blocking and easily returns no bytes
Thread.yield();
} while (size != -1);
if (size == -1) {
eofReached = true;
}
buffer.flip();
}
public PolicyType getPolicyType() {
return null;
}
public Object getPosition() {
return null;
}
public void init(DataRecordMetadata _metadata) throws ComponentNotReadyException {
if (_metadata == null) {
throw new ComponentNotReadyException("Metadata cannot be null");
}
this.metaData = _metadata;
int buffSize = bufferLimit > 0 ? Math.min(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE, bufferLimit) : Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE;
buffer = useDirectBuffers ? ByteBuffer.allocateDirect(buffSize) : ByteBuffer.allocate(buffSize);
// buffer = ByteBuffer.allocate(buffSize); // for memory consumption testing
buffer.clear();
buffer.limit(0);
eofReached = false;
}
public void init(DataRecordMetadata _metadata, String charsetName) throws ComponentNotReadyException {
init(_metadata);
setStringCharset(charsetName);
}
public DataRecordMetadata getMetadata() {
return this.metaData;
}
public void movePosition(Object position) throws IOException {
}
public void reset() throws ComponentNotReadyException {
buffer.clear();
buffer.limit(0);
close();
if (backendStream != null) {
reader = Channels.newChannel(backendStream);
}
eofReached = false;
}
public void setDataSource(Object inputDataSource) throws ComponentNotReadyException {
if (inputDataSource instanceof File) {
try {
backendStream = new FileInputStream((File) inputDataSource);
reader = Channels.newChannel(backendStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (inputDataSource instanceof InputStream) {
backendStream = (InputStream) inputDataSource;
reader = Channels.newChannel(backendStream);
}
}
public void setExceptionHandler(IParserExceptionHandler handler) {
this.exceptionHandler = handler;
}
public void setReleaseDataSource(boolean releaseInputSource) {
// TODO Auto-generated method stub
}
public int skip(int rec) throws JetelException {
// TODO Auto-generated method stub
return 0;
}
public String getStringCharset() {
return stringCharset;
}
public void setStringCharset(String stringCharset) {
if (stringCharset != null && (! Defaults.Record.USE_FIELDS_NULL_INDICATORS || ! getMetadata().isNullable())) {
this.stringCharset = stringCharset;
stringDecoder = Charset.forName(stringCharset).newDecoder();
charBuffer = CharBuffer.allocate(Defaults.DataParser.FIELD_BUFFER_LENGTH);
} else {
this.stringCharset = null;
stringDecoder = null;
charBuffer = null;
}
}
public InputStream getBackendStream() {
return backendStream;
}
public File getDeleteOnClose() {
return deleteOnClose;
}
public void setDeleteOnClose(File deleteOnClose) {
this.deleteOnClose = deleteOnClose;
}
public boolean isUseDirectBuffers() {
return useDirectBuffers;
}
public void setUseDirectBuffers(boolean useDirectBuffers) {
this.useDirectBuffers = useDirectBuffers;
}
}
|
package org.jetel.data.lookup;
import java.io.IOException;
import java.util.Random;
import org.jetel.data.DataRecord;
import org.jetel.data.RecordKey;
import org.jetel.data.parser.Parser;
import org.jetel.main.runGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import junit.framework.TestCase;
public class RangeLookupTest extends TestCase {
LookupTable lookup,lookupNotOverlap;
DataRecordMetadata lookupMetadata, metadata;
DataRecord record;
Random random = new Random();
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
runGraph.initEngine(null, null);
lookupMetadata = new DataRecordMetadata("lookupTest",DataRecordMetadata.DELIMITED_RECORD);
lookupMetadata.addField(new DataFieldMetadata("name",DataFieldMetadata.STRING_FIELD,";"));
lookupMetadata.addField(new DataFieldMetadata("start",DataFieldMetadata.INTEGER_FIELD,";"));
lookupMetadata.addField(new DataFieldMetadata("end",DataFieldMetadata.INTEGER_FIELD,";"));
lookupMetadata.addField(new DataFieldMetadata("start1",DataFieldMetadata.INTEGER_FIELD,";"));
lookupMetadata.addField(new DataFieldMetadata("end1",DataFieldMetadata.INTEGER_FIELD,";"));
lookup = LookupTableFactory.createLookupTable(null, "rangeLookup",
new Object[]{"RangeLookup",lookupMetadata,null},
new Class[]{String.class,DataRecordMetadata.class,Parser.class});
lookupNotOverlap = LookupTableFactory.createLookupTable(null, "rangeLookup",
new Object[]{"RangeLookup",lookupMetadata,null},
new Class[]{String.class,DataRecordMetadata.class,Parser.class});
lookup.init();
lookupNotOverlap.init();
record = new DataRecord(lookupMetadata);
record.init();
record.getField("name").setValue("10-20,100-200");
record.getField("start").setValue(10);
record.getField("end").setValue(20);
record.getField("start1").setValue(100);
record.getField("end1").setValue(200);
lookup.put(record, record.duplicate());
record.getField("name").setValue("20-30,0-100");
record.getField("start").setValue(20);
record.getField("end").setValue(30);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookup.put(record, record.duplicate());
record.getField("name").setValue("20-30,100-200");
record.getField("start").setValue(20);
record.getField("end").setValue(30);
record.getField("start1").setValue(100);
record.getField("end1").setValue(200);
lookup.put(record, record.duplicate());
record.getField("name").setValue("30-40,0-100");
record.getField("start").setValue(30);
record.getField("end").setValue(40);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookup.put(record, record.duplicate());
record.getField("name").setValue("30-40,100-200");
record.getField("start").setValue(30);
record.getField("end").setValue(40);
record.getField("start1").setValue(100);
record.getField("end1").setValue(200);
lookup.put(record, record.duplicate());
record.getField("name").setValue("0-10,0-100");
record.getField("start").setValue(0);
record.getField("end").setValue(10);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookup.put(record, record.duplicate());
record.getField("name").setValue("0-10,100-200");
record.getField("start").setValue(0);
record.getField("start1").setValue(100);
record.getField("end").setValue(10);
record.getField("end1").setValue(200);
lookup.put(record, record.duplicate());
record.getField("name").setValue("10-20,0-100");
record.getField("start").setValue(10);
record.getField("end").setValue(20);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookup.put(record, record.duplicate());
record.getField("name").setValue("10-20,100-200");
record.getField("start").setValue(11);
record.getField("end").setValue(20);
record.getField("start1").setValue(101);
record.getField("end1").setValue(200);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("20-30,0-100");
record.getField("start").setValue(21);
record.getField("end").setValue(30);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("20-30,100-200");
record.getField("start").setValue(21);
record.getField("end").setValue(30);
record.getField("start1").setValue(101);
record.getField("end1").setValue(200);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("30-40,0-100");
record.getField("start").setValue(31);
record.getField("end").setValue(40);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("30-40,100-200");
record.getField("start").setValue(31);
record.getField("end").setValue(40);
record.getField("start1").setValue(101);
record.getField("end1").setValue(200);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("0-10,0-100");
record.getField("start").setValue(0);
record.getField("end").setValue(10);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("0-10,100-200");
record.getField("start").setValue(0);
record.getField("start1").setValue(101);
record.getField("end").setValue(10);
record.getField("end1").setValue(200);
lookupNotOverlap.put(record, record.duplicate());
record.getField("name").setValue("10-20,0-100");
record.getField("start").setValue(11);
record.getField("end").setValue(20);
record.getField("start1").setValue(0);
record.getField("end1").setValue(100);
lookupNotOverlap.put(record, record.duplicate());
metadata = new DataRecordMetadata("in",DataRecordMetadata.DELIMITED_RECORD);
metadata.addField(new DataFieldMetadata("id",DataFieldMetadata.INTEGER_FIELD,";"));
metadata.addField(new DataFieldMetadata("value",DataFieldMetadata.INTEGER_FIELD,";"));
metadata.addField(new DataFieldMetadata("value1",DataFieldMetadata.INTEGER_FIELD,";"));
record = new DataRecord(metadata);
record.init();
RecordKey key = new RecordKey(new int[]{1,2},metadata);
lookup.setLookupKey(key);
lookupNotOverlap.setLookupKey(key);
}
public void test_1() throws IOException{
DataRecord tmp,tmp1;
for (int i=0;i<500;i++){
record.getField("id").setValue(i);
record.getField("value").setValue(random.nextInt(41));
record.getField("value1").setValue(random.nextInt(201));
tmp = lookup.get(record);
tmp1 = lookupNotOverlap.get(record);
System.out.println("Input record " + i + ":\n" + record + "From lookup table:\n" + tmp);
assertTrue((Integer)record.getField("value").getValue() >= (Integer)tmp.getField("start").getValue());
assertTrue((Integer)record.getField("value").getValue() <= (Integer)tmp.getField("end").getValue());
assertTrue((Integer)record.getField("value1").getValue() >= (Integer)tmp.getField("start1").getValue());
assertTrue((Integer)record.getField("value1").getValue() <= (Integer)tmp.getField("end1").getValue());
System.out.println("From lookupNotOverlap table:\n" + tmp1);
assertEquals(tmp.getField("end"), tmp1.getField("end"));
assertEquals(tmp.getField("end1"), tmp1.getField("end1"));
// if ((Integer)record.getField("value").getValue()%10 == 0 ||
// (Integer)record.getField("value1").getValue()%100 == 0 ){
// System.in.read();
tmp = lookup.getNext();
tmp1 = lookupNotOverlap.getNext();
while (tmp != null) {
System.out.println("Next:\n" + tmp);
assertTrue((Integer)record.getField("value").getValue() >= (Integer)tmp.getField("start").getValue());
assertTrue((Integer)record.getField("value").getValue() <= (Integer)tmp.getField("end").getValue());
assertTrue((Integer)record.getField("value1").getValue() >= (Integer)tmp.getField("start1").getValue());
assertTrue((Integer)record.getField("value1").getValue() <= (Integer)tmp.getField("end1").getValue());
System.out.println("Next1:\n" + tmp1);
tmp = lookup.getNext();
}
}
}
}
|
package com.elmakers.mine.bukkit.wand;
import org.bukkit.configuration.ConfigurationSection;
import com.elmakers.mine.bukkit.api.magic.Mage;
public class WandUpgradeSlot {
private final String slotType;
private boolean hidden = false;
private boolean swappable = false;
private boolean replaceable = false;
private Wand slotted;
public WandUpgradeSlot(String slotType) {
this.slotType = slotType;
}
public WandUpgradeSlot(String configKey, ConfigurationSection config) {
slotType = config.getString("type", configKey);
hidden = config.getBoolean("hidden", false);
swappable = config.getBoolean("swappable", false);
replaceable = config.getBoolean("replaceable", false);
}
public Wand getSlotted() {
return slotted;
}
public boolean addSlotted(Wand upgrade, Mage mage) {
String slotType = upgrade.getSlot();
if (slotType == null || slotType.isEmpty()) {
return false;
}
if (!slotType.equals(slotType)) {
return false;
}
if (slotted == null || replaceable) {
slotted = upgrade;
return true;
}
if (!swappable || mage == null) {
return false;
}
mage.giveItem(slotted.getItem());
slotted = upgrade;
return true;
}
public boolean isHidden() {
return hidden;
}
public String getType() {
return slotType;
}
}
|
package org.appwork.utils.swing;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
public class TreeModelStateSaver {
protected JTree tree;
/**
* Stores for each node the expanded state
*/
private HashMap<Object, Boolean> expandCache;
/**
* @param selectedPathes
* the selectedPathes to set
*/
public void setSelectedPathes(TreePath[] selectedPathes) {
this.selectedPathes = selectedPathes;
}
/**
* @return the expandCache
*/
public HashMap<Object, Boolean> getExpandCache() {
return expandCache;
}
/**
* treePath for internal use
*/
private TreePath treePath;
/**
* Stores all selected Pathes
*/
protected TreePath[] selectedPathes;
/**
* @param tree
*/
public TreeModelStateSaver(JTree tree) {
this.tree = tree;
this.expandCache = new HashMap<Object, Boolean>();
}
/**
* Save the current state of the tree
*/
public void save() {
saveState(tree.getModel().getRoot(), new ArrayList<Object>());
selectedPathes = tree.getSelectionPaths();
}
/**
* Saves the expaned states of each node to cacheMap runs rekursive
*
* @param root
*/
@SuppressWarnings("unchecked")
private void saveState(Object node, ArrayList<Object> path) {
path.add(node);
try {
treePath = new TreePath(path.toArray(new Object[] {}));
expandCache.put(node, tree.isExpanded(treePath));
} catch (Exception e) {
e.printStackTrace();
}
int max = tree.getModel().getChildCount(node);
for (int i = 0; i < max; i++) {
try {
saveState(tree.getModel().getChild(node, i), (ArrayList<Object>) path.clone());
} catch (Exception e) {
e.printStackTrace();
}
tree.getModel().getChildCount(node);
}
}
/**
* Restore the saved tree state
*/
public void restore() {
restoreState(tree.getModel().getRoot(), new ArrayList<Object>());
if (selectedPathes != null && selectedPathes.length > 0) tree.getSelectionModel().setSelectionPaths(selectedPathes);
}
/**
* @return the {@link TreeModelStateSaver#selectedPathes}
* @see TreeModelStateSaver#selectedPathes
*/
public TreePath[] getSelectedPathes() {
return selectedPathes;
}
/**
* @param root
* @param arrayList
*/
@SuppressWarnings("unchecked")
protected void restoreState(Object node, ArrayList<Object> path) {
if (node == null) return;
path.add(node);
treePath = new TreePath(path.toArray(new Object[] {}));
Boolean bo = expandCache.get(node);
if (bo != null && bo.booleanValue()) {
tree.expandPath(treePath);
}
for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
restoreState(tree.getModel().getChild(node, i), (ArrayList<Object>) path.clone());
}
}
}
|
package org.jetel.interpreter;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.parser.Parser;
import org.jetel.data.primitive.CloverInteger;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.graph.TransformationGraph;
import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration;
import org.jetel.interpreter.ASTnode.CLVFStart;
import org.jetel.interpreter.ASTnode.CLVFStartExpression;
import org.jetel.interpreter.data.TLValue;
import org.jetel.interpreter.data.TLValueType;
import org.jetel.interpreter.data.TLVariable;
import org.jetel.main.runGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
/**
* @author dpavlis
* @since 10.8.2004
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class TestInterpreter extends TestCase {
private static final String CLOVER_PATH="/home/avackova/workspace/cloveretl.engine";
DataRecordMetadata metadata,metadata1,metaOut,metaOut1;
DataRecord record,record1,out,out1;
TransformationGraph graph;
LookupTable lkp;
protected void setUp() {
runGraph.initEngine(null, null);
graph=new TransformationGraph();
metadata=new DataRecordMetadata("in",DataRecordMetadata.DELIMITED_RECORD);
metadata.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metadata.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metadata.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metadata1=new DataRecordMetadata("in1",DataRecordMetadata.DELIMITED_RECORD);
metadata1.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metadata1.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metadata1.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metadata1.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metadata1.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metaOut=new DataRecordMetadata("out",DataRecordMetadata.DELIMITED_RECORD);
metaOut.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metaOut.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metaOut.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metaOut.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metaOut.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metaOut1=new DataRecordMetadata("out1",DataRecordMetadata.DELIMITED_RECORD);
metaOut1.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metaOut1.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metaOut1.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metaOut1.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metaOut1.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
record = new DataRecord(metadata);
record.init();
record1 = new DataRecord(metadata1);
record1.init();
out = new DataRecord(metaOut);
out.init();
out1 = new DataRecord(metaOut1);
out1.init();
SetVal.setString(record,0," HELLO ");
SetVal.setString(record1,0," My name ");
SetVal.setInt(record,1,135);
SetVal.setDouble(record1,1,13.5);
SetVal.setString(record,2,"Some silly longer string.");
SetVal.setString(record1,2,"Prague");
SetVal.setValue(record1,3,Calendar.getInstance().getTime());
record.getField("Born").setNull(true);
SetVal.setInt(record,4,-999);
record1.getField("Value").setNull(true);
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE",
new Object[]{"test",graph,"test"}, new Class[]{String.class,TransformationGraph.class,String.class});
graph.addSequence("test", seq);
// LookupTable lkp=new SimpleLookupTable("LKP", metadata, new String[] {"Name"}, null);
lkp = LookupTableFactory.createLookupTable(graph, "simpleLookup",
new Object[]{"LKP" , metadata ,new String[] {"Name"} , null}, new Class[]{String.class,
DataRecordMetadata.class, String[].class, Parser.class});
try {
lkp.init();
graph.addLookupTable("LKP",lkp);
}catch(Exception ex) {
throw new RuntimeException(ex);
}
lkp.put("one",record);
record.getField("Name").setValue("xxxx");
lkp.put("two", record);
// RecordKey key = new RecordKey(new int[]{0}, metadata);
// key.init();
// lkp.setLookupKey(key);
// DataRecord keyRecord = new DataRecord(metadata);
// keyRecord.init();
// keyRecord.getField(0).setValue("one");
lkp.setLookupKey("nesmysl");
}
protected void tearDown() {
metadata= null;
record=null;
out=null;
}
public void test_int(){
System.out.println("int test:");
String expStr = "int i; i=0; print_err(i); \n"+
"int j; j=-1; print_err(j);\n"+
"int minInt; minInt="+Integer.MIN_VALUE+"; print_err(minInt, true);\n"+
"int maxInt; maxInt="+Integer.MAX_VALUE+"; print_err(maxInt, true);\n"+
"int field; field=$Value; print_err(field);";
try {
print_code(expStr);
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(0,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt());
assertEquals(-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getValue().getInt());
assertEquals(Integer.MIN_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("minInt")).getValue().getInt());
assertEquals(Integer.MAX_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("maxInt")).getValue().getInt());
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("field")).getValue().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_long(){
System.out.println("\nlong test:");
String expStr = "long i; i=0; print_err(i); \n"+
"long j; j=-1; print_err(j);\n"+
"long minLong; minLong="+(Long.MIN_VALUE+1)+"; print_err(minLong);\n"+
"long maxLong; maxLong="+(Long.MAX_VALUE)+"; print_err(maxLong);\n"+
"long field; field=$Value; print_err(field);\n"+
"long wrong;wrong="+Long.MAX_VALUE+"; print_err(wrong);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(0,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getLong());
assertEquals(-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getValue().getLong());
assertEquals(Long.MIN_VALUE+1,executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getValue().getLong());
assertEquals(Long.MAX_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("maxLong")).getValue().getLong());
assertEquals(((Integer)record.getField("Value").getValue()).longValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("field")).getValue().getLong());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_decimal(){
System.out.println("\ndecimal test:");
String expStr = "decimal i; i=0; print_err(i); \n"+
"decimal j; j=-1.0; print_err(j);\n"+
"decimal(18,3) minLong; minLong=999999.999d; print_err(minLong);\n"+
"decimal maxLong; maxLong=0000000.0000000; print_err(maxLong);\n"+
"decimal fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"decimal fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"decimal(400,350) minDouble; minDouble="+Double.MIN_VALUE+"d; print_err(minDouble);\n" +
"decimal def;print_err(def);\n" +
"print_err('the end');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(999999.999),executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("maxLong")).getValue().getNumeric());
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldValue")).getValue().getNumeric().getInt());
assertEquals((Double)record.getField("Age").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldAge")).getValue().getDouble());
assertEquals(new Double(Double.MIN_VALUE),executor.getGlobalVariable(parser.getGlobalVariableSlot("minDouble")).getValue().getDouble());
assertTrue(executor.getGlobalVariable(parser.getGlobalVariableSlot("def")).getValue().getNumeric().isNull());
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_number(){
System.out.println("\nnumber test:");
String expStr = "number i; i=0; print_err(i); \n"+
"number j; j=-1.0; print_err(j);\n"+
"number minLong; minLong=999999.99911; print_err(minLong); \n"+
"number fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"number fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"number minDouble; minDouble="+Double.MIN_VALUE+"; print_err(minDouble);\n" +
"number def;print_err(def);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getDouble());
assertEquals(new Double(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getValue().getDouble());
assertEquals(new Double(999999.99911),executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getValue().getDouble());
assertEquals(new Double(((Integer)record.getField("Value").getValue())),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldValue")).getValue().getDouble());
assertEquals(new Double((Double)record.getField("Age").getValue()),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldAge")).getValue().getDouble());
assertEquals(new Double(Double.MIN_VALUE),executor.getGlobalVariable(parser.getGlobalVariableSlot("minDouble")).getValue().getDouble());
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("def")).getValue().getDouble());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_string(){
System.out.println("\nstring test:");
int lenght=1000;
StringBuilder tmp = new StringBuilder(lenght);
for (int i=0;i<lenght;i++){
tmp.append(i%10);
}
String expStr = "string i; i=\"0\"; print_err(i); \n"+
"string hello; hello='hello'; print_err(hello);\n"+
"string fieldName; fieldName=$Name; print_err(fieldName);\n"+
"string fieldCity; fieldCity=$City; print_err(fieldCity);\n"+
"string longString; longString=\""+tmp+"\"; print_err(longString);\n"+
"string specialChars; specialChars='a\u0101\u0102A'; print_err(specialChars);\n" +
"string empty=\"\";print_err(empty+specialChars);\n" +
"print_err(\"\"+specialChars);\n" +
"print_err(concat('', specialChars));\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes("UTF-8")));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("0",executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getString());
assertEquals("hello",executor.getGlobalVariable(parser.getGlobalVariableSlot("hello")).getValue().getString());
assertEquals(record.getField("Name").getValue().toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldName")).getValue().getString());
assertEquals(record.getField("City").getValue().toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldCity")).getValue().getString());
assertEquals(tmp.toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("longString")).getValue().getString());
assertEquals("a\u0101\u0102A",executor.getGlobalVariable(parser.getGlobalVariableSlot("specialChars")).getValue().getString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
} catch (UnsupportedEncodingException ex){
ex.printStackTrace();
}
}
public void test_date(){
System.out.println("\ndate test:");
String expStr = "date d3; d3=2006-08-01; print_err(d3);\n"+
"date d2; d2=2006-08-02 15:15:00 ; print_err(d2);\n"+
"date d1; d1=2006-1-1 1:2:3; print_err(d1);\n"+
"date born; born=$0.Born; print_err(born);";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(new GregorianCalendar(2006,7,01).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d3")).getValue().getDate());
assertEquals(new GregorianCalendar(2006,7,02,15,15).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d2")).getValue().getDate());
assertEquals(new GregorianCalendar(2006,0,01,01,02,03).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d1")).getValue().getDate());
assertEquals((Date)record.getField("Born").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("born")).getValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_boolean(){
System.out.println("\nboolean test:");
String expStr = "boolean b1; b1=true; print_err(b1);\n"+
"boolean b2; b2=false ; print_err(b2);\n"+
"boolean b4; print_err(b4);";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b1")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("b2")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("b4")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_variables(){
System.out.println("\nvariable test:");
String expStr = "boolean b1; boolean b2; b1=true; print_err(b1);\n"+
"b2=false ; print_err(b2);\n"+
"string b4; b4=\"hello\"; print_err(b4);\n"+
"b2 = true; print_err(b2);\n" +
"int in;\n" +
"if (b2) {in=2;print_err('in');}\n"+
"print_err(b2);";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b1")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b2")).getValue().getBoolean());
assertEquals("hello",executor.getGlobalVariable(parser.getGlobalVariableSlot("b4")).getValue().getString());
// assertEquals(2,executor.getGlobalVariable(parser.getGlobalVariableSlot("in")).getValue().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_plus(){
System.out.println("\nplus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i+j; print_err(\"plus int:\"+iplusj);\n" +
"long l;l="+Integer.MAX_VALUE/10+"l;print_err(l);\n" +
"long m;m="+(Integer.MAX_VALUE)+"l;print_err(m);\n" +
"long lplusm;lplusm=l+m;print_err(\"plus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n+m1;print_err(\"plus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n+j;print_err(\"number plus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d+d1;print_err(\"plus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d+j;print_err(\"decimal plus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d+m1;print_err(\"decimal plus number:\"+dplusn);\n" +
"dplusn=dplusn+10;\n" +
"string s; s=\"hello\"; print_err(s);\n" +
"string s1;s1=\" world\";print_err(s1);\n " +
"string spluss1;spluss1=s+s1;print_err(\"adding strings:\"+spluss1);\n" +
"string splusm1;splusm1=s+m1;print_err(\"string plus decimal:\"+splusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate+i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("iplusj",110,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getValue().getInt()));
assertEquals("lplusm",(long)Integer.MAX_VALUE+(long)Integer.MAX_VALUE/10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getValue().getLong());
assertEquals("nplusm1",new Double(0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getValue().getDouble());
assertEquals("nplusj",new Double(100),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusj")).getValue().getDouble());
assertEquals("dplusd1",new Double(0.1000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getDouble());
assertEquals("dplusj",new Double(100.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getValue().getDouble());
assertEquals("dplusn",new Double(10.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getValue().getDouble());
assertEquals("spluss1","hello world",executor.getGlobalVariable(parser.getGlobalVariableSlot("spluss1")).getValue().getString());
assertEquals("splusm1","hello0.0010",executor.getGlobalVariable(parser.getGlobalVariableSlot("splusm1")).getValue().getString());
assertEquals("dateplus",new GregorianCalendar(2004,01,9,15,00,30).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("dateplus")).getValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_minus(){
System.out.println("\nminus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i-j; print_err(\"minus int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l-m;print_err(\"minus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n-m1;print_err(\"minus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n-j;print_err(\"number minus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001d;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d-d1;print_err(\"minus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d-j;print_err(\"decimal minus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d-m1;print_err(\"decimal minus number:\"+dplusn);\n" +
"number d1minusm1;d1minusm1=d1-m1;print_err('decimal minus number = number:'+d1minusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate-i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("iplusj",-90,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getValue().getInt()));
assertEquals("lplusm",(long)Integer.MAX_VALUE+9,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getValue().getLong());
assertEquals("nplusm1",new Double(-0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getValue().getDouble());
assertEquals("nplusj",new Double(-100),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusj")).getValue().getDouble());
// Decimal tmp = DecimalFactory.getDecimal(0.1);
// tmp.sub(DecimalFactory.getDecimal(0.0001,10,4));
// assertEquals("dplusd1",tmp, executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals("dplusd1",DecimalFactory.getDecimal(0.09), executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals("dplusj",new Double(-99.9),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getValue().getDouble());
assertEquals("dplusn",new Double(0.0900),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getValue().getDouble());
assertEquals("d1minusm1",new Double(-0.0009),executor.getGlobalVariable(parser.getGlobalVariableSlot("d1minusm1")).getValue().getDouble());
assertEquals("dateplus",new GregorianCalendar(2004,0,20,15,00,30).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("dateplus")).getValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_multiply(){
System.out.println("\nmultiply test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i*j; print_err(\"multiply int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l*m;print_err(\"multiply long:\"+lplusm);\n" +
"number n; n=0.1;print_err(n);\n" +
"number m1; m1=-0.01;print_err(m1);\n" +
"number nplusm1; nplusm1=n*m1;print_err(\"multiply number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=m1*j;print_err(\"number multiply int:\"+m1plusj);\n"+
"decimal(8,4) d; d=0.1; print_err(d);\n" +
"decimal(10,4) d1; d1=10.01d;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d*d1;print_err(\"multiply decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d*j;print_err(\"decimal multiply int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=d*n;print_err(\"decimal multiply number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("i*j",1000,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getValue().getInt()));
assertEquals("l*m",(long)Integer.MAX_VALUE+10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getValue().getLong());
assertEquals("n*m1",new Double(-0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getValue().getDouble());
assertEquals("m1*j",new Double(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getValue().getDouble());
assertEquals("d*d1",DecimalFactory.getDecimal(1.001,10,4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals("d*j",DecimalFactory.getDecimal(10,10,4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getValue().getNumeric());
assertEquals("d*n",DecimalFactory.getDecimal(0.01, 10, 4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_division(){
System.out.println("\ndivision test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i/j; print_err(\"div int:\"+iplusj);\n" +
"int jdivi;jdivi=j/i; print_err(\"div int:\"+jdivi);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l/m;print_err(\"div long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.01;print_err(m1);\n" +
"number n1; n1=10;print_err(n1);\n" +
"number nplusm1; nplusm1=n/m1;print_err(\"0/0.01:\"+nplusm1);\n" +
"number m1divn; m1divn=m1/n;print_err(\"deleni nulou:\"+m1divn);\n" +
"number m1divn1; m1divn1=m1/n1;print_err(\"deleni numbers:\"+m1divn1);\n" +
"number m1plusj;m1plusj=j/n1;print_err(\"number division int:\"+m1plusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.01;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d/d1;print_err(\"div decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d/j;print_err(\"decimal div int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=n1/d;print_err(\"decimal div number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("i/j",0,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getValue().getInt()));
assertEquals("j/i",10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("jdivi")).getValue().getInt()));
assertEquals("l/m",(long)Integer.MAX_VALUE+10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getValue().getLong());
assertEquals("n/m1",new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getValue().getDouble());
assertEquals("m1/n",new Double(Double.POSITIVE_INFINITY),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1divn")).getValue().getDouble());
assertEquals("m1/n1",new Double(0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1divn1")).getValue().getDouble());
assertEquals("j/n1",new Double(10),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getValue().getDouble());
assertEquals("d/d1",DecimalFactory.getDecimal(0.1/0.01),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals("d/j",DecimalFactory.getDecimal(0.0000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getValue().getNumeric());
assertEquals("n1/d",DecimalFactory.getDecimal(100.0000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_modulus(){
System.out.println("\nmodulus test:");
String expStr = "int i; i=10;\n"+
"int j; j=103;\n" +
"int iplusj;iplusj=j%i; print_err(\"mod int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=2;print_err(m);\n" +
"long lplusm;lplusm=l%m;print_err(\"mod long:\"+lplusm);\n" +
"number n; n=10.2;print_err(n);\n" +
"number m1; m1=2;print_err(m1);\n" +
"number nplusm1; nplusm1=n%m1;print_err(\"mod number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=n%i;print_err(\"number mod int:\"+m1plusj);\n"+
"decimal d; d=10.1;print_err(d);\n" +
"decimal(10,4) d1; d1=10;print_err(d1);\n" +
"decimal dplusd1; dplusd1=d%d1;print_err(\"mod decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d1%j;print_err(\"decimal mod int:\"+dplusj);\n"+
"decimal dplusn;dplusn=d%m1;print_err(\"decimal mod number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(3,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getValue().getInt()));
assertEquals(((long)Integer.MAX_VALUE+10)%2,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getValue().getLong());
assertEquals(new Double(10.2%2),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getValue().getDouble());
assertEquals(new Double(10.2%10),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getValue().getDouble());
assertEquals(DecimalFactory.getDecimal(0.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(10),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(0.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_increment_decrement(){
System.out.println("\nincrement-decrement test:");
String expStr = "int i; i=10;print_err(++i);\n" +
"i
"print_err(--i);\n"+
"long j;j="+(Long.MAX_VALUE-10)+"l;print_err(++j);\n" +
"print_err(--j);\n"+
"decimal d;d=2;d++;\n" +
"print_err(--d);\n;" +
"number n;n=3.5;print_err(++n);\n" +
"n
"{print_err(++n);}\n" +
"print_err(++n);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(9,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
assertEquals(new CloverLong(Long.MAX_VALUE-10).getLong(),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getValue().getLong());
assertEquals(DecimalFactory.getDecimal(2),executor.getGlobalVariable(parser.getGlobalVariableSlot("d")).getValue().getNumeric());
assertEquals(new Double(5.5),executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getValue().getDouble());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_equal(){
System.out.println("\nequal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i==j+1);print_err(\"eq1=\"+eq1);\n" +
// "boolean eq1;eq1=(i.eq.(j+1));print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l==j);print_err(\"eq2=\"+eq2);\n" +
"eq2=(l.eq.i);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d==i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.eq.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n==d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello \";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s.eq.s1;print_err(\"eq6=\"+eq6);\n" +
"boolean eq7;eq7=s==trim(s1);print_err(\"eq7=\"+eq7);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate);\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate.eq.anothermydate;print_err(\"eq8=\"+eq8);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq9;eq9=mydate==anothermydate;print_err(\"eq9=\"+eq9);\n" +
"boolean eq10;eq10=eq9.eq.eq8;print_err(\"eq10=\"+eq10);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq4")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq5")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq6")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq7")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq8")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq9")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq10")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_non_equal(){
System.out.println("\nNon equal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i!=j);print_err(\"eq1=\");print_err(eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l<>j);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d.ne.i;print_err(\"eq3=\");print_err(eq3);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getValue().getBoolean());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getValue().getBoolean());
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_greater_less(){
System.out.println("\nGreater and less test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i>j);print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l>=j);print_err(\"eq2=\"+eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d=>i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.gt.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n.ge.d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello\";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s<s1;print_err(\"eq6=\"+eq6);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate);\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq7;eq7=mydate.lt.anothermydate;print_err(\"eq7=\"+eq7);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate<=anothermydate;print_err(\"eq8=\"+eq8);\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("eq1",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getValue().getBoolean());
assertEquals("eq2",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getValue().getBoolean());
assertEquals("eq3",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getValue().getBoolean());
assertEquals("eq4",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq4")).getValue().getBoolean());
assertEquals("eq5",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq5")).getValue().getBoolean());
assertEquals("eq6",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq6")).getValue().getBoolean());
assertEquals("eq7",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq7")).getValue().getBoolean());
assertEquals("eq8",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq8")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_regex(){
System.out.println("\nRegex test:");
String expStr = "string s;s='Hej';print_err(s);\n" +
"boolean eq2;eq2=(s~=\"[A-Za-z]{3}\");\n" +
"print_err(\"eq2=\"+eq2);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_1_expression() {
String expStr="$Age>=135 or 200>$Age and not $Age<=0 and 1==999999999999999 or $Name==\"HELLO\"";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true, executor.getResult().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_2_expression() {
String expStr="datediff(nvl($Born,2005-2-1),2005-1-1,month)";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(1, executor.getResult().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_3_expression() {
// String expStr="not (trim($Name) .ne. \"HELLO\") || replace($Name,\".\" ,\"a\")=='aaaaaaa'";
String expStr="print_err(trim($Name)); print_err(replace('xyyxyyxzz',\"x\" ,\"ab\")); print_err('aaaaaaa'); print_err(split('abcdef','c'));";
print_code(expStr);
try {
System.out.println("in Test3expression");
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
// CLVFStartExpression parseTree = parser.StartExpression();
parseTree.dump("ccc");
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.err.println(it.next());
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
// assertEquals(false, executor.getResult().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_if(){
System.out.println("\nIf statement test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"long l;" +
"if (i>j) l=1; else l=0;\n" +
"print_err(l);\n" +
"decimal d;" +
"if (i.gt.j and l.eq.1) {d=0;print_err('d rovne 0');}\n" +
"else d=0.1;\n" +
"number n;\n" +
"if (d==0.1) n=0;\n" +
"if (d==0.1 || l<=1) n=0;\n" +
"else {n=-1;print_err('n rovne -1');}\n" +
"date date1; date1=2006-01-01;print_err(date1);\n" +
"date date2; date2=2006-02-01;print_err(date2);\n" +
"boolean result;result=false;\n" +
"boolean compareDates;compareDates=date1<=date2;print_err(compareDates);\n" +
"if (date1<=date2) \n" +
"{ print_err('before if (i<j)');\n" +
" if (i<j) print_err('date1<today and i<j'); else print_err('date1<date2 only');\n" +
" result=true;}\n" +
"result=false;" +
"if (i<j) result=true;\n" +
"else if (not result) result=true;\n" +
"else print_err('last else');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(1,executor.getGlobalVariable(parser.getGlobalVariableSlot("l")).getValue().getLong());
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("d")).getValue().getNumeric());
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getValue().getDouble());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("result")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_switch(){
System.out.println("\nSwitch test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"int n;n=date2num(born,month);print_err(n);\n" +
"string mont;\n" +
"decimal april;april=4;\n" +
"switch (n) {\n" +
" case 0.0:mont='january';\n" +
" case 1.0:mont='february';\n" +
" case 2.0:mont='march';\n" +
" case 3:mont='april';\n" +
" case april:mont='may';\n" +
" case 5.0:mont='june';\n" +
" case 6.0:mont='july';\n" +
" case 7.0:mont='august';\n" +
" case 3:print_err('4th month');\n" +
" case 8.0:mont='september';\n" +
" case 9.0:mont='october';\n" +
" case 10.0:mont='november';\n" +
" case 11.0:mont='december';\n" +
" default: mont='unknown';};\n"+
"print_err('month:'+mont);\n" +
"boolean ok;ok=(n.ge.0)and(n.lt.12);\n" +
"switch (ok) {\n" +
" case true:print_err('OK');\n" +
" case false:print_err('WRONG');};\n" +
"switch (born) {\n" +
" case 2006-01-01:{mont='January';print_err('january');}\n" +
" case 1973-04-23:{mont='April';print_err('april');}}\n" +
"// default:print_err('other')};\n"+
"switch (born<1996-08-01) {\n" +
" case true:{print_err('older then ten');}\n" +
" default:print_err('younger then ten');};\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(3,executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getValue().getInt());
assertEquals("April",executor.getGlobalVariable(parser.getGlobalVariableSlot("mont")).getValue().getString());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("ok")).getValue().getBoolean());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_while(){
System.out.println("\nWhile test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"while (born<now) {\n" +
" born=dateadd(born,1,year);\n " +
" while (yer<5) yer=yer+1;\n" +
" yer=yer+1;}\n" +
"print_err('years:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
GregorianCalendar b;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
assertEquals(new GregorianCalendar().get(Calendar.YEAR) - b.get(Calendar.YEAR) + 6,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_do_while(){
System.out.println("\nDo-while test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"do {\n" +
" born=dateadd(born,1,year);\n " +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" do yer=yer+1; while (yer<5);\n" +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" yer=yer+1;}\n" +
"while (born<now)\n" +
"print_err('years on the end:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
GregorianCalendar b;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
assertEquals(2 * (new GregorianCalendar().get(Calendar.YEAR) - b.get(Calendar.YEAR)) + 6,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_for(){
System.out.println("\nFor test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"for (born;born<now;born=dateadd(born,1,year)) yer++;\n" +
"print_err('years on the end:'+yer);\n" +
"boolean b;\n" +
"for (born;!b;++yer) \n" +
" if (yer==100) b=true;\n" +
"print_err(born);\n" +
"print_err('years on the end:'+yer);\n" +
"print_err('born:'+born);\n"+
"int i;\n" +
"for (i=0;i.le.10;++i) ;\n" +
"print_err('on the end i='+i);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
int iVarSlot=parser.getGlobalVariableSlot("i");
int yerVarSlot=parser.getGlobalVariableSlot("yer");
TLVariable[] result = executor.stack.globalVarSlot;
assertEquals(101,result[yerVarSlot].getValue().getInt());
assertEquals(11,result[iVarSlot].getValue().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_for2(){
System.out.println("\nFor test:");
String expStr ="int i;int yer;yer=0;\n" +
"for (i=0;i.le.10;++i) ;\n" +
"print_err('on the end i='+i);\n" +
"int j=1;long l=123456789012345678L;\n" +
"for (j=5;j<i;++j){\n" +
" l=l-i;}";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
int iVarSlot=parser.getGlobalVariableSlot("i");
int jVarSlot=parser.getGlobalVariableSlot("j");
TLVariable[] result = executor.stack.globalVarSlot;
assertEquals(11,result[jVarSlot].getValue().getInt());
assertEquals(11,result[iVarSlot].getValue().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_break(){
System.out.println("\nBreak test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"while (born<now) {\n" +
" yer++;\n" +
" born=dateadd(born,1,year);\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(new GregorianCalendar().get(Calendar.YEAR) - born.get(Calendar.YEAR) + 1,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getValue().getInt()));
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_break2(){
System.out.println("\nBreak test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now; now=today(); print_err(now);\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"while (yer<date2num(now,year)) {\n" +
" yer++;\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(2007,(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getValue().getInt()));
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_continue(){
System.out.println("\nContinue test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"for (i=0;i<10;i=i+1) {\n" +
" print_err('i='+i);\n" +
" if (i>5) continue;\n" +
" print_err('After if');" +
"}\n" +
"print_err('new loop starting');\n" +
"print_err('born '+born+' now '+now);\n"+
"while (born<now) {\n" +
" print_err('i='+i);i=0;\n" +
" print_err(yer);\n" +
" yer=yer+1;\n" +
" born=dateadd(born,1,year);\n" +
" if (yer>30) continue\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
assertEquals(35,(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getValue().getInt()));
assertEquals(0,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_continue2(){
System.out.println("\nContinue test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"for (i=0;i<10;i=i+1) {\n" +
" print_err('i='+i);\n" +
" if (i>5) continue;\n" +
" print_err('After if');" +
"}\n" +
"print_err('i after f:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_return(){
System.out.println("\nReturn test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"function year_before(now) {\n" +
" return dateadd(now,-1,year);" +
"}\n" +
"function age(born){\n" +
" date now;int yer;\n" +
" now=today();yer=0;\n" +
" for (born;born<now;born=dateadd(born,1,year)) yer++;\n" +
" if (yer>0) return yer else return -1;" +
"}\n" +
"print_err('years born'+age(born));\n" +
"print_err(\"year before:\"+year_before(born));\n" +
" while (true) {print_err('pred return');" +
"return;\n" +
"print_err('po return');}\n" +
"print_err('za blokem');\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
for(Iterator iter=parser.getParseExceptions().iterator();iter.hasNext();){
System.err.println(iter.next());
}
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
//TODO
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_list_map(){
System.out.println("\nList/Map test:");
String expStr = "list seznam; list seznam2; list fields;\n"+
"map mapa; mapa['f1']=10; mapa['f2']='hello'; map mapa2; mapa2[]=mapa; map mapa3; \n"+
"int i; for(i=0;i<20;i++) { seznam[]=i; if (i==10) seznam2[]=seznam; }\n"+
"seznam[1]=999; seznam2[3]='hello'; \n"+
"fields=split('a,b,c,d,e,f,g,h',','); fields[]=null;"+
"int length=length(seznam); print_err('length: '+length);\n print_err(seznam);\n print_err(seznam2); print_err(fields);\n"+
"list novy; novy[]=mapa; mapa2['f2']='xxx'; novy[]=mapa2; mapa['f1']=99; novy[]=mapa; \n" +
"print_err('novy='+novy); print_err(novy[1]); \n" +
"mapa3=novy[1]; print_err(mapa2['f2']);\n" +
"fields=seznam2; print_err(fields);";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
TransformLangParser parser=null;
try {
parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("lengh",20,executor.getGlobalVariable(parser.getGlobalVariableSlot("length")).getValue().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
Iterator it=parser.getParseExceptions().iterator();
while(it.hasNext()){
System.err.println(((Throwable)it.next()).getMessage());
}
throw new RuntimeException("Parse exception",e);
}
}
public void test_buildInFunctions(){
System.out.println("\nBuild-in functions test:");
String expStr = "string s;s='hello world';\n" +
"number lenght;lenght=5.5;\n" +
"string subs;subs=substring(s,1,lenght);\n" +
"print_err('original string:'+s );\n" +
"print_err('substring:'+subs );\n" +
"string upper;upper=uppercase(subs);\n" +
"print_err('to upper case:'+upper );\n"+
"string lower;lower=lowercase(subs+'hI ');\n" +
"print_err('to lower case:'+lower );\n"+
"string t;t=trim('\t im '+lower);\n" +
"print_err('after trim:'+t );\n" +
"breakpoint();\n" +
"//print_stack();\n"+
"decimal l;l=length(upper);\n" +
"print_err('length of '+upper+':'+l );\n"+
"string c;c=concat(lower,upper,2,',today is ',today());\n" +
"print_err('concatenation \"'+lower+'\"+\"'+upper+'\"+2+\",today is \"+today():'+c );\n"+
"date datum; date born;born=nvl($Born,today()-400);\n" +
"datum=dateadd(born,100,millisec);\n" +
"print_err(datum );\n"+
"long ddiff;date otherdate;otherdate=today();\n" +
"ddiff=datediff(born,otherdate,year);\n" +
"print_err('date diffrence:'+ddiff );\n" +
"print_err('born: '+born+' otherdate: '+otherdate);\n" +
"boolean isn;isn=isnull(ddiff);\n" +
"print_err(isn );\n" +
"number s1;s1=nvl(l+1,1);\n" +
"print_err(s1 );\n" +
"string rep;rep=replace(c,'[lL]','t');\n" +
"print_err(rep );\n" +
"decimal(10,5) stn;stn=str2num('2.5125e-1',decimal);\n" +
"print_err(stn );\n" +
"int i = str2num('1234');\n" +
"string nts;nts=num2str(10,4);\n" +
"print_err(nts );\n" +
"date newdate;newdate=2001-12-20 16:30:04;\n" +
"decimal dtn;dtn=date2num(newdate,month);\n" +
"print_err(dtn );\n" +
"int ii;ii=iif(newdate<2000-01-01,20,21);\n" +
"print_err('ii:'+ii);\n" +
"print_stack();\n" +
"date ndate;ndate=2002-12-24;\n" +
"string dts;dts=date2str(ndate,'yy.MM.dd');\n" +
"print_err('date to string:'+dts);\n" +
"print_err(str2date(dts,'yy.MM.dd'));\n" +
"string lef=left(dts,5);\n" +
"string righ=right(dts,5);\n" +
"print_err('s=word, soundex='+soundex('word'));\n" +
"print_err('s=world, soundex='+soundex('world'));\n" +
"int j;for (j=0;j<length(s);j++){print_err(char_at(s,j));};\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("subs","ello ",executor.getGlobalVariable(parser.getGlobalVariableSlot("subs")).getValue().getString());
assertEquals("upper","ELLO ",executor.getGlobalVariable(parser.getGlobalVariableSlot("upper")).getValue().getString());
assertEquals("lower","ello hi ",executor.getGlobalVariable(parser.getGlobalVariableSlot("lower")).getValue().getString());
assertEquals("t(=trim)","im ello hi",executor.getGlobalVariable(parser.getGlobalVariableSlot("t")).getValue().getString());
assertEquals("l(=length)",5,executor.getGlobalVariable(parser.getGlobalVariableSlot("l")).getValue().getInt());
assertEquals("c(=concat)","ello hi ELLO 2,today is "+new Date(),executor.getGlobalVariable(parser.getGlobalVariableSlot("c")).getValue().getString());
// assertEquals("datum",record.getField("Born").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("datum")).getValue().getDate());
assertEquals("ddiff",-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("ddiff")).getValue().getLong());
assertEquals("isn",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("isn")).getValue().getBoolean());
assertEquals("s1",new Double(6),executor.getGlobalVariable(parser.getGlobalVariableSlot("s1")).getValue().getDouble());
assertEquals("rep",("etto hi EttO 2,today is "+new Date()).replaceAll("[lL]", "t"),executor.getGlobalVariable(parser.getGlobalVariableSlot("rep")).getValue().getString());
assertEquals("stn",0.25125,executor.getGlobalVariable(parser.getGlobalVariableSlot("stn")).getValue().getDouble());
assertEquals("i",1234,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt());
assertEquals("nts","22",executor.getGlobalVariable(parser.getGlobalVariableSlot("nts")).getValue().getString());
assertEquals("dtn",11.0,executor.getGlobalVariable(parser.getGlobalVariableSlot("dtn")).getValue().getDouble());
assertEquals("ii",21,executor.getGlobalVariable(parser.getGlobalVariableSlot("ii")).getValue().getInt());
assertEquals("dts","02.12.24",executor.getGlobalVariable(parser.getGlobalVariableSlot("dts")).getValue().getString());
assertEquals("lef","02.12",executor.getGlobalVariable(parser.getGlobalVariableSlot("lef")).getValue().getString());
assertEquals("righ","12.24",executor.getGlobalVariable(parser.getGlobalVariableSlot("righ")).getValue().getString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_math_functions(){
System.out.println("\nMath functions test:");
String expStr = "number original;original=pi();\n" +
"print_err('pi='+original);\n" +
"number ee=e();\n" +
"number result;result=sqrt(original);\n" +
"print_err('sqrt='+result);\n" +
"int i;i=9;\n" +
"number p9;p9=sqrt(i);\n" +
"number ln;ln=log(p9);\n" +
"print_err('sqrt(-1)='+sqrt(-1));\n" +
"decimal d;d=0;"+
"print_err('log(0)='+log(d));\n" +
"number l10;l10=log10(p9);\n" +
"number ex;ex =exp(l10);\n" +
"number po;po=pow(p9,1.2);\n" +
"number p;p=pow(-10,-0.3);\n" +
"print_err('power(-10,-0.3)='+p);\n" +
"int r;r=round(-po);\n" +
"print_err('round of '+(-po)+'='+r);"+
"int t;t=trunc(-po);\n" +
"print_err('truncation of '+(-po)+'='+t);\n" +
"date date1;date1=2004-01-02 17:13:20;\n" +
"date tdate1; tdate1=trunc(date1);\n" +
"print_err('truncation of '+date1+'='+tdate1);\n" +
"print_err('Random number: '+random());\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals("pi",new Double(Math.PI),executor.getGlobalVariable(parser.getGlobalVariableSlot("original")).getValue().getDouble());
assertEquals("e",new Double(Math.E),executor.getGlobalVariable(parser.getGlobalVariableSlot("ee")).getValue().getDouble());
assertEquals("sqrt",new Double(Math.sqrt(Math.PI)),executor.getGlobalVariable(parser.getGlobalVariableSlot("result")).getValue().getDouble());
assertEquals("sqrt(9)",new Double(3),executor.getGlobalVariable(parser.getGlobalVariableSlot("p9")).getValue().getDouble());
assertEquals("ln",new Double(Math.log(3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("ln")).getValue().getDouble());
assertEquals("log10",new Double(Math.log10(3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("l10")).getValue().getDouble());
assertEquals("exp",new Double(Math.exp(Math.log10(3))),executor.getGlobalVariable(parser.getGlobalVariableSlot("ex")).getValue().getDouble());
assertEquals("power",new Double(Math.pow(3,1.2)),executor.getGlobalVariable(parser.getGlobalVariableSlot("po")).getValue().getDouble());
assertEquals("power--",new Double(Math.pow(-10,-0.3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("p")).getValue().getDouble());
assertEquals("round",Integer.parseInt("-4"),executor.getGlobalVariable(parser.getGlobalVariableSlot("r")).getValue().getInt());
assertEquals("truncation",Integer.parseInt("-3"),executor.getGlobalVariable(parser.getGlobalVariableSlot("t")).getValue().getInt());
assertEquals("date truncation",new GregorianCalendar(2004,00,02).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("tdate1")).getValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
// public void test_global_parameters(){
// System.out.println("\nGlobal parameters test:");
// String expStr = "string original;original=${G1};\n" +
// "int num; num=str2num(original); \n"+
// "print_err(original);\n"+
// "print_err(num);\n";
// print_code(expStr);
// try {
// TransformLangParser parser = new TransformLangParser(record.getMetadata(),
// new ByteArrayInputStream(expStr.getBytes()));
// CLVFStart parseTree = parser.Start();
// System.out.println("Initializing parse tree..");
// parseTree.init();
// System.out.println("Parse tree:");
// parseTree.dump("");
// System.out.println("Interpreting parse tree..");
// TransformLangExecutor executor=new TransformLangExecutor();
// executor.setInputRecords(new DataRecord[] {record});
// Properties globalParameters = new Properties();
// globalParameters.setProperty("G1","10");
// executor.setGlobalParameters(globalParameters);
// executor.visit(parseTree,null);
// System.out.println("Finished interpreting.");
// assertEquals("num",10,executor.getGlobalVariable(parser.getGlobalVariableSlot("num")).getValue().getInt());
// } catch (ParseException e) {
// System.err.println(e.getMessage());
// e.printStackTrace();
// throw new RuntimeException("Parse exception",e);
public void test_mapping(){
System.out.println("\nMapping test:");
String expStr = "print_err($1.City); "+
"function test(){\n" +
" string result;\n" +
" print_err('function');\n" +
" result='result';\n" +
" //return result;\n" +
" $Name:=result;\n" +
" $0.Age:=$Age;\n" +
" $out.City:=concat(\"My City \",$City);\n" +
" $Born:=$1.Born;\n" +
" $0.Value:=nvl(0,$in1.Value);\n" +
" }\n" +
"test();\n" +
"print_err('Age='+ $0.Age);\n "+
"if (isnull($0.Age)) {print_err('!!!! Age is null!!!');}\n" +
"print_err($1.City); "+
"//print_err($out.City); " +
"print_err($1.City); "+
"$1.Name:=test();\n" +
"$out1.Age:=$Age;\n" +
"$1.City:=$1.City;\n" +
"$out1.Value:=$in.Value;\n";
print_code(expStr);
try {
DataRecordMetadata[] recordMetadata=new DataRecordMetadata[] {metadata,metadata1};
DataRecordMetadata[] outMetadata=new DataRecordMetadata[] {metaOut,metaOut1};
TransformLangParser parser = new TransformLangParser(recordMetadata,
outMetadata,new ByteArrayInputStream(expStr.getBytes()),"UTF-8");
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record,record1});
executor.setOutputRecords(new DataRecord[]{out,out1});
SetVal.setString(record1,2,"Prague");
record.getField("Age").setNull(true);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("result",out.getField("Name").getValue().toString());
assertEquals(record.getField("Age").getValue(),out.getField("Age").getValue());
assertEquals("My City "+record.getField("City").getValue().toString(), out.getField("City").getValue().toString());
assertEquals(record1.getField("Born").getValue(), out.getField("Born").getValue());
assertEquals(0,out.getField("Value").getValue());
assertEquals("",out1.getField("Name").getValue().toString());
assertEquals(record.getField("Age").getValue(), out1.getField("Age").getValue());
assertEquals(record1.getField("City").getValue().toString(), out1.getField("City").getValue().toString());
assertNull(out1.getField("Born").getValue());
assertEquals(record.getField("Value").getValue(), out1.getField("Value").getValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_logger(){
System.out.println("\nLogger test:");
String expStr = "/*raise_error(\"my testing error\") ;*/ " +
"print_log(fatal,10 * 15);";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_sequence(){
System.out.println("\nSequence test:");
String expStr = "print_err(sequence(test).next);\n"+
"print_err(sequence(test).next);\n"+
"int i; for(i=0;i<10;++i) print_err(sequence(test).next);\n"+
"i=sequence(test).current; print_err(i,true); i=sequence(test).reset; \n" +
"print_err('i after reset='+i);\n" +
"int current;string next;"+
"for(i=0;i<50;++i) { current=sequence(test).current;\n" +
"print_err('current='+current);\n" +
"next=sequence(test).next;\n" +
" print_err('next='+next); }\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_lookup(){
System.out.println("\nLookup test:");
String expStr = "string key='one';\n"+
"string val=lookup(LKP,key).Name;\n"+
"print_err(lookup(LKP,' HELLO ').Age); \n"+
"print_err(lookup_found(LKP));\n"+
"print_err(lookup_next(LKP).Age);\n"+
"print_err(lookup(LKP,'two').Name); \n"+
"/*print_err(lookup(LKP,'two').Name);\n"+
"print_err(lookup(LKP,'xxx').Name);\n*/";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_function(){
System.out.println("\nFunction test:");
String expStr = "function myFunction(idx){\n" +
"if (idx==1) print_err('idx equals 1'); else print_err('idx does not equal 1');}\n" +
"myFunction(1);\n" +
"myFunction1(1);\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
// CLVFFunctionDeclaration function = (CLVFFunctionDeclaration)parser.getFunctions().get("myFunction");
// executor.executeFunction(function, new TLValue[]{new TLValue(TLValueType.INTEGER,new CloverInteger(1))});
// executor.executeFunction(function, new TLValue[]{new TLValue(TLValueType.INTEGER,new CloverInteger(10))});
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_import(){
System.out.println("\nImport test:");
String expStr = "import '" + CLOVER_PATH + "/data/tlExample.ctl';";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getValue().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void print_code(String text){
String[] lines=text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for(int i=0;i<lines.length;i++){
System.out.println((i+1)+"\t:"+lines[i]);
}
}
}
|
package org.bouncycastle.crypto.engines;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.StreamCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class HC128Engine
implements StreamCipher
{
private int[] p = new int[512];
private int[] q = new int[512];
private int cnt = 0;
private static int f1(int x)
{
return rotateRight(x, 7) ^ rotateRight(x, 18)
^ (x >>> 3);
}
private static int f2(int x)
{
return rotateRight(x, 17) ^ rotateRight(x, 19)
^ (x >>> 10);
}
private int g1(int x, int y, int z)
{
return (rotateRight(x, 10) ^ rotateRight(z, 23))
+ rotateRight(y, 8);
}
private int g2(int x, int y, int z)
{
return (rotateLeft(x, 10) ^ rotateLeft(z, 23)) + rotateLeft(y, 8);
}
private static int rotateLeft(
int x,
int bits)
{
return (x << bits) | (x >>> -bits);
}
private static int rotateRight(
int x,
int bits)
{
return (x >>> bits) | (x << -bits);
}
private int h1(int x)
{
return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256];
}
private int h2(int x)
{
return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256];
}
private static int mod1024(int x)
{
return x & 0x3FF;
}
private static int mod512(int x)
{
return x & 0x1FF;
}
private static int dim(int x, int y)
{
return mod512(x - y);
}
private int step()
{
int j = mod512(cnt);
int ret;
if (cnt < 512)
{
p[j] += g1(p[dim(j, 3)], p[dim(j, 10)], p[dim(j, 511)]);
ret = h1(p[dim(j, 12)]) ^ p[j];
}
else
{
q[j] += g2(q[dim(j, 3)], q[dim(j, 10)], q[dim(j, 511)]);
ret = h2(q[dim(j, 12)]) ^ q[j];
}
cnt = mod1024(cnt + 1);
return ret;
}
private byte[] key, iv;
private boolean initialised;
private void init()
{
if (key.length != 16)
{
throw new java.lang.IllegalArgumentException(
"The key must be 128 bit long");
}
cnt = 0;
int[] w = new int[1280];
for (int i = 0; i < 16; i++)
{
w[i >> 3] |= (key[i] & 0xff) << (i & 0x7);
}
System.arraycopy(w, 0, w, 4, 4);
for (int i = 0; i < iv.length && i < 16; i++)
{
w[(i >> 3) + 8] |= (iv[i] & 0xff) << (i & 0x7);
}
System.arraycopy(w, 8, w, 12, 4);
for (int i = 16; i < 1280; i++)
{
w[i] = f2(w[i - 2]) + w[i - 7] + f1(w[i - 15]) + w[i - 16] + i;
}
System.arraycopy(w, 256, p, 0, 512);
System.arraycopy(w, 768, q, 0, 512);
for (int i = 0; i < 512; i++)
{
p[i] = step();
}
for (int i = 0; i < 512; i++)
{
q[i] = step();
}
cnt = 0;
}
public String getAlgorithmName()
{
return "HC-128";
}
public void init(boolean forEncryption, CipherParameters params)
throws IllegalArgumentException
{
CipherParameters keyParam = params;
if (params instanceof ParametersWithIV)
{
iv = ((ParametersWithIV)params).getIV();
keyParam = ((ParametersWithIV)params).getParameters();
}
else
{
iv = new byte[0];
}
if (keyParam instanceof KeyParameter)
{
key = ((KeyParameter)keyParam).getKey();
init();
}
else
{
throw new IllegalArgumentException(
"Invalid parameter passed to HC128 init - "
+ params.getClass().getName());
}
initialised = true;
}
private byte[] buf = new byte[4];
private int idx = 0;
private byte getByte()
{
if (idx == 0)
{
int step = step();
buf[3] = (byte)(step & 0xFF);
step >>= 8;
buf[2] = (byte)(step & 0xFF);
step >>= 8;
buf[1] = (byte)(step & 0xFF);
step >>= 8;
buf[0] = (byte)(step & 0xFF);
}
byte ret = buf[idx];
idx = idx + 1 & 0x3;
return ret;
}
public void processBytes(byte[] in, int inOff, int len, byte[] out,
int outOff) throws DataLengthException
{
if (!initialised)
{
throw new IllegalStateException(getAlgorithmName()
+ " not initialised");
}
if ((inOff + len) > in.length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + len) > out.length)
{
throw new DataLengthException("output buffer too short");
}
for (int i = 0; i < len; i++)
{
out[outOff + i] = (byte)(in[inOff + i] ^ getByte());
}
}
public void reset()
{
idx = 0;
init();
}
public byte returnByte(byte in)
{
return (byte)(in ^ getByte());
}
}
|
package org.jetel.interpreter;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.parser.Parser;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.interpreter.ASTnode.CLVFStart;
import org.jetel.interpreter.ASTnode.CLVFStartExpression;
import org.jetel.interpreter.data.TLValue;
import org.jetel.interpreter.data.TLVariable;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.string.StringUtils;
/**
* @author dpavlis
* @since 10.8.2004
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class TestInterpreter extends TestCase {
DataRecordMetadata metadata,metadata1,metaOut,metaOut1;
DataRecord record,record1,out,out1;
TransformationGraph graph;
LookupTable lkp;
private GregorianCalendar today;
protected void setUp() {
EngineInitializer.initEngine((String) null, null, null);
graph=new TransformationGraph();
metadata=new DataRecordMetadata("in",DataRecordMetadata.DELIMITED_RECORD);
metadata.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metadata.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metadata.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metadata1=new DataRecordMetadata("in1",DataRecordMetadata.DELIMITED_RECORD);
metadata1.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metadata1.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metadata1.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metadata1.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metadata1.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metaOut=new DataRecordMetadata("out",DataRecordMetadata.DELIMITED_RECORD);
metaOut.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metaOut.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metaOut.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metaOut.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metaOut.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
metaOut1=new DataRecordMetadata("out1",DataRecordMetadata.DELIMITED_RECORD);
metaOut1.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metaOut1.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metaOut1.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metaOut1.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metaOut1.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
record = new DataRecord(metadata);
record.init();
record1 = new DataRecord(metadata1);
record1.init();
out = new DataRecord(metaOut);
out.init();
out1 = new DataRecord(metaOut1);
out1.init();
SetVal.setString(record,0," HELLO ");
SetVal.setString(record1,0," My name ");
SetVal.setInt(record,1,135);
SetVal.setDouble(record1,1,13.5);
SetVal.setString(record,2,"Some silly longer string.");
SetVal.setString(record1,2,"Prague");
today = (GregorianCalendar)Calendar.getInstance();
SetVal.setValue(record1,3,today.getTime());
record.getField("Born").setNull(true);
SetVal.setInt(record,4,-999);
record1.getField("Value").setNull(true);
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE",
new Object[]{"test",graph,"test"}, new Class[]{String.class,TransformationGraph.class,String.class});
graph.addSequence(seq);
try {
seq.init();
} catch (ComponentNotReadyException e) {
throw new RuntimeException(e);
}
// LookupTable lkp=new SimpleLookupTable("LKP", metadata, new String[] {"Name"}, null);
lkp = LookupTableFactory.createLookupTable(graph, "simpleLookup",
new Object[]{"LKP" , metadata ,new String[] {"Name"} , null}, new Class[]{String.class,
DataRecordMetadata.class, String[].class, Parser.class});
try {
lkp.init();
graph.addLookupTable(lkp);
}catch(Exception ex) {
throw new RuntimeException(ex);
}
lkp.put("one",record);
record.getField("Name").setValue("xxxx");
lkp.put("two", record);
// RecordKey key = new RecordKey(new int[]{0}, metadata);
// key.init();
// lkp.setLookupKey(key);
// DataRecord keyRecord = new DataRecord(metadata);
// keyRecord.init();
// keyRecord.getField(0).setValue("one");
lkp.setLookupKey("nesmysl");
}
protected void tearDown() {
metadata= null;
record=null;
out=null;
}
public void testA_lexer(){
//new ByteArrayInputStream("\"([^\\\\|]*\\\\|){3}\"".getBytes())
/*System.out.print("enter token string:");
JavaCharStream cs=new JavaCharStream(System.in);
TransformLangParserTokenManager ltm;
ltm=new TransformLangParserTokenManager(cs);
Token t = ltm.getNextToken();
System.out.println(t.image);*/
//assertEquals(t.kind,TransformLangParserConstants.STRING_LITERAL);
// test expression
System.out.print("enter exp string: ");
String strin="$Name~=\"([^\\\\|]*\\\\|){3}\"";
System.out.println(strin);
TransformLangParser parser = new TransformLangParser(metadata,strin);
CLVFStartExpression parseTree=null;
try{
parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
/*
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
*/
System.out.println("Finished interpreting.");
}catch(ParseException ex){
ex.printStackTrace();
}
}
public void test_int(){
System.out.println("int test:");
String expStr = "int i; i=0; print_err(i); \n"+
"int j; j=-1; print_err(j);\n"+
"int minInt; minInt="+Integer.MIN_VALUE+"; print_err(minInt, true);\n"+
"int maxInt; maxInt="+Integer.MAX_VALUE+"; print_err(maxInt, true);\n"+
"int field; field=$Value; print_err(field);";
try {
print_code(expStr);
TransformLangParser parser = new TransformLangParser(record.getMetadata(), expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(0,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt());
assertEquals(-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getTLValue().getNumeric().getInt());
assertEquals(Integer.MIN_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("minInt")).getTLValue().getNumeric().getInt());
assertEquals(Integer.MAX_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("maxInt")).getTLValue().getNumeric().getInt());
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("field")).getTLValue().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_long(){
System.out.println("\nlong test:");
String expStr = "long i; i=0; print_err(i); \n"+
"long j; j=-1; print_err(j);\n"+
"long minLong; minLong="+(Long.MIN_VALUE+1)+"; print_err(minLong);\n"+
"long maxLong; maxLong="+(Long.MAX_VALUE)+"; print_err(maxLong);\n"+
"long field; field=$Value; print_err(field);\n"+
"long wrong;wrong="+Long.MAX_VALUE+"; print_err(wrong);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(0,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getLong());
assertEquals(-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getTLValue().getNumeric().getLong());
assertEquals(Long.MIN_VALUE+1,executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getTLValue().getNumeric().getLong());
assertEquals(Long.MAX_VALUE,executor.getGlobalVariable(parser.getGlobalVariableSlot("maxLong")).getTLValue().getNumeric().getLong());
assertEquals(((Integer)record.getField("Value").getValue()).longValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("field")).getTLValue().getNumeric().getLong());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_decimal(){
System.out.println("\ndecimal test:");
String expStr = "decimal i; i=0; print_err(i); \n"+
"decimal j; j=-1.0; print_err(j);\n"+
"decimal(18,3) minLong; minLong=999999.999d; print_err(minLong);\n"+
"decimal maxLong; maxLong=0000000.0000000; print_err(maxLong);\n"+
"decimal fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"decimal fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"decimal(400,350) minDouble; minDouble="+Double.MIN_VALUE+"d; print_err(minDouble);\n" +
"decimal def;print_err(def);\n" +
"print_err('the end');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getTLValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(999999.999),executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getTLValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("maxLong")).getTLValue().getNumeric());
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldValue")).getTLValue().getNumeric().getInt());
assertEquals((Double)record.getField("Age").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldAge")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(Double.MIN_VALUE),executor.getGlobalVariable(parser.getGlobalVariableSlot("minDouble")).getTLValue().getNumeric().getDouble());
assertTrue(executor.getGlobalVariable(parser.getGlobalVariableSlot("def")).getTLValue().getNumeric().isNull());
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_number(){
System.out.println("\nnumber test:");
String expStr = "number i; i=0; print_err(i); \n"+
"number j; j=-1.0; print_err(j);\n"+
"number minLong; minLong=999999.99911; print_err(minLong); \n"+
"number fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"number fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"number minDouble; minDouble="+Double.MIN_VALUE+"; print_err(minDouble);\n" +
"number def;print_err(def);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(), expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(999999.99911),executor.getGlobalVariable(parser.getGlobalVariableSlot("minLong")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(((Integer)record.getField("Value").getValue())),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldValue")).getTLValue().getNumeric().getDouble());
assertEquals(new Double((Double)record.getField("Age").getValue()),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldAge")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(Double.MIN_VALUE),executor.getGlobalVariable(parser.getGlobalVariableSlot("minDouble")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("def")).getTLValue().getNumeric().getDouble());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_string(){
System.out.println("\nstring test:");
int lenght=1000;
StringBuilder tmp = new StringBuilder(lenght);
for (int i=0;i<lenght;i++){
tmp.append(i%10);
}
String expStr = "string i; i=\"0\"; print_err(i); \n"+
"string hello; hello='hello\\nworld'; print_err(hello);\n"+
"string fieldName; fieldName=$Name; print_err(fieldName);\n"+
"string fieldCity; fieldCity=$City; print_err(fieldCity);\n"+
"string longString; longString=\""+tmp+"\"; print_err(longString);\n"+
"string specialChars; specialChars='a\u0101\u0102A'; print_err(specialChars);\n" +
"string empty=\"\";print_err(empty+specialChars);\n" +
"print_err(\"\"+specialChars);\n" +
"print_err(concat('', specialChars));\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes("UTF-8")));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("0",executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().toString());
assertEquals("hello\\nworld",executor.getGlobalVariable(parser.getGlobalVariableSlot("hello")).getTLValue().toString());
assertEquals(record.getField("Name").getValue().toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldName")).getTLValue().toString());
assertEquals(record.getField("City").getValue().toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("fieldCity")).getTLValue().toString());
assertEquals(tmp.toString(),executor.getGlobalVariable(parser.getGlobalVariableSlot("longString")).getTLValue().toString());
assertEquals("a\u0101\u0102A",executor.getGlobalVariable(parser.getGlobalVariableSlot("specialChars")).getTLValue().toString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
} catch (UnsupportedEncodingException ex){
ex.printStackTrace();
}
}
public void test_date(){
System.out.println("\ndate test:");
String expStr = "date d3; d3=2006-08-01; print_err(d3);\n"+
"date d2; d2=2006-08-02 15:15:00 ; print_err(d2);\n"+
"date d1; d1=2006-1-1 1:2:3; print_err(d1);\n"+
"date born; born=$0.Born; print_err(born);\n" +
"date dnull = null; print_err(dnull);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(new GregorianCalendar(2006,7,01).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d3")).getTLValue().getDate());
assertEquals(new GregorianCalendar(2006,7,02,15,15).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d2")).getTLValue().getDate());
assertEquals(new GregorianCalendar(2006,0,01,01,02,03).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("d1")).getTLValue().getDate());
assertEquals((Date)record.getField("Born").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("born")).getTLValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_boolean(){
System.out.println("\nboolean test:");
String expStr = "boolean b1; b1=true; print_err(b1);\n"+
"boolean b2; b2=false ; print_err(b2);\n"+
"boolean b4; print_err(b4);";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b1")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("b2")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("b4")).getTLValue()==TLValue.TRUE_VAL);
assertTrue(executor.getGlobalVariable(parser.getGlobalVariableSlot("b4")).isNullable());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_variables(){
System.out.println("\nvariable test:");
String expStr = "boolean b1; boolean b2; b1=true; print_err(b1);\n"+
"b2=false ; print_err(b2);\n"+
"string b4; b4=\"hello\"; print_err(b4);\n"+
"b2 = true; print_err(b2);\n" +
"int in;\n" +
"if (b2) {in=2;print_err('in');}\n"+
"print_err(b2);\n" +
"b4=null; print_err(b4);\n"+
"b4='hi'; print_err(b4);";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b1")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("b2")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("hi",executor.getGlobalVariable(parser.getGlobalVariableSlot("b4")).getTLValue().toString());
// assertEquals(2,executor.getGlobalVariable(parser.getGlobalVariableSlot("in")).getValue().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_plus(){
System.out.println("\nplus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i+j; print_err(\"plus int:\"+iplusj);\n" +
"long l;l="+Integer.MAX_VALUE/10+"l;print_err(l);\n" +
"long m;m="+(Integer.MAX_VALUE)+"l;print_err(m);\n" +
"long lplusm;lplusm=l+m;print_err(\"plus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n+m1;print_err(\"plus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n+j;print_err(\"number plus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d+d1;print_err(\"plus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d+j;print_err(\"decimal plus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d+m1;print_err(\"decimal plus number:\"+dplusn);\n" +
"dplusn=dplusn+10;\n" +
"string s; s=\"hello\"; print_err(s);\n" +
"string s1;s1=\" world\";print_err(s1);\n " +
"string spluss1;spluss1=s+s1;print_err(\"adding strings:\"+spluss1);\n" +
"string splusm1;splusm1=s+m1;print_err(\"string plus decimal:\"+splusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate+i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("iplusj",110,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getTLValue().getNumeric().getInt()));
assertEquals("lplusm",(long)Integer.MAX_VALUE+(long)Integer.MAX_VALUE/10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getTLValue().getNumeric().getLong());
assertEquals("nplusm1",new Double(0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getTLValue().getNumeric().getDouble());
assertEquals("nplusj",new Double(100),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusj")).getTLValue().getNumeric().getDouble());
assertEquals("dplusd1",new Double(0.1000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getTLValue().getNumeric().getDouble());
assertEquals("dplusj",new Double(100.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getTLValue().getNumeric().getDouble());
assertEquals("dplusn",new Double(10.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getTLValue().getNumeric().getDouble());
assertEquals("spluss1","hello world",executor.getGlobalVariable(parser.getGlobalVariableSlot("spluss1")).getTLValue().toString());
assertEquals("splusm1","hello0.0010",executor.getGlobalVariable(parser.getGlobalVariableSlot("splusm1")).getTLValue().toString());
assertEquals("dateplus",new GregorianCalendar(2004,01,9,15,00,30).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("dateplus")).getTLValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_minus(){
System.out.println("\nminus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i-j; print_err(\"minus int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l-m;print_err(\"minus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n-m1;print_err(\"minus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n-j;print_err(\"number minus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001d;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d-d1;print_err(\"minus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d-j;print_err(\"decimal minus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d-m1;print_err(\"decimal minus number:\"+dplusn);\n" +
"number d1minusm1;d1minusm1=d1-m1;print_err('decimal minus number = number:'+d1minusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate-i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("iplusj",-90,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getTLValue().getNumeric().getInt()));
assertEquals("lplusm",(long)Integer.MAX_VALUE+9,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getTLValue().getNumeric().getLong());
assertEquals("nplusm1",new Double(-0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getTLValue().getNumeric().getDouble());
assertEquals("nplusj",new Double(-100),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusj")).getTLValue().getNumeric().getDouble());
// Decimal tmp = DecimalFactory.getDecimal(0.1);
// tmp.sub(DecimalFactory.getDecimal(0.0001,10,4));
// assertEquals("dplusd1",tmp, executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getValue().getNumeric());
assertEquals("dplusd1",DecimalFactory.getDecimal(0.09), executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getTLValue().getNumeric());
assertEquals("dplusj",new Double(-99.9),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getTLValue().getNumeric().getDouble());
assertEquals("dplusn",new Double(0.0900),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getTLValue().getNumeric().getDouble());
assertEquals("d1minusm1",new Double(-0.0009),executor.getGlobalVariable(parser.getGlobalVariableSlot("d1minusm1")).getTLValue().getNumeric().getDouble());
assertEquals("dateplus",new GregorianCalendar(2004,0,20,15,00,30).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("dateplus")).getTLValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_multiply(){
System.out.println("\nmultiply test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i*j; print_err(\"multiply int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l*m;print_err(\"multiply long:\"+lplusm);\n" +
"number n; n=0.1;print_err(n);\n" +
"number m1; m1=-0.01;print_err(m1);\n" +
"number nplusm1; nplusm1=n*m1;print_err(\"multiply number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=m1*j;print_err(\"number multiply int:\"+m1plusj);\n"+
"decimal(8,4) d; d=0.1; print_err(d);\n" +
"decimal(10,4) d1; d1=10.01d;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d*d1;print_err(\"multiply decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d*j;print_err(\"decimal multiply int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=d*n;print_err(\"decimal multiply number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("i*j",1000,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getTLValue().getNumeric().getInt()));
assertEquals("l*m",(long)Integer.MAX_VALUE+10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getTLValue().getNumeric().getLong());
assertEquals("n*m1",new Double(-0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getTLValue().getNumeric().getDouble());
assertEquals("m1*j",new Double(-1),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getTLValue().getNumeric().getDouble());
assertEquals("d*d1",DecimalFactory.getDecimal(1.001,10,4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getTLValue().getNumeric());
assertEquals("d*j",DecimalFactory.getDecimal(10,10,4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getTLValue().getNumeric());
assertEquals("d*n",DecimalFactory.getDecimal(0.01, 10, 4),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getTLValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_division(){
System.out.println("\ndivision test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i/j; print_err(\"div int:\"+iplusj);\n" +
"int jdivi;jdivi=j/i; print_err(\"div int:\"+jdivi);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m);\n" +
"long lplusm;lplusm=l/m;print_err(\"div long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.01;print_err(m1);\n" +
"number n1; n1=10;print_err(n1);\n" +
"number nplusm1; nplusm1=n/m1;print_err(\"0/0.01:\"+nplusm1);\n" +
"number m1divn; m1divn=m1/n;print_err(\"deleni nulou:\"+m1divn);\n" +
"number m1divn1; m1divn1=m1/n1;print_err(\"deleni numbers:\"+m1divn1);\n" +
"number m1plusj;m1plusj=j/n1;print_err(\"number division int:\"+m1plusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.01;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d/d1;print_err(\"div decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d/j;print_err(\"decimal div int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=n1/d;print_err(\"decimal div number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("i/j",0,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getTLValue().getNumeric().getInt()));
assertEquals("j/i",10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("jdivi")).getTLValue().getNumeric().getInt()));
assertEquals("l/m",(long)Integer.MAX_VALUE+10,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getTLValue().getNumeric().getLong());
assertEquals("n/m1",new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getTLValue().getNumeric().getDouble());
assertEquals("m1/n",new Double(Double.POSITIVE_INFINITY),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1divn")).getTLValue().getNumeric().getDouble());
assertEquals("m1/n1",new Double(0.001),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1divn1")).getTLValue().getNumeric().getDouble());
assertEquals("j/n1",new Double(10),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getTLValue().getNumeric().getDouble());
assertEquals("d/d1",DecimalFactory.getDecimal(0.1/0.01),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getTLValue().getNumeric());
assertEquals("d/j",DecimalFactory.getDecimal(0.0000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getTLValue().getNumeric());
assertEquals("n1/d",DecimalFactory.getDecimal(100.0000),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getTLValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_modulus(){
System.out.println("\nmodulus test:");
String expStr = "int i; i=10;\n"+
"int j; j=103;\n" +
"int iplusj;iplusj=j%i; print_err(\"mod int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=2;print_err(m);\n" +
"long lplusm;lplusm=l%m;print_err(\"mod long:\"+lplusm);\n" +
"number n; n=10.2;print_err(n);\n" +
"number m1; m1=2;print_err(m1);\n" +
"number nplusm1; nplusm1=n%m1;print_err(\"mod number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=n%i;print_err(\"number mod int:\"+m1plusj);\n"+
"decimal d; d=10.1;print_err(d);\n" +
"decimal(10,4) d1; d1=10;print_err(d1);\n" +
"decimal dplusd1; dplusd1=d%d1;print_err(\"mod decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d1%j;print_err(\"decimal mod int:\"+dplusj);\n"+
"decimal dplusn;dplusn=d%m1;print_err(\"decimal mod number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(3,(executor.getGlobalVariable(parser.getGlobalVariableSlot("iplusj")).getTLValue().getNumeric().getInt()));
assertEquals(((long)Integer.MAX_VALUE+10)%2,executor.getGlobalVariable(parser.getGlobalVariableSlot("lplusm")).getTLValue().getNumeric().getLong());
assertEquals(new Double(10.2%2),executor.getGlobalVariable(parser.getGlobalVariableSlot("nplusm1")).getTLValue().getNumeric().getDouble());
assertEquals(new Double(10.2%10),executor.getGlobalVariable(parser.getGlobalVariableSlot("m1plusj")).getTLValue().getNumeric().getDouble());
assertEquals(DecimalFactory.getDecimal(0.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusd1")).getTLValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(10),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusj")).getTLValue().getNumeric());
assertEquals(DecimalFactory.getDecimal(0.1),executor.getGlobalVariable(parser.getGlobalVariableSlot("dplusn")).getTLValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_increment_decrement(){
System.out.println("\nincrement-decrement test:");
String expStr = "int i; i=10;print_err(++i);\n" +
"i
"print_err(--i);\n"+
"long j;j="+(Long.MAX_VALUE-10)+"l;print_err(++j);\n" +
"print_err(--j);\n"+
"decimal d;d=2;d++;\n" +
"print_err(--d);\n;" +
"number n;n=3.5;print_err(++n);\n" +
"n
"{print_err(++n);}\n" +
"print_err(++n);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(9,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
assertEquals(new CloverLong(Long.MAX_VALUE-10).
getLong(),executor.getGlobalVariable(parser.getGlobalVariableSlot("j")).getTLValue().getNumeric().getLong());
assertEquals(DecimalFactory.getDecimal(2),executor.getGlobalVariable(parser.getGlobalVariableSlot("d")).getTLValue().getNumeric());
assertEquals(new Double(5.5),executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getTLValue().getNumeric().getDouble());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_equal(){
System.out.println("\nequal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i==j+1);print_err(\"eq1=\"+eq1);\n" +
// "boolean eq1;eq1=(i.eq.(j+1));print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l==j);print_err(\"eq2=\"+eq2);\n" +
"eq2=(l.eq.i);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d==i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.eq.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n==d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello \";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s.eq.s1;print_err(\"eq6=\"+eq6);\n" +
"boolean eq7;eq7=s==trim(s1);print_err(\"eq7=\"+eq7);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate);\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate.eq.anothermydate;print_err(\"eq8=\"+eq8);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq9;eq9=mydate==anothermydate;print_err(\"eq9=\"+eq9);\n" +
"boolean eq10;eq10=eq9.eq.eq8;print_err(\"eq10=\"+eq10);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq4")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq5")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq6")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq7")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq8")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq9")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq10")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_non_equal(){
System.out.println("\nNon equal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i!=j);print_err(\"eq1=\");print_err(eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l<>j);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d.ne.i;print_err(\"eq3=\");print_err(eq3);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getTLValue()==TLValue.TRUE_VAL);
assertEquals(false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_greater_less(){
System.out.println("\nGreater and less test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i>j);print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l>=j);print_err(\"eq2=\"+eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d=>i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.gt.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n.ge.d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello\";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s<s1;print_err(\"eq6=\"+eq6);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate);\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq7;eq7=mydate.lt.anothermydate;print_err(\"eq7=\"+eq7);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate<=anothermydate;print_err(\"eq8=\"+eq8);\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("eq1",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq1")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq2",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq3",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq3")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq4",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq4")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq5",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq5")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq6",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq6")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq7",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq7")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("eq8",true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq8")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_regex(){
System.out.println("\nRegex test:");
String expStr = "string s;s='Hej';print_err(s);\n" +
"boolean eq2;eq2=(s~=\"[A-Za-z]{3}\");\n" +
"print_err(\"eq2=\"+eq2);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("eq2")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_1_expression() {
String expStr="$Age>=135 or 200>$Age and not $Age<=0 and 1==999999999999999 or $Name==\"HELLO\"";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true, executor.getResult()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_2_expression() {
String expStr="datediff(nvl($Born,2005-2-1),2005-1-1,month)";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(1, executor.getResult().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_3_expression() {
// String expStr="not (trim($Name) .ne. \"HELLO\") || replace($Name,\".\" ,\"a\")=='aaaaaaa'";
String expStr="print_err(trim($Name)); print_err(replace('xyyxyyxzz',\"x\" ,\"ab\")); print_err('aaaaaaa'); print_err(split('abcdef','c'));";
print_code(expStr);
try {
System.out.println("in Test3expression");
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
// CLVFStartExpression parseTree = parser.StartExpression();
parseTree.dump("ccc");
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.err.println(it.next());
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
// assertEquals(false, executor.getResult()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_if(){
System.out.println("\nIf statement test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"long l;" +
"if (i>j) l=1; else l=0;\n" +
"print_err(l);\n" +
"decimal d;" +
"if (i.gt.j and l.eq.1) {d=0;print_err('d rovne 0');}\n" +
"else d=0.1;\n" +
"number n;\n" +
"if (d==0.1) n=0;\n" +
"if (d==0.1 || l<=1) n=0;\n" +
"else {n=-1;print_err('n rovne -1');}\n" +
"date date1; date1=2006-01-01;print_err(date1);\n" +
"date date2; date2=2006-02-01;print_err(date2);\n" +
"boolean result;result=false;\n" +
"boolean compareDates;compareDates=date1<=date2;print_err(compareDates);\n" +
"if (date1<=date2) \n" +
"{ print_err('before if (i<j)');\n" +
" if (i<j) print_err('date1<today and i<j'); else print_err('date1<date2 only');\n" +
" result=true;}\n" +
"result=false;" +
"if (i<j) result=true;\n" +
"else if (not result) result=true;\n" +
"else print_err('last else');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals(1,executor.getGlobalVariable(parser.getGlobalVariableSlot("l")).getTLValue().getNumeric().getLong());
assertEquals(DecimalFactory.getDecimal(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("d")).getTLValue().getNumeric());
assertEquals(new Double(0),executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getTLValue().getNumeric().getDouble());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("result")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_switch(){
System.out.println("\nSwitch test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"int n;n=date2num(born,month);print_err(n);\n" +
"string mont;\n" +
"decimal april;april=4;\n" +
"switch (n) {\n" +
" case 0.0:mont='january';\n" +
" case 1.0:mont='february';\n" +
" case 2.0:mont='march';\n" +
" case 3:mont='april';\n" +
" case april:mont='may';\n" +
" case 5.0:mont='june';\n" +
" case 6.0:mont='july';\n" +
" case 7.0:mont='august';\n" +
" case 3:print_err('4th month');\n" +
" case 8.0:mont='september';\n" +
" case 9.0:mont='october';\n" +
" case 10.0:mont='november';\n" +
" case 11.0:mont='december';\n" +
" default: mont='unknown';};\n"+
"print_err('month:'+mont);\n" +
"boolean ok;ok=(n.ge.0)and(n.lt.12);\n" +
"switch (ok) {\n" +
" case true:print_err('OK');\n" +
" case false:print_err('WRONG');};\n" +
"switch (born) {\n" +
" case 2006-01-01:{mont='January';print_err('january');}\n" +
" case 1973-04-23:{mont='April';print_err('april');}}\n" +
"// default:print_err('other')};\n"+
"switch (born<1996-08-01) {\n" +
" case true:{print_err('older then ten');}\n" +
" default:print_err('younger then ten');};\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(3,executor.getGlobalVariable(parser.getGlobalVariableSlot("n")).getTLValue().getNumeric().getInt());
assertEquals("April",executor.getGlobalVariable(parser.getGlobalVariableSlot("mont")).getTLValue().toString());
assertEquals(true,executor.getGlobalVariable(parser.getGlobalVariableSlot("ok")).getTLValue()==TLValue.TRUE_VAL);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_while(){
System.out.println("\nWhile test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"while (born<now) {\n" +
" born=dateadd(born,1,year);\n " +
" while (yer<5) yer=yer+1;\n" +
" yer=yer+1;}\n" +
"print_err('years:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
GregorianCalendar b,n;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
n = new GregorianCalendar();
int diff = n.get(Calendar.YEAR) - b.get(Calendar.YEAR) + 5;
b.set(Calendar.YEAR, 0);
n.set(Calendar.YEAR, 0);
if (n.after(b)) {diff++;}
assertEquals(diff,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_do_while(){
System.out.println("\nDo-while test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"do {\n" +
" born=dateadd(born,1,year);\n " +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" do yer=yer+1; while (yer<5);\n" +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" yer=yer+1;}\n" +
"while (born<now)\n" +
"print_err('years on the end:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
GregorianCalendar b,n;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
n = new GregorianCalendar();
int diff = n.get(Calendar.YEAR) - b.get(Calendar.YEAR);
b.set(Calendar.YEAR, 0);
n.set(Calendar.YEAR, 0);
if (n.after(b)) {diff++;}
assertEquals(2 * (diff) + 4,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_for(){
System.out.println("\nFor test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"for (born;born<now;born=dateadd(born,1,year)) yer++;\n" +
"print_err('years on the end:'+yer);\n" +
"boolean b;\n" +
"for (born;!b;++yer) \n" +
" if (yer==100) b=true;\n" +
"print_err(born);\n" +
"print_err('years on the end:'+yer);\n" +
"print_err('born:'+born);\n"+
"int i;\n" +
"for (i=0;i.le.10;++i) ;\n" +
"print_err('on the end i='+i);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
int iVarSlot=parser.getGlobalVariableSlot("i");
int yerVarSlot=parser.getGlobalVariableSlot("yer");
TLVariable[] result = executor.stack.globalVarSlot;
assertEquals(101,result[yerVarSlot].getTLValue().getNumeric().getInt());
assertEquals(11,result[iVarSlot].getTLValue().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_for2(){
System.out.println("\nFor test:");
String expStr ="int i;int yer;yer=0;\n" +
"for (i=0;i.le.10;++i) ;\n" +
"print_err('on the end i='+i);\n" +
"int j=1;long l=123456789012345678L;\n" +
"for (j=5;j<i;++j){\n" +
" l=l-i;}";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
int iVarSlot=parser.getGlobalVariableSlot("i");
int jVarSlot=parser.getGlobalVariableSlot("j");
TLVariable[] result = executor.stack.globalVarSlot;
assertEquals(11,result[jVarSlot].getTLValue().getNumeric().getInt());
assertEquals(11,result[iVarSlot].getTLValue().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_break(){
System.out.println("\nBreak test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"while (born<now) {\n" +
" yer++;\n" +
" born=dateadd(born,1,year);\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
GregorianCalendar b,n;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
n = new GregorianCalendar();
int diff = n.get(Calendar.YEAR) - b.get(Calendar.YEAR);
b.set(Calendar.YEAR, 0);
n.set(Calendar.YEAR, 0);
if (n.after(b)) {diff++;}
assertEquals(diff,
(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getTLValue().getNumeric().getInt()));
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_break2(){
System.out.println("\nBreak test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now; now=today(); print_err(now);\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"while (yer<date2num(now,year)) {\n" +
" yer++;\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals((new GregorianCalendar()).get(Calendar.YEAR),(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getTLValue().getNumeric().getInt()));
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_continue(){
System.out.println("\nContinue test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"for (i=0;i<10;i=i+1) {\n" +
" print_err('i='+i);\n" +
" if (i>5) continue;\n" +
" print_err('After if');" +
"}\n" +
"print_err('new loop starting');\n" +
"print_err('born '+born+' now '+now);\n"+
"while (born<now) {\n" +
" print_err('i='+i);i=0;\n" +
" print_err(yer);\n" +
" yer=yer+1;\n" +
" born=dateadd(born,1,year);\n" +
" if (yer>30) continue\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break;\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
GregorianCalendar b,n;
b= new GregorianCalendar();
b.setTime(((Date)record.getField("Born").getValue()));
n = new GregorianCalendar();
int diff = n.get(Calendar.YEAR) - b.get(Calendar.YEAR);
b.set(Calendar.YEAR, 0);
n.set(Calendar.YEAR, 0);
if (n.after(b)) {diff++;}
assertEquals(diff,(executor.getGlobalVariable(parser.getGlobalVariableSlot("yer")).getTLValue().getNumeric().getInt()));
assertEquals(0,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_continue2(){
System.out.println("\nContinue test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"for (i=0;i<10;i=i+1) {\n" +
" print_err('i='+i);\n" +
" if (i>5) continue;\n" +
" print_err('After if');" +
"}\n" +
"print_err('i after f:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_return(){
System.out.println("\nReturn test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"function year_before(now) {\n" +
" return dateadd(now,-1,year);" +
"}\n" +
"function age(born){\n" +
" date now;int yer;\n" +
" now=today();yer=0;\n" +
" for (born;born<now;born=dateadd(born,1,year)) yer++;\n" +
" if (yer>0) return yer else return -1;" +
"}\n" +
"print_err('years born'+age(born));\n" +
"print_err(\"year before:\"+year_before(born));\n" +
" while (true) {print_err('pred return');" +
"return;\n" +
"print_err('po return');}\n" +
"print_err('za blokem');\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
for(Iterator iter=parser.getParseExceptions().iterator();iter.hasNext();){
System.err.println(iter.next());
}
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
//TODO
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_list_map(){
System.out.println("\nList/Map test:");
String expStr = "list seznam; list seznam2; list fields;\n"+
"map mapa; mapa['f1']=10; mapa['f2']='hello'; map mapa2; mapa2[]=mapa; map mapa3; \n"+
"int i; for(i=0;i<20;i++) { seznam[]=i; if (i>10) seznam2[]=seznam; }\n"+
"seznam[1]=999; seznam2[3]='hello'; \n"+
"fields=split('a,b,c,d,e,f,g,h',','); fields[]=null;"+
"int length=length(seznam); print_err('length: '+length);\n print_err(seznam);\n print_err(seznam2); print_err(fields);\n"+
"list novy; novy[]=mapa; print_err('novy1:'+novy); mapa2['f2']='xxx'; novy[]=mapa2; mapa['f1']=99; novy[]=mapa; \n" +
"print_err('novy='+novy); print_err(novy[1]); \n" +
"print_err('novy[2]:'+novy[2]); mapa3=novy[2]; print_err(mapa2['f2']); print_err(mapa3); \n" +
"fields=seznam2; print_err(fields);\n" +
"print_err(join(':del:',seznam,mapa,novy[1]));\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
TransformLangParser parser=null;
try {
parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("lengh",20,executor.getGlobalVariable(parser.getGlobalVariableSlot("length")).getTLValue().getNumeric().getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
Iterator it=parser.getParseExceptions().iterator();
while(it.hasNext()){
System.err.println(((Throwable)it.next()).getMessage());
}
throw new RuntimeException("Parse exception",e);
}
}
public void test_list_map2(){
// TODO rozchodit tento test
/*
System.out.println("\nList/Map test2:");
String expStr = "list novy=[1,2,3,4,5,6,7,8];\n" +
"print_err('novy: ' + novy);\n" +
"novy[]=[9,8,7,6,5];\n"+
"print_err('novy: ' + novy);\n" +
"int index=1; print_err('novy with index '+index);\n"+
"print_err(' content: '+novy[index]);\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
TransformLangParser parser=null;
try {
parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
Iterator it=parser.getParseExceptions().iterator();
while(it.hasNext()){
System.err.println(((Throwable)it.next()).getMessage());
}
throw new RuntimeException("Parse exception",e);
}
*/
}
public void test_buildInFunctions(){
System.out.println("\nBuild-in functions test:");
String expStr = "string s;s='hello world';\n" +
"number lenght;lenght=5.5;\n" +
"string subs;subs=substring(s,1,lenght);\n" +
"print_err('original string:'+s );\n" +
"print_err('substring:'+subs );\n" +
"string upper;upper=uppercase(subs);\n" +
"print_err('to upper case:'+upper );\n"+
"string lower;lower=lowercase(subs+'hI ');\n" +
"print_err('to lower case:'+lower );\n"+
"string t;t=trim('\t im '+lower);\n" +
"print_err('after trim:'+t );\n" +
"breakpoint();\n" +
"//print_stack();\n"+
"decimal l;l=length(upper);\n" +
"print_err('length of '+upper+':'+l );\n"+
"string c;c=concat(lower,upper,2,',today is ',today());\n" +
"print_err('concatenation \"'+lower+'\"+\"'+upper+'\"+2+\",today is \"+today():'+c );\n"+
"date datum; date born;born=nvl($Born,today()-365);\n" +
"print_err('born=' + born);\n" +
"datum=dateadd(born,100,millisec);\n" +
"print_err('dataum = ' + datum );\n"+
"long ddiff;date otherdate;otherdate=today();\n" +
"ddiff=datediff(born,otherdate,year);\n" +
"print_err('date diffrence:'+ddiff );\n" +
"print_err('born: '+born+' otherdate: '+otherdate);\n" +
"boolean isn;isn=isnull(ddiff);\n" +
"print_err(isn );\n" +
"number s1;s1=nvl(l+1,1);\n" +
"print_err(s1 );\n" +
"string rep;rep=replace(c,'[lL]','t');\n" +
"print_err(rep );\n" +
"decimal(10,5) stn;stn=str2num('2.5125e-1',decimal);\n" +
"print_err(stn );\n" +
"int i = str2num('1234');\n" +
"string nts;nts=num2str(10,4);\n" +
"print_err(nts );\n" +
"date newdate;newdate=2001-12-20 16:30:04;\n" +
"decimal dtn;dtn=date2num(newdate,month);\n" +
"print_err(dtn );\n" +
"int ii;ii=iif(newdate<2000-01-01,20,21);\n" +
"print_err('ii:'+ii);\n" +
"print_stack();\n" +
"date ndate;ndate=2002-12-24;\n" +
"string dts;dts=date2str(ndate,'yy.MM.dd');\n" +
"print_err('date to string:'+dts);\n" +
"print_err(str2date(dts,'yy.MM.dd'));\n" +
"string lef=left(dts,5);\n" +
"string righ=right(dts,5);\n" +
"print_err('s=word, soundex='+soundex('word'));\n" +
"print_err('s=world, soundex='+soundex('world'));\n" +
"int j;for (j=0;j<length(s);j++){print_err(char_at(s,j));};\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("subs","ello ",executor.getGlobalVariable(parser.getGlobalVariableSlot("subs")).getTLValue().toString());
assertEquals("upper","ELLO ",executor.getGlobalVariable(parser.getGlobalVariableSlot("upper")).getTLValue().toString());
assertEquals("lower","ello hi ",executor.getGlobalVariable(parser.getGlobalVariableSlot("lower")).getTLValue().toString());
assertEquals("t(=trim)","im ello hi",executor.getGlobalVariable(parser.getGlobalVariableSlot("t")).getTLValue().toString());
assertEquals("l(=length)",5,executor.getGlobalVariable(parser.getGlobalVariableSlot("l")).getTLValue().getNumeric().getInt());
assertEquals("c(=concat)","ello hi ELLO 2,today is "+new Date(),executor.getGlobalVariable(parser.getGlobalVariableSlot("c")).getTLValue().toString());
// assertEquals("datum",record.getField("Born").getValue(),executor.getGlobalVariable(parser.getGlobalVariableSlot("datum")).getValue().getDate());
assertEquals("ddiff",-1,executor.getGlobalVariable(parser.getGlobalVariableSlot("ddiff")).getTLValue().getNumeric().getLong());
assertEquals("isn",false,executor.getGlobalVariable(parser.getGlobalVariableSlot("isn")).getTLValue()==TLValue.TRUE_VAL);
assertEquals("s1",new Double(6),executor.getGlobalVariable(parser.getGlobalVariableSlot("s1")).getTLValue().getNumeric().getDouble());
assertEquals("rep",("etto hi EttO 2,today is "+new Date()).replaceAll("[lL]", "t"),executor.getGlobalVariable(parser.getGlobalVariableSlot("rep")).getTLValue().toString());
assertEquals("stn",0.25125,executor.getGlobalVariable(parser.getGlobalVariableSlot("stn")).getTLValue().getNumeric().getDouble());
assertEquals("i",1234,executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt());
assertEquals("nts","22",executor.getGlobalVariable(parser.getGlobalVariableSlot("nts")).getTLValue().toString());
assertEquals("dtn",11.0,executor.getGlobalVariable(parser.getGlobalVariableSlot("dtn")).getTLValue().getNumeric().getDouble());
assertEquals("ii",21,executor.getGlobalVariable(parser.getGlobalVariableSlot("ii")).getTLValue().getNumeric().getInt());
assertEquals("dts","02.12.24",executor.getGlobalVariable(parser.getGlobalVariableSlot("dts")).getTLValue().toString());
assertEquals("lef","02.12",executor.getGlobalVariable(parser.getGlobalVariableSlot("lef")).getTLValue().toString());
assertEquals("righ","12.24",executor.getGlobalVariable(parser.getGlobalVariableSlot("righ")).getTLValue().toString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_functions2(){
System.out.println("\nFunctions test:");
String expStr = "string test='test';\n" +
"boolean isBlank=is_blank(test);\n" +
"boolean isBlank1=is_blank('');\n" +
"test=null; boolean isBlank2=is_blank(test);\n" +
"boolean isAscii1=is_ascii('test');\n" +
"boolean isAscii2=is_ascii('aęř');\n" +
"boolean isNumber=is_number('t1');\n" +
"boolean isNumber1=is_number('1g');\n" +
"boolean isNumber2=is_number('1'); print_err(str2num('1'));\n" +
"boolean isNumber3=is_number('-382.334'); print_err(str2num('-382.334',decimal));\n" +
"boolean isNumber4=is_number('+332e2');\n" +
"boolean isNumber5=is_number('8982.8992e-2');print_err(str2num('8982.8992e-2',double));\n" +
"boolean isNumber6=is_number('-7888873.2E3');print_err(str2num('-7888873.2E3',number));\n" +
"boolean isInteger=is_integer('h3');\n" +
"boolean isInteger1=is_integer('78gd');\n" +
"boolean isInteger2=is_integer('8982.8992');\n" +
"boolean isInteger3=is_integer('-766542378');print_err(str2num('-766542378'));\n" +
"boolean isLong=is_long('7864232568822234');\n" +
"boolean isDate5=is_date('20Jul2000','ddMMMyyyy','en.GB');print_err(str2date('20Jul2000','ddMMMyyyy','en.GB'));\n" +
"boolean isDate6=is_date('20July 2000','ddMMMMMMMMyyyy','en.GB');print_err(str2date('20July 2000','ddMMMyyyy','en.GB'));\n" +
"boolean isDate3=is_date('4:42','HH:mm');print_err(str2date('4:42','HH:mm'));\n" +
"boolean isDate=is_date('20.11.2007','dd.MM.yyyy');print_err(str2date('20.11.2007','dd.MM.yyyy'));\n" +
"boolean isDate1=is_date('20.11.2007','dd-MM-yyyy');\n" +
"boolean isDate2=is_date('24:00 20.11.2007','HH:mm dd.MM.yyyy');print_err(str2date('24:00 20.11.2007','HH:mm dd.MM.yyyy'));\n" +
"boolean isDate4=is_date('test 20.11.2007','hhmm dd.MM.yyyy');\n" +
"boolean isDate7=is_date('','HH:mm dd.MM.yyyy');print_err(str2date('','HH:mm dd.MM.yyyy'));\n" +
"boolean isDate8=is_date(' ','HH:mm dd.MM.yyyy');\n"+
"boolean isDate9=is_date('20-15-2007','dd-MM-yyyy');print_err(str2date('20-15-2007','dd-MM-yyyy'));\n" +
"boolean isDate10=is_date('20-15-2007','dd-MM-yyyy',false);\n" +
"boolean isDate11=is_date('20-15-2007','dd-MM-yyyy',true);\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isBlank")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isBlank1")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isBlank2")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isAscii1")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isAscii2")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber1")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber2")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber3")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber4")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber5")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isNumber6")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isInteger")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isInteger1")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isInteger2")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isInteger3")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isLong")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate1")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate2")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate3")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate4")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate5")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate6")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate7")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate8")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate9")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(false,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate10")).getTLValue()==TLValue.TRUE_VAL));
assertEquals(true,(executor.getGlobalVariable(parser.getGlobalVariableSlot("isDate11")).getTLValue()==TLValue.TRUE_VAL));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_functions3(){
System.out.println("\nFunctions test:");
String expStr = "string test=remove_diacritic('teścik');\n" +
"string test1=remove_diacritic('žabička');\n" +
"string r1=remove_blank_space(\"" +
StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") +
"\");\n" +
"string an1 = get_alphanumeric_chars(\"" +
StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") +
"\");\n" +
"string an2 = get_alphanumeric_chars(\"" +
StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") +
"\",true,true);\n" +
"string an3 = get_alphanumeric_chars(\"" +
StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") +
"\",true,false);\n" +
"string an4 = get_alphanumeric_chars(\"" +
StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") +
"\",false,true);\n" +
"string t=translate('hello','leo','pii');\n" +
"string t1=translate('hello','leo','pi');\n" +
"string t2=translate('hello','leo','piims');\n" +
"string t3=translate('hello','leo',null); print_err(t3);\n" +
"string t4=translate('my language needs the letter e', 'egms', 'X');\n" +
"string input='hello world';\n" +
"int index=index_of(input,'l');\n" +
"int index1=index_of(input,'l',5);\n" +
"int index2=index_of(input,'hello');\n" +
"int index3=index_of(input,'hello',1);\n" +
"int index4=index_of(input,'world',1);\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
// assertEquals("tescik",(executor.getGlobalVariable(parser.getGlobalVariableSlot("test")).getTLValue().toString()));
// assertEquals("zabicka",(executor.getGlobalVariable(parser.getGlobalVariableSlot("test1")).getTLValue().toString()));
assertEquals("abcdef",(executor.getGlobalVariable(parser.getGlobalVariableSlot("r1")).getTLValue().toString()));
assertEquals("a1bcde2f",(executor.getGlobalVariable(parser.getGlobalVariableSlot("an1")).getTLValue().toString()));
assertEquals("a1bcde2f",(executor.getGlobalVariable(parser.getGlobalVariableSlot("an2")).getTLValue().toString()));
assertEquals("abcdef",(executor.getGlobalVariable(parser.getGlobalVariableSlot("an3")).getTLValue().toString()));
assertEquals("12",(executor.getGlobalVariable(parser.getGlobalVariableSlot("an4")).getTLValue().toString()));
assertEquals("hippi",(executor.getGlobalVariable(parser.getGlobalVariableSlot("t")).getTLValue().toString()));
assertEquals("hipp",(executor.getGlobalVariable(parser.getGlobalVariableSlot("t1")).getTLValue().toString()));
assertEquals("hippi",(executor.getGlobalVariable(parser.getGlobalVariableSlot("t2")).getTLValue().toString()));
// assertTrue((executor.getGlobalVariable(parser.getGlobalVariableSlot("t3")).isNULL()));
assertEquals("y lanuaX nXXd thX lXttXr X",(executor.getGlobalVariable(parser.getGlobalVariableSlot("t4")).getTLValue().toString()));
assertEquals(2,(executor.getGlobalVariable(parser.getGlobalVariableSlot("index")).getTLValue().getNumeric().getInt()));
assertEquals(9,(executor.getGlobalVariable(parser.getGlobalVariableSlot("index1")).getTLValue().getNumeric().getInt()));
assertEquals(0,(executor.getGlobalVariable(parser.getGlobalVariableSlot("index2")).getTLValue().getNumeric().getInt()));
assertEquals(-1,(executor.getGlobalVariable(parser.getGlobalVariableSlot("index3")).getTLValue().getNumeric().getInt()));
assertEquals(6,(executor.getGlobalVariable(parser.getGlobalVariableSlot("index4")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_functions4(){
System.out.println("\nFunctions test:");
DecimalFormat format = (DecimalFormat)NumberFormat.getInstance();
String expStr =
"string stringNo='12';\n" +
"int No;\n" +
"function print_result(from,to, format){\n" +
" if (isnull(format)) {\n" +
" if (try_convert(from,to)) print_err('converted:'+from+'-->'+to);\n" +
" else print_err('cant convert:'+from+'-->'+to);\n" +
" }else{\n" +
" if (try_convert(from,to, format)) print_err('converted:'+from+'-->'+to);\n" +
" else print_err('cant convert:'+from+'-->'+to+' with pattern '+format);\n" +
" }\n" +
"};\n" +
"print_result(stringNo,No,null);\n" +
"stringNo='128a';\n" +
"print_result(stringNo,No,null);\n" +
"stringNo='" + format.format(1285.455) + "';\n" +
"double no1=1.34;\n" +
"print_result(stringNo,no1,'" + format.toPattern() + "');\n" +
"decimal(10,3) no2;\n" +
"print_result(no1,no2,null);\n" +
"print_result(34542.3,no2,null);\n" +
"int no3;\n" +
"print_result(34542.7,no3,null);\n" +
"print_result(345427,no3,null);\n" +
"print_result(3454876434468927,no3,null);\n" +
"date date1 = $Born;\n" +
"long no4;\n" +
"print_result(date1,no4,null);\n" +
"no4 = no4 + 1000*60*60*24;\n" +
"print_result(no4,date1,null);\n" +
"date date2;\n" +
"print_result('20.9.2007',date2,'dd.MM.yyyy');\n" +
"decimal(6,4) d1=73.8474;\n" +
"decimal(4,2) d2;\n" +
"print_result(d1,d2,null);\n" +
"d2 = 75.32;\n" +
"print_result(d2,d1,null);\n" +
"boolean b;\n" +
"print_result(1,b,null);\n" +
"print_result(b,d2,null);\n" +
"boolean b1;\n" +
"print_result('prawda',b1,null);\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record1});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(12,(executor.getGlobalVariable(parser.getGlobalVariableSlot("No")).getTLValue().getNumeric().getInt()));
assertEquals(1285.455,(executor.getGlobalVariable(parser.getGlobalVariableSlot("no1")).getTLValue().getNumeric().getDouble()));
assertEquals(DecimalFactory.getDecimal(34542.3, 10, 3),(executor.getGlobalVariable(parser.getGlobalVariableSlot("no2")).getTLValue().getNumeric()));
assertEquals(345427,(executor.getGlobalVariable(parser.getGlobalVariableSlot("no3")).getTLValue().getNumeric().getInt()));
today.add(Calendar.DATE, 1);
assertEquals(today.getTime(),(executor.getGlobalVariable(parser.getGlobalVariableSlot("date1")).getTLValue().getDate()));
assertEquals(today.getTimeInMillis(),(executor.getGlobalVariable(parser.getGlobalVariableSlot("no4")).getTLValue().getNumeric().getLong()));
assertEquals(new GregorianCalendar(2007,8,20).getTime(),(executor.getGlobalVariable(parser.getGlobalVariableSlot("date2")).getTLValue().getDate()));
assertEquals(DecimalFactory.getDecimal(75.32, 6, 4),(executor.getGlobalVariable(parser.getGlobalVariableSlot("d1")).getTLValue().getNumeric()));
assertEquals(DecimalFactory.getDecimal(75.32, 6, 4),(executor.getGlobalVariable(parser.getGlobalVariableSlot("d1")).getTLValue().getNumeric()));
assertEquals(DecimalFactory.getDecimal(1), executor.getGlobalVariable(parser.getGlobalVariableSlot("d2")).getTLValue().getNumeric());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_math_functions(){
System.out.println("\nMath functions test:");
String expStr = "number original;original=pi();\n" +
"print_err('pi='+original);\n" +
"number ee=e();\n" +
"number result;result=sqrt(original);\n" +
"print_err('sqrt='+result);\n" +
"int i;i=9;\n" +
"number p9;p9=sqrt(i);\n" +
"number ln;ln=log(p9);\n" +
"print_err('sqrt(-1)='+sqrt(-1));\n" +
"decimal d;d=0;"+
"print_err('log(0)='+log(d));\n" +
"number l10;l10=log10(p9);\n" +
"number ex;ex =exp(l10);\n" +
"number po;po=pow(p9,1.2);\n" +
"number p;p=pow(-10,-0.3);\n" +
"print_err('power(-10,-0.3)='+p);\n" +
"int r;r=round(-po);\n" +
"print_err('round of '+(-po)+'='+r);"+
"int t;t=trunc(-po);\n" +
"print_err('truncation of '+(-po)+'='+t);\n" +
"date date1;date1=2004-01-02 17:13:20;\n" +
"date tdate1; tdate1=trunc(date1);\n" +
"print_err('truncation of '+date1+'='+tdate1);\n" +
"print_err('Random number: '+random());\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
assertEquals("pi",new Double(Math.PI),executor.getGlobalVariable(parser.getGlobalVariableSlot("original")).getTLValue().getNumeric().getDouble());
assertEquals("e",new Double(Math.E),executor.getGlobalVariable(parser.getGlobalVariableSlot("ee")).getTLValue().getNumeric().getDouble());
assertEquals("sqrt",new Double(Math.sqrt(Math.PI)),executor.getGlobalVariable(parser.getGlobalVariableSlot("result")).getTLValue().getNumeric().getDouble());
assertEquals("sqrt(9)",new Double(3),executor.getGlobalVariable(parser.getGlobalVariableSlot("p9")).getTLValue().getNumeric().getDouble());
assertEquals("ln",new Double(Math.log(3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("ln")).getTLValue().getNumeric().getDouble());
assertEquals("log10",new Double(Math.log10(3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("l10")).getTLValue().getNumeric().getDouble());
assertEquals("exp",new Double(Math.exp(Math.log10(3))),executor.getGlobalVariable(parser.getGlobalVariableSlot("ex")).getTLValue().getNumeric().getDouble());
assertEquals("power",new Double(Math.pow(3,1.2)),executor.getGlobalVariable(parser.getGlobalVariableSlot("po")).getTLValue().getNumeric().getDouble());
assertEquals("power--",new Double(Math.pow(-10,-0.3)),executor.getGlobalVariable(parser.getGlobalVariableSlot("p")).getTLValue().getNumeric().getDouble());
assertEquals("round",Integer.parseInt("-4"),executor.getGlobalVariable(parser.getGlobalVariableSlot("r")).getTLValue().getNumeric().getInt());
assertEquals("truncation",Integer.parseInt("-3"),executor.getGlobalVariable(parser.getGlobalVariableSlot("t")).getTLValue().getNumeric().getInt());
assertEquals("date truncation",new GregorianCalendar(2004,00,02).getTime(),executor.getGlobalVariable(parser.getGlobalVariableSlot("tdate1")).getTLValue().getDate());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
// public void test_global_parameters(){
// System.out.println("\nGlobal parameters test:");
// String expStr = "string original;original=${G1};\n" +
// "int num; num=str2num(original); \n"+
// "print_err(original);\n"+
// "print_err(num);\n";
// print_code(expStr);
// try {
// TransformLangParser parser = new TransformLangParser(record.getMetadata(),
// new ByteArrayInputStream(expStr.getBytes()));
// CLVFStart parseTree = parser.Start();
// System.out.println("Initializing parse tree..");
// parseTree.init();
// System.out.println("Parse tree:");
// parseTree.dump("");
// System.out.println("Interpreting parse tree..");
// TransformLangExecutor executor=new TransformLangExecutor();
// executor.setInputRecords(new DataRecord[] {record});
// Properties globalParameters = new Properties();
// globalParameters.setProperty("G1","10");
// executor.setGlobalParameters(globalParameters);
// executor.visit(parseTree,null);
// System.out.println("Finished interpreting.");
// assertEquals("num",10,executor.getGlobalVariable(parser.getGlobalVariableSlot("num")).getValue().getNumeric().getInt());
// } catch (ParseException e) {
// System.err.println(e.getMessage());
// e.printStackTrace();
// throw new RuntimeException("Parse exception",e);
public void test_mapping(){
System.out.println("\nMapping test:");
String expStr = "print_err($1.City); "+
"function test(){\n" +
" string result;\n" +
" print_err('function');\n" +
" result='result';\n" +
" //return result;\n" +
" $Name:=result;\n" +
" $0.Age:=$Age;\n" +
" $out.City:=concat(\"My City \",$City);\n" +
" $Born:=$1.Born;\n" +
" $0.Value:=nvl(0,$in1.Value);\n" +
" }\n" +
"test();\n" +
"print_err('Age='+ $0.Age);\n "+
"if (isnull($0.Age)) {print_err('!!!! Age is null!!!');}\n" +
"print_err($1.City); "+
"//print_err($out.City); " +
"print_err($1.City); "+
"$1.Name:=test();\n" +
"$out1.Age:=$Age;\n" +
"$1.City:=$1.City;\n" +
"$out1.Value:=$in.Value;\n";
print_code(expStr);
try {
DataRecordMetadata[] recordMetadata=new DataRecordMetadata[] {metadata,metadata1};
DataRecordMetadata[] outMetadata=new DataRecordMetadata[] {metaOut,metaOut1};
TransformLangParser parser = new TransformLangParser(recordMetadata,
outMetadata,new ByteArrayInputStream(expStr.getBytes()),"UTF-8");
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record,record1});
executor.setOutputRecords(new DataRecord[]{out,out1});
SetVal.setString(record1,2,"Prague");
record.getField("Age").setNull(true);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals("result",out.getField("Name").getValue().toString());
assertEquals(record.getField("Age").getValue(),out.getField("Age").getValue());
assertEquals("My City "+record.getField("City").getValue().toString(), out.getField("City").getValue().toString());
assertEquals(record1.getField("Born").getValue(), out.getField("Born").getValue());
assertEquals(0,out.getField("Value").getValue());
assertEquals("",out1.getField("Name").getValue().toString());
assertEquals(record.getField("Age").getValue(), out1.getField("Age").getValue());
assertEquals(record1.getField("City").getValue().toString(), out1.getField("City").getValue().toString());
assertNull(out1.getField("Born").getValue());
assertEquals(record.getField("Value").getValue(), out1.getField("Value").getValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_logger(){
System.out.println("\nLogger test:");
String expStr = "/*raise_error(\"my testing error\") ;*/ " +
"print_log(fatal,10 * 15);";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_sequence(){
System.out.println("\nSequence test:");
String expStr = "print_err(sequence(test).next);\n"+
"print_err(sequence(test).next);\n"+
"int i; for(i=0;i<10;++i) print_err(sequence(test).next);\n"+
"i=sequence(test).current; print_err(i,true); i=sequence(test).reset; \n" +
"print_err('i after reset='+i);\n" +
"int current;string next;"+
"for(i=0;i<50;++i) { current=sequence(test).current;\n" +
"print_err('current='+current);\n" +
"next=sequence(test).next;\n" +
" print_err('next='+next); }\n";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_lookup(){
System.out.println("\nLookup test:");
String expStr = "string key='one';\n"+
"string val=lookup(LKP,key).Name;\n"+
"print_err(lookup(LKP,' HELLO ').Age); \n"+
"print_err(lookup_found(LKP));\n"+
"print_err(lookup_next(LKP).Age);\n"+
"print_err(lookup(LKP,'two').Name); \n"+
"/*print_err(lookup(LKP,'two').Name);\n"+
"print_err(lookup(LKP,'xxx').Name);\n*/";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_function(){
System.out.println("\nFunction test:");
String expStr = "function myFunction(idx){\n" +
"if (idx==1) print_err('idx equals 1');\n" +
" else {\n" +
" print_err('idx does not equal 1');\n" +
" idx=1;\n" +
" }\n" +
"}\n" +
"myFunction(1);\n" +
"int in;\n" +
"print_err('in='+in);\n"+
"myFunction(in);\n" +
"print_err('in='+in);\n" +
"function init(){" +
"print_err('in init');\n" +
"};\n" +
"init();";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
// CLVFFunctionDeclaration function = (CLVFFunctionDeclaration)parser.getFunctions().get("myFunction");
// executor.executeFunction(function, new TLValue[]{new TLValue(TLValueType.INTEGER,new CloverInteger(1))});
// executor.executeFunction(function, new TLValue[]{new TLValue(TLValueType.INTEGER,new CloverInteger(10))});
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_import(){
System.out.println("\nImport test:");
String expStr = "import 'data/tlExample.ctl';";
print_code(expStr);
Log logger = LogFactory.getLog(this.getClass());
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setRuntimeLogger(logger);
executor.setGraph(graph);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(10,(executor.getGlobalVariable(parser.getGlobalVariableSlot("i")).getTLValue().getNumeric().getInt()));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_eval(){
System.out.println("\neval test:");
String expStr = "string str='print_err(\"eval test OK\");';\n eval(str); print_err(eval_exp('\"ahoj\"'));\n";
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),expStr);
CLVFStart parseTree = parser.Start();
print_code(expStr);
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Parse tree:");
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setParser(parser);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void print_code(String text){
String[] lines=text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for(int i=0;i<lines.length;i++){
System.out.println((i+1)+"\t:"+lines[i]);
}
}
}
|
package org.bullecarree.improv.model;
public class ImprovRenderer {
private Improv improv;
private final String compared;
private final String mixt;
private final String unlimited;
private final String categoryFree;
public ImprovRenderer(String compared, String mixt, String unlimited, String categoryFree) {
this.compared = compared;
this.mixt = mixt;
this.unlimited = unlimited;
this.categoryFree = categoryFree;
}
public void setImprov(Improv improv) {
this.improv = improv;
}
public String getTitle() {
return improv.getTitle();
}
public String getType() {
if (improv.getType() == ImprovType.COMPARED) {
return this.compared;
} else {
return this.mixt;
}
}
public String getCategory() {
String res = improv.getCategory();
if (res == null || "".equals(res)) {
res = categoryFree;
}
return res;
}
public String getPlayerCount() {
if (improv.getPlayerCount() == 0) {
return this.unlimited;
} else {
return String.valueOf(improv.getPlayerCount());
}
}
public String getDuration() {
return displayTime(improv.getDuration());
}
public String displayTime(int duration) {
StringBuffer res = new StringBuffer();
int minutes = duration / 60;
int seconds = duration % 60;
if (minutes > 0) {
res.append(minutes).append("m ");
}
if (seconds > 0 && duration != 0) {
res.append(seconds).append("s");
}
return res.toString();
}
}
|
package com.yeokm1.nussocprint;
import android.os.Bundle;
import android.preference.PreferenceScreen;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import com.yeokm1.nussocprint.fragments.HelpFragment;
import com.yeokm1.nussocprint.fragments.PreferenceListFragment.OnPreferenceAttachedListener;
import com.yeokm1.nussocprint.fragments.PrintFragment;
import com.yeokm1.nussocprint.fragments.QuotaFragment;
import com.yeokm1.nussocprint.fragments.SettingsFragment;
import java.util.Locale;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener, OnPreferenceAttachedListener {
private static final int FRAGMENT_PRINT_NUMBER = 0;
private static final int FRAGMENT_QUOTA_NUMBER = 1;
private static final int FRAGMENT_SETTINGS_NUMBER = 2;
private static final int FRAGMENT_HELP_NUMBER = 3;
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentStatePagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch(position){
case FRAGMENT_PRINT_NUMBER :
return new PrintFragment();
case FRAGMENT_QUOTA_NUMBER :
return new QuotaFragment();
case FRAGMENT_SETTINGS_NUMBER :
return new SettingsFragment();
case FRAGMENT_HELP_NUMBER :
return new HelpFragment();
default :
return null;
}
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case FRAGMENT_PRINT_NUMBER:
return getString(R.string.tab_print).toUpperCase(l);
case FRAGMENT_QUOTA_NUMBER:
return getString(R.string.tab_quota).toUpperCase(l);
case FRAGMENT_SETTINGS_NUMBER:
return getString(R.string.tab_settings).toUpperCase(l);
case FRAGMENT_HELP_NUMBER:
return getString(R.string.tab_help).toUpperCase(l);
}
return null;
}
}
@Override
public void onPreferenceAttached(PreferenceScreen root, int xmlId) {
//Dummy function used by PreferenceListFragment
}
}
|
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import reflect.ClassHint;
import reflect.ParamsHint;
import reflect.android.AndroidParamsHint;
@SuppressWarnings("rawtypes")
public class Reflect {
private static class ClassInfo
{
String m_className;
Class m_class;
String m_super;
ClassInfo(String clazz)
{
m_className = clazz;
m_class = null;
m_super = null;
}
boolean Extends(String clazz)
{
return m_super != null && m_super.equals(clazz);
}
void Start() throws ClassNotFoundException {
m_class = Class.forName(m_className);
final Class s = m_class.getSuperclass();
if (s != null) m_super = s.getName();
}
static void detachNextClass(Vector<Class> dst, Map<String, ClassInfo> src)
{
String nextName = null;
Class next = null;
for (Map.Entry<String, ClassInfo> e: src.entrySet())
{
if (e.getValue().m_super == null)
{
nextName = e.getKey();
next = e.getValue().m_class;
break;
}
}
if (nextName != null) src.remove(nextName);
if (next == null) return;
dst.add(next);
for (Map.Entry<String, ClassInfo> e: src.entrySet())
{
if (e.getValue().Extends(next.getName()))
e.getValue().m_super = null;
}
}
static void sort(Vector<Class> dst, Map<String, ClassInfo> src)
{
while(src.size() > 0)
{
int size = src.size();
detachNextClass(dst, src);
if (size == src.size()) // we have loops
{
for (Map.Entry<String, ClassInfo> e: src.entrySet())
{
if (e.getValue().m_class != null)
dst.add(e.getValue().m_class);
}
break;
}
}
}
}
private ParamsHint.HintCreator m_hinter;
public Reflect(ParamsHint.HintCreator hinter) {
m_hinter = hinter;
}
private ClassHint[] getHints(String klazz)
{
return m_hinter.createHint().getHints(klazz);
}
private void printClass(Class klazz) throws IOException
{
Class supah = klazz.getSuperclass();
System.out.println("Class: " + klazz.getName());
if (supah != null)
System.out.println(" Extends: " + supah.getName() + "\n");
ClassHint[] hints = getHints(klazz.getName());
}
private static void usage(String err)
{
System.out.println("usage: Reflect --android # <class> [<class>...]");
System.out.println();
if (err != null) System.err.println(err);
else System.out.println("i.e.: Reflect --android 17 android.graphics.Canvas");
}
public static void main(String[] args)
{
Map<String, ClassInfo> classes = new HashMap<String, ClassInfo>();
String sdk = null;
boolean nextIsSdk = false;
for (String arg: args)
{
if (arg.startsWith("
{
if (nextIsSdk)
{
usage("Error: --android followed by " + arg);
return;
}
final String var = arg.substring(2);
if (var.equalsIgnoreCase("android"))
nextIsSdk = true;
else
{
usage("Unknown param: " + arg);
return;
}
continue;
}
if (nextIsSdk)
{
sdk = arg;
nextIsSdk = false;
}
else
{
classes.put(arg, new ClassInfo(arg));
}
}
if (nextIsSdk || sdk == null || classes.size() == 0)
{
usage(null);
return;
}
try {
final Reflect reflect = new Reflect(new AndroidParamsHint.HintCreator(sdk));
Map<String, ClassInfo> additional = new HashMap<String, ClassInfo>();
for (Map.Entry<String, ClassInfo> e: classes.entrySet())
{
e.getValue().Start();
if (e.getValue().m_super != null)
{
String _superName = e.getValue().m_super;
Class _super = Class.forName(_superName);
while (_super != null)
{
ClassInfo nfo = new ClassInfo(_superName);
nfo.Start();
additional.put(_superName, nfo);
_superName = nfo.m_super;
_super = _superName == null ? null : Class.forName(_superName);
}
}
}
for (Map.Entry<String, ClassInfo> e: additional.entrySet())
{
classes.put(e.getKey(), e.getValue());
}
Vector<Class> _classes = new Vector<Class>();
ClassInfo.sort(_classes, classes);
for (Class c: _classes)
reflect.printClass(c);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.game.runner.game.descriptor.utils;
/**
*
* @author Karl
*/
public enum Layer{
CLOUDS_1(0, 220, "clouds_1"),
CLOUDS_2(0, 240, "clouds_2"),
CITY_1(0, 0, "city_1"),
CITY_2(0, 0, "city_2"),
DESERT_1(0, 0, "desert_1"),
DESERT_2(0, 0, "desert_2"),
MOUNTAIN_1(0, 0, "mountain_1"),
MOUNTAIN_2(0, 0, "mountain_2"),
FOREST_1(0, 0, "forest_1"),
FOREST_2(0, 0, "forest_2"),
HILL_1(0, 0, "hill_1"),
HILL_2(0, 0, "hill_2"),
SWEET_1(0, 0, "sweet_1"),
SWEET_2(0, 0, "sweet_2"),
SWEET_3(0, 280, "sweet_3"),
SWEET_4(0, 170, "sweet_4"),
JUMP_1(0, 190, "training_1"),
JUMP_2(0, 220, "training_2"),
ROLL_1(0, 5, "training_3"),
ROLL_2(0, 5, "training_4"),
DOUBLEJUMP_1(0, 190, "training_5"),
DOUBLEJUMP_2(0, 220, "training_6");
public float x;
public float y;
public String resName;
public float speed;
private Layer(float x, float y, String resName) {
this.x = x;
this.y = y;
this.resName = resName;
this.speed = 0;
}
public Layer withSpeed(float speed){
this.speed = speed;
return this;
}
}
|
package org.intellij.ibatis.dom.sqlMap.impl;
import com.intellij.javaee.model.xml.impl.BaseImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.xml.DomManager;
import org.intellij.ibatis.dom.sqlMap.Sql;
import org.intellij.ibatis.util.IbatisUtil;
import org.jetbrains.annotations.NotNull;
/**
* SQL element implementation
*/
public abstract class SqlImpl extends BaseImpl implements Sql {
/**
* get the SQL code
*
* @return SQL sentence
*/
@NotNull public String getSQL() {
return IbatisUtil.getSQLForXmlTag(getXmlTag());
}
}
|
package org.marswars.frc4143.subsystems;
import com.sun.squawk.util.MathUtils;
import edu.wpi.first.wpilibj.DigitalModule;
import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
import org.marswars.frc4143.AnalogChannelVolt;
import org.marswars.frc4143.ConstantMap;
import org.marswars.frc4143.RobotMap;
import org.marswars.frc4143.commands.CrabDrive;
public class SwerveDrive extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
public AnalogChannelVolt positionFL = new AnalogChannelVolt(1, 4);
public AnalogChannelVolt positionFR = new AnalogChannelVolt(1, 1);
public AnalogChannelVolt positionRL = new AnalogChannelVolt(1, 2);
public AnalogChannelVolt positionRR = new AnalogChannelVolt(1, 3);
private SpeedController motorSteerFL = new Victor(1, 8);
private SpeedController motorSteerFR = new Victor(1, 5);
private SpeedController motorSteerRL = new Victor(1, 6);
private SpeedController motorSteerRR = new Victor(1, 7);
public PIDController frontRight = new PIDController(RobotMap.P, RobotMap.I,
RobotMap.D, RobotMap.F, positionFR, motorSteerFR, RobotMap.PERIOD);
public PIDController frontLeft = new PIDController(RobotMap.P, RobotMap.I,
RobotMap.D, RobotMap.F, positionFL, motorSteerFL, RobotMap.PERIOD);
public PIDController rearRight = new PIDController(RobotMap.P, RobotMap.I,
RobotMap.D, RobotMap.F, positionRR, motorSteerRR, RobotMap.PERIOD);
public PIDController rearLeft = new PIDController(RobotMap.P, RobotMap.I,
RobotMap.D, RobotMap.F, positionRL, motorSteerRL, RobotMap.PERIOD);
private SpeedController motorDriveFL = new Victor(1, 1);
private SpeedController motorDriveFR = new Victor(1, 2);
private SpeedController motorDriveRL = new Victor(1, 4);
private SpeedController motorDriveRR = new Victor(1, 3);
//private DigitalModule i2cmodule = new DigitalModule();
public I2C i2c;
boolean unwinding = false;
private double robotAngle = 0.;
private double X;
private double Y;
private double AP;
private double BP;
private double CP;
private double DP;
private double FL;
private double FR;
private double RL;
private double RR;
private double FLRatio;
private double FRRatio;
private double RLRatio;
private double RRRatio;
private boolean driveFront = true;
private double FLInv = 1.;
private double FRInv = 1.;
private double RLInv = 1.;
private double RRInv = 1.;
private double FLOffset;
private double FROffset;
private double RLOffset;
private double RROffset;
private double W;
private static ConstantMap fileMap = new ConstantMap();
public SwerveDrive() {
frontRight.setContinuous(RobotMap.CONTINUOUS);
frontLeft.setContinuous(RobotMap.CONTINUOUS);
rearRight.setContinuous(RobotMap.CONTINUOUS);
rearLeft.setContinuous(RobotMap.CONTINUOUS);
frontRight.setAbsoluteTolerance(RobotMap.TOLERANCE);
frontLeft.setAbsoluteTolerance(RobotMap.TOLERANCE);
rearRight.setAbsoluteTolerance(RobotMap.TOLERANCE);
rearLeft.setAbsoluteTolerance(RobotMap.TOLERANCE);
frontRight.setInputRange(RobotMap.POTMIN, RobotMap.POTMAX);
frontLeft.setInputRange(RobotMap.POTMIN, RobotMap.POTMAX);
rearRight.setInputRange(RobotMap.POTMIN, RobotMap.POTMAX);
rearLeft.setInputRange(RobotMap.POTMIN, RobotMap.POTMAX);
frontRight.setOutputRange(-RobotMap.STEERPOW, RobotMap.STEERPOW);
frontLeft.setOutputRange(-RobotMap.STEERPOW, RobotMap.STEERPOW);
rearRight.setOutputRange(-RobotMap.STEERPOW, RobotMap.STEERPOW);
rearLeft.setOutputRange(-RobotMap.STEERPOW, RobotMap.STEERPOW);
positionFL.start();
positionFR.start();
positionRL.start();
positionRR.start();
frontLeft.enable();
frontRight.enable();
rearLeft.enable();
rearRight.enable();
i2c = DigitalModule.getInstance(1).getI2C(0x04 << 1);
fileMap.load();
if (fileMap.m_Map.containsKey("FLOff")) {
FLOffset = ((Double)fileMap.m_Map.get("FLOff")).doubleValue();
}
if (fileMap.m_Map.containsKey("FROff")) {
FROffset = ((Double)fileMap.m_Map.get("FROff")).doubleValue();
}
if (fileMap.m_Map.containsKey("RLOff")) {
RLOffset = ((Double)fileMap.m_Map.get("RLOff")).doubleValue();
}
if (fileMap.m_Map.containsKey("RROff")) {
RROffset = ((Double)fileMap.m_Map.get("RROff")).doubleValue();
}
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(new CrabDrive());
}
public void toggleFrontBack() {
driveFront = !driveFront;
outputLED();
}
public void Crab(double twist, double y, double x, double brake) {
if (unwinding
|| Math.abs(positionFL.getTurns()) > 5
|| Math.abs(positionFR.getTurns()) > 5
|| Math.abs(positionRL.getTurns()) > 5
|| Math.abs(positionRR.getTurns()) > 5) {
setDriveSpeed(0., 0., 0., 0.);
return;
}
if (Math.abs(twist) < 1E-6 && Math.abs(y) < 1E-6 && Math.abs(x) < 1E-6) {
y = 0.05;
}
double FWD = y * Math.cos(robotAngle) + x * Math.sin(robotAngle);
double STR = -y * Math.sin(robotAngle) + x * Math.cos(robotAngle);
double radius = Math.sqrt(MathUtils.pow(Y, 2) + MathUtils.pow(X, 2));
AP = STR - twist * X / radius;
BP = STR + twist * X / radius;
CP = FWD - twist * Y / radius;
DP = FWD + twist * Y / radius;
double FLSetPoint = 2.5;
double FRSetPoint = 2.5;
double RLSetPoint = 2.5;
double RRSetPoint = 2.5;
if (DP != 0 || BP != 0) {
FLSetPoint = (2.5 + 2.5 / Math.PI * MathUtils.atan2(BP, DP));
}
if (BP != 0 || CP != 0) {
FRSetPoint = (2.5 + 2.5 / Math.PI * MathUtils.atan2(BP, CP));
}
if (AP != 0 || DP != 0) {
RLSetPoint = (2.5 + 2.5 / Math.PI * MathUtils.atan2(AP, DP));
}
if (AP != 0 || CP != 0) {
RRSetPoint = (2.5 + 2.5 / Math.PI * MathUtils.atan2(AP, CP));
}
SetSteerSetpoint(FLSetPoint, FRSetPoint, RLSetPoint, RRSetPoint);
FL = Math.sqrt(MathUtils.pow(BP, 2) + MathUtils.pow(DP, 2));
FR = Math.sqrt(MathUtils.pow(BP, 2) + MathUtils.pow(CP, 2));
RL = Math.sqrt(MathUtils.pow(AP, 2) + MathUtils.pow(DP, 2));
RR = Math.sqrt(MathUtils.pow(AP, 2) + MathUtils.pow(CP, 2));
//Solve for fastest wheel speed
double speedarray[] = {Math.abs(FL), Math.abs(FR), Math.abs(RL), Math.abs(RR)};
int arrayLength = 4;
double maxspeed = speedarray[0];
for (int i = 1; i < arrayLength; i++) {
maxspeed = Math.max(maxspeed, speedarray[i]);
}
//Set ratios based on maximum wheel speed
if (maxspeed > 1 || maxspeed < -1) {
FLRatio = FL / maxspeed;
FRRatio = FR / maxspeed;
RLRatio = RL / maxspeed;
RRRatio = RR / maxspeed;
} else {
FLRatio = FL;
FRRatio = FR;
RLRatio = RL;
RRRatio = RR;
}
if (brake < -0.5 || y == 0.05 || x == 0.05 || twist == 0.05) {
FLRatio = 0;
FRRatio = 0;
RLRatio = 0;
RRRatio = 0;
}
//Set drive speeds
setDriveSpeed(FLRatio, -FRRatio, RLRatio, -RRRatio);
}
public void Steer(double speed, double angle) {
// Valid angle input: -Math.PI/2 < angle < Math.PI/2
// Valid speed input: -1 < speed < 1
double radius = RobotMap.chassisLength / (2 * Math.cos(Math.PI / 2. - Math.abs(angle))); // Law of cosines
}
private void setDriveSpeed(double FLSpeed, double FRSpeed, double RLSpeed, double RRSpeed) {
if (driveFront) {
motorDriveFL.set(FLSpeed * FLInv);
motorDriveFR.set(FRSpeed * FRInv);
motorDriveRL.set(RLSpeed * RLInv);
motorDriveRR.set(RRSpeed * RRInv);
} else {
motorDriveFL.set(RRSpeed * FLInv);
motorDriveFR.set(RLSpeed * FRInv);
motorDriveRL.set(FRSpeed * RLInv);
motorDriveRR.set(FLSpeed * RRInv);
}
}
private void SetSteerSetpoint(double FLSetPoint, double FRSetPoint, double RLSetPoint, double RRSetPoint) {
if (driveFront) {
if (Math.abs(FLSetPoint + FLOffset - positionFL.getAverageVoltage()) < 1.25 || Math.abs(FLSetPoint + FLOffset - positionFL.getAverageVoltage()) > 3.75) {
frontLeft.setSetpoint(correctSteerSetpoint(FLSetPoint + FLOffset));
FLInv = 1;
} else {
frontLeft.setSetpoint(correctSteerSetpoint(FLSetPoint + FLOffset - 2.5));
FLInv = -1;
}
if (Math.abs(FRSetPoint + FROffset - positionFR.getAverageVoltage()) < 1.25 || Math.abs(FRSetPoint + FROffset - positionFR.getAverageVoltage()) > 3.75) {
frontRight.setSetpoint(correctSteerSetpoint(FRSetPoint + FROffset));
FRInv = 1;
} else {
frontRight.setSetpoint(correctSteerSetpoint(FRSetPoint + FROffset - 2.5));
FRInv = -1;
}
if (Math.abs(RLSetPoint + RLOffset - positionRL.getAverageVoltage()) < 1.25 || Math.abs(RLSetPoint + RLOffset - positionRL.getAverageVoltage()) > 3.75) {
rearLeft.setSetpoint(correctSteerSetpoint(RLSetPoint + RLOffset));
RLInv = 1;
} else {
rearLeft.setSetpoint(correctSteerSetpoint(RLSetPoint + RLOffset - 2.5));
RLInv = -1;
}
if (Math.abs(RRSetPoint + RROffset - positionRR.getAverageVoltage()) < 1.25 || Math.abs(RRSetPoint + RROffset - positionRR.getAverageVoltage()) > 3.75) {
rearRight.setSetpoint(correctSteerSetpoint(RRSetPoint + RROffset));
RRInv = 1;
} else {
rearRight.setSetpoint(correctSteerSetpoint(RRSetPoint + RROffset - 2.5));
RRInv = -1;
}
} else {
if (Math.abs(RRSetPoint + FLOffset - positionFL.getAverageVoltage()) < 1.25 || Math.abs(RRSetPoint + FLOffset - positionFL.getAverageVoltage()) > 3.75) {
frontLeft.setSetpoint(correctSteerSetpoint(RRSetPoint + FLOffset));
FLInv = 1;
} else {
frontLeft.setSetpoint(correctSteerSetpoint(RRSetPoint + FLOffset - 2.5));
FLInv = -1;
}
if (Math.abs(RLSetPoint + FROffset - positionFR.getAverageVoltage()) < 1.25 || Math.abs(RLSetPoint + FROffset - positionFR.getAverageVoltage()) > 3.75) {
frontRight.setSetpoint(correctSteerSetpoint(RLSetPoint + FROffset));
FRInv = 1;
} else {
frontRight.setSetpoint(correctSteerSetpoint(RLSetPoint + FROffset - 2.5));
FRInv = -1;
}
if (Math.abs(FRSetPoint + RLOffset - positionRL.getAverageVoltage()) < 1.25 || Math.abs(FRSetPoint + RLOffset - positionRL.getAverageVoltage()) > 3.75) {
rearLeft.setSetpoint(correctSteerSetpoint(FRSetPoint + RLOffset));
RLInv = 1;
} else {
rearLeft.setSetpoint(correctSteerSetpoint(FRSetPoint + RLOffset - 2.5));
RLInv = -1;
}
if (Math.abs(FLSetPoint + RROffset - positionRR.getAverageVoltage()) < 1.25 || Math.abs(FLSetPoint + RROffset - positionRR.getAverageVoltage()) > 3.75) {
rearRight.setSetpoint(correctSteerSetpoint(FLSetPoint + RROffset));
RRInv = 1;
} else {
rearRight.setSetpoint(correctSteerSetpoint(FLSetPoint + RROffset - 2.5));
RRInv = -1;
}
}
}
private double correctSteerSetpoint(double setpoint) {
if (setpoint < 0) {
return (setpoint + 5);
} else if (setpoint > 5) {
return (setpoint - 5);
} else if (setpoint == 5) {
return 0;
} else {
return setpoint;
}
}
public void outputLED() {
i2c.write(0x0, 40 * (driveFront ? 1 : 0));
}
public void setWheelbase(double w, double x, double y) {
W = w;
X = x;
Y = y;
}
public boolean unwind() {
boolean retval = false;
unwinding = true;
retval = unwindWheel(positionFL, frontLeft) || unwindWheel(positionFR, frontRight) || unwindWheel(positionRL, rearLeft) || unwindWheel(positionRR, rearRight);
if (!retval) {
unwinding = false;
}
return retval;
}
private boolean unwindWheel(AnalogChannelVolt wheel, PIDController pid) {
double temp;
double turns = wheel.getTurns();
if (turns > 1) {
temp = wheel.getAverageVoltage() - 1.0;
if (temp < 0.0) {
temp = 5.0 + temp;
}
pid.setSetpoint(temp);
return true;
} else if (turns < 1) {
temp = wheel.getAverageVoltage() + 1.0;
if (temp > 5.0) {
temp = temp - 5.0;
}
pid.setSetpoint(temp);
return true;
} else {
return false;
}
}
public void doneUnwind() {
unwinding = false;
}
public void angleUp() {
robotAngle += 0.1;
if (robotAngle > 360.) {
robotAngle = 0.;
}
outputLED();
}
public void angleDown() {
robotAngle -= 0.1;
if (robotAngle > 360.) {
robotAngle = 0.;
}
outputLED();
}
public boolean resetTurns() {
positionFR.resetTurns();
positionFL.resetTurns();
positionRR.resetTurns();
positionRL.resetTurns();
robotAngle = 0.;
return true;
}
public void setOffsets(double FLOff, double FROff, double RLOff, double RROff) {
FLOffset = FLOff;
FROffset = FROff;
RLOffset = RLOff;
RROffset = RROff;
fileMap.m_Map.put("FLOffset", new Double(FLOff));
fileMap.m_Map.put("FROffset", new Double(FROff));
fileMap.m_Map.put("RLOffset", new Double(RLOff));
fileMap.m_Map.put("RROffset", new Double(RROff));
fileMap.save();
}
}
|
package org.moeaframework.problem.tsplib;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.moeaframework.core.Algorithm;
import org.moeaframework.core.EvolutionaryAlgorithm;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
import org.moeaframework.core.spi.AlgorithmFactory;
import org.moeaframework.core.variable.EncodingUtils;
import org.moeaframework.problem.AbstractProblem;
public class TSPExample {
/**
* The color for population members.
*/
private static final Color lightGray = new Color(128, 128, 128, 64);
/**
* Converts a MOEA Framework solution to a {@link Tour}.
*
* @param solution the MOEA Framework solution
* @return the tour defined by the solution
*/
public static Tour toTour(Solution solution) {
int[] permutation = EncodingUtils.getPermutation(
solution.getVariable(0));
// increment values since TSP nodes start at 1
for (int i = 0; i < permutation.length; i++) {
permutation[i]++;
}
return Tour.fromArray(permutation);
}
/**
* The optimization problem definition. This is a 1 variable, 1 objective
* optimization problem. The single variable is a permutation that defines
* the nodes visited by the salesman.
*/
public static class TSPProblem extends AbstractProblem {
/**
* The TSP problem instance.
*/
private final TSPInstance instance;
/**
* Constructs a new optimization problem for the given TSP problem
* instance.
*
* @param instance the TSP problem instance
*/
public TSPProblem(TSPInstance instance) {
super(1, 1);
this.instance = instance;
}
@Override
public void evaluate(Solution solution) {
solution.setObjective(0, toTour(solution).distance(instance));
}
@Override
public Solution newSolution() {
Solution solution = new Solution(1, 1);
solution.setVariable(0, EncodingUtils.newPermutation(
instance.getDimension()));
return solution;
}
}
/**
* Runs the example TSP optimization problem.
*
* @param args the command line arguments; none are defined
* @throws IOException if an I/O error occurred
*/
public static void main(String[] args) throws IOException {
// create the TSP problem instance and display panel
TSPInstance instance = new TSPInstance(
new File("./data/tsp/pr76.tsp"));
TSPPanel panel = new TSPPanel(instance);
panel.setAutoRepaint(false);
// create other components on the display
StringBuilder progress = new StringBuilder();
JTextArea progressText = new JTextArea();
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(panel);
splitPane.setBottomComponent(new JScrollPane(progressText));
splitPane.setDividerLocation(300);
splitPane.setResizeWeight(1.0);
// display the panel on a window
JFrame frame = new JFrame(instance.getName());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// create the optimization problem and evolutionary algorithm
Problem problem = new TSPProblem(instance);
Properties properties = new Properties();
properties.setProperty("swap.rate", "0.7");
properties.setProperty("insertion.rate", "0.9");
properties.setProperty("pmx.rate", "0.4");
Algorithm algorithm = AlgorithmFactory.getInstance().getAlgorithm(
"NSGAII", properties, problem);
int iteration = 0;
// now run the evolutionary algorithm
while (frame.isVisible()) {
algorithm.step();
iteration++;
// clear existing tours in display
panel.clearTours();
// display population with light gray lines
if (algorithm instanceof EvolutionaryAlgorithm) {
EvolutionaryAlgorithm ea = (EvolutionaryAlgorithm)algorithm;
for (Solution solution : ea.getPopulation()) {
panel.displayTour(toTour(solution), lightGray);
}
}
// display current optimal solutions with red line
Tour best = toTour(algorithm.getResult().get(0));
panel.displayTour(best, Color.RED, new BasicStroke(2.0f));
progress.insert(0, "Iteration " + iteration + ": " +
best.distance(instance) + "\n");
progressText.setText(progress.toString());
// repaint the TSP display
panel.repaint();
}
}
}
|
package org.myrobotlab.codec.serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Arduino;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.Serial;
import org.myrobotlab.service.interfaces.LoggingSink;
import org.python.netty.handler.codec.CodecException;
import org.slf4j.Logger;
// FIXME - use InputStream OutputStream
// Stream encoders are more complicated than Document
// with InputStream decoding - you need to deal with blocking / timeouts etc
// if the thing before it deals with it then you have a byte array - but it may not be complete
/**
* Codec to interface with the Arduino service and MRLComm.ino
* part of this file is dynamically generated from the method signatures of the Arduino service
*
* MAGIC_NUMBER|NUM_BYTES|FUNCTION|DATA0|DATA1|....|DATA(N)
* NUM_BYTES - is the number of bytes after NUM_BYTES to the end
* @author GroG
*
*/
public class ArduinoMsgCodec extends Codec implements Serializable {
public ArduinoMsgCodec(){
super(null);
}
public ArduinoMsgCodec(LoggingSink sink) {
super(sink);
}
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(ArduinoMsgCodec.class);
transient static final HashMap<Integer, String> byteToMethod = new HashMap<Integer, String>();
transient static final HashMap<String, Integer> methodToByte = new HashMap<String, Integer>();
int byteCount = 0;
int decodeMsgSize = 0;
StringBuilder rest = new StringBuilder();
public static final int MAX_MSG_SIZE = 64;
public static final int MRLCOMM_VERSION = 33;
public static final int MAGIC_NUMBER = 170; // 10101010
public static final int STEPPER_EVENT_STOP = 1;
public static final int STEPPER_EVENT_STEP = 2;
///// java ByteToMethod generated definition - DO NOT MODIFY - Begin //////
// {publishMRLCommError Integer}
public final static int PUBLISH_MRLCOMM_ERROR = 1;
// {getVersion}
public final static int GET_VERSION = 2;
// {publishVersion Integer}
public final static int PUBLISH_VERSION = 3;
// {analogReadPollingStart Integer}
public final static int ANALOG_READ_POLLING_START = 4;
// {analogReadPollingStop Integer}
public final static int ANALOG_READ_POLLING_STOP = 5;
// {analogWrite Integer Integer}
public final static int ANALOG_WRITE = 6;
// {digitalReadPollingStart Integer}
public final static int DIGITAL_READ_POLLING_START = 7;
// {digitalReadPollingStop Integer}
public final static int DIGITAL_READ_POLLING_STOP = 8;
// {digitalWrite Integer Integer}
public final static int DIGITAL_WRITE = 9;
// {motorAttach Motor}
public final static int MOTOR_ATTACH = 10;
// {motorDetach Motor}
public final static int MOTOR_DETACH = 11;
// {motorMove Motor}
public final static int MOTOR_MOVE = 12;
// {motorMoveTo Motor}
public final static int MOTOR_MOVE_TO = 13;
// {motorReset Motor}
public final static int MOTOR_RESET = 14;
// {motorStop Motor}
public final static int MOTOR_STOP = 15;
// {pinMode Integer Integer}
public final static int PIN_MODE = 16;
// {publishCustomMsg Object[]}
public final static int PUBLISH_CUSTOM_MSG = 17;
// {publishLoadTimingEvent Long}
public final static int PUBLISH_LOAD_TIMING_EVENT = 18;
// {publishPin Pin}
public final static int PUBLISH_PIN = 19;
// {publishPulse Long}
public final static int PUBLISH_PULSE = 20;
// {publishPulseStop Integer}
public final static int PUBLISH_PULSE_STOP = 21;
// {publishSensorData Object}
public final static int PUBLISH_SENSOR_DATA = 22;
// {publishServoEvent Integer}
public final static int PUBLISH_SERVO_EVENT = 23;
// {publishTrigger Pin}
public final static int PUBLISH_TRIGGER = 24;
// {pulse int int int int}
public final static int PULSE = 25;
// {pulseStop}
public final static int PULSE_STOP = 26;
// {sensorAttach SensorDataSink}
public final static int SENSOR_ATTACH = 27;
// {sensorPollingStart String int}
public final static int SENSOR_POLLING_START = 28;
// {sensorPollingStop String}
public final static int SENSOR_POLLING_STOP = 29;
// {servoAttach Servo Integer}
public final static int SERVO_ATTACH = 30;
// {servoDetach Servo}
public final static int SERVO_DETACH = 31;
// {servoEventsEnabled Servo}
public final static int SERVO_EVENTS_ENABLED = 32;
// {servoSweepStart Servo}
public final static int SERVO_SWEEP_START = 33;
// {servoSweepStop Servo}
public final static int SERVO_SWEEP_STOP = 34;
// {servoWrite Servo}
public final static int SERVO_WRITE = 35;
// {servoWriteMicroseconds Servo}
public final static int SERVO_WRITE_MICROSECONDS = 36;
// {setDebounce int}
public final static int SET_DEBOUNCE = 37;
// {setDigitalTriggerOnly Boolean}
public final static int SET_DIGITAL_TRIGGER_ONLY = 38;
// {setLoadTimingEnabled boolean}
public final static int SET_LOAD_TIMING_ENABLED = 39;
// {setPWMFrequency Integer Integer}
public final static int SET_PWMFREQUENCY = 40;
// {setSampleRate int}
public final static int SET_SAMPLE_RATE = 41;
// {setSerialRate int}
public final static int SET_SERIAL_RATE = 42;
// {setServoSpeed Servo}
public final static int SET_SERVO_SPEED = 43;
// {setTrigger int int int}
public final static int SET_TRIGGER = 44;
// {softReset}
public final static int SOFT_RESET = 45;
static {
byteToMethod.put(PUBLISH_MRLCOMM_ERROR,"publishMRLCommError");
methodToByte.put("publishMRLCommError",PUBLISH_MRLCOMM_ERROR);
byteToMethod.put(GET_VERSION,"getVersion");
methodToByte.put("getVersion",GET_VERSION);
byteToMethod.put(PUBLISH_VERSION,"publishVersion");
methodToByte.put("publishVersion",PUBLISH_VERSION);
byteToMethod.put(ANALOG_READ_POLLING_START,"analogReadPollingStart");
methodToByte.put("analogReadPollingStart",ANALOG_READ_POLLING_START);
byteToMethod.put(ANALOG_READ_POLLING_STOP,"analogReadPollingStop");
methodToByte.put("analogReadPollingStop",ANALOG_READ_POLLING_STOP);
byteToMethod.put(ANALOG_WRITE,"analogWrite");
methodToByte.put("analogWrite",ANALOG_WRITE);
byteToMethod.put(DIGITAL_READ_POLLING_START,"digitalReadPollingStart");
methodToByte.put("digitalReadPollingStart",DIGITAL_READ_POLLING_START);
byteToMethod.put(DIGITAL_READ_POLLING_STOP,"digitalReadPollingStop");
methodToByte.put("digitalReadPollingStop",DIGITAL_READ_POLLING_STOP);
byteToMethod.put(DIGITAL_WRITE,"digitalWrite");
methodToByte.put("digitalWrite",DIGITAL_WRITE);
byteToMethod.put(MOTOR_ATTACH,"motorAttach");
methodToByte.put("motorAttach",MOTOR_ATTACH);
byteToMethod.put(MOTOR_DETACH,"motorDetach");
methodToByte.put("motorDetach",MOTOR_DETACH);
byteToMethod.put(MOTOR_MOVE,"motorMove");
methodToByte.put("motorMove",MOTOR_MOVE);
byteToMethod.put(MOTOR_MOVE_TO,"motorMoveTo");
methodToByte.put("motorMoveTo",MOTOR_MOVE_TO);
byteToMethod.put(MOTOR_RESET,"motorReset");
methodToByte.put("motorReset",MOTOR_RESET);
byteToMethod.put(MOTOR_STOP,"motorStop");
methodToByte.put("motorStop",MOTOR_STOP);
byteToMethod.put(PIN_MODE,"pinMode");
methodToByte.put("pinMode",PIN_MODE);
byteToMethod.put(PUBLISH_CUSTOM_MSG,"publishCustomMsg");
methodToByte.put("publishCustomMsg",PUBLISH_CUSTOM_MSG);
byteToMethod.put(PUBLISH_LOAD_TIMING_EVENT,"publishLoadTimingEvent");
methodToByte.put("publishLoadTimingEvent",PUBLISH_LOAD_TIMING_EVENT);
byteToMethod.put(PUBLISH_PIN,"publishPin");
methodToByte.put("publishPin",PUBLISH_PIN);
byteToMethod.put(PUBLISH_PULSE,"publishPulse");
methodToByte.put("publishPulse",PUBLISH_PULSE);
byteToMethod.put(PUBLISH_PULSE_STOP,"publishPulseStop");
methodToByte.put("publishPulseStop",PUBLISH_PULSE_STOP);
byteToMethod.put(PUBLISH_SENSOR_DATA,"publishSensorData");
methodToByte.put("publishSensorData",PUBLISH_SENSOR_DATA);
byteToMethod.put(PUBLISH_SERVO_EVENT,"publishServoEvent");
methodToByte.put("publishServoEvent",PUBLISH_SERVO_EVENT);
byteToMethod.put(PUBLISH_TRIGGER,"publishTrigger");
methodToByte.put("publishTrigger",PUBLISH_TRIGGER);
byteToMethod.put(PULSE,"pulse");
methodToByte.put("pulse",PULSE);
byteToMethod.put(PULSE_STOP,"pulseStop");
methodToByte.put("pulseStop",PULSE_STOP);
byteToMethod.put(SENSOR_ATTACH,"sensorAttach");
methodToByte.put("sensorAttach",SENSOR_ATTACH);
byteToMethod.put(SENSOR_POLLING_START,"sensorPollingStart");
methodToByte.put("sensorPollingStart",SENSOR_POLLING_START);
byteToMethod.put(SENSOR_POLLING_STOP,"sensorPollingStop");
methodToByte.put("sensorPollingStop",SENSOR_POLLING_STOP);
byteToMethod.put(SERVO_ATTACH,"servoAttach");
methodToByte.put("servoAttach",SERVO_ATTACH);
byteToMethod.put(SERVO_DETACH,"servoDetach");
methodToByte.put("servoDetach",SERVO_DETACH);
byteToMethod.put(SERVO_EVENTS_ENABLED,"servoEventsEnabled");
methodToByte.put("servoEventsEnabled",SERVO_EVENTS_ENABLED);
byteToMethod.put(SERVO_SWEEP_START,"servoSweepStart");
methodToByte.put("servoSweepStart",SERVO_SWEEP_START);
byteToMethod.put(SERVO_SWEEP_STOP,"servoSweepStop");
methodToByte.put("servoSweepStop",SERVO_SWEEP_STOP);
byteToMethod.put(SERVO_WRITE,"servoWrite");
methodToByte.put("servoWrite",SERVO_WRITE);
byteToMethod.put(SERVO_WRITE_MICROSECONDS,"servoWriteMicroseconds");
methodToByte.put("servoWriteMicroseconds",SERVO_WRITE_MICROSECONDS);
byteToMethod.put(SET_DEBOUNCE,"setDebounce");
methodToByte.put("setDebounce",SET_DEBOUNCE);
byteToMethod.put(SET_DIGITAL_TRIGGER_ONLY,"setDigitalTriggerOnly");
methodToByte.put("setDigitalTriggerOnly",SET_DIGITAL_TRIGGER_ONLY);
byteToMethod.put(SET_LOAD_TIMING_ENABLED,"setLoadTimingEnabled");
methodToByte.put("setLoadTimingEnabled",SET_LOAD_TIMING_ENABLED);
byteToMethod.put(SET_PWMFREQUENCY,"setPWMFrequency");
methodToByte.put("setPWMFrequency",SET_PWMFREQUENCY);
byteToMethod.put(SET_SAMPLE_RATE,"setSampleRate");
methodToByte.put("setSampleRate",SET_SAMPLE_RATE);
byteToMethod.put(SET_SERIAL_RATE,"setSerialRate");
methodToByte.put("setSerialRate",SET_SERIAL_RATE);
byteToMethod.put(SET_SERVO_SPEED,"setServoSpeed");
methodToByte.put("setServoSpeed",SET_SERVO_SPEED);
byteToMethod.put(SET_TRIGGER,"setTrigger");
methodToByte.put("setTrigger",SET_TRIGGER);
byteToMethod.put(SOFT_RESET,"softReset");
methodToByte.put("softReset",SOFT_RESET);
}
///// JAVA GENERATED DEFINITION END - DO NOT MODIFY //////
static public String byteToMethod(int m) {
if (byteToMethod.containsKey(m)) {
return byteToMethod.get(m);
}
return null;
}
public static void main(String[] args) {
try {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
LoggingFactory.getInstance().addAppender("FILE");
log.info("===setUpBeforeClass===");
// LoggingFactory.getInstance().setLevel(Level.INFO);
Runtime.start("gui", "GUIService");
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
Serial serial = arduino.getSerial();
serial.record("out");
// rxtxLib
arduino.connect("COM15");
// arduino.connectTCP("localhost", 9191);
arduino.pinMode(10, 1);
arduino.digitalWrite(10, 1);
arduino.analogReadPollingStart(0);
// uart = serial.createVirtualUART();
arduino.analogReadPollingStop(0);
arduino.analogReadPollingStart(0);
arduino.analogReadPollingStop(0);
arduino.analogReadPollingStart(0);
arduino.analogReadPollingStop(0);
serial.stopRecording();
// Test test = (org.myrobotlab.service.Test) Runtime.start("test",
// "Test");
/*
* ArduinoMsgCodec codec = new ArduinoMsgCodec();
*
* FileOutputStream test = new FileOutputStream(new
* File("out.bin"));
*
* for (int j = 0; j < 4; ++j) { for (int i = 0; i < 100; ++i) {
* int[] data = codec.encode(String.format("publishPin/15/%d/%d\n",
* j, i)); for (int z = 0; z < data.length; ++z){
* test.write(data[z]); } } }
*
* test.close();
*/
/*
*
* // digitalWrite/9/1 StringBuilder sb = new StringBuilder();
* sb.append(codec.decode(170)); sb.append(codec.decode(3));
* sb.append(codec.decode(7)); sb.append(codec.decode(9));
* sb.append(codec.decode(1));
*
* sb.append(codec.decode(170)); sb.append(codec.decode(3));
* sb.append(codec.decode(7)); sb.append(codec.decode(11));
* sb.append(codec.decode(0));
*
* log.info(String.format("[%s]", sb.toString()));
*
* codec.encode(sb.toString());
*
* Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
* Serial serial = arduino.getSerial(); serial.record();
* serial.processRxByte(170); serial.processRxByte(3);
* serial.processRxByte(7); serial.processRxByte(9);
* serial.processRxByte(1);
*/
} catch (Exception e) {
Logging.logError(e);
}
}
// /// JAVA GENERATED DEFINITION END - DO NOT MODIFY //////
/**
* MAGIC_NUMBER|NUM_BYTES|FUNCTION|DATA0|DATA1|....|DATA(N)
*
* @throws CodecException
*/
@Override
public String decodeImpl(int newByte){
// log.info(String.format("byteCount %d", byteCount));
++byteCount;
if (byteCount == 1 && newByte != MAGIC_NUMBER) {
// reset - try again
rest.setLength(0);
byteCount = 0;
decodeMsgSize = 0;
error("bad magic number %d", newByte);
}
if (byteCount == 2) {
// get the size of message
// todo check msg < 64 (MAX_MSG_SIZE)
decodeMsgSize = newByte;
}
// set method
if (byteCount == 3) {
rest.append(byteToMethod.get(newByte));
}
if (byteCount > 3) {
// FIXME - for
rest.append(String.format("/%d", newByte));
}
// if received header + msg
if (byteCount == 2 + decodeMsgSize) {
// msg done
byteCount = 0;
rest.append("\n");
String ret = rest.toString();
rest.setLength(0);
byteCount = 0;
decodeMsgSize = 0;
return ret;
}
// not ready yet
// no msg :P should be null ???
return null;
}
@Override
public String decode(int[] msgs) {
if (msgs == null) {
return new String("");
}
log.info(String.format("decoding input of %d bytes", msgs.length));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < msgs.length; ++i) {
sb.append(decode(msgs[i]));
}
return sb.toString();
}
// must maintain state - partial string
@Override
public int[] encode(String msgs) {
// moved all member vars as local
// otherwise state information would explode
// cheap way of making threadsafe
// this variables
int pos = 0;
int newLinePos = 0;
int slashPos = 0;
ArrayList<Integer> temp = new ArrayList<Integer>();
ArrayList<Integer> data = new ArrayList<Integer>();
if (msgs == null) {
return new int[0];
}
//log.info(String.format("encoding input of %d characters", msgs.length()));
newLinePos = msgs.indexOf("\n", pos);
slashPos = msgs.indexOf("/", pos);
// while not done - string not completed...
// make sure you leave in a good state if not a full String
// FIXME test cases - newLinePos == -1 pos == -1 00 01 10 11
// while either / or new line or eof (string) [eof leave vars in
// unfinished state]
while (slashPos != -1 || newLinePos != -1) {
// ++currentLine;
if (slashPos > 0 && newLinePos > 0 && slashPos < newLinePos) {
// digitalWrite/9/1
// pos^ slashpos ^ ^newLinePos
if (temp.size() == 0) {
String method = msgs.substring(pos, slashPos);
pos = slashPos + 1;
// found method
if (methodToByte.containsKey(method)) {
temp.add(methodToByte.get(method));
} else {
error("method [%s] at position %d is not defined for codec", method, pos);
pos = 0;
data.clear();
}
} else {
// in data region
String param = msgs.substring(pos, slashPos);
temp.add(Integer.parseInt(param));
pos = slashPos + 1;
}
} else if ((slashPos > 0 && newLinePos > 0 && newLinePos < slashPos) || (slashPos == -1 && newLinePos > 0)) {
// end of message slash is beyond newline || newline exists and
// slash does not
String param = msgs.substring(pos, newLinePos);
temp.add(Integer.parseInt(param));
pos = newLinePos + 1;
slashPos = pos;
// unload temp buffer - start next message - if there is one
data.add(170);// MAGIC NUMBER
data.add(temp.size());// SIZE
for (int i = 0; i < temp.size(); ++i) {
// should be end of record
data.add(temp.get(i));
}
// clear buffer - ready for next message
temp.clear();
}
newLinePos = msgs.indexOf("\n", pos);
slashPos = msgs.indexOf("/", pos);
}
int[] ret = new int[data.size()];
// for (int i : data) {
for (int i = 0; i < data.size(); ++i) {
ret[i] = data.get(i);
}
// FIXME - more cases when pos is reset - or all vars reset?
pos = 0;
data.clear();
return ret;
}
@Override
public String getCodecExt() {
return getKey().substring(0, 3);
}
@Override
public String getKey() {
return "arduino";
}
}
|
package org.royawesome.renderer;
import java.io.FileNotFoundException;
import gnu.trove.list.array.TFloatArrayList;
import org.lwjgl.util.vector.*;
import org.royawesome.renderer.shader.EmptyShader;
import org.royawesome.renderer.shader.Shader;
/**
*
* @author RoyAwesome
*
*/
public abstract class BatchVertexRenderer {
boolean batching = false;
boolean flushed = false;
int renderMode;
//Using FloatArrayList because I need O(1) access time
//and fast ToArray()
TFloatArrayList vertexBuffer = new TFloatArrayList();
TFloatArrayList colorBuffer = new TFloatArrayList();
TFloatArrayList normalBuffer = new TFloatArrayList();
boolean useColors = false;
boolean useNormals = false;
Shader activeShader = null;
public BatchVertexRenderer(int mode){
renderMode = mode;
}
/**
* Begin batching render calls
*/
public void begin(){
if(batching) throw new IllegalStateException("Already Batching!");
batching = true;
flushed = false;
vertexBuffer.clear();
colorBuffer.clear();
}
/**
* Ends batching and flushes cache to the GPU
*/
public void end(){
if(!batching) throw new IllegalStateException("Not Batching!");
batching = false;
flush();
}
protected void flush(){
flushed = true;
}
/**
* Draws this batch
*/
public abstract void render();
protected void checkRender(){
if(batching) throw new IllegalStateException("Cannot Render While Batching");
if(!flushed) throw new IllegalStateException("Cannon Render Without Flushing the Batch");
}
public void AddVertex(float x, float y, float z){
vertexBuffer.add(x);
vertexBuffer.add(y);
vertexBuffer.add(z);
vertexBuffer.add(1.0f);
}
public void AddVertex(float x, float y, float z, float w){
vertexBuffer.add(x);
vertexBuffer.add(y);
vertexBuffer.add(z);
vertexBuffer.add(w);
}
public void AddVertex(float x, float y){
vertexBuffer.add(x);
vertexBuffer.add(y);
vertexBuffer.add(1.0f);
vertexBuffer.add(1.0f);
}
public void AddVertex(Vector3f vertex){
AddVertex(vertex.x, vertex.y, vertex.z);
}
public void AddVertex(Vector2f vertex){
AddVertex(vertex.x, vertex.y);
}
public void AddVertex(Vector4f vertex){
AddVertex(vertex.x, vertex.y, vertex.z, vertex.w);
}
public void AddColor(float r, float g, float b){
colorBuffer.add(r);
colorBuffer.add(g);
colorBuffer.add(b);
colorBuffer.add(1.0f);
}
public void AddColor(float r, float g, float b, float a){
colorBuffer.add(r);
colorBuffer.add(g);
colorBuffer.add(b);
colorBuffer.add(a);
}
public void AddNormal(float x, float y, float z){
normalBuffer.add(x);
normalBuffer.add(y);
normalBuffer.add(z);
normalBuffer.add(1.0f);
}
public void AddNormal(float x, float y, float z, float w){
normalBuffer.add(x);
normalBuffer.add(y);
normalBuffer.add(z);
normalBuffer.add(w);
}
public void AddNormal(float x, float y){
normalBuffer.add(x);
normalBuffer.add(y);
normalBuffer.add(1.0f);
normalBuffer.add(1.0f);
}
public void AddNormal(Vector3f vertex){
AddVertex(vertex.x, vertex.y, vertex.z);
}
public void AddNormal(Vector2f vertex){
AddVertex(vertex.x, vertex.y);
}
public void AddNormal(Vector4f vertex){
AddVertex(vertex.x, vertex.y, vertex.z, vertex.w);
}
public void setShader(Shader shader){
if(shader == null){
try {
activeShader = new EmptyShader();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else activeShader = shader;
}
public void enableColors(){
useColors = true;
}
public void enableNormals(){
useNormals = true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.