answer stringlengths 17 10.2M |
|---|
package io.scif.formats;
import io.scif.AbstractFormat;
import io.scif.AbstractMetadata;
import io.scif.AbstractParser;
import io.scif.ByteArrayPlane;
import io.scif.ByteArrayReader;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.common.DataTools;
import io.scif.io.RandomAccessInputStream;
import io.scif.util.FormatTools;
import java.io.IOException;
import net.imglib2.meta.Axes;
import org.scijava.plugin.Plugin;
@Plugin(type = Format.class)
public class FITSFormat extends AbstractFormat {
// -- Format API Methods --
public String getFormatName() {
return "Flexible Image Transport System";
}
public String[] getSuffixes() {
return new String[] { "fits", "fts" };
}
// -- Nested Classes --
/**
* @author Mark Hiner
*/
public static class Metadata extends AbstractMetadata {
// -- Constants --
public static final String CNAME = "io.scif.formats.FITSFormat$Metadata";
// -- Fields --
private long pixelOffset;
// -- FITS Metadata getters and setters --
public long getPixelOffset() {
return pixelOffset;
}
public void setPixelOffset(final long pixelOffset) {
this.pixelOffset = pixelOffset;
}
// -- Metadata API methods --
public void populateImageMetadata() {
final ImageMetadata iMeta = get(0);
if (iMeta.getAxisLength(Axes.Z) == 0) iMeta.setAxisLength(Axes.Z, 1);
iMeta.setAxisLength(Axes.CHANNEL, 1);
iMeta.setAxisLength(Axes.TIME, 1);
// correct for truncated files
final int planeSize =
iMeta.getAxisLength(Axes.X) * iMeta.getAxisLength(Axes.Y) *
FormatTools.getBytesPerPixel(iMeta.getPixelType());
try {
if (DataTools.safeMultiply64(planeSize, iMeta.getAxisLength(Axes.Z)) > (getSource()
.length() - pixelOffset))
{
iMeta.setAxisLength(Axes.Z,
(int) ((getSource().length() - pixelOffset) / planeSize));
}
}
catch (final IOException e) {
log().error("Failed to determine input stream length", e);
}
iMeta.setPlaneCount(iMeta.getAxisLength(Axes.Z));
iMeta.setRGB(false);
iMeta.setLittleEndian(false);
iMeta.setInterleaved(false);
iMeta.setIndexed(false);
iMeta.setFalseColor(false);
iMeta.setMetadataComplete(true);
}
@Override
public void close() {
pixelOffset = 0;
}
}
/**
* @author Mark Hiner
*/
public static class Parser extends AbstractParser<Metadata> {
private static final int LINE_LENGTH = 80;
@Override
protected void typedParse(final RandomAccessInputStream stream,
final Metadata meta) throws IOException, FormatException
{
meta.createImageMetadata(1);
final ImageMetadata iMeta = meta.get(0);
String line = in.readString(LINE_LENGTH);
if (!line.startsWith("SIMPLE")) {
throw new FormatException("Unsupported FITS file.");
}
String key = "", value = "";
while (true) {
line = in.readString(LINE_LENGTH);
// parse key/value pair
final int ndx = line.indexOf("=");
int comment = line.indexOf("/", ndx);
if (comment < 0) comment = line.length();
if (ndx >= 0) {
key = line.substring(0, ndx).trim();
value = line.substring(ndx + 1, comment).trim();
}
else key = line.trim();
// if the file has an extended header, "END" will appear twice
// the first time marks the end of the extended header
// the second time marks the end of the standard header
// image dimensions are only populated by the standard header
if (key.equals("END") && iMeta.getAxisLength(Axes.X) > 0) break;
if (key.equals("BITPIX")) {
final int bits = Integer.parseInt(value);
final boolean fp = bits < 0;
final boolean signed = bits != 8;
final int bytes = Math.abs(bits) / 8;
iMeta.setPixelType(FormatTools.pixelTypeFromBytes(bytes, signed, fp));
iMeta.setBitsPerPixel(Math.abs(bits));
}
else if (key.equals("NAXIS1")) iMeta.setAxisLength(Axes.X, Integer
.parseInt(value));
else if (key.equals("NAXIS2")) iMeta.setAxisLength(Axes.Y, Integer
.parseInt(value));
else if (key.equals("NAXIS3")) iMeta.setAxisLength(Axes.Z, Integer
.parseInt(value));
addGlobalMeta(key, value);
}
while (in.read() == 0x20);
meta.setPixelOffset(in.getFilePointer() - 1);
}
}
/**
* @author Mark Hiner
*/
public static class Reader extends ByteArrayReader<Metadata> {
// -- Constructor --
public Reader() {
domains =
new String[] { FormatTools.ASTRONOMY_DOMAIN, FormatTools.UNKNOWN_DOMAIN };
}
// -- Reader API Methods --
public ByteArrayPlane openPlane(final int imageIndex, final int planeIndex,
final ByteArrayPlane plane, final int x, final int y, final int w,
final int h) throws FormatException, IOException
{
final byte[] buf = plane.getData();
FormatTools.checkPlaneParameters(this, imageIndex, planeIndex,
buf.length, x, y, w, h);
getStream().seek(
getMetadata().getPixelOffset() + planeIndex *
FormatTools.getPlaneSize(this, imageIndex));
return readPlane(getStream(), imageIndex, x, y, w, h, plane);
}
}
} |
package com.artifex.mupdf;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ChoosePDFActivity extends ListActivity {
private File mDirectory;
private File [] mFiles;
private Handler mHandler;
private Runnable mUpdateFiles;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
String appName = res.getString(R.string.app_name);
String version = res.getString(R.string.version);
String title = res.getString(R.string.picker_title);
setTitle(String.format(title, appName, version));
String storageState = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(storageState)
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.no_media_warning);
builder.setMessage(R.string.no_media_hint);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE,"Dismiss",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
}
@Override
protected void onResume() {
super.onResume();
mDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
// Create a list adapter...
List<String> fileNames = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.picker_entry, fileNames);
setListAdapter(adapter);
// ...that is updated dynamically when files are scanned
mHandler = new Handler();
mUpdateFiles = new Runnable() {
public void run() {
mFiles = mDirectory.listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
if (name.toLowerCase().endsWith(".pdf"))
return true;
if (name.toLowerCase().endsWith(".xps"))
return true;
if (name.toLowerCase().endsWith(".cbz"))
return true;
return false;
}
});
adapter.clear();
if (mFiles != null)
for (File f : mFiles)
adapter.add(f.getName());
}
};
// Start initial file scan...
mHandler.post(mUpdateFiles);
// ...and observe the directory and scan files upon changes.
FileObserver observer = new FileObserver(mDirectory.getPath(), FileObserver.CREATE | FileObserver.DELETE) {
public void onEvent(int event, String path) {
mHandler.post(mUpdateFiles);
}
};
observer.startWatching();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Uri uri = Uri.parse(mFiles[position].getAbsolutePath());
Intent intent = new Intent(this,MuPDFActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} |
package jmini3d.android;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import jmini3d.GpuObjectStatus;
import jmini3d.MatrixUtils;
import jmini3d.Object3d;
import jmini3d.Scene;
import jmini3d.android.compat.CompatibilityWrapper5;
import jmini3d.android.input.TouchController;
import jmini3d.input.TouchListener;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.PixelFormat;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.Log;
import com.mobialia.min3d.R;
public class Renderer implements GLSurfaceView.Renderer {
public static final String TAG = "Renderer";
public static boolean needsRedraw = true;
// stats-related
public static final int FRAMERATE_SAMPLEINTERVAL_MS = 1000;
private boolean logFps = false;
private long frameCount = 0;
private float fps = 0;
private long timeLastSample;
public GLSurfaceView glSurfaceView;
private ActivityManager activityManager;
private ActivityManager.MemoryInfo memoryInfo;
Scene scene;
private ResourceLoader resourceLoader;
private GpuUploader gpuUploader;
private TouchController touchController;
public float[] ortho = new float[16];
int width;
int height;
private int shaderProgram;
private int vertexPositionAttribute, vertexNormalAttribute, textureCoordAttribute;
private int uPerspectiveMatrix, uModelViewMatrix,
uNormalMatrix, uUseLighting, uAmbientColor, uPointLightingLocation,
uPointLightingColor, uSampler, uEnvMap, uReflectivity, uObjectColor, uObjectColorTrans;
boolean stop = false;
public Renderer(Context context, Scene scene, ResourceLoader resourceLoader, boolean traslucent) {
this.scene = scene;
this.resourceLoader = resourceLoader;
activityManager = (ActivityManager) resourceLoader.getContext().getSystemService(Context.ACTIVITY_SERVICE);
memoryInfo = new ActivityManager.MemoryInfo();
MatrixUtils.ortho(ortho, 0, 1, 0, 1, -5, 1);
glSurfaceView = new GLSurfaceView(context);
glSurfaceView.setEGLContextClientVersion(2);
// TODO
//glSurfaceView.setPreserveEGLContextOnPause(true);
if (traslucent) {
if (Build.VERSION.SDK_INT >= 5) {
CompatibilityWrapper5.setZOrderOnTop(glSurfaceView);
}
glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
}
glSurfaceView.setRenderer(this);
glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
glSurfaceView.setFocusable(true); // make sure we get key events
glSurfaceView.setFocusableInTouchMode(true);
glSurfaceView.requestFocus();
gpuUploader = new GpuUploader(resourceLoader);
}
public void onSurfaceCreated(GL10 unused, EGLConfig eglConfig) {
Log.i(TAG, "onSurfaceCreated()");
initShaders();
width = -1;
height = -1;
}
public void onSurfaceChanged(GL10 unused, int w, int h) {
Log.i(TAG, "onSurfaceChanged()");
if (w != width || h != height) {
setSize(w, h);
width = w;
height = h;
}
}
public void onPause() {
glSurfaceView.onPause();
}
public void onResume() {
glSurfaceView.onResume();
}
public void setSize(int width, int height) {
scene.camera.setWidth(width);
scene.camera.setHeight(height);
// Scene reload on size changed, needed to keep aspect ratios
reset();
gpuUploader.reset();
scene.reset();
scene.sceneController.initScene();
needsRedraw = true;
}
private void reset() {
GLES20.glClearDepthf(1.0f);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthFunc(GLES20.GL_LEQUAL);
// For transparency
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
}
public void onDrawFrame(GL10 unused) {
boolean sceneUpdated = scene.sceneController.updateScene();
boolean cameraChanged = scene.camera.updateMatrices();
if (!needsRedraw && !sceneUpdated && !cameraChanged) {
return;
}
for (Object o : scene.unload) {
gpuUploader.unload(o);
}
scene.unload.clear();
needsRedraw = false;
GLES20.glViewport(0, 0, scene.camera.getWidth(), scene.camera.getHeight());
GLES20.glClearColor(scene.getBackgroundColor().r, scene.getBackgroundColor().g, scene.getBackgroundColor().b, scene.getBackgroundColor().a);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
setSceneUniforms();
for (Object3d o3d : scene.children) {
if (o3d.visible) {
o3d.updateMatrices(scene.camera.modelViewMatrix, cameraChanged);
drawObject(o3d);
}
}
GLES20.glUniformMatrix4fv(uPerspectiveMatrix, 1, false, ortho, 0);
for (Object3d o3d : scene.hud) {
if (o3d.visible) {
o3d.updateMatrices(MatrixUtils.IDENTITY4, false);
drawObject(o3d);
}
}
if (logFps) {
doFps();
}
}
private void drawObject(Object3d o3d) {
GeometryBuffers buffers = gpuUploader.upload(o3d.geometry3d);
if (o3d.material.texture != null) {
gpuUploader.upload(o3d.material.texture);
if ((o3d.material.texture.status & GpuObjectStatus.TEXTURE_UPLOADED) == 0)
return;
}
if (o3d.material.envMapTexture != null) {
gpuUploader.upload(o3d.material.envMapTexture);
if ((o3d.material.envMapTexture.status & GpuObjectStatus.TEXTURE_UPLOADED) == 0)
return;
}
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers.vertexBufferId);
GLES20.glVertexAttribPointer(vertexPositionAttribute, 3, GLES20.GL_FLOAT, false, 0, 0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers.normalsBufferId);
GLES20.glVertexAttribPointer(vertexNormalAttribute, 3, GLES20.GL_FLOAT, false, 0, 0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers.uvsBufferId);
GLES20.glVertexAttribPointer(textureCoordAttribute, 2, GLES20.GL_FLOAT, false, 0, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, buffers.facesBufferId);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, gpuUploader.textures.get(o3d.material.texture));
setMaterialUniforms(o3d);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, o3d.geometry3d.facesLength, GLES20.GL_UNSIGNED_SHORT, 0);
}
private void setSceneUniforms() {
GLES20.glUniform1i(uSampler, 0);
GLES20.glUniform1i(uUseLighting, 1);
GLES20.glUniform3f(uAmbientColor, scene.ambientColor.r, scene.ambientColor.g, scene.ambientColor.b);
GLES20.glUniform3f(uPointLightingColor, scene.pointLightColor.r, scene.pointLightColor.g, scene.pointLightColor.b);
GLES20.glUniform3f(uPointLightingLocation, scene.pointLightLocation.x, scene.pointLightLocation.y, scene.pointLightLocation.z);
GLES20.glUniformMatrix4fv(uPerspectiveMatrix, 1, false, scene.camera.perspectiveMatrix, 0);
}
private void setMaterialUniforms(Object3d o3d) {
GLES20.glUniformMatrix4fv(uModelViewMatrix, 1, false, o3d.modelViewMatrix, 0);
if (o3d.normalMatrix != null) { // BUG
GLES20.glUniformMatrix3fv(uNormalMatrix, 1, false, o3d.normalMatrix, 0);
}
GLES20.glUniform3f(uObjectColor, o3d.material.color.r, o3d.material.color.g, o3d.material.color.b);
GLES20.glUniform1f(uObjectColorTrans, o3d.material.color.a);
GLES20.glUniform1f(uReflectivity, o3d.material.reflectivity);
GLES20.glUniform1i(uEnvMap, 1); // This out the if or fails
if (o3d.material.envMapTexture != null) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, gpuUploader.cubeMapTextures.get(o3d.material.envMapTexture));
}
}
private void initShaders() {
int fragmentShader = getShader(GLES20.GL_FRAGMENT_SHADER, resourceLoader.loadRawResource(R.raw.fragment_shader));
int vertexShader = getShader(GLES20.GL_VERTEX_SHADER, resourceLoader.loadRawResource(R.raw.vertex_shader));
shaderProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(shaderProgram, vertexShader);
GLES20.glAttachShader(shaderProgram, fragmentShader);
GLES20.glLinkProgram(shaderProgram);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(shaderProgram, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(shaderProgram));
GLES20.glDeleteProgram(shaderProgram);
shaderProgram = 0;
}
GLES20.glUseProgram(shaderProgram);
vertexPositionAttribute = GLES20.glGetAttribLocation(shaderProgram, "vertexPosition");
GLES20.glEnableVertexAttribArray(vertexPositionAttribute);
textureCoordAttribute = GLES20.glGetAttribLocation(shaderProgram, "textureCoord");
GLES20.glEnableVertexAttribArray(textureCoordAttribute);
vertexNormalAttribute = GLES20.glGetAttribLocation(shaderProgram, "vertexNormal");
GLES20.glEnableVertexAttribArray(vertexNormalAttribute);
uPerspectiveMatrix = GLES20.glGetUniformLocation(shaderProgram, "perspectiveMatrix");
uModelViewMatrix = GLES20.glGetUniformLocation(shaderProgram, "modelViewMatrix");
uNormalMatrix = GLES20.glGetUniformLocation(shaderProgram, "normalMatrix");
uUseLighting = GLES20.glGetUniformLocation(shaderProgram, "useLighting");
uAmbientColor = GLES20.glGetUniformLocation(shaderProgram, "ambientColor");
uPointLightingLocation = GLES20.glGetUniformLocation(shaderProgram, "pointLightingLocation");
uPointLightingColor = GLES20.glGetUniformLocation(shaderProgram, "pointLightingColor");
uSampler = GLES20.glGetUniformLocation(shaderProgram, "sampler");
uObjectColor = GLES20.glGetUniformLocation(shaderProgram, "objectColor");
uObjectColorTrans = GLES20.glGetUniformLocation(shaderProgram, "objectColorTrans");
uReflectivity = GLES20.glGetUniformLocation(shaderProgram, "reflectivity");
uEnvMap = GLES20.glGetUniformLocation(shaderProgram, "envMap");
}
private int getShader(int type, String source) {
int shader = GLES20.glCreateShader(type);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
return shader;
}
public GpuUploader getGpuUploader() {
return gpuUploader;
}
public void requestRender() {
needsRedraw = true;
}
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
public void setTouchListener(TouchListener listener) {
if (touchController == null) {
touchController = new TouchController(glSurfaceView);
}
touchController.setListener(listener);
}
public void stop() {
stop = true;
}
public GLSurfaceView getView() {
return glSurfaceView;
}
/**
* If true, framerate and memory is periodically calculated and Log'ed, and
* gettable thru fps()
*/
public void setLogFps(boolean b) {
logFps = b;
if (logFps) { // init
timeLastSample = System.currentTimeMillis();
frameCount = 0;
}
}
private void doFps() {
frameCount++;
long now = System.currentTimeMillis();
long delta = now - timeLastSample;
if (delta >= FRAMERATE_SAMPLEINTERVAL_MS) {
fps = frameCount / (delta / 1000f);
activityManager.getMemoryInfo(memoryInfo);
Log.v(TAG, "FPS: " + Math.round(fps) + ", availMem: " + Math.round(memoryInfo.availMem / 1048576) + "MB");
timeLastSample = now;
frameCount = 0;
}
}
/**
* Returns last sampled framerate (logFps must be set to true)
*/
public float getFps() {
return fps;
}
} |
package de.holisticon.util;
import de.holisticon.util.tracee.Tracee;
import de.holisticon.util.tracee.TraceeException;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Daniel Wegener (Holisticon AG)
*/
public class TraceeTest {
@Test(expected = TraceeException.class)
public void testGetContext() throws Exception {
try {
Tracee.getBackend();
} catch (TraceeException e) {
assertThat(e.getMessage(), equalTo("Unable to find a tracee backend provider. Make sure that you have a implementation on your classpath."));
throw e;
}
}
} |
package be.viaa.fxp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import be.viaa.util.Strings;
/**
* FXP implementation of a file transporter
*
* @author Hannes Lowette
*
*/
public class FxpFileTransporter implements FileTransporter {
/**
* The logger for this class
*/
private static final Logger logger = LogManager.getLogger(FxpFileTransporter.class);
/**
* The maximum amount of retry attempts
*/
private static final int MAX_RETRY_ATTEMPTS = 10;
/**
* The amount of times the file size equal check needs to verify
*/
private static final int FILESIZE_EQUAL_CHECKS = 10;
/**
* The interval in between 2 file size checks
*/
private static final long FILESIZE_COMPARE_INTERVAL = 10000L;
/**
* The executor service
*/
private final ExecutorService executor = Executors.newCachedThreadPool();
@Override
public void transfer(File sourceFile, File destinationFile, Host source, Host destination, boolean move) throws IOException {
FxpStatus status = FxpStatus.RUNNING;
/*
* Debug information
*/
logger.debug("Attempting file transfer");
logger.debug("Source Host: {}:{}", source.getHost(), source.getPort());
logger.debug("Target Host: {}:{}", source.getHost(), source.getPort());
logger.debug("Source file: {}/{}", sourceFile.getDirectory(), sourceFile.getName());
logger.debug("Target file: {}/{}", destinationFile.getDirectory(), destinationFile.getName());
/*
* Attempt 10 times to transfer the file correctly
*/
for (int attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) {
if ((status = transferSingle(sourceFile, destinationFile, source, destination)) == FxpStatus.OK) {
break;
}
else if (attempt + 1 >= MAX_RETRY_ATTEMPTS) {
throw new IOException("file could not be transferred");
}
else {
logger.info("RETRY {}", attempt);
}
try {
Thread.sleep(10000L);
} catch (Exception ex) {
ex.printStackTrace(); // This should never happen
}
}
/*
* If move is set to true, the source file needs to be deleted
*/
if (FxpStatus.OK.equals(status) && move) {
delete(sourceFile, source);
}
}
@Override
public void move(File sourceFile, File destinationFile, Host host) throws IOException {
FTPClient client = connect(host);
try {
logger.debug("attempting to move file");
logger.debug("Host: {}", host.getHost());
logger.debug("Directory: {}", sourceFile.getDirectory());
logger.debug("Source filename: {}", sourceFile.getName());
logger.debug("Target filename: {}", destinationFile.getName());
// /*
// * Send the commands that indicate a transaction needs to happen
// */
// client.sendCommand("TYPE I");
// /*
// * Send the STOR and RETR commands to the corresponding FTP servers
// * TODO: Find out why this needs to be on a different thread.
// */
// executor.submit(new FxpCommandThread(client, "RNFR " + sourceFile.getDirectory() + "/" + sourceFile.getName()));
// executor.submit(new FxpCommandThread(client, "RNTO " + destinationFile.getDirectory() + "/" + destinationFile.getName()));
if (client.rename(sourceFile.getDirectory() + "/" + sourceFile.getName(), destinationFile.getDirectory() + "/" + destinationFile.getName())) {
logger.info("SUCCESS: moved file from directory '{}' to '{}'", sourceFile.getDirectory(), destinationFile.getDirectory());
}
else {
throw new IOException("could not move file '" + sourceFile.getDirectory() + "/" + sourceFile.getName() + "' - " + client.getReplyString());
}
} catch (IOException ex) {
// TODO: Connection to the FTP server has gone wrong
logger.catching(ex);
} finally {
client.disconnect();
}
}
@Override
public void delete(File file, Host host) throws IOException {
FTPClient client = connect(host);
try {
logger.debug("attempting to delete file");
logger.debug("Host: {}:{}", host.getHost(), host.getPort());
logger.debug("File: {}/{}", file.getDirectory(), file.getName());
/*
* Check to see if the source file exists and whether it' a file or a directory
*/
client.changeWorkingDirectory(file.getDirectory());
boolean isDirectory = false;
if (containsFile(Arrays.asList(client.listDirectories()), file.getName())) {
// This is a directory
isDirectory = true;
} else {
// This might be a file
if (!containsFile(Arrays.asList(client.listFiles()), file.getName())) {
// No. Nothing exists
throw new FileNotFoundException("could not find file " + file.getDirectory() + "/" + file.getName() + " on the FTP server");
}
}
/*
* Delete the file or directory from the remote FTP server and return the OK status when successful
*/
if (!isDirectory) {
if (!client.deleteFile(file.getName())) {
throw new IOException("could not delete " + file.getDirectory() + "/" + file.getName());
}
else {
logger.info("SUCCESS: file {}/{} successfully deleted", file.getDirectory(), file.getName());
}
} else {
// We must delete a directory. Recursively delete all files within it
removeDirectory(client, file.getDirectory(), file.getName());
}
} finally {
client.disconnect();
}
}
public static boolean containsFile(List<FTPFile> files, String file) {
for (FTPFile ftpFile : files) {
if (ftpFile.getName().equals(file)) {
return true;
}
}
return false;
}
public static void removeDirectory(FTPClient ftpClient, String parentDir,
String currentDir) throws IOException {
String dirToList = parentDir;
if (!currentDir.equals("")) {
dirToList += "/" + currentDir;
}
FTPFile[] subFiles = ftpClient.listFiles(dirToList);
if (subFiles != null && subFiles.length > 0) {
for (FTPFile aFile : subFiles) {
String currentFileName = aFile.getName();
if (currentFileName.equals(".") || currentFileName.equals("..")) {
// skip parent directory and the directory itself
continue;
}
String filePath = parentDir + "/" + currentDir + "/"
+ currentFileName;
if (currentDir.equals("")) {
filePath = parentDir + "/" + currentFileName;
}
if (aFile.isDirectory()) {
// remove the sub directory
removeDirectory(ftpClient, dirToList, currentFileName);
} else {
// delete the file
boolean deleted = ftpClient.deleteFile(filePath);
if (deleted) {
logger.info("DELETED the file: " + filePath);
} else {
logger.info("CANNOT delete the file: "
+ filePath);
throw new IOException("CANNOT delete the file: "
+ filePath);
}
}
}
// finally, remove the directory itself
boolean removed = ftpClient.removeDirectory(dirToList);
if (removed) {
logger.info("REMOVED the directory: " + dirToList);
} else {
logger.info("CANNOT remove the directory: " + dirToList);
throw new IOException("CANNOT remove the directory: " + dirToList);
}
}
}
@Override
public void rename(File source, File destination, Host host) throws IOException {
FTPClient client = connect(host);
logger.info("attempting to rename file '{}/{}'", source.getDirectory(), source.getName());
logger.debug("Host: {}:{}", host.getHost(), host.getPort());
logger.debug("New: {}/{}", destination.getDirectory(), destination.getName());
try {
client.changeWorkingDirectory(source.getDirectory());
client.rename(source.getName(), destination.getName());
logger.info("SUCCESS: renamed file '{}/{}'", source.getDirectory(), source.getName());
} finally {
client.disconnect();
}
}
private FxpStatus transferSingle(File sourceFile, File destinationFile, Host source, Host destination) throws IOException {
FTPClient sourceClient = connect(source);
FTPClient targetClient = connect(destination);
Future<?> future_source = null;
Future<?> future_destination = null;
File partFile = destinationFile.derive(destinationFile.getName() + ".part");
try {
/*
* Send the commands that indicate a transaction needs to happen
* TODO: Rework to use short commands?
*/
targetClient.sendCommand("TYPE I");
sourceClient.sendCommand("TYPE I");
targetClient.sendCommand("PASV");
sourceClient.sendCommand("PORT " + filterPortNumber(targetClient.getReplyString()));
/*
* Transfer the file data
*/
createDirectoryTree(destinationFile, targetClient);
createDirectoryTree(sourceFile, sourceClient);
/*
* Send the STOR and RETR commands to the corresponding FTP servers.
*/
logger.debug("sending store and retreive commands");
future_destination = executor.submit(new FxpCommandThread(targetClient, "STOR " + partFile.getName()));
future_source = executor.submit(new FxpCommandThread(sourceClient, "RETR " + sourceFile.getName()));
/*
* Periodically check the size of the partfile and compare it to the size of the file that
* is being transferred.
*/
AtomicInteger counter = new AtomicInteger();
AtomicLong currentSize = new AtomicLong();
AtomicLong expectedSize = new AtomicLong(get(sourceFile, source).getSize());
while (currentSize.get() != expectedSize.get() && counter.get() <= FILESIZE_EQUAL_CHECKS) {
Thread.sleep(FILESIZE_COMPARE_INTERVAL);
long filesize = get(partFile, destination).getSize();
if (filesize == currentSize.get()) {
// If these are equal, the file hasn't progressed at all in 30 seconds
counter.incrementAndGet();
}
currentSize.set(filesize);
logger.info("Transfer progress: {}", ((float) currentSize.get() * 100) / ((float) expectedSize.get()));
}
/*
* Check to see if the file sizes are different
*/
if (expectedSize.get() != get(partFile, destination).getSize()) {
// TODO: the files have not successfully transferred
logger.warn("ERROR: could not transfer file {}/{}", sourceFile.getDirectory(), sourceFile.getName());
return FxpStatus.ERROR;
}
/*
* If they aren't, we can assume the files are equal
*/
else {
rename(partFile, destinationFile, destination);
logger.info("SUCCESS: file {}/{} transferred", sourceFile.getDirectory(), sourceFile.getName());
return FxpStatus.OK;
}
} catch (Exception ex) {
logger.catching(ex);
return FxpStatus.ERROR;
} finally {
sourceClient.disconnect();
targetClient.disconnect();
future_source.cancel(true);
future_destination.cancel(true);
}
}
/**
* Attempts to create the directory structure of the given file
*
* @param file
* @param client
* @return
* @throws IOException
*/
private boolean createDirectoryTree(File file, FTPClient client) throws IOException {
Deque<String> directoryStructure = new LinkedList<>(Arrays.asList(file.getDirectory().split("/")));
Deque<String> directoryUnexistant = new LinkedList<>();
logger.debug("creating directory tree for {}", file.getDirectory());
/*
* Scans to see which directory is already present and which directories
* need to be created.
*/
while (!directoryStructure.isEmpty()) {
if (!client.changeWorkingDirectory(Strings.join("/", directoryStructure))) {
directoryUnexistant.addFirst(directoryStructure.removeLast());
} else break;
}
logger.debug("folders to be created: {}", Strings.join("/", directoryUnexistant));
/*
* Creates the directories that need to be created
*/
for (Iterator<String> iterator = directoryUnexistant.iterator(); iterator.hasNext();) {
String directory = iterator.next();
if (!client.makeDirectory(directory) || !client.changeWorkingDirectory(directory)) {
throw new IOException("could not create directory tree");
}
}
return true;
}
/**
*
* @param client
* @param host
* @return
* @throws IOException
*/
private FTPClient connect(Host host) throws IOException {
FTPClient client = new FTPClient();
client.setControlEncoding("UTF8");
try {
logger.debug("connecting to {}:{}", host.getHost(), host.getPort());
/*
* Attempt to establish a connection
*/
client.connect(host.getHost(), host.getPort());
client.enterLocalPassiveMode();
logger.debug("made connection with {}:{}", host.getHost(), host.getPort());
/*
* Attempt to authenticate on the remote server
*/
if (!client.login(host.getUsername(), host.getPassword())) {
throw new IOException("invalid credentials for the source FTP");
}
logger.debug("successfully authenticated with {}:{}", host.getHost(), host.getPort());
/*
* Send both of the FTP hosts to see if they are reachable
*/
if (!client.isConnected() || !client.isAvailable()) {
throw new IOException("ftp connection not available");
}
return client;
} catch (Exception ex) {
if (client.isConnected())
client.disconnect();
throw new IOException("could not connect to " + host.getHost() + ":" + host.getPort(), ex);
}
}
/**
* Gets a remote FTP file by its name
*
* @param file
* @param client
* @return
*/
private FTPFile get(File file, Host host) throws IOException {
FTPClient client = connect(host);
try {
logger.debug("looking up file {}/{} on {}:{}", file.getDirectory(), file.getName(), host.getHost(), host.getPort());
client.changeWorkingDirectory(file.getDirectory());
FTPFile[] files = client.listFiles(file.getName());
if (files == null || files.length == 0) {
throw new FileNotFoundException("file '" + file.getDirectory() + "/" + file.getName() + "' not found on '" + client.getRemoteAddress().getHostAddress() + "'");
}
if (files.length == 1) {
return files[0];
}
throw new FileNotFoundException("ambiguous filename");
} finally {
client.disconnect();
}
}
/**
* Support method that is used to retrieve the port number that is received
* in a string in between 2 parentheses
*
* @param input
* @return
*/
private final String filterPortNumber(String input) {
return input.substring(input.indexOf("(") + 1, input.indexOf(")"));
}
} |
package checkdep.util;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import lombok.NonNull;
import lombok.Value;
@Value
public class ImmutableMapBase<K, V> {
@NonNull
private final ImmutableMap<K, V> map;
public ImmutableMapBase(Map<K, V> map) {
this.map = ImmutableMap.copyOf(map);
}
public Optional<V> get(@NonNull K key) {
return Optional.ofNullable(map.get(key));
}
public Set<K> keySet() {
return map.keySet();
}
public Collection<V> values() {
return map.values();
}
public Set<Map.Entry<K, V>> entrySet() {
return map.entrySet();
}
@Override
public String toString() {
return map.toString();
}
} |
package collinear;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Arrays;
public class BruteCollinearPoints {
private Point[] points;
private LineSegment[] lineSegments;
private int numberOfSegments = 0;
public BruteCollinearPoints(Point[] points) {
if (points == null || points.length == 0) {
throw new NullPointerException("there are no points");
}
if (points.length > 0) {
for (int i = 0; i < points.length; i++) {
if (points[i] == null) {
throw new NullPointerException("one of the points is null");
}
}
}
Set<Point> pointSet = new TreeSet<>();
if (points.length > 1) {
for (int i = 0; i < points.length; i++) {
pointSet.add(points[i]);
}
if (pointSet.size() != points.length) {
throw new IllegalArgumentException("there is a duplicate");
}
}
if (points.length == 1) {
return;
}
List<Point> pointList = new ArrayList<>(pointSet);
this.points = new Point[pointList.size()];
for (int i = 0; i < pointList.size(); i++) {
this.points[i] = pointList.get(i);
}
Arrays.sort(this.points);
lineSegments = new LineSegment[this.points.length];
double slope01, slope02, slope03;
if (this.points.length == 4) {
slope01 = this.points[0].slopeTo(this.points[1]);
slope02 = this.points[0].slopeTo(this.points[2]);
if (slope01 == slope02)
slope03 = this.points[0].slopeTo(this.points[3]);
else
return;
if (slope01 == slope02 && slope02 == slope03) {
if (numberOfSegments < this.points.length) {
lineSegments[numberOfSegments++]
= new LineSegment(this.points[0], this.points[3]);
}
}
} else {
for (int i = 0; i < this.points.length; i++) {
for (int j = 0 + i; j < this.points.length; j++) {
for (int k = 0 + j; k < this.points.length; k++) {
for (int l = 0 + k; l < this.points.length; l++) {
if (i != j && i != k && i != l && j != k && k != l) {
slope01 = this.points[i].slopeTo(this.points[j]);
slope02 = this.points[i].slopeTo(this.points[k]);
if (slope01 == slope02)
slope03 = this.points[i].slopeTo(this.points[l]);
else
continue;
if (slope01 == slope02 && slope02 == slope03) {
if (numberOfSegments < this.points.length) {
lineSegments[numberOfSegments++]
= new LineSegment(this.points[i],
this.points[l]);
}
}
}
}
}
}
}
}
} // finds all line segments containing 4 points
public LineSegment[] segments() {
LineSegment[] copyOfLineSegments = new LineSegment[numberOfSegments];
System.arraycopy(lineSegments, 0, copyOfLineSegments, 0, numberOfSegments);
return copyOfLineSegments;
} // the line segments
public int numberOfSegments() {
return numberOfSegments;
} // the number of line segments
} |
// DrawingTool.java
package imagej.data;
import imagej.util.RealRect;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import net.imglib2.RandomAccess;
import net.imglib2.meta.Axes;
import net.imglib2.type.numeric.RealType;
// TODO
// - move awt code out of here to avoid a dependency
// - black color draws in weird blue
// Ok, the problem is the image is 3 channel composite and not RGBMerged.
// So the draw gray code is called. Which draws on a single channel (the
// first?). Need code like elsewhere that draws to all channels if its a
// composite image. And maybe track channel fill values in draw tool rather
// than color/gray split.
// - text drawing uses shades of the current color. what is to be done when
// you're drawing into a gray dataset?
/**
* Draws data across all channels in an orthoplane of a {@link Dataset}. Many
* methods adapted from ImageJ1's ImageProcessor methods. Internally the drawing
* routines work in a UV plane. U and V can be specified from existing coord
* axes (i.e UV can equal XY or ZT or any other combination of Dataset axes that
* do not involve the channel axis). It is the user's responsibility to avoid
* using a single axis to specify both the U and V axes.
*
* @author Barry DeZonia
*/
public class DrawingTool {
// -- instance variables --
private final Dataset dataset;
private int uAxis;
private int vAxis;
private int channelAxis;
private final RandomAccess<? extends RealType<?>> accessor;
private long lineWidth;
private long u0, v0;
private long maxU, maxV;
private final ChannelCollection channels;
private double intensity;
private TextRenderer textRenderer;
public enum FontFamily {
MONOSPACED, SERIF, SANS_SERIF
}
public enum FontStyle {
PLAIN, BOLD, ITALIC, BOLD_ITALIC
}
public enum TextJustification {
LEFT, CENTER, RIGHT
}
// -- constructor --
/**
* Creates a DrawingTool to modify a specified Dataset. Will draw pixel values
* using the given fill values. After construction the default U axis will be
* the first non-channel axis. The default V axis will be the second
* non-channel axis.
*/
public DrawingTool(final Dataset ds, final ChannelCollection fillValues) {
this.dataset = ds;
this.accessor = ds.getImgPlus().randomAccess();
this.channels = new ChannelCollection(fillValues);
this.lineWidth = 1;
this.intensity = 1;
this.textRenderer = new AWTTextRenderer(); // FIXME - do elsewhere
textRenderer.setAntialiasing(true);
this.u0 = 0;
this.v0 = 0;
initAxisVariables();
}
// -- public interface --
/** Return the Dataset associated with this DrawingTool. */
public Dataset getDataset() {
return dataset;
}
/** Sets the U axis index this DrawingTool will work in. */
public void setUAxis(final int axisNum) {
checkAxisValid(axisNum);
uAxis = axisNum;
maxU = dataset.dimension(uAxis) - 1;
}
/** Returns the index of the U axis of this Drawing Tool. */
public int getUAxis() {
return uAxis;
}
/** Sets the V axis index this DrawingTool will work in. */
public void setVAxis(final int axisNum) {
checkAxisValid(axisNum);
vAxis = axisNum;
maxV = dataset.dimension(vAxis) - 1;
}
/** Returns the index of the V axis of this Drawing Tool. */
public int getVAxis() {
return vAxis;
}
/**
* Sets this DrawingHelper's current drawing position. Usually specified once
* before a series of drawing operations are done. Useful for changing the
* drawing plane position quickly. Also useful when changing U or V axes.
*/
public void setPosition(final long[] position) {
accessor.setPosition(position);
}
/** Gets this DrawingHelper's current drawing position. */
public void getPosition(final long[] position) {
for (int i = 0; i < accessor.numDimensions(); i++)
position[i] = accessor.getLongPosition(i);
}
public ChannelCollection getChannels() {
return channels;
}
/**
* Sets the current drawing line width. This affects how other methods draw
* such as lines, circles, dots, etc.
*/
public void setLineWidth(final long lineWidth) {
this.lineWidth = lineWidth;
}
/** Gets the current drawing line width. */
public long getLineWidth() {
return lineWidth;
}
public void setTextRenderer(final TextRenderer renderer) {
this.textRenderer = renderer;
}
/**
* Sets the family name of the drawing font.
*/
public void setFontFamily(final FontFamily family) {
textRenderer.setFontFamily(family);
}
/**
* Gets the family name of the drawing font.
*/
public FontFamily getFontFamily() {
return textRenderer.getFontFamily();
}
/**
* Sets the style of the drawing font.
*/
public void setFontStyle(final FontStyle style) {
textRenderer.setFontStyle(style);
}
/**
* Gets the style of the drawing font.
*/
public FontStyle getFontStyle() {
return textRenderer.getFontStyle();
}
/**
* Sets the size of the drawing font.
*/
public void setFontSize(final int size) {
textRenderer.setFontSize(size);
}
/**
* Gets the size of the drawing font.
*/
public int getFontSize() {
return textRenderer.getFontSize();
}
/** Draws a pixel in the current UV plane at specified UV coordinates. */
public void drawPixel(final long u, final long v) {
if (u < 0) return;
if (v < 0) return;
if (u > maxU) return;
if (v > maxV) return;
accessor.setPosition(u, uAxis);
accessor.setPosition(v, vAxis);
long numChan = 1;
if (channelAxis != -1) numChan = dataset.dimension(channelAxis);
for (long c = 0; c < numChan; c++) {
final double value = intensity * channels.getChannelValue(c);
if (channelAxis != -1) accessor.setPosition(c, channelAxis);
accessor.get().setReal(value);
}
}
/**
* Draws a dot in the current UV plane at specified UV coordinates. The size
* of the dot is determined by the current line width.
*/
public void drawDot(final long u, final long v) {
if (lineWidth == 1) drawPixel(u, v);
else if (lineWidth == 2) {
drawPixel(u, v);
drawPixel(u, v - 1);
drawPixel(u - 1, v);
drawPixel(u - 1, v - 1);
}
else { // 3 or more pixels wide
drawCircle(u, v);
}
}
/**
* Moves the drawing origin of the current UV plane to the specified
* coordinates.
*/
public void moveTo(final long u, final long v) {
u0 = u;
v0 = v;
}
/**
* Draws a line in the current UV plane from the current origin to the
* specified coordinate.
*/
public void lineTo(final long u1, final long v1) {
final long du = u1 - u0;
final long dv = v1 - v0;
final long absdu = du >= 0 ? du : -du;
final long absdv = dv >= 0 ? dv : -dv;
long n = absdv > absdu ? absdv : absdu;
final double uinc = (double) du / n;
final double vinc = (double) dv / n;
double u = u0;
double v = v0;
n++;
u0 = u1;
v0 = v1;
// old IJ1 code - still relevant?
// if (n>1000000) return;
do {
drawDot(Math.round(u), Math.round(v));
u += uinc;
v += vinc;
}
while (--n > 0);
}
/** Draws a line from (u1,v1) to (u2,v2). */
public void drawLine(final long u1, final long v1, final long u2,
final long v2)
{
moveTo(u1, v1);
lineTo(u2, v2);
}
// TODO - performance improve drawCircle? Necessary? Test.
// TODO - make a version that draws the outline only. That version would need
// user to provide radius. Line width would be the width of the outline.
// TODO - make an ellipse method. have drawCircle call it.
/**
* Draws a filled circle in the current UV plane centered at the specified UV
* coordinates. The radius of the circle is equals the current line width.
*/
public void drawCircle(final long uc, final long vc) {
double r = lineWidth / 2.0;
final long umin = (long) (uc - r + 0.5);
final long vmin = (long) (vc - r + 0.5);
final long umax = umin + lineWidth;
final long vmax = vmin + lineWidth;
final double r2 = r * r;
r -= 0.5;
final double uoffset = umin + r;
final double voffset = vmin + r;
double uu, vv;
for (long v = vmin; v < vmax; v++) {
for (long u = umin; u < umax; u++) {
uu = u - uoffset;
vv = v - voffset;
if ((uu * uu + vv * vv) <= r2) drawPixel(u, v);
}
}
}
// TODO - IJ1 fill() applies to the ROI rectangle bounds. Do we want to mirror
// this behavior in IJ2? For now implement two fill methods. But perhaps in
// the future the DrawingTool might track a region of interest within a plane.
/**
* Fills the current UV plane.
*/
public void fill() {
for (long u = 0; u <= maxU; u++)
for (long v = 0; v <= maxV; v++)
drawPixel(u, v);
}
/**
* Fills a subset of the current UV plane.
*/
public void fill(final RealRect rect) {
for (long u = (long) rect.x; u < rect.x + rect.width; u++)
for (long v = (long) rect.y; v < rect.y + rect.height; v++)
drawPixel(u, v);
}
/**
* Draws a line of text along the U axis
*/
public void drawText(final long anchorU, final long anchorV,
final String text, final TextJustification just)
{
// render into buffer
textRenderer.renderText(text);
// get extents of drawn text in buffer
final int bufferSizeU = textRenderer.getPixelsWidth();
final int bufferSizeV = textRenderer.getPixelsHeight();
final int[] buffer = textRenderer.getPixels();
int minu = Integer.MAX_VALUE;
int minv = Integer.MAX_VALUE;
int maxu = Integer.MIN_VALUE;
int maxv = Integer.MIN_VALUE;
for (int u = 0; u < bufferSizeU; u++) {
for (int v = 0; v < bufferSizeV; v++) {
final int index = v * bufferSizeU + u;
// only worry about nonzero pixels
if (buffer[index] != 0) {
if (u < minu) minu = u;
if (u > maxu) maxu = u;
if (v < minv) minv = v;
if (v > maxv) maxv = v;
}
}
}
// determine drawing origin based on justification
long originU, originV;
switch (just) {
case CENTER:
originU = anchorU - (maxu - minu + 1) / 2;
originV = anchorV - (maxv - minv + 1) / 2;
break;
case RIGHT:
originU = anchorU - (maxu - minu + 1);
originV = anchorV - (maxv - minv + 1);
break;
default: // LEFT
originU = anchorU;
originV = anchorV;
break;
}
// draw pixels in dataset as needed
for (int u = minu; u <= maxu; u++) {
for (int v = minv; v <= maxv; v++) {
final int index = v * bufferSizeU + u;
// only render nonzero pixels
if (buffer[index] != 0) {
final double pixVal = buffer[index] & 0xff;
intensity = pixVal / 255.0;
drawPixel(originU + u - minu, originV + v - minv);
}
}
}
intensity = 1;
}
// -- private helpers --
private void initAxisVariables() {
channelAxis = dataset.getAxisIndex(Axes.CHANNEL);
uAxis = -1;
vAxis = -1;
for (int i = 0; i < dataset.numDimensions(); i++) {
if (i == channelAxis) continue;
if (uAxis == -1) uAxis = i;
else if (vAxis == -1) vAxis = i;
}
if (uAxis == -1 || vAxis == -1) {
throw new IllegalArgumentException(
"DrawingTool cannot find appropriate default UV axes");
}
maxU = dataset.dimension(uAxis) - 1;
maxV = dataset.dimension(vAxis) - 1;
}
private void checkAxisValid(final int axisNum) {
if (axisNum == channelAxis) {
throw new IllegalArgumentException("DrawingTool misconfiguration. "
+ "The tool fills multiple channels at once. "
+ "Cannot use a channel plane as working plane.");
}
}
/**
* Basic text renderer interface. Implementers render text into an int[]
* buffer. Values range from 0 to 255 (for now) and represent grayscale
* intensities. The buffer is then available afterwards including its
* dimensions. Users can set font attributes before rendering.
*/
private interface TextRenderer {
void renderText(String text);
int getPixelsWidth();
int getPixelsHeight();
int[] getPixels();
void setFontFamily(FontFamily family);
FontFamily getFontFamily();
void setFontStyle(FontStyle style);
FontStyle getFontStyle();
void setFontSize(int size);
int getFontSize();
void setAntialiasing(boolean val);
boolean getAntialiasing();
}
/**
* The AWT implementation of the TextRendered interface. TODO - relocate to
* some other subproject to remove AWT dependencies from this subproject.
*/
private class AWTTextRenderer implements TextRenderer {
private int bufferSizeU;
private int bufferSizeV;
private BufferedImage textBuffer;
private WritableRaster textRaster;
private String fontFamily;
private int fontStyle;
private int fontSize;
private Font font;
private int[] pixels;
private boolean antialiasing;
public AWTTextRenderer() {
fontFamily = Font.SANS_SERIF;
fontStyle = Font.PLAIN;
fontSize = 12;
antialiasing = false;
buildFont();
initTextBuffer("42 is my favorite number");
}
@Override
public void renderText(final String text) {
initTextBuffer(text);
final Graphics2D g = textBuffer.createGraphics();
setAntialiasedText(g, antialiasing);
g.setFont(font);
final int x = 0, y = bufferSizeV / 2;
// TODO: Why does Color.red look wrong (and Color.black paints nothing)?
drawTextOutline(g, text, Color.red, x, y, 5);
g.drawString(text, x, y);
g.dispose();
}
@Override
public int getPixelsWidth() {
return bufferSizeU;
}
@Override
public int getPixelsHeight() {
return bufferSizeV;
}
@Override
public int[] getPixels() {
if (pixels != null && pixels.length != bufferSizeU * bufferSizeV) {
pixels = null;
}
pixels = textRaster.getPixels(0, 0, bufferSizeU, bufferSizeV, pixels);
return pixels;
}
@Override
public void setFontFamily(final FontFamily family) {
final String familyString;
switch (family) {
case MONOSPACED:
familyString = Font.MONOSPACED;
break;
case SERIF:
familyString = Font.SERIF;
break;
case SANS_SERIF:
familyString = Font.SANS_SERIF;
break;
default:
throw new IllegalArgumentException("unknown font family: " + family);
}
if (font.getFamily().equalsIgnoreCase(familyString)) return;
this.fontFamily = familyString;
buildFont();
}
@Override
public FontFamily getFontFamily() {
if (fontFamily.equals(Font.MONOSPACED)) return FontFamily.MONOSPACED;
if (fontFamily.equals(Font.SERIF)) return FontFamily.SERIF;
if (fontFamily.equals(Font.SANS_SERIF)) return FontFamily.SANS_SERIF;
throw new IllegalArgumentException("unknown font family: " + fontFamily);
}
@Override
public void setFontStyle(final FontStyle style) {
final int styleInt;
switch (style) {
case PLAIN:
styleInt = Font.PLAIN;
break;
case BOLD:
styleInt = Font.BOLD;
break;
case ITALIC:
styleInt = Font.ITALIC;
break;
case BOLD_ITALIC:
styleInt = Font.BOLD | Font.ITALIC;
break;
default:
throw new IllegalArgumentException("unknown font style: " + style);
}
if (font.getStyle() == styleInt) return;
this.fontStyle = styleInt;
buildFont();
}
@Override
public FontStyle getFontStyle() {
switch (fontStyle) {
case Font.PLAIN:
return FontStyle.PLAIN;
case Font.BOLD:
return FontStyle.BOLD;
case Font.ITALIC:
return FontStyle.ITALIC;
case (Font.BOLD | Font.ITALIC):
return FontStyle.BOLD_ITALIC;
default:
throw new IllegalArgumentException("unknown font style: " + fontStyle);
}
}
@Override
public void setFontSize(final int size) {
if (size <= 0) return;
if (font.getSize() == size) return;
this.fontSize = size;
buildFont();
}
@Override
public int getFontSize() {
return fontSize;
}
@Override
public void setAntialiasing(final boolean val) {
antialiasing = val;
}
@Override
public boolean getAntialiasing() {
return antialiasing;
}
// -- private helpers --
private void buildFont() {
font = new Font(fontFamily, fontStyle, fontSize);
}
private void initTextBuffer(final String text) {
// the first time we call this method the buffer could be null.
// need to allocate an arbitrary one because calcTextSize() uses it
if (textBuffer == null) {
this.bufferSizeU = 200;
this.bufferSizeV = 20;
this.textBuffer =
new BufferedImage(bufferSizeU, bufferSizeV,
BufferedImage.TYPE_BYTE_GRAY);
this.textRaster = textBuffer.getRaster();
}
// determine extents of text to be drawn
final Rectangle extents = calcTextSize(text);
// if extents are bigger than existing buffer then allocate a new buffer
if ((extents.width > textBuffer.getWidth()) ||
(extents.height > textBuffer.getHeight()))
{
this.bufferSizeU = extents.width;
this.bufferSizeV = extents.height + 10; // + to avoid top clipping
this.textBuffer =
new BufferedImage(bufferSizeU, bufferSizeV,
BufferedImage.TYPE_BYTE_GRAY);
this.textRaster = textBuffer.getRaster();
}
else // use existing buffer but prepare for drawing into it
clearTextBuffer();
}
private void clearTextBuffer() {
for (int u = 0; u < bufferSizeU; u++)
for (int v = 0; v < bufferSizeV; v++)
textRaster.setSample(u, v, 0, 0);
}
private Rectangle calcTextSize(final String txt) {
final Graphics g = textBuffer.getGraphics();
final FontMetrics metrics = g.getFontMetrics(font);
g.dispose();
final int width = metrics.charsWidth(txt.toCharArray(), 0, txt.length());
final Rectangle extents = new Rectangle();
extents.x = 0;
extents.y = 0;
extents.width = width;
extents.height = metrics.getHeight() + 10;
return extents;
}
private void setAntialiasedText(final Graphics2D g,
final boolean antialiasedText)
{
final Object antialias =
antialiasedText ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
: RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antialias);
}
private void drawTextOutline(final Graphics2D g, final String text,
final Color c, final int x, final int y, final float outlineWidth)
{
final FontRenderContext frc = g.getFontRenderContext();
final TextLayout textLayout = new TextLayout(text, font, frc);
final AffineTransform transform = new AffineTransform();
transform.setToTranslation(x, y);
final Shape shape = textLayout.getOutline(transform);
final Color oldColor = g.getColor();
g.setStroke(new BasicStroke(outlineWidth));
g.setColor(c);
g.draw(shape);
g.setColor(oldColor);
}
}
} |
package com.bina.varsim.util;
import com.bina.varsim.types.ChrString;
import com.bina.varsim.types.FlexSeq;
import com.bina.varsim.types.variant.VariantType;
import com.bina.varsim.types.variant.Variant;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
/**
* Reads a DGV database flat file... not really sure if this format is stable
*/
public class DGVparser extends GzFileParser<Variant> {
private final static Logger log = Logger.getLogger(DGVparser.class.getName());
public final static String DGV_HEADER_START = "
public final static String DGV_COLUMN_SEPARATOR = "\t";
Random rand = null;
private SimpleReference reference;
/**
* This does not read the file, it just initialises the reading
*
* @param fileName DGV flat file filename
* @param reference Reference genome
*/
public DGVparser(String fileName, SimpleReference reference, Random rand) {
this.rand = rand;
try {
bufferedReader = new BufferedReader(new InputStreamReader(decompressStream(fileName)));
readLine(); // skip the first line
readLine();
} catch (IOException ex) {
log.error("Can't open file " + fileName);
log.error(ex.toString());
}
this.reference = reference;
}
/**
*
* @param dgvVariantType DGV Variant type
* @param dgvVariantSubtype DGV Variant subtype
* @return VariantType. Return value is null if cannot map to the right VariantType
*/
public VariantType getVariantType(final String dgvVariantType, final String dgvVariantSubtype) {
switch (dgvVariantType) {
case "CNV":
switch (dgvVariantSubtype) {
case "Gain":
return VariantType.Tandem_Duplication;
case "Loss":
return VariantType.Deletion;
case "CNV":
return VariantType.Tandem_Duplication;
case "Duplication":
return VariantType.Tandem_Duplication;
case "Insertion":
return VariantType.Insertion;
case "Deletion":
return VariantType.Deletion;
default:
return null;
}
case "OTHER":
switch (dgvVariantSubtype) {
case "Tandem Duplication":
return VariantType.Tandem_Duplication;
case "Inversion":
return VariantType.Inversion;
default:
return null;
}
default:
return null;
}
}
/**
*
* @param line
* @return True if the line is a header-line, false otherwise
*/
public boolean isHeaderLine(final String line) {
return line.startsWith(DGV_HEADER_START);
}
// returns null if the line is not a variant
public Variant parseLine() {
String line = this.line;
readLine();
if (line == null || line.length() == 0) {
return null;
}
if (isHeaderLine(line)) {
return null;
}
String[] ll = line.split(DGV_COLUMN_SEPARATOR);
/*
format
0 1 2 3 4 5 6
variantaccession chr start end varianttype variantsubtype reference
7 8 9
pubmedid method platform
10 11 12 13 14
mergedvariants supportingvariants mergedorsample frequency samplesize
15 16
observedgains observedlosses
17 18 19
cohortdescription genes samples
*/
final String var_id = ll[0];
final ChrString chr = new ChrString(ll[1]);
final int start_loc = Integer.parseInt(ll[2]);
final int end_loc = Integer.parseInt(ll[3]);
// determine variant type
final VariantType type = getVariantType(ll[4], ll[5]);
// TODO right now we treat all gains as tandem duplications
int observedgains = (ll[15].length() > 0) ? Integer.parseInt(ll[15]) : 0;
// TODO right now we treat any number of losses as a complete loss (ie.
// deletion)
// int observedlosses = Integer.parseInt(ll[16]);
String REF;
FlexSeq[] alts = new FlexSeq[1];
switch (type) {
case Deletion:
// reference sequence is the deletion
// reference sequence always includes an extra character...
byte[] temp = reference.byteRange(chr, start_loc, end_loc);
if (temp != null) {
REF = new String(temp);
} else {
log.error("Error: Invalid range");
log.error(" " + line);
return null;
}
alts[0] = new FlexSeq();
break;
case Insertion:
REF = "";
// TODO this is suspect... should sample from distribution of deletions.. maybe ok for now
alts[0] = new FlexSeq(FlexSeq.Type.INS, end_loc - start_loc + 1);
break;
case Tandem_Duplication:
REF = "";
observedgains = Math.max(2, observedgains);
alts[0] = new FlexSeq(FlexSeq.Type.DUP, end_loc - start_loc + 1,
observedgains);
break;
case Inversion:
REF = "";
alts[0] = new FlexSeq(FlexSeq.Type.INV, end_loc - start_loc + 1);
break;
default:
return null;
}
// Upper casing
REF = REF.toUpperCase();
byte[] refs = new byte[REF.length()];
for (int i = 0; i < REF.length(); i++) {
refs[i] = (byte) REF.charAt(i);
}
// Check
if (REF.length() == 1 && alts[0].length() == 1) {
// SNP
return null; // TODO ?
} else if (REF.length() == 0 && alts[0].length() == 0) {
log.error("Skipping invalid record:");
log.error(" " + line);
return null;
}
byte[] phase = {1, 1};
return new Variant(chr, start_loc, refs.length, refs,
alts, phase, false, var_id, "PASS", String.valueOf((char) reference
.byteAt(chr, start_loc - 1)), rand);
}
} |
package com.boxymoron.ha;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements a simple Leader election algorithm (over UDP) similar to Raft. The algorithm is essentially a state machine:<br><br>
* The valid states are: MASTER, SLAVE, UNDEFINED<br><br>
* <li>Each node in the cluster maintains a static list of all (other) cluster member IP addresses/hostnames.<br>
* <li>Each node asynchronously sends a message with its own 'priority' (UDP), which is a an integer in the range 0 - 9999 every {@link ClusterMember#timeout_ms}/2 ms.<br>
* <li>Each node listens to all other node's messages.<br>
* <li>The node with the highest priority, in a majority partition, becomes the MASTER.<br><br>
* For this mechanism to work correctly, each node should have a distinct priority. Currently, only odd numbers of nodes >= 3 are supported ;)<br><br>
*
* The API provides a joinCluster({@link ClusterMember.Listener}) method to register a state changed listener. The listener can then
* be used to control application specific behavior, such as starting/stopping services, replication, etc.
* <br>
* <br>
* Notes/TODO:<br>
* <li>Look into UDP multicast, so non-cluster members can monitor status?
* <li>Look into TCP, so network connection issues can be detected more rapidly (at the expense of TCP/network congestion issues).
* <br>
* <br>
* @author Leonardo Rodriguez-Velez
*
*/
public class ClusterMember {
private static Logger logger = LoggerFactory.getLogger(ClusterMember.class);
private static Properties props = new Properties();
/**
* Sets the UDP datagram's payload width (fixed).
* This sets a max value of 9999 for property 'priority'
*/
private static final int BUFF_SIZE = 4;
/**
* The number of milliseconds to wait for a ping from *any* other member in the cluster.
*/
private static int timeout_ms = 30000;
/**
* The port for UDP. This should be the same on all nodes.
*/
private static int port = 8888;
/**
* A list of other nodes in this cluster.
*/
private static List<Member> members = new ArrayList<Member>();
/**
* The priority of this node, between 0 and 9999 (inclusive)
*/
private static int priority;
private static volatile boolean isInitialized = false;
private static AtomicInteger timeoutCount = new AtomicInteger();
private static AtomicInteger totalTimeoutCount = new AtomicInteger();
/**
// * This is used to block the calling thread(main?) until an initial state is selected.
*/
private static CountDownLatch latch = new CountDownLatch(1);
private static Thread statusThread = null;
/**
* The initial state of each node is always 'UNDEFINED'.
*/
public static volatile State state = State.UNDEFINED;
/**
* Valid states.
*
*/
public static enum State {
MASTER, SLAVE, UNDEFINED
}
public static class Member {
public InetAddress address;
public volatile long lastRxPacket = System.currentTimeMillis();
public volatile int priority = -1;
public Member(InetAddress address, long lastRxPacket) {
this.address = address;
this.lastRxPacket = lastRxPacket;
}
public InetAddress getAddress() {
return this.address;
}
public long getLastRxPacket() {
return lastRxPacket;
}
public void setLastRxPacket(long lastRxPacket) {
this.lastRxPacket = lastRxPacket;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setAddress(InetAddress address) {
this.address = address;
}
public boolean isExpired(long currTS){
return (currTS - lastRxPacket) > timeout_ms;
}
@Override
public String toString() {
return "Member [address=" + address + ", lastRxPacket="
+ lastRxPacket + ", priority=" + priority + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((address == null) ? 0 : address.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Member other = (Member) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
return true;
}
}
/**
* A listener's onStateChange method is invoked whenever the cluster's state changes.
*
*/
public static interface Listener {
public void onStateChange(State state);
}
public static synchronized void joinCluster(final Listener listener) throws FileNotFoundException, IOException, InterruptedException {
if(isInitialized){
throw new IllegalStateException("Cannot join cluster more than once.");
}
final Thread caller = Thread.currentThread();
initProps(new Listener(){
@Override
public void onStateChange(State state) {
if(State.UNDEFINED.equals(state)){
throw new IllegalStateException("Cluster state is UNDEFINED.");
}
latch.countDown();
listener.onStateChange(state);
}
});
startPriorityTXThread(caller, listener);
startPriorityRXThread(caller, listener);
isInitialized = true;
latch.await(timeout_ms * 2, TimeUnit.MILLISECONDS);
statusThread = startStatusThread(listener);
}
private static Thread startStatusThread(final Listener listener) {
Thread statusThread = new Thread(new Runnable(){
@Override
public void run() {
AtomicLong ts = new AtomicLong(System.currentTimeMillis());
while(true){
out:{
ts.set(System.currentTimeMillis());
if(!State.UNDEFINED.equals(state) && members.stream().anyMatch(m -> m.priority == priority)){
state = State.UNDEFINED;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+4);
}else {
if(!State.SLAVE.equals(state) && members.stream().anyMatch(m -> !m.isExpired(ts.get()) && m.priority > priority)){
state = State.SLAVE;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+3);
break out;
}
if(!State.MASTER.equals(state)){
final List<Member> membersCurr = members.stream().filter(m -> !m.isExpired(ts.get())).collect(Collectors.toList());
//we add one since the members doesn't include *this* node
if((membersCurr.size() + 1) >= ((int)((members.size()+1) / 2) + 1) && membersCurr.stream().allMatch(m -> m.priority < priority)){
state = State.MASTER;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+5);
break out;
}
}
if(!State.UNDEFINED.equals(state) && members.stream().filter(m -> !m.isExpired(ts.get())).count() == 0){//I'm running all by myself
state = State.UNDEFINED;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+7);
}else if(State.MASTER.equals(state)){
final List<Member> membersCurr = members.stream().filter(m -> !m.isExpired(ts.get())).collect(Collectors.toList());
if(membersCurr.size() > 0 && membersCurr.stream().anyMatch(m -> m.priority > priority)){
state = State.SLAVE;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+6);
}else if(membersCurr.size() + 1 < ((int)((members.size()+1) / 2) + 1)){//Network Partition?
state = State.UNDEFINED;
listener.onStateChange(state);
logger.info("State changed to: "+state+" "+8);
}
}else{
//logger.info("State: "+state+" ");
}
}
}
try {
if(!Thread.interrupted()){
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}
});
statusThread.setName("statusThrd");
statusThread.setDaemon(true);
statusThread.start();
return statusThread;
}
private static void startPriorityTXThread(final Thread caller, final Listener listener) {
final Thread pingThread = new Thread(new Runnable(){
@Override
public void run() {
DatagramSocket socket = null;
try{
socket = new DatagramSocket();
byte[] buff = String.format("%"+BUFF_SIZE+"d", priority).getBytes("ASCII");//pad with zeroes on left
while(true){
for(Member member : members){
final DatagramPacket packet = new DatagramPacket(buff, 0, buff.length, member.getAddress(), port);
logger.debug("Sending priority: "+priority+" to: "+member);
try{
socket.send(packet);
}catch(IOException ioe2){
ioe2.printStackTrace();
//the show must go on
if(socket.isClosed()){
socket.disconnect();
socket = new DatagramSocket();
}
}
}
try{
Thread.sleep(timeout_ms/2);
}catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception ioe){
ioe.printStackTrace();
listener.onStateChange(State.UNDEFINED);
caller.interrupt();
//TODO maybe interrupt the status thread??
}finally{
if(socket != null){
socket.close();
}
}
}
});
pingThread.setName("priorityTX");
pingThread.setDaemon(true);
pingThread.start();
}
private static Pattern integer = Pattern.compile("\\s*(\\d+)\\s*");
private static void startPriorityRXThread(final Thread caller, final Listener listener) {
final Thread keepAliveThread = new Thread(new Runnable(){
@Override
public void run() {
DatagramSocket sock = null;
try{
sock = new DatagramSocket(port);
sock.setSoTimeout(timeout_ms);
sock.setTrafficClass(4);
byte[] buff = new byte[BUFF_SIZE];
int count = 0;
final DatagramPacket packet = new DatagramPacket(buff, BUFF_SIZE);
while(true){
try{
long ts;
start:{
sock.receive(packet);
ts = System.currentTimeMillis();
final String dataStr = new String(packet.getData(), "ASCII");
for(Member m : members){
if(m.address.equals(packet.getAddress())){
m.setLastRxPacket(ts);
final Matcher matcher = integer.matcher(dataStr);
if(!matcher.find()){
throw new NumberFormatException("invalid priority(int) received: "+dataStr);
}
final int otherPriority = Integer.parseInt(matcher.group(1));
m.setPriority(otherPriority);
logger.info("Received packet: "+dataStr+" from: "+m);
if(m.getPriority() == priority && (!State.UNDEFINED.equals(state) || count == 0)){//handle initial UNDEFINED state
state = State.UNDEFINED;
listener.onStateChange(state);
break start;
}
}
}
if(statusThread != null){
statusThread.interrupt();
}
}
count++;
}catch(NumberFormatException nfe){
nfe.printStackTrace();
state = State.UNDEFINED;
listener.onStateChange(state);
if(statusThread != null){
statusThread.interrupt();
}
}catch(SocketTimeoutException ste){
//ste.printStackTrace();
logger.debug("Packet timed out.");
totalTimeoutCount.incrementAndGet();
timeoutCount.incrementAndGet();
if(statusThread != null){
statusThread.interrupt();
}
}catch(SocketException se2){
se2.printStackTrace();
state = State.UNDEFINED;
listener.onStateChange(state);
caller.interrupt();
if(statusThread != null){
statusThread.interrupt();
}
}catch(IOException ioe){
ioe.printStackTrace();
if(statusThread != null){
statusThread.interrupt();
}
if(sock.isClosed()){
sock.disconnect();
sock = new DatagramSocket(port);
//the show must go on
//throw new RuntimeException("Socket is closed.");
}
}
}
}catch(SocketException se){
se.printStackTrace();
}
}
});
keepAliveThread.setDaemon(true);
keepAliveThread.setName("priorityRX");
keepAliveThread.start();
}
private static synchronized void initProps(Listener listener) throws IOException, FileNotFoundException {
if(listener == null){
throw new IllegalArgumentException("Listener cannot be null");
}
loadProperties(props, "cluster.properties");
if(null == props.getProperty("priority")){
throw new RuntimeException("cluster.properties is missing boolean property 'priority'");
}
if(null == props.getProperty("members")){
throw new RuntimeException("cluster.properties is missing boolean property 'members'");
}
priority = Integer.parseInt(props.getProperty("priority"));
timeout_ms = Integer.parseInt(props.getProperty("timeout_ms", ""+timeout_ms));
if(timeout_ms < 100 || timeout_ms > 99999){
throw new IllegalStateException("Invalid property value: timeout_ms="+timeout_ms);
}
port = Integer.parseInt(props.getProperty("port", ""+port));
final String[] addrs = props.getProperty("members").split(",");
for(String addr : addrs){
final InetAddress currInetAddr = InetAddress.getByName(addr);
members.add(new Member(currInetAddr, -1));
logger.info("Registering remote cluster member: "+currInetAddr);
}
}
public static void loadProperties(Properties properties, String defaultPropsLocation) throws IOException, FileNotFoundException {
final String propertiesFile = System.getProperty(defaultPropsLocation);
if(propertiesFile != null && new File(propertiesFile).canRead()){
final Reader reader = new FileReader(propertiesFile);
try{
properties.load(reader);
}finally{
reader.close();
}
}else if(null == propertiesFile){
final InputStream is = ClusterMember.class.getClassLoader().getResourceAsStream(defaultPropsLocation);
try{
properties.load(is);
}finally{
is.close();
}
}else{
throw new IOException(new StringBuilder("Invalid ").append(defaultPropsLocation).append(" file: ").append(propertiesFile).toString());
}
for(Entry<Object, Object> entry : properties.entrySet()){
logger.info(entry.getKey()+"="+entry.getValue());
}
}
} |
package com.clementscode.mmi.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.imageio.ImageIO;
import javax.jnlp.BasicService;
import javax.jnlp.UnavailableServiceException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import com.clementscode.mmi.MainGui;
import com.clementscode.mmi.res.CategoryItem;
import com.clementscode.mmi.res.ConfigParser;
import com.clementscode.mmi.res.ConfigParser100;
import com.clementscode.mmi.res.LegacyConfigParser;
import com.clementscode.mmi.res.Session;
import com.clementscode.mmi.res.SessionConfig;
import com.clementscode.mmi.util.Shuffler;
import com.clementscode.mmi.util.Utils;
public class Gui implements ActionListener {
private Logger logger = Logger.getLogger(this.getClass().getName());
private static final String BROWSE_SESSION_DATA_FILE = "BROWSE_SESSION_DATA_FILE";
private static final String SESSION_DIRECTORY = "SESSION_DIRECTORY";
private static final String ADVT_URL = "http://clementscode.com/avdt";
private static final Object OUTPUT_CSV_FILE_LOCATION = "OUTPUT_CSV_FILE_LOCATION";
// private ImageIcon imgIconCenter;
private JButton centerButton;
private Queue<CategoryItem> itemQueue = null;
private Session session = null;
private Timer timer;
private Timer betweenTimer;
protected Log log = LogFactory.getLog(this.getClass());
private JFrame frame;
private String frameTitle = Messages.getString("Gui.FrameTitle"); //$NON-NLS-1$
private ActionRecorder attendingAction;
private ActionRecorder independentAction;
private ActionRecorder verbalAction;
private ActionRecorder modelingAction;
private ActionRecorder noAnswerAction;
private ActionRecorder quitAction;
private ActionRecorder timerAction;
private ActionRecorder timerBetweenAction;
private ActionRecorder openAction;
private JPanel mainPanel;
private Mediator mediator;
private File tmpDir;
private ArrayList<JComponent> lstButtons;
private ImageIcon iiSmilingFace, iiSmilingFaceClickToBegin;
private JTextField tfSessionName;
private JTextField tfSessionDataFile;
private JButton clickToStartButton;
private List<String> lstTempDirectories;
private LoggingFrame loggingFrame;
private ActionRecorder showLoggingFrameAction;
private URL codeBaseUrl = null;
private int shownItemCount = 0;
private int totalItemCount;
private boolean bDebounce = false; // DISGUSTING! and Mysterious.
private BufferedImage clearImage;
private Properties preferences;
private ActionRecorder toggleButtonsAction;
private boolean buttonsVisible;
// GLOBALS EVERYWHERE!
private CategoryItem currentItem;
private ConfigParser parser = null;
private ActionRecorder wrongAnswerAction;
private ActionRecorder timerTimeDelayAutoAdvance;
public Gui() {
loggingFrame = new LoggingFrame();
jnlpSetup();
loadPreferences();
String tmpDirStr = "/tmp/mmi";
tmpDir = new File(tmpDirStr);
tmpDir.mkdirs();
mediator = new Mediator(this);
setupActions(mediator);
mainPanel = setupMainPanel();
// TODO: Check to see if there's a logic bug here....
frame = new JFrame(frameTitle);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
setupMenus();
disableButtons();
hideButtons();
lstTempDirectories = new ArrayList<String>();
// Register a shutdown thread
Runtime.getRuntime().addShutdownHook(new Thread() {
// This method is called during shutdown
public void run() {
// Do shutdown work ...
savePreferences();
Utils.deleteTempDirectories(lstTempDirectories);
}
});
}
private void jnlpSetup() {
try {
String[] sn = javax.jnlp.ServiceManager.getServiceNames();
for (String string : sn) {
logger.info("A service name is: " + string);
}
Object obj = javax.jnlp.ServiceManager
.lookup("javax.jnlp.BasicService");
BasicService bs = (BasicService) obj;
codeBaseUrl = bs.getCodeBase();
} catch (UnavailableServiceException e) {
logger.error("Could not look up BasicService.", e);
e.printStackTrace();
} catch (Exception bland) {
logger
.error("Some odd JNLP related problem: bland=" + bland,
bland);
}
}
private void disableButtons() {
for (JComponent jc : lstButtons) {
jc.setEnabled(false);
}
}
public void toggleButtons() {
if (buttonsVisible) {
hideButtons();
} else {
showButtons();
}
}
private void hideButtons() {
for (JComponent jc : lstButtons) {
jc.setVisible(false);
}
buttonsVisible = false;
}
private void showButtons() {
for (JComponent jc : lstButtons) {
jc.setVisible(true);
}
buttonsVisible = true;
}
private void enableButtons() {
for (JComponent jc : lstButtons) {
jc.setEnabled(true);
}
}
private void setupMenus() {
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
// Build the first menu.
JMenu menu = new JMenu(Messages.getString("Gui.File")); //$NON-NLS-1$
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
// a group of JMenuItems
JMenuItem menuItem = new JMenuItem(openAction);
menu.add(menuItem);
// menuItem = new JMenuItem(openHttpAction);
// menu.add(menuItem);
/*
* menuItem = new JMenuItem(crudAction); menu.add(menuItem);
*/
menuItem = new JMenuItem(showLoggingFrameAction);
menu.add(menuItem);
menuItem = new JMenuItem(quitAction);
menu.add(menuItem);
menuBar.add(menu);
JMenu buttonMenu = new JMenu(Messages.getString("Gui.Buttons")); //$NON-NLS-1$
menuItem = new JMenuItem(attendingAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(independentAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(verbalAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(modelingAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(noAnswerAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(wrongAnswerAction);
buttonMenu.add(menuItem);
menuItem = new JMenuItem(toggleButtonsAction);
buttonMenu.add(menuItem);
menuBar.add(buttonMenu);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
}
private JPanel setupMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel southPanel = new JPanel();
lstButtons = new ArrayList<JComponent>();
addButton(southPanel, attendingAction);
addButton(southPanel, independentAction);
addButton(southPanel, verbalAction);
addButton(southPanel, modelingAction);
addButton(southPanel, noAnswerAction);
addButton(southPanel, wrongAnswerAction);
JPanel belowSouthPanel = new JPanel();
belowSouthPanel.setLayout(new GridLayout(0, 1));
tfSessionName = new JTextField(40);
if (null != session) {
tfSessionName.setText(session.getSessionName());
} else {
tfSessionName.setText("Session 1");
}
belowSouthPanel.add(new LabelAndField("Session Name: ", tfSessionName));
tfSessionDataFile = new JTextField(30);
try {
if (null != session) {
tfSessionDataFile.setText(session.getSessionDataFile()
.getCanonicalPath());
} else {
tfSessionDataFile.setText((String) preferences
.get(OUTPUT_CSV_FILE_LOCATION));
// tfSessionDataFile.setText(System.getProperty("user.home")
// + "/avdt.csv");
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JPanel midBelowSouthPanel = new JPanel();
midBelowSouthPanel.add(new LabelAndField("Session Data File: ",
tfSessionDataFile));
JButton browse = new JButton("Browse...");
browse.setActionCommand(BROWSE_SESSION_DATA_FILE);
browse.addActionListener(this);
midBelowSouthPanel.add(browse);
belowSouthPanel.add(midBelowSouthPanel);
clickToStartButton = new JButton("Click to Start");
belowSouthPanel.add(clickToStartButton);
clickToStartButton.setEnabled(false);
clickToStartButton.addActionListener(this);
// response value. This can be 1 of 4 things: independent (child
// answered before the prompt audio), verbal (child answered after the
// prompt but before the answer), modeling (child answered anytime after
// the answer audio) or the child did not answer.
JPanel southContainerPanel = new JPanel();
southContainerPanel.setLayout(new GridLayout(0, 1));
southContainerPanel.add(southPanel);
southContainerPanel.add(belowSouthPanel);
panel.add(southContainerPanel, BorderLayout.SOUTH);
BufferedImage imageData = null;
BufferedImage imageDataClickToBegin = null;
try {
imageData = readImageDataFromClasspath("images/happy-face.jpg");
imageDataClickToBegin = readImageDataFromClasspath("images/happy-face-click-to-begin.jpg");
} catch (Exception e) {
// TODO Auto-generated catch block
logger.warn("Could not find image from classpath...", e);
e.printStackTrace();
}
iiSmilingFace = null;
if (null != imageData) {
iiSmilingFace = new ImageIcon(imageData);
iiSmilingFaceClickToBegin = new ImageIcon(imageDataClickToBegin);
}
if (null == imageData) {
try {
iiSmilingFace = new ImageIcon(new URL(
"http://MattPayne.org/mmi/happy-face.jpg"));
iiSmilingFaceClickToBegin = new ImageIcon(new URL(
"http://MattPayne.org/mmi/happy-face.jpg"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
centerButton = new JButton(iiSmilingFace);
centerButton.addActionListener(this);
panel.add(centerButton, BorderLayout.CENTER);
return panel;
}
public void backToStartScreen() {
frame.setTitle(frameTitle);
centerButton.setIcon(iiSmilingFace);
refreshGui();
disableButtons();
}
private void addButton(JPanel southPanel, ActionRecorder independentAction2) {
JButton responseButton = new JButton(independentAction2);
southPanel.add(responseButton);
lstButtons.add(responseButton);
}
private BufferedImage readImageDataFromClasspath(String fileName)
throws IOException {
// Do it this way and no relative path huha is needed.
InputStream in = this.getClass().getClassLoader().getResourceAsStream(
fileName);
return ImageIO.read(in);
}
public void setupTimer() {
if (null != timer) {
timer.stop(); // fix for issue
}
SessionConfig config = session.getConfig();
// DON'T LET THE NAME CHANGES FOOL YOU!
int answerDelay = config.getTimeDelayAudioPrompt()
+ getPromptLen(currentItem.getAudioPrompt());
timer = new Timer(answerDelay * 1000, timerAction);
timer.setInitialDelay(config.getTimeDelayAudioSD() * 1000);
timer.setRepeats(true);
timer.start();
}
private void setupBetweenTimer() {
if (betweenTimer != null) {
// just in case
betweenTimer.stop();
}
SessionConfig config = session.getConfig();
betweenTimer = new Timer(config.getTimeDelayInterTrial() * 1000,
timerBetweenAction);
betweenTimer.setRepeats(false);
}
public Timer getBetweenTimer() {
return betweenTimer;
}
public void startTimerTimeDelayAutoAdvance(int timeDelayAutoAdvance) {
Timer xxx = new Timer(timeDelayAutoAdvance * 1000,
timerTimeDelayAutoAdvance);
xxx.setRepeats(false);
xxx.start();
log.info(String.format(
"Started timerTimeDelayAutoAdvance timer for %d seconds.",
timeDelayAutoAdvance));
}
int getPromptLen(File sndFile) {
// FIXME I'm a horrible hack
if (sndFile == null) {
return 0;
}
AudioInputStream audioInputStream;
try {
audioInputStream = AudioSystem.getAudioInputStream(sndFile);
AudioFormat format = audioInputStream.getFormat();
long frames = audioInputStream.getFrameLength();
audioInputStream.close();
return (int) (frames / format.getFrameRate());
} catch (Exception e) {
log.error("Horrible hack blew up, karma", e);
return 0;
}
}
public void setupCenterButton() {
// // TODO: Call this when we get a new session file read in....
// CategoryItem first = itemQueue.remove();
// log.info(String.format("About to display image: %s from item=%d",
// first.getImgFile(), first.getItemNumber()));
// imgIconCenter = new ImageIcon(first.getImg());
// // centerButton = new JButton(imgIconCenter);
// centerButton.setIcon(imgIconCenter);
Dimension max = session.getMaxDimensions();
centerButton.setPreferredSize(max);
int width = (int) max.getWidth();
int height = (int) max.getHeight();
clearImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = clearImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.dispose();
}
private void setupActions(MediatorListener mediator) {
// TODO: Fix bug that control A does not toggle the checkbox
// TODO: Make attending not a checkbox.
// TODO: Make hot keys come from a properties file. Hopefully ask JNLP
// Utils where this program was loaded from and do a http get to there
// for the properties file.
Properties hotKeysProperties = null;
String fileName = "hotkeys.ini";
try {
hotKeysProperties = readPropertiesFromClassPath(fileName);
} catch (Exception e) {
hotKeysProperties = new Properties();
hotKeysProperties.put("Hotkey.Gui.Attending","A");
hotKeysProperties.put("Hotkey.Gui.Independent","1");
hotKeysProperties.put("Hotkey.Gui.Verbal","2");
hotKeysProperties.put("Hotkey.Gui.Modeling","3");
hotKeysProperties.put("Hotkey.Gui.NoAnswer","4");
hotKeysProperties.put("Hotkey.Gui.WrongAnswer","5");
log.warn(String.format(
"Problem reading %s. Defaulting hotkeysPropteries=%s",
fileName, hotKeysProperties), e);
}
String hk = (String) hotKeysProperties.get("Hotkey.Gui.Attending");
attendingAction = new ActionRecorder(Messages
.getString("Gui.Attending"), null, //$NON-NLS-1$
Messages.getString("Gui.AttendingDescription"), new Integer( //$NON-NLS-1$
KeyEvent.VK_F1), KeyStroke.getKeyStroke(hk),
Mediator.ATTENDING, mediator);
hk = (String) hotKeysProperties.get("Hotkey.Gui.Independent");
independentAction = new ActionRecorder(Messages
.getString("Gui.Independent"), null, //$NON-NLS-1$
Messages.getString("Gui.IndependentDescription"), new Integer( //$NON-NLS-1$
KeyEvent.VK_F2), KeyStroke.getKeyStroke(hk),
Mediator.INDEPENDENT, mediator);
hk = (String) hotKeysProperties.get("Hotkey.Gui.Verbal");
verbalAction = new ActionRecorder(
Messages.getString("Gui.Verbal"), null, //$NON-NLS-1$
Messages.getString("Gui.VerbalDescription"), //$NON-NLS-1$
new Integer(KeyEvent.VK_F3), KeyStroke.getKeyStroke(hk),
Mediator.VERBAL, mediator);
hk = (String) hotKeysProperties.get("Hotkey.Gui.Modeling");
modelingAction = new ActionRecorder(
Messages.getString("Gui.Modeling"), null, //$NON-NLS-1$
Messages.getString("Gui.ModelingDescriptin"), new Integer( //$NON-NLS-1$
KeyEvent.VK_F4), KeyStroke.getKeyStroke(hk),
Mediator.MODELING, mediator);
hk = (String) hotKeysProperties.get("Hotkey.Gui.NoAnswer");
noAnswerAction = new ActionRecorder(
Messages.getString("Gui.NoAnswer"), null, //$NON-NLS-1$
Messages.getString("Gui.NoAnswerDescription"), new Integer(KeyEvent.VK_F5), //$NON-NLS-1$
KeyStroke.getKeyStroke(hk), Mediator.NO_ANSWER, mediator);
hk = (String) hotKeysProperties.get("Hotkey.Gui.WrongAnswer");
wrongAnswerAction = new ActionRecorder(
Messages.getString("Gui.WrongAnswer"), null, //$NON-NLS-1$
Messages.getString("Gui.WrongAnswerDescription"), new Integer(KeyEvent.VK_F5), //$NON-NLS-1$
KeyStroke.getKeyStroke(hk), Mediator.WRONG_ANSWER, mediator);
toggleButtonsAction = new ActionRecorder(
Messages.getString("Gui.ToggleButtons"), null, //$NON-NLS-1$
Messages.getString("Gui.ToggleButtons.Description"), new Integer(KeyEvent.VK_L), //$NON-NLS-1$
KeyStroke.getKeyStroke("B"), Mediator.TOGGLE_BUTTONS, mediator);
quitAction = new ActionRecorder(
Messages.getString("Gui.Quit"), null, //$NON-NLS-1$
Messages.getString("Gui.QuitDescriptino"), new Integer(KeyEvent.VK_L), //$NON-NLS-1$
KeyStroke.getKeyStroke("control Q"), Mediator.QUIT, mediator);
timerAction = new ActionRecorder(
Messages.getString("Gui.TimerSwing"), null, //$NON-NLS-1$
"Quit (Exit) the program", new Integer(KeyEvent.VK_L), //$NON-NLS-1$
KeyStroke.getKeyStroke("control F2"), Mediator.TIMER, mediator);
timerBetweenAction = new ActionRecorder(Messages
.getString("Gui.TimerBetweenSwing"), null, //$NON-NLS-1$
"Quit (Exit) the program", new Integer(KeyEvent.VK_L), //$NON-NLS-1$
KeyStroke.getKeyStroke("control F2"), Mediator.BETWEEN_TIMER,
mediator);
timerTimeDelayAutoAdvance = new ActionRecorder(
Messages.getString("Gui.TimeDelayAutoAdvance"), null, //$NON-NLS-1$
"xxxxxxxxxxxxxx", new Integer(KeyEvent.VK_L), //$NON-NLS-1$
KeyStroke.getKeyStroke("control F2"),
Mediator.CHANGE_DELAY_TIMER, mediator);
openAction = new ActionRecorder(Messages.getString("Gui.Open"), null, //$NON-NLS-1$
Messages.getString("Gui.OpenDescription"), //$NON-NLS-1$
new Integer(KeyEvent.VK_L),
KeyStroke.getKeyStroke("control O"), Mediator.OPEN, mediator);
showLoggingFrameAction = new ActionRecorder(
Messages.getString("Gui.Open.ShowLoggingFrame"), null, //$NON-NLS-1$
Messages.getString("Gui.ShowLoggingFrameDescription"), //$NON-NLS-1$
new Integer(KeyEvent.VK_L),
KeyStroke.getKeyStroke("control D"),
Mediator.SHOW_LOGGING_FRAME, mediator);
}
public void run(Session session) {
}
public Queue<CategoryItem> getItemQueue() {
return itemQueue;
}
public void clearImage() {
centerButton.setIcon(new ImageIcon(clearImage));
refreshGui();
}
public void switchImage(ImageIcon ii) {
setFrameTitle();
centerButton.setIcon(ii);
}
/*
* They use bmp images which don't display with the program right now. I
* looked at the code and noticed that you don't use the 'img' field of the
* CategoryItem. You use the image file to get a path to the image and read
* it in again using an icon. I suspect that it will work better if you use
* the image that ImageIO already read into memory.
*/
public void switchItem(CategoryItem item) {
currentItem = item;
ImageIcon ii = new ImageIcon(item.getImg());
switchImage(ii);
setupTimer();
}
private void setFrameTitle() {
frame.setTitle(frameTitle
+ String.format("%d of %d", shownItemCount++, totalItemCount));
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public void stopTimer() {
if (timer != null) {
timer.stop();
}
}
public void setVisble(boolean b) {
frame.setVisible(b);
}
public void openSession() {
bDebounce = false;
File file;
// TODO: Remove hard coded directory.
// TODO: Get application to remember the last place we opened this...
String sessionDir = (String) preferences.get(SESSION_DIRECTORY);
sessionDir = null == sessionDir ? System.getProperty("user.home")
: sessionDir;
JFileChooser chooser = new JFileChooser(new File(sessionDir));
int returnVal = chooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
readSessionFile(file);
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, String.format(
"Problem reading %s exception was %s", file, e));
e.printStackTrace();
}
preferences.put(SESSION_DIRECTORY, getDirectory(file));
savePreferences();
}
displayClickToBegin();
}
private Object getDirectory(File file) {
String dirStr = file.getAbsolutePath();
int firstSlash = dirStr.lastIndexOf(File.separator);
dirStr = dirStr.substring(0, firstSlash);
return dirStr;
}
private void savePreferences() {
preferences.put(OUTPUT_CSV_FILE_LOCATION, tfSessionDataFile.getText());
File preferencesFile = getPreferencesFile();
PrintWriter out;
try {
out = new PrintWriter(preferencesFile);
preferences.store(out, "Config information for " + ADVT_URL
+ " written on " + new java.util.Date());
out.close();
} catch (Exception e) {
log.error("Problem saving preferences to " + preferencesFile, e);
e.printStackTrace();
}
}
private void loadPreferences() {
File preferencesFile = getPreferencesFile();
preferences = new Properties();
FileReader in;
try {
in = new FileReader(preferencesFile);
preferences.load(in);
in.close();
} catch (Exception e) {
log.error("Problem loading preferences from " + preferencesFile, e);
e.printStackTrace();
}
}
private File getPreferencesFile() {
String home = System.getProperty("user.home");
String advtSettingsDirectory = home + "/AVDT_Settings";
File preferencesDir = new File(advtSettingsDirectory);
if (!preferencesDir.exists()) {
createPreferencesDirectory(advtSettingsDirectory);
}
File prefsFile = new File(advtSettingsDirectory + "/advt_prefs.ini");
return prefsFile;
}
private void createPreferencesDirectory(String advtSettingsDirectory) {
File dir = new File(advtSettingsDirectory);
dir.mkdirs();
try {
PrintWriter out = new PrintWriter(advtSettingsDirectory
+ "/README.txt");
out
.println("This directory contains settings for the program AVDT.");
out.println("For more information, please visit " + ADVT_URL);
out.println("This directory was initially created at "
+ new java.util.Date());
out.println("Please do not delete these files or this directory.");
out.close();
} catch (Exception e) {
log.error("Problem making readme in directory: "
+ advtSettingsDirectory, e);
e.printStackTrace();
}
}
public void useNewSession() {
if (bDebounce) {
return;
}
bDebounce = true;
shownItemCount = 0;// fix for issue
centerButton.removeActionListener(this);
clickToStartButton.setEnabled(false);
clickToStartButton.setForeground(Color.white);
// centerButton.setText("");
if (null != session) {
CategoryItem[] copy = Arrays.copyOf(session.getItems(), session
.getItems().length);
SessionConfig config = session.getConfig();
for (int i = 0; i < config.getShuffleCount(); ++i) {
Shuffler.shuffle(copy);
}
itemQueue = new ConcurrentLinkedQueue<CategoryItem>();
for (CategoryItem item : copy) {
// TODO: Is there a collections add all I could use here?
itemQueue.add(item);
}
itemQueue.add(copy[copy.length - 1]); // DISGUSTING!
totalItemCount = itemQueue.size() - 1; // DISGUSTING!
mediator.setSession(session);
setupCenterButton();
setFrameTitle();
refreshGui();
// setupTimer is now done on a per-item basis
// setupTimer();
setupBetweenTimer();
enableButtons();
mediator.execute(Mediator.BETWEEN_TIMER);
}
}
private void readSessionFile(File file) throws Exception {
readSessionFile(file, null);
}
private void readSessionFile(File file, String newItemBase)
throws Exception {
if (this.parser == null) {
// SHOULDN'T ALL OF THIS BE HAPPENING DURING STARTUP? No, the open
// menu allows reading new sessions.
Properties props = readPropertiesFromClassPath(MainGui.propFile);
String[] sndExts = props.getProperty(MainGui.sndKey).split(",");
LegacyConfigParser legacy = new LegacyConfigParser(sndExts);
this.parser = new ConfigParser(legacy);
this.parser.registerVersionParser(new ConfigParser100());
}
SessionConfig config = this.parser.parse(file);
if (null != newItemBase) {
config.setItemBase(newItemBase);
// prompts are relative to base in new configs
// config.setPrompt(newItemBase + "/prompt.wav");
}
session = new Session(config);
}
private Properties readPropertiesFromClassPath(String fileName)
throws IOException {
Properties props = new Properties();
// Do it this way and no relative path huha is needed.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream(fileName);
props.load(new InputStreamReader(in));
return props;
}
void refreshGui() {
mainPanel.revalidate();
frame.pack();
}
private void displayClickToBegin() {
centerButton.setEnabled(true);
centerButton.addActionListener(this); // fix for issue
centerButton.setIcon(iiSmilingFaceClickToBegin);
// centerButton.setText("Click to Begin");
centerButton.invalidate();
clickToStartButton.setEnabled(true);
clickToStartButton.setForeground(Color.red);
refreshGui();
}
public void actionPerformed(ActionEvent e) {
if ((clickToStartButton == e.getSource())
|| (centerButton == e.getSource())) {
useNewSession();
} else if (BROWSE_SESSION_DATA_FILE.equals(e.getActionCommand())) {
chooseSessionDataFile();
}
}
private void chooseSessionDataFile() {
JFileChooser chooser = new JFileChooser(new File(tfSessionDataFile
.getText()));
int returnVal = chooser.showSaveDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
tfSessionDataFile.setText(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void populateSessionName() {
session.setSessionName(tfSessionName.getText());
}
public void populateSessionDataFile() {
String fileName = System.getProperty("user.home") + "/brian.csv";
String str = tfSessionDataFile.getText();
str = "".equals(str) ? fileName : str;
session.setSessionDataFile(new File(str));
}
public void showLoggingFrame() {
loggingFrame.setVisible(true);
}
} |
package com.draga.manager.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.draga.Constants;
import com.draga.manager.AssMan;
import com.draga.manager.ScreenManager;
import com.draga.manager.level.LevelManager;
import com.draga.manager.level.serialisableEntities.SerialisableLevel;
import com.draga.manager.level.serialisableEntities.SerialisablePlanet;
import com.google.common.base.Joiner;
public class LoadingScreen implements Screen
{
private static final String LOGGING_TAG = LoadingScreen.class.getSimpleName();
private final Stage stage;
private final FreeTypeFontGenerator freeTypeFontGenerator;
private final BitmapFont pDark24Font;
private final long startTime;
private ProgressBar progressBar;
private SerialisableLevel serialisableLevel;
public LoadingScreen(String levelName)
{
startTime = System.nanoTime();
serialisableLevel = LevelManager.getSerialisedLevelFromName(levelName);
AssMan.DisposeAllAndClear();
AssMan.getAssetManager().load(
serialisableLevel.serialisedBackground.getTexturePath(), Texture.class);
AssMan.getAssetManager().load(
serialisableLevel.serialisedShip.getShipTexturePath(), Texture.class);
AssMan.getAssetManager().load(
serialisableLevel.serialisedShip.getThrusterTextureAtlasPath(), TextureAtlas.class);
for (SerialisablePlanet serialisablePlanet : serialisableLevel.serialisedPlanets)
{
AssMan.getAssetManager().load(serialisablePlanet.getTexturePath(), Texture.class);
}
AssMan.getAssetManager().load("explosion/explosion.atlas", TextureAtlas.class);
AssMan.getAssetManager().load("star/starGold64.png", Texture.class);
AssMan.getAssetManager().load("star/starGray64.png", Texture.class);
freeTypeFontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("font/pdark.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter =
new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 64;
pDark24Font = freeTypeFontGenerator.generateFont(parameter);
stage = new Stage();
Actor headerLabel = getHeaderLabel();
float progressBarHeight = stage.getHeight() / 20f;
progressBar = getProgressBar((int) progressBarHeight);
Table table = new Table();
stage.addActor(table);
table.setFillParent(true);
table.add(headerLabel);
table.row();
table
.add(progressBar)
.height(progressBarHeight)
.width(stage.getWidth() * 0.75f);
stage.setDebugAll(Constants.IS_DEBUGGING);
}
@Override
public void show()
{
}
@Override
public void render(float deltaTime)
{
if (AssMan.getAssetManager().update())
{
if (Constants.IS_DEBUGGING)
{
Gdx.app.debug(
LOGGING_TAG, Joiner.on(", ").join(AssMan.getAssetManager().getAssetNames()));
}
GameScreen gameScreen = LevelManager.getLevelGameScreen(
serialisableLevel, new SpriteBatch());
long elapsedNanoTime = System.nanoTime() - startTime;
Gdx.app.debug(LOGGING_TAG, "Loading time: " + elapsedNanoTime * Constants.NANO + "s");
ScreenManager.setActiveScreen(gameScreen);
}
updateProgressBar();
stage.act(deltaTime);
stage.draw();
}
private void updateProgressBar()
{
progressBar.setRange(
0,
AssMan.getAssetManager().getQueuedAssets() + AssMan.getAssetManager()
.getLoadedAssets());
progressBar.setValue(AssMan.getAssetManager().getLoadedAssets());
}
@Override
public void dispose()
{
freeTypeFontGenerator.dispose();
stage.dispose();
}
@Override
public void pause()
{
}
@Override
public void resize(int width, int height)
{
stage.getViewport().update(width, height);
}
@Override
public void resume()
{
}
@Override
public void hide()
{
}
public Label getHeaderLabel()
{
Label.LabelStyle labelStyle = new Label.LabelStyle();
labelStyle.font = pDark24Font;
Label headerLabel = new Label("Loading", labelStyle);
return headerLabel;
}
private ProgressBar getProgressBar(int height)
{
Skin skin = new Skin();
Pixmap pixmap = new Pixmap(
1, height, Pixmap.Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
skin.add("white", new Texture(pixmap));
ProgressBar.ProgressBarStyle progressBarStyle = new ProgressBar.ProgressBarStyle(
skin.newDrawable("white", Color.DARK_GRAY), null);
progressBarStyle.knobBefore = skin.newDrawable("white", Color.WHITE);
ProgressBar progressBar = new ProgressBar(
0,
AssMan.getAssetManager().getQueuedAssets() + AssMan.getAssetManager().getLoadedAssets(),
1,
false,
progressBarStyle);
return progressBar;
}
} |
package com.cube.storm;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.cube.storm.content.lib.Environment;
import com.cube.storm.content.lib.parser.BundleBuilder;
import com.cube.storm.content.lib.factory.FileFactory;
import com.cube.storm.content.lib.listener.UpdateListener;
import com.cube.storm.content.lib.resolver.CacheResolver;
import com.cube.storm.util.lib.manager.FileManager;
import com.cube.storm.util.lib.resolver.AssetsResolver;
import com.cube.storm.util.lib.resolver.FileResolver;
import com.cube.storm.util.lib.resolver.Resolver;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Getter;
/**
* This is the entry point class of the library. To enable the use of the library, you must instantiate
* a new {@link com.cube.storm.ContentSettings.Builder} object in your {@link android.app.Application} singleton class.
*
* This class should not be directly instantiated.
*
* @author Callum Taylor
* @project StormContent
*/
public class ContentSettings
{
/**
* The singleton instance of the settings
*/
private static ContentSettings instance;
public static ContentSettings getInstance()
{
if (instance == null)
{
throw new IllegalAccessError("You must build the Content settings object first using ContentSettings$Builder");
}
return instance;
}
/**
* Default private constructor
*/
private ContentSettings(){}
/**
* Default {@link com.cube.storm.util.lib.manager.FileManager} to use throughout the module
*/
@Getter private FileManager fileManager;
/**
* The path to the storage folder on disk
*/
@Getter private String storagePath;
/**
* Storm app ID in the format {@code SYSTEM-SOCIETYID-APPID}
*/
@Getter private String appId;
@Getter private String contentBaseUrl;
/**
* Content URL version of the API
*
* Example version {@code v1.0}. Version must not end in a slash
*/
@Getter private String contentVersion;
/**
* Content environment
*
* Defaults to {@link com.cube.storm.content.lib.Environment#LIVE}
*/
@Getter private Environment contentEnvironment;
/**
* Listener instance for updates downloaded
*/
@Getter private UpdateListener updateListener;
/**
* The gson builder class used to build classes such as manifest
*/
@Getter private BundleBuilder bundleBuilder;
/**
* Factory class responsible for loading a file from disk based on its Uri
*/
@Getter private FileFactory fileFactory;
/**
* Uri resolver used to load a file based on it's protocol.
*/
@Getter private Map<String, Resolver> uriResolvers = new LinkedHashMap<String, Resolver>(2);
/**
* The builder class for {@link com.cube.storm.ContentSettings}. Use this to create a new {@link com.cube.storm.ContentSettings} instance
* with the customised properties specific for your project.
* <p/>
* The following methods are required to be set before you can download any content
* <ul>
* <li>{@link #appId(String)} or {@link #appId(String, int, int)}</li>
* <li>{@link #contentBaseUrl(String)}</li>
* <li>{@link #contentVersion}</li>
* </ul>
* <p/>
* Call {@link #build()} to build the settings object.
*/
public static class Builder
{
/**
* The temporary instance of the {@link com.cube.storm.ContentSettings} object.
*/
private ContentSettings construct;
/**
* The application context
*/
private Context context;
/**
* Default constructor
*/
public Builder(Context context)
{
this.construct = new ContentSettings();
this.context = context.getApplicationContext();
fileFactory(new FileFactory(){});
bundleBuilder(new BundleBuilder(){});
registerUriResolver("file", new FileResolver());
registerUriResolver("assets", new AssetsResolver(this.context));
registerUriResolver("cache", new CacheResolver(this.context));
storagePath(this.context.getFilesDir().getAbsolutePath());
fileManager(FileManager.getInstance());
contentEnvironment(Environment.LIVE);
}
/**
* Sets the new listener for updates
*
* @param listener The new listener
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder updateListener(@Nullable UpdateListener listener)
{
construct.updateListener = listener;
return this;
}
/**
* Set the app id to use when dealing with Storm CMS
*
* @param id The ID of the app in the format {@code SYSTEM-SOCIETYID-APPID}
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder appId(@NonNull String id)
{
construct.appId = id;
return this;
}
/**
* Set the app id to use when dealing with Storm CMS
*
* @param system The system name
* @param society The society ID
* @param app The app number
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder appId(@NonNull String system, int society, int app)
{
construct.appId = system + "_" + society + "_" + app;
return this;
}
public Builder contentBaseUrl(@NonNull String baseUrl)
{
construct.contentBaseUrl = baseUrl;
return this;
}
/**
* Set the content URL to download bundles from
*
* @param version The version of the endpoint to download content from. Example version {@code v1.0}. Version must not end in a slash
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder contentVersion(@NonNull String version)
{
construct.contentVersion = version;
return this;
}
/**
* Set the content URL to download bundles from
*
* @param environment The environment of the endpoint.
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder contentEnvironment(@NonNull Environment environment)
{
construct.contentEnvironment = environment;
return this;
}
public Builder contentUrl(@NonNull String baseUrl, @NonNull String version, @NonNull Environment environment)
{
construct.contentBaseUrl = baseUrl;
construct.contentVersion = version;
construct.contentEnvironment = environment;
return this;
}
/**
* Set the path to use as the storage dir
*
* @param path The file dir path to the storage folder
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder storagePath(@NonNull String path)
{
construct.storagePath = path;
return this;
}
/**
* Sets the default {@link com.cube.storm.content.lib.parser.BundleBuilder} for the module
*
* @param bundleBuilder The new {@link com.cube.storm.content.lib.parser.BundleBuilder}
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder bundleBuilder(BundleBuilder bundleBuilder)
{
construct.bundleBuilder = bundleBuilder;
return this;
}
/**
* Set the default file manager
*
* @param manager The new file manager
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder fileManager(@NonNull FileManager manager)
{
construct.fileManager = manager;
return this;
}
/**
* Registers a uri resolver
*
* @param protocol The string protocol to register
* @param resolver The resolver to use for the registered protocol
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(String protocol, Resolver resolver)
{
construct.uriResolvers.put(protocol, resolver);
return this;
}
/**
* Registers a uri resolvers
*
* @param resolvers The map of resolvers to register
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(Map<String, Resolver> resolvers)
{
construct.uriResolvers.putAll(resolvers);
return this;
}
/**
* Sets the default {@link com.cube.storm.content.lib.factory.FileFactory} for the module
*
* @param fileFactory The new {@link com.cube.storm.content.lib.factory.FileFactory}
*
* @return The {@link com.cube.storm.ContentSettings.Builder} instance for chaining
*/
public Builder fileFactory(FileFactory fileFactory)
{
construct.fileFactory = fileFactory;
return this;
}
/**
* Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings
* instance.
*
* @return The newly set {@link com.cube.storm.ContentSettings} instance
*/
public ContentSettings build()
{
return (ContentSettings.instance = construct);
}
}
} |
package com.smeanox.games.ld34.world;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.smeanox.games.ld34.Consts;
import com.smeanox.games.ld34.Textures;
/**
* Comment
*/
public class CoinPlant extends Plant {
private ParticleSystem destroySystem;
private static Animation animation;
private float animationTime;
private int moneyLog;
private int colorNum;
private Color color;
private boolean didGiveMoney;
public static final Color[] colors = {new Color(0.5f, 0.3f, 0.1f, 1), new Color(0.8f, 0.4f, 0.1f, 1), new Color(0.6f, 0.7f, 0.8f, 1), new Color(0.9f, 0.9f, 0, 1), new Color(0.4f, 0, 0.9f, 1)};
public CoinPlant(World world, float x0, float y0, int moneyLog, int colorNum) {
super(world, x0, y0, Consts.COIN_START_LIVES);
this.moneyLog = moneyLog;
this.colorNum = colorNum;
this.color = colors[colorNum];
lives = Consts.COIN_START_LIVES;
didGiveMoney = false;
initAnimation();
initParticles();
}
private void initAnimation(){
if(animation != null){
return;
}
animation = Hero.createAnimation(Textures.get().coin, 0, 1, 0, 6, Consts.COIN_TEX_WIDTH, Consts.COIN_TEX_HEIGHT, 0.15f, Animation.PlayMode.LOOP);
animationTime = 0;
}
private void initParticles(){
GameState.get().addMoney((1 << moneyLog));
destroySystem = new ParticleSystem(world, "coinDestroy", new CoinParticleFactory(), Consts.LAYER_PLANT, Textures.get().particle, color, 0.5f, 5f, 0.2f,
0.2f / (colorNum + 1) * 1f / 128,
0.2f / (colorNum + 1) * 1f / 256,
getX(), getY() + getHeight() / 2, 2, 2, 0,0 ,Consts.COIN_VELOCITY, Consts.COIN_VELOCITY);//(1 + colorNum*colorNum) * Consts.COIN_VELOCITY, (1 + colorNum*colorNum)* Consts.COIN_VELOCITY);
}
@Override
public void grow(float delta) {
}
@Override
public float getWidth() {
return Consts.COIN_TEX_WIDTH * Consts.COIN_TEX_ZOOM;
}
@Override
public float getHeight() {
return Consts.COIN_TEX_HEIGHT * Consts.COIN_TEX_ZOOM;
}
@Override
public Rectangle getCollisionBox() {
return new Rectangle(getX() - Consts.COIN_TEX_WIDTH * Consts.COIN_TEX_ZOOM / 2, getY(), Consts.COIN_TEX_WIDTH * Consts.COIN_TEX_ZOOM, Consts.COIN_TEX_HEIGHT * Consts.COIN_TEX_ZOOM);
}
@Override
public boolean onCollision(Collidable collidable, float delta) {
if(collidable instanceof Hero){
didGiveMoney = true;
destroy();
}
return true;
}
@Override
public void render(float delta, SpriteBatch spriteBatch) {
animationTime += delta;
spriteBatch.setColor(color);
spriteBatch.draw(animation.getKeyFrame(animationTime), getX() - Consts.COIN_TEX_WIDTH * Consts.COIN_TEX_ZOOM / 2, getY(),
Consts.COIN_TEX_WIDTH * Consts.COIN_TEX_ZOOM, Consts.COIN_TEX_HEIGHT * Consts.COIN_TEX_ZOOM);
spriteBatch.setColor(Color.WHITE);
}
@Override
public void destroy() {
if(isDestroyed()){
return;
}
super.destroy();
if(didGiveMoney) {
spawnDestroySystem();
}
}
private void spawnDestroySystem(){
destroySystem.setGenerating(true);
destroySystem.setAutoDisable(0.2f);
}
public class CoinParticleFactory implements ParticleSystem.ParticleFactory {
@Override
public ParticleSystem.Particle createParticle(ParticleSystem ps, float time, float x, float y, float vx, float vy) {
return new CoinParticle(world, ps, time, x, y, vx, vy, moneyLog);
}
}
} |
package com.devquixote.redisqs;
import static com.devquixote.redisqs.SqsReferenceOps.queueUrl;
import static com.devquixote.redisqs.SqsReferenceOps.setRegionEndpoint;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.ResponseMetadata;
import com.amazonaws.regions.Region;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.AddPermissionRequest;
import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequest;
import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry;
import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchResult;
import com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.CreateQueueResult;
import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest;
import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry;
import com.amazonaws.services.sqs.model.DeleteMessageBatchResult;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.GetQueueUrlResult;
import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesRequest;
import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesResult;
import com.amazonaws.services.sqs.model.ListQueuesRequest;
import com.amazonaws.services.sqs.model.ListQueuesResult;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.PurgeQueueRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import com.amazonaws.services.sqs.model.RemovePermissionRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
import com.amazonaws.services.sqs.model.SendMessageBatchResult;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageResult;
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
import redis.clients.jedis.Jedis;
/**
* AmazonSQS implementation backed by Redis.
*
* @author lance.woodson
*
*/
public class RedisQS implements AmazonSQS {
private Jedis jedis;
/**
* Create a new RedisQS using a Jedis client.
*
* @param jedis the ready-to-use Jedis client
*/
public RedisQS(Jedis jedis) {
this.jedis = jedis;
}
/**
* Create a new RedisQS instance using explicit connection
* details
*
* @param host the host machine where the redis server is found
* @param port the port on which redis is listening
* @param db the database number
*/
public RedisQS(String host, Integer port, Integer db) {
jedis = new Jedis(host, port);
jedis.select(db);
}
/**
* @return the Jedis instance communicating to the db.
*/
public Jedis getJedis() {
return jedis;
}
/**
* Does nothing
*/
public void setEndpoint(String endpoint) throws IllegalArgumentException {}
/**
* Does nothing
*/
public void setRegion(Region region) throws IllegalArgumentException {
setRegionEndpoint(region.getName());
}
public void setQueueAttributes(SetQueueAttributesRequest setQueueAttributesRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(
ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void changeMessageVisibility(ChangeMessageVisibilityRequest changeMessageVisibilityRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public GetQueueUrlResult getQueueUrl(GetQueueUrlRequest getQueueUrlRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void removePermission(RemovePermissionRequest removePermissionRequest)
throws AmazonServiceException, AmazonClientException {}
public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest getQueueAttributesRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public SendMessageBatchResult sendMessageBatch(SendMessageBatchRequest sendMessageBatchRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void purgeQueue(PurgeQueueRequest purgeQueueRequest) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public ListDeadLetterSourceQueuesResult listDeadLetterSourceQueues(
ListDeadLetterSourceQueuesRequest listDeadLetterSourceQueuesRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void deleteQueue(DeleteQueueRequest deleteQueueRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public SendMessageResult sendMessage(SendMessageRequest request)
throws AmazonServiceException, AmazonClientException {
jedis.rpush(keyFor(request.getQueueUrl()), request.getMessageBody());
SendMessageResult result = new SendMessageResult();
// TODO properly populate result
return result;
}
public ReceiveMessageResult receiveMessage(ReceiveMessageRequest request)
throws AmazonServiceException, AmazonClientException {
String body = jedis.lpop(keyFor(request.getQueueUrl()));
Message message = new Message();
message.setBody(body);
ReceiveMessageResult result = new ReceiveMessageResult();
result.setMessages(Arrays.asList(message));
return result;
}
public ListQueuesResult listQueues(ListQueuesRequest listQueuesRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public DeleteMessageBatchResult deleteMessageBatch(DeleteMessageBatchRequest deleteMessageBatchRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
/**
* Create a representative URL for the queue name in the request. Do not
* need to create a list as redis does that automatically when we push onto
* it.
*/
public CreateQueueResult createQueue(CreateQueueRequest createQueueRequest)
throws AmazonServiceException, AmazonClientException {
String queueUrl = queueUrl(createQueueRequest.getQueueName());
CreateQueueResult result = new CreateQueueResult();
result.setQueueUrl(queueUrl);
return result;
}
public void addPermission(AddPermissionRequest addPermissionRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public void deleteMessage(DeleteMessageRequest deleteMessageRequest)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public ListQueuesResult listQueues() throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void setQueueAttributes(String queueUrl, Map<String, String> attributes)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(String queueUrl,
List<ChangeMessageVisibilityBatchRequestEntry> entries)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void changeMessageVisibility(String queueUrl, String receiptHandle, Integer visibilityTimeout)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public GetQueueUrlResult getQueueUrl(String queueName) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void removePermission(String queueUrl, String label) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public GetQueueAttributesResult getQueueAttributes(String queueUrl, List<String> attributeNames)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public SendMessageBatchResult sendMessageBatch(String queueUrl, List<SendMessageBatchRequestEntry> entries)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void deleteQueue(String queueUrl) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public SendMessageResult sendMessage(String queueUrl, String messageBody)
throws AmazonServiceException, AmazonClientException {
SendMessageRequest request = new SendMessageRequest(queueUrl, messageBody);
return sendMessage(request);
}
public ReceiveMessageResult receiveMessage(String queueUrl) throws AmazonServiceException, AmazonClientException {
ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl);
return receiveMessage(request);
}
public ListQueuesResult listQueues(String queueNamePrefix) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public CreateQueueResult createQueue(String queueName) throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
return null;
}
public void addPermission(String queueUrl, String label, List<String> aWSAccountIds, List<String> actions)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public void deleteMessage(String queueUrl, String receiptHandle)
throws AmazonServiceException, AmazonClientException {
// TODO Auto-generated method stub
}
public void shutdown() {
// TODO Auto-generated method stub
}
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) {
// TODO Auto-generated method stub
return null;
}
private String keyFor(String url) {
return "sqs:" + url;
}
} |
package com.elevenpaths.latch;
import java.util.*;
/**
* This class model the API for Applications. Every action here is related to an Application. This
* means that a LatchApp object should use a pair ApplicationId/Secret obtained from the Application page of the Latch Website.
*/
public class LatchApp extends LatchAuth {
/**
* Create an instance of the class with the Application ID and secret obtained from Eleven Paths
* @param appId
* @param secretKey
*/
public LatchApp(String appId, String secretKey){
this.appId = appId;
this.secretKey = secretKey;
}
public LatchResponse pairWithId(String id) {
return HTTP_GET_proxy(new StringBuilder(API_PAIR_WITH_ID_URL).append("/").append(id).toString());
}
public LatchResponse pair(String token) {
return HTTP_GET_proxy(new StringBuilder(API_PAIR_URL).append("/").append(token).toString());
}
/**
* Return application status for a given accountId
* @param accountId The accountId which status is going to be retrieved
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId) {
return status(accountId, null, null, false, false);
}
/**
* Return application status for a given accountId
* @param accountId The accountId which status is going to be retrieved
* @param silent True for not sending lock/unlock push notifications to the mobile devices, false otherwise.
* @param noOtp True for not generating a OTP if needed.
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, boolean silent, boolean noOtp) {
return status(accountId, null, null, silent, noOtp);
}
/**
* Return operation status for a given accountId and operationId
* @param accountId The accountId which status is going to be retrieved
* @param operationId The operationId which status is going to be retrieved
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, String operationId) {
return status(accountId, operationId, null, false, false);
}
/**
* Return operation status for a given accountId and operationId
* @param accountId The accountId which status is going to be retrieved
* @param operationId The operationId which status is going to be retrieved
* @param silent True for not sending lock/unlock push notifications to the mobile devices, false otherwise.
* @param noOtp True for not generating a OTP if needed.
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, String operationId, String instanceId, boolean silent, boolean noOtp){
StringBuilder url = new StringBuilder(API_CHECK_STATUS_URL).append("/").append(accountId);
if (operationId != null && !operationId.isEmpty()){
url.append("/op/").append(operationId);
}
if (instanceId != null && !instanceId.isEmpty()){
url.append("/i/").append(instanceId);
}
if (noOtp) {
url.append("/nootp");
}
if (silent) {
url.append("/silent");
}
return HTTP_GET_proxy(url.toString());
}
/**
* Return application status for a given accountId while sending some custom data (Like OTP token or a message)
* @param accountId The accountId which status is going to be retrieved
* @param otpToken This will be the OTP sent to the user instead of generating a new one
* @param otpMessage To attach a custom message with the OTP to the user
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, String otpToken, String otpMessage){
return status(accountId, null, false, otpToken, otpMessage);
}
/**
* Return application status for a given accountId while sending some custom data (Like OTP token or a message)
* @param accountId The accountId which status is going to be retrieved
* @param silent True for not sending lock/unlock push notifications to the mobile devices, false otherwise.
* @param otpToken This will be the OTP sent to the user instead of generating a new one
* @param otpMessage To attach a custom message with the OTP to the user
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, boolean silent, String otpToken, String otpMessage){
return status(accountId, null, null, silent, otpToken, otpMessage);
}
public LatchResponse status(String accountId, String operationId, boolean silent, String otpToken, String otpMessage){
return status(accountId, operationId, null, silent, otpToken, otpMessage);
}
/**
* Return operation status for a given accountId and operation while sending some custom data (Like OTP token or a message)
* @param accountId The accountId which status is going to be retrieved
* @param operationId The operationId which status is going to be retrieved
* @param silent True for not sending lock/unlock push notifications to the mobile devices, false otherwise.
* @param otpToken This will be the OTP sent to the user instead of generating a new one
* @param otpMessage To attach a custom message with the OTP to the user
* @return LatchResponse containing the status
*/
public LatchResponse status(String accountId, String operationId, String instanceId, boolean silent, String otpToken, String otpMessage){
StringBuilder url = new StringBuilder(API_CHECK_STATUS_URL).append("/").append(accountId);
if (operationId != null && !operationId.isEmpty()){
url.append("/op/").append(operationId);
}
if (instanceId != null && !instanceId.isEmpty()){
url.append("/i/").append(instanceId);
}
if (silent) {
url.append("/silent");
}
Map<String, String> data = new HashMap<String, String>();
if (otpToken != null && !otpToken.isEmpty()) {
data.put("otp", otpToken);
}
if (otpMessage != null && !otpMessage.isEmpty()) {
data.put("msg", otpMessage);
}
return HTTP_POST_proxy(url.toString(), data);
}
public LatchResponse addInstance(String accountId, String operationId, String instanceName){
StringBuilder url = new StringBuilder(API_INSTANCE_URL).append("/").append(accountId);
if (operationId != null && !operationId.isEmpty()){
url.append("/op/").append(operationId);
}
Map<String, String> data = new HashMap<String, String>();
if (instanceName != null && !instanceName.isEmpty()) {
data.put("instances", instanceName);
}
return HTTP_POST_proxy(url.toString(), data);
}
public LatchResponse removeInstance(String accountId, String operationId, String instanceId){
StringBuilder url = new StringBuilder(API_INSTANCE_URL).append("/").append(accountId);
if (operationId != null && !operationId.isEmpty()){
url.append("/op/").append(operationId);
}
url.append("/i/").append(instanceId);
return HTTP_DELETE_proxy(url.toString());
}
@Deprecated
public LatchResponse operationStatus(String accountId, String operationId) {
return status(accountId, operationId, null, false, false);
}
@Deprecated
public LatchResponse operationStatus(String accountId, String operationId, boolean silent, boolean noOtp) {
return status(accountId, operationId, null, silent, noOtp);
}
public LatchResponse unpair(String id) {
return HTTP_GET_proxy(new StringBuilder(API_UNPAIR_URL).append("/").append(id).toString());
}
public LatchResponse lock(String accountId) {
return HTTP_POST_proxy(new StringBuilder(API_LOCK_URL).append("/").append(accountId).toString());
}
public LatchResponse lock(String accountId, String operationId) {
return HTTP_POST_proxy(new StringBuilder(API_LOCK_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse unlock(String accountId) {
return HTTP_POST_proxy(new StringBuilder(API_UNLOCK_URL).append("/").append(accountId).toString());
}
public LatchResponse unlock(String accountId, String operationId) {
return HTTP_POST_proxy(new StringBuilder(API_UNLOCK_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse history(String accountId) {
return HTTP_GET_proxy(new StringBuilder(API_HISTORY_URL).append("/").append(accountId).toString());
}
public LatchResponse history(String accountId, Long from, Long to) {
return HTTP_GET_proxy(new StringBuilder(API_HISTORY_URL).append("/").append(accountId)
.append("/").append(from != null ? String.valueOf(from) :"0")
.append("/").append(to != null ? String.valueOf(to) : String.valueOf(new Date().getTime())).toString());
}
public LatchResponse createOperation(String parentId, String name, String twoFactor, String lockOnRequest) {
Map<String, String> data = new HashMap<String, String>();
data.put("parentId", parentId);
data.put("name", name);
data.put("two_factor", twoFactor);
data.put("lock_on_request", lockOnRequest);
return HTTP_PUT_proxy(new StringBuilder(API_OPERATION_URL).toString(), data);
}
public LatchResponse removeOperation(String operationId) {
return HTTP_DELETE_proxy(new StringBuilder(API_OPERATION_URL).append("/").append(operationId).toString());
}
public LatchResponse getOperations() {
return HTTP_GET_proxy(new StringBuilder(API_OPERATION_URL).toString());
}
public LatchResponse getOperations(String operationId) {
return HTTP_GET_proxy(new StringBuilder(API_OPERATION_URL).append("/").append(operationId).toString());
}
public LatchResponse updateOperation(String operationId, String name, String twoFactor, String lockOnRequest) {
Map<String, String> data = new HashMap<String, String>();
data.put("name", name);
data.put("two_factor", twoFactor);
data.put("lock_on_request", lockOnRequest);
return HTTP_POST_proxy(new StringBuilder(API_OPERATION_URL).append("/").append(operationId).toString(), data);
}
} |
package gaia.cu9.ari.gaiaorbit.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.badlogic.gdx.math.MathUtils;
import gaia.cu9.ari.gaiaorbit.GaiaSky;
import gaia.cu9.ari.gaiaorbit.event.EventManager;
import gaia.cu9.ari.gaiaorbit.event.Events;
import gaia.cu9.ari.gaiaorbit.event.IObserver;
import gaia.cu9.ari.gaiaorbit.render.ComponentType;
import gaia.cu9.ari.gaiaorbit.render.system.AbstractRenderSystem;
import gaia.cu9.ari.gaiaorbit.util.concurrent.ThreadIndexer;
import gaia.cu9.ari.gaiaorbit.util.format.DateFormatFactory;
import gaia.cu9.ari.gaiaorbit.util.format.DateFormatFactory.DateType;
import gaia.cu9.ari.gaiaorbit.util.format.IDateFormat;
import gaia.cu9.ari.gaiaorbit.util.math.MathUtilsd;
/**
* Holds the global configuration options
*
* @author Toni Sagrista
*
*/
public class GlobalConf {
public static final String APPLICATION_NAME = "Gaia Sky";
public static final String WEBPAGE = "https:
public static final String WEBPAGE_DOWNLOADS = "https:
public static final String DOCUMENTATION = "http://gaia-sky.rtfd.io";
public static final String ICON_URL = "http:
public static final String TEXTURES_FOLDER = "data/tex/";
public static float SCALE_FACTOR = -1.0f;
public static void updateScaleFactor(float sf) {
SCALE_FACTOR = sf;
Logger.debug(GlobalConf.class.getSimpleName(), "GUI scale factor set to " + GlobalConf.SCALE_FACTOR);
}
public static interface IConf {
}
public enum ScreenshotMode {
simple, redraw
}
public static class ScreenshotConf implements IConf {
public static final int MIN_SCREENSHOT_SIZE = 50;
public static final int MAX_SCREENSHOT_SIZE = 25000;
public int SCREENSHOT_WIDTH;
public int SCREENSHOT_HEIGHT;
public String SCREENSHOT_FOLDER;
public ScreenshotMode SCREENSHOT_MODE;
public void initialize(int sCREENSHOT_WIDTH, int sCREENSHOT_HEIGHT, String sCREENSHOT_FOLDER, ScreenshotMode sCREENSHOT_MODE) {
SCREENSHOT_WIDTH = sCREENSHOT_WIDTH;
SCREENSHOT_HEIGHT = sCREENSHOT_HEIGHT;
SCREENSHOT_FOLDER = sCREENSHOT_FOLDER;
SCREENSHOT_MODE = sCREENSHOT_MODE;
}
public boolean isSimpleMode() {
return SCREENSHOT_MODE.equals(ScreenshotMode.simple);
}
public boolean isRedrawMode() {
return SCREENSHOT_MODE.equals(ScreenshotMode.redraw);
}
}
public static class PerformanceConf implements IConf {
public boolean MULTITHREADING;
public int NUMBER_THREADS;
public void initialize(boolean MULTITHREADING, int NUMBER_THREADS) {
this.MULTITHREADING = MULTITHREADING;
this.NUMBER_THREADS = NUMBER_THREADS;
}
/**
* Returns the actual number of threads. It accounts for the number of
* threads being 0 or less, "let the program decide" option, in which
* case the number of processors is returned
*
* @return The number of threads
*/
public int NUMBER_THREADS() {
if (NUMBER_THREADS <= 0)
return ThreadIndexer.instance.nthreads();
else
return NUMBER_THREADS;
}
}
public static class PostprocessConf implements IConf, IObserver {
public int POSTPROCESS_ANTIALIAS;
public float POSTPROCESS_BLOOM_INTENSITY;
public float POSTPROCESS_MOTION_BLUR;
public boolean POSTPROCESS_LENS_FLARE;
public boolean POSTPROCESS_LIGHT_SCATTERING;
public boolean POSTPROCESS_FISHEYE;
/** Brightness level in [-1..1]. Default is 0. **/
public float POSTPROCESS_BRIGHTNESS;
/** Contrast level in [0..2]. Default is 1. **/
public float POSTPROCESS_CONTRAST;
public PostprocessConf() {
EventManager.instance.subscribe(this, Events.BLOOM_CMD, Events.LENS_FLARE_CMD, Events.MOTION_BLUR_CMD, Events.LIGHT_SCATTERING_CMD, Events.FISHEYE_CMD, Events.BRIGHTNESS_CMD, Events.CONTRAST_CMD);
}
public void initialize(int POSTPROCESS_ANTIALIAS, float POSTPROCESS_BLOOM_INTENSITY, float POSTPROCESS_MOTION_BLUR, boolean POSTPROCESS_LENS_FLARE, boolean POSTPROCESS_LIGHT_SCATTERING, boolean POSTPROCESS_FISHEYE, float POSTPROCESS_BRIGHTNESS, float POSTPROCESS_CONTRAST) {
this.POSTPROCESS_ANTIALIAS = POSTPROCESS_ANTIALIAS;
this.POSTPROCESS_BLOOM_INTENSITY = POSTPROCESS_BLOOM_INTENSITY;
this.POSTPROCESS_MOTION_BLUR = POSTPROCESS_MOTION_BLUR;
this.POSTPROCESS_LENS_FLARE = POSTPROCESS_LENS_FLARE;
this.POSTPROCESS_LIGHT_SCATTERING = POSTPROCESS_LIGHT_SCATTERING;
this.POSTPROCESS_FISHEYE = POSTPROCESS_FISHEYE;
this.POSTPROCESS_BRIGHTNESS = POSTPROCESS_BRIGHTNESS;
this.POSTPROCESS_CONTRAST = POSTPROCESS_CONTRAST;
}
@Override
public void notify(Events event, Object... data) {
switch (event) {
case BLOOM_CMD:
POSTPROCESS_BLOOM_INTENSITY = (float) data[0];
break;
case LENS_FLARE_CMD:
POSTPROCESS_LENS_FLARE = (Boolean) data[0];
break;
case LIGHT_SCATTERING_CMD:
POSTPROCESS_LIGHT_SCATTERING = (Boolean) data[0];
break;
case MOTION_BLUR_CMD:
POSTPROCESS_MOTION_BLUR = (float) data[0];
break;
case FISHEYE_CMD:
POSTPROCESS_FISHEYE = (Boolean) data[0];
break;
case BRIGHTNESS_CMD:
POSTPROCESS_BRIGHTNESS = MathUtils.clamp((float) data[0], Constants.MIN_BRIGHTNESS, Constants.MAX_BRIGHTNESS);
break;
case CONTRAST_CMD:
POSTPROCESS_CONTRAST = MathUtils.clamp((float) data[0], Constants.MIN_CONTRAST, Constants.MAX_CONTRAST);
break;
default:
break;
}
}
}
public static class ControlsConf implements IConf {
public String CONTROLLER_MAPPINGS_FILE;
public boolean INVERT_LOOK_Y_AXIS;
public boolean DEBUG_MODE;
public ControlsConf() {
}
public void initialize(String cONTROLLER_MAPPINGS_FILE, boolean iNVERT_LOOK_Y_AXIS, boolean dEBUG_MODE) {
CONTROLLER_MAPPINGS_FILE = cONTROLLER_MAPPINGS_FILE;
INVERT_LOOK_Y_AXIS = iNVERT_LOOK_Y_AXIS;
DEBUG_MODE = dEBUG_MODE;
}
}
/**
* Runtime configuration values, which are never persisted.
*
* @author Toni Sagrista
*
*/
public static class RuntimeConf implements IConf, IObserver {
public boolean DISPLAY_GUI;
public boolean UPDATE_PAUSE;
public boolean TIME_ON;
/** Whether we use the RealTimeClock or the GlobalClock **/
public boolean REAL_TIME;
public boolean INPUT_ENABLED;
public boolean RECORD_CAMERA;
public float LIMIT_MAG_RUNTIME;
public int OUTPUT_FRAME_BUFFER_SIZE = 50;
public boolean STRIPPED_FOV_MODE = false;
/** Whether octree drawing is active or not **/
public boolean DRAW_OCTREE;
public boolean RELATIVISTIC_ABERRATION = false;
public RuntimeConf() {
EventManager.instance.subscribe(this, Events.LIMIT_MAG_CMD, Events.INPUT_ENABLED_CMD, Events.DISPLAY_GUI_CMD, Events.TOGGLE_UPDATEPAUSE, Events.TOGGLE_TIME_CMD, Events.RECORD_CAMERA_CMD);
}
public void initialize(boolean dISPLAY_GUI, boolean uPDATE_PAUSE, boolean sTRIPPED_FOV_MODE, boolean tIME_ON, boolean iNPUT_ENABLED, boolean rECORD_CAMERA, float lIMIT_MAG_RUNTIME, boolean rEAL_TIME, boolean dRAW_OCTREE) {
DISPLAY_GUI = dISPLAY_GUI;
UPDATE_PAUSE = uPDATE_PAUSE;
TIME_ON = tIME_ON;
INPUT_ENABLED = iNPUT_ENABLED;
RECORD_CAMERA = rECORD_CAMERA;
LIMIT_MAG_RUNTIME = lIMIT_MAG_RUNTIME;
STRIPPED_FOV_MODE = sTRIPPED_FOV_MODE;
REAL_TIME = rEAL_TIME;
DRAW_OCTREE = dRAW_OCTREE;
}
@Override
public void notify(Events event, Object... data) {
switch (event) {
case LIMIT_MAG_CMD:
LIMIT_MAG_RUNTIME = (float) data[0];
AbstractRenderSystem.POINT_UPDATE_FLAG = true;
break;
case INPUT_ENABLED_CMD:
INPUT_ENABLED = (boolean) data[0];
break;
case DISPLAY_GUI_CMD:
if (data.length > 1) {
// Value
Boolean val = (Boolean) data[1];
DISPLAY_GUI = val;
} else {
// Toggle
DISPLAY_GUI = !DISPLAY_GUI;
}
break;
case TOGGLE_UPDATEPAUSE:
UPDATE_PAUSE = !UPDATE_PAUSE;
EventManager.instance.post(Events.UPDATEPAUSE_CHANGED, UPDATE_PAUSE);
break;
case TOGGLE_TIME_CMD:
toggleTimeOn((Boolean) data[0]);
break;
case RECORD_CAMERA_CMD:
toggleRecord((Boolean) data[0]);
break;
default:
break;
}
}
/**
* Toggles the time
*/
public void toggleTimeOn(Boolean timeOn) {
if (timeOn != null) {
TIME_ON = timeOn;
} else {
TIME_ON = !TIME_ON;
}
}
/**
* Toggles the record camera
*/
public void toggleRecord(Boolean rec) {
if (rec != null) {
RECORD_CAMERA = rec;
} else {
RECORD_CAMERA = !RECORD_CAMERA;
}
}
}
/**
* Holds the configuration for the output frame subsystem and the camera
* recording.
*
* @author Toni Sagrista
*
*/
public static class FrameConf implements IConf, IObserver {
public static final int MIN_FRAME_SIZE = 50;
public static final int MAX_FRAME_SIZE = 25000;
/** The width of the image frames **/
public int RENDER_WIDTH;
/** The height of the image frames **/
public int RENDER_HEIGHT;
/** The number of images per second to produce **/
public int RENDER_TARGET_FPS;
/** The target FPS when recording the camera **/
public int CAMERA_REC_TARGET_FPS;
/**
* Automatically activate frame output system when playing camera file
**/
public boolean AUTO_FRAME_OUTPUT_CAMERA_PLAY;
/** The output folder **/
public String RENDER_FOLDER;
/** The prefix for the image files **/
public String RENDER_FILE_NAME;
/** Should we write the simulation time to the images? **/
public boolean RENDER_SCREENSHOT_TIME;
/** Whether the frame system is activated or not **/
public boolean RENDER_OUTPUT = false;
/** The frame output screenshot mode **/
public ScreenshotMode FRAME_MODE;
public FrameConf() {
EventManager.instance.subscribe(this, Events.CONFIG_FRAME_OUTPUT, Events.FRAME_OUTPUT_CMD);
}
public boolean isSimpleMode() {
return FRAME_MODE.equals(ScreenshotMode.simple);
}
public boolean isRedrawMode() {
return FRAME_MODE.equals(ScreenshotMode.redraw);
}
public void initialize(int rENDER_WIDTH, int rENDER_HEIGHT, int rENDER_TARGET_FPS, int cAMERA_REC_TARGET_FPS, boolean aUTO_FRAME_OUTPUT_CAMERA_PLAY, String rENDER_FOLDER, String rENDER_FILE_NAME, boolean rENDER_SCREENSHOT_TIME, boolean rENDER_OUTPUT, ScreenshotMode fRAME_MODE) {
RENDER_WIDTH = rENDER_WIDTH;
RENDER_HEIGHT = rENDER_HEIGHT;
RENDER_TARGET_FPS = rENDER_TARGET_FPS;
CAMERA_REC_TARGET_FPS = cAMERA_REC_TARGET_FPS;
AUTO_FRAME_OUTPUT_CAMERA_PLAY = aUTO_FRAME_OUTPUT_CAMERA_PLAY;
RENDER_FOLDER = rENDER_FOLDER;
RENDER_FILE_NAME = rENDER_FILE_NAME;
RENDER_SCREENSHOT_TIME = rENDER_SCREENSHOT_TIME;
RENDER_OUTPUT = rENDER_OUTPUT;
FRAME_MODE = fRAME_MODE;
}
@Override
public void notify(Events event, Object... data) {
switch (event) {
case CONFIG_FRAME_OUTPUT:
RENDER_WIDTH = (int) data[0];
RENDER_HEIGHT = (int) data[1];
RENDER_TARGET_FPS = (int) data[2];
RENDER_FOLDER = (String) data[3];
RENDER_FILE_NAME = (String) data[4];
break;
case FRAME_OUTPUT_CMD:
RENDER_OUTPUT = (Boolean) data[0];
// Flush buffer if needed
if (!RENDER_OUTPUT && GaiaSky.instance != null) {
EventManager.instance.post(Events.FLUSH_FRAMES);
}
break;
default:
break;
}
}
}
/**
* Holds all configuration values related to data.
*
* @author Toni Sagrista
*
*/
public static class DataConf implements IConf {
/** The json data file in case of local data source **/
public String OBJECTS_JSON_FILE;
/** String with different files for different qualities **/
public String[] OBJECTS_JSON_FILE_GQ;
/** The json file with the catalogue(s) to load **/
public String CATALOG_JSON_FILE;
/**
* High accuracy positions for planets and moon - use all terms of
* VSOP87 and moon algorithms
**/
public boolean HIGH_ACCURACY_POSITIONS;
/**
* Limit magnitude used for loading stars. All stars above this
* magnitude will not even be loaded by the sandbox.
**/
public float LIMIT_MAG_LOAD;
/**
* Whether to use the real attitude of Gaia or the NSL approximation
**/
public boolean REAL_GAIA_ATTITUDE;
public void initialize(String cATALOG_JSON_FILE, String oBJECTS_JSON_FILE, String[] oBJECTS_JSON_FILE_GQ, float lIMIT_MAG_LOAD, boolean rEAL_GAIA_ATTITUDE, boolean hIGH_ACCURACY_POSITIONS) {
CATALOG_JSON_FILE = cATALOG_JSON_FILE;
OBJECTS_JSON_FILE = oBJECTS_JSON_FILE;
OBJECTS_JSON_FILE_GQ = oBJECTS_JSON_FILE_GQ;
LIMIT_MAG_LOAD = lIMIT_MAG_LOAD;
REAL_GAIA_ATTITUDE = rEAL_GAIA_ATTITUDE;
HIGH_ACCURACY_POSITIONS = hIGH_ACCURACY_POSITIONS;
}
public void initialize(String cATALOG_JSON_FILE, String oBJECTS_JSON_FILE, boolean dATA_SOURCE_LOCAL, float lIMIT_MAG_LOAD) {
this.CATALOG_JSON_FILE = cATALOG_JSON_FILE;
this.OBJECTS_JSON_FILE = oBJECTS_JSON_FILE;
this.LIMIT_MAG_LOAD = lIMIT_MAG_LOAD;
}
public void initialize(String cATALOG_JSON_FILE, String dATA_JSON_FILE, boolean dATA_SOURCE_LOCAL, float lIMIT_MAG_LOAD, boolean rEAL_GAIA_ATTITUDE) {
this.CATALOG_JSON_FILE = cATALOG_JSON_FILE;
this.OBJECTS_JSON_FILE = dATA_JSON_FILE;
this.LIMIT_MAG_LOAD = lIMIT_MAG_LOAD;
this.REAL_GAIA_ATTITUDE = rEAL_GAIA_ATTITUDE;
}
}
public static class ScreenConf implements IConf {
public int SCREEN_WIDTH;
public int SCREEN_HEIGHT;
public int FULLSCREEN_WIDTH;
public int FULLSCREEN_HEIGHT;
public boolean FULLSCREEN;
public boolean RESIZABLE;
public boolean VSYNC;
public boolean SCREEN_OUTPUT = true;
public void initialize(int sCREEN_WIDTH, int sCREEN_HEIGHT, int fULLSCREEN_WIDTH, int fULLSCREEN_HEIGHT, boolean fULLSCREEN, boolean rESIZABLE, boolean vSYNC, boolean sCREEN_OUTPUT) {
SCREEN_WIDTH = sCREEN_WIDTH;
SCREEN_HEIGHT = sCREEN_HEIGHT;
FULLSCREEN_WIDTH = fULLSCREEN_WIDTH;
FULLSCREEN_HEIGHT = fULLSCREEN_HEIGHT;
FULLSCREEN = fULLSCREEN;
RESIZABLE = rESIZABLE;
VSYNC = vSYNC;
SCREEN_OUTPUT = sCREEN_OUTPUT;
}
public int getScreenWidth() {
return FULLSCREEN ? FULLSCREEN_WIDTH : SCREEN_WIDTH;
}
public int getScreenHeight() {
return FULLSCREEN ? FULLSCREEN_HEIGHT : SCREEN_HEIGHT;
}
}
public static class ProgramConf implements IConf, IObserver {
public static enum StereoProfile {
/** Left image -> left eye, distortion **/
VR_HEADSET,
/** Left image -> left eye, distortion **/
HD_3DTV,
/** Left image -> right eye, no distortion **/
CROSSEYE,
/** Left image -> left eye, no distortion **/
PARALLEL_VIEW,
/** Red-cyan anaglyphic 3D mode **/
ANAGLYPHIC
}
public boolean DISPLAY_TUTORIAL;
public String TUTORIAL_POINTER_SCRIPT_LOCATION;
public String TUTORIAL_SCRIPT_LOCATION;
public boolean SHOW_DEBUG_INFO;
public Date LAST_CHECKED;
public String LAST_VERSION_TIME;
public String VERSION_CHECK_URL;
public String UI_THEME;
public String SCRIPT_LOCATION;
public int REST_PORT;
public String LOCALE;
public boolean DISPLAY_HUD;
public boolean DISPLAY_POINTER_COORDS;
public boolean CUBEMAP360_MODE;
public boolean STEREOSCOPIC_MODE;
/** Eye separation in stereoscopic mode in meters **/
public float STEREOSCOPIC_EYE_SEPARATION_M = 1;
/** This controls the side of the images in the stereoscopic mode **/
public StereoProfile STEREO_PROFILE = StereoProfile.VR_HEADSET;
public boolean ANALYTICS_ENABLED;
/** Whether to display the dataset dialog at startup or not **/
public boolean DISPLAY_DATASET_DIALOG;
public ProgramConf() {
EventManager.instance.subscribe(this, Events.STEREOSCOPIC_CMD, Events.STEREO_PROFILE_CMD, Events.CUBEMAP360_CMD);
}
public void initialize(boolean dISPLAY_TUTORIAL, String tUTORIAL_POINTER_SCRIPT_LOCATION, String tUTORIAL_SCRIPT_LOCATION, boolean sHOW_DEBUG_INFO, Date lAST_CHECKED, String lAST_VERSION_TIME, String vERSION_CHECK_URL, String uI_THEME, String sCRIPT_LOCATION, int rEST_PORT, String lOCALE, boolean sTEREOSCOPIC_MODE, StereoProfile sTEREO_PROFILE, boolean cUBEMAP360_MODE, boolean aNALYTICS_ENABLED, boolean dISPLAY_HUD, boolean dISPLAY_POINTER_COORDS, boolean dISPLAY_DATASET_DIALOG) {
DISPLAY_TUTORIAL = dISPLAY_TUTORIAL;
TUTORIAL_POINTER_SCRIPT_LOCATION = tUTORIAL_POINTER_SCRIPT_LOCATION;
TUTORIAL_SCRIPT_LOCATION = tUTORIAL_SCRIPT_LOCATION;
SHOW_DEBUG_INFO = sHOW_DEBUG_INFO;
LAST_CHECKED = lAST_CHECKED;
LAST_VERSION_TIME = lAST_VERSION_TIME;
VERSION_CHECK_URL = vERSION_CHECK_URL;
UI_THEME = uI_THEME;
SCRIPT_LOCATION = sCRIPT_LOCATION;
REST_PORT = rEST_PORT;
LOCALE = lOCALE;
STEREOSCOPIC_MODE = sTEREOSCOPIC_MODE;
STEREO_PROFILE = sTEREO_PROFILE;
CUBEMAP360_MODE = cUBEMAP360_MODE;
ANALYTICS_ENABLED = aNALYTICS_ENABLED;
DISPLAY_HUD = dISPLAY_HUD;
DISPLAY_POINTER_COORDS = dISPLAY_POINTER_COORDS;
DISPLAY_DATASET_DIALOG = dISPLAY_DATASET_DIALOG;
}
public void initialize(boolean dISPLAY_TUTORIAL, boolean sHOW_DEBUG_INFO, String uI_THEME, String lOCALE, boolean sTEREOSCOPIC_MODE, StereoProfile sTEREO_PROFILE) {
DISPLAY_TUTORIAL = dISPLAY_TUTORIAL;
SHOW_DEBUG_INFO = sHOW_DEBUG_INFO;
UI_THEME = uI_THEME;
LOCALE = lOCALE;
STEREOSCOPIC_MODE = sTEREOSCOPIC_MODE;
STEREO_PROFILE = sTEREO_PROFILE;
}
public String getLastCheckedString() {
IDateFormat df = DateFormatFactory.getFormatter(I18n.locale, DateType.DATE);
return df.format(LAST_CHECKED);
}
public boolean isStereoHalfWidth() {
return STEREOSCOPIC_MODE && (STEREO_PROFILE != StereoProfile.HD_3DTV && STEREO_PROFILE != StereoProfile.ANAGLYPHIC);
}
public boolean isStereoFullWidth() {
return !isStereoHalfWidth();
}
public boolean isStereoHalfViewport() {
return STEREOSCOPIC_MODE && STEREO_PROFILE != StereoProfile.ANAGLYPHIC;
}
@Override
public void notify(Events event, Object... data) {
switch (event) {
case STEREOSCOPIC_CMD:
if (!GaiaSky.instance.cam.mode.isGaiaFov()) {
boolean stereomode = (Boolean) data[0];
STEREOSCOPIC_MODE = stereomode;
if (STEREOSCOPIC_MODE && CUBEMAP360_MODE) {
CUBEMAP360_MODE = false;
EventManager.instance.post(Events.DISPLAY_GUI_CMD, I18n.bundle.get("notif.cleanmode"), true);
}
EventManager.instance.post(Events.POST_NOTIFICATION, "You have entered 3D mode. Go back to normal mode using <CTRL+S>");
EventManager.instance.post(Events.POST_NOTIFICATION, "Switch between stereoscopic modes using <CTRL+SHIFT+S>");
}
break;
case STEREO_PROFILE_CMD:
STEREO_PROFILE = StereoProfile.values()[(Integer) data[0]];
break;
case CUBEMAP360_CMD:
CUBEMAP360_MODE = (Boolean) data[0];
EventManager.instance.post(Events.DISPLAY_GUI_CMD, I18n.bundle.get("notif.cleanmode"), !CUBEMAP360_MODE);
EventManager.instance.post(Events.POST_NOTIFICATION, "You have entered the 360 mode. Go back to normal mode using <CTRL+3>");
break;
default:
break;
}
}
}
public static class SpacecraftConf implements IConf {
public float SC_RESPONSIVENESS;
public boolean SC_VEL_TO_DIRECTION;
public float SC_HANDLING_FRICTION;
public boolean SC_SHOW_AXES;
public void initialize(float sC_RESPONSIVENESS, boolean sC_VEL_TO_DIRECTION, float sC_HANDLING_FRICTION, boolean sC_SHOW_AXES) {
this.SC_RESPONSIVENESS = sC_RESPONSIVENESS;
this.SC_VEL_TO_DIRECTION = sC_VEL_TO_DIRECTION;
this.SC_HANDLING_FRICTION = sC_HANDLING_FRICTION;
this.SC_SHOW_AXES = sC_SHOW_AXES;
}
}
public static class VersionConf implements IConf {
public String version;
public Date buildtime;
public String builder;
public String system;
public String build;
public void initialize(String version, Date buildtime, String builder, String system, String build) {
this.version = version;
this.buildtime = buildtime;
this.builder = builder;
this.system = system;
this.build = build;
}
public static int[] getMajorMinorRevFromString(String version) {
String majorS = version.substring(0, version.indexOf("."));
String minorS, revS;
int dots = GlobalResources.countOccurrences(version, '.');
int idx0 = GlobalResources.nthIndexOf(version, '.', 1);
if (dots == 1) {
minorS = version.substring(version.indexOf(".", idx0) + 1, version.length());
revS = null;
} else if (dots > 1) {
int idx1 = GlobalResources.nthIndexOf(version, '.', 2);
minorS = version.substring(version.indexOf(".", idx0) + 1, version.indexOf(".", idx1));
revS = version.substring(version.indexOf(".", idx1) + 1, version.length());
} else {
return null;
}
if (majorS.matches("^\\D{1}\\d+$")) {
majorS = majorS.substring(1, majorS.length());
}
if (minorS.matches("^\\d+\\D{1}$")) {
minorS = minorS.substring(0, minorS.length() - 1);
}
if (revS != null && revS.matches("^\\d+\\D{1}$")) {
revS = revS.substring(0, revS.length() - 1);
}
return new int[] { Integer.parseInt(majorS), Integer.parseInt(minorS), revS != null ? Integer.parseInt(revS) : 0 };
}
@Override
public String toString() {
return version;
}
}
public static class SceneConf implements IConf, IObserver {
public long OBJECT_FADE_MS;
public double STAR_BRIGHTNESS;
public double AMBIENT_LIGHT;
public int CAMERA_FOV;
public double CAMERA_SPEED;
public double TURNING_SPEED;
public double ROTATION_SPEED;
public boolean FREE_CAMERA_TARGET_MODE_ON;
public int CAMERA_SPEED_LIMIT_IDX;
public double CAMERA_SPEED_LIMIT;
public boolean FOCUS_LOCK;
public boolean FOCUS_LOCK_ORIENTATION;
public boolean CINEMATIC_CAMERA;
public float LABEL_NUMBER_FACTOR;
/** Visibility of component types **/
public boolean[] VISIBILITY;
/** Display galaxy as 3D object or as a 2D texture **/
public boolean GALAXY_3D;
/** Shadows enabled or disabled **/
public boolean SHADOW_MAPPING;
/** Max number of objects with shadows **/
public int SHADOW_MAPPING_N_SHADOWS;
/** Resolution of the shadow map **/
public int SHADOW_MAPPING_RESOLUTION;
/** Whether to display proper motion vectors **/
public boolean PROPER_MOTION_VECTORS;
/** Factor to apply to the length of the proper motion vectors **/
public float PM_LEN_FACTOR;
/** This governs the number of proper motion vectors to display **/
public float PM_NUM_FACTOR;
public boolean STAR_COLOR_TRANSIT;
public boolean ONLY_OBSERVED_STARS;
public boolean COMPUTE_GAIA_SCAN;
/**
* Whether to use the general line renderer or a faster GPU-based
* approach
* <ul>
* <li>0 - Sorted lines (see LINE_RENDERER) - slower but looks
* better</li>
* <li>1 - GPU VBO - faster but looks a bit worse</li>
* </ul>
*/
public int ORBIT_RENDERER;
/** The line render system: 0 - normal, 1 - shader **/
public int LINE_RENDERER;
/** The graphics quality mode: 0 - high, 1 - normal, 2 - low **/
public int GRAPHICS_QUALITY;
/** Lazy texture initialisation - textures are loaded only if needed **/
public boolean LAZY_TEXTURE_INIT;
/** Whether to show crosshair in focus mode **/
public boolean CROSSHAIR;
/**
* Resolution of each of the faces in the cubemap which will be mapped
* to a equirectangular projection for the 360 mode.
*/
public int CUBEMAP_FACE_RESOLUTION;
public double STAR_THRESHOLD_NONE;
public double STAR_THRESHOLD_POINT;
public double STAR_THRESHOLD_QUAD;
public float POINT_ALPHA_MIN;
public float POINT_ALPHA_MAX;
/** Size of stars rendered as point primitives **/
public float STAR_POINT_SIZE;
/** Fallback value **/
public float STAR_POINT_SIZE_BAK;
/**
* Particle fade in/out flag for octree-backed catalogs. WARNING: This
* implies particles are sent to GPU at each cycle
**/
public boolean OCTREE_PARTICLE_FADE;
/**
* Angle [rad] above which we start painting stars in octant with fade
* in
**/
public float OCTANT_THRESHOLD_0;
/**
* Angle [rad] below which we paint stars in octant with fade out. Above
* this angle, inner stars are painted with full brightness
**/
public float OCTANT_THRESHOLD_1;
public SceneConf() {
EventManager.instance.subscribe(this, Events.TOGGLE_VISIBILITY_CMD, Events.FOCUS_LOCK_CMD, Events.ORIENTATION_LOCK_CMD, Events.PROPER_MOTIONS_CMD, Events.STAR_BRIGHTNESS_CMD, Events.PM_LEN_FACTOR_CMD, Events.PM_NUM_FACTOR_CMD, Events.FOV_CHANGED_CMD, Events.CAMERA_SPEED_CMD, Events.ROTATION_SPEED_CMD, Events.TURNING_SPEED_CMD, Events.SPEED_LIMIT_CMD, Events.TRANSIT_COLOUR_CMD, Events.ONLY_OBSERVED_STARS_CMD, Events.COMPUTE_GAIA_SCAN_CMD, Events.OCTREE_PARTICLE_FADE_CMD, Events.STAR_POINT_SIZE_CMD, Events.STAR_POINT_SIZE_INCREASE_CMD, Events.STAR_POINT_SIZE_DECREASE_CMD, Events.STAR_POINT_SIZE_RESET_CMD, Events.STAR_MIN_OPACITY_CMD, Events.AMBIENT_LIGHT_CMD, Events.GALAXY_3D_CMD, Events.CROSSHAIR_CMD, Events.CAMERA_CINEMATIC_CMD, Events.CUBEMAP_RESOLUTION_CMD);
}
public void initialize(int gRAPHICS_QUALITY, long oBJECT_FADE_MS, float sTAR_BRIGHTNESS, float aMBIENT_LIGHT, int cAMERA_FOV, float cAMERA_SPEED, float tURNING_SPEED, float rOTATION_SPEED, int cAMERA_SPEED_LIMIT_IDX, boolean fOCUS_LOCK, boolean fOCUS_LOCK_ORIENTATION, float lABEL_NUMBER_FACTOR, boolean[] vISIBILITY, int oRBIT_RENDERER, int lINE_RENDERER, double sTAR_TH_ANGLE_NONE, double sTAR_TH_ANGLE_POINT, double sTAR_TH_ANGLE_QUAD, float pOINT_ALPHA_MIN, float pOINT_ALPHA_MAX,
boolean oCTREE_PARTICLE_FADE, float oCTANT_TH_ANGLE_0, float oCTANT_TH_ANGLE_1, boolean pROPER_MOTION_VECTORS, float pM_NUM_FACTOR, float pM_LEN_FACTOR, float sTAR_POINT_SIZE, boolean gALAXY_3D, int cUBEMAP_FACE_RESOLUTION, boolean cROSSHAIR, boolean cINEMATIC_CAMERA, boolean lAZY_TEXTURE_INIT, boolean fREE_CAMERA_TARGET_MODE_ON, boolean sHADOW_MAPPING, int sHADOW_MAPPING_N_SHADOWS, int sHADOW_MAPPING_RESOLUTION) {
GRAPHICS_QUALITY = gRAPHICS_QUALITY;
OBJECT_FADE_MS = oBJECT_FADE_MS;
STAR_BRIGHTNESS = sTAR_BRIGHTNESS;
AMBIENT_LIGHT = aMBIENT_LIGHT;
CAMERA_FOV = cAMERA_FOV;
CAMERA_SPEED = cAMERA_SPEED;
TURNING_SPEED = tURNING_SPEED;
ROTATION_SPEED = rOTATION_SPEED;
FREE_CAMERA_TARGET_MODE_ON = fREE_CAMERA_TARGET_MODE_ON;
CAMERA_SPEED_LIMIT_IDX = cAMERA_SPEED_LIMIT_IDX;
this.updateSpeedLimit();
FOCUS_LOCK = fOCUS_LOCK;
FOCUS_LOCK_ORIENTATION = fOCUS_LOCK_ORIENTATION;
LABEL_NUMBER_FACTOR = lABEL_NUMBER_FACTOR;
VISIBILITY = vISIBILITY;
ORBIT_RENDERER = oRBIT_RENDERER;
LINE_RENDERER = lINE_RENDERER;
STAR_THRESHOLD_NONE = sTAR_TH_ANGLE_NONE;
STAR_THRESHOLD_POINT = sTAR_TH_ANGLE_POINT;
STAR_THRESHOLD_QUAD = sTAR_TH_ANGLE_QUAD;
POINT_ALPHA_MIN = pOINT_ALPHA_MIN;
POINT_ALPHA_MAX = pOINT_ALPHA_MAX;
OCTREE_PARTICLE_FADE = oCTREE_PARTICLE_FADE;
OCTANT_THRESHOLD_0 = oCTANT_TH_ANGLE_0;
OCTANT_THRESHOLD_1 = oCTANT_TH_ANGLE_1;
PROPER_MOTION_VECTORS = pROPER_MOTION_VECTORS;
PM_NUM_FACTOR = pM_NUM_FACTOR;
PM_LEN_FACTOR = pM_LEN_FACTOR;
STAR_POINT_SIZE = sTAR_POINT_SIZE;
STAR_POINT_SIZE_BAK = STAR_POINT_SIZE;
GALAXY_3D = gALAXY_3D;
CUBEMAP_FACE_RESOLUTION = cUBEMAP_FACE_RESOLUTION;
CROSSHAIR = cROSSHAIR;
CINEMATIC_CAMERA = cINEMATIC_CAMERA;
LAZY_TEXTURE_INIT = lAZY_TEXTURE_INIT;
SHADOW_MAPPING = sHADOW_MAPPING;
SHADOW_MAPPING_N_SHADOWS = sHADOW_MAPPING_N_SHADOWS;
SHADOW_MAPPING_RESOLUTION = sHADOW_MAPPING_RESOLUTION;
}
public void updateSpeedLimit() {
switch (CAMERA_SPEED_LIMIT_IDX) {
case 0:
// 100 km/h is 0.027 km/s
CAMERA_SPEED_LIMIT = 0.0277777778 * Constants.KM_TO_U;
break;
case 1:
CAMERA_SPEED_LIMIT = 0.5 * Constants.C * Constants.M_TO_U;
break;
case 2:
CAMERA_SPEED_LIMIT = 0.8 * Constants.C * Constants.M_TO_U;
break;
case 3:
CAMERA_SPEED_LIMIT = 0.9 * Constants.C * Constants.M_TO_U;
break;
case 4:
CAMERA_SPEED_LIMIT = 0.99 * Constants.C * Constants.M_TO_U;
break;
case 5:
CAMERA_SPEED_LIMIT = 0.99999 * Constants.C * Constants.M_TO_U;
break;
case 6:
CAMERA_SPEED_LIMIT = Constants.C * Constants.M_TO_U;
break;
case 7:
CAMERA_SPEED_LIMIT = 2.0 * Constants.C * Constants.M_TO_U;
break;
case 8:
// 10 c
CAMERA_SPEED_LIMIT = 10.0 * Constants.C * Constants.M_TO_U;
break;
case 9:
// 1000 c
CAMERA_SPEED_LIMIT = 1000.0 * Constants.C * Constants.M_TO_U;
break;
case 10:
CAMERA_SPEED_LIMIT = 1.0 * Constants.AU_TO_U;
break;
case 11:
CAMERA_SPEED_LIMIT = 10.0 * Constants.AU_TO_U;
break;
case 12:
CAMERA_SPEED_LIMIT = 1000.0 * Constants.AU_TO_U;
break;
case 13:
CAMERA_SPEED_LIMIT = 10000.0 * Constants.AU_TO_U;
break;
case 14:
CAMERA_SPEED_LIMIT = Constants.PC_TO_U;
break;
case 15:
CAMERA_SPEED_LIMIT = 2.0 * Constants.PC_TO_U;
break;
case 16:
// 10 pc/s
CAMERA_SPEED_LIMIT = 10.0 * Constants.PC_TO_U;
break;
case 17:
// 1000 pc/s
CAMERA_SPEED_LIMIT = 1000.0 * Constants.PC_TO_U;
break;
case 18:
// No limit
CAMERA_SPEED_LIMIT = -1;
break;
}
}
@Override
public void notify(Events event, Object... data) {
switch (event) {
case TOGGLE_VISIBILITY_CMD:
String key = (String) data[0];
Boolean state = null;
if (data.length > 2) {
state = (Boolean) data[2];
}
ComponentType ct = ComponentType.getFromKey(key);
VISIBILITY[ct.ordinal()] = (state != null ? state : !VISIBILITY[ct.ordinal()]);
break;
case TRANSIT_COLOUR_CMD:
STAR_COLOR_TRANSIT = (boolean) data[1];
break;
case ONLY_OBSERVED_STARS_CMD:
ONLY_OBSERVED_STARS = (boolean) data[1];
break;
case COMPUTE_GAIA_SCAN_CMD:
COMPUTE_GAIA_SCAN = (boolean) data[1];
break;
case FOCUS_LOCK_CMD:
FOCUS_LOCK = (boolean) data[1];
break;
case ORIENTATION_LOCK_CMD:
FOCUS_LOCK_ORIENTATION = (boolean) data[1];
break;
case AMBIENT_LIGHT_CMD:
AMBIENT_LIGHT = (float) data[0];
break;
case STAR_BRIGHTNESS_CMD:
STAR_BRIGHTNESS = Math.max(0.01f, (float) data[0]);
break;
case FOV_CHANGED_CMD:
CAMERA_FOV = MathUtilsd.clamp(((Float) data[0]).intValue(), Constants.MIN_FOV, Constants.MAX_FOV);
break;
case PM_NUM_FACTOR_CMD:
PM_NUM_FACTOR = Math.min(Constants.MAX_PM_NUM_FACTOR, Math.max(Constants.MIN_PM_NUM_FACTOR, (float) data[0]));
break;
case PM_LEN_FACTOR_CMD:
PM_LEN_FACTOR = Math.min(Constants.MAX_PM_LEN_FACTOR, Math.max(Constants.MIN_PM_LEN_FACTOR, (float) data[0]));
break;
case CAMERA_SPEED_CMD:
CAMERA_SPEED = (float) data[0];
break;
case ROTATION_SPEED_CMD:
ROTATION_SPEED = (float) data[0];
break;
case TURNING_SPEED_CMD:
TURNING_SPEED = (float) data[0];
break;
case SPEED_LIMIT_CMD:
CAMERA_SPEED_LIMIT_IDX = (Integer) data[0];
updateSpeedLimit();
break;
case OCTREE_PARTICLE_FADE_CMD:
OCTREE_PARTICLE_FADE = (boolean) data[1];
break;
case PROPER_MOTIONS_CMD:
PROPER_MOTION_VECTORS = (boolean) data[1];
break;
case STAR_POINT_SIZE_CMD:
STAR_POINT_SIZE = (float) data[0];
break;
case STAR_POINT_SIZE_INCREASE_CMD:
float size = Math.min(STAR_POINT_SIZE + Constants.STEP_STAR_POINT_SIZE, Constants.MAX_STAR_POINT_SIZE);
EventManager.instance.post(Events.STAR_POINT_SIZE_CMD, size, false);
break;
case STAR_POINT_SIZE_DECREASE_CMD:
size = Math.max(STAR_POINT_SIZE - Constants.STEP_STAR_POINT_SIZE, Constants.MIN_STAR_POINT_SIZE);
EventManager.instance.post(Events.STAR_POINT_SIZE_CMD, size, false);
break;
case STAR_POINT_SIZE_RESET_CMD:
STAR_POINT_SIZE = STAR_POINT_SIZE_BAK;
break;
case STAR_MIN_OPACITY_CMD:
POINT_ALPHA_MIN = (float) data[0];
break;
case GALAXY_3D_CMD:
GALAXY_3D = (boolean) data[0];
break;
case CROSSHAIR_CMD:
CROSSHAIR = (boolean) data[0];
break;
case CAMERA_CINEMATIC_CMD:
CINEMATIC_CAMERA = (boolean) data[0];
break;
case CUBEMAP_RESOLUTION_CMD:
CUBEMAP_FACE_RESOLUTION = (int) data[0];
break;
default:
break;
}
}
public boolean isNormalLineRenderer() {
return LINE_RENDERER == 0;
}
public boolean isQuadLineRenderer() {
return LINE_RENDERER == 1;
}
public boolean isHighQuality() {
return GRAPHICS_QUALITY == 0;
}
public boolean isNormalQuality() {
return GRAPHICS_QUALITY == 1;
}
public boolean isLowQuality() {
return GRAPHICS_QUALITY == 2;
}
}
public static List<IConf> configurations;
public static FrameConf frame;
public static ScreenConf screen;
public static ProgramConf program;
public static DataConf data;
public static SceneConf scene;
public static RuntimeConf runtime;
public static ScreenshotConf screenshot;
public static PerformanceConf performance;
public static PostprocessConf postprocess;
public static ControlsConf controls;
public static SpacecraftConf spacecraft;
public static VersionConf version;
static boolean initialized = false;
public GlobalConf() {
super();
}
public static boolean initialized() {
return initialized;
}
/**
* Initialises the properties
*/
public static void initialize(VersionConf vc, ProgramConf pc, SceneConf sc, DataConf dc, RuntimeConf rc, PostprocessConf ppc, PerformanceConf pfc, FrameConf fc, ScreenConf scrc, ScreenshotConf shc, ControlsConf cc, SpacecraftConf scc) throws Exception {
if (!initialized) {
if (configurations == null) {
configurations = new ArrayList<IConf>();
}
version = vc;
program = pc;
scene = sc;
data = dc;
runtime = rc;
postprocess = ppc;
performance = pfc;
frame = fc;
screenshot = shc;
screen = scrc;
controls = cc;
spacecraft = scc;
configurations.add(program);
configurations.add(scene);
configurations.add(data);
configurations.add(runtime);
configurations.add(postprocess);
configurations.add(performance);
configurations.add(frame);
configurations.add(screenshot);
configurations.add(screen);
configurations.add(controls);
configurations.add(spacecraft);
initialized = true;
}
}
public static String getFullApplicationName() {
return APPLICATION_NAME + " - " + version.version;
}
} |
package com.ezardlabs.dethsquare;
import com.ezardlabs.dethsquare.Touch.TouchPhase;
import com.ezardlabs.dethsquare.util.GameListeners;
import com.ezardlabs.dethsquare.util.GameListeners.KeyListener;
import com.ezardlabs.dethsquare.util.GameListeners.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;
public final class Input {
static {
GameListeners.addMouseListener(new MouseListener() {
@Override
public void onMove(int x, int y) {
mousePosition.set(x, y);
}
@Override
public void onButtonDown(int index) {
switch(index) {
case 1:
setKeyDown(KeyCode.MOUSE_LEFT);
break;
case 2:
setKeyDown(KeyCode.MOUSE_MIDDLE);
break;
case 3:
setKeyDown(KeyCode.MOUSE_RIGHT);
break;
default:
break;
}
}
@Override
public void onButtonUp(int index) {
switch(index) {
case 1:
setKeyUp(KeyCode.MOUSE_LEFT);
break;
case 2:
setKeyUp(KeyCode.MOUSE_MIDDLE);
break;
case 3:
setKeyUp(KeyCode.MOUSE_RIGHT);
break;
default:
break;
}
}
});
GameListeners.addKeyListener(new KeyListener() {
@Override
public void onKeyDown(String key) {
setKeyDown(KeyCode.valueOf(key));
}
@Override
public void onKeyUp(String key) {
setKeyUp(KeyCode.valueOf(key));
}
});
GameListeners.addUpdateListener(Input::update);
}
public static final Vector2 mousePosition = new Vector2();
public static Touch[] touches = new Touch[0];
/**
* Each key that has been pressed either has a value of true if it has been pressed down in the current frame, or false if it's been held down for multiple frames
*/
private static HashMap<KeyCode, Integer> keys = new HashMap<>();
private static HashMap<KeyCode, Integer> keyChanges = new HashMap<>();
private static ArrayList<Holder> changesToMake = new ArrayList<>(10);
private static ArrayList<Touch> touchesToRemove = new ArrayList<>(10);
public enum KeyCode {
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
ALPHA_0,
ALPHA_1,
ALPHA_2,
ALPHA_3,
ALPHA_4,
ALPHA_5,
ALPHA_6,
ALPHA_7,
ALPHA_8,
ALPHA_9,
SPACE,
RETURN,
ESCAPE,
BACKSPACE,
DELETE,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
MOUSE_LEFT,
MOUSE_RIGHT,
MOUSE_MIDDLE
}
private static class Holder {
int id;
float x;
float y;
TouchPhase phase;
Holder(int id, float x, float y, TouchPhase phase) {
this.id = id;
this.x = x;
this.y = y;
this.phase = phase;
}
}
public static void update() {
Holder holder;
for (int i = 0; i < changesToMake.size(); i++) {
switch((holder = changesToMake.get(i)).phase) {
case BEGAN:
Touch[] temp = new Touch[touches.length + 1];
System.arraycopy(touches, 0, temp, 0, touches.length);
temp[touches.length] = new Touch(holder.id, new Vector2(holder.x, holder.y));
touches = temp;
break;
case MOVED:
for (Touch t : touches) {
if (t.fingerId == holder.id && t.lastModified < Time.frameCount) {
t.phase = Touch.TouchPhase.MOVED;
t.position.set(holder.x, holder.y);
t.lastModified = Time.frameCount;
}
}
break;
case STATIONARY:
break;
case ENDED:
for (Touch t : touches) {
if (t.fingerId == holder.id) {
t.phase = Touch.TouchPhase.ENDED;
t.position.set(holder.x, holder.y);
t.lastModified = Time.frameCount;
}
}
break;
case CANCELLED:
for (Touch t : touches) {
if (t.fingerId == holder.id) {
t.phase = Touch.TouchPhase.CANCELLED;
t.position.set(holder.x, holder.y);
t.lastModified = Time.frameCount;
}
}
break;
default:
break;
}
}
changesToMake.clear();
for (KeyCode keyCode : keys.keySet().toArray(new KeyCode[keys.size()])) {
switch (keys.get(keyCode)) {
case 0:
keys.put(keyCode, 1);
break;
case 2:
keys.remove(keyCode);
break;
default:
break;
}
}
keys.putAll(keyChanges);
keyChanges.clear();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < touches.length; i++) {
if ((touches[i].phase == Touch.TouchPhase.ENDED || touches[i].phase == Touch.TouchPhase.CANCELLED) && touches[i].lastModified < Time.frameCount) {
touchesToRemove.add(touches[i]);
} else if (touches[i].lastModified < Time.frameCount) {
touches[i].lastModified = Time.frameCount;
touches[i].phase = Touch.TouchPhase.STATIONARY;
}
}
if (!touchesToRemove.isEmpty()) {
Touch[] temp = new Touch[touches.length - touchesToRemove.size()];
int count = 0;
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < touches.length; i++) {
if (!touchesToRemove.contains(touches[i])) {
temp[count++] = touches[i];
}
}
touchesToRemove.clear();
touches = temp;
}
}
private static void setKeyDown(KeyCode keyCode) {
if (!keys.containsKey(keyCode)) keyChanges.put(keyCode, 0);
}
private static void setKeyUp(KeyCode keyCode) {
keyChanges.put(keyCode, 2);
}
public static boolean getKeyDown(KeyCode keyCode) {
return keys.containsKey(keyCode) && keys.get(keyCode) == 0;
}
public static boolean getKey(KeyCode keyCode) {
return keys.containsKey(keyCode) && keys.get(keyCode) < 2;
}
public static boolean getKeyUp(KeyCode keyCode) {
return keys.containsKey(keyCode) && keys.get(keyCode) == 2;
}
public static void addTouch(int id, float x, float y) {
changesToMake.add(new Holder(id, x, y, TouchPhase.BEGAN));
}
public static void moveTouch(int id, float x, float y) {
changesToMake.add(new Holder(id, x, y, TouchPhase.MOVED));
}
public static void removeTouch(int id, float x, float y) {
changesToMake.add(new Holder(id, x, y, TouchPhase.ENDED));
}
public static void cancelTouch(int id, float x, float y) {
changesToMake.add(new Holder(id, x, y, TouchPhase.CANCELLED));
}
} |
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 146. LRU Cache
*
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache(2);//capacity
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
*/
public class _146 {
public class LinkedHashMapSolution {
private Map<Integer, Integer> cache;
private final int max;
public LinkedHashMapSolution(int capacity) {
max = capacity;
cache = new LinkedHashMap<Integer, Integer>(capacity, 1.0f, true) {
public boolean removeEldestEntry(Map.Entry eldest) {
return cache.size() > max;
}
};
}
public int get(int key) {
return cache.getOrDefault(key, -1);
}
public void set(int key, int value) {
cache.put(key, value);
}
}
public class DoublyLinkedListPlusHashMapSolution {
private class Node {
int key, value;
DoublyLinkedListPlusHashMapSolution.Node prev, next;
Node(int k, int v) {
this.key = k;
this.value = v;
}
Node() {
this.key = 0;
this.value = 0;
}
}
private int capacity;
private int count;
private DoublyLinkedListPlusHashMapSolution.Node head, tail;
private Map<Integer, DoublyLinkedListPlusHashMapSolution.Node> map;
// ATTN: the value should be Node type! This is the whole point of having a class called Node!
public DoublyLinkedListPlusHashMapSolution(int capacity) {
this.capacity = capacity;
this.count = 0;// we need a count to keep track of the number of elements in the cache so
// that we know when to evict the LRU one from the cache
this.map = new HashMap();
head = new DoublyLinkedListPlusHashMapSolution.Node();
tail = new DoublyLinkedListPlusHashMapSolution.Node();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DoublyLinkedListPlusHashMapSolution.Node node = map.get(key);
// HashMap allows value to be null, this is superior than HashTable!
if (node == null) {
return -1;
} else {
/**Do two operations: this makes the process more clear:
* remove the old node first, and then
* just add the node again.
* This will guarantee that this node will be at the latest position:
* the most recently used position.*/
remove(node);
add(node);
return node.value;
}
}
public void set(int key, int value) {
DoublyLinkedListPlusHashMapSolution.Node node = map.get(key);
if (node == null) {
node = new DoublyLinkedListPlusHashMapSolution.Node(key, value);
map.put(key, node);
add(node);
count++;
if (count > capacity) {
/** ATTN: It's tail.prev, not tail, because tail is always an invalid node, it
doesn't contain anything, it's always the tail.prev that is the last node in the
cache*/
DoublyLinkedListPlusHashMapSolution.Node toDelete = tail.prev;
map.remove(toDelete.key);
remove(toDelete);
count
}
} else {
remove(node);
node.value = value;
add(node);
}
}
private void remove(DoublyLinkedListPlusHashMapSolution.Node node) {
DoublyLinkedListPlusHashMapSolution.Node next = node.next, prev = node.prev;
prev.next = next;
next.prev = prev;
}
private void add(DoublyLinkedListPlusHashMapSolution.Node node) {
// ATTN: we'll always add the node into the first position: head.next!!!!
DoublyLinkedListPlusHashMapSolution.Node next = head.next;
head.next = node;
node.next = next;
node.prev = head;
next.prev = node;
}
}
} |
package com.onelogin.saml2.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.XMLConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.EncryptedKey;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.XMLUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISOPeriodFormat;
import org.joda.time.format.PeriodFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.onelogin.saml2.exception.ValidationError;
import com.onelogin.saml2.exception.XMLEntityException;
/**
* Util class of OneLogin's Java Toolkit.
*
* A class that contains several auxiliary methods related to the SAML protocol
*/
public final class Util {
/**
* Private property to construct a logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(Util.class);
private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(DateTimeZone.UTC);
private static final DateTimeFormatter DATE_TIME_FORMAT_MILLS = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
public static final String UNIQUE_ID_PREFIX = "ONELOGIN_";
public static final String RESPONSE_SIGNATURE_XPATH = "/samlp:Response/ds:Signature";
public static final String ASSERTION_SIGNATURE_XPATH = "/samlp:Response/saml:Assertion/ds:Signature";
/** Indicates if JAXP 1.5 support has been detected. */
private static boolean JAXP_15_SUPPORTED = isJaxp15Supported();
private Util() {
//not called
}
public static boolean isJaxp15Supported() {
boolean supported = true;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "file");
} catch (SAXException ex) {
String err = ex.getMessage();
if (err.contains("Property 'http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.")) {
//expected, jaxp 1.5 not supported
supported = false;
}
} catch (Exception e) {
LOGGER.info("An exception occurred while trying to determine if JAXP 1.5 options are supported.", e);
}
return supported;
}
/**
* This function load an XML string in a save way. Prevent XEE/XXE Attacks
*
* @param xml
* String. The XML string to be loaded.
*
* @return The result of load the XML at the Document or null if any error occurs
*/
public static Document loadXML(String xml) {
try {
if (xml.contains("<!ENTITY")) {
throw new XMLEntityException("Detected use of ENTITY in XML, disabled to prevent XXE/XEE attacks");
}
return convertStringToDocument(xml);
} catch (XMLEntityException e) {
LOGGER.debug("Load XML error due XMLEntityException.", e);
} catch (Exception e) {
LOGGER.debug("Load XML error: " + e.getMessage(), e);
}
return null;
}
/**
* Extracts a node from the DOMDocument
*
* @param dom
* The DOMDocument
* @param query
* Xpath Expression
* @param context
* Context Node (DomElement)
*
* @return DOMNodeList The queried node
*
* @throws XPathExpressionException
*/
public static NodeList query(Document dom, String query, Node context) throws XPathExpressionException {
NodeList nodeList;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
String result = null;
if (prefix.equals("samlp") || prefix.equals("samlp2")) {
result = Constants.NS_SAMLP;
} else if (prefix.equals("saml") || prefix.equals("saml2")) {
result = Constants.NS_SAML;
} else if (prefix.equals("ds")) {
result = Constants.NS_DS;
} else if (prefix.equals("xenc")) {
result = Constants.NS_XENC;
} else if (prefix.equals("md")) {
result = Constants.NS_MD;
}
return result;
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@SuppressWarnings("rawtypes")
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
});
if (context == null) {
nodeList = (NodeList) xpath.evaluate(query, dom, XPathConstants.NODESET);
} else {
nodeList = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET);
}
return nodeList;
}
/**
* Extracts a node from the DOMDocument
*
* @param dom
* The DOMDocument
* @param query
* Xpath Expression
*
* @return DOMNodeList The queried node
*
* @throws XPathExpressionException
*/
public static NodeList query(Document dom, String query) throws XPathExpressionException {
return query(dom, query, null);
}
/**
* This function attempts to validate an XML against the specified schema.
*
* @param xmlDocument
* The XML document which should be validated
* @param schemaUrl
* The schema filename which should be used
*
* @return found errors after validation
*/
public static boolean validateXML(Document xmlDocument, URL schemaUrl) {
try {
if (xmlDocument == null) {
throw new IllegalArgumentException("xmlDocument was null");
}
Schema schema = SchemaFactory.loadFromUrl(schemaUrl);
Validator validator = schema.newValidator();
if (JAXP_15_SUPPORTED) {
// Prevent XXE attacks
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
}
XMLErrorAccumulatorHandler errorAcumulator = new XMLErrorAccumulatorHandler();
validator.setErrorHandler(errorAcumulator);
Source xmlSource = new DOMSource(xmlDocument);
validator.validate(xmlSource);
final boolean isValid = !errorAcumulator.hasError();
if (!isValid) {
LOGGER.warn("Errors found when validating SAML response with schema: " + errorAcumulator.getErrorXML());
}
return isValid;
} catch (Exception e) {
LOGGER.warn("Error executing validateXML: " + e.getMessage(), e);
return false;
}
}
/**
* Converts an XML in string format in a Document object
*
* @param xmlStr
* The XML string which should be converted
*
* @return the Document object
*
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static Document convertStringToDocument(String xmlStr) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory docfactory = DocumentBuilderFactory.newInstance();
docfactory.setNamespaceAware(true);
// do not expand entity reference nodes
docfactory.setExpandEntityReferences(false);
docfactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Add various options explicitly to prevent XXE attacks.
// (adding try/catch around every setAttribute just in case a specific parser does not support it.
try {
// do not include external general entities
docfactory.setAttribute("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
} catch (Throwable e) {}
try {
// do not include external parameter entities or the external DTD subset
docfactory.setAttribute("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
} catch (Throwable e) {}
try {
docfactory.setAttribute("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
} catch (Throwable e) {}
try {
docfactory.setAttribute("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE);
} catch (Throwable e) {}
try {
// ignore the external DTD completely
docfactory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
} catch (Throwable e) {}
try {
// build the grammar but do not use the default attributes and attribute types information it contains
docfactory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", Boolean.FALSE);
} catch (Throwable e) {}
try {
docfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (Throwable e) {}
DocumentBuilder builder = docfactory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
// Loop through the doc and tag every element with an ID attribute
// as an XML ID node.
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr;
try {
/**
* Converts an XML in Document format in a String
*
* @param doc
* The Document object
* @param c14n
* If c14n transformation should be applied
*
* @return the Document object
*/
public static String convertDocumentToString(Document doc, Boolean c14n) {
org.apache.xml.security.Init.init();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (c14n) {
XMLUtils.outputDOMc14nWithComments(doc, baos);
} else {
XMLUtils.outputDOM(doc, baos);
}
return Util.toStringUtf8(baos.toByteArray());
}
/**
* Converts an XML in Document format in a String without applying the c14n transformation
*
* @param doc
* The Document object
*
* @return the Document object
*/
public static String convertDocumentToString(Document doc) {
return convertDocumentToString(doc, false);
}
/**
* Returns a certificate in String format (adding header and footer if required)
*
* @param cert
* A x509 unformatted cert
* @param heads
* True if we want to include head and footer
*
* @return X509Certificate $x509 Formated cert
*/
public static String formatCert(String cert, Boolean heads) {
String x509cert = StringUtils.EMPTY;
if (cert != null) {
x509cert = cert.replace("\\x0D", "").replace("\r", "").replace("\n", "").replace(" ", "");
if (!StringUtils.isEmpty(x509cert)) {
x509cert = x509cert.replace("
if (heads) {
x509cert = "
}
}
}
return x509cert;
}
/**
* Returns a private key (adding header and footer if required).
*
* @param key
* A private key
* @param heads
* True if we want to include head and footer
*
* @return Formated private key
*/
public static String formatPrivateKey(String key, boolean heads) {
String xKey = StringUtils.EMPTY;
if (key != null) {
xKey = key.replace("\\x0D", "").replace("\r", "").replace("\n", "").replace(" ", "");
if (!StringUtils.isEmpty(xKey)) {
if (xKey.startsWith("
xKey = xKey.replace("
if (heads) {
xKey = "
}
} else {
xKey = xKey.replace("
if (heads) {
xKey = "
}
}
}
}
return xKey;
}
/**
* chunk a string
*
* @param str
* The string to be chunked
* @param chunkSize
* The chunk size
*
* @return the chunked string
*/
private static String chunkString(String str, int chunkSize) {
String newStr = StringUtils.EMPTY;
int stringLength = str.length();
for (int i = 0; i < stringLength; i += chunkSize) {
if (i + chunkSize > stringLength) {
chunkSize = stringLength - i;
}
newStr += str.substring(i, chunkSize + i) + '\n';
}
return newStr;
}
/**
* Load X.509 certificate
*
* @param certString
* certificate in string format
*
* @return Loaded Certificate. X509Certificate object
*
* @throws UnsupportedEncodingException
* @throws CertificateException
*
*/
public static X509Certificate loadCert(String certString) throws CertificateException, UnsupportedEncodingException {
certString = formatCert(certString, true);
X509Certificate cert;
try {
cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(
new ByteArrayInputStream(certString.getBytes("utf-8")));
} catch (IllegalArgumentException e){
cert = null;
}
return cert;
}
/**
* Load private key
*
* @param keyString
* private key in string format
*
* @return Loaded private key. PrivateKey object
*
* @throws GeneralSecurityException
* @throws IOException
*/
public static PrivateKey loadPrivateKey(String keyString) throws GeneralSecurityException, IOException {
org.apache.xml.security.Init.init();
keyString = formatPrivateKey(keyString, false);
keyString = chunkString(keyString, 64);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey;
try {
byte[] encoded = Base64.decodeBase64(keyString);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
privKey = (PrivateKey) kf.generatePrivate(keySpec);
}
catch(IllegalArgumentException e) {
privKey = null;
}
return privKey;
}
/**
* Calculates the fingerprint of a x509cert
*
* @param x509cert
* x509 certificate
* @param alg
* Digest Algorithm
*
* @return the formated fingerprint
*/
public static String calculateX509Fingerprint(X509Certificate x509cert, String alg) {
String fingerprint = StringUtils.EMPTY;
try {
byte[] dataBytes = x509cert.getEncoded();
if (alg == null || alg.isEmpty() || alg.equals("SHA-1")|| alg.equals("sha1")) {
fingerprint = DigestUtils.sha1Hex(dataBytes);
} else if (alg.equals("SHA-256") || alg .equals("sha256")) {
fingerprint = DigestUtils.sha256Hex(dataBytes);
} else if (alg.equals("SHA-384") || alg .equals("sha384")) {
fingerprint = DigestUtils.sha384Hex(dataBytes);
} else if (alg.equals("SHA-512") || alg.equals("sha512")) {
fingerprint = DigestUtils.sha512Hex(dataBytes);
} else {
LOGGER.debug("Error executing calculateX509Fingerprint. alg " + alg + " not supported");
}
} catch (Exception e) {
LOGGER.debug("Error executing calculateX509Fingerprint: "+ e.getMessage(), e);
}
return fingerprint.toLowerCase();
}
/**
* Calculates the SHA-1 fingerprint of a x509cert
*
* @param x509cert
* x509 certificate
*
* @return the SHA-1 formated fingerprint
*/
public static String calculateX509Fingerprint(X509Certificate x509cert) {
return calculateX509Fingerprint(x509cert, "SHA-1");
}
/**
* Converts an X509Certificate in a well formated PEM string
*
* @param certificate
* The public certificate
*
* @return the formated PEM string
*/
public static String convertToPem(X509Certificate certificate) {
String pemCert = "";
try {
Base64 encoder = new Base64(64);
String cert_begin = "
String end_cert = "
byte[] derCert = certificate.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
pemCert = cert_begin + pemCertPre + end_cert;
} catch (Exception e) {
LOGGER.debug("Error converting certificate on PEM format: "+ e.getMessage(), e);
}
return pemCert;
}
/**
* Loads a resource located at a relative path
*
* @param relativeResourcePath
* Relative path of the resource
*
* @return the loaded resource in String format
*
* @throws IOException
*/
public static String getFileAsString(String relativeResourcePath) throws IOException {
InputStream is = Util.class.getResourceAsStream("/" + relativeResourcePath);
if (is == null) {
throw new FileNotFoundException(relativeResourcePath);
}
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
copyBytes(new BufferedInputStream(is), bytes);
return bytes.toString("utf-8");
} finally {
is.close();
}
}
private static void copyBytes(InputStream is, OutputStream bytes) throws IOException {
int res = is.read();
while (res != -1) {
bytes.write(res);
res = is.read();
}
}
/**
* Returns String Base64 decoded and inflated
*
* @param input
* String input
*
* @return the base64 decoded and inflated string
*/
public static String base64decodedInflated(String input) {
// Base64 decoder
byte[] decoded = Base64.decodeBase64(input);
// Inflater
try {
Inflater decompresser = new Inflater(true);
decompresser.setInput(decoded);
byte[] result = new byte[2048];
int resultLength = decompresser.inflate(result);
decompresser.end();
String inflated = new String(result, 0, resultLength, "UTF-8");
return inflated;
} catch (Exception e) {
return new String(decoded);
}
}
/**
* Returns String Deflated and base64 encoded
*
* @param input
* String input
*
* @return the deflated and base64 encoded string
* @throws IOException
*/
public static String deflatedBase64encoded(String input) throws IOException {
// Deflater
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
deflaterStream.write(input.getBytes(Charset.forName("UTF-8")));
deflaterStream.finish();
// Base64 encoder
return new String(Base64.encodeBase64(bytesOut.toByteArray()));
}
/**
* Returns String base64 encoded
*
* @param input
* Stream input
*
* @return the base64 encoded string
*/
public static String base64encoder(byte [] input) {
return toStringUtf8(Base64.encodeBase64(input));
}
/**
* Returns String base64 encoded
*
* @param input
* String input
*
* @return the base64 encoded string
*/
public static String base64encoder(String input) {
return base64encoder(toBytesUtf8(input));
}
/**
* Returns String base64 decoded
*
* @param input
* Stream input
*
* @return the base64 decoded bytes
*/
public static byte[] base64decoder(byte [] input) {
return Base64.decodeBase64(input);
}
/**
* Returns String base64 decoded
*
* @param input
* String input
*
* @return the base64 decoded bytes
*/
public static byte[] base64decoder(String input) {
return base64decoder(toBytesUtf8(input));
}
/**
* Returns String URL encoded
*
* @param input
* String input
*
* @return the URL encoded string
*/
public static String urlEncoder(String input) {
if (input != null) {
try {
return URLEncoder.encode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("URL encoder error.", e);
throw new IllegalArgumentException();
}
} else {
return null;
}
}
/**
* Returns String URL decoded
*
* @param input
* URL encoded input
*
* @return the URL decoded string
*/
public static String urlDecoder(String input) {
if (input != null) {
try {
return URLDecoder.decode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("URL decoder error.", e);
throw new IllegalArgumentException();
}
} else {
return null;
}
}
/**
* Generates a signature from a string
*
* @param text
* The string we should sign
* @param key
* The private key to sign the string
* @param signAlgorithm
* Signature algorithm method
*
* @return the signature
*
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static byte[] sign(String text, PrivateKey key, String signAlgorithm) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
org.apache.xml.security.Init.init();
if (signAlgorithm == null) {
signAlgorithm = Constants.RSA_SHA1;
}
Signature instance = Signature.getInstance(signatureAlgConversion(signAlgorithm));
instance.initSign(key);
instance.update(text.getBytes());
byte[] signature = instance.sign();
return signature;
}
/**
* Converts Signature algorithm method name
*
* @param sign
* signature algorithm method
*
* @return the converted signature name
*/
public static String signatureAlgConversion(String sign) {
String convertedSignatureAlg = "";
if (sign == null) {
convertedSignatureAlg = "SHA1withRSA";
} else if (sign.equals(Constants.DSA_SHA1)) {
convertedSignatureAlg = "SHA1withDSA";
} else if (sign.equals(Constants.RSA_SHA256)) {
convertedSignatureAlg = "SHA256withRSA";
} else if (sign.equals(Constants.RSA_SHA384)) {
convertedSignatureAlg = "SHA384withRSA";
} else if (sign.equals(Constants.RSA_SHA512)) {
convertedSignatureAlg = "SHA512withRSA";
} else {
convertedSignatureAlg = "SHA1withRSA";
}
return convertedSignatureAlg;
}
/**
* Validate the signature pointed to by the xpath
*
* @param doc The document we should validate
* @param cert The public certificate
* @param fingerprint The fingerprint of the public certificate
* @param alg The signature algorithm method
* @param xpath the xpath of the ds:Signture node to validate
*
* @return True if the signature exists and is valid, false otherwise.
*/
public static boolean validateSign(final Document doc, final X509Certificate cert, final String fingerprint,
final String alg, final String xpath) {
try {
final NodeList signatures = query(doc, xpath);
return signatures.getLength() == 1 && validateSignNode(signatures.item(0), cert, fingerprint, alg);
} catch (XPathExpressionException e) {
LOGGER.warn("Failed to find signature nodes", e);
}
return false;
}
/**
* Validate signature (Metadata).
*
* @param doc
* The document we should validate
* @param cert
* The public certificate
* @param fingerprint
* The fingerprint of the public certificate
* @param alg
* The signature algorithm method
*
* @return True if the sign is valid, false otherwise.
*/
public static Boolean validateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg) {
NodeList signNodesToValidate;
try {
signNodesToValidate = query(doc, "/md:EntitiesDescriptor/ds:Signature");
if (signNodesToValidate.getLength() == 0) {
signNodesToValidate = query(doc, "/md:EntityDescriptor/ds:Signature");
if (signNodesToValidate.getLength() == 0) {
signNodesToValidate = query(doc, "/md:EntityDescriptor/md:SPSSODescriptor/ds:Signature|/md:EntityDescriptor/IDPSSODescriptor/ds:Signature");
}
}
if (signNodesToValidate.getLength() > 0) {
for (int i = 0; i < signNodesToValidate.getLength(); i++) {
Node signNode = signNodesToValidate.item(i);
if (!validateSignNode(signNode, cert, fingerprint, alg)) {
return false;
}
}
return true;
}
} catch (XPathExpressionException e) {
LOGGER.warn("Failed to find signature nodes", e);
}
return false;
}
/**
* Validate signature of the Node.
*
* @param signNode
* The document we should validate
* @param cert
* The public certificate
* @param fingerprint
* The fingerprint of the public certificate
* @param alg
* The signature algorithm method
*
* @return True if the sign is valid, false otherwise.
*/
public static Boolean validateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg) {
Boolean res = false;
try {
org.apache.xml.security.Init.init();
Element sigElement = (Element) signNode;
XMLSignature signature = new XMLSignature(sigElement, "", true);
if (cert != null) {
res = signature.checkSignatureValue(cert);
} else {
KeyInfo keyInfo = signature.getKeyInfo();
if (keyInfo != null && keyInfo.containsX509Data()) {
X509Certificate providedCert = keyInfo.getX509Certificate();
if (fingerprint.equals(calculateX509Fingerprint(providedCert, alg))) {
res = signature.checkSignatureValue(providedCert);
}
}
}
} catch (Exception e) {
LOGGER.warn("Error executing validateSignNode: " + e.getMessage(), e);
}
return res;
}
/**
* Decrypt an encrypted element.
*
* @param encryptedDataElement
* The encrypted element.
* @param inputKey
* The private key to decrypt.
*/
public static void decryptElement(Element encryptedDataElement, PrivateKey inputKey) {
try {
org.apache.xml.security.Init.init();
XMLCipher xmlCipher = XMLCipher.getInstance();
xmlCipher.init(XMLCipher.DECRYPT_MODE, null);
/* Check if we have encryptedData with a KeyInfo that contains a RetrievalMethod to obtain the EncryptedKey.
xmlCipher is not able to handle that so we move the EncryptedKey inside the KeyInfo element and
replacing the RetrievalMethod.
*/
NodeList keyInfoInEncData = encryptedDataElement.getElementsByTagNameNS(Constants.NS_DS, "KeyInfo");
if (keyInfoInEncData.getLength() == 0) {
throw new ValidationError("No KeyInfo inside EncryptedData element", ValidationError.KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA);
}
NodeList childs = keyInfoInEncData.item(0).getChildNodes();
for (int i=0; i < childs.getLength(); i++) {
if (childs.item(i).getLocalName() != null && childs.item(i).getLocalName().equals("RetrievalMethod")) {
Element retrievalMethodElem = (Element)childs.item(i);
if (!retrievalMethodElem.getAttribute("Type").equals("http://www.w3.org/2001/04/xmlenc#EncryptedKey")) {
throw new ValidationError("Unsupported Retrieval Method found", ValidationError.UNSUPPORTED_RETRIEVAL_METHOD);
}
String uri = retrievalMethodElem.getAttribute("URI").substring(1);
NodeList encryptedKeyNodes = ((Element) encryptedDataElement.getParentNode()).getElementsByTagNameNS(Constants.NS_XENC, "EncryptedKey");
for (int j=0; j < encryptedKeyNodes.getLength(); j++) {
if (((Element)encryptedKeyNodes.item(j)).getAttribute("Id").equals(uri)) {
keyInfoInEncData.item(0).replaceChild(encryptedKeyNodes.item(j), childs.item(i));
}
}
}
}
xmlCipher.setKEK(inputKey);
xmlCipher.doFinal(encryptedDataElement.getOwnerDocument(), encryptedDataElement, false);
} catch (Exception e) {
LOGGER.warn("Error executing decryption: " + e.getMessage(), e);
}
}
/**
* Clone a Document object.
*
* @param source
* The Document object to be cloned.
*
* @return the clone of the Document object
*
* @throws ParserConfigurationException
*/
public static Document copyDocument(Document source) throws ParserConfigurationException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Node originalRoot = source.getDocumentElement();
Document copiedDocument = db.newDocument();
Node copiedRoot = copiedDocument.importNode(originalRoot, true);
copiedDocument.appendChild(copiedRoot);
return copiedDocument;
}
/**
* Signs the Document using the specified signature algorithm with the private key and the public certificate.
*
* @param document
* The document to be signed
* @param key
* The private key
* @param certificate
* The public certificate
* @param signAlgorithm
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws XMLSecurityException
* @throws XPathExpressionException
*/
public static String addSign(Document document, PrivateKey key, X509Certificate certificate, String signAlgorithm) throws XMLSecurityException, XPathExpressionException {
org.apache.xml.security.Init.init();
// Check arguments.
if (document == null) {
throw new IllegalArgumentException("Provided document was null");
}
if (document.getDocumentElement() == null) {
throw new IllegalArgumentException("The Xml Document has no root element.");
}
if (key == null) {
throw new IllegalArgumentException("Provided key was null");
}
if (certificate == null) {
throw new IllegalArgumentException("Provided certificate was null");
}
if (signAlgorithm == null || signAlgorithm.isEmpty()) {
signAlgorithm = Constants.RSA_SHA1;
}
// document.normalizeDocument();
String c14nMethod = Constants.C14N_WC;
// Signature object
XMLSignature sig = new XMLSignature(document, null, signAlgorithm, c14nMethod);
// Including the signature into the document before sign, because
// this is an envelop signature
Element root = document.getDocumentElement();
document.setXmlStandalone(false);
// If Issuer, locate Signature after Issuer, Otherwise as first child.
NodeList issuerNodes = Util.query(document, "//saml:Issuer", null);
if (issuerNodes.getLength() > 0) {
Node issuer = issuerNodes.item(0);
root.insertBefore(sig.getElement(), issuer.getNextSibling());
} else {
root.insertBefore(sig.getElement(), root.getFirstChild());
}
String id = root.getAttribute("ID");
String reference = id;
if (!id.isEmpty()) {
root.setIdAttributeNS(null, "ID", true);
reference = "
}
// Create the transform for the document
Transforms transforms = new Transforms(document);
transforms.addTransform(Constants.ENVSIG);
//transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS);
transforms.addTransform(c14nMethod);
sig.addDocument(reference, transforms, Constants.SHA1);
// Add the certification info
sig.addKeyInfo(certificate);
// Sign the document
sig.sign(key);
return convertDocumentToString(document, true);
}
/**
* Signs a Node using the specified signature algorithm with the private key and the public certificate.
*
* @param node
* The Node to be signed
* @param key
* The private key
* @param certificate
* The public certificate
* @param signAlgorithm
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws ParserConfigurationException
* @throws XMLSecurityException
* @throws XPathExpressionException
*/
public static String addSign(Node node, PrivateKey key, X509Certificate certificate, String signAlgorithm) throws ParserConfigurationException, XPathExpressionException, XMLSecurityException {
// Check arguments.
if (node == null) {
throw new IllegalArgumentException("Provided node was null");
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
Node newNode = doc.importNode(node, true);
doc.appendChild(newNode);
return addSign(doc, key, certificate, signAlgorithm);
}
/**
* Validates signed binary data (Used to validate GET Signature).
*
* @param signedQuery
* The element we should validate
* @param signature
* The signature that will be validate
* @param cert
* The public certificate
* @param signAlg
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static Boolean validateBinarySignature(String signedQuery, byte[] signature, X509Certificate cert, String signAlg) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
Boolean valid = false;
try {
org.apache.xml.security.Init.init();
String convertedSigAlg = signatureAlgConversion(signAlg);
Signature sig = Signature.getInstance(convertedSigAlg); //, provider);
sig.initVerify(cert.getPublicKey());
sig.update(signedQuery.getBytes());
valid = sig.verify(signature);
} catch (Exception e) {
LOGGER.warn("Error executing validateSign: " + e.getMessage(), e);
}
return valid;
}
/**
* Generates a nameID.
*
* @param value
* The value
* @param spnq
* SP Name Qualifier
* @param format
* SP Format
* @param cert
* IdP Public certificate to encrypt the nameID
*
* @return Xml contained in the document.
*/
public static String generateNameId(String value, String spnq, String format, X509Certificate cert) {
String res = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
Element nameId = doc.createElement("saml:NameID");
if (spnq != null && !spnq.isEmpty()) {
nameId.setAttribute("SPNameQualifier", spnq);
}
if (format != null && !format.isEmpty()) {
nameId.setAttribute("Format", format);
}
nameId.appendChild(doc.createTextNode(value));
doc.appendChild(nameId);
if (cert != null) {
// We generate a symmetric key
Key symmetricKey = generateSymmetricKey();
// cipher for encrypt the data
XMLCipher xmlCipher = XMLCipher.getInstance(Constants.AES128_CBC);
xmlCipher.init(XMLCipher.ENCRYPT_MODE, symmetricKey);
// cipher for encrypt the symmetric key
XMLCipher keyCipher = XMLCipher.getInstance(Constants.RSA_1_5);
keyCipher.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
// encrypt the symmetric key
EncryptedKey encryptedKey = keyCipher.encryptKey(doc, symmetricKey);
// Add keyinfo inside the encrypted data
EncryptedData encryptedData = xmlCipher.getEncryptedData();
KeyInfo keyInfo = new KeyInfo(doc);
keyInfo.add(encryptedKey);
encryptedData.setKeyInfo(keyInfo);
// Encrypt the actual data
xmlCipher.doFinal(doc, nameId, false);
// Building the result
res = "<saml:EncryptedID>" + convertDocumentToString(doc) + "</saml:EncryptedID>";
} else {
res = convertDocumentToString(doc);
}
} catch (Exception e) {
LOGGER.error("Error executing generateNameId: " + e.getMessage(), e);
}
return res;
}
/**
* Generates a nameID.
*
* @param value
* The value
* @param spnq
* SP Name Qualifier
* @param format
* SP Format
*
* @return Xml contained in the document.
*/
public static String generateNameId(String value, String spnq, String format) {
return generateNameId(value, spnq, format, null);
}
/**
* Method to generate a symmetric key for encryption
*
* @return the symmetric key
*
* @throws Exception
*/
private static SecretKey generateSymmetricKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
}
/**
* Generates a unique string (used for example as ID of assertions)
*
* @return A unique string
*/
public static String generateUniqueID() {
return UNIQUE_ID_PREFIX + UUID.randomUUID();
}
public static long parseDuration(String duration) throws IllegalArgumentException {
TimeZone timeZone = DateTimeZone.UTC.toTimeZone();
return parseDuration(duration, Calendar.getInstance(timeZone).getTimeInMillis() / 1000);
}
public static long parseDuration(String durationString, long timestamp) throws IllegalArgumentException {
boolean haveMinus = false;
if (durationString.startsWith("-")) {
durationString = durationString.substring(1);
haveMinus = true;
}
PeriodFormatter periodFormatter = ISOPeriodFormat.standard().withLocale(new Locale("UTC"));
Period period = periodFormatter.parsePeriod(durationString);
DateTime dt = new DateTime(timestamp * 1000, DateTimeZone.UTC);
DateTime result = null;
if (haveMinus) {
result = dt.minus(period);
} else {
result = dt.plus(period);
}
return result.getMillis() / 1000;
}
/**
* @return the unix timestamp that matches the current time.
*/
public static Long getCurrentTimeStamp() {
DateTime currentDate = new DateTime(DateTimeZone.UTC);
return currentDate.getMillis() / 1000;
}
/**
* Compare 2 dates and return the the earliest
*
* @param cacheDuration
* The duration, as a string.
* @param validUntil
* The valid until date, as a string
*
* @return the expiration time (timestamp format).
*/
public static long getExpireTime(String cacheDuration, String validUntil) {
long expireTime = 0;
try {
if (cacheDuration != null && !StringUtils.isEmpty(cacheDuration)) {
expireTime = parseDuration(cacheDuration);
}
if (validUntil != null && !StringUtils.isEmpty(validUntil)) {
DateTime dt = Util.parseDateTime(validUntil);
long validUntilTimeInt = dt.getMillis() / 1000;
if (expireTime == 0 || expireTime > validUntilTimeInt) {
expireTime = validUntilTimeInt;
}
}
} catch (Exception e) {
LOGGER.error("Error executing getExpireTime: " + e.getMessage(), e);
}
return expireTime;
}
/**
* Compare 2 dates and return the the earliest
*
* @param cacheDuration
* The duration, as a string.
* @param validUntil
* The valid until date, as a timestamp
*
* @return the expiration time (timestamp format).
*/
public static long getExpireTime(String cacheDuration, long validUntil) {
long expireTime = 0;
try {
if (cacheDuration != null && !StringUtils.isEmpty(cacheDuration)) {
expireTime = parseDuration(cacheDuration);
}
if (expireTime == 0 || expireTime > validUntil) {
expireTime = validUntil;
}
} catch (Exception e) {
LOGGER.error("Error executing getExpireTime: " + e.getMessage(), e);
}
return expireTime;
}
/**
* Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZ
*
* @param timeInMillis
* The time in Millis
*
* @return string with format yyyy-MM-ddTHH:mm:ssZ
*/
public static String formatDateTime(long timeInMillis) {
return DATE_TIME_FORMAT.print(timeInMillis);
}
/**
* Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZ
*
* @param time
* The time
* @param millis
* Defines if the time is in Millis
*
* @return string with format yyyy-MM-ddTHH:mm:ssZ
*/
public static String formatDateTime(long time, boolean millis) {
if (millis) {
return DATE_TIME_FORMAT_MILLS.print(time);
} else {
return formatDateTime(time);
}
}
/**
* Create calendar form string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
*
* @param dateTime
* string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
*
* @return datetime
*/
public static DateTime parseDateTime(String dateTime) {
DateTime parsedData = null;
try {
parsedData = DATE_TIME_FORMAT.parseDateTime(dateTime);
} catch(Exception e) {
return DATE_TIME_FORMAT_MILLS.parseDateTime(dateTime);
}
return parsedData;
}
private static String toStringUtf8(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
private static byte[] toBytesUtf8(String str) {
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.List;
/**
* 147. Insertion Sort List
*
* Sort a linked list using insertion sort.
*
* Algorithm of Insertion Sort:
*
* Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
* At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
* It repeats until no input elements remain.
*
*
* Example 1:
*
* Input: 4->2->1->3
* Output: 1->2->3->4
*
* Example 2:
*
* Input: -1->5->3->4->0
* Output: -1->0->3->4->5
*/
public class _147 {
public static class Solution1 {
public ListNode insertionSortList(ListNode head) {
ListNode temp = head;
List<Integer> list = new ArrayList<>();
while (temp != null) {
list.add(temp.val);
temp = temp.next;
}
Integer[] nums = list.toArray(new Integer[list.size()]);
for (int i = 1; i < list.size(); i++) {
for (int j = i - 1; j >= 0; j
if (nums[j] > nums[j + 1]) {
int tempNum = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tempNum;
}
}
}
ListNode newHead = head;
for (int i = 0; i < nums.length; i++) {
newHead.val = nums[i];
newHead = newHead.next;
}
return head;
}
}
} |
// Triple Play - utilities for use in PlayN-based games
package tripleplay.util;
import react.Function;
import react.IntValue;
import react.RSet;
import react.Slot;
import react.Value;
import playn.core.Storage;
import static playn.core.PlayN.log;
/**
* Makes using PlayN {@link Storage} more civilized. Provides getting and setting of typed values
* (ints, booleans, etc.). Provides support for default values. Provides {@link Value} interface to
* storage items.
*/
public class TypedStorage
{
public TypedStorage (Storage storage) {
_storage = storage;
}
/**
* Returns whether the specified key is mapped to some value.
*/
public boolean contains (String key) {
return _storage.getItem(key) != null;
}
/**
* Returns the specified property as a string, returning null if the property does not exist.
*/
public String get (String key) {
return _storage.getItem(key);
}
/**
* Returns the specified property as a string, returning the supplied defautl value if the
* property does not exist.
*/
public String get (String key, String defval) {
String value = _storage.getItem(key);
return (value == null) ? defval : value;
}
/**
* Sets the specified property to the supplied string value.
*/
public void set (String key, String value) {
_storage.setItem(key, value);
}
/**
* Returns the specified property as an int. If the property does not exist, the default value
* will be returned. If the property cannot be parsed as an int, an error will be logged and
* the default value will be returned.
*/
public int get (String key, int defval) {
String value = null;
try {
value = _storage.getItem(key);
return (value == null) ? defval : Integer.parseInt(value);
} catch (Exception e) {
log().warn("Failed to parse int prop [key=" + key + ", value=" + value + "]", e);
return defval;
}
}
/**
* Sets the specified property to the supplied int value.
*/
public void set (String key, int value) {
_storage.setItem(key, String.valueOf(value));
}
/**
* Returns the specified property as a long. If the property does not exist, the default value
* will be returned. If the property cannot be parsed as a long, an error will be logged and
* the default value will be returned.
*/
public long get (String key, long defval) {
String value = null;
try {
value = _storage.getItem(key);
return (value == null) ? defval : Long.parseLong(value);
} catch (Exception e) {
log().warn("Failed to parse long prop [key=" + key + ", value=" + value + "]", e);
return defval;
}
}
/**
* Sets the specified property to the supplied long value.
*/
public void set (String key, long value) {
_storage.setItem(key, String.valueOf(value));
}
/**
* Returns the specified property as a double. If the property does not exist, the default
* value will be returned. If the property cannot be parsed as a double, an error will be
* logged and the default value will be returned.
*/
public double get (String key, double defval) {
String value = null;
try {
value = _storage.getItem(key);
return (value == null) ? defval : Double.parseDouble(value);
} catch (Exception e) {
log().warn("Failed to parse double prop [key=" + key + ", value=" + value + "]", e);
return defval;
}
}
/**
* Sets the specified property to the supplied double value.
*/
public void set (String key, double value) {
_storage.setItem(key, String.valueOf(value));
}
/**
* Returns the specified property as a boolean. If the property does not exist, the default
* value will be returned. Any existing value equal to {@code t} (ignoring case) will be
* considered true; all others, false.
*/
public boolean get (String key, boolean defval) {
String value = _storage.getItem(key);
return (value == null) ? defval : value.equalsIgnoreCase("t");
}
/**
* Sets the specified property to the supplied boolean value.
*/
public void set (String key, boolean value) {
_storage.setItem(key, value ? "t" : "f");
}
/**
* Returns the specified property as an enum. If the property does not exist, the default value
* will be returned.
* @throws NullPointerException if {@code defval} is null.
*/
public <E extends Enum<E>> E get (String key, E defval) {
@SuppressWarnings("unchecked") Class<E> eclass = (Class<E>)defval.getClass();
String value = null;
try {
value = _storage.getItem(key);
return (value == null) ? defval : Enum.valueOf(eclass, value);
} catch (Exception e) {
log().warn("Failed to parse enum prop [key=" + key + ", value=" + value + "]", e);
return defval;
}
}
/**
* Sets the specified property to the supplied enum value.
*/
public void set (String key, Enum<?> value) {
_storage.setItem(key, value.name());
}
/**
* Removes the specified key (and its value) from storage.
*/
public void remove (String key) {
_storage.removeItem(key);
}
/**
* Exposes the specified property as a {@link Value}. The supplied default value will be used
* if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link Value} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public Value<String> valueFor (final String key, String defval) {
Value<String> value = Value.create(get(key, defval));
value.connect(new Slot<String>() {
@Override public void onEmit (String value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as an {@link IntValue}. The supplied default value will be
* used if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link IntValue} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public IntValue valueFor (final String key, int defval) {
IntValue value = new IntValue(get(key, defval));
value.connect(new Slot<Integer>() {
@Override public void onEmit (Integer value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as a {@link Value}. The supplied default value will be used
* if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link Value} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public Value<Long> valueFor (final String key, long defval) {
Value<Long> value = Value.create(get(key, defval));
value.connect(new Slot<Long>() {
@Override public void onEmit (Long value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as a {@link Value}. The supplied default value will be used
* if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link Value} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public Value<Double> valueFor (final String key, double defval) {
Value<Double> value = Value.create(get(key, defval));
value.connect(new Slot<Double>() {
@Override public void onEmit (Double value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as a {@link Value}. The supplied default value will be used
* if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link Value} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public Value<Boolean> valueFor (final String key, boolean defval) {
Value<Boolean> value = Value.create(get(key, defval));
value.connect(new Slot<Boolean>() {
@Override public void onEmit (Boolean value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as a {@link Value}. The supplied default value will be used
* if the property has no current value. Updates to the value will be written back to the
* storage system. Note that each call to this method yields a new {@link Value} and those
* values will not coordinate with one another, so the caller must be sure to only call this
* method once for a given property and share that value properly.
*/
public <E extends Enum<E>> Value<E> valueFor (final String key, E defval) {
Value<E> value = Value.create(get(key, defval));
value.connect(new Slot<E>() {
@Override public void onEmit (E value) {
set(key, value);
}
});
return value;
}
/**
* Exposes the specified property as an {@link RSet}. The contents of the set will be encoded
* as a comma separated string and the supplied {@code toFunc} and {@code fromFunc} will be
* used to convert an individual set item to and from a string. The to and from functions
* should perform escaping and unescaping of commas if the encoded representation of the items
* might naturally contain commas.
*
* <p>Any modifications to the set will be immediately persisted back to storage. Note that
* each call to this method yields a new {@link RSet} and those sets will not coordinate with
* one another, so the caller must be sure to only call this method once for a given property
* and share that set properly. Changes to the underlying persistent value that do not take
* place through the returned set will <em>not</em> be reflected in the set and will be
* overwritten if the set changes.</p>
*/
public <E> RSet<E> setFor (final String key, Function<String,E> toFunc,
final Function<E,String> fromFunc) {
final RSet<E> rset = RSet.create();
String data = get(key, (String)null);
if (data != null) {
for (String value : data.split(",")) {
try {
rset.add(toFunc.apply(value));
} catch (Exception e) {
log().warn("Invalid value (key=" + key + "): " + value, e);
}
}
}
rset.connect(new RSet.Listener<E>() {
@Override public void onAdd (E unused) { save(); }
@Override public void onRemove (E unused) { save(); }
protected void save () {
if (rset.isEmpty()) remove(key);
else {
StringBuilder buf = new StringBuilder();
int ii = 0;
for (E value : rset) {
if (ii++ > 0) buf.append(",");
buf.append(fromFunc.apply(value));
}
set(key, buf.toString());
}
}
});
return rset;
}
protected final Storage _storage;
} |
package com.fishercoder.solutions;
public class _393 {
public static class Solution1 {
public boolean validUtf8(int[] data) {
int count = 0;
for (int d : data) {
if (count == 0) {
if ((d >> 5) == 0b110) {
count = 1;
} else if ((d >> 4) == 0b1110) {
count = 2;
} else if ((d >> 3) == 0b11110) {
count = 3;
} else if ((d >> 7) == 1) {
return false;
}
} else {
if ((d >> 6) != 0b10) {
return false;
} else {
count
}
}
}
return count == 0;
}
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _450 {
public static class Solution1 {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return root;
}
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
TreeNode minNode = getMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
}
return root;
}
private TreeNode getMin(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}
} |
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.LinkedList;
public class _456 {
public static class Solution1 {
public boolean find132pattern(int[] nums) {
Deque<Integer> stack = new LinkedList<>();
int s3 = Integer.MIN_VALUE;
for (int i = nums.length - 1; i >= 0; i
if (nums[i] < s3) {
return true;
} else {
while (!stack.isEmpty() && nums[i] > stack.peek()) {
s3 = Math.max(s3, stack.pop());
}
}
stack.push(nums[i]);
}
return false;
}
}
} |
package com.fishercoder.solutions;
import java.util.Arrays;
public class _493 {
public static class Solution1 {
public int reversePairs(int[] nums) {
return mergeSort(nums, 0, nums.length - 1);
}
private int mergeSort(int[] nums, int start, int end) {
if (start >= end) {
return 0;
}
int mid = start + (end - start) / 2;
int cnt = mergeSort(nums, start, mid) + mergeSort(nums, mid + 1, end);
for (int i = start, j = mid + 1; i <= mid; i++) {
/**it has to be 2.0 instead of 2, otherwise it's going to stack overflow, i.e. test3 is going to fail*/
while (j <= end && nums[i] > nums[j] * 2.0) {
j++;
}
cnt += j - (mid + 1);
}
Arrays.sort(nums, start, end + 1);
return cnt;
}
}
} |
package com.fishercoder.solutions;
import java.util.Arrays;
import java.util.Comparator;
public class _522 {
public static class Solution1 {
/**
* Idea: if there's such a LUS there in the list, it must be one of the strings in the given list,
* so we'll just go through the list and check if one string is NOT subsequence of any others, if so, return it, otherwise, return -1
*/
public int findLUSlength(String[] strs) {
Arrays.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
for (int i = 0; i < strs.length; i++) {
boolean found = true;
for (int j = 0; j < strs.length; j++) {
if (i == j) {
continue;
} else if (isSubsequence(strs[i], strs[j])) {
found = false;
break;
}
}
if (found) {
return strs[i].length();
}
}
return -1;
}
private boolean isSubsequence(String a, String b) {
int i = 0;
for (int j = 0; i < a.length() && j < b.length(); j++) {
if (a.charAt(i) == b.charAt(j)) {
i++;
}
}
return i == a.length();
}
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class _545 {
public static class Solution1 {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> nodes = new ArrayList<>();
if (root == null) {
return nodes;
}
nodes.add(root.val);
leftBoundary(root.left, nodes);
addLeaves(root.left, nodes);
addLeaves(root.right, nodes);
rightBoundary(root.right, nodes);
return nodes;
}
public void leftBoundary(TreeNode root, List<Integer> nodes) {
if (root == null || (root.left == null && root.right == null)) {
/**we don't want to add any LEAVES in leftBoundary and rightBoundary functions either,
* that's why we have the later condition in the if branch.*/
return;
}
nodes.add(root.val);// add BEFORE child visit
if (root.left == null) {
leftBoundary(root.right, nodes);
} else {
leftBoundary(root.left, nodes);
}
}
public void rightBoundary(TreeNode root, List<Integer> nodes) {
if (root == null || (root.right == null && root.left == null)) {
return;
}
if (root.right == null) {
rightBoundary(root.left, nodes);
} else {
rightBoundary(root.right, nodes);
}
nodes.add(root.val); // add AFTER child visit(reverse)
}
public void addLeaves(TreeNode root, List<Integer> nodes) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
nodes.add(root.val);
return;
}
addLeaves(root.left, nodes);
addLeaves(root.right, nodes);
}
}
} |
package com.fishercoder.solutions;
public class _551 {
public static class Solution1 {
public boolean checkRecord(String s) {
int aCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'A') {
aCount++;
if (aCount > 1) {
return false;
}
} else if (s.charAt(i) == 'L') {
int continuousLCount = 0;
while (i < s.length() && s.charAt(i) == 'L') {
i++;
continuousLCount++;
if (continuousLCount > 2) {
return false;
}
}
i
}
}
return true;
}
}
} |
package com.fishercoder.solutions;
/**
* 556. Next Greater Element III
*
* Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing
* in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
*
* Example 1:
* Input: 12
* Output: 21
*
* Example 2:
* Input: 21
* Output: -1
*/
public class _556 {
public int nextGreaterElement(int n) {
char[] digits = String.valueOf(n).toCharArray();
int i = digits.length - 2;
while (i >= 0 && digits[i + 1] <= digits[i]) {
i
}
if (i < 0) {
return -1;
}
int j = digits.length - 1;
while (j >= 0 && digits[j] <= digits[i]) {
j
}
swap(digits, i, j);
reverse(digits, i + 1);
try {
return Integer.parseInt(new String(digits));
} catch (Exception e) {
return -1;
}
}
private void reverse(char[] a, int start) {
int i = start;
int j = a.length - 1;
while (i < j) {
swap(a, i, j);
i++;
j
}
}
private void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
} |
package edu.berkeley.eecs.emission.cordova.transitionnotify;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.webkit.ValueCallback;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*
* Importing dependencies from the notification plugin
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import de.appplant.cordova.plugin.localnotification.TriggerReceiver;
import de.appplant.cordova.plugin.notification.Manager;
/*
* Importing dependencies from the logger plugin
*/
import edu.berkeley.eecs.emission.BuildConfig;
import edu.berkeley.eecs.emission.R;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.SimpleLocation;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.Transition;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log;
import edu.berkeley.eecs.emission.cordova.usercache.UserCache;
import edu.berkeley.eecs.emission.cordova.usercache.UserCacheFactory;
public class TransitionNotificationReceiver extends BroadcastReceiver {
public static final String USERDATA = "userdata";
private static String TAG = TransitionNotificationReceiver.class.getSimpleName();
public static final String EVENTNAME_ERROR = "event name null or empty.";
private static final String TRIP_STARTED = "trip_started";
private static final String TRIP_ENDED = "trip_ended";
private static final String TRACKING_STARTED = "tracking_started";
private static final String TRACKING_STOPPED = "tracking_stopped";
private static final String CONFIG_LIST_KEY = "config_list";
public TransitionNotificationReceiver() {
// The automatically created receiver needs a default constructor
android.util.Log.i(TAG, "noarg constructor called");
}
public TransitionNotificationReceiver(Context context) {
android.util.Log.i(TAG, "constructor called with arg "+context);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(context, TAG, "TripDiaryStateMachineReciever onReceive(" + context + ", " + intent + ") called");
// Next two calls copied over from the constructor, figure out if this is the best place to
// put them
Set<String> validTransitions = new HashSet<String>(Arrays.asList(new String[]{
context.getString(R.string.transition_initialize),
context.getString(R.string.transition_exited_geofence),
context.getString(R.string.transition_stopped_moving),
context.getString(R.string.transition_stop_tracking),
context.getString(R.string.transition_start_tracking),
context.getString(R.string.transition_tracking_error)
}));
if (!validTransitions.contains(intent.getAction())) {
Log.e(context, TAG, "Received unknown action "+intent.getAction()+" ignoring");
return;
}
fireGenericTransition(context, intent.getAction(), new JSONObject());
}
/**
* @param context
* @param eventName
* @param userInfo
* @throws JSONException
*/
protected void fireGenericTransition( final Context context, final String eventName,
final JSONObject userInfo) {
Log.d(context, TAG, "Received platform-specification notification "+eventName);
try {
if (eventName.equals(context.getString(R.string.transition_exited_geofence))) {
JSONObject autogenData = getTripStartData(context);
postNativeAndNotify(context, TRIP_STARTED, autogenData);
}
if (eventName.equals(context.getString(R.string.transition_stopped_moving))) {
JSONObject autogenData = getTripStartEndData(context);
if (autogenData != null) {
postNativeAndNotify(context, TRIP_ENDED, autogenData);
}
}
if (eventName.equals(context.getString(R.string.transition_stop_tracking))) {
postNativeAndNotify(context, TRACKING_STOPPED, new JSONObject());
}
if (eventName.equals(context.getString(R.string.transition_start_tracking))) {
postNativeAndNotify(context, TRACKING_STARTED, new JSONObject());
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(context, TAG, "Skipping firing of generic transition due to "+e.getMessage());
}
}
public void postNativeAndNotify(Context context, String genericTransition, JSONObject autogenData) {
Log.d(context, TAG, "Broadcasting generic transition "+genericTransition
+" and generating notification");
Intent genericTransitionIntent = new Intent();
genericTransitionIntent.setAction(genericTransition);
genericTransitionIntent.putExtras(jsonToBundle(autogenData));
context.sendBroadcast(genericTransitionIntent);
notifyEvent(context, genericTransition, autogenData);
}
public void notifyEvent(Context context, String eventName, JSONObject autogenData) {
Log.d(context, TAG, "Generating all notifications for generic "+eventName);
try {
JSONObject notifyConfigWrapper = UserCacheFactory.getUserCache(context).getLocalStorage(eventName, false);
if (notifyConfigWrapper == null) {
Log.d(context, TAG, "no configuration found for event "+eventName+", skipping notification");
return;
}
JSONArray notifyConfigs = notifyConfigWrapper.getJSONArray(CONFIG_LIST_KEY);
for(int i = 0; i < notifyConfigs.length(); i++) {
try {
JSONObject currNotifyConfig = notifyConfigs.getJSONObject(i);
if (autogenData != null) { // we need to merge in the autogenerated data with any user data
JSONObject currData = currNotifyConfig.optJSONObject("data");
if (currData == null) {
currData = new JSONObject();
currNotifyConfig.put("data", currData);
}
mergeObjects(currData, autogenData);
}
Log.d(context, TAG, "generating notification for event "+eventName
+" and id = "+currNotifyConfig.getLong("id"));
Manager.getInstance(context).schedule(currNotifyConfig, TriggerReceiver.class);
} catch (Exception e) {
Log.e(context, TAG, "Got error "+e.getMessage()+" while processing object "
+ notifyConfigs.getJSONObject(i) + " at index "+i);
}
}
} catch(JSONException e) {
Log.e(context, TAG, e.getMessage());
Log.e(context, TAG, e.toString());
}
}
private JSONObject getTripStartData(Context context) throws JSONException {
JSONObject retData = new JSONObject();
long currTime = System.currentTimeMillis();
// We store the point at which the geofence was exited before we generate the exited_geofence
// message. The trip start was at the last location.
SimpleLocation[] lastLocArray = UserCacheFactory.getUserCache(context)
.getLastSensorData(R.string.key_usercache_filtered_location, 1, SimpleLocation.class);
if (lastLocArray.length == 0) {
Log.e(context, TAG, "lastLocArray.length = "+lastLocArray.length+" while generating trip start event");
retData.put("start_ts", ((double)currTime)/1000);
} else {
SimpleLocation lastLoc = lastLocArray[0];
retData.put("start_ts", ((double) currTime) / 1000);
retData.put("start_lat", lastLoc.getLatitude());
retData.put("start_lng", lastLoc.getLongitude());
}
return retData;
}
private JSONObject getTripStartEndData(Context context) throws JSONException {
JSONObject retData = new JSONObject();
long currTime = System.currentTimeMillis();
// We store the point at which the geofence was exited before we generate the exited_geofence
// message. The trip start was at the last location.
SimpleLocation[] lastLocArray = UserCacheFactory.getUserCache(context)
.getLastSensorData(R.string.key_usercache_filtered_location, 1, SimpleLocation.class);
if (BuildConfig.DEBUG) {
if (lastLocArray.length != 1) {
Log.e(context, TAG, "lastLocArray = "+lastLocArray.length+" while generating trip start event");
// throw new RuntimeException("lastLocArray = "+lastLocArray.length+" while generating trip start event");
}
}
if (lastLocArray.length == 0) {
Log.e(context, TAG, "no locations found at trip end, skipping notification");
return null;
}
SimpleLocation lastLoc = lastLocArray[0];
retData.put("end_ts", lastLoc.getTs());
retData.put("end_lat", lastLoc.getLatitude());
retData.put("end_lng", lastLoc.getLongitude());
// Find the start of this trip
// Since the transitions are sorted in reverse order, we expect that the first will be the stopped moving transition
// for the trip that just ended, the second will be the exited geofence transition that started it,
// and the third (if present) will be the stopped_moving transition before that
Transition[] lastTwoTransitions = UserCacheFactory.getUserCache(context).getLastMessages(
R.string.key_usercache_transition, 2, Transition.class);
SimpleLocation firstLoc = getFirstLocation(context, lastTwoTransitions);
if(firstLoc == null) {
Log.e(context, TAG, "error determining first location, skipping notification");
return null;
}
retData.put("start_ts", firstLoc.getTs());
retData.put("start_lat", firstLoc.getLatitude());
retData.put("start_lng", firstLoc.getLongitude());
return retData;
}
private SimpleLocation getFirstLocation(Context context, Transition[] lastTwoTransitions) {
if (BuildConfig.DEBUG) {
Log.d(context, TAG, "number of transitions = "+lastTwoTransitions.length);
if (lastTwoTransitions.length == 0) {
Log.e(context, TAG, "found no transitions at trip end, skipping notification");
return null;
}
if (lastTwoTransitions.length > 2) {
Log.e(context, TAG, "found too many transitions "
+lastTwoTransitions.length+ " at trip end, skipping notification");
return null;
}
}
if (lastTwoTransitions.length <= 2) {
Transition startTransition = getStartTransition(lastTwoTransitions);
if (startTransition.getTransition().equals(context.getString(R.string.transition_exited_geofence))) {
UserCache.TimeQuery tq = new UserCache.TimeQuery("write_ts",
startTransition.getTs() - 5 * 60,
startTransition.getTs() + 5 * 60);
SimpleLocation[] firstLocArray = UserCacheFactory.getUserCache(context).getSensorDataForInterval(
R.string.key_usercache_filtered_location, tq, SimpleLocation.class);
if (firstLocArray.length == 0) { // no locations found, switch to default
Log.d(context, TAG, "Found no locations before exiting geofence while ending trip!");
SimpleLocation firstLoc = getDefaultLocation(context);
if (firstLoc.getTs() < startTransition.getTs()) {
throw new RuntimeException("firstLocArray[0].ts "+firstLoc.getTs()
+" < startTransition.ts "+startTransition.getTs());
}
return firstLoc;
} else {
// There are points around the start transition
// Return the last point before (preferable) or the first point after
ArrayList<SimpleLocation> beforePoints = new ArrayList<SimpleLocation>();
ArrayList<SimpleLocation> equalOrAfterPoints = new ArrayList<SimpleLocation>();
splitArray(firstLocArray, startTransition.getTs(), beforePoints, equalOrAfterPoints);
if (beforePoints.size() == 0 && equalOrAfterPoints.size() == 0) {
throw new RuntimeException("beforePoints.size = "+beforePoints.size()
+ "afterPoints.size = "+equalOrAfterPoints.size());
}
int beforeSize = beforePoints.size();
if (beforeSize > 0) {
return beforePoints.get(beforeSize - 1);
} else {
return equalOrAfterPoints.get(0);
}
}
} else { // there were at least two transitions in the cache, but the second one
// was not a geofence exit
Log.d(context, TAG, "startTransition is "+startTransition.getTransition()
+" not "+context.getString(R.string.transition_exited_geofence));
return getDefaultLocation(context);
}
} else {
// Not enough transitions (have only one transition, presumably the stopping one)
return getDefaultLocation(context);
}
}
private Transition getStartTransition(Transition[] lastTwoTransitions) {
/*
Simple function here - no error checking since we have done that already
* Small if - that's all we need
*/
if (lastTwoTransitions.length == 2) {
return lastTwoTransitions[1];
} else {
if (BuildConfig.DEBUG) {
if (lastTwoTransitions.length > 2) {
throw new RuntimeException("last two transitions.length is " + lastTwoTransitions.length
+ " should be < 2");
}
}
return lastTwoTransitions[0];
}
}
private void splitArray(SimpleLocation[] inArray, double ts,
ArrayList<SimpleLocation> beforePoints,
ArrayList<SimpleLocation> equalOrAfterPoints) {
for (int i = 0; i < inArray.length; i++) {
SimpleLocation currLoc = inArray[i];
if (currLoc.getTs() < ts) {
beforePoints.add(currLoc);
} else {
equalOrAfterPoints.add(currLoc);
}
}
}
private SimpleLocation getDefaultLocation(Context context) {
SimpleLocation[] firstLocArray = UserCacheFactory.getUserCache(context).getFirstSensorData(
R.string.key_usercache_filtered_location,
1,
SimpleLocation.class);
if (firstLocArray.length == 0) {
Log.e(context, TAG, "Found no locations while ending trip!");
throw new RuntimeException("Found no locations while ending trip!");
}
return firstLocArray[0];
}
private void mergeObjects(JSONObject existing, JSONObject autogen) throws JSONException {
JSONArray toBeCopiedKeys = autogen.names();
for(int j = 0; j < toBeCopiedKeys.length(); j++) {
String currKey = toBeCopiedKeys.getString(j);
existing.put(currKey, autogen.get(currKey));
}
}
private Bundle jsonToBundle(JSONObject toConvert) {
Bundle bundle = new Bundle();
for (Iterator<String> it = toConvert.keys(); it.hasNext(); ) {
String key = it.next();
JSONArray arr = toConvert.optJSONArray(key);
Double num = toConvert.optDouble(key);
String str = toConvert.optString(key);
if (arr != null && arr.length() <= 0)
bundle.putStringArray(key, new String[]{});
else if (arr != null && !Double.isNaN(arr.optDouble(0))) {
double[] newarr = new double[arr.length()];
for (int i=0; i<arr.length(); i++)
newarr[i] = arr.optDouble(i);
bundle.putDoubleArray(key, newarr);
}
else if (arr != null && arr.optString(0) != null) {
String[] newarr = new String[arr.length()];
for (int i=0; i<arr.length(); i++)
newarr[i] = arr.optString(i);
bundle.putStringArray(key, newarr);
}
else if (!num.isNaN())
bundle.putDouble(key, num);
else if (str != null)
bundle.putString(key, str);
else
System.err.println("unable to transform json to bundle " + key);
}
return bundle;
}
} |
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _694 {
public static class Solution1 {
/**
* My original idea:
* my not fully working yet: the equals() and hashcode() methods need to be refined
* because HashSet is not really filtering the islands wiht the same shape.
*/
class Quadrilateral {
int[] topLeft;
int[] bottomLeft;
int[] topRight;
int[] bottomRight;
int area;
public Quadrilateral(int i, int j) {
this.area = 0;
this.topLeft = new int[]{i, j};
this.topRight = new int[]{i, j};
this.bottomLeft = new int[]{i, j};
this.bottomRight = new int[]{i, j};
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Quadrilateral)) {
return false;
}
Quadrilateral that = (Quadrilateral) o;
return this.area == that.area && checkDistance(that);
}
private boolean checkDistance(Quadrilateral that) {
int thisTop = computeDistance(this.topLeft, this.topRight);
int thatTop = computeDistance(that.topLeft, that.topRight);
if (thisTop != thatTop) {
return false;
}
int thisRight = computeDistance(this.topRight, this.bottomRight);
int thatRight = computeDistance(that.topRight, that.bottomRight);
if (thisRight != thatRight) {
return false;
}
int thisBottom = computeDistance(this.bottomRight, this.bottomLeft);
int thatBottom = computeDistance(that.bottomRight, that.bottomLeft);
if (thisBottom != thatBottom) {
return false;
}
int thisLeft = computeDistance(this.bottomLeft, this.topLeft);
int thatLeft = computeDistance(that.bottomLeft, that.topLeft);
return thisLeft == thatLeft;
}
private int computeDistance(int[] A, int[] B) {
return (int) (Math.pow(A[0] - B[0], 2) + Math.pow(A[1] - B[1], 2));
}
@Override
public int hashCode() {
return area + computeDistance(this.topLeft, this.topRight) + computeDistance(this.topRight, this.bottomRight)
+ computeDistance(this.bottomRight, this.bottomLeft) + computeDistance(this.bottomLeft, this.topLeft);
}
public void addPoint(int i, int j) {
//todo: check wether this point (i,j) is in the range, if not, expand the range
if (i == topRight[0]) {
topRight[1] = Math.max(topRight[1], j);
}
if (j == topRight[1]) {
topRight[0] = Math.min(topRight[1], i);
}
if (i == topLeft[0]) {
topLeft[1] = Math.min(topLeft[1], j);
}
if (j == topLeft[1]) {
topLeft[0] = Math.min(topLeft[0], i);
}
if (i == bottomLeft[0]) {
bottomLeft[1] = Math.min(bottomLeft[1], j);
}
if (j == bottomLeft[1]) {
bottomLeft[0] = Math.max(bottomLeft[0], i);
}
if (j == bottomRight[1]) {
bottomRight[0] = Math.max(bottomRight[0], i);
}
if (i == bottomRight[0]) {
bottomRight[1] = Math.max(bottomRight[1], j);
}
}
public void addArea() {
this.area++;
}
}
public int numDistinctIslands(int[][] grid) {
Set<Quadrilateral> set = new HashSet<>();
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
Quadrilateral quadrilateral = dfs(grid, i, j, m, n, new Quadrilateral(i, j));
set.add(quadrilateral);
}
}
}
return set.size();
}
private Quadrilateral dfs(int[][] grid, int i, int j, int m, int n, Quadrilateral quadrilateral) {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) {
return quadrilateral;
}
grid[i][j] = 0;
quadrilateral.addPoint(i, j);
quadrilateral.addArea();
quadrilateral = dfs(grid, i + 1, j, m, n, quadrilateral);
quadrilateral = dfs(grid, i - 1, j, m, n, quadrilateral);
quadrilateral = dfs(grid, i, j + 1, m, n, quadrilateral);
quadrilateral = dfs(grid, i, j - 1, m, n, quadrilateral);
return quadrilateral;
}
}
public static class Solution2 {
int[][] directions = new int[][]{
{0, 1},
{1, 0},
{0, -1},
{-1, 0}
};
public int numDistinctIslands(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
Set<List<List<Integer>>> uniqueShapeIslands = new HashSet<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
List<List<Integer>> island = new ArrayList<>();
if (dfs(i, j, i, j, grid, m, n, island)) {
uniqueShapeIslands.add(island);
}
}
}
return uniqueShapeIslands.size();
}
private boolean dfs(int i0, int j0, int i, int j, int[][] grid, int m, int n, List<List<Integer>> island) {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] <= 0) {
return false;
}
island.add(Arrays.asList(i - i0, j - j0));
grid[i][j] *= -1;
for (int k = 0; k < 4; k++) {
dfs(i0, j0, i + directions[k][0], j + directions[k][1], grid, m, n, island);
}
return true;
}
}
} |
package com.gamingmesh.jobs.stuff;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.BlockIterator;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.CMILib.ItemManager.CMIMaterial;
public class Util {
public Util() {
}
private static HashMap<UUID, String> jobsEditorMap = new HashMap<>();
@SuppressWarnings("deprecation")
public static ItemStack setEntityType(ItemStack is, EntityType type) throws IllegalArgumentException {
boolean useMeta;
try {
ItemStack testis = CMIMaterial.SPAWNER.newItemStack();
ItemMeta meta = testis.getItemMeta();
useMeta = meta instanceof BlockStateMeta;
} catch (Exception e) {
useMeta = false;
}
if (useMeta) {
BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta();
BlockState bs = bsm.getBlockState();
((CreatureSpawner) bs).setSpawnedType(type);
((CreatureSpawner) bs).setCreatureTypeByName(type.name());
bsm.setBlockState(bs);
String cap = type.name().toLowerCase().replace("_", " ").substring(0, 1).toUpperCase() + type.name().toLowerCase().replace("_", " ").substring(1);
bsm.setDisplayName(Jobs.getLanguage().getMessage("general.Spawner", "[type]", cap));
is.setItemMeta(bsm);
} else {
is.setDurability(type.getTypeId());
}
return is;
}
@SuppressWarnings("deprecation")
public static EntityType getEntityType(ItemStack is) {
if (is.getItemMeta() instanceof BlockStateMeta) {
BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta();
if (bsm.getBlockState() instanceof CreatureSpawner) {
CreatureSpawner bs = (CreatureSpawner) bsm.getBlockState();
return bs.getSpawnedType();
}
}
return EntityType.fromId(is.getData().getData());
}
public static HashMap<UUID, String> getJobsEditorMap() {
return jobsEditorMap;
}
public static Block getTargetBlock(Player player, int distance, boolean ignoreNoneSolids) {
return getTargetBlock(player, null, distance, ignoreNoneSolids);
}
public static Block getTargetBlock(Player player, int distance) {
return getTargetBlock(player, null, distance, false);
}
public static Block getTargetBlock(Player player, Material lookingFor, int distance) {
return getTargetBlock(player, lookingFor, distance, false);
}
public static Block getTargetBlock(Player player, Material lookingFor, int distance, boolean ignoreNoneSolids) {
if (distance > 15 * 16)
distance = 15 * 16;
if (distance < 1)
distance = 1;
ArrayList<Block> blocks = new ArrayList<>();
Iterator<Block> itr = new BlockIterator(player, distance);
while (itr.hasNext()) {
Block block = itr.next();
blocks.add(block);
if (distance != 0 && blocks.size() > distance) {
blocks.remove(0);
}
Material material = block.getType();
if (ignoreNoneSolids && !block.getType().isSolid())
continue;
if (lookingFor == null) {
if (!CMIMaterial.AIR.equals(material) && !CMIMaterial.CAVE_AIR.equals(material) && !CMIMaterial.VOID_AIR.equals(material)) {
break;
}
} else {
if (lookingFor.equals(material)) {
return block;
}
}
}
return !blocks.isEmpty() ? blocks.get(blocks.size() - 1) : null;
}
} |
package com.github.enanomapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Stream;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.formats.RDFXMLDocumentFormat;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.AddOntologyAnnotation;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.RemoveImport;
import org.semanticweb.owlapi.model.SetOntologyID;
import org.semanticweb.owlapi.search.EntitySearcher;
import org.semanticweb.owlapi.search.Searcher;
import org.semanticweb.owlapi.util.OWLEntityRemover;
import org.semanticweb.owlapi.util.OWLOntologyMerger;
import org.semanticweb.owlapi.util.SimpleIRIMapper;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
/**
* The purpose of this class is to take one or more OWL ontology files and remove everything that
* we do not want in. This includes, in the first place, 3rd party classes and predicates that some
* ontology imports from other ontologies (from the BAO ontology, we only want to keep terms added
* by BAO and not used from IAO or SIO). But we may also only use part of the ontology itself. For
* example, keep some key terms but not full subtrees.
*
* <p>What is kept to be, is specified by a configuration file read by the {@link Configuration}
* class. This class specifies the format used by these config files. If nothing is specified, all
* content (classes, object and data properties) is removed.
*
* @author egonw
*/
public class Slimmer {
private OWLOntologyManager man;
private OWLOntology onto;
public Slimmer(File owlFile, String mergedOntologyIRI) throws OWLOntologyCreationException, FileNotFoundException {
this(owlFile.getName(), new FileInputStream(owlFile), mergedOntologyIRI);
}
public Slimmer(InputStream owlFile) throws OWLOntologyCreationException {
this("undefined for InputStream", owlFile, null);
}
/**
* Constructs a new Slimmer object that will slim the given OWL file.
*
* @param owlFile
* @param mergedOntologyIRI
* @throws OWLOntologyCreationException
*/
public Slimmer(String filename, InputStream owlFile, String mergedOntologyIRI) throws OWLOntologyCreationException {
System.out.println("Loading OWL file: " + filename);
man = OWLManager.createOWLOntologyManager();
if (System.getenv("WORKSPACE") != null) {
String root = System.getenv("WORKSPACE");
System.out.println("Adding mappings with root: " + root);
addMappings(man, root);
}
onto = man.loadOntologyFromOntologyDocument(owlFile);
if (mergedOntologyIRI != null) {
Set<OWLImportsDeclaration> importDeclarations = onto.getImportsDeclarations();
for (OWLImportsDeclaration declaration : importDeclarations) {
try {
man.loadOntology(declaration.getIRI());
System.out.println("Loaded imported ontology: " + declaration.getIRI());
} catch (Exception exception) {
System.out.println("Failed to load imported ontology: " + declaration.getIRI());
}
}
// Merge all of the loaded ontologies, specifying an IRI for the new ontology
OWLOntologyMerger merger = new OWLOntologyMerger(man);
onto = merger.createMergedOntology(man, IRI.create(mergedOntologyIRI));
for (OWLOntology ontology : man.getOntologies()) {
System.out.println(" Copying annotations from " + ontology.getOntologyID());
for (OWLAnnotation annotation : ontology.getAnnotations()) {
System.out.println(" copying annotation: " + annotation.getProperty() + " -> " + annotation.getValue());
AddOntologyAnnotation annotationAdd = new AddOntologyAnnotation(onto, annotation);
man.applyChange(annotationAdd);
}
}
}
}
public OWLOntology getOntology() {
return this.onto;
}
/**
* Main method to allow running the Slimmer from the command line. The full slimming
* process consists of a number of steps:
* <ol>
* <li>read the instructions that specify which ontology to slim</li>
* <li>read the ontology to slim (including imports)</li>
* <li>read the instructions that specify how the ontology is to be slimmed</li>
* <li>remove everything from the ontology except what is to be kept, but after that still
* delete things explicitly marked to be removed</li>
* <li>remove owl:import statements from the OWL file</li>
* <li>normalize term labels</li>
* <li>save as OWL/XML (which includes updating the ontology metadata)</li>
* </ol>
*
* @param args
*/
public static void main(String[] args) {
boolean allSucceeded = true;
String rootFolder = args[0];
System.out.println("Searching configuration files in " + rootFolder);
File dir = new File(rootFolder);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".props");
}
});
for (File file : files) {
try {
System.out.println("Slimming for " + file.getName());
// read the information about the ontology to process
Properties props = new Properties();
props.load(new FileReader(file));
String owlURL = props.getProperty("owl"); // for step 1
String owlFilename = owlURL;
if (owlFilename.contains("/")) {
owlFilename = owlFilename.substring(owlFilename.lastIndexOf('/')+1);
}
String iriFilename = props.getProperty("iris"); // for step 2,3
String slimmedURI = props.getProperty("slimmed"); // for step 5
String slimmedFilename = slimmedURI;
if (slimmedFilename.contains("/")) {
slimmedFilename = slimmedFilename.substring(slimmedFilename.lastIndexOf('/')+1);
}
// 1. read the original ontology
File owlFile = new File(owlFilename);
Slimmer slimmer = new Slimmer(owlFile, slimmedFilename);
OWLOntology onto = slimmer.getOntology();
System.out.println("Loaded axioms: " + onto.getAxiomCount());
// 2. read the configuration of what to keep/remove
File configFile = new File(rootFolder,iriFilename);
Configuration config = new Configuration();
try {
System.out.println("Reading config file: " + configFile);
config.read(configFile);
} catch (Exception exception) {
System.out.println("Error while reading the config file: " + exception.getMessage());
System.exit(-1);
}
// 3. remove everything except for what is defined by the instructions
Set<Instruction> irisToSave = config.getTreePartsToSave();
slimmer.removeAllExcept(irisToSave);
Set<Instruction> irisToRemove = config.getTreePartsToRemove();
slimmer.removeAll(irisToRemove);
// 4. remove owl:imports
Set<OWLImportsDeclaration> importDeclarations = onto.getImportsDeclarations();
for (OWLImportsDeclaration declaration : importDeclarations) {
System.out.println("Removing imports: " + declaration.getIRI());
RemoveImport removeImport = new RemoveImport(onto, declaration);
slimmer.man.applyChange(removeImport);
}
// 5. update descriptions and labels
Set<OWLClass> entities = onto.getClassesInSignature();
for (OWLClass clazz : entities) {
for (OWLAnnotation annot : (Iterable<OWLAnnotation>)EntitySearcher.getAnnotations(clazz, onto).iterator()) {
if (annot.getProperty().getIRI().toString().equals("http://purl.org/dc/elements/1.1/description") ||
annot.getProperty().getIRI().toString().equals("http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#P97")) {
System.out.println(" description: " + annot.getValue());
OWLDataFactory factory = slimmer.man.getOWLDataFactory();
OWLAnnotationProperty newDescription =
factory.getOWLAnnotationProperty(IRI.create("http://purl.obolibrary.org/obo/IAO_0000115"));
OWLAnnotation commentAnno = factory.getOWLAnnotation(
newDescription,
annot.getValue()
);
System.out.println(" new description: " + commentAnno);
OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(
clazz.getIRI(), commentAnno
);
slimmer.man.applyChange(new AddAxiom(onto, ax));
}
}
}
// 6. remove some nasty NPO properties (WORKAROUND: may be removed later)
entities = onto.getClassesInSignature();
for (OWLClass clazz : entities) {
Set<OWLAnnotationAssertionAxiom> annots = onto.getAnnotationAssertionAxioms(clazz.getIRI());
Set<OWLAnnotationAssertionAxiom> toRemove = new HashSet<OWLAnnotationAssertionAxiom>();
for (OWLAnnotationAssertionAxiom axiom : annots) {
if (axiom.getProperty().getIRI().toString().equals("http://purl.bioontology.org/ontology/npo#FULL_SYN") ||
axiom.getProperty().getIRI().toString().equals("http://purl.bioontology.org/ontology/npo#definition")) {
toRemove.add(axiom);
}
}
slimmer.man.removeAxioms(onto, toRemove);
}
// 7. save in OWL/XML format
SetOntologyID ontologyIDChange = new SetOntologyID(onto, IRI.create(slimmedURI));
slimmer.man.applyChange(ontologyIDChange);
File output = new File(slimmedFilename);
System.out.println("Saving to: " + output.getAbsolutePath());
slimmer.saveAs(output, owlURL);
} catch (Exception e) {
e.printStackTrace();
allSucceeded = false;
}
}
if (!allSucceeded) System.exit(-1);
}
public void saveAs(File output, String orinalOWL) throws OWLOntologyStorageException, FileNotFoundException {
saveAs(new FileOutputStream(output), orinalOWL);
}
/**
* Save the ontology as OWL/XML. It first includes new meta data about the slimming process.
*
* @param output
* @param originalOWL
* @throws OWLOntologyStorageException
*/
public void saveAs(OutputStream output, String originalOWL) throws OWLOntologyStorageException {
// add provenance
OWLDataFactory dataFac = man.getOWLDataFactory();
// version info
OWLLiteral lit = dataFac.getOWLLiteral(
"This SLIM file was generated automatically by the eNanoMapper Slimmer "
+ "software library. For more information see "
+ "http://github.com/enanomapper/slimmer.");
OWLAnnotationProperty owlAnnotationProperty =
dataFac.getOWLAnnotationProperty(OWLRDFVocabulary.OWL_VERSION_INFO.getIRI());
OWLAnnotation anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
OWLAnnotationProperty pavImportedFrom = dataFac.getOWLAnnotationProperty(
IRI.create("http://purl.org/pav/importedFrom")
);
anno = dataFac.getOWLAnnotation(pavImportedFrom, dataFac.getOWLLiteral(originalOWL));
man.applyChange(new AddOntologyAnnotation(onto, anno));
// generation tool
lit = dataFac.getOWLLiteral("Slimmer");
owlAnnotationProperty = dataFac.getOWLAnnotationProperty(
IRI.create("http://www.geneontology.org/formats/oboInOwl#auto-generated-by")
);
anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
// generation date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
lit = dataFac.getOWLLiteral(dateFormat.format(date));
owlAnnotationProperty = dataFac.getOWLAnnotationProperty(
IRI.create("http://www.geneontology.org/formats/oboInOwl#date")
);
anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
// save to file
RDFXMLDocumentFormat format = new RDFXMLDocumentFormat();
format.setPrefix("ncicp", "http://ncicb.nci.nih.gov/xml/owl/EVS/ComplexProperties.xsd
man.saveOntology(onto, format, output);
}
/**
* This functions applies the <code>D</code> and <code>U</code> statements from the configuration
* files by traversing the OWL hierarchy and either including all parents or all children.
*
* @param instructions
* @return
*/
private Set<String> explode(Set<Instruction> instructions) {
Set<String> singleIRIs = new HashSet<String>();
for (Instruction instruction : instructions) {
String iri = instruction.getUriString();
if (instruction.getScope() == Instruction.Scope.UP) {
System.out.println("Extracting " + iri + "...");
Set<OWLEntity> entities = onto.getEntitiesInSignature(IRI.create(iri));
if (entities.size() > 0) {
OWLEntity entity = entities.iterator().next();
if (entity instanceof OWLClass) {
OWLClass clazz = (OWLClass)entity;
System.out.println("Class " + clazz);
Set<String> superClasses = allSuperClasses(clazz, onto);
for (String superClass : superClasses) {
System.out.println("Extracting " + superClass + "...");
singleIRIs.add(superClass);
}
}
}
singleIRIs.add(iri);
} else if (instruction.getScope() == Instruction.Scope.DOWN) {
System.out.println("Extracting " + iri + "...");
Set<OWLEntity> entities = onto.getEntitiesInSignature(IRI.create(iri));
if (entities.size() > 0) {
OWLEntity entity = entities.iterator().next();
if (entity instanceof OWLClass) {
OWLClass clazz = (OWLClass)entity;
System.out.println("Class " + clazz);
Set<String> subClasses = allSubClasses(clazz, onto);
for (String subClass : subClasses) {
System.out.println("Extracting " + subClass + "...");
singleIRIs.add(subClass);
}
}
}
singleIRIs.add(iri);
} else if (instruction.getScope() == Instruction.Scope.SINGLE) {
System.out.println("Extracting " + iri + "...");
singleIRIs.add(iri);
} else {
System.out.println("Cannot handle this instruction: " + instruction.getScope());
}
}
return singleIRIs;
}
/**
* This methods removes all classes, data properties, and object properties, except those
* URIs specified by the parameter. If a class is kept, the instructions also indicates
* what the new parent of the class is.
*
* @param irisToSave which IRIs are to be kept
*/
public void removeAllExcept(Set<Instruction> irisToSave) {
Set<String> singleIRIs = explode(irisToSave);
Map<String,String> newSuperClasses = getNewSuperClasses(irisToSave);
System.out.println("" + singleIRIs);
// remove classes
OWLEntityRemover remover = new OWLEntityRemover(Collections.singleton(onto));
for (OWLClass ind : onto.getClassesInSignature()) {
String indIRI = ind.getIRI().toString();
System.out.println(indIRI);
if (!singleIRIs.contains(indIRI)) {
System.out.println("Remove: " + indIRI);
ind.accept(remover);
} else {
// OK, keep this one. But does it have a new super class?
if (newSuperClasses.containsKey(indIRI)) {
String newSuperClass = newSuperClasses.get(indIRI);
OWLDataFactory factory = man.getOWLDataFactory();
System.out.println("Super class: " + newSuperClass);
OWLClass superClass = factory.getOWLClass(IRI.create(newSuperClass));
OWLAxiom axiom = factory.getOWLSubClassOfAxiom(ind, superClass);
System.out.println("Adding super class axiom: " + axiom);
AddAxiom addAxiom = new AddAxiom(onto, axiom);
man.applyChange(addAxiom);
}
}
}
// remove properties
for (OWLObjectProperty axiom : onto.getObjectPropertiesInSignature()) {
String propIRI = axiom.getIRI().toString();
System.out.println(propIRI);
if (!singleIRIs.contains(propIRI)) {
System.out.println("Remove: " + propIRI);
axiom.accept(remover);
}
}
for (OWLDataProperty axiom : onto.getDataPropertiesInSignature()) {
String propIRI = axiom.getIRI().toString();
System.out.println(propIRI);
if (!singleIRIs.contains(propIRI)) {
System.out.println("Remove: " + propIRI);
axiom.accept(remover);
}
}
man.applyChanges(remover.getChanges());
}
private Map<String, String> getNewSuperClasses(Set<Instruction> irisToSave) {
Map<String,String> newSuperClasses = new HashMap<String, String>();
for (Instruction instruction : irisToSave) {
if (instruction.getNewSuperClass() != null) {
newSuperClasses.put(instruction.getUriString(), instruction.getNewSuperClass());
}
}
return newSuperClasses;
}
/**
* This method removes all IRIs given by the parameter.
*
* @param irisToRemove
*/
public void removeAll(Set<Instruction> irisToRemove) {
Set<String> singleIRIs = explode(irisToRemove);
System.out.println("" + singleIRIs);
OWLEntityRemover remover = new OWLEntityRemover(Collections.singleton(onto));
for (OWLClass ind : onto.getClassesInSignature()) {
String indIRI = ind.getIRI().toString();
System.out.println(indIRI);
if (singleIRIs.contains(indIRI)) {
System.out.println("Remove: " + indIRI);
ind.accept(remover);
}
}
// remove properties
for (OWLObjectProperty axiom : onto.getObjectPropertiesInSignature()) {
String propIRI = axiom.getIRI().toString();
System.out.println(propIRI);
if (singleIRIs.contains(propIRI)) {
System.out.println("Remove: " + propIRI);
axiom.accept(remover);
}
}
for (OWLDataProperty axiom : onto.getDataPropertiesInSignature()) {
String propIRI = axiom.getIRI().toString();
System.out.println(propIRI);
if (singleIRIs.contains(propIRI)) {
System.out.println("Remove: " + propIRI);
axiom.accept(remover);
}
}
man.applyChanges(remover.getChanges());
}
private Set<String> allSuperClasses(OWLClass clazz,
OWLOntology onto) {
Set<String> allSuperClasses = new HashSet<String>();
Stream<OWLClassExpression> superClasses = Searcher.sup(onto.subClassAxiomsForSubClass(clazz));
superClasses.forEach(superClass -> {
OWLClass superOwlClass = superClass.asOWLClass();
String superIri = superOwlClass.getIRI().toString();
allSuperClasses.add(superIri);
// recurse
allSuperClasses.addAll(allSuperClasses(superOwlClass, onto));
});
return allSuperClasses;
}
/**
* Helper method that returns a collection sub classes of the given class.
*
* @param clazz
* @param onto
* @return
*/
private Set<String> allSubClasses(OWLClass clazz,
OWLOntology onto) {
Set<String> allSubClasses = new HashSet<String>();
System.out.println("clazz: " + clazz);
Stream<OWLClassExpression> subClasses = Searcher.sub(onto.subClassAxiomsForSuperClass(clazz));
subClasses.forEach(subClass -> {
// skip itself
OWLClass subOwlClass = subClass.asOWLClass();
System.out.println("subclass: " + subOwlClass);
String subIri = subOwlClass.getIRI().toString();
allSubClasses.add(subIri);
// recurse
allSubClasses.addAll(allSubClasses(subOwlClass, onto));
});
System.out.println("subclass count: " + allSubClasses.size());
return allSubClasses;
}
@SuppressWarnings("serial")
Map<String,String> mappings = new HashMap<String,String>() {{
}};
private void addMappings(OWLOntologyManager m, String root) {
if (!root.endsWith("/")) root = (root + "/").replace(" ", "%20");
for (String ontoIRI : mappings.keySet()) {
String localPart = mappings.get(ontoIRI);
m.addIRIMapper(new SimpleIRIMapper(
IRI.create(ontoIRI), IRI.create("file://" + root + localPart)
));
System.out.println(" added: " + IRI.create("file://" + root + localPart));
}
}
} |
package com.github.sergueik.swet;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.PropertyConfigurator;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import edu.emory.mathcs.backport.java.util.Collections;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
public class Utils {
private static Utils instance = new Utils();
private static Keys keyCTRL;
private static final String getSWDCommand = "return document.swdpr_command === undefined ? '' : document.swdpr_command;";
private static String osName = OSUtils.getOsName();
private WebDriver driver;
private WebDriverWait wait;
private Actions actions;
private int flexibleWait = 5;
public void setFlexibleWait(int flexibleWait) {
this.flexibleWait = flexibleWait;
this.wait = new WebDriverWait(this.driver, flexibleWait);
}
public void setDriver(WebDriver value) {
this.driver = value;
}
public void setActions(Actions value) {
this.actions = value;
}
private Utils() {
}
public static Utils getInstance() {
return instance;
}
private static String defaultScript = "ElementSearch.js";
public String getScriptContent(String resourceFileName) {
try {
/* System.err.println("Script contents: " + getResourceURI(resourceFileName)); */
final InputStream stream = this.getClass().getClassLoader()
.getResourceAsStream(resourceFileName);
final byte[] bytes = new byte[stream.available()];
stream.read(bytes);
return new String(bytes, "UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// NOTE: getResourceURI does not work well with standalone app.
public String getResourceURI(String resourceFileName) {
try {
URI uri = this.getClass().getClassLoader().getResource(resourceFileName)
.toURI();
// System.err.println("Resource URI: " + uri.toString());
return uri.toString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public InputStream getResourceStream(String resourceFilePath) {
return this.getClass().getClassLoader()
.getResourceAsStream(resourceFilePath);
}
public String getResourcePath(String resourceFileName) {
return String.format("%s/src/main/resources/%s",
System.getProperty("user.dir"), resourceFileName);
}
public String writeDataJSON(Map<String, String> data, String defaultPayload) {
String payload = defaultPayload;
JSONObject json = new JSONObject();
try {
for (String key : data.keySet()) {
json.put(key, data.get(key));
}
StringWriter wr = new StringWriter();
json.write(wr);
payload = wr.toString();
} catch (JSONException e) {
System.err.println("Exception (ignored): " + e);
}
return payload;
}
public String readData(Optional<Map<String, String>> parameters) {
return readData(null, parameters);
}
public String readData(String payload,
Optional<Map<String, String>> parameters) {
Map<String, String> collector = (parameters.isPresent()) ? parameters.get()
: new HashMap<>();
String data = (payload == null)
? "{ \"Url\": \"http:
: payload;
try {
JSONObject elementObj = new JSONObject(data);
@SuppressWarnings("unchecked")
Iterator<String> propIterator = elementObj.keys();
while (propIterator.hasNext()) {
String propertyKey = propIterator.next();
String propertyVal = elementObj.getString(propertyKey);
// logger.info(propertyKey + ": " + propertyVal);
System.err.println("readData: " + propertyKey + ": " + propertyVal);
collector.put(propertyKey, propertyVal);
}
} catch (JSONException e) {
System.err.println("Exception (ignored): " + e.toString());
return null;
}
return collector.get("ElementCodeName");
}
public void flushVisualSearchResult() {
executeScript("document.swdpr_command = undefined;");
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
public String readVisualSearchResult(String payload) {
return readVisualSearchResult(payload,
Optional.<Map<String, String>> empty());
}
public String readVisualSearchResult(final String payload,
Optional<Map<String, String>> parameters) {
Boolean collectResults = parameters.isPresent();
Map<String, String> collector = (collectResults) ? parameters.get()
: new HashMap<>();
String result = readData(payload, Optional.of(collector));
assertTrue(collector.containsKey("ElementId"));
// NOTE: elementCodeName will not be set if
// user clicked the SWD Table Close Button
// ElementId is always set
// TODO: read the 'ElementSelectedBy'
return result;
}
public void highlight(WebElement element, long highlight_interval) {
try {
new WebDriverWait(driver, flexibleWait)
.until(ExpectedConditions.visibilityOf(element));
executeScript("arguments[0].style.border='3px solid yellow'", element);
Thread.sleep(highlight_interval);
executeScript("arguments[0].style.border=''", element);
} catch (InterruptedException e) {
System.err.println("Exception (ignored): " + e.toString());
}
}
public void completeVisualSearch(String elementCodeName) {
WebElement swdAddElementButton = null;
try {
WebElement swdControl = wait.until(ExpectedConditions
.visibilityOf(driver.findElement(By.id("SWDTable"))));
assertThat(swdControl, notNullValue());
WebElement swdCodeID = wait.until(ExpectedConditions.visibilityOf(
swdControl.findElement(By.id("SwdPR_PopUp_CodeIDText"))));
assertThat(swdCodeID, notNullValue());
// Act
swdCodeID.sendKeys(elementCodeName);
swdAddElementButton = wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver _driver) {
System.err.println("Waiting for the element to become available...");
Iterator<WebElement> _elements = _driver
.findElements(By
.cssSelector("div#SwdPR_PopUp > form > input[type='button']"))
.iterator();
WebElement result = null;
Pattern pattern = Pattern.compile(Pattern.quote("Add element"),
Pattern.CASE_INSENSITIVE);
while (_elements.hasNext()) {
WebElement _element = _elements.next();
Matcher matcher = pattern.matcher(_element.getAttribute("value"));
if (matcher.find()) {
result = _element;
break;
}
}
return result;
}
});
} catch (Exception e) {
ExceptionDialogEx.getInstance().render(e);
if (driver != null) {
try {
// NOTE: BrowserDriver static method
BrowserDriver.close();
} catch (Exception ex) {
System.err.println("Exception (ignored): " + ex.toString());
}
}
}
assertThat(swdAddElementButton, notNullValue());
highlight(swdAddElementButton);
flash(swdAddElementButton);
// Act
swdAddElementButton.click();
}
public void completeVisualSearchSaved(String elementCodeName) {
/*
WebElement swdControl = wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver d) {
WebElement e = d.findElement(By.id("SWDTable"));
return e.isDisplayed() ? e : null;
}
});
*/
WebElement swdControl = wait.until(
ExpectedConditions.visibilityOf(driver.findElement(By.id("SWDTable"))));
assertThat(swdControl, notNullValue());
/*
WebElement swdCodeID = wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver d) {
WebElement e = d.findElement(By.id("SwdPR_PopUp_CodeIDText"));
return e.isDisplayed() ? e : null;
}
});
*/
WebElement swdCodeID = wait.until(ExpectedConditions
.visibilityOf(swdControl.findElement(By.id("SwdPR_PopUp_CodeIDText"))));
assertThat(swdCodeID, notNullValue());
swdCodeID.sendKeys(elementCodeName);
/*
WebElement swdAddElementButton = wait
.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver d) {
WebElement e = d.findElement(By.cssSelector(
"div#SwdPR_PopUp > input[type='button'][value='Add element']"));
System.err.println(
"in apply iterator (1): Text = " + e.getAttribute("value"));
return e.isDisplayed() ? e : null;
}
});
*/
/*
WebElement swdAddElementButton = wait
.until(ExpectedConditions.visibilityOf(swdControl.findElement(
By.xpath("//input[@type='button'][@value='Add element']"))));
assertThat(swdAddElementButton, notNullValue());
*/
WebElement swdAddElementButton = null;
try {
swdAddElementButton = wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver _driver) {
System.err.println("Waiting for the element to become available...");
Iterator<WebElement> _elements = _driver
.findElements(By
.cssSelector("div#SwdPR_PopUp > form > input[type='button']"))
.iterator();
WebElement result = null;
Pattern pattern = Pattern.compile(Pattern.quote("Add element"),
Pattern.CASE_INSENSITIVE);
while (_elements.hasNext()) {
WebElement _element = _elements.next();
Matcher matcher = pattern.matcher(_element.getAttribute("value"));
if (matcher.find()) {
result = _element;
break;
}
}
return result;
}
});
} catch (Exception e) {
// TODO: dialog
// ExceptionDialogEx.getInstance().render(e);
System.err.println("Exception: " + e.toString());
}
assertThat(swdAddElementButton, notNullValue());
highlight(swdAddElementButton);
flash(swdAddElementButton);
// Act
swdAddElementButton.click();
}
public void closeVisualSearch() {
WebElement swdControl = wait.until(
ExpectedConditions.visibilityOf(driver.findElement(By.id("SWDTable"))));
assertThat(swdControl, notNullValue());
WebElement swdCloseButton = wait.until(ExpectedConditions.visibilityOf(
swdControl.findElement(By.id("SwdPR_PopUp_CloseButton"))));
assertThat(swdCloseButton, notNullValue());
highlight(swdCloseButton);
swdCloseButton.click();
}
private void closeVisualSearchSaved() {
WebElement swdControl = wait.until(
ExpectedConditions.visibilityOf(driver.findElement(By.id("SWDTable"))));
assertThat(swdControl, notNullValue());
/*
WebElement swdCloseButton = null;
try {
swdCloseButton = wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver d) {
Iterator<WebElement> i = d
.findElements(By.id("SwdPR_PopUp_CloseButton")).iterator();
WebElement result = null;
// "(?:" + "Navigate Back" + ")"
Pattern pattern = Pattern.compile(Pattern.quote("X"),
Pattern.CASE_INSENSITIVE);
while (i.hasNext()) {
WebElement e = (WebElement) i.next();
String t = e.getText();
// System.err.println("in apply iterator (2): Text = " + t);
Matcher matcher = pattern.matcher(t);
if (matcher.find()) {
result = e;
break;
}
}
return result;
}
});
assertThat(swdCloseButton, notNullValue());
utils.highlight(swdCloseButton);
swdCloseButton.click();
} catch (Exception e) {
// TODO: dialog
System.err.println("Exception: " + e.toString());
}
*/
WebElement swdCloseButton = wait.until(ExpectedConditions.visibilityOf(
swdControl.findElement(By.id("SwdPR_PopUp_CloseButton"))));
assertThat(swdCloseButton, notNullValue());
highlight(swdCloseButton);
swdCloseButton.click();
}
public String getElementText(WebElement element) {
String script = "var element = arguments[0];var text = element.innerText || element.textContent || ''; return text;";
return (String) executeScript(script, element);
}
public void inspectElement(WebElement element) {
keyCTRL = osName.startsWith("mac") ? Keys.COMMAND : Keys.CONTROL;
if (osName.startsWith("mac")) {
actions.keyDown(keyCTRL).build().perform();
actions.moveToElement(element).contextClick().build().perform();
actions.keyUp(keyCTRL).build().perform();
} else {
actions.moveToElement(element).build().perform();
actions.keyDown(keyCTRL).contextClick().keyUp(keyCTRL).build().perform();
}
// Assert
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
public void highlight(WebElement element) {
highlight(element, 100);
}
public static boolean createFolder(String path) throws Exception {
File dir = new File(path.trim());
if (!dir.exists()) {
return dir.mkdir();
} else
return false;
}
/*
public static String getDate() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date);
} catch (Exception e) {
}
return "";
}
public static String getTime() {
try {
DateFormat dateFormat = new SimpleDateFormat("HHmmss");
Date date = new Date();
return dateFormat.format(date);
} catch (Exception e) {
}
return "";
}
*/
public static void writeToFile(List<String> content, String filename,
Boolean overwriteFlag) {
File file = new File(filename);
if (overwriteFlag) {
try {
file.createNewFile();
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (String line : content) {
bw.write(line);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Write content to " + filename + " succesfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<String> readFileLineByLine(String filename)
throws IOException {
FileInputStream fis = new FileInputStream(filename);
// Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
List<String> res = new ArrayList<>();
String line = null;
while ((line = br.readLine()) != null) {
res.add(line);
}
br.close();
return res;
}
// origin:
public static String getPropertyEnv(String name, String defaultValue) {
String value = System.getProperty(name);
if (value == null) {
value = System.getenv(name);
if (value == null) {
value = defaultValue;
}
}
return value;
}
public static String resolveEnvVars(String input) {
if (null == input) {
return null;
}
Pattern p = Pattern.compile("\\$(?:\\{(\\w+)\\}|(\\w+))");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String envVarName = null == m.group(1) ? m.group(2) : m.group(1);
String envVarValue = System.getenv(envVarName);
m.appendReplacement(sb,
null == envVarValue ? "" : envVarValue.replace("\\", "\\\\"));
}
m.appendTail(sb);
return sb.toString();
}
// TODO: array
public void injectScripts(Optional<String> script) {
ArrayList<String> scripts = (defaultScript == null) ? new ArrayList<>()
: new ArrayList<>(Arrays.asList(getScriptContent(defaultScript)));
if (script.isPresent()) {
scripts.add(script.get());
}
for (String s : scripts) {
System.err
.println(String.format("Executing: %s\u2026", s.substring(0, 30)));
if (s != null)
executeScript(s);
}
}
public void injectElementSearch(Optional<String> script) {
List<String> scripts = new ArrayList<>(
Arrays.asList(getScriptContent(defaultScript)));
if (script.isPresent()) {
scripts.add(script.get());
}
for (String s : scripts) {
if (s != null)
System.err.println(
String.format("Adding the script: %s\u2026", s.substring(0, 100)));
executeScript(s);
}
}
public Object executeScript(String script, Object... arguments) {
if (driver != null && (driver instanceof JavascriptExecutor)) {
JavascriptExecutor javascriptExecutor = JavascriptExecutor.class
.cast(driver);
// IE: org.openqa.selenium.NoSuchWindowException
// Chrome: Exception in thread "main"
// org.openqa.selenium.WebDriverException: disconnected: not connected to
// DevTools
return javascriptExecutor.executeScript(script, arguments);
} else {
throw new RuntimeException(
"Script execution failed: driver it not defined properly");
}
}
public String readManifestVersion() {
CodeSource src = this.getClass().getProtectionDomain().getCodeSource();
String result = null;
String manifestTag = "Implementation-Version: (\\d+\\.\\d+(?:\\.\\d+)(?:\\-SNAPSHOT)*)";
try {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry ze = null;
while ((ze = zip.getNextEntry()) != null) {
String manifestResourcePath = ze.getName();
if (manifestResourcePath.endsWith("MANIFEST.MF")) {
InputStream inputStream = getResourceStream(manifestResourcePath);
String manifestSource = IOUtils.toString(inputStream, "UTF8");
Pattern pattern = Pattern.compile(manifestTag,
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(Pattern.quote(manifestSource));
if (matcher.find()) {
result = matcher.group(1);
System.err.println("Discovered version: " + result
+ " in manifest : " + manifestResourcePath);
}
IOUtils.closeQuietly(inputStream);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String getPayload() {
return executeScript(getSWDCommand).toString();
}
// sorting elements by valueColumn, returns Array List of indexColumn
public List<String> sortSteps(Map<String, Map<String, String>> testData,
String indexColumn, String valueColumn) {
List<String> sortedSteps = new ArrayList<>();
Map<String, Integer> elementSteps = testData.values().stream()
.collect(Collectors.toMap(o -> o.get(indexColumn),
o -> Integer.parseInt(o.get(valueColumn))));
/*
elementSteps = testData.keySet().stream().collect(Collectors.toMap(o -> o,
o -> Integer.parseInt(testData.get(o).get(valueColumn))));
*/
List<Entry<String, Integer>> stepNumbers = new ArrayList<>();
stepNumbers.addAll(elementSteps.entrySet());
Collections.sort(stepNumbers, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> obj_left,
Entry<String, Integer> obj_right) {
return obj_left.getValue().compareTo(obj_right.getValue());
}
});
return stepNumbers.stream().map(e -> e.getKey())
.collect(Collectors.toList());
}
public void sleep(Integer seconds) {
long secondsLong = (long) seconds;
try {
Thread.sleep(secondsLong);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void flash(WebElement element) {
String bgcolor = element.getCssValue("backgroundColor");
for (int i = 0; i < 3; i++) {
changeColor("rgb(0,200,0)", element);
changeColor(bgcolor, element);
}
}
public void changeColor(String color, WebElement element) {
executeScript("arguments[0].style.backgroundColor = '" + color + "'",
element);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
// sorting example from
// currently not used
public <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(
Map<K, V> map) {
return map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
}
public void initializeLogger() {
Properties logProperties = new Properties();
String log4J_properties = String.format("%s/%s/%s",
System.getProperty("user.dir"), "src/main/resources", "log4j.xml");
try {
logProperties.load(new FileInputStream(log4J_properties));
PropertyConfigurator.configure(logProperties);
} catch (IOException e) {
throw new RuntimeException("Fail to load: " + log4J_properties);
}
}
} |
package com.justjournal.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Rss file record.
*
* @author Lucas Holt
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@Entity
@Table(name = "rss_cache")
public final class RssCache implements Serializable {
private static final long serialVersionUID = 7699995609479936367L;
@Id
@GeneratedValue
private int id;
private int interval;
@Temporal(value = TemporalType.TIMESTAMP)
@Column(name = "lastupdated")
private Date lastUpdated;
//TODO: mark as tinytext
@Column(name = "uri", nullable = false, length = 255)
private String uri;
@Column(name = "content", nullable = false, length = 65535, columnDefinition = "TEXT")
private String content;
@JsonCreator
public RssCache() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} |
//Namespace
package com.katujo.web.utils;
//Imports
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* JSON util methods that makes it easier to work with GSON/JSON in java.
* @author Johan Hertz
*
*/
public class JsonUtils
{
//The map that holds the translation from SQL column format to JSON field name
//<SQL_COLUMN, JSON_FIELD>
private static final ConcurrentHashMap<String, String> createJsonObjectColumnTranslator = new ConcurrentHashMap<String, String>();
//Database types used when creating JSON objects and arrays
private static enum DatabaseTypes
{
BOOLEAN,
DATE,
DOUBLE,
INTEGER,
LONG,
STRING,
TIMESTAMP
}
/**
* Get the member value as an object.
* @param element
* @param member
* @return
* @throws Exception
*/
public static Object get(JsonElement element, String member) throws Exception
{
//Check if null
if(element == null)
return null;
//Check if object
if(!element.isJsonObject())
throw new Exception("Element is not a JSON object");
//Get the object value for the member
return get(element.getAsJsonObject(), member);
}
/**
* Get the member value as an object.
* @param obj
* @param member
* @return
* @throws Exception
*/
public static Object get(JsonObject obj, String member) throws Exception
{
//The value is null
if(obj.get(member) == null || obj.get(member).isJsonNull())
return null;
//Get the primitive
JsonPrimitive primitive = obj.get(member).getAsJsonPrimitive();
//Boolean
if(primitive.isBoolean())
return primitive.getAsBoolean();
//Number/Double
if(primitive.isNumber())
return primitive.getAsDouble();
//String
if(primitive.isString())
return primitive.getAsString();
//Could not find a matching type
throw new Exception("The member type is not regonised");
}
/**
* Get the date from a number member.
* @param element
* @param member
* @return
* @throws Exception
*/
public static Date getDate(JsonElement element, String member) throws Exception
{
//Check if null
if(element == null)
return null;
//Check if object
if(!element.isJsonObject())
throw new Exception("Element is not a JSON object");
//Get the date
return getDate(element.getAsJsonObject(), member);
}
/**
* Get the date from a number member.
* @param obj
* @param member
* @return
* @throws Exception
*/
public static Date getDate(JsonObject obj, String member) throws Exception
{
//Get the getObject
Object getObj = get(obj, member);
//Check if getObject is null
if(getObj == null)
return null;
//Check if getObject is not a Double
if(!(getObj instanceof Double))
throw new Exception("Only number members can be cast to Date");
//Create a date from the number value
return new Date(((Double) getObj).longValue());
}
/**
* Check if the object member is true or false.
* @param element
* @param member
* @return
* @throws Exception
*/
public static boolean is(JsonElement element, String member) throws Exception
{
//Return false if element not set
if(element == null)
return false;
//Call the is function with the element as an object
if(element.isJsonObject())
return is(element.getAsJsonObject(), member);
//The is function can only handle JSON objects
throw new Exception("JSON element is not a JSON object");
}
/**
* Check if the object member is true or false.
*
* <table border="1">
* <tr><td><b>Type</b></td><td><b>Value</b></td><td><b>Returns</b></td></tr>
* <tr><td>Array</td><td>any but null</td><td>true</td></tr>
* <tr><td>Array</td><td>null</td><td>false</td></tr>
* <tr><td>Boolean</td><td>true</td><td>true</td></tr>
* <tr><td>Boolean</td><td>false</td><td>false</td></tr>
* <tr><td>Number</td><td>Any but 0</td><td>true</td></tr>
* <tr><td>Number</td><td>0</td><td>false</td></tr>
* <tr><td>String</td><td>Any but empty</td><td>true</td></tr>
* <tr><td>String</td><td>empty</td><td>false</td></tr>
* <tr><td>Object</td><td>any but null</td><td>true</td></tr>
* <tr><td>Object</td><td>null</td><td>false</td></tr>
* <tr><td>*</td><td>obj or member is null or JSON null</td><td>false</td></tr>
* </table>
*
* @param obj
* @param member
* @return
* @throws Exception
*/
public static boolean is(JsonObject obj, String member) throws Exception
{
//If object is not set return false
if(obj == null || obj.isJsonNull())
return false;
//If the object does not have the member return false
if(!obj.has(member))
return false;
//If the member is null return false
if(obj.get(member) == null || obj.get(member).isJsonNull())
return false;
//If the member is an object or an array return true (if set)
if(obj.get(member).isJsonObject() || obj.get(member).isJsonArray())
return true;
//Get the object
Object get = get(obj, member);
//If the get object is null return false
if(get == null)
return false;
//If this is a boolean return as is
if(get instanceof Boolean)
return (Boolean) get;
//Double: 0 is false all other number are true
if(get instanceof Double)
return !((Double) get == 0);
//String: empty string is false, all other are true
if(get instanceof String)
return !"".equals(get);
//Could not find a matching type
throw new Exception("The member type is not regonised");
}
/**
* Create a JSON array of JSON objects to hold the data in
* the result set.
* @param result
* @return
* @throws Exception
*/
public static JsonArray createJsonArray(ResultSet result) throws Exception
{
//Try to create the data
try
{
//Create the JSON array to hold the data
JsonArray data = new JsonArray();
//Get the meta data
ResultSetMetaData meta = result.getMetaData();
//Get the column types and the field names
DatabaseTypes[] columnTypes = getColumnTypes(meta);
String[] fieldNames = getFieldNames(meta);
//Read the result into the data
while(result.next())
data.add(createJsonObject(result, columnTypes, fieldNames));
//Return the data
return data;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to create JSON array from result set", ex);
}
}
/**
* Create a JSON object from a result set row.
* @param result
* @return
* @throws Exception
*/
public static JsonObject createJsonObject(ResultSet result) throws Exception
{
//Get the meta data
ResultSetMetaData meta = result.getMetaData();
//Create the JSON object
return createJsonObject(result, getColumnTypes(meta), getFieldNames(meta));
}
/**
* Create a JSON object from a result set row using the column types and the field names.
* @param result
* @param columnTypes
* @param fieldNames
* @return
* @throws Exception
*/
public static JsonObject createJsonObject(ResultSet result, DatabaseTypes[] columnTypes, String[] fieldNames) throws Exception
{
//Try to create the JSON object
try
{
//Create the JSON object
JsonObject obj = new JsonObject();
//Read the data into the object
for(int i=0; i<fieldNames.length; i++)
{
//Add the data to the object
if(DatabaseTypes.STRING == columnTypes[i]) obj.addProperty(fieldNames[i], result.getString(i+1));
else if(DatabaseTypes.DOUBLE == columnTypes[i]) obj.addProperty(fieldNames[i], getDouble(result, i+1));
else if(DatabaseTypes.INTEGER == columnTypes[i]) obj.addProperty(fieldNames[i], getInteger(result, i+1));
else if(DatabaseTypes.BOOLEAN == columnTypes[i]) obj.addProperty(fieldNames[i], getBoolean(result, i+1));
else if(DatabaseTypes.LONG == columnTypes[i]) obj.addProperty(fieldNames[i], getLong(result, i+1));
else if(DatabaseTypes.DATE == columnTypes[i]) obj.addProperty(fieldNames[i], getDate(result, i+1));
else if(DatabaseTypes.TIMESTAMP == columnTypes[i]) obj.addProperty(fieldNames[i], getTimestamp(result, i+1));
else throw new Exception("No mapping made for column type " + columnTypes[i]);
}
//Return the JSON object
return obj;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to create the JSON object from the current result set row", ex);
}
}
/**
* Get the column types.
* @param meta
* @return
* @throws Exception
*/
private static DatabaseTypes[] getColumnTypes(ResultSetMetaData meta) throws Exception
{
//Create the column index(used in catch)
int column = 0;
//Try to get the column types
try
{
//Create the types array
DatabaseTypes[] types = new DatabaseTypes[meta.getColumnCount()];
//Populate the types
for(column=0; column<types.length; column++)
{
//Get the column type
String type = meta.getColumnClassName(column+1);
//If class column type not found use database column type instead
if(type == null)
type = meta.getColumnTypeName(column+1);
//Type could not be set (will throw error)
if(type == null)
type = "NOT_SET";
//Change to type long if field is BIG_DECIMAL and does not have a scale (Oracle number fix)
if(meta.getScale(column+1) == 0 && BigDecimal.class.getName().equals(type))
type = Long.class.getName();
//Add the types to the array
if(String.class.getName().equals(type)) types[column] = DatabaseTypes.STRING;
else if(Object.class.getName().equals(type)) types[column] = DatabaseTypes.STRING; //This is for null values like SELECT NULL AS MY_COLUMN FROM ...
else if(Double.class.getName().equals(type)) types[column] = DatabaseTypes.DOUBLE;
else if(BigDecimal.class.getName().equals(type) || type.contains("BINARY_DOUBLE")) types[column] = DatabaseTypes.DOUBLE;
else if(Integer.class.getName().equals(type)) types[column] = DatabaseTypes.INTEGER;
else if(Long.class.getName().equals(type) || BigInteger.class.getName().equals(type)) types[column] = DatabaseTypes.LONG;
else if(java.sql.Timestamp.class.getName().equals(type)) types[column] = DatabaseTypes.TIMESTAMP;
else if(java.sql.Date.class.getName().equals(type)) types[column] = DatabaseTypes.DATE;
else if(type != null && (type.toUpperCase().endsWith(".CLOB") || "BINARY".equals(meta.getColumnTypeName(column+1)))) types[column] = DatabaseTypes.STRING;
else if(Boolean.class.getName().equals(type)) types[column] = DatabaseTypes.BOOLEAN;
else throw new Exception("There is no mapping for type: " + type);
}
//Return the types
return types;
}
//Failed
catch(Exception ex)
{
//Create the column name
String name = "";
//Try to get the column name
try{name = meta.getColumnLabel(column+1);} catch(Throwable t) {}
//Throw the exception
throw new Exception("Failed to get the column types from the meta data (failed on column " + name + " )", ex);
}
}
/**
* Get the field names for the columns.
* @param meta
* @return
* @throws Exception
*/
private static String[] getFieldNames(ResultSetMetaData meta) throws Exception
{
//Try to get the field names
try
{
//Create the names array
String[] fieldNames = new String[meta.getColumnCount()];
//Populate the field names
for(int i=0; i<fieldNames.length; i++)
fieldNames[i] = columnToField(meta.getColumnLabel(i+1));
//Return the field names
return fieldNames;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get the field names", ex);
}
}
/**
* Translate a column name to a JSON field name.
* @param column
* @return
*/
private static String columnToField(String column)
{
//Get the field name
String field = createJsonObjectColumnTranslator.get(column);
//Create the field if not set
if(field == null)
{
//Split the column
String[] columnSplit = column.split("_");
//Create the string builder to hold the filed
StringBuilder builder = new StringBuilder();
//Create the name in the builder
for(int y=0; y<columnSplit.length; y++)
if(y==0)
builder.append(columnSplit[y].toLowerCase());
else if(columnSplit[y].length() <= 2)
builder.append(columnSplit[y]);
else builder.append(columnSplit[y].substring(0, 1) + columnSplit[y].substring(1).toLowerCase());
//Set the filed
field = builder.toString();
//Add the filed to the map
createJsonObjectColumnTranslator.put(column, field);
}
//Return the filed
return field;
}
/**
* Get the boolean value if set or null if null.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Boolean getBoolean(ResultSet result, int index) throws Exception
{
//Try to get the value
try
{
//Get the value
boolean value = result.getBoolean(index);
//Check if null
if(result.wasNull())
return null;
//Return the value
return value;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get boolean form index " + index, ex);
}
}
/**
* Get the timestamp as long for the date if set or null if not set.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Long getDate(ResultSet result, int index) throws Exception
{
//Get the date
Date date = result.getDate(index);
//Return null if null
if(date == null)
return null;
//Return the timestamp if set
return date.getTime();
}
/**
* Get the double value if set or null if null.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Double getDouble(ResultSet result, int index) throws Exception
{
//Try to get the value
try
{
//Get the value
double value = result.getDouble(index);
//Check if null
if(result.wasNull())
return null;
//Return the value
return value;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get double form index " + index, ex);
}
}
/**
* Get the integer value if set or null if null.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Integer getInteger(ResultSet result, int index) throws Exception
{
//Try to get the value
try
{
//Get the value
int value = result.getInt(index);
//Check if null
if(result.wasNull())
return null;
//Return the value
return value;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get integer form index " + index, ex);
}
}
/**
* Get the timestamp as long for the timestamp if set or null if not set.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Long getTimestamp(ResultSet result, int index) throws Exception
{
//Get the date
Timestamp value = result.getTimestamp(index);
//Return null if null
if(value == null)
return null;
//Return the timestamp if set
return value.getTime();
}
/**
* Get the long value if set or null if null.
* @param result
* @param index
* @return
* @throws Exception
*/
private static Long getLong(ResultSet result, int index) throws Exception
{
//Try to get the value
try
{
//Get the value
long value = result.getLong(index);
//Check if null
if(result.wasNull())
return null;
//Return the value
return value;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get long form index " + index, ex);
}
}
} |
package com.maxdemarzi;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.event.LabelEntry;
import org.neo4j.graphdb.event.TransactionData;
import java.util.HashSet;
import java.util.Set;
public class SuspectRunnable implements Runnable {
private static TransactionData td;
private static GraphDatabaseService db;
public SuspectRunnable (TransactionData transactionData, GraphDatabaseService graphDatabaseService) {
td = transactionData;
db = graphDatabaseService;
}
@Override
public void run() {
try (Transaction tx = db.beginTx()) {
Set<Node> suspects = new HashSet<>();
for (Node node : td.createdNodes()) {
if (node.hasLabel(Labels.Suspect)) {
suspects.add(node);
//GmailSender.sendEmail("maxdemarzi@gmail.com", "A new Suspect has been created in the System!", "boo-yeah");
System.out.println("A new Suspect has been created!");
}
}
for (LabelEntry labelEntry : td.assignedLabels()) {
if (labelEntry.label().name().equals(Labels.Suspect.name()) && !suspects.contains(labelEntry.node())) {
System.out.println("A new Suspect has been identified!");
suspects.add(labelEntry.node());
}
}
for (Relationship relationship : td.createdRelationships()) {
if (relationship.isType(RelationshipTypes.KNOWS)) {
for (Node user : relationship.getNodes()) {
if (user.hasLabel(Labels.Suspect)) {
System.out.println("A new direct relationship to a Suspect has been created!");
}
for (Relationship knows : user.getRelationships(Direction.BOTH, RelationshipTypes.KNOWS)) {
Node otherUser = knows.getOtherNode(user);
if (otherUser.hasLabel(Labels.Suspect) && !otherUser.equals(relationship.getOtherNode(user))) {
System.out.println("A new indirect relationship to a Suspect has been created!");
}
}
}
}
}
}
}
} |
package com.northpine.scrape;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.northpine.scrape.ogr.GeoCollector;
import com.northpine.scrape.ogr.OgrCollector;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.northpine.scrape.JobManager.MAN;
import static com.northpine.scrape.request.HttpRequester.Q;
import static java.lang.String.format;
import static java.util.concurrent.CompletableFuture.runAsync;
/**
* Scrapes ArcGIS REST Servers
*/
public class ScrapeJob {
private static final int CHUNK_SIZE = 200;
private static final String OUTPUT_FOLDER = "output";
private static final Logger log = LoggerFactory.getLogger( ScrapeJob.class );
private final ExecutorService executor;
private String layerName;
private AtomicInteger current;
private AtomicInteger done;
private AtomicInteger total;
private AtomicBoolean failed;
private boolean isDone;
private String outputFileBase;
private String outputZip;
private String layerUrl;
private String queryUrlStr;
private String failMessage;
private File zipFile;
/**
* @param layerUrl Does not include "/query" appended to end of url to layer.
*/
public ScrapeJob(String layerUrl) {
executor = Executors.newWorkStealingPool();
current = new AtomicInteger();
total = new AtomicInteger();
failed = new AtomicBoolean( false);
this.layerUrl = layerUrl ;
this.queryUrlStr = layerUrl + "/query";
this.layerName = getLayerName();
this.outputFileBase = OUTPUT_FOLDER + "/" + layerName;
this.outputZip = OUTPUT_FOLDER + "/" + layerName + ".zip";
}
public void startScraping() {
current = new AtomicInteger();
done = new AtomicInteger();
isDone = false;
URL queryUrl = getURL( queryUrlStr + "?where=1=1&returnIdsOnly=true&f=json&outSR=3857" );
JSONObject idsJson = Q.submitSyncRequest(queryUrl.toString())
.orElseThrow(RuntimeException::new);
JSONArray arr = idsJson.getJSONArray( "objectIds" );
OgrCollector collector = new GeoCollector(outputFileBase);
buildIdStrs( arr ).stream()
.map( idListStr -> "OBJECTID in (" + idListStr + ")" )
.forEach(whereClause -> {
try {
String file = outputFileBase + current.incrementAndGet() + ".json";
var request = Unirest.get(queryUrlStr)
.queryString("where", whereClause)
.queryString("outFields", "*")
.queryString("f", "json")
.asBinary();
if(request.getStatus() == 200) {
writeToFile(request.getRawBody(), file);
var wasSuccessful = collector.addJsonToPool(file);
if(wasSuccessful) {
var numDone = done.incrementAndGet();
var numTotal = total.get();
if(numDone % (numTotal / 10) == 0) {
log.info(format("%d/%d requests done for %s", numDone, numTotal, layerUrl));
}
} else {
failJob("Couldn't run ogr2ogr");
}
} else {
throw new RuntimeException(request.getStatusText());
}
} catch (UnirestException httpException) {
log.error("Couldn't connect to server", httpException);
failJob("Connecting to server for query failed");
}
});
zipFile = collector.zipUpPool();
isDone = true;
log.info("Zipped '" + outputZip + "'");
log.info("Done with job.");
}
public int getNumDone() {
if(done != null) {
return done.get();
} else {
return -1;
}
}
public void stopJob() {
executor.shutdownNow();
}
public String getName() {
return layerName;
}
public int getTotal() {
return total.get();
}
public boolean isJobDone() {
return isDone;
}
public boolean isFailed() {
return failed.get();
}
public String getFailMessage() {
return failMessage;
}
private void failJob(String failMessage) {
this.failMessage = failMessage;
failed.set( true );
}
private void writeToFile(InputStream in, String file) {
try {
Files.copy(in, Paths.get(file), StandardCopyOption.REPLACE_EXISTING);
} catch(IOException io) {
log.error("Failed to write file" + file, io);
failJob("Failed to write file");
}
}
private String getLayerName() {
String jsonDetailsUrl = layerUrl + "?f=json";
return Q.submitSyncRequest(jsonDetailsUrl)
.orElseThrow( RuntimeException::new )
.getString( "name" );
}
public String getOutput() {
if ( isJobDone() ) {
return zipFile.getAbsolutePath();
} else {
return null;
}
}
private URL getURL(String str) {
try {
return new URL( str );
} catch ( MalformedURLException e ) {
throw new IllegalArgumentException( "Query str is invalid '" + str + "'" );
} catch ( Exception e ) {
throw new IllegalArgumentException( "Just kill me now" );
}
}
private List<String> buildIdStrs(JSONArray arr) {
List<String> idChunks = new ArrayList<>();
int counter = 0;
StringBuilder sb = new StringBuilder();
boolean newRow = true;
//Probably a string
for ( Object id : arr ) {
if ( counter % CHUNK_SIZE == 0 && counter != 0 ) {
total.incrementAndGet();
sb.append( "," ).append( id );
idChunks.add( sb.toString() );
sb = new StringBuilder();
newRow = true;
} else if ( newRow ) {
sb.append( id );
newRow = false;
} else {
sb.append( "," ).append( id );
}
counter++;
}
return idChunks;
}
} |
package com.payu.sdk.utils;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.payu.sdk.PayU;
import com.payu.sdk.constants.Constants;
import com.payu.sdk.exceptions.InvalidParametersException;
import com.payu.sdk.exceptions.PayUException;
import com.payu.sdk.exceptions.SDKException.ErrorCode;
import com.payu.sdk.helper.SignatureHelper;
import com.payu.sdk.model.Address;
import com.payu.sdk.model.AddressV4;
import com.payu.sdk.model.BankListInformation;
import com.payu.sdk.model.BcashRequest;
import com.payu.sdk.model.Buyer;
import com.payu.sdk.model.CreditCard;
import com.payu.sdk.model.CreditCardToken;
import com.payu.sdk.model.CreditCardTokenInformation;
import com.payu.sdk.model.Currency;
import com.payu.sdk.model.DocumentType;
import com.payu.sdk.model.ExtraParemeterNames;
import com.payu.sdk.model.Merchant;
import com.payu.sdk.model.Order;
import com.payu.sdk.model.Payer;
import com.payu.sdk.model.PaymentCountry;
import com.payu.sdk.model.PaymentMethod;
import com.payu.sdk.model.Person;
import com.payu.sdk.model.PersonType;
import com.payu.sdk.model.RemoveCreditCardToken;
import com.payu.sdk.model.Transaction;
import com.payu.sdk.model.TransactionSource;
import com.payu.sdk.model.TransactionType;
import com.payu.sdk.model.request.Command;
import com.payu.sdk.model.request.CommandRequest;
import com.payu.sdk.model.request.Request;
import com.payu.sdk.payments.model.CreditCardTokenListRequest;
import com.payu.sdk.payments.model.CreditCardTokenRequest;
import com.payu.sdk.payments.model.PaymentMethodRequest;
import com.payu.sdk.payments.model.PaymentRequest;
import com.payu.sdk.payments.model.RemoveCreditCardTokenRequest;
import com.payu.sdk.reporting.model.ReportingRequest;
/**
* Utility for requests in the PayU SDK.
*
* @author PayU Latam
* @since 1.0.0
* @version 1.0.0, 21/08/2013
*/
public final class RequestUtil extends CommonRequestUtil {
/** The encoding used to send confirmation page */
private static final String ENCODING = Constants.DEFAULT_ENCODING
.toString();
/** The character to append parameters */
private static final String APPENDER = "&";
/** The character to assign a value param */
private static final String EQUALS = "=";
/**
* Private Constructor
*/
private RequestUtil() {
}
/**
* Builds a payments ping request
*
* @return The complete payments ping request
*/
public static PaymentRequest buildPaymentsPingRequest() {
PaymentRequest request = buildDefaultPaymentRequest();
request.setCommand(Command.PING);
return request;
}
/**
* Builds a reporting ping request
*
* @return The complete reporting request to be sent to the server
*/
public static ReportingRequest buildReportingPingRequest() {
ReportingRequest request = buildDefaultReportingRequest();
request.setCommand(Command.PING);
return request;
}
/* Payment Requests */
/**
* Builds a get bank list request
*
* @param paymentCountry
* The country in which the transaction is being done
* @return The complete bank list request
*/
public static Request buildBankListRequest(PaymentCountry paymentCountry) {
PaymentRequest request = buildDefaultPaymentRequest();
request.setCommand(Command.GET_BANKS_LIST);
request.setBankListInformation(new BankListInformation(
PaymentMethod.PSE, paymentCountry));
return request;
}
/**
* Builds a payment request
*
* @param parameters
* The parameters to be sent to the server
* @param transactionType
* The transaction that is being done
* @return The complete payment request
* @throws InvalidParametersException
*/
public static Request buildPaymentRequest(Map<String, String> parameters,
TransactionType transactionType) throws InvalidParametersException {
PaymentRequest request = buildDefaultPaymentRequest();
request.setCommand(Command.SUBMIT_TRANSACTION);
// Priority the api key obtained from PayU.apiKey
if (request.getMerchant() != null && request.getMerchant().getApiKey() == null) {
request.getMerchant().setApiKey(getParameter(parameters, PayU.PARAMETERS.API_KEY));
}
// Priority the api login obtained from PayU.apiLogin
if (request.getMerchant() != null && request.getMerchant().getApiLogin() == null) {
request.getMerchant().setApiLogin(getParameter(parameters, PayU.PARAMETERS.API_LOGIN));
}
request.setTransaction(buildTransaction(parameters, transactionType));
return request;
}
/**
* Builds the payment method list request
*
* @return The complete payment methods list request
*/
public static Request buildPaymentMethodsListRequest() {
PaymentRequest request = buildDefaultPaymentRequest();
request.setCommand(Command.GET_PAYMENT_METHODS);
return request;
}
/**
* Builds the payment method request
*
* @param paymentMethod
* @param apiKey
* @param apiLogin
* @return the payment method request
*/
public static Request buildPaymentMethodAvailability(String paymentMethod, String apiKey, String apiLogin) {
PaymentMethodRequest request = new PaymentMethodRequest();
request = (PaymentMethodRequest) buildDefaultRequest(request);
request.setTest(PayU.isTest);
request.setCommand(Command.GET_PAYMENT_METHOD_AVAILABILITY);
request.setPaymentMethod(paymentMethod);
// Priority the api key obtained from PayU.apiKey
if (request.getMerchant() != null && request.getMerchant().getApiKey() == null) {
request.getMerchant().setApiKey(apiKey);
}
// Priority the api login obtained from PayU.apiLogin
if (request.getMerchant() != null && request.getMerchant().getApiLogin() == null) {
request.getMerchant().setApiLogin(apiLogin);
}
return request;
}
/* Reporting Requests */
/**
* Builds a order details reporting by the id
*
* @param parameters
* The parameters to be sent to the server
* @return The complete reporting request to be sent to the server
* @throws InvalidParametersException
*/
public static ReportingRequest buildOrderReportingDetails(
Map<String, String> parameters) throws InvalidParametersException {
ReportingRequest request = buildDefaultReportingRequest();
request.setCommand(Command.ORDER_DETAIL);
Integer orderId = getIntegerParameter(parameters,
PayU.PARAMETERS.ORDER_ID);
Map<String, Object> details = new HashMap<String, Object>();
details.put(PayU.PARAMETERS.ORDER_ID, orderId);
request.setDetails(details);
return request;
}
/**
* Builds a order details reporting by reference code
*
* @param parameters
* The parameters to be sent to the server
* @return The complete reporting request to be sent to the server
*/
public static ReportingRequest buildOrderReportingByReferenceCode(
Map<String, String> parameters) {
ReportingRequest request = buildDefaultReportingRequest();
request.setCommand(Command.ORDER_DETAIL_BY_REFERENCE_CODE);
request.setDetails(new HashMap<String, Object>(parameters));
return request;
}
/**
* Builds a transaction reporting by the id
*
* @param parameters
* The parameters to be sent to the server
* @return The complete reporting request to be sent to the server
*/
public static ReportingRequest buildTransactionResponse(
Map<String, String> parameters) {
ReportingRequest request = buildDefaultReportingRequest();
request.setCommand(Command.TRANSACTION_RESPONSE_DETAIL);
request.setDetails(new HashMap<String, Object>(parameters));
return request;
}
/* Token Requests */
/**
* Builds a create credit card token request
*
* @param parameters
* The parameters to be sent to the server
* @return The complete create credit card token request
* @throws InvalidParametersException
*/
public static Request buildCreateTokenRequest(Map<String, String> parameters)
throws InvalidParametersException {
String nameOnCard = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);
String payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);
String dni = getParameter(parameters, PayU.PARAMETERS.PAYER_DNI);
String creditCardNumber = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_NUMBER);
String expirationDate = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE);
PaymentMethod paymentMethod = getEnumValueParameter(
PaymentMethod.class, parameters, PayU.PARAMETERS.PAYMENT_METHOD);
CreditCardTokenRequest request = new CreditCardTokenRequest();
request = (CreditCardTokenRequest) buildDefaultRequest(request);
request.setCommand(Command.CREATE_TOKEN);
request.setCreditCardToken(buildCreditCardToken(nameOnCard, payerId,
dni, paymentMethod, creditCardNumber, expirationDate));
return request;
}
/**
* Builds a get credit card token request
*
* @param parameters
* The parameters to be sent to the server
* @return The complete get credit card token request
* @throws InvalidParametersException
*/
public static Request buildGetCreditCardTokensRequest(
Map<String, String> parameters) throws InvalidParametersException {
String payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);
String tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);
String strStartDate = getParameter(parameters,
PayU.PARAMETERS.START_DATE);
String strEndDate = getParameter(parameters, PayU.PARAMETERS.END_DATE);
validateDateParameter(strStartDate, PayU.PARAMETERS.START_DATE,
Constants.DEFAULT_DATE_FORMAT);
validateDateParameter(strEndDate, PayU.PARAMETERS.END_DATE,
Constants.DEFAULT_DATE_FORMAT);
CreditCardTokenListRequest request = new CreditCardTokenListRequest();
request = (CreditCardTokenListRequest) buildDefaultRequest(request);
request.setCommand(Command.GET_TOKENS);
CreditCardTokenInformation information = new CreditCardTokenInformation();
information.setPayerId(payerId);
information.setTokenId(tokenId);
information.setStartDate(strStartDate);
information.setEndDate(strEndDate);
request.setCreditCardTokenInformation(information);
return request;
}
/**
* Builds a remove credit card token request
*
* @param parameters
* The parameters to be sent to the server
* @return The complete remove credit card token request
*/
public static Request buildRemoveTokenRequest(Map<String, String> parameters) {
String payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);
String tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);
RemoveCreditCardTokenRequest request = new RemoveCreditCardTokenRequest();
request = (RemoveCreditCardTokenRequest) buildDefaultRequest(request);
request.setCommand(Command.REMOVE_TOKEN);
RemoveCreditCardToken remove = new RemoveCreditCardToken();
remove.setPayerId(payerId);
remove.setCreditCardTokenId(tokenId);
request.setRemoveCreditCardToken(remove);
return request;
}
/* PRIVATE METHODS */
/* Default Requests Methods */
/**
* Builds a default request
*
* @return A simple request with merchant and language
*/
private static Request buildDefaultRequest(CommandRequest request) {
request.setMerchant(buildMerchant());
request.setLanguage(PayU.language);
return request;
}
/**
* Builds the default payment request
*
* @return A simple payment request with merchant, language and test
*/
private static PaymentRequest buildDefaultPaymentRequest() {
PaymentRequest request = new PaymentRequest();
request = (PaymentRequest) buildDefaultRequest(request);
request.setTest(PayU.isTest);
return request;
}
/**
* Builds the default reporting request
*
* @return A simple reporting request with merchant, language and test
*/
private static ReportingRequest buildDefaultReportingRequest() {
ReportingRequest request = new ReportingRequest();
request = (ReportingRequest) buildDefaultRequest(request);
request.setTest(PayU.isTest);
return request;
}
/**
* Builds a credit card entity
*
* @param name
* The credit card owner's name
* @param creditCardNumber
* The credit card's number
* @param expirationDate
* The credit card's expiration date
* @param securityCode
* The credit card's security code
* @return The credit cards built
*/
private static CreditCard buildCreditCard(String name,
String creditCardNumber, String expirationDate,
Boolean processWithoutCvv2, String securityCode) {
if (creditCardNumber != null || processWithoutCvv2 != null
|| securityCode != null) {
CreditCard creditCard = new CreditCard();
creditCard.setName(name);
creditCard.setNumber(creditCardNumber);
creditCard.setExpirationDate(expirationDate);
creditCard.setProcessWithoutCvv2(processWithoutCvv2);
creditCard.setSecurityCode(securityCode);
return creditCard;
}
return null;
}
/**
* builds credit card token
*
* @param nameOnCard
* the credit card owner's name
* @param payerId
* the payer's id
* @param payerIdentificationNumber
* the payer's identification number
* @param paymentMethod
* the payment method being used
* @param creditCardNumber
* the credit card's number
* @param expirationDate
* the credit card's expiration date
* @return The credit card token built
*/
private static CreditCardToken buildCreditCardToken(String nameOnCard,
String payerId, String payerIdentificationNumber,
PaymentMethod paymentMethod, String creditCardNumber,
String expirationDate) {
CreditCardToken creditCardToken = new CreditCardToken();
creditCardToken.setName(nameOnCard);
creditCardToken.setPayerId(payerId);
creditCardToken.setIdentificationNumber(payerIdentificationNumber);
creditCardToken.setPaymentMethod(paymentMethod);
creditCardToken.setExpirationDate(expirationDate);
creditCardToken.setNumber(creditCardNumber);
return creditCardToken;
}
/**
* Builds a credit card transaction
*
* @param transaction
* The transaction to modify
* @param nameOnCard
* The credit card owner's name
* @param creditCardNumber
* The credit card's number
* @param expirationDate
* The credit card's expiration date
* @param securityCode
* The credit card's security code
* @param installments
* The number of installments for the transaction
* @param createCreditCardToken
* @throws InvalidParametersException
*/
private static void buildCreditCardTransaction(Transaction transaction,
String nameOnCard, String creditCardNumber, String expirationDate,
Boolean processWithoutCvv2, String securityCode,
Integer installments, Boolean createCreditCardToken)
throws InvalidParametersException {
transaction.setCreditCard(buildCreditCard(nameOnCard, creditCardNumber,
expirationDate, processWithoutCvv2, securityCode));
if (installments != null) {
transaction.addExtraParameter(
ExtraParemeterNames.INSTALLMENTS_NUMBER.name(),
installments.toString());
}
transaction.setCreateCreditCardToken(createCreditCardToken);
}
/**
* Builds a merchant entity
*
* @return The merchant entity built
*/
private static Merchant buildMerchant() {
Merchant merchant = new Merchant();
merchant.setApiKey(PayU.apiKey);
merchant.setApiLogin(PayU.apiLogin);
return merchant;
}
/**
* Builds the order
*
* @param accountId
* The account's id number
* @param txCurrency
* The currency of the transaction
* @param txValue
* The value of the transaction
* @param description
* The description of the transaction
* @param referenceCode
* The order's reference code
* @param notifyUrl
* The confirmation page URL
* @return The order built
*/
private static Order buildOrder(Integer accountId, Currency txCurrency,
BigDecimal txValue, BigDecimal taxValue, BigDecimal taxReturnBase,
String description, String referenceCode, String notifyUrl) {
Order order = new Order();
order.setAccountId(accountId);
order.setDescription(description);
order.setLanguage(PayU.language);
order.setReferenceCode(referenceCode);
order.setNotifyUrl(notifyUrl);
order.setAdditionalValues(buildAdditionalValues(txCurrency, txValue,
taxValue, taxReturnBase));
return order;
}
/**
* Builds the buyer entity
*
* @param parameters
* The parameters map to build the buyer
* @return The buyer built
*/
private static Buyer buildBuyer(Map<String, String> parameters) throws InvalidParametersException {
String buyerId = getParameter(parameters, PayU.PARAMETERS.BUYER_ID);
String buyerEmail = getParameter(parameters,
PayU.PARAMETERS.BUYER_EMAIL);
String buyerName = getParameter(parameters, PayU.PARAMETERS.BUYER_NAME);
String buyerCNPJ = getParameter(parameters, PayU.PARAMETERS.BUYER_CNPJ);
String buyerContactPhone = getParameter(parameters,
PayU.PARAMETERS.BUYER_CONTACT_PHONE);
String buyerDniNumber = getParameter(parameters,
PayU.PARAMETERS.BUYER_DNI);
DocumentType buyerDniType = getEnumValueParameter(DocumentType.class,
parameters, PayU.PARAMETERS.BUYER_DNI_TYPE);
String buyerCity = getParameter(parameters, PayU.PARAMETERS.BUYER_CITY);
String buyerCountry = getParameter(parameters,
PayU.PARAMETERS.BUYER_COUNTRY);
String buyerPhone = getParameter(parameters,
PayU.PARAMETERS.BUYER_PHONE);
String buyerPostalCode = getParameter(parameters,
PayU.PARAMETERS.BUYER_POSTAL_CODE);
String buyerState = getParameter(parameters,
PayU.PARAMETERS.BUYER_STATE);
String buyerStreet = getParameter(parameters,
PayU.PARAMETERS.BUYER_STREET);
String buyerStreet2 = getParameter(parameters,
PayU.PARAMETERS.BUYER_STREET_2);
String buyerStreet3 = getParameter(parameters,
PayU.PARAMETERS.BUYER_STREET_3);
Buyer buyer = new Buyer();
buildPerson(buyer, buyerId, buyerEmail, buyerName, buyerCNPJ,
buyerContactPhone, buyerDniNumber, buyerDniType, buyerCity,
buyerCountry, buyerPhone, buyerPostalCode, buyerState,
buyerStreet, buyerStreet2, buyerStreet3);
return buyer;
}
/**
* Builds the payer entity
*
* @param parameters The parameters map to build the payer
* @return The payer built
* @throws InvalidParametersException
*/
private static Payer buildPayer(final Map<String, String> parameters) throws InvalidParametersException {
final String payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);
final String payerEmail = getParameter(parameters, PayU.PARAMETERS.PAYER_EMAIL);
final String payerName = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);
final String payerCNPJ = getParameter(parameters, PayU.PARAMETERS.PAYER_CNPJ);
final String payerContactPhone = getParameter(parameters, PayU.PARAMETERS.PAYER_CONTACT_PHONE);
final String payerDniNumber = getParameter(parameters, PayU.PARAMETERS.PAYER_DNI);
final String payerCity = getParameter(parameters, PayU.PARAMETERS.PAYER_CITY);
final String payerCountry = getParameter(parameters, PayU.PARAMETERS.PAYER_COUNTRY);
final String payerPhone = getParameter(parameters, PayU.PARAMETERS.PAYER_PHONE);
final String payerPostalCode = getParameter(parameters, PayU.PARAMETERS.PAYER_POSTAL_CODE);
final String payerState = getParameter(parameters, PayU.PARAMETERS.PAYER_STATE);
final String payerStreet = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET);
final String payerStreet2 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_2);
final String payerStreet3 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_3);
final String payerBusinessName = getParameter(parameters, PayU.PARAMETERS.PAYER_BUSINESS_NAME);
final PersonType payerType = getEnumValueParameter(PersonType.class, parameters,
PayU.PARAMETERS.PAYER_PERSON_TYPE);
final String payerBirthdate = getParameter(parameters, PayU.PARAMETERS.PAYER_BIRTH_DATE);
final DocumentType payerDniType = getEnumValueParameter(DocumentType.class, parameters,
PayU.PARAMETERS.PAYER_DNI_TYPE);
if (payerBirthdate != null && !payerBirthdate.isEmpty()) {
validateDateParameter(payerBirthdate, PayU.PARAMETERS.PAYER_BIRTH_DATE,
Constants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT, false);
}
final Payer payer = new Payer();
buildPerson(payer, payerId, payerEmail, payerName, payerCNPJ,
payerContactPhone, payerDniNumber, payerDniType, payerCity,
payerCountry, payerPhone, payerPostalCode, payerState,
payerStreet, payerStreet2, payerStreet3);
payer.setBusinessName(payerBusinessName);
payer.setPayerType(payerType);
payer.setBirthdate(payerBirthdate);
return payer;
}
/**
* Builds the person entity
*
* @param person
* The person to build
* @param personId
* The person's id in the merchant
* @param email
* The person's e-mail
* @param name
* The person's name
* @param CNPJ
* The person's CNPJ
* @param contactPhone
* The person's contact phone
* @param dniNumber
* The person's dni number
* @param dniType
* The person's dni type
* @param city
* The person's city
* @param country
* The person's country
* @param phone
* The person's phone
* @param postalCode
* The person's postal code
* @param state
* The person's state
* @param street
* The person's street
* @param street2
* The person's street2
* @param street3
* The person's street3
*/
private static void buildPerson(Person person, String personId,
String email, String name, String CNPJ, String contactPhone,
String dniNumber, DocumentType dniType, String city, String country,
String phone, String postalCode, String state, String street,
String street2, String street3) {
person.setMerchantPersonId(personId);
person.setEmailAddress(email);
person.setFullName(name);
person.setCNPJ(CNPJ);
person.setContactPhone(contactPhone);
person.setDniNumber(dniNumber);
person.setDniType(dniType);
Address address = new Address();
address.setCity(city);
address.setCountry(country);
address.setPhone(phone);
address.setPostalCode(postalCode);
address.setState(state);
address.setLine1(street);
address.setLine2(street2);
address.setLine3(street3);
person.setAddress(address);
}
/**
* Build a transaction request based on the query parameters
*
* @param parameters
* The parameters map to send to the request
* @param transactionType
* The type of payment transaction to build
* @return The transaction to be sent built
* @throws InvalidParametersException
*/
public static Transaction buildTransaction(Map<String, String> parameters,
TransactionType transactionType) throws InvalidParametersException {
String payerName = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);
Integer orderId = getIntegerParameter(parameters,
PayU.PARAMETERS.ORDER_ID);
Integer accountId = getIntegerParameter(parameters,
PayU.PARAMETERS.ACCOUNT_ID);
String merchantIdParam = getParameter(parameters,
PayU.PARAMETERS.MARCHANT_ID);
String orderReference = getParameter(parameters,
PayU.PARAMETERS.REFERENCE_CODE);
String orderDescription = getParameter(parameters,
PayU.PARAMETERS.DESCRIPTION);
String orderNotifyUrl = getParameter(parameters,
PayU.PARAMETERS.NOTIFY_URL);
String creditCardHolderName = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_HOLDER_NAME);
String creditCardNumber = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_NUMBER);
String creditCardExpirationDate = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE);
Boolean processWithoutCvv2 = getBooleanParameter(parameters,
PayU.PARAMETERS.PROCESS_WITHOUT_CVV2);
String securityCode = getParameter(parameters,
PayU.PARAMETERS.CREDIT_CARD_SECURITY_CODE);
Boolean createCreditCardToken = getBooleanParameter(parameters,
PayU.PARAMETERS.CREATE_CREDIT_CARD_TOKEN);
String parentTransactionId = getParameter(parameters,
PayU.PARAMETERS.TRANSACTION_ID);
String expirationDate = getParameter(parameters,
PayU.PARAMETERS.EXPIRATION_DATE);
String cookie = getParameter(parameters, PayU.PARAMETERS.COOKIE);
PaymentCountry paymentCountry = getEnumValueParameter(
PaymentCountry.class, parameters, PayU.PARAMETERS.COUNTRY);
//Obtains the payment method. If the parameter is a value that doesn't belong to the enum, this return null and continue
PaymentMethod paymentMethod = CommonRequestUtil
.getPaymentMethodParameter(parameters,PayU.PARAMETERS.PAYMENT_METHOD);
String reason = getParameter(parameters,
PayU.PARAMETERS.REASON);
Currency txCurrency = getEnumValueParameter(Currency.class, parameters,
PayU.PARAMETERS.CURRENCY);
BigDecimal txValue = getBigDecimalParameter(parameters,
PayU.PARAMETERS.VALUE);
Integer installments = getIntegerParameter(parameters,
PayU.PARAMETERS.INSTALLMENTS_NUMBER);
// TAX_VALUE
BigDecimal taxValue = getBigDecimalParameter(parameters,
PayU.PARAMETERS.TAX_VALUE);
// TAX_RETURN_BASE
BigDecimal taxReturnBase = getBigDecimalParameter(parameters,
PayU.PARAMETERS.TAX_RETURN_BASE);
// IP Address
String ipAddress = getParameter(parameters, PayU.PARAMETERS.IP_ADDRESS);
// User Agent
String userAgent = getParameter(parameters, PayU.PARAMETERS.USER_AGENT);
// Device session ID
String deviceSessionId = getParameter(parameters,
PayU.PARAMETERS.DEVICE_SESSION_ID);
// Response page
String responseUrlPage = getParameter(parameters, PayU.PARAMETERS.RESPONSE_URL);
String tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);
Transaction transaction = new Transaction();
transaction.setType(transactionType);
if (responseUrlPage != null) {
addResponseUrlPage(transaction, responseUrlPage);
}
// Shipping address fields
String shippingAddressLine1 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_1);
String shippingAddressLine2 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_2);
String shippingAddressLine3 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_3);
String shippingAddressCity = getParameter(parameters, PayU.PARAMETERS.SHIPPING_CITY);
String shippingAddressState = getParameter(parameters, PayU.PARAMETERS.SHIPPING_STATE);
String shippingAddressCountry = getParameter(parameters, PayU.PARAMETERS.SHIPPING_COUNTRY);
String shippingAddressPostalCode = getParameter(parameters, PayU.PARAMETERS.SHIPPING_POSTAL_CODE);
String shippingAddressPhone = getParameter(parameters, PayU.PARAMETERS.SHIPPING_PHONE);
Boolean termsAndConditionsAcepted = getBooleanParameter(parameters,
PayU.PARAMETERS.TERMS_AND_CONDITIONS_ACEPTED);
String bcashRequestContentType = getParameter(parameters, PayU.PARAMETERS.BCASH_REQUEST_CONTENT_TYPE);
String bcashRequestContent = getParameter(parameters, PayU.PARAMETERS.BCASH_REQUEST_CONTENT);
if (bcashRequestContentType != null || bcashRequestContent != null) {
transaction.setBcashRequest(buildBcashRequest(bcashRequestContentType, bcashRequestContent));
}
if (TransactionType.AUTHORIZATION_AND_CAPTURE.equals(transactionType)
|| TransactionType.AUTHORIZATION.equals(transactionType)) {
transaction.setPaymentCountry(paymentCountry);
if (orderId == null) {
String signature = getParameter(parameters,
PayU.PARAMETERS.SIGNATURE);
String merchantId = PayU.merchantId != null ? PayU.merchantId : merchantIdParam;
Order order = buildOrder(accountId, txCurrency, txValue,
taxValue, taxReturnBase, orderDescription,
orderReference, orderNotifyUrl);
if (signature == null && merchantId != null) {
signature = SignatureHelper.buildSignature(order,
Integer.parseInt(merchantId), PayU.apiKey,
SignatureHelper.DECIMAL_FORMAT_3,
SignatureHelper.MD5_ALGORITHM);
}
order.setSignature(signature);
// Adds the shipping address
AddressV4 shippingAddress = buildShippingAddress(
shippingAddressLine1, shippingAddressLine2,
shippingAddressLine3, shippingAddressCity,
shippingAddressState, shippingAddressCountry,
shippingAddressPostalCode, shippingAddressPhone);
order.setShippingAddress(shippingAddress);
transaction.setOrder(order);
} else {
Order order = new Order();
order.setId(orderId);
transaction.setOrder(order);
}
transaction.getOrder().setBuyer(buildBuyer(parameters));
transaction.setCookie(cookie);
// MAF parameters
transaction.setUserAgent(userAgent);
transaction.setIpAddress(ipAddress);
transaction.setDeviceSessionId(deviceSessionId);
// PSE extra parameters
if (PaymentMethod.PSE.equals(paymentMethod)) {
addPSEExtraParameters(transaction, parameters);
}
transaction.setSource(TransactionSource.PAYU_SDK);
if (creditCardNumber != null || tokenId != null) {
// If credit card holder name is null or empty, a payer name
// will be send to build a credit card
creditCardHolderName = creditCardHolderName != null
&& !creditCardHolderName.trim().equals("") ? creditCardHolderName
: payerName;
buildCreditCardTransaction(transaction, creditCardHolderName,
creditCardNumber, creditCardExpirationDate,
processWithoutCvv2, securityCode, installments,
createCreditCardToken);
}
if (expirationDate != null) {
Date expDate = validateDateParameter(expirationDate,
PayU.PARAMETERS.EXPIRATION_DATE,
Constants.DEFAULT_DATE_FORMAT);
transaction.setExpirationDate(expDate);
}
transaction.setCreditCardTokenId(tokenId);
//Set the param of Payment Method
String paramPaymentMethod = getParameter(parameters, PayU.PARAMETERS.PAYMENT_METHOD);
transaction.setPaymentMethod(paramPaymentMethod);
//transaction.setPaymentMethod(paymentMethod);
transaction.setPayer(buildPayer(parameters));
transaction.setTermsAndConditionsAcepted(termsAndConditionsAcepted);
addTransactionExtraParameters(transaction, parameters);
} else if (TransactionType.VOID.equals(transactionType)
|| TransactionType.REFUND.equals(transactionType)
|| TransactionType.CAPTURE.equals(transactionType)) {
transaction.setParentTransactionId(parentTransactionId);
Order order = new Order();
order.setId(orderId);
order.setReferenceCode(orderReference);
order.setDescription(orderDescription);
order.setLanguage(PayU.language);
transaction.setAdditionalValues(buildAdditionalValues(txCurrency,
txValue, taxValue, taxReturnBase));
transaction.setOrder(order);
transaction.setReason(reason);
}
return transaction;
}
/**
* Adds the transaction extra parameters.
*
* @param transaction the transaction
* @param parameters the parameters
* @throws InvalidParametersException the invalid parameters exception
*/
private static void addTransactionExtraParameters(Transaction transaction, Map<String, String> parameters) throws InvalidParametersException {
String extra1 = getParameter(parameters, PayU.PARAMETERS.EXTRA1);
String extra2 = getParameter(parameters, PayU.PARAMETERS.EXTRA2);
String extra3 = getParameter(parameters, PayU.PARAMETERS.EXTRA3);
if (extra1 != null) {
transaction.addExtraParameter(ExtraParemeterNames.EXTRA1.name(), extra1);
}
if (extra2 != null) {
transaction.addExtraParameter(ExtraParemeterNames.EXTRA2.name(), extra2);
}
if (extra3 != null) {
transaction.addExtraParameter(ExtraParemeterNames.EXTRA3.name(), extra3);
}
}
/**
* Adds the extra parameters required by the PSE payment method
*
* @param transaction
* @param parameters
* @throws InvalidParametersException
*/
private static void addPSEExtraParameters(Transaction transaction,
Map<String, String> parameters) throws InvalidParametersException {
// PSE reference identification 1
String pseReference1 = getParameter(parameters,
PayU.PARAMETERS.IP_ADDRESS);
// PSE reference identification 2
String pseReference2 = getEnumValueParameter(DocumentType.class,
parameters, PayU.PARAMETERS.PAYER_DOCUMENT_TYPE).name();
// PSE reference identification 3
String pseReference3 = getParameter(parameters,
PayU.PARAMETERS.PAYER_DNI);
PersonType pseUserType = getEnumValueParameter(PersonType.class,
parameters, PayU.PARAMETERS.PAYER_PERSON_TYPE);
// PSE financial institution code (Bank code)
String pseFinancialInstitutionCode = getParameter(parameters,
PayU.PARAMETERS.PSE_FINANCIAL_INSTITUTION_CODE);
// PSE financial institution name (Bank Name)
String pseFinancialInstitutionName = getParameter(parameters,
PayU.PARAMETERS.PSE_FINANCIAL_INSTITUTION_NAME);
if (pseFinancialInstitutionCode != null) {
transaction.addExtraParameter(
ExtraParemeterNames.FINANCIAL_INSTITUTION_CODE.name(),
pseFinancialInstitutionCode);
}
if (pseFinancialInstitutionName != null) {
transaction.addExtraParameter(
ExtraParemeterNames.FINANCIAL_INSTITUTION_NAME.name(),
pseFinancialInstitutionName);
}
if (pseUserType != null) {
transaction.addExtraParameter(ExtraParemeterNames.USER_TYPE.name(),
pseUserType.getPseCode());
}
if (pseReference1 != null) {
transaction.addExtraParameter(
ExtraParemeterNames.PSE_REFERENCE1.name(), pseReference1);
}
if (pseReference2 != null) {
transaction.addExtraParameter(
ExtraParemeterNames.PSE_REFERENCE2.name(), pseReference2);
}
if (pseReference3 != null) {
transaction.addExtraParameter(
ExtraParemeterNames.PSE_REFERENCE3.name(), pseReference3);
}
}
public static String mapToString(Map<String, String> map)
throws PayUException {
StringBuilder stringBuilder = new StringBuilder();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (value != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append(APPENDER);
}
try {
stringBuilder.append((key != null ? URLEncoder.encode(
key, ENCODING) : ""));
stringBuilder.append(EQUALS);
stringBuilder.append(URLEncoder.encode(
value, ENCODING));
} catch (UnsupportedEncodingException e) {
throw new PayUException(ErrorCode.INVALID_PARAMETERS,
"can not encode the url");
}
}
}
}
return stringBuilder.toString();
}
/**
* Method for add in the transaccion a {@link ExtraParemeterNames} with the response url page.
* <ul>
* <li>1. Get of the {@link ExtraParemeterNames} RESPONSE_URL.</li>
* <li>2. sets in the extra parameter of the {@code responseUrl value}.</li>
* </ul>
*
* @param transaction
* @param responseUrl
* @throws InvalidParametersException
*/
private static void addResponseUrlPage(final Transaction transaction, String responseUrl) throws InvalidParametersException{
transaction.addExtraParameter(ExtraParemeterNames.RESPONSE_URL.name(),
responseUrl);
}
/**
* Builds a {@link Address} according to parameters.
*
* @param shippingAddressLine1
* the address line 1 to set.
* @param shippingAddressLine2
* the address line 2 to set.
* @param shippingAddressLine3
* the address line 3 to set.
* @param shippingAddressCity
* the address city to set.
* @param shippingAddressState
* the address state to set.
* @param shippingAddressCountry
* the address country to set.
* @param shippingAddressPostalCode
* the address postal code to set.
* @param shippingAddressPhone
* the address phone to set.
* @return {@link Address} object.
*/
private static AddressV4 buildShippingAddress(String shippingAddressLine1,
String shippingAddressLine2, String shippingAddressLine3,
String shippingAddressCity, String shippingAddressState,
String shippingAddressCountry, String shippingAddressPostalCode,
String shippingAddressPhone) {
AddressV4 shippingAddress = new AddressV4();
shippingAddress.setStreet1(shippingAddressLine1);
shippingAddress.setStreet2(shippingAddressLine2);
shippingAddress.setStreet3(shippingAddressLine3);
shippingAddress.setCity(shippingAddressCity);
shippingAddress.setState(shippingAddressState);
shippingAddress.setCountry(shippingAddressCountry);
shippingAddress.setPostalCode(shippingAddressPostalCode);
shippingAddress.setPhone(shippingAddressPhone);
return shippingAddress;
}
/**
* Builds a Bcash request
*
* @param contentType the content type
* @param content the content
* @return the Bcash request
* @throws InvalidParametersException if any of the arguments is null
*/
private static BcashRequest buildBcashRequest(String contentType, String content) throws InvalidParametersException {
if (contentType == null || content == null) {
throw new InvalidParametersException("Both the bcashRequestContentType and bcashRequestContent must be set set");
}
BcashRequest bcashRequest = new BcashRequest();
bcashRequest.setContentType(contentType);
bcashRequest.setContent(content);
return bcashRequest;
}
} |
// samskivert library - useful routines for java programs
package com.samskivert.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.samskivert.annotation.ReplacedBy;
/**
* An int map is like a regular map, but with integers as keys. We avoid
* the annoyance of having to create integer objects every time we want to
* lookup or insert values. The hash int map is an int map that uses a
* hashtable mechanism to store its key/value mappings.
*/
@ReplacedBy(value="java.util.Map",
reason="Boxing shouldn't be a major concern. It's probably better to stick to " +
"standard classes rather than worry about a tiny memory or performance gain.")
public class HashIntMap<V> extends AbstractMap<Integer,V>
implements IntMap<V>, Cloneable, Serializable
{
/**
* The default number of buckets to use for the hash table.
*/
public final static int DEFAULT_BUCKETS = 16;
/**
* The default load factor.
*/
public final static float DEFAULT_LOAD_FACTOR = 1.75f;
/**
* Constructs an empty hash int map with the specified number of hash
* buckets.
*/
public HashIntMap (int buckets, float loadFactor)
{
// force the capacity to be a power of 2
int capacity = 1;
while (capacity < buckets) {
capacity <<= 1;
}
_buckets = createBuckets(capacity);
_loadFactor = loadFactor;
}
/**
* Constructs an empty hash int map with the default number of hash
* buckets.
*/
public HashIntMap ()
{
this(DEFAULT_BUCKETS, DEFAULT_LOAD_FACTOR);
}
@Override
public int size ()
{
return _size;
}
@Override
public boolean containsKey (Object key)
{
return (key instanceof Integer) && containsKey(((Integer)key).intValue());
}
// documentation inherited
public boolean containsKey (int key)
{
return (null != getImpl(key));
}
@Override
public boolean containsValue (Object o)
{
for (Record<V> bucket : _buckets) {
for (Record<V> r = bucket; r != null; r = r.next) {
if (ObjectUtil.equals(r.value, o)) {
return true;
}
}
}
return false;
}
@Override
public V get (Object key)
{
return (key instanceof Integer) ? get(((Integer)key).intValue()) : null;
}
// documentation inherited
public V get (int key)
{
Record<V> rec = getImpl(key);
return (rec == null) ? null : rec.value;
}
@Override
public V put (Integer key, V value)
{
return put(key.intValue(), value);
}
// documentation inherited
public V put (int key, V value)
{
// check to see if we've passed our load factor, if so: resize
ensureCapacity(_size + 1);
int index = keyToIndex(key);
Record<V> rec = _buckets[index];
// either we start a new chain
if (rec == null) {
_buckets[index] = new Record<V>(key, value);
_size++; // we're bigger
return null;
}
// or we replace an element in an existing chain
Record<V> prev = rec;
for (; rec != null; rec = rec.next) {
if (rec.key == key) {
V ovalue = rec.value;
rec.value = value; // we're not bigger
return ovalue;
}
prev = rec;
}
// or we append it to this chain
prev.next = new Record<V>(key, value);
_size++; // we're bigger
return null;
}
@Override
public V remove (Object key)
{
return (key instanceof Integer) ? remove(((Integer)key).intValue()) : null;
}
// documentation inherited
public V remove (int key)
{
Record<V> removed = removeImpl(key, true);
return (removed == null) ? null : removed.value;
}
/**
* Locate the record with the specified key.
*/
protected Record<V> getImpl (int key)
{
for (Record<V> rec = _buckets[keyToIndex(key)]; rec != null; rec = rec.next) {
if (rec.key == key) {
return rec;
}
}
return null;
}
/**
* Remove an element with optional checking to see if we should shrink.
* When this is called from our iterator, checkShrink==false to avoid booching the buckets.
*/
protected Record<V> removeImpl (int key, boolean checkShrink)
{
int index = keyToIndex(key);
// go through the chain looking for a match
for (Record<V> prev = null, rec = _buckets[index]; rec != null; rec = rec.next) {
if (rec.key == key) {
if (prev == null) {
_buckets[index] = rec.next;
} else {
prev.next = rec.next;
}
_size
if (checkShrink) {
checkShrink();
}
return rec;
}
prev = rec;
}
return null;
}
// documentation inherited
public void putAll (IntMap<V> t)
{
// if we can, avoid creating Integer objects while copying
for (IntEntry<V> entry : t.intEntrySet()) {
put(entry.getIntKey(), entry.getValue());
}
}
@Override
public void clear ()
{
// abandon all of our hash chains (the joy of garbage collection)
Arrays.fill(_buckets, null);
// zero out our size
_size = 0;
}
/**
* Ensure that the hash can comfortably hold the specified number
* of elements. Calling this method is not necessary, but can improve
* performance if done prior to adding many elements.
*/
public void ensureCapacity (int minCapacity)
{
int size = _buckets.length;
while (minCapacity > (int) (size * _loadFactor)) {
size *= 2;
}
if (size != _buckets.length) {
resizeBuckets(size);
}
}
/**
* Turn the specified key into an index.
*/
protected final int keyToIndex (int key)
{
// we lift the hash-fixing function from HashMap because Sun
// wasn't kind enough to make it public
key += ~(key << 9);
key ^= (key >>> 14);
key += (key << 4);
key ^= (key >>> 10);
return key & (_buckets.length - 1);
}
/**
* Check to see if we want to shrink the table.
*/
protected void checkShrink ()
{
if ((_buckets.length > DEFAULT_BUCKETS) &&
(_size < (int) (_buckets.length * _loadFactor * .125))) {
resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.length >> 1));
}
}
/**
* Resize the hashtable.
*
* @param newsize MUST be a power of 2.
*/
protected void resizeBuckets (int newsize)
{
Record<V>[] oldbuckets = _buckets;
_buckets = createBuckets(newsize);
// we shuffle the records around without allocating new ones
int index = oldbuckets.length;
while (index
Record<V> oldrec = oldbuckets[index];
while (oldrec != null) {
Record<V> newrec = oldrec;
oldrec = oldrec.next;
// always put the newrec at the start of a chain
int newdex = keyToIndex(newrec.key);
newrec.next = _buckets[newdex];
_buckets[newdex] = newrec;
}
}
}
@Override
public Set<Entry<Integer,V>> entrySet ()
{
return new AbstractSet<Entry<Integer,V>>() {
@Override public int size () {
return _size;
}
@Override public Iterator<Entry<Integer,V>> iterator () {
return new MapEntryIterator();
}
};
}
// documentation inherited
public Set<IntEntry<V>> intEntrySet ()
{
return new AbstractSet<IntEntry<V>>() {
@Override public int size () {
return _size;
}
@Override public Iterator<IntEntry<V>> iterator () {
return new IntEntryIterator();
}
};
}
protected abstract class RecordIterator<E>
implements Iterator<E>
{
public boolean hasNext ()
{
// if we're pointing to an entry, we're good
if (_record != null) {
return true;
}
// search backward through the buckets looking for the next non-empty hash chain
while (_index
if ((_record = _buckets[_index]) != null) {
return true;
}
}
// found no non-empty hash chains, we're done
return false;
}
public Record<V> nextRecord ()
{
// if we're not pointing to an entry, search for the next
// non-empty hash chain
if (_record == null) {
if (!hasNext()) {
throw new NoSuchElementException();
}
}
// keep track of the last thing we returned, our next record, and return
_last = _record;
_record = _record.next;
return _last;
}
public void remove ()
{
if (_last == null) {
throw new IllegalStateException();
}
// remove the record the hard way, avoiding any major changes to the buckets
HashIntMap.this.removeImpl(_last.key, false);
_last = null;
}
protected int _index = _buckets.length;
protected Record<V> _record, _last;
}
protected class IntEntryIterator extends RecordIterator<IntEntry<V>>
{
public IntEntry<V> next () {
return nextRecord();
}
}
protected class MapEntryIterator extends RecordIterator<Entry<Integer,V>>
{
public Entry<Integer,V> next () {
return nextRecord();
}
}
// documentation inherited from interface IntMap
public IntSet intKeySet ()
{
// damn Sun bastards made the 'keySet' variable with default access, so we can't share it
if (_keySet == null) {
_keySet = new AbstractIntSet() {
public Interator interator () {
return new AbstractInterator () {
public boolean hasNext () {
return i.hasNext();
}
public int nextInt () {
return i.next().getIntKey();
}
@Override public void remove () {
i.remove();
}
private Iterator<IntEntry<V>> i = intEntrySet().iterator();
};
}
@Override public int size () {
return HashIntMap.this.size();
}
@Override public boolean contains (int t) {
return HashIntMap.this.containsKey(t);
}
@Override public boolean remove (int value) {
Record<V> removed = removeImpl(value, true);
return (removed != null);
}
};
}
return _keySet;
}
@Override
public Set<Integer> keySet ()
{
return intKeySet();
}
/**
* Returns an interation over the keys of this hash int map.
*/
public Interator keys ()
{
return intKeySet().interator();
}
/**
* Returns an iteration over the elements (values) of this hash int
* map.
*/
public Iterator<V> elements ()
{
return values().iterator();
}
@Override
public HashIntMap<V> clone ()
{
try {
@SuppressWarnings("unchecked")
HashIntMap<V> result = (HashIntMap<V>) super.clone();
result._keySet = null;
Record<V>[] buckets = result._buckets = result._buckets.clone();
for (int ii = buckets.length - 1; ii >= 0; ii
if (buckets[ii] != null) {
buckets[ii] = buckets[ii].clone();
}
}
return result;
} catch (CloneNotSupportedException cnse) {
throw new AssertionError(cnse); // won't happen; we're Cloneable
}
}
/**
* Save the state of this instance to a stream (i.e., serialize it).
*/
private void writeObject (ObjectOutputStream s)
throws IOException
{
// write out number of buckets
s.writeInt(_buckets.length);
s.writeFloat(_loadFactor);
// write out size (number of mappings)
s.writeInt(_size);
// write out keys and values
for (IntEntry<V> entry : intEntrySet()) {
s.writeInt(entry.getIntKey());
s.writeObject(entry.getValue());
}
}
/**
* Reconstitute the <tt>HashIntMap</tt> instance from a stream (i.e.,
* deserialize it).
*/
private void readObject (ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// read in number of buckets and allocate the bucket array
_buckets = createBuckets(s.readInt());
_loadFactor = s.readFloat();
// read in size (number of mappings)
int size = s.readInt();
// read the keys and values
for (int i=0; i<size; i++) {
int key = s.readInt();
@SuppressWarnings("unchecked") V value = (V)s.readObject();
put(key, value);
}
}
protected Record<V>[] createBuckets (int size)
{
@SuppressWarnings("unchecked") Record<V>[] recs = (Record<V>[])new Record<?>[size];
return recs;
}
protected static class Record<V>
implements Cloneable, IntEntry<V>
{
public Record<V> next;
public int key;
public V value;
public Record (int key, V value)
{
this.key = key;
this.value = value;
}
public Integer getKey ()
{
return Integer.valueOf(key);
}
public int getIntKey ()
{
return key;
}
public V getValue ()
{
return value;
}
public V setValue (V value)
{
V ovalue = this.value;
this.value = value;
return ovalue;
}
@Override public boolean equals (Object o)
{
if (o instanceof IntEntry<?>) {
IntEntry<?> that = (IntEntry<?>)o;
return (this.key == that.getIntKey()) &&
ObjectUtil.equals(this.value, that.getValue());
} else if (o instanceof Entry<?,?>) {
Entry<?,?> that = (Entry<?,?>)o;
return (this.getKey().equals(that.getKey())) &&
ObjectUtil.equals(this.value, that.getValue());
} else {
return false;
}
}
@Override public int hashCode ()
{
return key ^ ((value == null) ? 0 : value.hashCode());
}
@Override public String toString ()
{
return key + "=" + StringUtil.toString(value);
}
@Override public Record<V> clone ()
{
try {
@SuppressWarnings("unchecked")
Record<V> result = (Record<V>) super.clone();
// value is not cloned
if (result.next != null) {
result.next = result.next.clone();
}
return result;
} catch (CloneNotSupportedException cnse) {
throw new AssertionError(cnse); // won't happen; we are Cloneable.
}
}
}
protected Record<V>[] _buckets;
protected int _size;
protected float _loadFactor;
/** A stateless view of our keys, so we re-use it. */
protected transient volatile IntSet _keySet = null;
/** Change this if the fields or inheritance hierarchy ever changes
* (which is extremely unlikely). We override this because I'm tired
* of serialized crap not working depending on whether I compiled with
* jikes or javac. */
private static final long serialVersionUID = 1;
} |
package com.sbiger.qbe;
public interface CriteriaExample<T> {
enum LogicType{
AND,
OR
}
CriteriaExample<T> asc();
CriteriaExample<T> desc();
CriteriaExample<T> orderby();
CriteriaExample<T> avg();
CriteriaExample<T> sum();
CriteriaExample<T> sumAsLong();
CriteriaExample<T> sumAsDouble();
CriteriaExample<T> max();
CriteriaExample<T> in();
CriteriaExample<T> greatest();
CriteriaExample<T> least();
CriteriaExample<T> count();
CriteriaExample<T> countDistinct();
CriteriaExample<T> exists();
CriteriaExample<T> all();
CriteriaExample<T> some();
CriteriaExample<T> any();
CriteriaExample<T> and();
CriteriaExample<T> or();
CriteriaExample<T> not();
CriteriaExample<T> isTrue();
CriteriaExample<T> isFalse();
CriteriaExample<T> isNull();
CriteriaExample<T> isNotNull();
CriteriaExample<T> equal();
CriteriaExample<T> notEqual();
CriteriaExample<T> greaterThan();
CriteriaExample<T> greaterThanOrEqualTo();
CriteriaExample<T> lessThan();
CriteriaExample<T> lessThanOrEqualTo();
CriteriaExample<T> between();
CriteriaExample<T> gt();
CriteriaExample<T> ge();
CriteriaExample<T> lt();
CriteriaExample<T> le();
CriteriaExample<T> neg();
CriteriaExample<T> prod();
CriteriaExample<T> diff();
CriteriaExample<T> quot();
CriteriaExample<T> mod();
CriteriaExample<T> sqrt();
CriteriaExample<T> toLong();
CriteriaExample<T> toInteger();
CriteriaExample<T> toFloat();
CriteriaExample<T> toDouble();
CriteriaExample<T> toBigDecimal();
CriteriaExample<T> toBigInteger();
CriteriaExample<T> isEmpty();
CriteriaExample<T> isNotEmpty();
CriteriaExample<T> size();
CriteriaExample<T> isMember();
CriteriaExample<T> isNotMember();
CriteriaExample<T> like();
CriteriaExample<T> notLike();
CriteriaExample<T> concat();
CriteriaExample<T> substring();
CriteriaExample<T> trim();
CriteriaExample<T> lower();
CriteriaExample<T> upper();
CriteriaExample<T> length();
CriteriaExample<T> locate();
CriteriaExample<T> currentDate();
CriteriaExample<T> currentTimestamp();
CriteriaExample<T> currentTime();
CriteriaExample<T> coalesce();
CriteriaExample<T> nullif();
CriteriaExample<T> selectCase();
} |
package com.seleniumtests.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import com.seleniumtests.controller.EasyFilter;
import com.seleniumtests.controller.Logging;
import com.seleniumtests.exception.SeleniumTestsException;
import com.seleniumtests.util.internal.entity.TestObject;
public class CSVUtil {
private static Logger logger = Logging.getLogger(CSVUtil.class);
public static final String DOUBLE_QUOTE = "\"";
public static final String DELIM_CHAR = ",";
public static final String TAB_CHAR = " ";
/**
* Reads data from csv formatted file. Put the excel sheet in the same folder as the test case and specify clazz as <code>this.getClass()</code>.
*
* @param clazz
* @param filename
* @param fields
* @param filter
* @param readHeaders
* @return
* @throws Exception
*/
public static Iterator<Object[]> getDataFromCSVFile(Class<?> clazz, String filename, String[] fields, EasyFilter filter, boolean readHeaders, boolean supportDPFilter) {
return getDataFromCSVFile(clazz, filename, fields, filter, readHeaders, null, supportDPFilter);
}
public static Iterator<Object[]> getDataFromCSVFile(Class<?> clazz, String filename, String[] fields, EasyFilter filter, boolean readHeaders, String delimiter, boolean supportDPFilter) {
InputStream is = null;
try {
if (clazz != null)
is = clazz.getResourceAsStream(filename);
else
is = new FileInputStream(filename);
if (is == null)
return new ArrayList<Object[]>().iterator();
// Get the sheet
String[][] csvData = read(is, delimiter);
List<Object[]> sheetData = new ArrayList<Object[]>();
if (readHeaders) {
List<Object> rowData = new ArrayList<Object>();
if (fields == null) {
for (int j = 0; j < csvData[0].length; j++) {
rowData.add(csvData[0][j]);
}
} else {
for (int i = 0; i < fields.length; i++) {
rowData.add(fields[i]);
}
}
sheetData.add(rowData.toArray(new Object[rowData.size()]));
}
int testTitleColumnIndex = -1;
int testSiteColumnIndex = -1;
// Search for Title & Site column
for (int i = 0; i < csvData[0].length; i++) {
if (testTitleColumnIndex == -1 && TestObject.TEST_TITLE.equalsIgnoreCase(csvData[0][i])) {
testTitleColumnIndex = i;
} else if (testSiteColumnIndex == -1 && TestObject.TEST_SITE.equalsIgnoreCase(csvData[0][i])) {
testSiteColumnIndex = i;
}
if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1)
break;
}
// Let's check for blank rows first
// The first row is the header
StringBuffer sbBlank = new StringBuffer();
for (int i = 1; i < csvData.length; i++) {
if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1 && (csvData[i][testTitleColumnIndex].trim().length() == 0 || csvData[i][testSiteColumnIndex].trim().length() == 0)) {
sbBlank.append(i + 1).append(',');
}
}
if (sbBlank.length() > 0) {
sbBlank.deleteCharAt(sbBlank.length() - 1);
throw new SeleniumTestsException("Blank TestTitle and/or Site value(s) found on Row(s) " + sbBlank.toString() + ".");
}
Set<String> uniqueDataSet = new TreeSet<String>();
// Jerry: Add DataProviderTags filter
if (supportDPFilter) {
EasyFilter dpFilter = SpreadSheetUtil.getDPFilter();
if (dpFilter != null) {
if (filter == null) {
filter = dpFilter;
} else {
filter = EasyFilter.and(filter, dpFilter);
}
}
}
// End
// The first row is the header
for (int i = 1; i < csvData.length; i++) {
// Check for duplicate Title & Site
if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1) {
String uniqueString = csvData[i][testTitleColumnIndex] + "$$$$
if (uniqueDataSet.contains(uniqueString))
throw new SeleniumTestsException("Duplicate TestTitle and Site combination found in the spreadsheet " + "with TestTitle = {" + csvData[i][testTitleColumnIndex] + "} " + "and Site = {" + csvData[i][testSiteColumnIndex] + "}");
uniqueDataSet.add(uniqueString);
}
Map<String, Object> rowDataMap = new HashMap<String, Object>();
List<Object> rowData = new ArrayList<Object>();
// Create the mapping between headers and column data
for (int j = 0; j < csvData[i].length; j++) {
rowDataMap.put(csvData[0][j], csvData[i][j]);
}
if (fields == null) {
for (int j = 0; j < csvData[0].length; j++) {
// Fix for null values not getting created when number of columns in a row is less than expected.
if (csvData[i].length > j)
rowData.add(csvData[i][j]);
else
rowData.add(null);
}
} else {
for (int k = 0; k < fields.length; k++) {
rowData.add(SpreadSheetUtil.getValue(rowDataMap, fields[k]));
}
}
// Jerry: Add DataProviderTags filter
if (supportDPFilter) {
SpreadSheetUtil.formatDPTags(rowDataMap);
}
// End
if (filter == null || filter.match(rowDataMap)) {
sheetData.add(rowData.toArray(new Object[rowData.size()]));
}
}
if ((!readHeaders && sheetData.isEmpty()) || (readHeaders && sheetData.size() <= 1))
logger.warn("No matching data found on csv file: " + filename + " with filter criteria: " + filter.toString());
return sheetData.iterator();
} catch (Throwable e) {
throw new RuntimeException(e.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}// KEEPME
}
}
}
/**
* Get headers from a csv file
* @param clazz - null means use the absolute file path, otherwise use relative path under the class
* @param filename
* @param delimiter - null means ","
* @return
*/
public static ArrayList<String> getHeaderFromCSVFile(Class<?> clazz, String filename,String delimiter)
{
if(delimiter==null)delimiter=",";
InputStream is = null;
try {
if (clazz != null)
is = clazz.getResourceAsStream(filename);
else
is = new FileInputStream(filename);
if (is == null)
return null;
// Get the sheet
String[][] csvData = read(is, delimiter);
ArrayList<String> rowData = new ArrayList<String>();
for (int j = 0; j < csvData[0].length; j++) {
rowData.add(csvData[0][j]);
}
return rowData;
} catch (Throwable e) {
throw new RuntimeException(e.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}// KEEPME
}
}
}
public static void main(String[] s) {
String line = "142843,\"testOneTimeCCMultiple,AccountPending\"," + " Step 8. Verify user can make 1xCC payment for pending and active accounts " + "(for users with multiple \"accounts),US,,ecaf_seller_cc_pmt0_us,password,,,991,,";
String[] s2 = parseLine(line, DELIM_CHAR);
System.out.print(s2);
}
/**
* Parse a line
*
* @param line
* @param delim
* @return
*/
public static String[] parseLine(String line, String delim) {
if (line == null || line.trim().length() == 0) {
return null;
}
List<String> tokenList = new ArrayList<String>();
String[] result = null;
String[] tokens = line.split(delim);
int count = 0;
while (count < tokens.length) {
if (tokens[count] == null || tokens[count].length() == 0) {
tokenList.add("");
count++;
continue;
}
if (tokens[count].startsWith(DOUBLE_QUOTE)) {
StringBuffer sbToken = new StringBuffer(tokens[count].substring(1));
while (count < tokens.length && !tokens[count].endsWith(DOUBLE_QUOTE)) {
count++;
sbToken.append(DELIM_CHAR).append(tokens[count]);
}
sbToken.deleteCharAt(sbToken.length() - 1);
tokenList.add(sbToken.toString());
} else {
tokenList.add(tokens[count]);
}
count++;
}
if (tokenList.size() > 0) {
result = new String[tokenList.size()];
tokenList.toArray(result);
}
return result;
}
/**
* Parses an file and returns a String[][] object
*
* @param file
* @return
* @throws IOException
*/
public static String[][] read(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
return read(fis);
}
public static String[][] read(InputStream is) throws IOException {
return read(is, null);
}
/**
* Parses an input stream and returns a String[][] object
*
* @param is
* @return
* @throws IOException
*/
public static String[][] read(InputStream is, String delim) throws IOException {
String[][] result = null;
List<String[]> list = new ArrayList<String[]>();
String inputLine; // String that holds current file line
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); // KEEPME
while ((inputLine = reader.readLine()) != null) {
try {
String[] item = null;
if (delim == null)
item = parseLine(inputLine, DELIM_CHAR);
else
item = parseLine(inputLine, delim);
if (item != null)
list.add(item);
} catch (Exception e) {// KEEPME
}
}
reader.close();
if (list.size() > 0) {
result = new String[list.size()][];
list.toArray(result);
}
return result;
}
/**
* Parses an URL and returns a String[][] object
*
* @param url
* @return
* @throws IOException
*/
public static String[][] read(URL url) throws IOException {
URLConnection con = url.openConnection();
return read(con.getInputStream());
}
} |
package com.skraylabs.poker.model;
/**
* A playing card.
*/
public class Card {
/**
* Playing card rank (A, K, Q, J, 10-2).
*/
Rank rank;
/**
* Playing card suit (Spades, Hearts, Diamond, Clubs).
*/
Suit suit;
/**
* Constructor.
*
* @param rank playing card rank
* @param suit playing card suit
*/
Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
/**
* Copy constructor.
*
* @param card non-null Card from which to copy member values.
*/
Card(Card card) {
this(card.rank, card.suit);
}
/**
* Test equality with another object. Other object must be a Card with identical {link Rank} and
* {@link Suit} values.
*
* @return true if {@code o} is a Card with the same rank and suit; false otherwise.
*/
@Override
public boolean equals(Object object) {
boolean result = false;
if (object instanceof Card) {
Card card = (Card) object;
if (card.rank == this.rank && card.suit == this.suit) {
result = true;
}
}
return result;
}
@Override
public int hashCode() {
String hashString = CardFactory.createStringFromCard(this);
return hashString.hashCode();
}
/**
* Accessor: Playing card rank (A, K, Q, J, 10-2).
* @return the rank
*/
public Rank getRank() {
return rank;
}
/**
* Accessor: Playing card suit (Spades, Hearts, Diamond, Clubs).
* @return the suit
*/
public Suit getSuit() {
return suit;
}
} |
package com.skraylabs.poker.model;
/**
* Ranks of playing cards.
*/
public enum Rank {
Ace (14, 1),
King (13),
Queen (12),
Jack (11),
Ten (10),
Nine (9),
Eight (8),
Seven (7),
Six (6),
Five (5),
Four (4),
Three (3),
Two (2);
private final int aceHighValue;
private final int aceLowValue;
Rank(int aceHighValue, int aceLowValue) {
this.aceHighValue = aceHighValue;
this.aceLowValue = aceLowValue;
}
Rank(int aceHighValue) {
this(aceHighValue, aceHighValue);
}
/**
* Get relative rank value.
*
* <p>
* Aces high: Ace is a "14".
* @return relative value with Aces high.
*/
public int aceHighValue() {
return this.aceHighValue;
}
/**
* Get relative rank value.
*
* <p>
* Aces low: Ace is a "1".
* @return relative value with Aces low.
*/
public int aceLowValue() {
return this.aceLowValue;
}
} |
package com.sksamuel.jqm4gwt;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Stephen K Samuel samspade79@gmail.com 11 Jul 2011 17:02:40
*
* An extension of the standard GWT {@link Widget} that adds
* functionality common to all JQM elements, as well as convenience
* methods used by subclasses.
*
* The {@link JQMWidget} is an extension of composite because
* {@link JQMWidget}s do not typically add new functionality (in terms
* of new elements), they are mostly compositions of existing HTML
* elements.
*
* This abstract superclass does not define the nature of the
* composition in use. Implementating subclasses must decide how to
* compose and thus call initWidget() themselves.
*
*/
public abstract class JQMWidget extends Composite implements HasTheme, HasId, HasDataRole, HasEnabled {
private static final String STYLE_UI_DISABLED = "ui-disabled";
/**
* Returns the value of the attribute with the given name
*/
protected String getAttribute(String name) {
return getElement().getAttribute(name);
}
public boolean getAttributeBoolean(String name) {
return "true".equalsIgnoreCase(getAttribute(name));
}
@Override
public String getDataRole() {
return getAttribute("data-role");
}
/**
* Returns the ID set on the main element
*/
@Override
public String getId() {
return getElement().getId();
}
@Override
public String getTheme() {
return getAttribute("data-theme");
}
/**
* Removes the attribute with the given name
*
* @param name
* the name of the attribute to remove
*/
protected void removeAttribute(String name) {
getElement().removeAttribute(name);
}
public void removeDataRole() {
removeAttribute("data-role");
}
/**
* Sets the value of the attribute with the given name to the given value.
*
*/
public void setAttribute(String name, String value) {
if (value == null)
getElement().removeAttribute(name);
else
getElement().setAttribute(name, value);
}
/**
* Sets the data-role attribute to the given value.
*
* @param value
* the value to set the data-role attribute to
*/
@Override
public void setDataRole(String value) {
setAttribute("data-role", value);
}
/**
* Assigns an automatically generated ID to this widget. This method uses
* the default GWT id creation methods in Document.get().createUniqueId()
*/
protected void setId() {
setId(Document.get().createUniqueId());
}
@Override
public final void setId(String id) {
getElement().setId(id);
}
@Override
public void setTheme(String themeName) {
setAttribute("data-theme", themeName);
}
public void setEnabled(boolean b)
{
if(isEnabled() != b)
{
if(b) removeStyleName(STYLE_UI_DISABLED);
else addStyleName(STYLE_UI_DISABLED);
}
}
public boolean isEnabled()
{
return !getStyleName().contains(STYLE_UI_DISABLED);
}
} |
package de.bmoth.parser.ast.nodes;
import java.util.List;
public interface Node {
default boolean sameClass(Node that) {
return this == that || that != null && this.getClass() == that.getClass();
}
default boolean equalAst(Node other) {
return false;
}
class ListAstEquals<T extends Node> {
boolean equalAst(List<T> first, List<T> second) {
if (first.size() != second.size()) {
return false;
}
// relies on same ordering of elements, e.g. x+1 != 1+x
for (int i = 0; i < first.size(); i++) {
if (first.get(i).equalAst(second.get(i))) {
return false;
}
}
return true;
}
}
} |
package de.borellda.logic;
import de.borellda.domain.base.CoreEntity;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
public class PluginOption {
/* The Logger */
private static final Logger log = LoggerFactory.getLogger(PluginOption.class);
public void getPluginInterface(){
Reflections reflections = new Reflections("de.borellda.domain");
Set<Class<? extends CoreEntity>> subTypes =
reflections.getSubTypesOf(CoreEntity.class);
for (Class<? extends CoreEntity> obj:subTypes) {
try {
CoreEntity tmp = obj.newInstance();
} catch (InstantiationException e) {
log.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
}
} |
package edu.brandeis.cs.steele.wn;
import java.util.logging.*;
import java.util.EnumSet;
import java.util.Arrays;
import java.util.Iterator;
/**
* A <code>Word</code> represents a line of a WordNet <code>index.<em>pos</em></code> file.
* A <code>Word</code> is retrieved via {@link DictionaryDatabase#lookupWord},
* and has a <i>lemma</i>, a <i>part of speech (POS)</i>, and a set of <i>senses</i>, which are of type {@link Synset}.
*
* XXX debatable what the type of each sense is - Steele said Synset, i'd say WordSense
*
* @see Synset
* @see WordSense
* @see Pointer
* @author Oliver Steele, steele@cs.brandeis.edu
* @version 1.0
*/
public class Word implements Comparable<Word>, Iterable<Synset> {
private static final Logger log = Logger.getLogger(Word.class.getName());
/** offset in <var>pos</var><code>.index</code> file */
private final int offset;
/** No case "lemma". Each {@link WordSense} has at least 1 true case lemma
* (could vary by POS).
*/
private final String lemma;
// number of senses with counts in sense tagged corpora
private final int taggedSenseCount;
/** Synsets are initially stored as offsets, and paged in on demand
* of the first call of {@link #getSynsets()}.
*/
private Object synsets;
private EnumSet<PointerType> ptrTypes;
private final byte posOrdinal;
// Constructor
Word(final CharSequence line, final int offset) {
try {
log.log(Level.FINEST, "parsing line: {0}", line);
final CharSequenceTokenizer tokenizer = new CharSequenceTokenizer(line, " ");
this.lemma = tokenizer.nextToken().toString().replace('_', ' ');
this.posOrdinal = (byte) POS.lookup(tokenizer.nextToken()).ordinal();
tokenizer.skipNextToken(); // poly_cnt
//final int poly_cnt = tokenizer.nextInt(); // poly_cnt
final int pointerCount = tokenizer.nextInt();
//this.ptrTypes = EnumSet.noneOf(PointerType.class);
for (int i = 0; i < pointerCount; i++) {
//XXX each of these tokens is a pointertype, although it may be may be
//incorrect - see getPointerTypes() comments)
tokenizer.skipNextToken();
// try {
// ptrTypes.add(PointerType.parseKey(tokenizer.nextToken()));
// } catch (final java.util.NoSuchElementException exc) {
// log.log(Level.SEVERE, "Word() got PointerType.parseKey() error:", exc);
}
this.offset = offset;
final int senseCount = tokenizer.nextInt();
// this is redundant information
//assert senseCount == poly_cnt;
this.taggedSenseCount = tokenizer.nextInt();
final int[] synsetOffsets = new int[senseCount];
for (int i = 0; i < senseCount; i++) {
synsetOffsets[i] = tokenizer.nextInt();
}
this.synsets = synsetOffsets;
//final EnumSet<PointerType> actualPtrTypes = EnumSet.noneOf(PointerType.class);
//for (final Synset synset : getSynsets()) {
// for (final Pointer pointer : synset.getPointers()) {
// final PointerType ptrType = pointer.getType();
// actualPtrTypes.add(ptrType);
//// in actualPtrTypes, NOT ptrTypes
//final EnumSet<PointerType> missing = EnumSet.copyOf(actualPtrTypes); missing.removeAll(ptrTypes);
//// in ptrTypes, NOT actualPtrTypes
//final EnumSet<PointerType> extra = EnumSet.copyOf(ptrTypes); extra.removeAll(actualPtrTypes);
//if(false == missing.isEmpty()) {
// //log.log(Level.SEVERE, "missing: {0}", missing);
//if(false == extra.isEmpty()) {
// //log.log(Level.SEVERE, "extra: {0}", extra);
} catch (final RuntimeException e) {
log.log(Level.SEVERE, "Word parse error on offset: {0} line:\n\"{1}\"",
new Object[]{ offset, line });
log.log(Level.SEVERE, "", e);
throw e;
}
}
// Accessors
public POS getPOS() {
return POS.fromOrdinal(posOrdinal);
}
/**
* The pointer types available for this indexed word. May not apply to all
* senses of the word.
*/
public EnumSet<PointerType> getPointerTypes() {
if (ptrTypes == null) {
// these are not always correct
// PointerType.INSTANCE_HYPERNYM
// PointerType.HYPERNYM
// PointerType.INSTANCE_HYPONYM
// PointerType.HYPONYM
final EnumSet<PointerType> localPtrTypes = EnumSet.noneOf(PointerType.class);
for (final Synset synset : getSynsets()) {
for (final Pointer pointer : synset.getPointers()) {
final PointerType ptrType = pointer.getType();
localPtrTypes.add(ptrType);
}
}
this.ptrTypes = localPtrTypes;
}
return ptrTypes;
}
/** Return the word's lowercased <i>lemma</i>. Its lemma is its orthographic
* representation, for example <code>"dog"</code> or <code>"get up"</code>
* or <code>"u.s."</code>.
*/
public String getLemma() {
return lemma;
}
/**
* Number of "words" (aka "tokens") in this <tt>Word</tt>'s lemma.
*/
public int getWordCount() {
// Morphy.counts() default implementation already counts
// space (' ') and underscore ('_') separated words
return Morphy.countWords(lemma, '-');
}
/**
* @return true if this <tt>Word</tt>'s <code>{@link #getWordCount()} < 1</code>.
*/
public boolean isCollocation() {
return getWordCount() > 1;
}
public int getTaggedSenseCount() {
return taggedSenseCount;
}
public Iterator<Synset> iterator() {
return Arrays.asList(getSynsets()).iterator();
}
public Synset[] getSynsets() {
// careful with this.synsets
synchronized(this) {
if (synsets instanceof int[]) {
final FileBackedDictionary dictionary = FileBackedDictionary.getInstance();
final int[] synsetOffsets = (int[])synsets;
// This memory optimization allows this.synsets is an int[] until this
// method is called to avoid needing to store both the offset and synset
// arrays
final Synset[] syns = new Synset[synsetOffsets.length];
for (int i = 0; i < synsetOffsets.length; i++) {
syns[i] = dictionary.getSynsetAt(getPOS(), synsetOffsets[i]);
assert syns[i] != null : "null Synset at index "+i+" of "+this;
}
synsets = syns;
}
// else assert this.synsets instanceof Synset[] already
}
return (Synset[])synsets;
}
public WordSense[] getSenses() {
final WordSense[] senses = new WordSense[getSynsets().length];
int senseNumberMinusOne = 0;
for (final Synset synset : getSynsets()) {
final WordSense wordSense = synset.getWordSense(this);
senses[senseNumberMinusOne] = wordSense;
assert senses[senseNumberMinusOne] != null :
this+" null WordSense at senseNumberMinusOne: "+senseNumberMinusOne;
senseNumberMinusOne++;
}
return senses;
}
/** Note, <param>senseNumber</param> is a 1-indexed value. */
public WordSense getSense(final int senseNumber) {
if (senseNumber <= 0) {
return null;
}
final Synset[] synsets = getSynsets();
if (senseNumber >= synsets.length) {
throw new IllegalArgumentException(this+" only has "+synsets.length+" senses");
}
return synsets[senseNumber - 1].getWordSense(this);
}
int getOffset() {
return offset;
}
// Object methods
@Override public boolean equals(final Object object) {
return (object instanceof Word)
&& ((Word) object).posOrdinal == posOrdinal
&& ((Word) object).offset == offset;
}
@Override public int hashCode() {
// times 10 shifts left by 1 decimal place
return ((int) offset * 10) + getPOS().hashCode();
}
@Override public String toString() {
return new StringBuilder("[Word ").
append(offset).
append("@").
append(getPOS().getLabel()).
append(": \"").
append(getLemma()).
append("\"]").toString();
}
/**
* {@inheritDoc}
*/
public int compareTo(final Word that) {
int result;
// if these ' ' -> '_' replaces aren't done resulting sort will not match
// index files. Alternate implementations include using a Comparator<CharSequence>
// which does this substitution on the fly or using a Collator (which is probably
// less efficient)
result = this.getLemma().replace(' ', '_').compareTo(that.getLemma().replace(' ', '_'));
if(result == 0) {
result = this.getPOS().compareTo(that.getPOS());
}
return result;
}
} |
package edu.uib.info310;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import edu.uib.info310.search.ArtistNotFoundException;
import edu.uib.info310.search.Searcher;
/**
* Sample controller for going to the home page with a message
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
@Autowired
private Searcher searcher;
/**
* Selects the home page and populates the model with a message
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
String helloWrold = null;
try {
helloWrold = GetUrl.getContent("http:
} catch (Exception e1) {
e1.printStackTrace();
}
model.addAttribute("controllerMessage",
helloWrold);
return "home";
}
@RequestMapping(value = "/search")
@ResponseStatus(value = HttpStatus.OK)
public ModelAndView search(@RequestParam String q){
logger.debug("Artist got search string: " + q);
ModelAndView mav = new ModelAndView();
mav.addObject("q", q);
try {
mav.addObject("artist", searcher.searchArtist(q));
mav.setViewName("artist");
} catch (ArtistNotFoundException e) {
mav.addObject("records", searcher.searchRecord(q));
mav.setViewName("searchResult");
}
return mav;
}
@RequestMapping(value = "/artist")
@ResponseStatus(value = HttpStatus.OK)
public ModelAndView artist(@RequestParam String q){
logger.debug("Artist got search string: " + q);
ModelAndView mav = new ModelAndView();
try {
mav.addObject("artist", searcher.searchArtist(q));
mav.setViewName("artist");
} catch (ArtistNotFoundException e) {
mav.setViewName("notFound");
}
return mav;
}
@RequestMapping(value = "/album")
@ResponseStatus(value = HttpStatus.OK)
public ModelAndView album(@RequestParam String q){
logger.debug("Album got search string: " + q);
ModelAndView mav = new ModelAndView();
mav.addObject("record", searcher.searchRecord(q));
mav.setViewName("album");
return mav;
}
} |
package io.github.classgraph;
import java.io.File;
import java.lang.annotation.Inherited;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.github.classgraph.json.Id;
import io.github.classgraph.utils.JarUtils;
import io.github.classgraph.utils.LogNode;
import io.github.classgraph.utils.Parser.ParseException;
import io.github.classgraph.utils.URLPathEncoder;
/** Holds metadata about a class encountered during a scan. */
public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo> {
/** Name of the class. */
private @Id String name;
/** Class modifier flags, e.g. Modifier.PUBLIC */
private int modifiers;
/** True if the classfile indicated this is an interface (or an annotation, which is an interface). */
private boolean isInterface;
/** True if the classfile indicated this is an annotation. */
private boolean isAnnotation;
/**
* This annotation has the {@link Inherited} meta-annotation, which means that any class that this annotation is
* applied to also implicitly causes the annotation to annotate all subclasses too.
*/
boolean isInherited;
/** The class type signature string. */
private String typeSignatureStr;
/** The class type signature, parsed. */
private transient ClassTypeSignature typeSignature;
/** The fully-qualified defining method name, for anonymous inner classes. */
private String fullyQualifiedDefiningMethodName;
/**
* If true, this class is only being referenced by another class' classfile as a superclass / implemented
* interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a
* whitelisted (non-blacklisted) package.
*
* If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a
* whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package.
*/
private boolean isExternalClass;
/**
* The classpath element file (classpath root dir or jar) that this class was found within, or null if this
* class was found in a module.
*/
transient File classpathElementFile;
/**
* The package root within a jarfile (e.g. "BOOT-INF/classes"), or the empty string if this is not a jarfile, or
* the package root is the classpath element path (as opposed to within a subdirectory of the classpath
* element).
*/
private transient String jarfilePackageRoot = "";
/**
* The classpath element module that this class was found within, or null if this class was found within a
* directory or jar.
*/
private transient ModuleRef moduleRef;
/** The classpath element URL (classpath root dir or jar) that this class was found within. */
private transient URL classpathElementURL;
/** The classloaders to try to load this class with before calling a MatchProcessor. */
transient ClassLoader[] classLoaders;
/** Info on class annotations, including optional annotation param values. */
AnnotationInfoList annotationInfo;
/** Info on fields. */
FieldInfoList fieldInfo;
/** Reverse mapping from field name to FieldInfo. */
private transient Map<String, FieldInfo> fieldNameToFieldInfo;
/** Info on fields. */
MethodInfoList methodInfo;
/** For annotations, the default values of parameters. */
List<AnnotationParameterValue> annotationDefaultParamValues;
/** The set of classes related to this one. */
private final Map<RelType, Set<ClassInfo>> relatedClasses = new HashMap<>();
/** Default constructor for deserialization. */
ClassInfo() {
}
private ClassInfo(final String name, final int classModifiers, final boolean isExternalClass) {
this();
this.name = name;
if (name.endsWith(";")) {
// Spot check to make sure class names were parsed from descriptors
throw new RuntimeException("Bad class name");
}
this.modifiers = classModifiers;
this.isExternalClass = isExternalClass;
}
/** How classes are related. */
private static enum RelType {
// Classes:
/**
* Superclasses of this class, if this is a regular class.
*
* <p>
* (Should consist of only one entry, or null if superclass is java.lang.Object or unknown).
*/
SUPERCLASSES,
/** Subclasses of this class, if this is a regular class. */
SUBCLASSES,
/** Indicates that an inner class is contained within this one. */
CONTAINS_INNER_CLASS,
/** Indicates that an outer class contains this one. (Should only have zero or one entries.) */
CONTAINED_WITHIN_OUTER_CLASS,
// Interfaces:
/**
* Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an
* interface.
*
* <p>
* (May also include annotations, since annotations are interfaces, so you can implement an annotation.)
*/
IMPLEMENTED_INTERFACES,
/**
* Classes that implement this interface (including sub-interfaces), if this is an interface.
*/
CLASSES_IMPLEMENTING,
// Class annotations:
/**
* Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is
* an annotation.
*/
CLASS_ANNOTATIONS,
/** Classes annotated with this annotation, if this is an annotation. */
CLASSES_WITH_ANNOTATION,
// Method annotations:
/** Annotations on one or more methods of this class. */
METHOD_ANNOTATIONS,
/**
* Classes that have one or more methods annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_METHOD_ANNOTATION,
// Field annotations:
/** Annotations on one or more fields of this class. */
FIELD_ANNOTATIONS,
/**
* Classes that have one or more fields annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_FIELD_ANNOTATION,
}
/**
* Add a class with a given relationship type. Return whether the collection changed as a result of the call.
*/
private boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) {
Set<ClassInfo> classInfoSet = relatedClasses.get(relType);
if (classInfoSet == null) {
relatedClasses.put(relType, classInfoSet = new LinkedHashSet<>(4));
}
return classInfoSet.add(classInfo);
}
private static final int ANNOTATION_CLASS_MODIFIER = 0x2000;
/**
* Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should
* only ever be constructed by a single thread.
*/
private static ClassInfo getOrCreateClassInfo(final String className, final int classModifiers,
final Map<String, ClassInfo> classNameToClassInfo) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ true));
}
classInfo.modifiers |= classModifiers;
if ((classModifiers & ANNOTATION_CLASS_MODIFIER) != 0) {
classInfo.isAnnotation = true;
}
if ((classModifiers & Modifier.INTERFACE) != 0) {
classInfo.isInterface = true;
}
return classInfo;
}
/** Add a superclass to this class. */
void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) {
if (superclassName != null && !superclassName.equals("java.lang.Object")) {
final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, /* classModifiers = */ 0,
classNameToClassInfo);
this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo);
superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this);
}
}
/** Add an implemented interface to this class. */
void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName,
/* classModifiers = */ Modifier.INTERFACE, classNameToClassInfo);
interfaceClassInfo.isInterface = true;
interfaceClassInfo.modifiers |= Modifier.INTERFACE;
this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo);
interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this);
}
/** Add class containment info */
static void addClassContainment(final List<SimpleEntry<String, String>> classContainmentEntries,
final Map<String, ClassInfo> classNameToClassInfo) {
for (final SimpleEntry<String, String> ent : classContainmentEntries) {
final String innerClassName = ent.getKey();
final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(innerClassName,
/* classModifiers = */ 0, classNameToClassInfo);
final String outerClassName = ent.getValue();
final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(outerClassName,
/* classModifiers = */ 0, classNameToClassInfo);
innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo);
outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo);
}
}
/** Add containing method name, for anonymous inner classes */
void addFullyQualifiedDefiningMethodName(final String fullyQualifiedDefiningMethodName) {
this.fullyQualifiedDefiningMethodName = fullyQualifiedDefiningMethodName;
}
/** Add an annotation to this class. */
void addClassAnnotation(final AnnotationInfo classAnnotationInfo,
final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.getName(),
ANNOTATION_CLASS_MODIFIER, classNameToClassInfo);
if (this.annotationInfo == null) {
this.annotationInfo = new AnnotationInfoList(2);
}
this.annotationInfo.add(classAnnotationInfo);
this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_ANNOTATION, this);
// Record use of @Inherited meta-annotation
if (classAnnotationInfo.getName().equals(Inherited.class.getName())) {
isInherited = true;
}
}
/** Add field info. */
void addFieldInfo(final FieldInfoList fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final FieldInfo fieldInfo : fieldInfoList) {
final AnnotationInfoList fieldAnnotationInfoList = fieldInfo.annotationInfo;
if (fieldAnnotationInfoList != null) {
for (final AnnotationInfo fieldAnnotationInfo : fieldAnnotationInfoList) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.getName(),
ANNOTATION_CLASS_MODIFIER, classNameToClassInfo);
// Mark this class as having a field with this annotation
this.addRelatedClass(RelType.FIELD_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_FIELD_ANNOTATION, this);
}
}
}
if (this.fieldInfo == null) {
this.fieldInfo = fieldInfoList;
} else {
this.fieldInfo.addAll(fieldInfoList);
}
}
/** Add method info. */
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo methodInfo : methodInfoList) {
final AnnotationInfoList methodAnnotationInfoList = methodInfo.annotationInfo;
if (methodAnnotationInfoList != null) {
for (final AnnotationInfo methodAnnotationInfo : methodAnnotationInfoList) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(methodAnnotationInfo.getName(),
ANNOTATION_CLASS_MODIFIER, classNameToClassInfo);
// Mark this class as having a method with this annotation
this.addRelatedClass(RelType.METHOD_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_ANNOTATION, this);
}
}
// // Currently it is not possible to find methods by annotation parameter annotation
// final AnnotationInfo[][] methodParamAnnotationInfoList = methodInfo.parameterAnnotationInfo;
// if (methodParamAnnotationInfoList != null) {
// for (int i = 0; i < methodParamAnnotationInfoList.length; i++) {
// final AnnotationInfo[] paramAnnotationInfoArr = methodParamAnnotationInfoList[i];
// if (paramAnnotationInfoArr != null) {
// for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
// final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
// final ClassInfo annotationClassInfo = getOrCreateClassInfo(
// methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER,
// classNameToClassInfo);
// // Index parameter annotations here
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList;
} else {
this.methodInfo.addAll(methodInfoList);
}
}
/** Add the class type signature, including type params */
void addTypeSignature(final String typeSignatureStr) {
if (this.typeSignatureStr == null) {
this.typeSignatureStr = typeSignatureStr;
} else {
if (typeSignatureStr != null && !this.typeSignatureStr.equals(typeSignatureStr)) {
throw new RuntimeException("Trying to merge two classes with different type signatures for class "
+ name + ": " + this.typeSignatureStr + " ; " + typeSignatureStr);
}
}
}
/**
* Add annotation default values. (Only called in the case of annotation class definitions, when the annotation
* has default parameter values.)
*/
void addAnnotationParamDefaultValues(final List<AnnotationParameterValue> paramNamesAndValues) {
if (this.annotationDefaultParamValues == null) {
this.annotationDefaultParamValues = paramNamesAndValues;
} else {
this.annotationDefaultParamValues.addAll(paramNamesAndValues);
}
}
/**
* Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe,
* should be run in single threaded context.
*/
static ClassInfo addScannedClass(final String className, final int classModifiers, final boolean isInterface,
final boolean isAnnotation, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final ScanSpec scanSpec, final LogNode log) {
boolean classEncounteredMultipleTimes = false;
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ false));
} else {
if (!classInfo.isExternalClass) {
classEncounteredMultipleTimes = true;
}
}
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
final File file = modRef != null ? null : classpathElement.getClasspathElementFile(log);
if ((classInfo.moduleRef != null && modRef != null && !classInfo.moduleRef.equals(modRef))
|| (classInfo.classpathElementFile != null && file != null
&& !classInfo.classpathElementFile.equals(file))) {
classEncounteredMultipleTimes = true;
}
if (classEncounteredMultipleTimes) {
// The same class was encountered more than once in a single jarfile -- should not happen. However,
// actually there is no restriction for paths within a zipfile to be unique (!!), and in fact
// zipfiles in the wild do contain the same classfiles multiple times with the same exact path,
// e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class
if (log != null) {
log.log("Class " + className + " is defined in multiple different classpath elements or modules
+ "ClassInfo#getClasspathElementFile() and/or ClassInfo#getClasspathElementModuleRef "
+ "will only return the first of these; attempting to merge info from all copies of "
+ "the classfile");
}
}
if (classInfo.classpathElementFile == null) {
// If class was found in more than one classpath element, keep the first classpath element reference
classInfo.classpathElementFile = file;
// Save jarfile package root, if any
classInfo.jarfilePackageRoot = classpathElement.getJarfilePackageRoot();
}
if (classInfo.moduleRef == null) {
// If class was found in more than one module, keep the first module reference
classInfo.moduleRef = modRef;
}
// Remember which classloader handles the class was found in, for classloading
final ClassLoader[] classLoaders = classpathElement.getClassLoaders();
if (classInfo.classLoaders == null) {
classInfo.classLoaders = classLoaders;
} else if (classLoaders != null && !Arrays.equals(classInfo.classLoaders, classLoaders)) {
// Merge together ClassLoader list (concatenate and dedup)
final LinkedHashSet<ClassLoader> allClassLoaders = new LinkedHashSet<>(
Arrays.asList(classInfo.classLoaders));
for (final ClassLoader classLoader : classLoaders) {
allClassLoaders.add(classLoader);
}
final List<ClassLoader> classLoaderOrder = new ArrayList<>(allClassLoaders);
classInfo.classLoaders = classLoaderOrder.toArray(new ClassLoader[0]);
}
// Mark the classfile as scanned
classInfo.isExternalClass = false;
// Merge modifiers
classInfo.modifiers |= classModifiers;
classInfo.isInterface |= isInterface;
classInfo.isAnnotation |= isAnnotation;
return classInfo;
}
/** The class type to return. */
private static enum ClassType {
/** Get all class types. */
ALL,
/** A standard class (not an interface or annotation). */
STANDARD_CLASS,
/**
* An interface (this is named "implemented interface" rather than just "interface" to distinguish it from
* an annotation.)
*/
IMPLEMENTED_INTERFACE,
/** An annotation. */
ANNOTATION,
/** An interface or annotation (used since you can actually implement an annotation). */
INTERFACE_OR_ANNOTATION,
}
/**
* Filter classes according to scan spec and class type.
*
* @param strictWhitelist
* If true, exclude class if it is is external, blacklisted, or a system class.
*/
private static Set<ClassInfo> filterClassInfo(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final boolean strictWhitelist, final ClassType... classTypes) {
if (classes == null) {
return null;
}
boolean includeAllTypes = classTypes.length == 0;
boolean includeStandardClasses = false;
boolean includeImplementedInterfaces = false;
boolean includeAnnotations = false;
for (final ClassType classType : classTypes) {
switch (classType) {
case ALL:
includeAllTypes = true;
break;
case STANDARD_CLASS:
includeStandardClasses = true;
break;
case IMPLEMENTED_INTERFACE:
includeImplementedInterfaces = true;
break;
case ANNOTATION:
includeAnnotations = true;
break;
case INTERFACE_OR_ANNOTATION:
includeImplementedInterfaces = includeAnnotations = true;
break;
default:
throw new RuntimeException("Unknown ClassType: " + classType);
}
}
if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) {
includeAllTypes = true;
}
final Set<ClassInfo> classInfoSetFiltered = new LinkedHashSet<>(classes.size());
for (final ClassInfo classInfo : classes) {
// Check class type against requested type(s)
if (includeAllTypes
|| includeStandardClasses && classInfo.isStandardClass()
|| includeImplementedInterfaces && classInfo.isImplementedInterface()
|| includeAnnotations && classInfo.isAnnotation()) {
if (
// Always check blacklist
!scanSpec.classIsBlacklisted(classInfo.name)
// If not blacklisted, and strictWhitelist is false, add class
&& (!strictWhitelist || (
// Don't include external classes unless enableExternalClasses is true
(!classInfo.isExternalClass || scanSpec.enableExternalClasses)
// If this is a system class, ignore blacklist unless the blanket blacklisting of
// all system jars or modules has been disabled, and this system class was specifically
// blacklisted by name
&& (!scanSpec.blacklistSystemJarsOrModules
|| !JarUtils.isInSystemPackageOrModule(classInfo.name))))) {
// Class passed strict whitelist criteria
classInfoSetFiltered.add(classInfo);
}
}
}
return classInfoSetFiltered;
}
/**
* A set of classes that indirectly reachable through a directed path, for a given relationship type, and a set
* of classes that is directly related (only one relationship step away).
*/
static class ReachableAndDirectlyRelatedClasses {
final Set<ClassInfo> reachableClasses;
final Set<ClassInfo> directlyRelatedClasses;
private ReachableAndDirectlyRelatedClasses(final Set<ClassInfo> reachableClasses,
final Set<ClassInfo> directlyRelatedClasses) {
this.reachableClasses = reachableClasses;
this.directlyRelatedClasses = directlyRelatedClasses;
}
}
private static final ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES =
new ReachableAndDirectlyRelatedClasses(Collections.<ClassInfo> emptySet(),
Collections.<ClassInfo> emptySet());
/**
* Get the classes related to this one (the transitive closure) for the given relationship type, and those
* directly related.
*/
private ReachableAndDirectlyRelatedClasses filterClassInfo(final RelType relType, final boolean strictWhitelist,
final ClassType... classTypes) {
final Set<ClassInfo> directlyRelatedClasses = this.relatedClasses.get(relType);
if (directlyRelatedClasses == null) {
return NO_REACHABLE_CLASSES;
}
final Set<ClassInfo> reachableClasses = new LinkedHashSet<>(directlyRelatedClasses);
if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) {
// For method and field annotations, need to change the RelType when finding meta-annotations
for (final ClassInfo annotation : directlyRelatedClasses) {
reachableClasses.addAll(
annotation.filterClassInfo(RelType.CLASS_ANNOTATIONS, strictWhitelist).reachableClasses);
}
} else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_FIELD_ANNOTATION) {
// If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then
// look for the methods or fields that they annotate
for (final ClassInfo subAnnotation : this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION,
strictWhitelist, ClassType.ANNOTATION).reachableClasses) {
final Set<ClassInfo> annotatedClasses = subAnnotation.relatedClasses.get(relType);
if (annotatedClasses != null) {
reachableClasses.addAll(annotatedClasses);
}
}
} else {
// For other relationship types, the reachable type stays the same over the transitive closure. Find the
// transitive closure, breaking cycles where necessary.
final LinkedList<ClassInfo> queue = new LinkedList<>();
queue.addAll(directlyRelatedClasses);
while (!queue.isEmpty()) {
final ClassInfo head = queue.removeFirst();
final Set<ClassInfo> headRelatedClasses = head.relatedClasses.get(relType);
if (headRelatedClasses != null) {
for (final ClassInfo directlyReachableFromHead : headRelatedClasses) {
// Don't get in cycle
if (reachableClasses.add(directlyReachableFromHead)) {
queue.add(directlyReachableFromHead);
}
}
}
}
}
if (reachableClasses.isEmpty()) {
return NO_REACHABLE_CLASSES;
}
// Special case -- don't inherit java.lang.annotation.* meta-annotations as related meta-annotations
// (but still return them as direct meta-annotations on annotation classes).
Set<ClassInfo> javaLangAnnotationRelatedClasses = null;
for (final ClassInfo classInfo : reachableClasses) {
if (classInfo.getName().startsWith("java.lang.annotation.")) {
if (javaLangAnnotationRelatedClasses == null) {
javaLangAnnotationRelatedClasses = new LinkedHashSet<>();
}
javaLangAnnotationRelatedClasses.add(classInfo);
}
}
if (javaLangAnnotationRelatedClasses != null) {
// Remove all java.lang.annotation annotations that are not directly related to this class
Set<ClassInfo> javaLangAnnotationDirectlyRelatedClasses = null;
for (final ClassInfo classInfo : directlyRelatedClasses) {
if (classInfo.getName().startsWith("java.lang.annotation.")) {
if (javaLangAnnotationDirectlyRelatedClasses == null) {
javaLangAnnotationDirectlyRelatedClasses = new LinkedHashSet<>();
}
javaLangAnnotationDirectlyRelatedClasses.add(classInfo);
}
}
if (javaLangAnnotationDirectlyRelatedClasses != null) {
javaLangAnnotationRelatedClasses.removeAll(javaLangAnnotationDirectlyRelatedClasses);
}
reachableClasses.removeAll(javaLangAnnotationRelatedClasses);
}
return new ReachableAndDirectlyRelatedClasses(
filterClassInfo(reachableClasses, scanResult.scanSpec, strictWhitelist),
filterClassInfo(directlyRelatedClasses, scanResult.scanSpec, strictWhitelist));
}
/**
* Get all classes found during the scan.
*
* @return A list of all classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final ScanResult scanResult) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ALL),
/* sortByName = */ true);
}
/**
* Get all standard classes found during the scan.
*
* @return A list of all standard classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllStandardClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final ScanResult scanResult) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.STANDARD_CLASS), /* sortByName = */ true);
}
/**
* Get all implemented interface (non-annotation interface) classes found during the scan.
*
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllImplementedInterfaceClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec, final ScanResult scanResult) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.IMPLEMENTED_INTERFACE), /* sortByName = */ true);
}
/**
* Get all annotation classes found during the scan. See also {@link #getAllInterfaceOrAnnotationClasses()}.
*
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final ScanResult scanResult) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION),
/* sortByName = */ true);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
static ClassInfoList getAllInterfacesOrAnnotationClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec, final ScanResult scanResult) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.INTERFACE_OR_ANNOTATION), /* sortByName = */ true);
}
// Predicates
/** @return The name of the class. */
public String getName() {
return name;
}
/**
* @return true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass,
* interface, or annotation, but is not itself a whitelisted class.
*/
public boolean isExternalClass() {
return isExternalClass;
}
/**
* @return The class modifier bits, e.g. {@link Modifier#PUBLIC}.
*/
public int getModifiers() {
return modifiers;
}
/**
* @return The field modifiers as a string, e.g. "public static final". For the modifier bits, call
* {@link #getModifiers()}.
*/
public String getModifiersStr() {
final StringBuilder buf = new StringBuilder();
ClassTypeSignature.modifiersToString(modifiers, buf);
return buf.toString();
}
/**
* @return true if this class is a public class.
*/
public boolean isPublic() {
return (modifiers & Modifier.PUBLIC) != 0;
}
/**
* @return true if this class is an abstract class.
*/
public boolean isAbstract() {
return (modifiers & 0x400) != 0;
}
/**
* @return true if this class is a synthetic class.
*/
public boolean isSynthetic() {
return (modifiers & 0x1000) != 0;
}
/**
* @return true if this class is a final class.
*/
public boolean isFinal() {
return (modifiers & Modifier.FINAL) != 0;
}
/**
* @return true if this class is static.
*/
public boolean isStatic() {
return Modifier.isStatic(modifiers);
}
/**
* @return true if this class is an annotation class.
*/
public boolean isAnnotation() {
return isAnnotation;
}
/**
* @return true if this class is an interface and is not an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterface() {
return isInterface && !isAnnotation;
}
/**
* @return true if this class is an interface or an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterfaceOrAnnotation() {
return isInterface;
}
/**
* @return true if this class is an {@link Enum}.
*/
public boolean isEnum() {
return (modifiers & 0x4000) != 0;
}
/**
* @return true if this class is a standard class (i.e. is not an annotation or interface).
*/
public boolean isStandardClass() {
return !(isAnnotation || isInterface);
}
/**
* @param superclassName
* The name of a superclass.
* @return true if this class extends the named superclass.
*/
public boolean extendsSuperclass(final String superclassName) {
return getSuperclasses().containsName(superclassName);
}
/**
* @return true if this is an inner class (call {@link #isAnonymousInnerClass()} to test if this is an anonymous
* inner class). If true, the containing class can be determined by calling {@link #getOuterClasses()}.
*/
public boolean isInnerClass() {
return !getOuterClasses().isEmpty();
}
/**
* @return true if this class contains inner classes. If true, the inner classes can be determined by calling
* {@link #getInnerClasses()}.
*/
public boolean isOuterClass() {
return !getInnerClasses().isEmpty();
}
/**
* @return true if this is an anonymous inner class. If true, the name of the containing method can be obtained
* by calling {@link #getFullyQualifiedDefiningMethodName()}.
*/
public boolean isAnonymousInnerClass() {
return fullyQualifiedDefiningMethodName != null;
}
/**
* Return whether this class is an implemented interface (meaning a standard, non-annotation interface, or an
* annotation that has also been implemented as an interface by some class).
*
* <p>
* Annotations are interfaces, but you can also implement an annotation, so to we return whether an interface
* (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not
* an interface but not an annotation.
*
* @return true if this class is an implemented interface.
*/
public boolean isImplementedInterface() {
return relatedClasses.get(RelType.CLASSES_IMPLEMENTING) != null || (isInterface && !isAnnotation);
}
/**
* @param interfaceName
* The name of an interface.
* @return true if this class implements the named interface.
*/
public boolean implementsInterface(final String interfaceName) {
return getInterfaces().containsName(interfaceName);
}
/**
* @param annotationName
* The name of an annotation.
* @return true if this class has the named annotation.
*/
public boolean hasAnnotation(final String annotationName) {
return getAnnotations().containsName(annotationName);
}
/**
* @param fieldName
* The name of a field.
* @return true if this class has the named field.
*/
public boolean hasField(final String fieldName) {
return getFieldInfo().containsName(fieldName);
}
/**
* @param fieldAnnotationName
* The name of a field annotation.
* @return true if this class has a field with the named annotation.
*/
public boolean hasFieldAnnotation(final String fieldAnnotationName) {
for (final FieldInfo fieldInfo : getFieldInfo()) {
if (fieldInfo.getAnnotationInfo().containsName(fieldAnnotationName)) {
return true;
}
}
return false;
}
/**
* @param methodName
* The name of a method.
* @return true if this class has a method of the requested name.
*/
public boolean hasMethod(final String methodName) {
return getMethodInfo().containsName(methodName);
}
/**
* @param methodAnnotationName
* The name of a mehtod annotation.
* @return true if this class has a method with the named annotation.
*/
public boolean hasMethodAnnotation(final String methodAnnotationName) {
for (final MethodInfo methodInfo : getMethodInfo()) {
if (methodInfo.getAnnotationInfo().containsName(methodAnnotationName)) {
return true;
}
}
return false;
}
// Standard classes
/**
* Get the subclasses of this class, sorted in order of name. Call {@link ClassInfoList#directOnly()} to get
* direct subclasses.
*
* @return the list of subclasses of this class, or the empty list if none.
*/
public ClassInfoList getSubclasses() {
if (getName().equals("java.lang.Object")) {
// Make an exception for querying all subclasses of java.lang.Object
return scanResult.getAllClasses();
} else {
return new ClassInfoList(this.filterClassInfo(RelType.SUBCLASSES, /* strictWhitelist = */ true),
/* sortByName = */ true);
}
}
/**
* Get all superclasses of this class, in ascending order in the class hierarchy. Does not include
* superinterfaces, if this is an interface (use {@link #getInterfaces()} to get superinterfaces of an
* interface.}
*
* @return the list of all superclasses of this class, or the empty list if none.
*/
public ClassInfoList getSuperclasses() {
return new ClassInfoList(this.filterClassInfo(RelType.SUPERCLASSES, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* Get the single direct superclass of this class, or null if none. Does not return the superinterfaces, if this
* is an interface (use {@link #getInterfaces()} to get superinterfaces of an interface.}
*
* @return the superclass of this class, or null if none.
*/
public ClassInfo getSuperclass() {
final Set<ClassInfo> superClasses = relatedClasses.get(RelType.SUPERCLASSES);
if (superClasses == null || superClasses.isEmpty()) {
return null;
} else if (superClasses.size() > 2) {
throw new IllegalArgumentException("More than one superclass: " + superClasses);
} else {
final ClassInfo superclass = superClasses.iterator().next();
if (superclass.getName().equals("java.lang.Object")) {
return null;
} else {
return superclass;
}
}
}
/**
* @return A list of the containing outer classes, if this is an inner class, otherwise the empty list. Note
* that all containing outer classes are returned, not just the innermost of the containing outer
* classes.
*/
public ClassInfoList getOuterClasses() {
return new ClassInfoList(
this.filterClassInfo(RelType.CONTAINED_WITHIN_OUTER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* @return A list of the inner classes contained within this class, or the empty list if none.
*/
public ClassInfoList getInnerClasses() {
return new ClassInfoList(this.filterClassInfo(RelType.CONTAINS_INNER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ true);
}
/**
* @return The fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method
* name) for the defining method, if this is an anonymous inner class, or null if not.
*/
public String getFullyQualifiedDefiningMethodName() {
return fullyQualifiedDefiningMethodName;
}
// Interfaces
/**
* @return The list of interfaces implemented by this class or by one of its superclasses, if this is a standard
* class, or the superinterfaces extended by this interface, if this is an interface. Returns the empty
* list if none.
*/
public ClassInfoList getInterfaces() {
// Classes also implement the interfaces of their superclasses
final ReachableAndDirectlyRelatedClasses implementedInterfaces = this
.filterClassInfo(RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false);
final Set<ClassInfo> allInterfaces = new LinkedHashSet<>(implementedInterfaces.reachableClasses);
for (final ClassInfo superclass : this.filterClassInfo(RelType.SUPERCLASSES,
/* strictWhitelist = */ false).reachableClasses) {
final Set<ClassInfo> superclassImplementedInterfaces = superclass.filterClassInfo(
RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false).reachableClasses;
allInterfaces.addAll(superclassImplementedInterfaces);
}
return new ClassInfoList(allInterfaces, implementedInterfaces.directlyRelatedClasses,
/* sortByName = */ true);
}
/**
* @return the list of the classes (and their subclasses) that implement this interface, if this is an
* interface, otherwise returns the empty list.
*/
public ClassInfoList getClassesImplementing() {
if (!isInterface) {
throw new IllegalArgumentException("Class is not an interface: " + getName());
}
// Subclasses of implementing classes also implement the interface
final ReachableAndDirectlyRelatedClasses implementingClasses = this
.filterClassInfo(RelType.CLASSES_IMPLEMENTING, /* strictWhitelist = */ true);
final Set<ClassInfo> allImplementingClasses = new LinkedHashSet<>(implementingClasses.reachableClasses);
for (final ClassInfo implementingClass : implementingClasses.reachableClasses) {
final Set<ClassInfo> implementingSubclasses = implementingClass.filterClassInfo(RelType.SUBCLASSES,
/* strictWhitelist = */ true).reachableClasses;
allImplementingClasses.addAll(implementingSubclasses);
}
return new ClassInfoList(allImplementingClasses, implementingClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
// Annotations
/**
* Get the annotations and meta-annotations on this class. (Call {@link #getAnnotationInfo()} instead, if you
* need the parameter values of annotations, rather than just the annotation classes.)
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* @return the list of annotations and meta-annotations on this class.
*/
public ClassInfoList getAnnotations() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
// Get all annotations on this class
final ReachableAndDirectlyRelatedClasses annotationClasses = this.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false);
// Check for any @Inherited annotations on superclasses
Set<ClassInfo> inheritedSuperclassAnnotations = null;
for (final ClassInfo superclass : getSuperclasses()) {
for (final ClassInfo superclassAnnotationClass : superclass.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false).reachableClasses) {
final Set<ClassInfo> superclassAnnotations = superclassAnnotationClass.relatedClasses
.get(RelType.CLASS_ANNOTATIONS);
if (superclassAnnotations != null) {
// Check if any of the meta-annotations on this annotation are @Inherited,
// which causes an annotation to annotate a class and all of its subclasses.
if (isInherited) {
// inheritedSuperclassAnnotations is an inherited annotation
if (inheritedSuperclassAnnotations == null) {
inheritedSuperclassAnnotations = new LinkedHashSet<>();
}
inheritedSuperclassAnnotations.add(superclassAnnotationClass);
}
}
}
}
if (inheritedSuperclassAnnotations == null) {
// No inherited superclass annotations
return new ClassInfoList(annotationClasses, /* sortByName = */ true);
} else {
// Merge inherited superclass annotations and annotations on this class
inheritedSuperclassAnnotations.addAll(annotationClasses.reachableClasses);
return new ClassInfoList(inheritedSuperclassAnnotations, annotationClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
}
/**
* Get a list of direct annotations on this method, along with any annotation parameter values, as a list of
* {@link AnnotationInfo} objects, or the empty list if none.
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* @return A list of {@link AnnotationInfo} objects for the annotations on this method, or the empty list if
* none.
*/
public AnnotationInfoList getAnnotationInfo() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
// Check for any @Inherited annotations on superclasses
AnnotationInfoList inheritedSuperclassAnnotations = null;
for (final ClassInfo superclass : getSuperclasses()) {
for (final AnnotationInfo superclassAnnotationInfo : superclass.getAnnotationInfo()) {
if (superclassAnnotationInfo.isInherited()) {
// inheritedSuperclassAnnotations is an inherited annotation
if (inheritedSuperclassAnnotations == null) {
inheritedSuperclassAnnotations = new AnnotationInfoList();
}
inheritedSuperclassAnnotations.add(superclassAnnotationInfo);
}
}
}
if (inheritedSuperclassAnnotations == null) {
// No inherited superclass annotations
return annotationInfo == null ? AnnotationInfoList.EMPTY_LIST : annotationInfo;
} else {
// Merge inherited superclass annotations and annotations on this class
if (annotationInfo != null) {
inheritedSuperclassAnnotations.addAll(annotationInfo);
}
Collections.sort(inheritedSuperclassAnnotations);
return inheritedSuperclassAnnotations;
}
}
/**
* @return A list of {@link AnnotationParameterValue} objects for each of the default parameter values for this
* annotation, if this is an annotation class with default parameter values, otherwise the empty list.
*/
public List<AnnotationParameterValue> getAnnotationDefaultParameterValues() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
return annotationDefaultParamValues == null ? Collections.<AnnotationParameterValue> emptyList()
: annotationDefaultParamValues;
}
/**
* @return A list of standard classes and non-annotation interfaces that are annotated by this class, if this is
* an annotation class, or the empty list if none. Also handles the {@link Inherited} meta-annotation,
* which causes an annotation on a class to be inherited by all of its subclasses.
*/
public ClassInfoList getClassesWithAnnotation() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
// Get classes that have this annotation
final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this
.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ true);
if (isInherited) {
// If this is an inherited annotation, add into the result all subclasses of the annotated classes.
final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>(
classesWithAnnotation.reachableClasses);
for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) {
classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithAnnotationAndTheirSubclasses,
classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true);
} else {
// If not inherited, only return the annotated classes
return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true);
}
}
/**
* @return The list of classes that are directly (i.e. are not meta-annotated) annotated with the requested
* annotation, or the empty list if none.
*/
ClassInfoList getClassesWithAnnotationDirectOnly() {
return new ClassInfoList(
this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ true),
/* sortByName = */ true);
}
// Methods
public MethodInfoList getMethodInfo() {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
if (methodInfo == null) {
return MethodInfoList.EMPTY_LIST;
} else {
final MethodInfoList nonConstructorMethods = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
final String methodName = mi.getName();
if (!methodName.equals("<init>") && !methodName.equals("<clinit>")) {
nonConstructorMethods.add(mi);
}
}
return nonConstructorMethods;
}
}
public MethodInfoList getConstructorInfo() {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
if (methodInfo == null) {
return MethodInfoList.EMPTY_LIST;
} else {
final MethodInfoList nonConstructorMethods = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
final String methodName = mi.getName();
if (methodName.equals("<init>")) {
nonConstructorMethods.add(mi);
}
}
return nonConstructorMethods;
}
}
public MethodInfoList getMethodAndConstructorInfo() {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
return methodInfo == null ? MethodInfoList.EMPTY_LIST : methodInfo;
}
public MethodInfoList getMethodInfo(final String methodName) {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
if (methodInfo == null) {
return MethodInfoList.EMPTY_LIST;
}
boolean hasMethodWithName = false;
for (final MethodInfo f : methodInfo) {
if (f.getName().equals(methodName)) {
hasMethodWithName = true;
break;
}
}
if (!hasMethodWithName) {
return MethodInfoList.EMPTY_LIST;
}
final MethodInfoList methodInfoList = new MethodInfoList();
for (final MethodInfo f : methodInfo) {
if (f.getName().equals(methodName)) {
methodInfoList.add(f);
}
}
return methodInfoList;
}
/**
* @return A list of method annotations or meta-annotations on this class, as a list of {@link ClassInfo}
* objects, or the empty list if none. N.B. these annotations do not contain specific annotation
* parameters -- call {@link MethodInfo#getAnnotationInfo()} to get details on specific method
* annotation instances.
*/
public ClassInfoList getMethodAnnotations() {
if (!scanResult.scanSpec.enableMethodInfo || !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call ClassGraph#enableMethodInfo() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses methodAnnotations = this
.filterClassInfo(RelType.METHOD_ANNOTATIONS, /* strictWhitelist = */ false, ClassType.ANNOTATION);
final Set<ClassInfo> methodAnnotationsAndMetaAnnotations = new LinkedHashSet<>(
methodAnnotations.reachableClasses);
for (final ClassInfo methodAnnotation : methodAnnotations.reachableClasses) {
methodAnnotationsAndMetaAnnotations.addAll(methodAnnotation.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false).reachableClasses);
}
return new ClassInfoList(methodAnnotationsAndMetaAnnotations, methodAnnotations.directlyRelatedClasses,
/* sortByName = */ true);
}
/**
* @return A list of classes that have a method with this annotation or meta-annotation, or the empty list if
* none.
*/
public ClassInfoList getClassesWithMethodAnnotation() {
if (!scanResult.scanSpec.enableMethodInfo || !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call ClassGraph#enableMethodInfo() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedMethods = this
.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION, /* strictWhitelist = */ true);
final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo(
RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ false, ClassType.ANNOTATION);
if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) {
// This annotation does not meta-annotate another annotation that annotates a method
return new ClassInfoList(classesWithDirectlyAnnotatedMethods, /* sortByName = */ true);
} else {
// Take the union of all classes with methods directly annotated by this annotation,
// and classes with methods meta-annotated by this annotation
final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedMethods = new LinkedHashSet<>(
classesWithDirectlyAnnotatedMethods.reachableClasses);
for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) {
allClassesWithAnnotatedOrMetaAnnotatedMethods
.addAll(metaAnnotatedAnnotation.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION,
/* strictWhitelist = */ true).reachableClasses);
}
return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedMethods,
classesWithDirectlyAnnotatedMethods.directlyRelatedClasses, /* sortByName = */ true);
}
}
/**
* @return A list of classes that have methods that are directly annotated (i.e. are not meta-annotated) with
* the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithMethodAnnotationDirectOnly() {
return new ClassInfoList(
this.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION, /* strictWhitelist = */ true),
/* sortByName = */ true);
}
// Fields
public FieldInfoList getFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
return fieldInfo == null ? FieldInfoList.EMPTY_LIST : fieldInfo;
}
public FieldInfo getFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
if (fieldInfo == null) {
return null;
}
if (fieldNameToFieldInfo == null) {
// Lazily build reverse mapping cache
fieldNameToFieldInfo = new HashMap<>();
for (final FieldInfo f : fieldInfo) {
fieldNameToFieldInfo.put(f.getName(), f);
}
}
return fieldNameToFieldInfo.get(fieldName);
}
/**
* @return A list of field annotations on this class, or the empty list if none. N.B. these annotations do not
* contain specific annotation parameters -- call {@link FieldInfo#getAnnotationInfo()} to get details
* on specific field annotation instances.
*/
public ClassInfoList getFieldAnnotations() {
if (!scanResult.scanSpec.enableFieldInfo || !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() and "
+ "ClassGraph#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses fieldAnnotations = this.filterClassInfo(RelType.FIELD_ANNOTATIONS,
/* strictWhitelist = */ false, ClassType.ANNOTATION);
final Set<ClassInfo> fieldAnnotationsAndMetaAnnotations = new LinkedHashSet<>(
fieldAnnotations.reachableClasses);
for (final ClassInfo fieldAnnotation : fieldAnnotations.reachableClasses) {
fieldAnnotationsAndMetaAnnotations.addAll(fieldAnnotation.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false).reachableClasses);
}
return new ClassInfoList(fieldAnnotationsAndMetaAnnotations, fieldAnnotations.directlyRelatedClasses,
/* sortByName = */ true);
}
/**
* @return A list of classes that have a field with this annotation or meta-annotation, or the empty list if
* none.
*/
public ClassInfoList getClassesWithFieldAnnotation() {
if (!scanResult.scanSpec.enableFieldInfo || !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() and "
+ "ClassGraph#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFields = this
.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION, /* strictWhitelist = */ true);
final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo(
RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ false, ClassType.ANNOTATION);
if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) {
// This annotation does not meta-annotate another annotation that annotates a field
return new ClassInfoList(classesWithDirectlyAnnotatedFields, /* sortByName = */ true);
} else {
// Take the union of all classes with fields directly annotated by this annotation,
// and classes with fields meta-annotated by this annotation
final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFields = new LinkedHashSet<>(
classesWithDirectlyAnnotatedFields.reachableClasses);
for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) {
allClassesWithAnnotatedOrMetaAnnotatedFields
.addAll(metaAnnotatedAnnotation.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION,
/* strictWhitelist = */ true).reachableClasses);
}
return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFields,
classesWithDirectlyAnnotatedFields.directlyRelatedClasses, /* sortByName = */ true);
}
}
/**
* @return A list of classes that have fields that are directly annotated (i.e. are not meta-annotated) with the
* requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithFieldAnnotationDirectOnly() {
return new ClassInfoList(
this.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION, /* strictWhitelist = */ true),
/* sortByName = */ true);
}
/** @return The class type signature, if available, otherwise returns null. */
public ClassTypeSignature getTypeSignature() {
if (typeSignatureStr == null) {
return null;
}
if (typeSignature == null) {
try {
typeSignature = ClassTypeSignature.parse(typeSignatureStr, this);
typeSignature.setScanResult(scanResult);
} catch (final ParseException e) {
throw new IllegalArgumentException(e);
}
}
return typeSignature;
}
/**
* @return The URL of the classpath element that this class was found within.
*/
public URL getClasspathElementURL() {
if (classpathElementURL == null) {
try {
if (moduleRef != null) {
// Classpath elt is a module
classpathElementURL = moduleRef.getLocation().toURL();
} else if (classpathElementFile.isFile() && !jarfilePackageRoot.isEmpty()) {
// Classpath elt is a jarfile with a non-empty package root
classpathElementURL = new URL("jar:" + classpathElementFile.toURI().toURL().toString() + "!"
+ URLPathEncoder.encodePath(jarfilePackageRoot));
} else {
// Classpath elt is a directory, or a jarfile with an empty package root
classpathElementURL = classpathElementFile.toURI().toURL();
}
} catch (final MalformedURLException e) {
// Shouldn't happen
throw new IllegalArgumentException(e);
}
}
return classpathElementURL;
}
/**
* @return The {@link File} for the classpath element package root dir or jar that this class was found within,
* or null if this class was found in a module. (See also {@link #getModuleRef}.)
*/
public File getClasspathElementFile() {
return classpathElementFile;
}
/**
* @return The module in the module path that this class was found within, as a {@link ModuleRef}, or null if
* this class was found in a directory or jar in the classpath. (See also
* {@link #getClasspathElementFile()}.)
*/
public ModuleRef getModuleRef() {
return moduleRef;
}
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType, final boolean ignoreExceptions) {
return super.loadClass(superclassOrInterfaceType, ignoreExceptions);
}
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType) {
return super.loadClass(superclassOrInterfaceType, /* ignoreExceptions = */ false);
}
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
return super.loadClass(ignoreExceptions);
}
@Override
public Class<?> loadClass() {
return super.loadClass(/* ignoreExceptions = */ false);
}
@Override
protected String getClassName() {
return name;
}
@Override
protected ClassInfo getClassInfo() {
return this;
}
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (this.typeSignature != null) {
this.typeSignature.setScanResult(scanResult);
}
if (annotationInfo != null) {
for (final AnnotationInfo ai : annotationInfo) {
ai.setScanResult(scanResult);
}
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.setScanResult(scanResult);
}
}
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.setScanResult(scanResult);
}
}
if (annotationDefaultParamValues != null) {
for (final AnnotationParameterValue apv : annotationDefaultParamValues) {
apv.setScanResult(scanResult);
}
}
}
/**
* Get the names of any classes referenced in this class' type descriptor, or the type descriptors of fields,
* methods or annotations.
*/
@Override
protected void getClassNamesFromTypeDescriptors(final Set<String> classNames) {
final Set<String> referencedClassNames = new LinkedHashSet<>();
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.getClassNamesFromTypeDescriptors(classNames);
}
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.getClassNamesFromTypeDescriptors(classNames);
}
}
if (annotationInfo != null) {
for (final AnnotationInfo ai : annotationInfo) {
ai.getClassNamesFromTypeDescriptors(referencedClassNames);
}
}
if (annotationDefaultParamValues != null) {
for (final AnnotationParameterValue paramValue : annotationDefaultParamValues) {
paramValue.getClassNamesFromTypeDescriptors(referencedClassNames);
}
}
final ClassTypeSignature classSig = getTypeSignature();
if (classSig != null) {
classSig.getClassNamesFromTypeDescriptors(referencedClassNames);
}
}
/** Compare based on class name. */
@Override
public int compareTo(final ClassInfo o) {
return this.name.compareTo(o.name);
}
/** Use class name for equals(). */
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final ClassInfo other = (ClassInfo) obj;
return name.equals(other.name);
}
/** Use hash code of class name. */
@Override
public int hashCode() {
return name != null ? name.hashCode() : 33;
}
private String toString(final boolean typeNameOnly) {
final ClassTypeSignature typeSig = getTypeSignature();
if (typeSig != null) {
// Generic classes
return typeSig.toString(name, typeNameOnly, modifiers, isAnnotation, isInterface);
} else {
// Non-generic classes
final StringBuilder buf = new StringBuilder();
if (typeNameOnly) {
buf.append(name);
} else {
ClassTypeSignature.modifiersToString(modifiers, buf);
if (buf.length() > 0) {
buf.append(' ');
}
buf.append(isAnnotation ? "@interface "
: isInterface ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class ");
buf.append(name);
final ClassInfo superclass = getSuperclass();
if (superclass != null && !superclass.getName().equals("java.lang.Object")) {
buf.append(" extends " + superclass.toString(/* typeNameOnly = */ true));
}
final Set<ClassInfo> interfaces = this.filterClassInfo(RelType.IMPLEMENTED_INTERFACES,
/* strictWhitelist = */ false).directlyRelatedClasses;
if (!interfaces.isEmpty()) {
buf.append(isInterface ? " extends " : " implements ");
boolean first = true;
for (final ClassInfo iface : interfaces) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(iface.toString(/* typeNameOnly = */ true));
}
}
}
return buf.toString();
}
}
@Override
public String toString() {
return toString(false);
}
} |
package ixa.kaflib;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom2.Element;
import org.jdom2.Element;
import org.jdom2.JDOMException;
/** A container to keep all annotations of a document (word forms, terms, dependencies, chunks, entities and coreferences). There are different hash maps to index annotations by different properties as ID, sentence... It enables to retrieve annotations by different properties in an effective way. Performance is very important. */
class AnnotationContainer implements Serializable {
private String rawText;
/** List to keep all word forms */
private List<WF> text;
/** Next offset: sum of all words' length plus one char per word */
private int nextOffset;
/** List to keep all terms */
private List<Term> terms;
private Map<String, List<Mark>> marks;
/** List to keep all dependencies */
private List<Dep> deps;
/** List to keep all chunks */
private List<Chunk> chunks;
/** List to keep all named entities */
private List<Entity> entities;
/** List to keep all properties */
private List<Feature> properties;
/** List to keep all categories */
private List<Feature> categories;
/** List to keep all coreferences */
private List<Coref> coreferences;
/** List to keep all timeExpressions */
private List<Timex3> timeExpressions;
/** List to keep all tLinks */
private List<TLink> tLinks;
/** List to keep all tLinks */
private List<CLink> cLinks;
/** List to keep all factualities */
private List<Factuality> factualities;
/** List to keep all linked entities */
private List<LinkedEntity> linkedEntities;
/** List to keep all opinions */
private List<Opinion> opinions;
/** List to keep all relations */
private List<Relation> relations;
/** List to keep all predicates */
private List<Predicate> predicates;
/** List to keep all trees */
private List<Tree> trees;
/** UNKNOWN annotation layers in plain DOM format */
private List<Element> unknownLayers;
/** Hash map for mapping word forms to terms. */
private HashMap<String, List<Term>> termsIndexedByWF;
private HashMap<String, Map<String, List<Mark>>> marksIndexedByWf;
private HashMap<String, List<Dep>> depsIndexedByTerm;
private HashMap<String, List<Chunk>> chunksIndexedByTerm;
private HashMap<String, List<Entity>> entitiesIndexedByTerm;
private HashMap<String, List<Coref>> corefsIndexedByTerm;
private HashMap<String, List<Timex3>> timeExsIndexedByWF;
private HashMap<String, List<Factuality>> factsIndexedByWF;
private HashMap<String, List<LinkedEntity>> linkedEntitiesIndexedByWF;
private HashMap<String, List<Feature>> propertiesIndexedByTerm;
private HashMap<String, List<Feature>> categoriesIndexedByTerm;
private HashMap<String, List<Opinion>> opinionsIndexedByTerm;
private HashMap<String, List<Relation>> relationsIndexedByRelational;
private HashMap<String, List<Predicate>> predicatesIndexedByTerm;
HashMap<Integer, List<WF>> textIndexedBySent;
HashMap<Integer, List<Term>> termsIndexedBySent;
HashMap<Integer, Map<String, List<Mark>>> marksIndexedBySent;
HashMap<Integer, List<Entity>> entitiesIndexedBySent;
HashMap<Integer, List<Dep>> depsIndexedBySent;
HashMap<Integer, List<Chunk>> chunksIndexedBySent;
HashMap<Integer, List<Coref>> corefsIndexedBySent;
HashMap<Integer, List<Timex3>> timeExsIndexedBySent;
HashMap<Integer, List<Factuality>> factsIndexedBySent;
HashMap<Integer, List<LinkedEntity>> linkedEntitiesIndexedBySent;
HashMap<Integer, List<Feature>> propertiesIndexedBySent;
HashMap<Integer, List<Feature>> categoriesIndexedBySent;
HashMap<Integer, List<Opinion>> opinionsIndexedBySent;
HashMap<Integer, List<Relation>> relationsIndexedBySent;
HashMap<Integer, List<Predicate>> predicatesIndexedBySent;
HashMap<Integer, List<Tree>> constituentsIndexedBySent;
HashMap<Integer, LinkedHashSet<Integer>> sentsIndexedByParagraphs;
/** This creates a new AnnotationContainer object */
AnnotationContainer() {
rawText = new String();
text = new ArrayList();
nextOffset = 0;
terms = new ArrayList();
marks = new HashMap();
deps = new ArrayList();
chunks = new ArrayList();
entities = new ArrayList();
properties = new ArrayList();
categories = new ArrayList();
coreferences = new ArrayList();
timeExpressions = new ArrayList();
tLinks = new ArrayList();
cLinks = new ArrayList();
factualities = new ArrayList();
linkedEntities = new ArrayList();
opinions = new ArrayList();
relations = new ArrayList();
predicates = new ArrayList();
trees = new ArrayList();
unknownLayers = new ArrayList<Element>();
termsIndexedByWF = new HashMap<String, List<Term>>();
marksIndexedByWf = new HashMap<String, Map<String, List<Mark>>>();
depsIndexedByTerm = new HashMap<String, List<Dep>>();
chunksIndexedByTerm = new HashMap<String, List<Chunk>>();
entitiesIndexedByTerm = new HashMap<String, List<Entity>>();
corefsIndexedByTerm = new HashMap<String, List<Coref>>();
timeExsIndexedByWF = new HashMap<String, List<Timex3>>();
linkedEntitiesIndexedByWF = new HashMap<String, List<LinkedEntity>>();
factsIndexedByWF = new HashMap<String, List<Factuality>>();
propertiesIndexedByTerm = new HashMap<String, List<Feature>>();
categoriesIndexedByTerm = new HashMap<String, List<Feature>>();
opinionsIndexedByTerm = new HashMap<String, List<Opinion>>();
relationsIndexedByRelational = new HashMap<String, List<Relation>>();
predicatesIndexedByTerm = new HashMap<String, List<Predicate>>();
textIndexedBySent = new HashMap<Integer, List<WF>>();
termsIndexedBySent = new HashMap<Integer, List<Term>>();
marksIndexedBySent = new HashMap<Integer, Map<String, List<Mark>>>();
entitiesIndexedBySent = new HashMap<Integer, List<Entity>>();
depsIndexedBySent = new HashMap<Integer, List<Dep>>();
chunksIndexedBySent = new HashMap<Integer, List<Chunk>>();
corefsIndexedBySent = new HashMap<Integer, List<Coref>>();
timeExsIndexedBySent = new HashMap<Integer, List<Timex3>>();
linkedEntitiesIndexedBySent = new HashMap<Integer, List<LinkedEntity>>();
factsIndexedBySent =new HashMap<Integer, List<Factuality>>();
propertiesIndexedBySent = new HashMap<Integer, List<Feature>>();
categoriesIndexedBySent = new HashMap<Integer, List<Feature>>();
opinionsIndexedBySent = new HashMap<Integer, List<Opinion>>();
relationsIndexedBySent = new HashMap<Integer, List<Relation>>();
predicatesIndexedBySent = new HashMap<Integer, List<Predicate>>();
constituentsIndexedBySent = new HashMap<Integer, List<Tree>>();
sentsIndexedByParagraphs = new HashMap<Integer, LinkedHashSet<Integer>>();
}
private <T> void indexBySent(T annotation, Integer sent, HashMap<Integer, List<T>> index) {
if (sent > 0) {
if (index.get(sent) == null) {
index.put(sent, new ArrayList<T>());
}
index.get(sent).add(annotation);
}
}
private void indexMarkBySent(Mark mark, String source, Integer sent) {
if (sent > 0) {
if (marksIndexedBySent.get(sent) == null) {
marksIndexedBySent.put(sent, new HashMap<String, List<Mark>>());
}
if (marksIndexedBySent.get(sent).get(source) == null) {
marksIndexedBySent.get(sent).put(source, new ArrayList<Mark>());
}
marksIndexedBySent.get(sent).get(source).add(mark);
}
}
void indexSentByPara(Integer sent, Integer para) {
if ((sent > 0) && (para > 0)) {
if (this.sentsIndexedByParagraphs.get(para) == null) {
this.sentsIndexedByParagraphs.put(para, new LinkedHashSet<Integer>());
}
this.sentsIndexedByParagraphs.get(para).add(sent);
}
}
public List<Integer> getSentsByParagraph(Integer para) {
return new ArrayList<Integer>(this.sentsIndexedByParagraphs.get(para));
}
<T> List<T> getLayerByPara(Integer para, HashMap<Integer, List<T>> index) {
List<T> layer = new ArrayList<T>();
for (Integer sent : this.getSentsByParagraph(para)) {
layer.addAll(index.get(sent));
}
return layer;
}
String getRawText() {
return rawText;
}
/** Returns all word forms. */
List<WF> getText() {
return text;
}
/** Returns all terms */
List<Term> getTerms() {
return terms;
}
List<String> getMarkSources() {
return new ArrayList<String>(marks.keySet());
}
List<Mark> getMarks(String source) {
return (marks.get(source) == null) ? new ArrayList<Mark>() : marks.get(source);
}
/** Returns all dependencies */
List<Dep> getDeps() {
return deps;
}
/** Returns all chunks */
List<Chunk> getChunks() {
return chunks;
}
/** Returns all named entities */
List<Entity> getEntities() {
return entities;
}
/** Returns all properties */
List<Feature> getProperties() {
return properties;
}
/** Returns all categories */
List<Feature> getCategories() {
return categories;
}
/** Returns all coreferences */
List<Coref> getCorefs() {
return coreferences;
}
/** Returns all timeExpressions */
List<Timex3> getTimeExs() {
return timeExpressions;
}
/** Returns all tlinks */
List<TLink> getTLinks() {
return this.tLinks;
}
/** Returns all clinks */
List<CLink> getCLinks() {
return this.cLinks;
}
List<Factuality> getFactualities() {
return factualities;
}
List<LinkedEntity> getLinkedEntities() {
return linkedEntities;
}
/** Returns all opinions */
List<Opinion> getOpinions() {
return opinions;
}
/** Returns all relations */
List<Relation> getRelations() {
return relations;
}
/** Returns all predicates */
List<Predicate> getPredicates() {
return predicates;
}
/** Returns all trees */
List<Tree> getConstituents() {
return trees;
}
/** Returns all unknown layers as a DOM Element list */
List<Element> getUnknownLayers() {
return unknownLayers;
}
void setRawText(String str) {
rawText = str;
}
/** Adds a word form to the container */
void add(WF wf) {
text.add(wf);
//nextOffset += wf.getLength() + 1;
this.indexBySent(wf, wf.getSent(), this.textIndexedBySent);
}
private <T> void indexAnnotation(T annotation, String hashId, HashMap<String, List<T>> index) {
if (index.get(hashId) == null) {
index.put(hashId, new ArrayList<T>());
}
index.get(hashId).add(annotation);
}
private void indexMarkByWf(Mark mark, String source, String tid) {
if (marksIndexedByWf.get(tid) == null) {
marksIndexedByWf.put(tid, new HashMap<String, List<Mark>>());
}
if (marksIndexedByWf.get(tid).get(source) == null) {
marksIndexedByWf.get(tid).put(source, new ArrayList<Mark>());
}
marksIndexedByWf.get(tid).get(source).add(mark);
}
/** Adds a term to the container */
void add(Term term) {
this.add(term, this.terms.size());
}
void add(Term term, int index) {
terms.add(index, term);
for (WF wf : term.getWFs()) {
indexAnnotation(term, wf.getId(), termsIndexedByWF);
}
if (!term.isComponent()) {
this.indexBySent(term, term.getSent(), this.termsIndexedBySent);
}
}
void remove(Term term) {
this.terms.remove(term);
}
void add(Mark mark, String source) {
List<Mark> sourceMarks = marks.get(source);
if (sourceMarks == null) {
sourceMarks = new ArrayList<Mark>();
}
sourceMarks.add(mark);
marks.put(source, sourceMarks);
for (WF wf : mark.getSpan().getTargets()) {
indexMarkByWf(mark, source, wf.getId());
}
this.indexMarkBySent(mark, source, mark.getSpan().getTargets().get(0).getSent());
}
/** Adds a dependency to the container */
void add(Dep dep) {
deps.add(dep);
/* Index by 'from' and 'to' terms */
if (dep.getFrom() != null) {
String tId = dep.getFrom().getId();
indexAnnotation(dep, tId, depsIndexedByTerm);
}
if (dep.getTo() != null) {
String tId = dep.getTo().getId();
indexAnnotation(dep, tId, depsIndexedByTerm);
}
this.indexBySent(dep, dep.getFrom().getSent(), this.depsIndexedBySent);
}
/** Adds a chunk to the container */
void add(Chunk chunk) {
chunks.add(chunk);
/* Index by terms */
for (Term term : chunk.getTerms()) {
indexAnnotation(chunk, term.getId(), chunksIndexedByTerm);
}
this.indexBySent(chunk, chunk.getSpan().getTargets().get(0).getSent(), this.chunksIndexedBySent);
}
/** Adds a named entity to the container */
void add(Entity entity) {
entities.add(entity);
/* Index by terms */
for (Term term : entity.getTerms()) {
indexAnnotation(entity, term.getId(), entitiesIndexedByTerm);
}
this.indexBySent(entity, entity.getSpans().get(0).getTargets().get(0).getSent(), this.entitiesIndexedBySent);
}
/** Adds a feature to the container. It checks if it is a property or a category. */
void add(Feature feature) {
if (feature.isAProperty()) {
properties.add(feature);
/* Index by terms */
for (Term term : feature.getTerms()) {
indexAnnotation(feature, term.getId(), propertiesIndexedByTerm);
}
//this.indexBySent(feature, feature.getSpans().get(0).getTargets().get(0).getSent(), this.propertiesIndexedBySent);
}
else {
categories.add(feature);
/* Index by terms */
for (Term term : feature.getTerms()) {
indexAnnotation(feature, term.getId(), categoriesIndexedByTerm);
}
//this.indexBySent(feature, feature.getSpans().get(0).getTargets().get(0).getSent(), this.categoriesIndexedBySent);
}
}
/** Adds a coreference to the container */
void add(Coref coref) {
coreferences.add(coref);
/* Index by terms */
for (Term term : coref.getTerms()) {
indexAnnotation(coref, term.getId(), corefsIndexedByTerm);
}
//this.indexBySent(coref, coref.getSpans().get(0).getTargets().get(0).getSent(), this.corefsIndexedBySent);
}
/** Adds a timeExpression to the container */
void add(Timex3 timex3) {
timeExpressions.add(timex3);
/* Index by terms */
if(timex3.hasSpan()){
for (WF wf : timex3.getSpan().getTargets()) {
indexAnnotation(timex3, wf.getId(), timeExsIndexedByWF);
}
}
}
/** Adds a tlink to the container */
void add(TLink tLink) {
tLinks.add(tLink);
/* Index by from/to (???) */
}
/** Adds a clink to the container */
void add(CLink cLink) {
cLinks.add(cLink);
/* Index by from/to (???) */
}
/** Adds a factuality to the container */
void add(Factuality factuality) {
factualities.add(factuality);
/* Index by terms */
indexAnnotation(factuality, factuality.getWF().getId(), factsIndexedByWF);
}
/** Adds a linked entity to the container */
void add(LinkedEntity linkedEntity) {
linkedEntities.add(linkedEntity);
/* Index by terms */
if(linkedEntity.getWFs() != null){
for (WF wf : linkedEntity.getWFs().getTargets()) {
indexAnnotation(linkedEntity, wf.getId(), linkedEntitiesIndexedByWF);
}
}
}
/** Adds an opinion to the container */
void add(Opinion opinion) {
opinions.add(opinion);
/* Index by terms */
/* Ezin hemen indexatu, terminoak oraindik ez baitira gehitu!!!
LinkedHashSet<Term> terms = new LinkedHashSet<Term>();
terms.addAll(opinion.getOpinionHolder().getTerms());
terms.addAll(opinion.getOpinionTarget().getTerms());
terms.addAll(opinion.getOpinionExpression().getTerms());
for (Term term : terms) {
indexAnnotation(opinion, term.getId(), opinionsIndexedByTerm);
}
*/
}
/** Adds a relation to the container */
void add(Relation relation) {
relations.add(relation);
/* Index by 'from' and 'to' terms */
if (relation.getFrom() != null) {
String rId = relation.getFrom().getId();
indexAnnotation(relation, rId, relationsIndexedByRelational);
}
if (relation.getTo() != null) {
String rId = relation.getTo().getId();
indexAnnotation(relation, rId, relationsIndexedByRelational);
}
}
/** Adds a predicate to the container */
void add(Predicate predicate) {
predicates.add(predicate);
/* Index by terms */
for (Term term : predicate.getTerms()) {
indexAnnotation(predicate, term.getId(), predicatesIndexedByTerm);
}
this.indexBySent(predicate, predicate.getSpan().getTargets().get(0).getSent(), this.predicatesIndexedBySent);
}
/** Adds a tree to the container */
void add(Tree tree) {
trees.add(tree);
TreeNode currentNode = tree.getRoot();
while (!currentNode.isTerminal()) {
currentNode = ((NonTerminal) currentNode).getChildren().get(0);
}
Integer sent = ((Terminal) currentNode).getSpan().getTargets().get(0).getSent();
this.indexBySent(tree, sent, this.constituentsIndexedBySent);
}
/** Adds an unknown layer to the container in DOM format */
void add(Element layer) {
unknownLayers.add(layer);
}
/** Index a Term by its sentence number */
void indexTermBySent(Term term, Integer sent) {
if (sent == -1) {
throw new IllegalStateException("You can't call indexTermBySent not having defined the sentence for its WFs");
}
List<Term> sentTerms = termsIndexedBySent.get(sent);
if (sentTerms == null) {
sentTerms = new ArrayList<Term>();
termsIndexedBySent.put(sent, sentTerms);
}
sentTerms.add(term);
}
/** Returns all tokens classified by sentences */
List<List<WF>> getSentences() {
List<List<WF>> sentences = new ArrayList<List<WF>>();
Set<Integer> sentNumsSet = this.textIndexedBySent.keySet();
List<Integer> sentNumsList = new ArrayList<Integer>(sentNumsSet);
Collections.sort(sentNumsList);
for (int i : sentNumsList) {
List<WF> wfs = this.textIndexedBySent.get(i);
sentences.add(wfs);
}
return sentences;
}
Integer termPosition(Term term) {
return this.terms.indexOf(term);
}
/** Returns WFs from a sentence */
List<WF> getSentenceWFs(int sent) {
return this.textIndexedBySent.get(sent);
}
/** Returns terms from a sentence */
List<Term> getSentenceTerms(int sent) {
return this.termsIndexedBySent.get(sent);
}
Term getTermByWF(WF wf) {
List<Term> terms = this.termsIndexedByWF.get(wf.getId());
if (terms == null) {
return null;
}
return terms.get(0);
}
List<Term> getTermsByWF(WF wf) {
List<Term> terms = this.termsIndexedByWF.get(wf.getId());
return (terms == null) ? new ArrayList<Term>() : terms;
}
/** Returns a list of terms containing the word forms given on argument.
* @param wfIds a list of word form IDs whose terms will be found.
* @return a list of terms containing the given word forms.
*/
List<Term> getTermsByWFs(List<WF> wfs) {
LinkedHashSet<Term> terms = new LinkedHashSet<Term>();
for (WF wf : wfs) {
terms.addAll(getTermsByWF(wf));
}
return new ArrayList<Term>(terms);
}
List<Mark> getMarksByWf(WF wf, String source) {
Map<String, List<Mark>> marks = this.marksIndexedByWf.get(wf.getId());
if (marks == null) {
return new ArrayList<Mark>();
}
List<Mark> sourceMarks = marks.get(source);
return (sourceMarks == null) ? new ArrayList<Mark>() : sourceMarks;
}
List<Dep> getDepsByTerm(Term term) {
List<Dep> deps = this.depsIndexedByTerm.get(term.getId());
return (deps == null) ? new ArrayList<Dep>() : deps;
}
List<Chunk> getChunksByTerm(Term term) {
List<Chunk> chunks = this.chunksIndexedByTerm.get(term.getId());
return (chunks == null) ? new ArrayList<Chunk>() : chunks;
}
List<Entity> getEntitiesByTerm(Term term) {
List<Entity> entities = this.entitiesIndexedByTerm.get(term.getId());
return (entities == null) ? new ArrayList<Entity>() : entities;
}
List<Coref> getCorefsByTerm(Term term) {
List<Coref> corefs = this.corefsIndexedByTerm.get(term.getId());
return (corefs == null) ? new ArrayList<Coref>() : corefs;
}
List<Timex3> getTimeExsByWF(WF wf) {
List<Timex3> timeExs = this.timeExsIndexedByWF.get(wf.getId());
return (timeExs == null) ? new ArrayList<Timex3>() : timeExs;
}
List<Feature> getPropertiesByTerm(Term term) {
List<Feature> properties = this.propertiesIndexedByTerm.get(term.getId());
return (properties == null) ? new ArrayList<Feature>() : properties;
}
List<Feature> getCategoriesByTerm(Term term) {
List<Feature> categories = this.categoriesIndexedByTerm.get(term.getId());
return (categories == null) ? new ArrayList<Feature>() : categories;
}
List<Opinion> getOpinionsByTerm(Term term) {
List<Opinion> opinions = this.opinionsIndexedByTerm.get(term.getId());
return (opinions == null) ? new ArrayList<Opinion>() : opinions;
}
List<Relation> getRelationsByRelational(Relational relational) {
List<Relation> relations = this.relationsIndexedByRelational.get(relational.getId());
return (relations == null) ? new ArrayList<Relation>() : relations;
}
List<Predicate> getPredicatesByTerm(Term term) {
List<Predicate> predicates = this.predicatesIndexedByTerm.get(term.getId());
return (predicates == null) ? new ArrayList<Predicate>() : predicates;
}
List<Dep> getDepsByTerms(List<Term> terms) {
LinkedHashSet<Dep> deps = new LinkedHashSet<Dep>();
for (Term term : terms) {
deps.addAll(getDepsByTerm(term));
}
return new ArrayList<Dep>(deps);
}
List<Chunk> getChunksByTerms(List<Term> terms) {
LinkedHashSet<Chunk> chunks = new LinkedHashSet<Chunk>();
for (Term term : terms) {
chunks.addAll(getChunksByTerm(term));
}
return new ArrayList<Chunk>(chunks);
}
List<Entity> getEntitiesByTerms(List<Term> terms) {
LinkedHashSet<Entity> entities = new LinkedHashSet<Entity>();
for (Term term : terms) {
entities.addAll(getEntitiesByTerm(term));
}
return new ArrayList<Entity>(entities);
}
List<Coref> getCorefsByTerms(List<Term> terms) {
LinkedHashSet<Coref> corefs = new LinkedHashSet<Coref>();
for (Term term : terms) {
corefs.addAll(getCorefsByTerm(term));
}
return new ArrayList<Coref>(corefs);
}
List<Timex3> getTimeExsByWFs(List<WF> wfs) {
LinkedHashSet<Timex3> timeExs = new LinkedHashSet<Timex3>();
for (WF wf : wfs) {
timeExs.addAll(getTimeExsByWF(wf));
}
return new ArrayList<Timex3>(timeExs);
}
List<Feature> getPropertiesByTerms(List<Term> terms) {
LinkedHashSet<Feature> properties = new LinkedHashSet<Feature>();
for (Term term : terms) {
properties.addAll(getPropertiesByTerm(term));
}
return new ArrayList<Feature>(properties);
}
List<Feature> getCategoriesByTerms(List<Term> terms) {
LinkedHashSet<Feature> categories = new LinkedHashSet<Feature>();
for (Term term : terms) {
categories.addAll(getCategoriesByTerm(term));
}
return new ArrayList<Feature>(categories);
}
List<Opinion> getOpinionsByTerms(List<Term> terms) {
LinkedHashSet<Opinion> opinions = new LinkedHashSet<Opinion>();
for (Term term : terms) {
opinions.addAll(getOpinionsByTerm(term));
}
return new ArrayList<Opinion>(opinions);
}
List<Relation> getRelationsByRelationals(List<Relational> relationals) {
LinkedHashSet<Relation> relations = new LinkedHashSet<Relation>();
for (Relational relational : relationals) {
relations.addAll(getRelationsByRelational(relational));
}
return new ArrayList<Relation>(relations);
}
List<Predicate> getPredicatesByTerms(List<Term> terms) {
LinkedHashSet<Predicate> predicates = new LinkedHashSet<Predicate>();
for (Term term : terms) {
predicates.addAll(getPredicatesByTerm(term));
}
return new ArrayList<Predicate>(predicates);
}
/** Returns next WF's offset. */
int getNextOffset() {
return nextOffset;
}
/** Deprecated. Returns a list of terms containing the word forms given on argument.
* @param wfIds a list of word form IDs whose terms will be found.
* @return a list of terms containing the given word forms.
*/
List<Term> getTermsByWFIds(List<String> wfIds) {
LinkedHashSet<Term> terms = new LinkedHashSet<Term>();
for (String wfId : wfIds) {
List<Term> newTerms = this.termsIndexedByWF.get(wfId);
if (newTerms != null) {
terms.addAll(newTerms);
}
}
return new ArrayList<Term>(terms);
}
void removeLayer(KAFDocument.Layer layer) {
switch (layer) {
case text:
this.text.clear();
break;
case terms:
this.terms.clear();
break;
case deps:
this.deps.clear();
break;
case chunks:
this.chunks.clear();
break;
case entities:
this.entities.clear();
break;
case properties:
this.properties.clear();
break;
case categories:
this.categories.clear();
break;
case coreferences:
this.coreferences.clear();
break;
case opinions:
this.opinions.clear();
break;
case relations:
this.relations.clear();
break;
case srl:
this.predicates.clear();
break;
case constituency:
this.trees.clear();
break;
default:
throw new IllegalArgumentException("Wrong layer");
}
}
} |
package javax.time.period;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.time.CalendricalException;
import javax.time.Duration;
import javax.time.calendar.ISOChronology;
import javax.time.calendar.PeriodUnit;
/**
* A period of time measured using a number of different units,
* such as '3 Months, 4 Days and 7 Hours'.
* <p>
* {@code PeriodFields} is an immutable period that stores an amount of human-scale
* time for a number of units. For example, humans typically measure periods of time
* in units of years, months, days, hours, minutes and seconds. These concepts are
* defined by instances of {@link PeriodUnit} in the chronology classes. This class
* allows an amount to be specified for a number of the units, such as '3 Days and 65 Seconds'.
* <p>
* Basic mathematical operations are provided - plus(), minus(), multipliedBy(),
* dividedBy() and negated(), all of which return a new instance
* <p>
* A value of zero can also be stored for any unit. This means that a
* period of zero hours is not equal to a period of zero minutes.
* However, an empty instance constant exists to represent zero irrespective of unit.
* The {@link #withZeroesRemoved()} method removes zero values.
* <p>
* {@code PeriodFields} can store units of any kind which makes it usable with
* any calendar system.
* <p>
* PeriodFields is immutable and thread-safe.
*
* @author Stephen Colebourne
*/
public final class PeriodFields
implements PeriodProvider, Iterable<PeriodField>, Serializable {
/**
* A constant for a period of zero.
* This constant is independent of any unit.
*/
public static final PeriodFields ZERO = new PeriodFields(new TreeMap<PeriodUnit, PeriodField>());
/**
* The serialization version.
*/
private static final long serialVersionUID = 1L;
/**
* The map of periods.
*/
private final TreeMap<PeriodUnit, PeriodField> unitFieldMap;
/**
* Obtains a {@code PeriodFields} from an amount and unit.
* <p>
* The parameters represent the two parts of a phrase like '6 Days'.
*
* @param amount the amount of create with, may be negative
* @param unit the period unit, not null
* @return the {@code PeriodFields} instance, never null
*/
public static PeriodFields of(long amount, PeriodUnit unit) {
checkNotNull(unit, "PeriodUnit must not be null");
TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
internalMap.put(unit, PeriodField.of(amount, unit));
return create(internalMap);
}
/**
* Obtains a {@code PeriodFields} from a single-unit period.
*
* @param period the single-unit period, not null
* @return the {@code PeriodFields} instance, never null
*/
public static PeriodFields of(PeriodField period) {
checkNotNull(period, "PeriodField must not be null");
TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
internalMap.put(period.getUnit(), period);
return create(internalMap);
}
public static PeriodFields of(PeriodField... periods) {
checkNotNull(periods, "PeriodField array must not be null");
TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
for (PeriodField period : periods) {
checkNotNull(period, "PeriodField array must not contain null");
if (internalMap.put(period.getUnit(), period) != null) {
throw new IllegalArgumentException("PeriodField array contains the same unit twice");
}
}
return create(internalMap);
}
// public static PeriodFields of(Iterable<PeriodField> periods) {
// checkNotNull(periods, "Iterable must not be null");
// TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
// for (PeriodField period : periods) {
// checkNotNull(period, "Iterable must not contain null");
// if (internalMap.put(period.getUnit(), period) != null) {
// return create(internalMap);
/**
* Obtains a {@code PeriodFields} from a set of unit-amount pairs.
* <p>
* The amount to store for each unit is obtained by calling {@link Number#longValue()}.
* This will lose any decimal places for instances of {@code Double} and {@code Float}.
* It may also silently lose precision for instances of {@code BigInteger} or {@code BigDecimal}.
*
* @param unitAmountMap a map of periods that will be used to create this
* period, not updated by this method, not null, contains no nulls
* @return the {@code PeriodFields} instance, never null
* @throws NullPointerException if the map is null or contains nulls
*/
public static PeriodFields of(Map<PeriodUnit, ? extends Number> unitAmountMap) {
checkNotNull(unitAmountMap, "Map must not be null");
// don't use contains() as tree map and others can throw NPE
TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
for (Entry<PeriodUnit, ? extends Number> entry : unitAmountMap.entrySet()) {
PeriodUnit unit = entry.getKey();
Number amount = entry.getValue();
checkNotNull(unit, "Null keys are not permitted in unit-amount map");
checkNotNull(amount, "Null amounts are not permitted in unit-amount map");
internalMap.put(unit, PeriodField.of(amount.longValue(), unit));
}
return create(internalMap);
}
/**
* Obtains a {@code PeriodFields} from a {@code PeriodProvider}.
* <p>
* This factory returns an instance with all the unit-amount pairs from the provider.
*
* @param periodProvider the provider to create from, not null
* @return the {@code PeriodFields} instance, never null
* @throws NullPointerException if the period provider is null or returns null
*/
public static PeriodFields from(PeriodProvider periodProvider) {
checkNotNull(periodProvider, "PeriodProvider must not be null");
PeriodFields result = periodProvider.toPeriodFields();
checkNotNull(result, "PeriodProvider implementation must not return null");
return result;
}
/**
* Obtains a {@code PeriodFields} by totalling the amounts in a list of
* {@code PeriodProvider} instances.
* <p>
* This method returns a period with all the unit-amount pairs from the providers
* totalled. Thus a period of '2 Months and 5 Days' combined with a period of
* '7 Days and 21 Hours' will yield a result of '2 Months, 12 Days and 21 Hours'.
*
* @param periodProviders the providers to total, not null
* @return the {@code PeriodFields} instance, never null
* @throws NullPointerException if any period provider is null or returns null
*/
public static PeriodFields total(PeriodProvider... periodProviders) {
checkNotNull(periodProviders, "PeriodProvider[] must not be null");
if (periodProviders.length == 1) {
return from(periodProviders[0]);
}
TreeMap<PeriodUnit, PeriodField> map = createMap();
for (PeriodProvider periodProvider : periodProviders) {
PeriodFields periods = from(periodProvider);
for (PeriodField period : periods.unitFieldMap.values()) {
PeriodField old = map.get(period.getUnit());
period = (old != null ? old.plus(period) : period);
map.put(period.getUnit(), period);
}
}
return create(map);
}
/**
* Obtains a {@code PeriodFields} from a {@code Duration} based on the standard
* durations of seconds and nanoseconds.
* <p>
* The conversion will create an instance with two units - the {@code ISOChronology}
* seconds and nanoseconds units. This matches the {@link #toDuration()} method.
* <p>
* This conversion can only be used if the duration is being used in a manner
* compatible with the {@code ISOChronology} definitions of seconds and nanoseconds.
* This will be the case for most applications - care only needs to be taken if
* using explicit time-scales.
*
* @param duration the duration to create from, not null
* @return the {@code PeriodFields} instance, never null
*/
public static PeriodFields from(Duration duration) {
checkNotNull(duration, "Duration must not be null");
TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
internalMap.put(ISOChronology.periodSeconds(), PeriodField.of(duration.getSeconds(), ISOChronology.periodSeconds()));
internalMap.put(ISOChronology.periodNanos(), PeriodField.of(duration.getNanosInSecond(), ISOChronology.periodNanos()));
return create(internalMap);
}
/**
* Creates a new empty map.
*
* @return ordered representation of internal map
*/
private static TreeMap<PeriodUnit, PeriodField> createMap() {
return new TreeMap<PeriodUnit, PeriodField>(Collections.reverseOrder());
}
/**
* Internal factory to create an instance using a pre-built map.
* The map must not be used by the calling code after calling the constructor.
*
* @param periodMap the unit-amount map, not null, assigned not cloned
* @return the created period, never null
*/
static PeriodFields create(TreeMap<PeriodUnit, PeriodField> periodMap) {
if (periodMap.isEmpty()) {
return ZERO;
}
return new PeriodFields(periodMap);
}
/**
* Validates that the input value is not null.
*
* @param object the object to check
* @param errorMessage the error to throw
* @throws NullPointerException if the object is null
*/
static void checkNotNull(Object object, String errorMessage) {
if (object == null) {
throw new NullPointerException(errorMessage);
}
}
/**
* Constructs an instance using a pre-built map.
* The map must not be used by the calling code after calling the constructor.
*
* @param periodMap the map of periods to represent, not null and safe to assign
*/
private PeriodFields(TreeMap<PeriodUnit, PeriodField> periodMap) {
this.unitFieldMap = periodMap;
}
/**
* Resolves singletons.
*
* @return the resolved instance
*/
private Object readResolve() {
if (unitFieldMap.size() == 0) {
return ZERO;
}
return this;
}
/**
* Checks if this period is zero-length.
* <p>
* This checks whether all the amounts in this period are zero.
*
* @return true if this period is zero-length
*/
public boolean isZero() {
for (PeriodField field : unitFieldMap.values()) {
if (field.isZero() == false) {
return false;
}
}
return true;
}
/**
* Checks if this period is fully positive, including zero.
* <p>
* This checks whether all the amounts in this period are positive,
* defined as greater than or equal to zero.
*
* @return true if this period is fully positive
*/
public boolean isPositive() {
for (PeriodField field : unitFieldMap.values()) {
if (field.isNegative()) {
return false;
}
}
return true;
}
/**
* Returns the size of the set of units in this period.
* <p>
* This returns the number of different units that are stored.
*
* @return number of unit-amount pairs
*/
public int size() {
return unitFieldMap.size();
}
/**
* Iterates through all the single-unit periods in this period.
* <p>
* This method fulfills the {@link Iterable} interface and allows looping
* around the contained single-unit periods using the for-each loop.
*
* @return an iterator over the single-unit periods in this period, never null
*/
public Iterator<PeriodField> iterator() {
return unitFieldMap.values().iterator();
}
/**
* Checks whether this period contains an amount for the unit.
*
* @param unit the unit to query, null returns false
* @return true if the map contains an amount for the unit
*/
public boolean contains(PeriodUnit unit) {
return unitFieldMap.containsKey(unit);
}
/**
* Gets the period for the specified unit.
* <p>
* This method allows the period to be queried by unit, like a map.
* If the unit is not found then {@code null} is returned.
*
* @param unit the unit to query, not null
* @return the period, null if no period stored for the unit
*/
public PeriodField get(PeriodUnit unit) {
checkNotNull(unit, "PeriodRule must not be null");
return unitFieldMap.get(unit);
}
/**
* Gets the amount of this period for the specified unit.
* <p>
* This method allows the amount to be queried by unit, like a map.
* If the unit is not found then zero is returned.
*
* @param unit the unit to query, not null
* @return the period amount, 0 if no period stored for the unit
* @throws CalendricalException if there is no amount for the unit
*/
public long getAmount(PeriodUnit unit) {
PeriodField field = get(unit);
if (field == null) {
return 0;
}
return field.getAmount();
}
/**
* Gets the amount of this period for the specified unit converted
* to an {@code int}.
* <p>
* This method allows the amount to be queried by unit, like a map.
* If the unit is not found then zero is returned.
*
* @param unit the unit to query, not null
* @return the period amount, 0 if no period stored for the unit
* @throws CalendricalException if there is no amount for the unit
* @throws ArithmeticException if the amount is too large to be returned in an int
*/
public int getAmountInt(PeriodUnit unit) {
PeriodField field = get(unit);
if (field == null) {
return 0;
}
return field.getAmountInt();
}
// /**
// * Gets the amount of the period for the specified unit, returning
// * the default value if this period does have an amount for the unit.
// *
// * @param unit the unit to query, not null
// * @param defaultValue the default value to return if the unit is not present
// * @return the period amount
// * @throws NullPointerException if the period unit is null
// */
// public long get(PeriodRule unit, long defaultValue) {
// checkNotNull(unit, "PeriodRule must not be null");
// Long amount = unitAmountMap.get(unit);
// return amount == null ? defaultValue : amount;
// /**
// * Gets the amount of the period for the specified unit, returning
// * the default value if this period does have an amount for the unit.
// * <p>
// * The amount is safely converted to an {@code int}.
// *
// * @param unit the unit to query, not null
// * @param defaultValue the default value to return if the unit is not present
// * @return the period amount
// * @throws NullPointerException if the period unit is null
// * @throws ArithmeticException if the amount is too large to be returned in an int
// */
// public int getInt(PeriodRule unit, int defaultValue) {
// return MathUtils.safeToInt(get(unit, defaultValue));
/**
* Returns a copy of this period with all zero amounts removed.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @return a new period with no zero amounts, never null
*/
public PeriodFields withZeroesRemoved() {
if (isZero()) {
return ZERO;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
for (Iterator<PeriodField> it = copy.values().iterator(); it.hasNext(); ) {
if (it.next().isZero()) {
it.remove();
}
}
return create(copy);
}
/**
* Returns a copy of this period with the specified amount for the unit.
* <p>
* If this period already contains an amount for the unit then the amount
* is replaced. Otherwise, the unit-amount pair is added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amount the amount to store in terms of the unit, may be negative
* @param unit the unit to store not null
* @return a new period with the specified amount and unit, never null
*/
public PeriodFields with(long amount, PeriodUnit unit) {
PeriodField existing = get(unit);
if (existing != null && existing.getAmount() == amount) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
copy.put(unit, PeriodField.of(amount, unit));
return create(copy);
}
// /**
// * Returns a copy of this period with the amounts from the specified map added.
// * <p>
// * If this instance already has an amount for any unit then the value is replaced.
// * Otherwise the value is added.
// * <p>
// * This instance is immutable and unaffected by this method call.
// *
// * @param unitAmountMap the new map of fields, not null
// * @return a new updated period instance, never null
// * @throws NullPointerException if the map contains null keys or values
// */
// public PeriodFields with(Map<PeriodRule, Long> unitAmountMap) {
// checkNotNull(unitAmountMap, "The field-value map must not be null");
// if (unitAmountMap.isEmpty()) {
// return this;
// // don't use contains() as tree map and others can throw NPE
// TreeMap<PeriodRule, Long> clonedMap = clonedMap();
// for (Entry<PeriodRule, Long> entry : unitAmountMap.entrySet()) {
// PeriodRule unit = entry.getKey();
// Long value = entry.getValue();
// checkNotNull(unit, "Null keys are not permitted in field-value map");
// checkNotNull(value, "Null values are not permitted in field-value map");
// clonedMap.put(unit, value);
// return new PeriodFields(clonedMap);
/**
* Returns a copy of this period with the specified values altered.
* <p>
* This method operates on each unit in the input in turn.
* If this period already contains an amount for the unit then the amount
* is replaced. Otherwise, the unit-amount pair is added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param period the period to store, not null
* @return a new period with the specified period set, never null
*/
public PeriodFields with(PeriodFields period) {
if (this == ZERO) {
return period;
}
if (period == ZERO) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
copy.putAll(period.unitFieldMap);
return create(copy);
}
/**
* Returns a copy of this period with the specified unit removed.
* <p>
* If this period already contains an amount for the unit then the amount
* is removed. Otherwise, no action occurs.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param unit the unit to remove, not null
* @return a new period with the unit removed, never null
*/
public PeriodFields withRuleRemoved(PeriodUnit unit) {
checkNotNull(unit, "PeriodRule must not be null");
if (unitFieldMap.containsKey(unit) == false) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
copy.remove(unit);
return create(copy);
}
/**
* Returns a copy of this period with the specified period added.
* <p>
* The returned period will take each unit in the provider and add the value
* to the amount already stored in this period, returning a new one.
* If this period does not contain an amount for the unit then the unit and
* amount are simply returned directly in the result. The result will have
* the union of the units in this instance and the units in the specified instance.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param periodProvider the period to add, not null
* @return a new period with the specified period added, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields plus(PeriodProvider periodProvider) {
checkNotNull(periodProvider, "PeriodProvider must not be null");
if (this == ZERO && periodProvider instanceof PeriodFields) {
return (PeriodFields) periodProvider;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
PeriodFields periods = from(periodProvider);
for (PeriodField period : periods.unitFieldMap.values()) {
PeriodField old = copy.get(period.getUnit());
period = (old != null ? old.plus(period) : period);
copy.put(period.getUnit(), period);
}
return create(copy);
}
/**
* Returns a copy of this period with the specified period added.
* <p>
* The result will contain the units and amounts from this period plus the
* specified unit and amount.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amount the amount to add, measured in the specified unit, may be negative
* @param unit the unit defining the amount, not null
* @return a new period with the specified unit and amount added, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields plus(long amount, PeriodUnit unit) {
checkNotNull(unit, "PeiodRule must not be null");
if (amount == 0) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
PeriodField old = copy.get(unit);
PeriodField field = (old != null ? old.plus(amount) : PeriodField.of(amount, unit));
copy.put(unit, field);
return create(copy);
}
/**
* Returns a copy of this period with the specified period subtracted.
* <p>
* The returned period will take each unit in the provider and subtract the
* value from the amount already stored in this period, returning a new one.
* If this period does not contain an amount for the unit then the unit and
* amount are simply returned directly in the result. The result will have
* the union of the units in this instance and the units in the specified instance.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param period the period to subtract, not null
* @return a new period with the specified period subtracted, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields minus(PeriodProvider periodProvider) {
checkNotNull(periodProvider, "PeriodProvider must not be null");
if (this == ZERO && periodProvider instanceof PeriodFields) {
return (PeriodFields) periodProvider;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
PeriodFields periods = from(periodProvider);
for (PeriodField period : periods.unitFieldMap.values()) {
PeriodField old = copy.get(period.getUnit());
period = (old != null ? old.minus(period) : period.negated());
copy.put(period.getUnit(), period);
}
return create(copy);
}
/**
* Returns a copy of this period with the specified period subtracted.
* <p>
* The result will contain the units and amounts from this period minus the
* specified unit and amount.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amount the amount to subtract, measured in the specified unit, may be negative
* @param unit the unit defining the amount, not null
* @return a new period with the specified amount and unit subtracted, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields minus(long amount, PeriodUnit unit) {
checkNotNull(unit, "PeiodRule must not be null");
if (amount == 0) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = clonedMap();
PeriodField old = copy.get(unit);
copy.put(unit, old != null ? old.minus(amount) : PeriodField.of(amount, unit).negated());
return create(copy);
}
/**
* Returns a new instance with each amount in this period multiplied
* by the specified scalar.
*
* @param scalar the scalar to multiply by, not null
* @return a new period multiplied by the scalar, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields multipliedBy(long scalar) {
if (scalar == 1 || isZero()) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = createMap();
for (PeriodField field : this) {
copy.put(field.getUnit(), field.multipliedBy(scalar));
}
return create(copy);
}
/**
* Returns a new instance with each amount in this period divided
* by the specified value.
*
* @param divisor the value to divide by, not null, not zero
* @return a new period instance with the amount divided by the divisor, never null
* @throws ArithmeticException if dividing by zero
*/
public PeriodFields dividedBy(long divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
if (divisor == 1 || isZero()) {
return this;
}
TreeMap<PeriodUnit, PeriodField> copy = createMap();
for (PeriodField field : this) {
copy.put(field.getUnit(), field.dividedBy(divisor));
}
return create(copy);
}
/**
* Returns a new instance with each amount in this period negated.
*
* @return a new period with the amount negated, never null
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields negated() {
return multipliedBy(-1);
}
/**
* Clone the internal data storage map.
*
* @return the cloned map, never null
*/
@SuppressWarnings("unchecked")
private TreeMap<PeriodUnit, PeriodField> clonedMap() {
return (TreeMap) unitFieldMap.clone();
}
/**
* Converts this period to one containing only the units specified.
* <p>
* This will attempt to convert this period to each of the specified units
* in turn. It is recommended to specify the units from largest to smallest.
* If this period is already one of the specified units, then {@code this}
* is returned.
* <p>
* For example, '3 Hours' can normally be converted to both minutes and seconds.
* If the units array contains both 'Minutes' and 'Seconds', then the result will
* be measured in whichever is first in the array.
* <p>
* A total of a compound period can also be obtained.
* For example, '3 Hours, 34 Minutes' can be totalled to minutes by passing the
* single unit of minutes, resulting in '214 Minutes'.
*
* @param units the required unit array, not altered, not null
* @return the converted period, never null
* @throws CalendricalException if the period cannot be converted to any of the units
* @throws ArithmeticException if the calculation overflows
*/
public PeriodFields toEquivalentPeriod(PeriodUnit... units) {
TreeMap<PeriodUnit, PeriodField> map = createMap();
for (PeriodField period : unitFieldMap.values()) {
period = period.toEquivalentPeriod(units);
PeriodField old = map.get(period.getUnit());
period = (old != null ? old.plus(period) : period);
map.put(period.getUnit(), period);
}
return (map.equals(unitFieldMap) ? this : create(map));
}
/**
* Converts this object to a map of units to amounts.
* <p>
* The returned map will never be null, however it may be empty.
* It is sorted by the unit, returning the largest first.
* It is independent of this object - changes will not be reflected back.
*
* @return the independent, modifiable map of periods, never null, never contains null
*/
public SortedMap<PeriodUnit, Long> toRuleAmountMap() {
SortedMap<PeriodUnit, Long> map = new TreeMap<PeriodUnit, Long>(Collections.reverseOrder());
for (PeriodField field : this) {
map.put(field.getUnit(), field.getAmount());
}
return map;
}
/**
* Converts this period to an estimated duration.
* <p>
* Each {@link PeriodUnit} contains an estimated duration for that unit.
* This method uses that estimate to calculate a total estimated duration for
* this period.
*
* @return the estimated duration of this period, never null
* @throws ArithmeticException if the calculation overflows
*/
public Duration toEstimatedDuration() {
Duration dur = Duration.ZERO;
for (PeriodField field : this) {
dur = dur.plus(field.toEstimatedDuration());
}
return dur;
}
/**
* Converts this {@code PeriodFields} to a {@code Duration} based on the standard
* durations of seconds and nanoseconds.
* <p>
* The conversion is based on the {@code ISOChronology} definition of the seconds and
* nanoseconds units. If all the fields in this period can be converted to one of these
* units then the conversion will succeed, subject to calculation overflow.
* If any field cannot be converted to these fields above then an exception is thrown.
* <p>
* This conversion can only be used if the duration is being used in a manner
* compatible with the {@code ISOChronology} definitions of seconds and nanoseconds.
* This will be the case for most applications - care only needs to be taken if
* using explicit time-scales.
*
* @return the duration of this period based on {@code ISOChronology} fields, never null
* @throws ArithmeticException if the calculation overflows
*/
public Duration toDuration() {
PeriodFields period = toEquivalentPeriod(ISOChronology.periodSeconds(), ISOChronology.periodNanos());
return Duration.seconds(period.getAmount(ISOChronology.periodSeconds()), period.getAmount(ISOChronology.periodNanos()));
}
/**
* Converts this period to a {@code PeriodFields}, trivially
* returning {@code this}.
*
* @return {@code this}, never null
*/
public PeriodFields toPeriodFields() {
return this;
}
/**
* Checks if this instance equal to the object specified.
* <p>
* Two {@code PeriodFields} instances are equal if all the contained
* {@code PeriodField} instances are equal.
*
* @param obj the other period to compare to, null returns false
* @return true if this instance is equal to the specified period
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof PeriodFields) {
PeriodFields other = (PeriodFields) obj;
return unitFieldMap.equals(other.unitFieldMap);
}
return false;
}
/**
* Returns the hash code for this period.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return unitFieldMap.hashCode();
}
/**
* Returns a string representation of the period, such as '[6 Days, 13 Hours]'.
*
* @return a descriptive representation of the period, not null
*/
@Override
public String toString() {
if (unitFieldMap.size() == 0) {
return "[]";
}
StringBuilder buf = new StringBuilder();
buf.append('[');
for (PeriodField field : this) {
buf.append(field.toString()).append(',').append(' ');
}
buf.setLength(buf.length() - 2);
buf.append(']');
return buf.toString();
}
} |
package me.lemire.roaringbitmap;
import java.util.Iterator;
import java.util.Map.Entry;
public class RRmain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RoaringBitmap rr = new RoaringBitmap();
/*rr.add(13); rr.add(50); rr.add(70); rr.add(60000); rr.add(60500); rr.add(70500); rr.add(300200);
rr.add(407001); rr.add(419534);rr.add(472537);//rr.add(550606); rr.add(616142);*/
for(int k = 4000; k<4256;++k) rr.add(k); //Seq
for(int k = 65535; k<65535+4000;++k) rr.add(k); //bitmap
for(int k = 4*65535; k<4*65535+4000;++k) rr.add(k); //4 ds seq et 3996 bitmap
for(int k = 6*65535; k<6*65535+1000;++k) rr.add(k); //6 ds seq et 994 ds bitmap
RoaringBitmap rr2 = new RoaringBitmap();
/*rr2.add(44); rr2.add(70); rr2.add(10050); rr2.add(50550); rr2.add(60000);
rr2.add(60500); rr2.add(300200); rr2.add(407001); rr2.add(472537); rr2.add(616142);*/
for(int k = 4000; k<4256;++k) rr2.add(k);
for(int k = 65535; k<65535+4000;++k) rr2.add(k);
for(int k = 6*65535; k<6*65535+1000;++k) rr2.add(k);
RoaringBitmap rror = RoaringBitmap.or(rr, rr2);
RoaringBitmap rrand = RoaringBitmap.and(rr, rr2);
RoaringBitmap rrxor = RoaringBitmap.xor(rr, rr2);
final Iterator<Entry<Short, Container>> p1 = rr.c.entrySet().iterator();
final Iterator<Entry<Short, Container>> p2 = rr2.c.entrySet().iterator();
final Iterator<Entry<Short, Container>> p3 = rror.c.entrySet().iterator();
final Iterator<Entry<Short, Container>> p4 = rrand.c.entrySet().iterator();
final Iterator<Entry<Short, Container>> p5 = rrxor.c.entrySet().iterator();
Entry<Short, Container> s1;
System.out.println("\n rr : ");
while (p1.hasNext())
{ s1=p1.next(); System.out.print(" "+s1.getKey().shortValue()/*+" "+s1.getValue().getCardinality()*/);}
System.out.println("\n rr2 : ");
while (p2.hasNext())
{ s1=p2.next(); System.out.print(" "+s1.getKey().shortValue()); }
/*System.out.println("\n rror : ");
while (p3.hasNext())
{ s1=p3.next(); System.out.print(" "+s1.getKey().shortValue()); }
System.out.println("\n rrand : ");
while (p4.hasNext())
{ s1=p4.next(); System.out.print(" "+s1.getKey().shortValue()); }*/
System.out.println("\n rrxor : ");
while (p5.hasNext())
{ s1=p5.next(); System.out.print(" "+s1.getKey().shortValue()); }
RoaringBitmap.afficher(rrxor);
/*System.out.println("\n rror : ");
for(int i : rror) System.out.print(i+" ");
System.out.println("\n rrand : ");
for(int i : rrand) System.out.print(i+" ");*/
}
} |
package me.moodcat.backend;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.moodcat.database.controllers.ChatDAO;
import me.moodcat.database.controllers.RoomDAO;
import me.moodcat.database.entities.ChatMessage;
import me.moodcat.database.entities.Room;
import me.moodcat.database.entities.Song;
import me.moodcat.util.CallableInUnitOfWork.CallableInUnitOfWorkFactory;
import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener;
import org.eclipse.jetty.util.component.LifeCycle;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
/**
* The backend of rooms, initializes room instances and keeps track of time and messages.
*/
@Slf4j
@Singleton
public class RoomBackend extends AbstractLifeCycleListener {
/**
* The size of executorService's thread pool.
*/
private static final int THREAD_POOL_SIZE = 4;
/**
* The service to increment the room's song time.
*/
private final ScheduledExecutorService executorService;
/**
* A map of room instances.
*/
private final Map<Integer, RoomInstance> roomInstances;
/**
* The room DAO provider.
*/
private final Provider<RoomDAO> roomDAOProvider;
/**
* The chat DAO provider.
*/
private Provider<ChatDAO> chatDAOProvider;
/**
* The CallableInUnitOfWorkFactory which is used to perform large tasks in the background.
*/
private final CallableInUnitOfWorkFactory callableInUnitOfWorkFactory;
/**
* The constructor of the chat's backend, initializes fields and rooms.
*
* @param roomDAOProvider
* The provider for the RoomDAO.
* @param callableInUnitOfWorkFactory
* The factory that can create UnitOfWorks.
* @param chatDAOProvider
* The provider for the ChatDAO.
*/
@Inject
public RoomBackend(final Provider<RoomDAO> roomDAOProvider,
final CallableInUnitOfWorkFactory callableInUnitOfWorkFactory,
final Provider<ChatDAO> chatDAOProvider) {
this(roomDAOProvider, callableInUnitOfWorkFactory, Executors
.newScheduledThreadPool(THREAD_POOL_SIZE), chatDAOProvider);
}
/**
* The constructor of the chat's backend, initializes fields and rooms.
*
* @param roomDAOProvider
* The provider for the RoomDAO.
* @param callableInUnitOfWorkFactory
* The factory that can create UnitOfWorks.
* @param executorService
* The executor service to run multi-threaded.
* @param chatDAOProvider
* The provider for the ChatDAO.
*/
protected RoomBackend(final Provider<RoomDAO> roomDAOProvider,
final CallableInUnitOfWorkFactory callableInUnitOfWorkFactory,
final ScheduledExecutorService executorService,
final Provider<ChatDAO> chatDAOProvider) {
this.executorService = executorService;
this.roomDAOProvider = roomDAOProvider;
this.chatDAOProvider = chatDAOProvider;
this.callableInUnitOfWorkFactory = callableInUnitOfWorkFactory;
this.roomInstances = initializeInitialRooms();
}
/**
* Initialize room instances for every room in the database.
*/
protected Map<Integer, RoomInstance> initializeInitialRooms() {
return performInUnitOfWork(() -> {
final RoomDAO roomDAO = roomDAOProvider.get();
return roomDAO.listRooms().stream()
.collect(Collectors.toMap(Room::getId, RoomInstance::new));
});
}
/**
* Get a room instance by its id.
*
* @param id
* the room's id
* @return the room
*/
public RoomInstance getRoomInstance(final int id) {
return roomInstances.get(id);
}
@Override
public void lifeCycleStopping(final LifeCycle event) {
log.info("Shutting down executor for {}", this);
executorService.shutdown();
}
@SneakyThrows
protected <V> V performInUnitOfWork(final Callable<V> callable) {
final Callable<V> inUnitOfWork = callableInUnitOfWorkFactory.create(callable);
return executorService.submit(inUnitOfWork).get();
}
/**
* The instance object of the rooms.
*/
public class RoomInstance {
/**
* Number of chat messages to cache for each room.
*/
public static final int MAXIMAL_NUMBER_OF_CHAT_MESSAGES = 100;
/**
* The roomInstance's room.
*
* @return the room.
*/
@Getter
private final Room room;
/**
* The current time of the room's song.
*/
private final AtomicInteger currentTime;
/**
* The cached messages in order to speed up retrieval.
*/
private final LinkedList<ChatMessage> messages;
/**
* ChatRoomInstance's constructur, will create a roomInstance from a room
* and start the timer for the current song.
*
* @param room
* the room used to create the roomInstance.
*/
public RoomInstance(final Room room) {
this.room = room;
this.currentTime = new AtomicInteger(0);
this.messages = new LinkedList<ChatMessage>(RoomBackend.this.chatDAOProvider.get()
.listByRoom(room));
scheduleSongTimer();
scheduleSyncTimer();
log.info("Created room {}", this);
}
/**
* Sync room messages to the database.
*/
private void scheduleSyncTimer() {
this.room.setChatMessages(Lists.newArrayList(messages));
RoomBackend.this.executorService.scheduleAtFixedRate(this::merge,
0, 1, TimeUnit.MINUTES);
}
/**
* Schedule song timer.
*/
private void scheduleSongTimer() {
RoomBackend.this.executorService.scheduleAtFixedRate(this::incrementTime,
0, 1, TimeUnit.SECONDS);
}
/**
* Store a message in the instance.
*
* @param chatMessage
* the message to send.
*/
public void sendMessage(final ChatMessage chatMessage) {
chatMessage.setRoom(room);
chatMessage.setTimestamp(System.currentTimeMillis());
messages.addLast(chatMessage);
if (messages.size() > MAXIMAL_NUMBER_OF_CHAT_MESSAGES) {
messages.removeFirst();
}
log.info("Sending message {} in room {}", chatMessage, this);
}
/**
* Merge the changes of the instance in the database.
*/
protected void merge() {
log.info("Merging changes in room {}", this);
performInUnitOfWork(() -> roomDAOProvider.get().merge(room));
}
/**
* The cached messages in order to speed up retrieval.
*
* @return The latest {@link #MAXIMAL_NUMBER_OF_CHAT_MESSAGES} messages.
*/
public List<ChatMessage> getMessages() {
return messages;
}
/**
* Get the instance's current song.
*
* @return the current song.
*/
public Song getCurrentSong() {
return this.room.getCurrentSong();
}
/**
* Get the progress of the current song.
*
* @return the progress in seconds.
*/
public int getCurrentTime() {
return this.currentTime.get();
}
/**
* Get the room name.
*
* @return the name of the room
*/
public String getName() {
return this.room.getName();
}
/**
* Method used to make the room play the next song.
*/
public void playNext() {
final List<Song> playHistory = room.getPlayHistory();
playHistory.add(room.getCurrentSong());
List<Song> playQueue = room.getPlayQueue();
if (playQueue.isEmpty() && room.isRepeat()) {
playQueue = Lists.newArrayList(playHistory);
}
if (!playQueue.isEmpty()) {
final Song currentSong = playQueue.remove(0);
log.info("Playing song {} in room {}", currentSong, this);
room.setCurrentSong(currentSong);
merge();
}
resetTime();
}
/**
* Method used to increment the time of the current song by one second.
*/
protected void incrementTime() {
final int time = this.currentTime.incrementAndGet();
final int duration = this.getCurrentSong().getDuration();
if (time > duration) {
playNext();
}
}
/**
* Reset the time of the room's current song.
*/
protected void resetTime() {
log.debug("Resetting time counter in room {}", this);
this.currentTime.set(0);
}
}
} |
package net.common.utils.mail;
/**
*
*
* @author krisjin (mailto:krisjin86@163.com)
* @date 2014-5-234:25:02
*/
public class MailInfo {
private String username;
private String password;
private String mailFrom;
private String mailTo;
private String mailSubject;
private String body;
private String mailServerHost = "smtp.163.com";
private String htmlBody;
private String mailName;
private boolean isAuth = true;
private int mailPort;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMailFrom() {
return mailFrom;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public String getMailTo() {
return mailTo;
}
public void setMailTo(String mailTo) {
this.mailTo = mailTo;
}
public String getMailSubject() {
return mailSubject;
}
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getHtmlBody() {
return htmlBody;
}
public void setHtmlBody(String htmlBody) {
this.htmlBody = htmlBody;
}
public String getMailName() {
return mailName;
}
public void setMailName(String mailName) {
this.mailName = mailName;
}
public boolean isAuth() {
return isAuth;
}
public void setIsAuth(boolean isAuth) {
this.isAuth = isAuth;
}
public int getMailPort() {
return mailPort;
}
public void setMailPort(int mailPort) {
this.mailPort = mailPort;
}
} |
package operator.viperSpout;
import java.io.File;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import statistics.CountStat;
import backtype.storm.Config;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
import core.TupleType;
import core.ViperUtils;
public class ViperSpout extends BaseRichSpout {
private static final long serialVersionUID = 1178144110062379252L;
public static Logger LOG = LoggerFactory.getLogger(ViperSpout.class);
private SpoutFunction udf;
private Fields outFields;
private SpoutOutputCollector collector;
private boolean flushSent = false;
private boolean writelogSent = false;
private boolean keepStats;
private String statsPath;
private CountStat countStat;
private String id;
private long counter = 0;
private long ackGap = 0;
private long failCounter = 0;
public ViperSpout(SpoutFunction udf, Fields outFields) {
this.udf = udf;
this.outFields = ViperUtils.enrichWithBaseFields(outFields);
}
public void nextTuple() {
if (udf.hasNext()) {
if (ackGap < 1000) {
Values v = udf.getTuple();
v.add(0, TupleType.REGULAR);
v.add(1, System.currentTimeMillis());
v.add(2, id);
collector.emit(v, counter);
counter++;
if (keepStats) {
countStat.increase(1);
}
}
} else if (!flushSent) {
collector.emit(ViperUtils.getFlushTuple(this.outFields.size() - 2));
LOG.info("Spout " + id + " sending FLUSH tuple");
flushSent = true;
} else if (!writelogSent) {
collector
.emit(ViperUtils.getWriteLogTuple(this.outFields.size() - 2));
writelogSent = true;
if (keepStats) {
Utils.sleep(2000); // Just wait for latest stats to be written
countStat.stopStats();
try {
countStat.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
countStat.writeStats();
}
} else {
Utils.sleep(1000);
}
}
@SuppressWarnings({ "rawtypes" })
public void open(Map arg0, TopologyContext arg1, SpoutOutputCollector arg2) {
collector = arg2;
Object temp = arg0.get("log.statistics");
this.keepStats = temp != null ? (Boolean) temp : false;
temp = arg0.get("log.statistics.path");
this.statsPath = temp != null ? (String) temp : "";
id = arg1.getThisComponentId() + "." + arg1.getThisTaskIndex();
if (keepStats) {
countStat = new CountStat("", statsPath + File.separator
+ arg0.get(Config.TOPOLOGY_NAME) + "_" + id + ".rate.csv",
false);
countStat.start();
}
udf.prepare(arg0, arg1);
}
public void declareOutputFields(OutputFieldsDeclarer arg0) {
arg0.declare(this.outFields);
}
@Override
public void ack(Object msgId) {
ackGap = counter - (Long) msgId;
if (ackGap % 100 == 0) {
System.out.println("ack: " + ackGap);
}
}
@Override
public void fail(Object msgId) {
failCounter++;
if (failCounter % 1000 == 0) {
System.out.println("fail: " + failCounter);
}
}
} |
package org.commcare.xml;
import org.commcare.cases.model.Case;
import org.commcare.cases.model.CaseIndex;
import org.commcare.data.xml.TransactionParser;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.util.externalizable.SerializationLimitationException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.ActionableInvalidStructureException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Date;
import java.util.NoSuchElementException;
/**
* The CaseXML Parser is responsible for processing and performing
* case transactions from an incoming XML stream. It will perform
* all of the actions specified by the transaction (Create/modify/close)
* against the application's current storage.
*
* NOTE: Future work on case XML Processing should shift to the BulkProcessingCaseXmlParser, since
* there's no good way for us to maintain multiple different sources for all of the complex logic
* inherent in this process. If anything would be added here, it should likely be replaced rather
* than implemented in both places.
*
* @author ctsims
*/
public class CaseXmlParser extends TransactionParser<Case> {
public static final String ATTACHMENT_FROM_LOCAL = "local";
public static final String ATTACHMENT_FROM_REMOTE = "remote";
public static final String ATTACHMENT_FROM_INLINE = "inline";
public static final String CASE_XML_NAMESPACE = "http://commcarehq.org/case/transaction/v2";
private final IStorageUtilityIndexed storage;
private final boolean acceptCreateOverwrites;
public CaseXmlParser(KXmlParser parser, IStorageUtilityIndexed storage) {
this(parser, true, storage);
}
/**
* Creates a Parser for case blocks in the XML stream provided.
*
* @param parser The parser for incoming XML.
* @param acceptCreateOverwrites Whether an Exception should be thrown if the transaction
* contains create actions for cases which already exist.
*/
public CaseXmlParser(KXmlParser parser, boolean acceptCreateOverwrites,
IStorageUtilityIndexed storage) {
super(parser);
this.acceptCreateOverwrites = acceptCreateOverwrites;
this.storage = storage;
}
@Override
public Case parse() throws InvalidStructureException, IOException, XmlPullParserException {
checkNode("case");
String caseId = parser.getAttributeValue(null, "case_id");
if (caseId == null || caseId.equals("")) {
throw InvalidStructureException.readableInvalidStructureException("The case_id attribute of a <case> wasn't set", parser);
}
String dateModified = parser.getAttributeValue(null, "date_modified");
if (dateModified == null) {
throw InvalidStructureException.readableInvalidStructureException("The date_modified attribute of a <case> wasn't set", parser);
}
Date modified = DateUtils.parseDateTime(dateModified);
String userId = parser.getAttributeValue(null, "user_id");
Case caseForBlock = null;
boolean isCreateOrUpdate = false;
while (nextTagInBlock("case")) {
String action = parser.getName().toLowerCase();
switch (action) {
case "create":
caseForBlock = createCase(caseId, modified, userId);
isCreateOrUpdate = true;
break;
case "update":
caseForBlock = loadCase(caseForBlock, caseId, true);
updateCase(caseForBlock, caseId);
isCreateOrUpdate = true;
break;
case "close":
caseForBlock = loadCase(caseForBlock, caseId, true);
closeCase(caseForBlock, caseId);
break;
case "index":
caseForBlock = loadCase(caseForBlock, caseId, false);
indexCase(caseForBlock, caseId);
break;
case "attachment":
caseForBlock = loadCase(caseForBlock, caseId, false);
processCaseAttachment(caseForBlock);
break;
}
}
if (caseForBlock != null) {
caseForBlock.setLastModified(modified);
try {
commit(caseForBlock);
} catch (SerializationLimitationException e) {
throw new InvalidStructureException("One of the property values for the case named '" +
caseForBlock.getName() + "' is too large (by " + e.percentOversized +
"%). Please show your supervisor.");
}
if (isCreateOrUpdate) {
onCaseCreateUpdate(caseId);
}
}
return null;
}
private Case createCase(String caseId, Date modified, String userId) throws InvalidStructureException, IOException, XmlPullParserException {
String[] data = new String[3];
Case caseForBlock = null;
while (nextTagInBlock("create")) {
String tag = parser.getName();
switch (tag) {
case "case_type":
data[0] = parser.nextText().trim();
break;
case "owner_id":
data[1] = parser.nextText().trim();
break;
case "case_name":
data[2] = parser.nextText().trim();
break;
default:
throw new InvalidStructureException("Expected one of [case_type, owner_id, case_name], found " + parser.getName(), parser);
}
}
if (data[0] == null || data[2] == null) {
throw new InvalidStructureException("One of [case_type, case_name] is missing for case <create> with ID: " + caseId, parser);
}
if (acceptCreateOverwrites) {
caseForBlock = retrieve(caseId);
if (caseForBlock != null) {
caseForBlock.setName(data[2]);
caseForBlock.setTypeId(data[0]);
}
}
if (caseForBlock == null) {
// The case is either not present on the phone, or we're on strict tolerance
caseForBlock = buildCase(data[2], data[0]);
caseForBlock.setCaseId(caseId);
caseForBlock.setDateOpened(modified);
}
if (data[1] != null) {
caseForBlock.setUserId(data[1]);
} else {
caseForBlock.setUserId(userId);
}
return caseForBlock;
}
private void updateCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException {
while (nextTagInBlock("update")) {
String key = parser.getName();
String value = parser.nextText().trim();
switch (key) {
case "case_type":
caseForBlock.setTypeId(value);
break;
case "case_name":
caseForBlock.setName(value);
break;
case "date_opened":
caseForBlock.setDateOpened(DateUtils.parseDate(value));
break;
case "owner_id":
String oldUserId = caseForBlock.getUserId();
if (oldUserId == null) {
throw InvalidStructureException.readableInvalidStructureException("The userid field of a <case> was found null", parser);
}
if (!oldUserId.equals(value)) {
onIndexDisrupted(caseId);
}
caseForBlock.setUserId(value);
break;
case "external_id":
caseForBlock.setExternalId(value);
break;
default:
caseForBlock.setProperty(key, value);
break;
}
}
}
private Case loadCase(Case caseForBlock, String caseId, boolean errorIfMissing) throws InvalidStructureException {
if (caseForBlock == null) {
caseForBlock = retrieve(caseId);
}
if (errorIfMissing && caseForBlock == null) {
throw InvalidStructureException.readableInvalidStructureException("Unable to update or close case " + caseId + ", it wasn't found", parser);
}
return caseForBlock;
}
private void closeCase(Case caseForBlock, String caseId) throws IOException {
caseForBlock.setClosed(true);
commit(caseForBlock);
onIndexDisrupted(caseId);
}
private void indexCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException {
while (nextTagInBlock("index")) {
String indexName = parser.getName();
String caseType = parser.getAttributeValue(null, "case_type");
String relationship = parser.getAttributeValue(null, "relationship");
if (relationship == null) {
relationship = CaseIndex.RELATIONSHIP_CHILD;
} else if ("".equals(relationship)) {
throw new InvalidStructureException("Invalid Case Transaction: Attempt to create '' relationship type", parser);
}
String value = parser.nextText().trim();
if (value.equals(caseId)) {
throw new ActionableInvalidStructureException("case.error.self.index", new String[]{caseId}, "Case " + caseId + " cannot index itself");
}
//Remove any ambiguity associated with empty values
if (value.equals("")) {
value = null;
}
//Process blank inputs in the same manner as data fields (IE: Remove the underlying model)
if (value == null) {
if (caseForBlock.removeIndex(indexName)) {
onIndexDisrupted(caseId);
}
} else {
if (caseForBlock.setIndex(new CaseIndex(indexName, caseType, value,
relationship))) {
onIndexDisrupted(caseId);
}
}
}
}
private void processCaseAttachment(Case caseForBlock) throws InvalidStructureException, IOException, XmlPullParserException {
while (nextTagInBlock("attachment")) {
String attachmentName = parser.getName();
String src = parser.getAttributeValue(null, "src");
String from = parser.getAttributeValue(null, "from");
String fileName = parser.getAttributeValue(null, "name");
if ((src == null || "".equals(src)) && (from == null || "".equals(from))) {
//this is actually an attachment removal
removeAttachment(caseForBlock, attachmentName);
caseForBlock.removeAttachment(attachmentName);
continue;
}
String reference = processAttachment(src, from, fileName, parser);
if (reference != null) {
caseForBlock.updateAttachment(attachmentName, reference);
}
}
}
protected void removeAttachment(Case caseForBlock, String attachmentName) {
}
protected String processAttachment(String src, String from, String name, KXmlParser parser) {
return null;
}
protected Case buildCase(String name, String typeId) {
return new Case(name, typeId);
}
@Override
protected void commit(Case parsed) throws IOException {
storage().write(parsed);
}
protected Case retrieve(String entityId) {
try {
return (Case)storage().getRecordForValue(Case.INDEX_CASE_ID, entityId);
} catch (NoSuchElementException nsee) {
return null;
}
}
public IStorageUtilityIndexed storage() {
return storage;
}
/**
* A signal that notes that processing a transaction has resulted in a
* potential change in what cases should be on the phone. This can be
* due to a case's owner changing, a case closing, an index moving, etc.
*
* Does not have to be consumed, but can be used to identify proactively
* when to reconcile what cases should be available.
*
* @param caseId The ID of a case which has changed in a potentially
* disruptive way
*/
public void onIndexDisrupted(String caseId) {
}
protected void onCaseCreateUpdate(String caseId) {
}
} |
package org.gnode.nix;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.annotation.*;
import org.gnode.nix.base.ImplContainer;
import org.gnode.nix.internal.None;
import org.gnode.nix.internal.OptionalDouble;
import org.gnode.nix.internal.OptionalString;
import org.gnode.nix.internal.Utils;
import java.util.List;
@Platform(value = "linux",
include = {"<nix/Dimensions.hpp>"},
link = {"nix"})
@Namespace("nix")
public class SampledDimension extends ImplContainer implements Comparable<SampledDimension> {
static {
Loader.load();
}
// Constructors
/**
* Constructor that creates an uninitialized SampledDimension.
* <p/>
* Calling any method on an uninitialized dimension will throw a {@link java.lang.RuntimeException}.
*/
public SampledDimension() {
allocate();
}
private native void allocate();
// Base class methods
public native
@Cast("bool")
boolean isNone();
// Methods concerning SampledDimension
/**
* The actual dimension that is described by the dimension descriptor.
* <p/>
* The index of the dimension entity representing the dimension of the actual
* data that is defined by this descriptor.
*
* @return The dimension index of the dimension.
*/
public native
@Name("index")
@Cast("size_t")
long getIndex();
/**
* The type of the dimension.
* <p/>
* This field indicates whether the dimension is a SampledDimension, SetDimension or
* RangeDimension.
*
* @return The dimension type.
*/
public native
@Name("dimensionType")
@ByVal
@Cast("nix::DimensionType")
int getDimensionType();
private native
@ByVal
OptionalString label();
/**
* Getter for the label of the dimension.
* <p/>
* The label of a SampledDimension corresponds to the axis label
* in a plot of the respective dimension.
*
* @return The label of the dimension. {#link null} if not present.
*/
public String getLabel() {
OptionalString label = label();
if (label.isPresent()) {
return label.getString();
}
return null;
}
private native void label(@StdString String label);
private native void label(@Const @ByVal None t);
/**
* Sets the label of the dimension. If {#link null} removes label.
*
* @param label The label of the dimension.
*/
public void setLabel(String label) {
if (label != null) {
label(label);
} else {
label(new None());
}
}
private native
@ByVal
OptionalString unit();
/**
* Gets the unit of a dimension.
* <p/>
* The unit describes which SI unit applies to this dimension
* and to its sampling interval.
*
* @return The unit of the dimension.
*/
public String getUnit() {
OptionalString unit = unit();
if (unit.isPresent()) {
return unit.getString();
}
return null;
}
private native void unit(@StdString String unit);
private native void unit(@Const @ByVal None t);
/**
* Sets the unit of a dimension. If {#link null} removes the unit.
*
* @param unit The unit to set.
*/
public void setUnit(String unit) {
if (unit != null) {
unit(unit);
} else {
unit(new None());
}
}
/**
* Gets the sampling interval of the dimension.
*
* @return The sampling interval.
*/
public native
@Name("samplingInterval")
double getSamplingInterval();
/**
* Sets the sampling interval of the dimension.
*
* @param interval The sampling interval to set.
*/
public native
@Name("samplingInterval")
void setSamplingInterval(double interval);
private native
@ByVal
OptionalDouble offset();
/**
* Gets the offset of the dimension.
* <p/>
* The offset defines at which position the sampling was started. The offset is
* interpreted in the same unit as the sampling interval.
* <p/>
* By default the offset is 0.
*
* @return The offset of the SampledDimension.
*/
public double getOffset() {
OptionalDouble offset = offset();
if (offset.isPresent()) {
return offset.getDouble();
}
return 0.0;
}
/**
* Sets the offset of the dimension.
*
* @param offset The offset of the dimension.
*/
public native
@Name("offset")
void setOffset(double offset);
/**
* Returns the index of the given position.
* <p/>
* This method returns the index of the given position. Use this method for
* example to find out which data point (index) relates to a given
* time. Note: This method does not check if the position is within the
* extent of the data!
*
* @param position The position
* @return The respective index.
*/
public native
@Name("indexOf")
@Cast("size_t")
long getIndexOf(double position);
/**
* Returns the position of this dimension at a given index.
* <p/>
* This method returns the position at a given index. Use this method for
* example to find the position that relates to a certain index. Note: This
* method does not check if the index is the extent of the data!
*
* @param index The index.
* @return The respective position
*/
public native
@Name("positionAt")
double getPositionAt(@Cast("const size_t") long index);
private native
@StdVector
DoublePointer axis(@Cast("const size_t") long count, @Cast("const size_t") long startIndex);
/**
* Returns a vector containing the positions defined by this
* dimension.
*
* @param count The number of indices
* @param startIndex The start index
* @return list containing the respective dimension.
*/
public List<Double> getAxis(long count, long startIndex) {
return Utils.convertPointerToList(axis(count, startIndex));
}
private native
@StdVector
DoublePointer axis(@Cast("const size_t") long count);
/**
* Returns a list containing the positions defined by this
* dimension with the start index set to 0.
*
* @param count The number of indices
* @return list containing the respective dimension.
*/
public List<Double> getAxis(long count) {
return Utils.convertPointerToList(axis(count));
}
@Override
public int compareTo(SampledDimension sampledDimension) {
if (this == sampledDimension) {
return 0;
}
return (int) (this.getIndex() - sampledDimension.getIndex());
}
} |
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.BreakIterator;
import org.jfree.chart.ui.TextAnchor;
/**
* Some utility methods for working with text in Java2D.
*/
public class TextUtils {
private static boolean drawStringsWithFontAttributes = false;
/**
* A flag that controls whether or not the rotated string workaround is
* used.
*/
private static boolean useDrawRotatedStringWorkaround = true;
/**
* A flag that controls whether the FontMetrics.getStringBounds() method
* is used or a workaround is applied.
*/
private static boolean useFontMetricsGetStringBounds = false;
/**
* Private constructor prevents object creation.
*/
private TextUtils() {
// prevent instantiation
}
/**
* Creates a {@link TextBlock} from a {@code String}. Line breaks
* are added where the {@code String} contains '\n' characters.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
TextBlock result = new TextBlock();
String input = text;
boolean moreInputToProcess = (text.length() > 0);
int start = 0;
while (moreInputToProcess) {
int index = input.indexOf("\n");
if (index > start) {
String line = input.substring(start, index);
if (index < input.length() - 1) {
result.addLine(line, font, paint);
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else if (index == start) {
if (index < input.length() - 1) {
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else {
result.addLine(input, font, paint);
moreInputToProcess = false;
}
}
return result;
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the {@code maxWidth} value is respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, TextMeasurer measurer) {
return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,
measurer);
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the {@code maxWidth} value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param maxLines the maximum number of lines.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {
TextBlock result = new TextBlock();
BreakIterator iterator = BreakIterator.getLineInstance();
iterator.setText(text);
int current = 0;
int lines = 0;
int length = text.length();
while (current < length && lines < maxLines) {
int next = nextLineBreak(text, current, maxWidth, iterator,
measurer);
if (next == BreakIterator.DONE) {
result.addLine(text.substring(current), font, paint);
return result;
} else if (next == current) {
next++; // we must take one more character or we'll loop forever
}
result.addLine(text.substring(current, next), font, paint);
lines++;
current = next;
while (current < text.length()&& text.charAt(current) == '\n') {
current++;
}
}
if (current < length) {
TextLine lastLine = result.getLastLine();
TextFragment lastFragment = lastLine.getLastTextFragment();
String oldStr = lastFragment.getText();
String newStr = "...";
if (oldStr.length() > 3) {
newStr = oldStr.substring(0, oldStr.length() - 3) + "...";
}
lastLine.removeFragment(lastFragment);
TextFragment newFragment = new TextFragment(newStr,
lastFragment.getFont(), lastFragment.getPaint());
lastLine.addFragment(newFragment);
}
return result;
}
/**
* Returns the character index of the next line break. If the next
* character is wider than {@code width]} this method will return
* {@code start} - the caller should check for this case.
*
* @param text the text ({@code null} not permitted).
* @param start the start index.
* @param width the target display width.
* @param iterator the word break iterator.
* @param measurer the text measurer.
*
* @return The index of the next line break.
*/
private static int nextLineBreak(String text, int start, float width,
BreakIterator iterator, TextMeasurer measurer) {
// this method is (loosely) based on code in JFreeReport's
// TextParagraph class
int current = start;
int end;
float x = 0.0f;
boolean firstWord = true;
int newline = text.indexOf('\n', start);
if (newline < 0) {
newline = Integer.MAX_VALUE;
}
while (((end = iterator.following(current)) != BreakIterator.DONE)) {
x += measurer.getStringWidth(text, current, end);
if (x > width) {
if (firstWord) {
while (measurer.getStringWidth(text, start, end) > width) {
end
if (end <= start) {
return end;
}
}
return end;
}
else {
end = iterator.previous();
return end;
}
}
else {
if (end > newline) {
return newline;
}
}
// we found at least one word that fits ...
firstWord = false;
current = end;
}
return BreakIterator.DONE;
}
/**
* Returns the bounds for the specified text.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics context (not {@code null}).
* @param fm the font metrics (not {@code null}).
*
* @return The text bounds ({@code null} if the {@code text}
* argument is {@code null}).
*/
public static Rectangle2D getTextBounds(String text, Graphics2D g2,
FontMetrics fm) {
Rectangle2D bounds;
if (TextUtils.useFontMetricsGetStringBounds) {
bounds = fm.getStringBounds(text, g2);
// getStringBounds() can return incorrect height for some Unicode
// characters...see bug parade 6183356, let's replace it with
// something correct
LineMetrics lm = fm.getFont().getLineMetrics(text,
g2.getFontRenderContext());
bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
lm.getHeight());
}
else {
double width = fm.stringWidth(text);
double height = fm.getHeight();
bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
height);
}
return bounds;
}
/**
* Returns the bounds of an aligned string.
*
* @param text the string ({@code null} not permitted).
* @param g2 the graphics target ({@code null} not permitted).
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param anchor the anchor point that will be aligned to
* {@code (x, y)} ({@code null} not permitted).
*
* @return The text bounds (never {@code null}).
*
* @since 1.3
*/
public static Rectangle2D calcAlignedStringBounds(String text,
Graphics2D g2, float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
return textBounds;
}
/**
* Draws a string such that the specified anchor point is aligned to the
* given (x, y) location.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x coordinate (Java 2D).
* @param y the y coordinate (Java 2D).
* @param anchor the anchor location.
*
* @return The text bounds (adjusted for the text position).
*/
public static Rectangle2D drawAlignedString(String text, Graphics2D g2,
float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
if (!drawStringsWithFontAttributes) {
g2.drawString(text, x + adjust[0], y + adjust[1]);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]);
}
return textBounds;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not {@code null}).
* @param text the text.
* @param anchor the anchor point.
* @param textBounds the text bounds (if not {@code null}, this
* object will be updated by this method to match the
* string bounds).
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor, Rectangle2D textBounds) {
float[] result = new float[3];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isVerticalCenter()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param angle the angle of the (clockwise) rotation (in radians).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(String text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float textX, float textY,
double angle, float rotateX, float rotateY) {
if ((text == null) || (text.equals(""))) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, textX, textY, TextAnchor.BASELINE_LEFT);
return;
}
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
TextLayout tl = new TextLayout(text, g2.getFont(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
}
else {
if (!drawStringsWithFontAttributes) {
g2.drawString(text, textX, textY);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), textX, textY);
}
}
g2.setTransform(saved);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle.
* @param rotationX the x-coordinate for the rotation anchor point.
* @param rotationY the y-coordinate for the rotation anchor point.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, float rotationX, float rotationY) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
} else {
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,
textAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,
rotationX, rotationY);
}
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
} else {
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,
textAnchor);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics device.
* @param x the x coordinate for the anchor point.
* @param y the y coordinate for the anchor point.
* @param textAnchor the text anchor.
* @param angle the angle.
* @param rotationAnchor the rotation anchor.
*
* @return The bounds (possibly {@code null}).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return null;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
Shape result = calculateRotatedStringBounds(text, g2,
x + textAdj[0], y + textAdj[1], angle,
x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);
return result;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not {@code null}).
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isVerticalCenter()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* ({@code BASELINE_LEFT}).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isLeft()) {
xAdj = 0.0f;
}
else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
}
else if (anchor.isVerticalCenter()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = metrics.getDescent() + metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics device.
* @param textX the x coordinate for the text.
* @param textY the y coordinate for the text.
* @param angle the angle.
* @param rotateX the x coordinate for the rotation point.
* @param rotateY the y coordinate for the rotation point.
*
* @return The bounds ({@code null} if {@code text} is
* {@code null} or has zero length).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
if ((text == null) || (text.equals(""))) {
return null;
}
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm);
AffineTransform translate = AffineTransform.getTranslateInstance(
textX, textY);
Shape translatedBounds = translate.createTransformedShape(bounds);
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
Shape result = rotate.createTransformedShape(translatedBounds);
return result;
}
/**
* Returns the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @return A boolean.
*/
public static boolean getUseFontMetricsGetStringBounds() {
return useFontMetricsGetStringBounds;
}
/**
* Sets the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @param use the flag.
*/
public static void setUseFontMetricsGetStringBounds(boolean use) {
useFontMetricsGetStringBounds = use;
}
/**
* Returns the flag that controls whether or not a workaround is used for
* drawing rotated strings.
*
* @return A boolean.
*/
public static boolean isUseDrawRotatedStringWorkaround() {
return useDrawRotatedStringWorkaround;
}
/**
* Sets the flag that controls whether or not a workaround is used for
* drawing rotated strings. The related bug is on Sun's bug parade
* (id 4312117) and the workaround involves using a {@code TextLayout}
* instance to draw the text instead of calling the
* {@code drawString()} method in the {@code Graphics2D} class.
*
* @param use the new flag value.
*/
public static void setUseDrawRotatedStringWorkaround(boolean use) {
TextUtils.useDrawRotatedStringWorkaround = use;
}
/**
* Returns the flag that controls whether or not strings are drawn using
* the current font attributes (such as underlining, strikethrough etc).
* The default value is {@code false}.
*
* @return A boolean.
*
* @since 1.0.21
*/
public static boolean getDrawStringsWithFontAttributes() {
return TextUtils.drawStringsWithFontAttributes;
}
public static void setDrawStringsWithFontAttributes(boolean b) {
TextUtils.drawStringsWithFontAttributes = b;
}
} |
package org.jtrfp.trcl;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.gpu.Texture;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.miss.LoadingProgressReporter;
import org.jtrfp.trcl.obj.DEFObject;
import org.jtrfp.trcl.obj.ObjectSystem;
import org.jtrfp.trcl.obj.PositionedRenderable;
public class OverworldSystem extends RenderableSpacePartitioningGrid {
private SkySystem skySystem;
private AltitudeMap altitudeMap, normalizedAltitudeMap;
private final List<DEFObject> defList = new ArrayList<DEFObject>();
private RenderableSpacePartitioningGrid
terrainMirror =
new RenderableSpacePartitioningGrid();
private boolean chamberMode = false;
private boolean tunnelMode = false;
private final TR tr;
private final LoadingProgressReporter
terrainReporter,
cloudReporter,
objectReporter;
private ObjectSystem objectSystem;
private Future<TerrainSystem> terrainSystem;
private TextureMesh textureMesh;
public OverworldSystem(TR tr, final LoadingProgressReporter progressReporter) {
super();
this.tr = tr;
final LoadingProgressReporter []reporters = progressReporter.generateSubReporters(256);
terrainReporter = reporters[0];
cloudReporter = reporters[1];
objectReporter = reporters[2];
}
public void loadLevel(final LVLFile lvl, final TDFFile tdf){
try {
final World w = tr.getWorld();
Color[] globalPalette = tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile());
Texture[] texturePalette = tr
.getResourceManager().getTextures(
lvl.getLevelTextureListFile(), new ColorPaletteVectorList(globalPalette),null,false);
System.out.println("Loading height map...");
altitudeMap = new ScalingAltitudeMap(normalizedAltitudeMap = new InterpolatingAltitudeMap(tr.getResourceManager()
.getRAWAltitude(lvl.getHeightMapOrTunnelFile())),new Vector3D(TR.mapSquareSize,tr.getWorld().sizeY / 2,TR.mapSquareSize));
System.out.println("... Done");
textureMesh = tr.getResourceManager().getTerrainTextureMesh(
lvl.getTexturePlacementFile(), texturePalette);
// Terrain
System.out.println("Building terrain...");
final boolean flatShadedTerrain = lvl.getHeightMapOrTunnelFile()
.toUpperCase().contains("BORG");//TODO: This should be in a config file.
terrainSystem = tr.getThreadManager().submitToThreadPool(new Callable<TerrainSystem>(){
@Override
public TerrainSystem call() throws Exception {
return new TerrainSystem(altitudeMap, textureMesh,TR.mapSquareSize, terrainMirror, tr, tdf,
flatShadedTerrain, terrainReporter, lvl.getHeightMapOrTunnelFile());
}});
System.out.println("...Done.");
// Clouds
System.out.println("Setting up sky...");
skySystem = new SkySystem(this, tr, this, lvl,
TR.mapSquareSize * 8,
(int) (TR.mapWidth / (TR.mapSquareSize * 8)),
w.sizeY/2, cloudReporter);
System.out.println("...Done.");
// Objects
System.out.println("Setting up objects...");
objectSystem = new ObjectSystem(tr, lvl, defList,
null, Vector3D.ZERO, objectReporter);
System.out.println("Adding terrain and object system to OverworldSystem...");
World.relevanceExecutor.submit(new Runnable(){
@Override
public void run() {
OverworldSystem.this.addBranch(objectSystem);
try{OverworldSystem.this.addBranch(terrainSystem.get());}catch(Exception e){e.printStackTrace();}
}}).get();
System.out.println("...Done.");
// Tunnel activators
} catch (Exception e) {
e.printStackTrace();
}
}// end constructor
public List<DEFObject> getDefList() {
return defList;
}
public SpacePartitioningGrid<PositionedRenderable> getTerrainMirror() {
return terrainMirror;
}
public void setChamberMode(boolean mirrorTerrain) {
System.out.println("setChamberMode from "+chamberMode+" to "+mirrorTerrain);
tr.getReporter().report("org.jtrfp.OverworldSystem.isInChamber?",
"" + mirrorTerrain);
if(chamberMode == mirrorTerrain)
return;//Nothing to change.
chamberMode = mirrorTerrain;
final SkySystem clouds = getCloudSystem();
if (mirrorTerrain) {
OverworldSystem.this.nonBlockingAddBranch(getTerrainMirror());
//No skycube updates in chamber
tr.mainRenderer.get().getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(false);
if (clouds != null)
OverworldSystem.this.nonBlockingRemoveBranch(clouds);
} else {
OverworldSystem.this.nonBlockingRemoveBranch(getTerrainMirror());
//Turn skycube updates back on
tr.mainRenderer.get().getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true);
if (clouds != null)
OverworldSystem.this.nonBlockingAddBranch(clouds);
}
}// end chamberMode
private SkySystem getCloudSystem() {
return skySystem;
}
/**
* @return the chamberMode
*/
public boolean isChamberMode() {
return chamberMode;
}
/**
* @return the tunnelMode
*/
public boolean isTunnelMode() {
return tunnelMode;
}
/**
* @param tunnelMode
* the tunnelMode to set
*/
public void setTunnelMode(boolean tunnelMode) {
this.tunnelMode = tunnelMode;
}
/**
* @return the objectSystem
*/
public ObjectSystem getObjectSystem() {
return objectSystem;
}
public AltitudeMap getAltitudeMap() {
return altitudeMap;
}
public SkySystem getSkySystem() {
return skySystem;
}
public TerrainSystem getTerrainSystem(){
try{return terrainSystem.get();}catch(Exception e){throw new RuntimeException(e);}
}
/**
* @return the normalizedAltitudeMap
*/
public AltitudeMap getNormalizedAltitudeMap() {
return normalizedAltitudeMap;
}
public TextureMesh getTextureMesh() {
return textureMesh;
}
}// end OverworldSystem |
package org.junit.runners;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.internal.AssumptionViolatedException;
import org.junit.internal.runners.model.EachTestNotifier;
import org.junit.internal.runners.model.MultipleFailureException;
import org.junit.internal.runners.statements.RunAfters;
import org.junit.internal.runners.statements.RunBefores;
import org.junit.rules.ClassRule;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.Filterable;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.manipulation.Sortable;
import org.junit.runner.manipulation.Sorter;
import org.junit.runner.notification.RunNotifier;
import org.junit.runner.notification.StoppedByUserException;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerScheduler;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;
/**
* Provides most of the functionality specific to a Runner that implements a
* "parent node" in the test tree, with children defined by objects of some data
* type {@code T}. (For {@link BlockJUnit4ClassRunner}, {@code T} is
* {@link Method} . For {@link Suite}, {@code T} is {@link Class}.) Subclasses
* must implement finding the children of the node, describing each child, and
* running each child. ParentRunner will filter and sort children, handle
* {@code @BeforeClass} and {@code @AfterClass} methods, create a composite
* {@link Description}, and run children sequentially.
*/
public abstract class ParentRunner<T> extends Runner implements Filterable,
Sortable {
private final TestClass fTestClass;
private Filter fFilter= null;
private Sorter fSorter= Sorter.NULL;
private RunnerScheduler fScheduler= new RunnerScheduler() {
public void schedule(Runnable childStatement) {
childStatement.run();
}
public void finished() {
// do nothing
}
};
/**
* Constructs a new {@code ParentRunner} that will run {@code @TestClass}
* @throws InitializationError
*/
protected ParentRunner(Class<?> testClass) throws InitializationError {
fTestClass= new TestClass(testClass);
validate();
}
// Must be overridden
/**
* Returns a list of objects that define the children of this Runner.
*/
protected abstract List<T> getChildren();
/**
* Returns a {@link Description} for {@code child}, which can be assumed to
* be an element of the list returned by {@link ParentRunner#getChildren()}
*/
protected abstract Description describeChild(T child);
/**
* Runs the test corresponding to {@code child}, which can be assumed to be
* an element of the list returned by {@link ParentRunner#getChildren()}.
* Subclasses are responsible for making sure that relevant test events are
* reported through {@code notifier}
*/
protected abstract void runChild(T child, RunNotifier notifier);
// May be overridden
/**
* Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}).
* Default implementation adds an error for each method annotated with
* {@code @BeforeClass} or {@code @AfterClass} that is not
* {@code public static void} with no arguments.
*/
protected void collectInitializationErrors(List<Throwable> errors) {
validatePublicVoidNoArgMethods(BeforeClass.class, true, errors);
validatePublicVoidNoArgMethods(AfterClass.class, true, errors);
}
/**
* Adds to {@code errors} if any method in this class is annotated with
* {@code annotation}, but:
* <ul>
* <li>is not public, or
* <li>takes parameters, or
* <li>returns something other than void, or
* <li>is static (given {@code isStatic is false}), or
* <li>is not static (given {@code isStatic is true}).
*/
protected void validatePublicVoidNoArgMethods(Class<? extends Annotation> annotation,
boolean isStatic, List<Throwable> errors) {
List<FrameworkMethod> methods= getTestClass().getAnnotatedMethods(annotation);
for (FrameworkMethod eachTestMethod : methods)
eachTestMethod.validatePublicVoidNoArg(isStatic, errors);
}
/**
* Constructs a {@code Statement} to run all of the tests in the test class. Override to add pre-/post-processing.
* Here is an outline of the implementation:
* <ul>
* <li>Call {@link #runChild(Object, RunNotifier)} on each object returned by {@link #getChildren()} (subject to any imposed filter and sort).</li>
* <li>ALWAYS run all non-overridden {@code @BeforeClass} methods on this class
* and superclasses before the previous step; if any throws an
* Exception, stop execution and pass the exception on.
* <li>ALWAYS run all non-overridden {@code @AfterClass} methods on this class
* and superclasses before any of the previous steps; all AfterClass methods are
* always executed: exceptions thrown by previous steps are combined, if
* necessary, with exceptions from AfterClass methods into a
* {@link MultipleFailureException}.
* </ul>
* @param notifier
* @return {@code Statement}
*/
protected Statement classBlock(final RunNotifier notifier) {
Statement statement= childrenInvoker(notifier);
statement= withBeforeClasses(statement);
statement= withAfterClasses(statement);
statement= withClassRules(statement);
return statement;
}
/**
* Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class
* and superclasses before executing {@code statement}; if any throws an
* Exception, stop execution and pass the exception on.
*/
protected Statement withBeforeClasses(Statement statement) {
List<FrameworkMethod> befores= fTestClass
.getAnnotatedMethods(BeforeClass.class);
return befores.isEmpty() ? statement :
new RunBefores(statement, befores, null);
}
/**
* Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class
* and superclasses before executing {@code statement}; all AfterClass methods are
* always executed: exceptions thrown by previous steps are combined, if
* necessary, with exceptions from AfterClass methods into a
* {@link MultipleFailureException}.
*/
protected Statement withAfterClasses(Statement statement) {
List<FrameworkMethod> afters= fTestClass
.getAnnotatedMethods(AfterClass.class);
return afters.isEmpty() ? statement :
new RunAfters(statement, afters, null);
}
/**
* Returns a {@link Statement}: apply all static {@link ClassRule} fields
* annotated with {@link Rule}.
*
* @param statement
* the base statement
* @return a WithClassRules statement if any class-level {@link Rule}s are
* found, or the base statement
*/
private Statement withClassRules(Statement statement) {
final List<ClassRule> classRules= classRules();
if (classRules.isEmpty()) {
return statement;
}
Statement next = statement;
for (final ClassRule classRule : classRules) {
next = classRule.apply(next, fTestClass);
}
return next;
}
/**
* @return the {@code ClassRule}s that can transform the block that runs
* each method in the tested class.
*/
protected List<ClassRule> classRules() {
final List<ClassRule> results= new ArrayList<ClassRule>();
for (FrameworkField field : ruleFields()) {
if (ClassRule.class.isAssignableFrom(field.getType())) {
results.add(getClassRule(field));
}
}
return results;
}
private ClassRule getClassRule(final FrameworkField field) {
try {
return (ClassRule) field.get(null);
} catch (IllegalAccessException e) {
throw new RuntimeException(
"How did getAnnotatedFields return a field we couldn't access?");
}
}
/**
* @return list of {@link FrameworkField}s annotated with {@link Rule}
*/
protected List<FrameworkField> ruleFields() {
return fTestClass.getAnnotatedFields(Rule.class);
}
/**
* Returns a {@link Statement}: Call {@link #runChild(Object, RunNotifier)}
* on each object returned by {@link #getChildren()} (subject to any imposed
* filter and sort)
*/
protected Statement childrenInvoker(final RunNotifier notifier) {
return new Statement() {
@Override
public void evaluate() {
runChildren(notifier);
}
};
}
private void runChildren(final RunNotifier notifier) {
for (final T each : getFilteredChildren())
fScheduler.schedule(new Runnable() {
public void run() {
ParentRunner.this.runChild(each, notifier);
}
});
fScheduler.finished();
}
/**
* Returns a name used to describe this Runner
*/
protected String getName() {
return fTestClass.getName();
}
// Available for subclasses
/**
* Returns a {@link TestClass} object wrapping the class to be executed.
*/
public final TestClass getTestClass() {
return fTestClass;
}
// Implementation of Runner
@Override
public Description getDescription() {
Description description= Description.createSuiteDescription(getName(),
fTestClass.getAnnotations());
for (T child : getFilteredChildren())
description.addChild(describeChild(child));
return description;
}
@Override
public void run(final RunNotifier notifier) {
EachTestNotifier testNotifier= new EachTestNotifier(notifier,
getDescription());
try {
Statement statement= classBlock(notifier);
statement.evaluate();
} catch (AssumptionViolatedException e) {
testNotifier.fireTestIgnored();
} catch (StoppedByUserException e) {
throw e;
} catch (Throwable e) {
testNotifier.addFailure(e);
}
}
// Implementation of Filterable and Sortable
public void filter(Filter filter) throws NoTestsRemainException {
fFilter= filter;
for (T each : getChildren())
if (shouldRun(each))
return;
throw new NoTestsRemainException();
}
public void sort(Sorter sorter) {
fSorter= sorter;
}
// Private implementation
private void validate() throws InitializationError {
List<Throwable> errors= new ArrayList<Throwable>();
collectInitializationErrors(errors);
if (!errors.isEmpty())
throw new InitializationError(errors);
}
private List<T> getFilteredChildren() {
ArrayList<T> filtered= new ArrayList<T>();
for (T each : getChildren())
if (shouldRun(each))
try {
filterChild(each);
sortChild(each);
filtered.add(each);
} catch (NoTestsRemainException e) {
// don't add it
}
Collections.sort(filtered, comparator());
return filtered;
}
private void sortChild(T child) {
fSorter.apply(child);
}
private void filterChild(T child) throws NoTestsRemainException {
if (fFilter != null)
fFilter.apply(child);
}
private boolean shouldRun(T each) {
return fFilter == null || fFilter.shouldRun(describeChild(each));
}
private Comparator<? super T> comparator() {
return new Comparator<T>() {
public int compare(T o1, T o2) {
return fSorter.compare(describeChild(o1), describeChild(o2));
}
};
}
/**
* Sets a scheduler that determines the order and parallelization
* of children. Highly experimental feature that may change.
*/
public void setScheduler(RunnerScheduler scheduler) {
this.fScheduler = scheduler;
}
} |
package org.kurento.perseus;
import static org.kurento.commons.PropertiesManager.getPropertyJson;
import java.util.List;
import java.util.Scanner;
import org.kurento.commons.ConfigFileManager;
import org.kurento.commons.PropertiesManager;
import org.kurento.jsonrpc.JsonUtils;
import org.kurento.room.KurentoRoomServerApp;
import org.kurento.room.kms.KmsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import com.google.gson.JsonArray;
@ComponentScan
@EnableAutoConfiguration
@Import(KurentoRoomServerApp.class)
public class PerseusApp {
private static final Logger log = LoggerFactory
.getLogger(PerseusApp.class);
private final static String KROOMDEMO_CFG_FILENAME = "kroomdemo.conf.json";
static {
ConfigFileManager.loadConfigFile(KROOMDEMO_CFG_FILENAME);
}
private final Integer DEMO_KMS_NODE_LIMIT = PropertiesManager.getProperty(
"demo.kmsLimit", 10);
private final String DEMO_AUTH_REGEX = PropertiesManager
.getProperty("demo.authRegex");
private static ConfigurableApplicationContext context;
@Autowired
private UserRepository userRepository;
@Bean
public User firstUser(){
User admin = new User();
if (userRepository.findAll().isEmpty()){
String name, password, email;
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Perseus, let's create an administrator.");
System.out.println("Name:");
name=in.next();
System.out.println("Password:");
password=in.next();
System.out.println("Email (you need a valid email in order to receive email from the users):");
email=in.next();
in.close();
admin.setName(name);
admin.setPassword(password);
admin.setEmail(email);
admin.setPrivileges(1);
userRepository.save(admin);
System.out.println("Administrator created");
}
return admin;
}
@Bean
public KmsManager kmsManager() {
JsonArray kmsUris =
getPropertyJson(KurentoRoomServerApp.KMSS_URIS_PROPERTY,
KurentoRoomServerApp.KMSS_URIS_DEFAULT, JsonArray.class);
List<String> kmsWsUris = JsonUtils.toStringList(kmsUris);
log.info("Configuring Kurento Room Server to use the following kmss: "
+ kmsWsUris);
FixedNKmsManager fixedKmsManager =
new FixedNKmsManager(kmsWsUris, DEMO_KMS_NODE_LIMIT);
fixedKmsManager.setAuthRegex(DEMO_AUTH_REGEX);
return fixedKmsManager;
}
public static ConfigurableApplicationContext start(String[] args, Object... sources) {
Object[] newSources = new Object[sources.length + 1];
newSources[0] = KurentoRoomServerApp.class;
for (int i = 0; i < sources.length; i++)
newSources[i + 1] = sources[i];
SpringApplication application = new SpringApplication(newSources);
context = application.run();
return context;
}
public static void main(String[] args) throws Exception {
start(args, PerseusApp.class);
}
public static void stop() {
context.stop();
}
} |
package org.lantern;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.security.auth.login.CredentialException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.kaleidoscope.BasicTrustGraphAdvertisement;
import org.kaleidoscope.BasicTrustGraphNodeId;
import org.kaleidoscope.TrustGraphNode;
import org.kaleidoscope.TrustGraphNodeId;
import org.lantern.event.ClosedBetaEvent;
import org.lantern.event.Events;
import org.lantern.event.GoogleTalkStateEvent;
import org.lantern.event.ResetEvent;
import org.lantern.event.UpdateEvent;
import org.lantern.event.UpdatePresenceEvent;
import org.lantern.ksope.LanternKscopeAdvertisement;
import org.lantern.ksope.LanternTrustGraphNode;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelUtils;
import org.lantern.state.Profile;
import org.lastbamboo.common.ice.MappedServerSocket;
import org.lastbamboo.common.ice.MappedTcpAnswererServer;
import org.lastbamboo.common.p2p.P2PConnectionEvent;
import org.lastbamboo.common.p2p.P2PConnectionListener;
import org.lastbamboo.common.p2p.P2PConstants;
import org.lastbamboo.common.portmapping.NatPmpService;
import org.lastbamboo.common.portmapping.PortMapListener;
import org.lastbamboo.common.portmapping.PortMappingProtocol;
import org.lastbamboo.common.portmapping.UpnpService;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.lastbamboo.common.stun.client.StunServerRepository;
import org.littleshoot.commom.xmpp.PasswordCredentials;
import org.littleshoot.commom.xmpp.XmppCredentials;
import org.littleshoot.commom.xmpp.XmppP2PClient;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.p2p.P2P;
import org.littleshoot.util.SessionSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.hoodcomputing.natpmp.NatPmpException;
/**
* Handles logging in to the XMPP server and processing trusted users through
* the roster.
*/
@Singleton
public class DefaultXmppHandler implements XmppHandler {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultXmppHandler.class);
private final AtomicReference<XmppP2PClient> client =
new AtomicReference<XmppP2PClient>();
static {
SmackConfiguration.setPacketReplyTimeout(30 * 1000);
}
private volatile long lastInfoMessageScheduled = 0L;
private final MessageListener typedListener = new MessageListener() {
@Override
public void processMessage(final Chat ch, final Message msg) {
// Note the Chat will always be null here. We try to avoid using
// actual Chat instances due to Smack's strange and inconsistent
// behavior with message listeners on chats.
final String part = msg.getFrom();
LOG.info("Got chat participant: {} with message:\n {}", part,
msg.toXML());
if (StringUtils.isNotBlank(part) &&
part.startsWith(LanternConstants.LANTERN_JID)) {
processLanternHubMessage(msg);
}
final Integer type =
(Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE);
if (type != null) {
LOG.info("Not processing typed message");
processTypedMessage(msg, type);
}
}
};
private String lastJson = "";
private String hubAddress;
private GoogleTalkState state;
private String lastUserName;
private String lastPass;
private NatPmpService natPmpService;
private final UpnpService upnpService;
private ClosedBetaEvent closedBetaEvent;
private final Object closedBetaLock = new Object();
private MappedServerSocket mappedServer;
private final PeerProxyManager trustedPeerProxyManager;
private final PeerProxyManager anonymousPeerProxyManager;
private final Timer timer;
private final Stats stats;
private final LanternKeyStoreManager keyStoreManager;
private final LanternSocketsUtil socketsUtil;
private final LanternXmppUtil xmppUtil;
private final Model model;
private volatile boolean started;
private final ModelUtils modelUtils;
private final ModelIo modelIo;
private final org.lantern.Roster roster;
private final ProxyTracker proxyTracker;
private final Censored censored;
/**
* Creates a new XMPP handler.
*/
@Inject
public DefaultXmppHandler(final Model model,
final TrustedPeerProxyManager trustedPeerProxyManager,
final AnonymousPeerProxyManager anonymousPeerProxyManager,
final Timer updateTimer, final Stats stats,
final LanternKeyStoreManager keyStoreManager,
final LanternSocketsUtil socketsUtil,
final LanternXmppUtil xmppUtil,
final ModelUtils modelUtils,
final ModelIo modelIo, final org.lantern.Roster roster,
final ProxyTracker proxyTracker,
final Censored censored) {
this.model = model;
this.trustedPeerProxyManager = trustedPeerProxyManager;
this.anonymousPeerProxyManager = anonymousPeerProxyManager;
this.timer = updateTimer;
this.stats = stats;
this.keyStoreManager = keyStoreManager;
this.socketsUtil = socketsUtil;
this.xmppUtil = xmppUtil;
this.modelUtils = modelUtils;
this.modelIo = modelIo;
this.roster = roster;
this.proxyTracker = proxyTracker;
this.censored = censored;
this.upnpService = new Upnp(stats);
new GiveModeConnectivityHandler();
prepopulateProxies();
Events.register(this);
//setupJmx();
}
@Override
public void start() {
// This just links connectivity with Google Talk login status when
// running in give mode.
NatPmpService temp = null;
try {
temp = new NatPmp(stats);
} catch (final NatPmpException e) {
// This will happen when NAT-PMP is not supported on the local
// network.
LOG.info("Could not map", e);
// We just use a dummy one in this case.
temp = new NatPmpService() {
@Override
public void removeNatPmpMapping(int arg0) {
}
@Override
public int addNatPmpMapping(
final PortMappingProtocol arg0, int arg1, int arg2,
PortMapListener arg3) {
return -1;
}
@Override
public void shutdown() {
}
};
}
natPmpService = temp;
MappedServerSocket tempMapper;
try {
LOG.debug("Creating mapped TCP server...");
tempMapper =
new MappedTcpAnswererServer(natPmpService, upnpService,
new InetSocketAddress(this.model.getSettings().getServerPort()));
LOG.debug("Created mapped TCP server...");
} catch (final IOException e) {
LOG.info("Exception mapping TCP server", e);
tempMapper = new MappedServerSocket() {
@Override
public boolean isPortMapped() {
return false;
}
@Override
public int getMappedPort() {
return 1;
}
@Override
public InetSocketAddress getHostAddress() {
return new InetSocketAddress(getMappedPort());
}
};
}
XmppUtils.setGlobalConfig(this.xmppUtil.xmppConfig());
XmppUtils.setGlobalProxyConfig(this.xmppUtil.xmppProxyConfig());
this.mappedServer = tempMapper;
this.started = true;
}
@Override
public void stop() {
LOG.info("Stopping XMPP handler...");
disconnect();
if (upnpService != null) {
upnpService.shutdown();
}
if (natPmpService != null) {
natPmpService.shutdown();
}
LOG.info("Finished stoppeding XMPP handler...");
}
@Subscribe
public void onAuthStatus(final GoogleTalkStateEvent ase) {
this.state = ase.getState();
switch (state) {
case connected:
// We wait until we're logged in before creating our roster.
final XMPPConnection conn = getP2PClient().getXmppConnection();
final org.jivesoftware.smack.Roster ros = conn.getRoster();
this.roster.onRoster(ros);
break;
case notConnected:
this.roster.reset();
break;
case connecting:
break;
case LOGIN_FAILED:
this.roster.reset();
break;
}
}
private void prepopulateProxies() {
// Add all the stored proxies.
final Collection<String> saved = this.model.getSettings().getProxies();
LOG.info("Proxy set is: {}", saved);
for (final String proxy : saved) {
// Don't use peer proxies since we're not connected to XMPP yet.
if (!proxy.contains("@")) {
LOG.info("Adding prepopulated proxy: {}", proxy);
addProxy(proxy);
}
}
}
@Override
public void connect() throws IOException, CredentialException,
NotInClosedBetaException {
if (!this.started) {
LOG.warn("Can't connect when not started!!");
throw new Error("Can't connect when not started!!");
}
if (!this.modelUtils.isConfigured()) {
if (this.model.getSettings().isUiEnabled()) {
LOG.info("Not connecting when not configured and UI enabled");
return;
}
}
LOG.info("Connecting to XMPP servers...");
if (this.model.getSettings().isUseGoogleOAuth2()) {
connectViaOAuth2();
} else {
//connectWithEmailAndPass();
throw new Error("Oauth not configured properly?");
}
}
private void connectViaOAuth2() throws IOException,
CredentialException, NotInClosedBetaException {
final XmppCredentials credentials =
this.modelUtils.newGoogleOauthCreds(getResource());
LOG.info("Logging in with credentials: {}", credentials);
connect(credentials);
}
@Override
public void connect(final String email, final String pass)
throws IOException, CredentialException, NotInClosedBetaException {
this.lastUserName = email;
this.lastPass = pass;
connect(new PasswordCredentials(email, pass, getResource()));
}
private String getResource() {
if (model.getSettings().isGetMode()) {
LOG.info("Setting ID for get mode...");
return "gmail.";
} else {
LOG.info("Setting ID for give mode");
return LanternConstants.UNCENSORED_ID;
}
}
public void connect(final XmppCredentials credentials)
throws IOException, CredentialException, NotInClosedBetaException {
LOG.debug("Connecting to XMPP servers with user name and password...");
this.closedBetaEvent = null;
final InetSocketAddress plainTextProxyRelayAddress =
new InetSocketAddress("127.0.0.1",
LanternUtils.PLAINTEXT_LOCALHOST_PROXY_PORT);
final SessionSocketListener sessionListener = new SessionSocketListener() {
@Override
public void reconnected() {
// We need to send a new presence message each time we
// reconnect to the XMPP server, as otherwise peers won't
// know we're available and we won't get data from the bot.
updatePresence();
}
@Override
public void onSocket(String arg0, Socket arg1) throws IOException {
}
};
this.client.set(P2P.newXmppP2PHttpClient("shoot", natPmpService,
upnpService, this.mappedServer,
this.socketsUtil.newTlsSocketFactory(), this.socketsUtil.newTlsServerSocketFactory(),
//SocketFactory.getDefault(), ServerSocketFactory.getDefault(),
plainTextProxyRelayAddress, sessionListener, false));
this.client.get().addConnectionListener(new P2PConnectionListener() {
@Override
public void onConnectivityEvent(final P2PConnectionEvent event) {
LOG.debug("Got connectivity event: {}", event);
Events.asyncEventBus().post(event);
}
});
// This is a global, backup listener added to the client. We might
// get notifications of messages twice in some cases, but that's
// better than the alternative of sometimes not being notified
// at all.
LOG.debug("Adding message listener...");
this.client.get().addMessageListener(typedListener);
Events.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.connecting));
try {
this.client.get().login(credentials);
LOG.debug("Sending connected event");
Events.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.connected));
} catch (final IOException e) {
// Note that the XMPP library will internally attempt to connect
// to our backup proxy if it can.
handleConnectionFailure();
throw e;
} catch (final IllegalStateException e) {
handleConnectionFailure();
throw e;
} catch (final CredentialException e) {
handleConnectionFailure();
throw e;
}
// Note we don't consider ourselves connected in get mode until we
// actually get proxies to work with.
final XMPPConnection connection = this.client.get().getXmppConnection();
final Collection<String> servers =
this.model.getSettings().getStunServers();
if (servers.isEmpty()) {
final Collection<InetSocketAddress> googleStunServers =
XmppUtils.googleStunServers(connection);
StunServerRepository.setStunServers(googleStunServers);
this.model.getSettings().setStunServers(
new HashSet<String>(toStringServers(googleStunServers)));
}
// Make sure all connections between us and the server are stored
// OTR.
LanternUtils.activateOtr(connection);
LOG.debug("Connection ID: {}", connection.getConnectionID());
// Here we handle allowing the server to subscribe to our presence.
connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(final Packet pack) {
final Presence pres = (Presence) pack;
LOG.debug("Processing packet!! {}", pres);
final String from = pres.getFrom();
LOG.debug("Responding to presence from {} and to {}",
from, pack.getTo());
final Type type = pres.getType();
// Allow subscription requests from the lantern bot.
if (from.startsWith("lanternctrl@") &&
from.endsWith("lanternctrl.appspotchat.com")) {
if (type == Type.subscribe) {
final Presence packet =
new Presence(Presence.Type.subscribed);
packet.setTo(from);
packet.setFrom(pack.getTo());
connection.sendPacket(packet);
} else {
LOG.info("Non-subscribe packet from hub? {}",
pres.toXML());
}
} else {
switch (type) {
case available:
return;
case error:
LOG.warn("Got error packet!! {}", pack.toXML());
return;
case subscribe:
LOG.info("Adding subscription request from: {}", from);
final boolean isLantern =
LanternUtils.isLanternMessage(pres);
// If we get a subscription request from someone
// already on our roster, auto-accept it.
if (isLantern) {
if (roster.autoAcceptSubscription(from)) {
subscribed(from);
}
roster.addIncomingSubscriptionRequest(pres);
}
break;
case subscribed:
break;
case unavailable:
return;
case unsubscribe:
LOG.info("Removing subscription request from: {}",from);
roster.removeIncomingSubscriptionRequest(from);
return;
case unsubscribed:
break;
}
}
}
}, new PacketFilter() {
@Override
public boolean accept(final Packet packet) {
if(packet instanceof Presence) {
return true;
} else {
LOG.debug("Not a presence packet: {}", packet.toXML());
}
return false;
}
});
gTalkSharedStatus();
updatePresence();
final boolean inClosedBeta =
waitForClosedBetaStatus(credentials.getUsername());
this.model.getConnectivity().setInvited(inClosedBeta);
// If we're in the closed beta and are an uncensored node, we want to
// advertise ourselves through the kaleidoscope trust network.
if (inClosedBeta && !censored.isCensored()) {
final TimerTask tt = new TimerTask() {
@Override
public void run() {
final TrustGraphNodeId tgnid = new BasicTrustGraphNodeId(
model.getNodeId());
final InetAddress address =
new PublicIpAddress().getPublicIpAddress();
final String user = connection.getUser();
// The payload here is JSON with everything from the
// JID of the user to the public IP address and port
// that should be mapped on the user's router.
final LanternKscopeAdvertisement ad;
if (mappedServer.isPortMapped()) {
ad = new LanternKscopeAdvertisement(user, address,
mappedServer.getMappedPort());
} else {
ad = new LanternKscopeAdvertisement(user);
}
// Now turn the advertisement into JSON.
final String payload = LanternUtils.jsonify(ad);
LOG.info("Sending kscope payload: {}", payload);
final BasicTrustGraphAdvertisement message =
new BasicTrustGraphAdvertisement(tgnid, payload, 0);
final TrustGraphNode tgn =
new LanternTrustGraphNode(DefaultXmppHandler.this);
tgn.advertiseSelf(message);
}
};
// We delay this to make sure we've successfully loaded all roster
// updates and presence notifications before sending out our
// advertisement.
this.timer.schedule(tt, 30000);
}
}
private void handleConnectionFailure() {
Events.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.LOGIN_FAILED));
}
private boolean waitForClosedBetaStatus(final String email)
throws NotInClosedBetaException {
if (this.modelUtils.isInClosedBeta(email)) {
LOG.debug("Already in closed beta...");
return true;
}
// The following is necessary because the call to login needs to either
// succeed or fail for the UI to work properly, but we don't know if
// a user is able to log in until we get an asynchronous XMPP message
// back from the server.
synchronized (this.closedBetaLock) {
if (this.closedBetaEvent == null) {
try {
this.closedBetaLock.wait(80 * 1000);
} catch (final InterruptedException e) {
LOG.info("Interrupted? Maybe on shutdown?", e);
}
}
}
if (this.closedBetaEvent != null) {
if(!this.closedBetaEvent.isInClosedBeta()) {
LOG.debug("Not in closed beta...");
notInClosedBeta("Not in closed beta");
} else {
LOG.info("Server notified us we're in the closed beta!");
return true;
}
} else {
LOG.warn("No closed beta event -- timed out!!");
notInClosedBeta("No closed beta event!!");
}
return false;
}
private void notInClosedBeta(final String msg)
throws NotInClosedBetaException {
//connectivityEvent(ConnectivityStatus.DISCONNECTED);
this.model.getConnectivity().setInvited(false);
disconnect();
throw new NotInClosedBetaException(msg);
}
private Set<String> toStringServers(
final Collection<InetSocketAddress> googleStunServers) {
final Set<String> strings = new HashSet<String>();
for (final InetSocketAddress isa : googleStunServers) {
strings.add(isa.getHostName()+":"+isa.getPort());
}
return strings;
}
@Override
public void disconnect() {
LOG.info("Disconnecting!!");
lastJson = "";
/*
LanternHub.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.LOGGING_OUT));
*/
final XmppP2PClient cl = this.client.get();
if (cl != null) {
this.client.get().logout();
this.client.set(null);
}
Events.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.notConnected));
proxyTracker.clearPeerProxySet();
this.closedBetaEvent = null;
// This is mostly logged for debugging thorny shutdown issues...
LOG.info("Finished disconnecting XMPP...");
}
private void processLanternHubMessage(final Message msg) {
LOG.debug("Lantern controlling agent response");
this.hubAddress = msg.getFrom();
final String to = XmppUtils.jidToUser(msg.getTo());
LOG.debug("Set hub address to: {}", hubAddress);
final String body = msg.getBody();
LOG.debug("Body: {}", body);
final Object obj = JSONValue.parse(body);
final JSONObject json = (JSONObject) obj;
final Long invites =
(Long) json.get(LanternConstants.INVITES_KEY);
if (invites != null) {
LOG.info("Setting invites to: {}", invites);
final int oldInvites = this.model.getNinvites();
final int newInvites = invites.intValue();
if (oldInvites != newInvites) {
this.model.setNinvites(newInvites);
Events.syncNInvites(invites.intValue());
}
}
final Boolean inClosedBeta =
(Boolean) json.get(LanternConstants.INVITED);
if (inClosedBeta != null) {
Events.asyncEventBus().post(new ClosedBetaEvent(to, inClosedBeta));
if (!inClosedBeta) {
//return;
}
} else {
Events.asyncEventBus().post(new ClosedBetaEvent(to, false));
//return;
}
final JSONArray servers =
(JSONArray) json.get(LanternConstants.SERVERS);
final Long delay =
(Long) json.get(LanternConstants.UPDATE_TIME);
LOG.debug("Server sent delay of: "+delay);
if (delay != null) {
final long now = System.currentTimeMillis();
final long elapsed = now - lastInfoMessageScheduled;
if (elapsed > 10000 && delay != 0L) {
lastInfoMessageScheduled = now;
timer.schedule(new TimerTask() {
@Override
public void run() {
updatePresence();
}
}, delay);
LOG.debug("Scheduled next info request in {} milliseconds",
delay);
} else {
LOG.debug("Ignoring duplicate info request scheduling- "+
"scheduled request {} milliseconds ago.", elapsed);
}
}
if (servers == null) {
LOG.debug("No servers in message");
} else {
final Iterator<String> iter = servers.iterator();
while (iter.hasNext()) {
final String server = iter.next();
addProxy(server);
}
}
// This is really a JSONObject, but that itself is a map.
final JSONObject update =
(JSONObject) json.get(LanternConstants.UPDATE_KEY);
if (update != null) {
LOG.info("About to propagate update...");
final Map<String, Object> event =
new HashMap<String, Object>();
event.putAll(update);
Events.asyncEventBus().post(new UpdateEvent(event));
}
}
@Subscribe
public void onClosedBetaEvent(final ClosedBetaEvent cbe) {
LOG.debug("Got closed beta event!!");
this.closedBetaEvent = cbe;
if (this.closedBetaEvent.isInClosedBeta()) {
this.modelUtils.addToClosedBeta(cbe.getTo());
}
synchronized (this.closedBetaLock) {
// We have to make sure that this event is actually intended for
// the user we're currently logged in as!
final String to = this.closedBetaEvent.getTo();
LOG.debug("Analyzing closed beta event for: {}", to);
if (isLoggedIn()) {
final String user = LanternUtils.toEmail(
this.client.get().getXmppConnection());
if (user.equals(to)) {
LOG.debug("Users match!");
this.closedBetaLock.notifyAll();
} else {
LOG.debug("Users don't match {}, {}", user, to);
}
}
}
}
private void gTalkSharedStatus() {
// This is for Google Talk compatibility. Surprising, all we need to
// do is grab our Google Talk shared status, signifying support for
// their protocol, and then we don't interfere with GChat visibility.
final Packet status = XmppUtils.getSharedStatus(
this.client.get().getXmppConnection());
LOG.info("Status:\n{}", status.toXML());
}
private String askForEmail() {
try {
System.out.print("Please enter your gmail e-mail, as in johndoe@gmail.com: ");
return LanternUtils.readLineCLI();
} catch (final IOException e) {
final String msg = "IO error trying to read your email address!";
System.out.println(msg);
LOG.error(msg, e);
throw new IllegalStateException(msg, e);
}
}
private String askForPassword() {
try {
System.out.print("Please enter your gmail password: ");
return new String(LanternUtils.readPasswordCLI());
} catch (IOException e) {
final String msg = "IO error trying to read your email address!";
System.out.println(msg);
LOG.error(msg, e);
throw new IllegalStateException(msg, e);
}
}
/**
* Updates the user's presence. We also include any stats updates in this
* message. Note that periodic presence updates are also used on the server
* side to verify which clients are actually available.
*
* We in part send presence updates instead of typical chat messages to
* get around these messages showing up in the user's gchat window.
*/
private void updatePresence() {
if (!isLoggedIn()) {
LOG.info("Not updating presence when we're not connected");
return;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
LOG.info("Sending presence available");
// OK, this is bizarre. For whatever reason, we **have** to send the
// following packet in order to get presence events from our peers.
// DO NOT REMOVE THIS MESSAGE!! See XMPP spec.
final Presence pres = new Presence(Presence.Type.available);
conn.sendPacket(pres);
final Presence forHub = new Presence(Presence.Type.available);
forHub.setTo(LanternConstants.LANTERN_JID);
//if (!LanternHub.settings().isGetMode()) {
final String str = LanternUtils.jsonify(stats);
LOG.debug("Reporting data: {}", str);
if (!this.lastJson.equals(str)) {
this.lastJson = str;
forHub.setProperty("stats", str);
stats.resetCumulativeStats();
} else {
LOG.info("No new stats to report");
}
//} else {
// LOG.info("Not reporting any stats in get mode");
conn.sendPacket(forHub);
}
/*
private void sendInfoRequest() {
// Send an "info" message to gather proxy data.
LOG.info("Sending INFO request");
final Message msg = new Message();
msg.setType(Type.chat);
//msg.setType(Type.normal);
msg.setTo(LanternConstants.LANTERN_JID);
msg.setFrom(this.client.getXmppConnection().getUser());
final JSONObject json = new JSONObject();
final StatsTracker statsTracker = LanternHub.statsTracker();
json.put(LanternConstants.COUNTRY_CODE, CensoredUtils.countryCode());
json.put(LanternConstants.BYTES_PROXIED,
statsTracker.getTotalBytesProxied());
json.put(LanternConstants.DIRECT_BYTES,
statsTracker.getDirectBytes());
json.put(LanternConstants.REQUESTS_PROXIED,
statsTracker.getTotalProxiedRequests());
json.put(LanternConstants.DIRECT_REQUESTS,
statsTracker.getDirectRequests());
json.put(LanternConstants.WHITELIST_ADDITIONS,
LanternUtils.toJsonArray(Whitelist.getAdditions()));
json.put(LanternConstants.WHITELIST_REMOVALS,
LanternUtils.toJsonArray(Whitelist.getRemovals()));
json.put(LanternConstants.VERSION_KEY, LanternConstants.VERSION);
final String str = json.toJSONString();
LOG.info("Reporting data: {}", str);
msg.setBody(str);
this.client.getXmppConnection().sendPacket(msg);
Whitelist.whitelistReported();
//statsTracker.clear();
}
*/
private void addPeerProxy(final URI peerUri) {
if (this.proxyTracker.addPeerProxy(peerUri)) {
sendAndRequestCert(peerUri);
}
}
@Subscribe
public void onUpdatePresenceEvent(final UpdatePresenceEvent upe) {
// This was originally added to decouple the roster from this class.
final Presence pres = upe.getPresence();
addOrRemovePeer(pres, pres.getFrom());
}
@Override
public void addOrRemovePeer(final Presence p, final String from) {
LOG.info("Processing peer: {}", from);
final URI uri;
try {
uri = new URI(from);
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", from);
return;
}
if (p.isAvailable()) {
LOG.info("Processing available peer");
// OK, we just request a certificate every time we get a present
// peer. If we get a response, this peer will be added to active
// peer URIs.
sendAndRequestCert(uri);
}
else {
LOG.info("Removing JID for peer '"+from);
this.proxyTracker.removePeer(uri);
}
}
private void processTypedMessage(final Message msg, final Integer type) {
final String from = msg.getFrom();
LOG.info("Processing typed message from {}", from);
switch (type) {
case (XmppMessageConstants.INFO_REQUEST_TYPE):
LOG.debug("Handling INFO request from {}", from);
processInfoData(msg);
sendInfoResponse(from);
break;
case (XmppMessageConstants.INFO_RESPONSE_TYPE):
LOG.debug("Handling INFO response from {}", from);
processInfoData(msg);
break;
case (LanternConstants.KSCOPE_ADVERTISEMENT):
LOG.debug("Handling KSCOPE ADVERTISEMENT");
final String payload =
(String) msg.getProperty(
LanternConstants.KSCOPE_ADVERTISEMENT_KEY);
if (StringUtils.isNotBlank(payload)) {
processKscopePayload(payload);
} else {
LOG.error("kscope ad with no payload? "+msg.toXML());
}
break;
default:
LOG.warn("Did not understand type: "+type);
break;
}
}
private void processKscopePayload(final String payload) {
final ObjectMapper mapper = new ObjectMapper();
try {
final LanternKscopeAdvertisement ad =
mapper.readValue(payload, LanternKscopeAdvertisement.class);
// If the ad includes a mapped port, include it as straight proxy.
if (ad.hasMappedEndpoint()) {
final String proxy = ad.getAddress() + ":" + ad.getPort();
this.proxyTracker.addGeneralProxy(proxy);
}
addPeerProxy(new URI(ad.getJid()));
} catch (final JsonParseException e) {
LOG.warn("Could not parse JSON", e);
} catch (final JsonMappingException e) {
LOG.warn("Could not map JSON", e);
} catch (final IOException e) {
LOG.warn("IO error parsing JSON", e);
} catch (final URISyntaxException e) {
LOG.error("Syntax exception with URI?", e);
}
}
private void sendInfoResponse(final String from) {
final Message msg = new Message();
// The from becomes the to when we're responding.
msg.setTo(from);
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_RESPONSE_TYPE);
msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress());
msg.setProperty(P2PConstants.CERT, this.keyStoreManager.getBase64Cert());
this.client.get().getXmppConnection().sendPacket(msg);
}
private void processInfoData(final Message msg) {
LOG.info("Processing INFO data from request or response.");
final URI uri;
try {
uri = new URI(msg.getFrom());
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", msg.getFrom());
return;
}
final String mac = (String) msg.getProperty(P2PConstants.MAC);
final String base64Cert = (String) msg.getProperty(P2PConstants.CERT);
LOG.info("Base 64 cert: {}", base64Cert);
if (StringUtils.isNotBlank(base64Cert)) {
LOG.info("Got certificate:\n"+
new String(Base64.decodeBase64(base64Cert)));
try {
// Add the peer if we're able to add the cert.
this.keyStoreManager.addBase64Cert(mac, base64Cert);
if (this.model.getSettings().isAutoConnectToPeers()) {
final String email = XmppUtils.jidToUser(msg.getFrom());
if (this.roster.isFullyOnRoster(email)) {
trustedPeerProxyManager.onPeer(uri);
} else {
anonymousPeerProxyManager.onPeer(uri);
}
/*
if (LanternHub.getTrustedContactsManager().isTrusted(msg)) {
LanternHub.trustedPeerProxyManager().onPeer(uri);
} else {
LanternHub.anonymousPeerProxyManager().onPeer(uri);
}
*/
}
} catch (final IOException e) {
LOG.error("Could not add cert??", e);
}
} else {
LOG.error("No cert for peer?");
}
}
private void addProxy(final String cur) {
LOG.info("Considering proxy: {}", cur);
if (cur.contains("appspot")) {
this.proxyTracker.addLaeProxy(cur);
return;
}
if (!cur.contains("@")) {
this.proxyTracker.addGeneralProxy(cur);
return;
}
if (!isLoggedIn()) {
LOG.info("Not connected -- ignoring proxy: {}", cur);
return;
}
final String jid =
this.client.get().getXmppConnection().getUser().trim();
final String emailId = XmppUtils.jidToUser(jid);
LOG.info("We are: {}", jid);
LOG.info("Service name: {}",
this.client.get().getXmppConnection().getServiceName());
if (jid.equals(cur.trim())) {
LOG.info("Not adding ourselves as a proxy!!");
return;
}
if (cur.startsWith(emailId+"/")) {
try {
addPeerProxy(new URI(cur));
} catch (final URISyntaxException e) {
LOG.error("Error with proxy URI", e);
}
} else if (cur.contains("@")) {
try {
addPeerProxy(new URI(cur));
} catch (final URISyntaxException e) {
LOG.error("Error with proxy URI", e);
}
}
}
private void sendAndRequestCert(final URI cur) {
LOG.info("Requesting cert from {}", cur);
final Message msg = new Message();
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_REQUEST_TYPE);
msg.setTo(cur.toASCIIString());
// Set our certificate in the request as well -- we want to make
// extra sure these get through!
msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress());
msg.setProperty(P2PConstants.CERT, this.keyStoreManager.getBase64Cert());
this.client.get().getXmppConnection().sendPacket(msg);
}
/*
@Override
public PeerProxyManager getAnonymousPeerProxyManager() {
return LanternHub.anonymousPeerProxyManager();
}
@Override
public PeerProxyManager getTrustedPeerProxyManager() {
return LanternHub.trustedPeerProxyManager();
}
*/
@Override
public XmppP2PClient getP2PClient() {
return client.get();
}
@Override
public boolean isLoggedIn() {
if (this.client.get() == null) {
return false;
}
final XMPPConnection conn = client.get().getXmppConnection();
if (conn == null) {
return false;
}
return conn.isAuthenticated();
}
@Override
public void sendInvite(final String email) {
LOG.info("Sending invite");
if (StringUtils.isBlank(this.hubAddress)) {
LOG.error("Blank hub address when sending invite?");
return;
}
final Set<String> invited = roster.getInvited();
if (invited.contains(email)) {
LOG.info("Already invited");
return;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final Presence pres = new Presence(Presence.Type.available);
pres.setTo(LanternConstants.LANTERN_JID);
// "emails" of the form xxx@public.talk.google.com aren't really
// e-mail addresses at all, so don't send 'em.
// In theory we might be able to use the Google Plus API to get
// actual e-mail addresses -- see:
if (LanternUtils.isNotJid(email)) {
pres.setProperty(LanternConstants.INVITED_EMAIL, email);
} else {
pres.setProperty(LanternConstants.INVITED_EMAIL, "");
}
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
final String name = entry.getName();
if (StringUtils.isNotBlank(name)) {
pres.setProperty(LanternConstants.INVITEE_NAME, name);
}
}
final Profile prof = this.model.getProfile();
pres.setProperty(LanternConstants.INVITER_NAME, prof.getName());
final String json = LanternUtils.jsonify(prof);
pres.setProperty(XmppMessageConstants.PROFILE, json);
invited.add(email);
//pres.setProperty(LanternConstants.INVITER_NAME, value);
final Runnable runner = new Runnable() {
@Override
public void run() {
conn.sendPacket(pres);
}
};
final Thread t = new Thread(runner, "Invite-Thread");
t.setDaemon(true);
t.start();
this.model.setNinvites(this.model.getNinvites() - 1);
this.modelIo.write();
//LanternHub.settings().setInvites(LanternHub.settings().getInvites()-1);
//LanternHub.settingsIo().write();
addToRoster(email);
}
@Override
public void subscribe(final String jid) {
LOG.info("Sending subscribe message to: {}", jid);
final Presence packet = new Presence(Presence.Type.subscribe);
packet.setTo(jid);
final String json = LanternUtils.jsonify(this.model.getProfile());
packet.setProperty(XmppMessageConstants.PROFILE, json);
final XMPPConnection conn = this.client.get().getXmppConnection();
conn.sendPacket(packet);
}
@Override
public void subscribed(final String jid) {
LOG.info("Sending subscribe message to: {}", jid);
sendTypedPacket(jid, Presence.Type.subscribed);
roster.removeIncomingSubscriptionRequest(jid);
}
@Override
public void unsubscribe(final String jid) {
LOG.info("Sending unsubscribe message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribe);
}
@Override
public void unsubscribed(final String jid) {
LOG.info("Sending unsubscribed message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribed);
roster.removeIncomingSubscriptionRequest(jid);
}
private void sendTypedPacket(final String jid, final Type type) {
final Presence packet = new Presence(type);
packet.setTo(jid);
final XMPPConnection conn = this.client.get().getXmppConnection();
conn.sendPacket(packet);
}
@Override
public void addToRoster(final String email) {
// If the user is not already on our roster, we want to make sure to
// send them an invite. If the e-mail address specified does not
// correspond with a Jabber ID, then we're out of luck. If it does,
// then this will send the roster invite.
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry == null) {
LOG.info("Inviting user to join roster: {}", email);
try {
// Note this also sends a subscription request!!
rost.createEntry(email,
StringUtils.substringBefore(email, "@"), new String[]{});
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
}
}
@Override
public void removeFromRoster(final String email) {
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
LOG.info("Removing user from roster: {}", email);
try {
rost.removeEntry(entry);
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
}
}
private void setupJmx() {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
final Class<? extends Object> clazz = getClass();
final String pack = clazz.getPackage().getName();
final String oName =
pack+":type="+clazz.getSimpleName()+"-"+clazz.getSimpleName();
LOG.info("Registering MBean with name: {}", oName);
final ObjectName mxBeanName = new ObjectName(oName);
if(!mbs.isRegistered(mxBeanName)) {
mbs.registerMBean(this, mxBeanName);
}
} catch (final MalformedObjectNameException e) {
LOG.error("Could not set up JMX", e);
} catch (final InstanceAlreadyExistsException e) {
LOG.error("Could not set up JMX", e);
} catch (final MBeanRegistrationException e) {
LOG.error("Could not set up JMX", e);
} catch (final NotCompliantMBeanException e) {
LOG.error("Could not set up JMX", e);
}
}
@Subscribe
public void onReset(final ResetEvent event) {
disconnect();
}
} |
package org.lightmare.ejb;
import static org.lightmare.ejb.meta.MetaContainer.getMetaData;
import static org.lightmare.jpa.JPAManager.getConnection;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.handlers.BeanLocalHandler;
import org.lightmare.ejb.meta.MetaData;
import org.lightmare.ejb.startup.MetaCreator;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.remote.rpc.RPCall;
/**
* Connector class for get ejb beans or call remotely procedure in ejb bean
* (RPC) by interface class
*
* @author Levan
*
*/
public class EjbConnector {
/**
* Gets connection for {@link Stateless} bean {@link Class} from cache
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
private EntityManagerFactory getEntityManagerFactory(MetaData metaData) {
String unitName = metaData.getUnitName();
if (unitName == null || unitName.isEmpty()) {
return null;
}
EntityManagerFactory emf = getConnection(unitName);
return emf;
}
@SuppressWarnings("unchecked")
private <T> T getBeanInstance(MetaData metaData)
throws InstantiationException, IllegalAccessException {
Class<? extends T> beanClass = (Class<? extends T>) metaData
.getBeanClass();
T beanInstance = beanClass.newInstance();
return beanInstance;
}
private <T> InvocationHandler getHandler(MetaData metaData)
throws InstantiationException, IllegalAccessException {
LibraryLoader.loadCurrentLibraries(metaData.getLoader());
T beanInstance = getBeanInstance(metaData);
EntityManagerFactory emf = getEntityManagerFactory(metaData);
Field connectorField = metaData.getConnectorField();
InvocationHandler handler = new BeanHandler(connectorField,
beanInstance, emf);
return handler;
}
@SuppressWarnings("unchecked")
public <T> T connectToBean(String beanName, Class<T> interfaceClass,
Object... rpcArgs) throws IOException {
InvocationHandler handler;
Configuration configuration = MetaCreator.configuration;
if (configuration.isServer()) {
MetaData metaData = getMetaData(beanName);
try {
handler = getHandler(metaData);
} catch (InstantiationException ex) {
throw new IOException(ex);
} catch (IllegalAccessException ex) {
throw new IOException(ex);
}
} else {
if (rpcArgs.length != 2) {
throw new IOException(
"Could not resolve host and port arguments");
}
String host = (String) rpcArgs[0];
int port = (Integer) rpcArgs[1];
handler = new BeanLocalHandler(new RPCall(host, port));
}
Class<?>[] interfaceArray = { interfaceClass };
T beanInstance = (T) Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), interfaceArray, handler);
return beanInstance;
}
} |
package org.lightmare.ejb;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.handlers.BeanHandlerFactory;
import org.lightmare.ejb.handlers.BeanLocalHandlerFactory;
import org.lightmare.ejb.handlers.RestHandler;
import org.lightmare.ejb.handlers.RestHandlerFactory;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.RpcUtils;
import org.lightmare.utils.StringUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Connector class for get EJB beans or call remote procedure in this bean (RPC)
* by interface class
*
* @author Levan
* @since 0.0.15-SNAPSHOT
*/
public class EjbConnector {
/**
* Gets {@link MetaData} from {@link MetaContainer} if it is not locked or
* waits while {@link MetaData#isInProgress()} is true
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
private MetaData getMeta(String beanName) throws IOException {
MetaData metaData = MetaContainer.getSyncMetaData(beanName);
return metaData;
}
/**
* Gets connection for {@link javax.ejb.Stateless} bean {@link Class} from
* cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactory(ConnectionData connection)
throws IOException {
if (connection.getEmf() == null) {
String unitName = connection.getUnitName();
if (StringUtils.valid(unitName)) {
ConnectionSemaphore semaphore = ConnectionContainer
.getConnection(unitName);
connection.setConnection(semaphore);
}
}
}
/**
* Gets connections for {@link Stateless} bean {@link Class} from cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void setEntityManagerFactories(MetaData metaData)
throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
setEntityManagerFactory(connection);
}
}
}
/**
* Instantiates bean by class
*
* @param metaData
* @return <code>T</code> Bean instance
* @throws IOException
*/
private <T> T getBeanInstance(MetaData metaData) throws IOException {
Class<? extends T> beanClass = ObjectUtils
.cast(metaData.getBeanClass());
T beanInstance = MetaUtils.instantiate(beanClass);
return beanInstance;
}
/**
* Creates {@link InvocationHandler} implementation for server mode
*
* @param metaData
* @return {@link InvocationHandler}
* @throws IOException
*/
private <T> BeanHandler getBeanHandler(MetaData metaData)
throws IOException {
T beanInstance = getBeanInstance(metaData);
// Caches EnriryManagerFactory instances in MetaData if they are not
// cached yet
setEntityManagerFactories(metaData);
// Initializes BeanHandler instance and caches it in MetaData if it was
// not cached yet
BeanHandler handler = BeanHandlerFactory.get(metaData, beanInstance);
return handler;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaces
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T>[] interfaces,
InvocationHandler handler, ClassLoader loader) {
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
} else {
LibraryLoader.loadCurrentLibraries(loader);
}
Object instance = Proxy.newProxyInstance(loader, interfaces, handler);
T beanInstance = ObjectUtils.cast(instance);
return beanInstance;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaceClass
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T> interfaceClass,
InvocationHandler handler, ClassLoader loader) {
Class<T>[] interfaceArray = ObjectUtils
.cast(new Class<?>[] { interfaceClass });
T beanInstance = instatiateBean(interfaceArray, handler, loader);
return beanInstance;
}
/**
* Initializes and caches all interfaces for bean class from passed
* {@link MetaData} instance if it is not already cached
*
* @param metaData
* @return {@link Class}[]
*/
private Class<?>[] setInterfaces(MetaData metaData) {
Class<?>[] interfaceClasses = metaData.getInterfaceClasses();
if (CollectionUtils.invalid(interfaceClasses)) {
List<Class<?>> interfacesList = new ArrayList<Class<?>>();
Class<?>[] interfaces = metaData.getLocalInterfaces();
if (CollectionUtils.valid(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
interfaces = metaData.getRemoteInterfaces();
if (CollectionUtils.valid(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
int size = interfacesList.size();
interfaceClasses = interfacesList.toArray(new Class[size]);
metaData.setInterfaceClasses(interfaceClasses);
}
return interfaceClasses;
}
/**
* Creates appropriate bean {@link Proxy} instance by passed
* {@link MetaData} parameter
*
* @param metaData
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(MetaData metaData) throws IOException {
InvocationHandler handler = getBeanHandler(metaData);
Class<?>[] interfaces = setInterfaces(metaData);
Class<T>[] typedInterfaces = ObjectUtils.cast(interfaces);
ClassLoader loader = metaData.getLoader();
T beanInstance = instatiateBean(typedInterfaces, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface {@link Class} instance
*
* @param interfaceClass
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, Class<T> interfaceClass,
Object... rpcArgs) throws IOException {
T beanInstance;
InvocationHandler handler;
ClassLoader loader;
if (Configuration.isServer()) {
MetaData metaData = getMeta(beanName);
setInterfaces(metaData);
handler = getBeanHandler(metaData);
loader = metaData.getLoader();
} else {
if (rpcArgs.length == RpcUtils.RPC_ARGS_LENGTH) {
handler = BeanLocalHandlerFactory.get(rpcArgs);
loader = null;
} else {
throw new IOException(RpcUtils.RPC_ARGS_ERROR);
}
}
beanInstance = instatiateBean(interfaceClass, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface name
*
* @param beanName
* @param interfaceName
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, String interfaceName,
Object... rpcArgs) throws IOException {
T beanInstance;
MetaData metaData = getMeta(beanName);
ClassLoader loader = metaData.getLoader();
Class<?> classForName = MetaUtils.classForName(interfaceName,
Boolean.FALSE, loader);
Class<T> interfaceClass = ObjectUtils.cast(classForName);
beanInstance = connectToBean(beanName, interfaceClass, rpcArgs);
return beanInstance;
}
/**
* Creates {@link RestHandler} instance for invoking bean methods by REST
* services
*
* @param metaData
* @return {@link RestHandler}
* @throws IOException
*/
public <T> RestHandler<T> createRestHandler(MetaData metaData)
throws IOException {
RestHandler<T> restHandler;
BeanHandler handler = getBeanHandler(metaData);
Class<T> beanClass = ObjectUtils.cast(metaData.getBeanClass());
T beanInstance = MetaUtils.instantiate(beanClass);
restHandler = RestHandlerFactory.get(handler, beanInstance);
return restHandler;
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice;
import org.myrobotlab.service.config.InMoov2Config;
import org.myrobotlab.service.config.ServiceConfig;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.IKJointAngleListener;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.Simulator;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider, IKJointAngleListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2.class);
public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>();
/**
* these should be methods like setRobotCanMoveBodyRandom(true) - which do
* what they need and then set config NOT STATIC PUBLIC VARS
*/
@Deprecated
public static boolean RobotCanMoveBodyRandom = true;
public static boolean isRobotCanMoveBodyRandom() {
return RobotCanMoveBodyRandom;
}
public static void setRobotCanMoveBodyRandom(boolean robotCanMoveBodyRandom) {
RobotCanMoveBodyRandom = robotCanMoveBodyRandom;
}
public static boolean isRobotCanMoveHeadRandom() {
return RobotCanMoveHeadRandom;
}
public static void setRobotCanMoveHeadRandom(boolean robotCanMoveHeadRandom) {
RobotCanMoveHeadRandom = robotCanMoveHeadRandom;
}
public static boolean isRobotCanMoveEyesRandom() {
return RobotCanMoveEyesRandom;
}
public static void setRobotCanMoveEyesRandom(boolean robotCanMoveEyesRandom) {
RobotCanMoveEyesRandom = robotCanMoveEyesRandom;
}
public static boolean isRobotCanMoveRandom() {
return RobotCanMoveRandom;
}
public static void setRobotCanMoveRandom(boolean robotCanMoveRandom) {
RobotCanMoveRandom = robotCanMoveRandom;
}
public static boolean isRobotIsSleeping() {
return RobotIsSleeping;
}
public static void setRobotIsSleeping(boolean robotIsSleeping) {
RobotIsSleeping = robotIsSleeping;
}
public static boolean isRobotIsStarted() {
return RobotIsStarted;
}
public static void setRobotIsStarted(boolean robotIsStarted) {
RobotIsStarted = robotIsStarted;
}
@Deprecated
public static boolean RobotCanMoveHeadRandom = true;
@Deprecated
public static boolean RobotCanMoveEyesRandom = true;
@Deprecated
public static boolean RobotCanMoveRandom = true;
@Deprecated
public static boolean RobotIsSleeping = false;
@Deprecated
public static boolean RobotIsStarted = false;
private static final long serialVersionUID = 1L;
static String speechRecognizer = "WebkitSpeechRecognition";
protected boolean loadGestures = true;
InMoov2Config config = new InMoov2Config();
/**
* @param someScriptName
* execute a resource script
* @return success or failure
*/
public boolean execScript(String someScriptName) {
try {
Python p = (Python) Runtime.start("python", "Python");
String script = getResourceAsString(someScriptName);
return p.exec(script, true);
} catch (Exception e) {
error("unable to execute script %s", someScriptName);
return false;
}
}
/**
* Single place for InMoov2 service to execute arbitrary code - needed
* initially to set "global" vars in python
*
* @param pythonCode
* @return
*/
public boolean exec(String pythonCode) {
try {
Python p = (Python) Runtime.start("python", "Python");
return p.exec(pythonCode, true);
} catch (Exception e) {
error("unable to execute script %s", pythonCode);
return false;
}
}
/**
* Part of service life cycle - a new servo has been started
*/
public void onStarted(String fullname) {
log.info("{} started", fullname);
try {
ServiceInterface si = Runtime.getService(fullname);
if ("Servo".equals(si.getSimpleName())) {
log.info("sending setAutoDisable true to {}", fullname);
send(fullname, "setAutoDisable", true);
// ServoControl sc = (ServoControl)Runtime.getService(name);
}
} catch (Exception e) {
log.error("onStarted threw", e);
}
}
public void startService() {
super.startService();
Runtime runtime = Runtime.getInstance();
// FIXME - shouldn't need this anymore
Runtime.getInstance().attachServiceLifeCycleListener(getName());
try {
// copy config if it doesn't already exist
String resourceBotDir = FileIO.gluePaths(getResourceDir(), "config");
List<File> files = FileIO.getFileList(resourceBotDir);
for (File f : files) {
String botDir = "data/config/" + f.getName();
File bDir = new File(botDir);
if (bDir.exists() || !f.isDirectory()) {
log.info("skipping data/config/{}", botDir);
} else {
log.info("will copy new data/config/{}", botDir);
try {
FileIO.copy(f.getAbsolutePath(), botDir);
} catch (Exception e) {
error(e);
}
}
}
// copy (if they don't already exist) the chatbots which came with InMoov2
resourceBotDir = FileIO.gluePaths(getResourceDir(), "chatbot/bots");
files = FileIO.getFileList(resourceBotDir);
for (File f : files) {
String botDir = "data/ProgramAB/" + f.getName();
if (new File(botDir).exists()) {
log.info("found data/ProgramAB/{} not copying", botDir);
} else {
log.info("will copy new data/ProgramAB/{}", botDir);
try {
FileIO.copy(f.getAbsolutePath(), botDir);
} catch (Exception e) {
error(e);
}
}
}
} catch (Exception e) {
error(e);
}
if (loadGestures) {
loadGestures();
}
runtime.invoke("publishConfigList");
}
public void onCreated(String fullname) {
log.info("{} created", fullname);
}
/**
* This method will load a python file into the python interpreter.
*
* @param file
* file to load
* @return success/failure
*/
@Deprecated /* use execScript - this doesn't handle resources correctly */
public static boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
boolean result = false;
try {
// This will open a gazillion tabs in InMoov
// result = p.execFile(f.getAbsolutePath(), true);
// old way - not using execFile :(
String script = FileIO.toString(f.getAbsolutePath());
result = p.exec(script, true);
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
boolean autoStartBrowser = false;
transient ProgramAB chatBot;
String currentConfigurationName = "default";
transient SpeechRecognizer ear;
transient OpenCV opencv;
transient Tracking eyesTracking;
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
// FIXME - what the hell is this for ?
Set<String> gestures = new TreeSet<String>();
transient InMoov2Head head;
transient Tracking headTracking;
transient HtmlFilter htmlFilter;
transient UltrasonicSensor ultrasonicRight;
transient UltrasonicSensor ultrasonicLeft;
transient Pir pir;
transient ImageDisplay imageDisplay;
/**
* simple booleans to determine peer state of existence FIXME - should be an
* auto-peer variable
*
* FIXME - sometime in the future there should just be a single simple
* reference to a loaded "config" but at the moment the new UI depends on
* these individual values :(
*
*/
boolean isChatBotActivated = false;
boolean isEarActivated = false;
boolean isOpenCvActivated = false;
boolean isEyeLidsActivated = false;
boolean isHeadActivated = false;
boolean isLeftArmActivated = false;
boolean isLeftHandActivated = false;
boolean isMouthActivated = false;
// adding to the problem :( :( :(
boolean isAudioPlayerActivated = true;
boolean isRightArmActivated = false;
boolean isRightHandActivated = false;
boolean isSimulatorActivated = false;
boolean isTorsoActivated = false;
boolean isNeopixelActivated = false;
boolean isPirActivated = false;
boolean isUltrasonicRightActivated = false;
boolean isUltrasonicLeftActivated = false;
boolean isServoMixerActivated = false;
boolean isController3Activated = false;
// TODO - refactor into a Simulator interface when more simulators are borgd
transient JMonkeyEngine simulator;
String lastGestureExecuted;
Long lastPirActivityTime;
transient InMoov2Arm leftArm;
transient InMoov2Hand leftHand;
/**
* supported locales
*/
Map<String, Locale> locales = null;
int maxInactivityTimeSeconds = 120;
transient SpeechSynthesis mouth;
// FIXME ugh - new MouthControl service that uses AudioFile output
transient public MouthControl mouthControl;
boolean mute = false;
transient NeoPixel neopixel;
transient ServoMixer servoMixer;
transient Python python;
transient InMoov2Arm rightArm;
transient InMoov2Hand rightHand;
transient InMoov2Torso torso;
@Deprecated
public Vision vision;
// FIXME - remove all direct references
// transient private HashMap<String, InMoov2Arm> arms = new HashMap<>();
protected List<Voice> voices = null;
protected String voiceSelected;
transient WebGui webgui;
protected List<String> configList;
private boolean isController4Activated;
private boolean isLeftHandSensorActivated;
private boolean isLeftPortActivated;
private boolean isRightHandSensorActivated;
private boolean isRightPortActivated;
public InMoov2(String n, String id) {
super(n, id);
// InMoov2 has a huge amount of peers
setAutoStartPeers(false);
// by default all servos will auto-disable
// Servo.setAutoDisableDefault(true); //until peer servo services for
// InMoov2 have the auto disable behavior, we should keep this
// same as created in runtime - send asyc message to all
// registered services, this service has started
// find all servos - set them all to autoDisable(true)
// onStarted(name) will handle all future created servos
List<ServiceInterface> services = Runtime.getServices();
for (ServiceInterface si : services) {
if ("Servo".equals(si.getSimpleName())) {
send(si.getFullName(), "setAutoDisable", true);
}
}
// dynamically gotten from filesystem/bots ?
locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT", "tr-TR");
locale = Runtime.getInstance().getLocale();
// REALLY NEEDS TO BE CLEANED UP - no direct references
// "publish" scripts which should be executed :(
// python = (Python) startPeer("python");
python = (Python) Runtime.start("python", "Python"); // this crud should
// stop
// load(locale.getTag()); WTH ?
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
subscribe(r.getName(), "publishConfigList");
// FIXME - Framework should auto-magically auto-start peers AFTER
// construction - unless explicitly told not to
// peers to start on construction
// imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
@Override /* local strong type - is to be avoided - use name string */
public void addTextListener(TextListener service) {
// CORRECT WAY ! - no direct reference - just use the name in a subscription
addListener("publishText", service.getName());
}
@Override
public void attachTextListener(TextListener service) {
attachTextListener(service.getName());
}
/**
* comes in from runtime which owns the config list
*
* @param configList
* list of configs
*/
public void onConfigList(List<String> configList) {
this.configList = configList;
invoke("publishConfigList");
}
/**
* "re"-publishing runtime config list, because I don't want to fix the js
* subscribeTo :P
*
* @return list of config names
*/
public List<String> publishConfigList() {
return configList;
}
public void attachTextPublisher(String name) {
subscribe(name, "publishText");
}
@Override
public void attachTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
public void closeAllImages() {
// imageDisplay.closeAll();
log.error("implement webgui.closeAllImages");
}
public void cycleGestures() {
// if not loaded load -
// FIXME - this needs alot of "help" :P
// WHY IS THIS DONE ?
if (gestures.size() == 0) {
loadGestures();
}
for (String gesture : gestures) {
try {
String methodName = gesture.substring(0, gesture.length() - 3);
speakBlocking(methodName);
log.info("executing gesture {}", methodName);
python.eval(methodName + "()");
// wait for finish - or timeout ?
} catch (Exception e) {
error(e);
}
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
}
public void displayFullScreen(String src) {
try {
if (imageDisplay == null) {
imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
imageDisplay.displayFullScreen(src);
log.error("implement webgui.displayFullScreen");
} catch (Exception e) {
error("could not display picture %s", src);
}
}
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
}
/**
* This method will try to launch a python command with error handling
*
* @param gesture
* the gesture
* @return gesture result
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
public void fullSpeed() {
if (head != null) {
head.fullSpeed();
}
if (rightHand != null) {
rightHand.fullSpeed();
}
if (leftHand != null) {
leftHand.fullSpeed();
}
if (rightArm != null) {
rightArm.fullSpeed();
}
if (leftArm != null) {
leftArm.fullSpeed();
}
if (torso != null) {
torso.fullSpeed();
}
}
public String get(String key) {
String ret = localize(key);
if (ret != null) {
return ret;
}
return "not yet translated";
}
public InMoov2Arm getArm(String side) {
if ("left".equals(side)) {
return leftArm;
} else if ("right".equals(side)) {
return rightArm;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Hand getHand(String side) {
if ("left".equals(side)) {
return leftHand;
} else if ("right".equals(side)) {
return rightHand;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Head getHead() {
return head;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (lastPirActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public InMoov2Arm getLeftArm() {
return leftArm;
}
public InMoov2Hand getLeftHand() {
return leftHand;
}
@Override
public Map<String, Locale> getLocales() {
return locales;
}
public InMoov2Arm getRightArm() {
return rightArm;
}
public InMoov2Hand getRightHand() {
return rightHand;
}
public Simulator getSimulator() {
return simulator;
}
public InMoov2Torso getTorso() {
return torso;
}
public void halfSpeed() {
if (head != null) {
head.setSpeed(25.0, 25.0, 25.0, 25.0, 100.0, 25.0);
}
if (rightHand != null) {
rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setSpeed(20.0, 20.0, 20.0);
}
}
public boolean isCameraOn() {
if (opencv != null) {
if (opencv.isCapturing()) {
return true;
}
}
return false;
}
public boolean isEyeLidsActivated() {
return isEyeLidsActivated;
}
public boolean isHeadActivated() {
return isHeadActivated;
}
public boolean isLeftArmActivated() {
return isLeftArmActivated;
}
public boolean isLeftHandActivated() {
return isLeftHandActivated;
}
public boolean isMute() {
return mute;
}
public boolean isNeopixelActivated() {
return isNeopixelActivated;
}
public boolean isRightArmActivated() {
return isRightArmActivated;
}
public boolean isRightHandActivated() {
return isRightHandActivated;
}
public boolean isTorsoActivated() {
return isTorsoActivated;
}
public boolean isPirActivated() {
return isPirActivated;
}
public boolean isUltrasonicRightActivated() {
return isUltrasonicRightActivated;
}
public boolean isUltrasonicLeftActivated() {
return isUltrasonicLeftActivated;
}
// by default all servos will auto-disable
// TODO: KW : make peer servo services for InMoov2 have the auto disable
// behavior.
// Servo.setAutoDisableDefault(true);
public boolean isServoMixerActivated() {
return isServoMixerActivated;
}
public void loadGestures() {
loadGestures(getResourceDir() + fs + "gestures");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
* @return true/false
*/
public boolean loadGestures(String directory) {
speakBlocking(get("STARTINGGESTURES"));
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = new File(directory);
dir.mkdirs();
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
String methodName = f.getName().substring(0, f.getName().length() - 3) + "()";
gestures.add(methodName);
} else {
error("could not load %s", f.getName());
totalError += 1;
}
} else {
log.info("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
broadcastState();
if (totalError > 0) {
speakAlert(get("GESTURE_ERROR"));
return false;
}
return true;
}
public void cameraOff() {
if (opencv != null) {
opencv.stopCapture();
opencv.disableAll();
}
}
public void cameraOn() {
try {
if (opencv == null) {
startOpenCV();
}
opencv.capture();
} catch (Exception e) {
error(e);
}
}
public void moveLeftArm(Double bicep, Double rotate, Double shoulder, Double omoplate) {
moveArm("left", bicep, rotate, shoulder, omoplate);
}
public void moveRightArm(Double bicep, Double rotate, Double shoulder, Double omoplate) {
moveArm("right", bicep, rotate, shoulder, omoplate);
}
public void moveArm(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
info("%s arm not started", which);
return;
}
arm.moveTo(bicep, rotate, shoulder, omoplate);
}
public void moveEyelids(Double eyelidleftPos, Double eyelidrightPos) {
if (head != null) {
head.moveEyelidsTo(eyelidleftPos, eyelidrightPos);
} else {
log.warn("moveEyelids - I have a null head");
}
}
public void moveEyes(Double eyeX, Double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.warn("moveEyes - I have a null head");
}
}
public void moveRightHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
moveHand("right", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveRightHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
moveHand("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void moveLeftHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
moveHand("left", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveLeftHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
moveHand("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
log.warn("{} hand does not exist", hand);
return;
}
hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveHead(Double neck, Double rothead) {
moveHead(neck, rothead, null, null, null, null);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(rollNeck, rothead, null, null, null, rollNeck);
}
public void moveHead(Integer neck, Integer rothead, Integer rollNeck) {
moveHead((double) rollNeck, (double) rothead, null, null, null, (double) rollNeck);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveHeadBlocking(Double neck, Double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
public OpenCVData onOpenCVData(OpenCVData data) {
return data;
}
@Override
public void onText(String text) {
// FIXME - we should be able to "re"-publish text but text is coming from
// different sources
// some might be coming from the ear - some from the mouth ... - there has
// to be a distinction
log.info("onText - {}", text);
invoke("publishText", text);
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
/**
* all published text from InMoov2 - including ProgramAB
*/
@Override
public String publishText(String text) {
return text;
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
// FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest
public void rest() {
log.info("InMoov2.rest()");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
}
public void setLeftArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed("left", bicep, rotate, shoulder, omoplate);
}
public void setLeftArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) {
setArmSpeed("left", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate);
}
public void setRightArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed("right", bicep, rotate, shoulder, omoplate);
}
public void setRightArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) {
setArmSpeed("right", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate);
}
public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
warn("%s arm not started", which);
return;
}
arm.setSpeed(bicep, rotate, shoulder, omoplate);
}
@Deprecated
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed(which, bicep, rotate, shoulder, omoplate);
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
/*
* if (eyelids != null) { eyelids.setAutoDisable(param); }
*/
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setLeftHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed("left", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setLeftHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
setHandSpeed("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void setRightHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed("right", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setRightHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
setHandSpeed("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
warn("%s hand not started", which);
return;
}
hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
public void setHeadSpeed(Integer rothead, Integer neck, Integer rollNeck) {
setHeadSpeed((double) rothead, (double) neck, null, null, null, (double) rollNeck);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head == null) {
warn("setHeadSpeed - head not started");
return;
}
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Override
public void setLocale(String code) {
if (code == null) {
log.warn("setLocale null");
return;
}
// filter of the set of supported locales
if (!Locale.hasLanguage(locales, code)) {
error("InMoov does not support %s only %s", code, locales.keySet());
return;
}
super.setLocale(code);
for (ServiceInterface si : Runtime.getLocalServices().values()) {
if (!si.equals(this)) {
si.setLocale(code);
}
}
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
sendToPeer("mouth", "setMute", mute);
broadcastState();
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public String setSpeechType(String speechType) {
serviceType.setPeer("mouth", speechType);
broadcastState();
return speechType;
}
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
public void setTorsoSpeed(Integer topStom, Integer midStom, Integer lowStom) {
setTorsoSpeed((double) topStom, (double) midStom, (double) lowStom);
}
@Deprecated
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
public boolean setAllVirtual(boolean virtual) {
Runtime.setAllVirtual(virtual);
speakBlocking(get("STARTINGVIRTUALHARD"));
return virtual;
}
public void setVoice(String name) {
if (mouth != null) {
mouth.setVoice(name);
voiceSelected = name;
speakBlocking(String.format("%s %s", get("SETLANG"), name));
}
}
public void speak(String toSpeak) {
sendToPeer("mouth", "speak", toSpeak);
}
public void speakAlert(String toSpeak) {
speakBlocking(get("ALERT"));
speakBlocking(toSpeak);
}
public void speakBlocking(String speak) {
speakBlocking(speak, (Object[]) null);
}
// FIXME - publish text regardless if mouth exists ...
public void speakBlocking(String format, Object... args) {
if (format == null) {
return;
}
String toSpeak = format;
if (args != null) {
toSpeak = String.format(format, args);
}
// FIXME - publish onText when listening
invoke("publishText", toSpeak);
if (!mute && isPeerStarted("mouth")) {
// sendToPeer("mouth", "speakBlocking", toSpeak);
invokePeer("mouth", "speakBlocking", toSpeak);
}
}
public void startAll() throws Exception {
startAll(null, null);
}
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startChatBot();
// startHeadTracking();
// startEyesTracking();
// startOpenCV();
startEar();
startServos(leftPort, rightPort);
// startMouthControl(head.jaw, mouth);
speakBlocking(get("STARTINGSEQUENCE"));
}
/**
* start servos - no controllers
*
* @throws Exception
* boom
*/
public void startServos() throws Exception {
startServos(null, null);
}
public ProgramAB startChatBot() {
try {
chatBot = (ProgramAB) startPeer("chatBot");
isChatBotActivated = true;
if (locale != null) {
chatBot.setCurrentBotName(locale.getTag());
}
speakBlocking(get("CHATBOTACTIVATED"));
chatBot.attachTextPublisher(ear);
// this.attach(chatBot); FIXME - attach as a TextPublisher - then
// re-publish
// FIXME - deal with language
// speakBlocking(get("CHATBOTACTIVATED"));
chatBot.repetitionCount(10);
// chatBot.setPath(getResourceDir() + fs + "chatbot");
chatBot.setPath(getDataDir() + fs + "chatbot");
chatBot.startSession("default", locale.getTag());
// reset some parameters to default...
chatBot.setPredicate("topic", "default");
chatBot.setPredicate("questionfirstinit", "");
chatBot.setPredicate("tmpname", "");
chatBot.setPredicate("null", "");
// load last user session
if (!chatBot.getPredicate("name").isEmpty()) {
if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown")) {
chatBot.setPredicate("lastUsername", chatBot.getPredicate("name"));
}
}
chatBot.setPredicate("parameterHowDoYouDo", "");
try {
chatBot.savePredicates();
} catch (IOException e) {
log.error("saving predicates threw", e);
}
// start session based on last recognized person
// if (!chatBot.getPredicate("default", "lastUsername").isEmpty() &&
// !chatBot.getPredicate("default", "lastUsername").equals("unknown")) {
// chatBot.startSession(chatBot.getPredicate("lastUsername"));
if (!chatBot.getPredicate("default", "firstinit").isEmpty() && !chatBot.getPredicate("default", "firstinit").equals("unknown")
&& !chatBot.getPredicate("default", "firstinit").equals("started")) {
chatBot.startSession(chatBot.getPredicate("default", "lastUsername"));
chatBot.getResponse("FIRST_INIT");
} else {
chatBot.startSession(chatBot.getPredicate("default", "lastUsername"));
chatBot.getResponse("WAKE_UP");
}
htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter",
// "HtmlFilter");
chatBot.attachTextListener(htmlFilter);
htmlFilter.attachTextListener((TextListener) getPeer("mouth"));
chatBot.attachTextListener(this);
} catch (Exception e) {
speak("could not load chatBot");
error(e.getMessage());
speak(e.getMessage());
}
broadcastState();
return chatBot;
}
public SpeechRecognizer startEar() {
ear = (SpeechRecognizer) startPeer("ear");
isEarActivated = true;
ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth"));
ear.attachTextListener(chatBot);
speakBlocking(get("STARTINGEAR"));
broadcastState();
return ear;
}
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
// FIXME - universal (good) way of handling all exceptions - ie - reporting
// back to the user the problem in a short concise way but have
// expandable detail in appropriate places
public OpenCV startOpenCV() throws Exception {
speakBlocking(get("STARTINGOPENCV"));
opencv = (OpenCV) startPeer("opencv");
subscribeTo(opencv.getName(), "publishOpenCVData");
isOpenCvActivated = true;
return opencv;
}
public OpenCV getOpenCV() {
return opencv;
}
public void setOpenCV(OpenCV opencv) {
this.opencv = opencv;
}
public Tracking startEyesTracking() throws Exception {
if (head == null) {
startHead();
}
// TODO: pass the PID values for the eye tracking
return startHeadTracking(head.eyeX, head.eyeY);
}
public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception {
if (opencv == null) {
startOpenCV();
}
speakBlocking(get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.attach(opencv.getName());
eyesTracking.attachPan(head.eyeX.getName());
eyesTracking.attachTilt(head.eyeY.getName());
return eyesTracking;
}
public InMoov2Head startHead() throws Exception {
return startHead(null, null, null, null, null, null, null, null);
}
public InMoov2Head startHead(String port) throws Exception {
return startHead(port, null, null, null, null, null, null, null);
}
// legacy inmoov head exposed pins
public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) {
speakBlocking(get("STARTINGHEAD"));
head = (InMoov2Head) startPeer("head");
isHeadActivated = true;
if (headYPin != null) {
head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
// lame assumption - port is specified - it must be an Arduino :(
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(head.neck);
arduino.attach(head.rothead);
arduino.attach(head.eyeX);
arduino.attach(head.eyeY);
arduino.attach(head.jaw);
// FIXME rollNeck and eyelids must be connected to right controller
// arduino.attach(head.rollNeck);
// arduino.attach(head.eyelidLeft);
// arduino.attach(head.eyelidRight);
} catch (Exception e) {
error(e);
}
}
speakBlocking(get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) getPeer("mouth"));
mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for
// config !!!
return head;
}
public void startHeadTracking() throws Exception {
if (opencv == null) {
startOpenCV();
}
if (head == null) {
startHead();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.attach(opencv.getName());
headTracking.attachPan(head.rothead.getName());
headTracking.attachTilt(head.neck.getName());
// TODO: where are the PID values?
}
}
public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception {
if (opencv == null) {
startOpenCV();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.attach(opencv.getName());
headTracking.attachPan(rothead.getName());
headTracking.attachTilt(neck.getName());
// TODO: where are the PID values?
}
return headTracking;
}
public InMoov2Arm startLeftArm() {
return startLeftArm(null);
}
public InMoov2Arm startLeftArm(String port) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
speakBlocking(get("STARTINGLEFTARM"));
leftArm = (InMoov2Arm) startPeer("leftArm");
isLeftArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(leftArm.bicep);
arduino.attach(leftArm.omoplate);
arduino.attach(leftArm.rotate);
arduino.attach(leftArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return leftArm;
}
public InMoov2Hand startLeftHand() {
return startLeftHand(null);
}
public InMoov2Hand startLeftHand(String port) {
speakBlocking(get("STARTINGLEFTHAND"));
leftHand = (InMoov2Hand) startPeer("leftHand");
isLeftHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(leftHand.thumb);
arduino.attach(leftHand.index);
arduino.attach(leftHand.majeure);
arduino.attach(leftHand.ringFinger);
arduino.attach(leftHand.pinky);
arduino.attach(leftHand.wrist);
} catch (Exception e) {
error(e);
}
}
return leftHand;
}
// TODO - general objective "might" be to reduce peers down to something
// that does not need a reference - where type can be switched before creation
// and the only thing needed is pubs/subs that are not handled in abstracts
public SpeechSynthesis startMouth() {
// FIXME - bad to have a reference, should only need the "name" of the
// service !!!
mouth = (SpeechSynthesis) startPeer("mouth");
voices = mouth.getVoices();
Voice voice = mouth.getVoice();
if (voice != null) {
voiceSelected = voice.getName();
}
isMouthActivated = true;
if (mute) {
mouth.setMute(true);
}
mouth.attachSpeechRecognizer(ear);
// mouth.attach(htmlFilter); // same as chatBot not needed
// this.attach((Attachable) mouth);
// if (ear != null) ....
broadcastState();
speakBlocking(get("STARTINGMOUTH"));
if (Platform.isVirtual()) {
speakBlocking(get("STARTINGVIRTUALHARD"));
}
speakBlocking(get("WHATISTHISLANGUAGE"));
return mouth;
}
public InMoov2Arm startRightArm() {
return startRightArm(null);
}
public InMoov2Arm startRightArm(String port) {
speakBlocking(get("STARTINGRIGHTARM"));
rightArm = (InMoov2Arm) startPeer("rightArm");
isRightArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right");
arduino.connect(port);
arduino.attach(rightArm.bicep);
arduino.attach(rightArm.omoplate);
arduino.attach(rightArm.rotate);
arduino.attach(rightArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return rightArm;
}
public InMoov2Hand startRightHand() {
return startRightHand(null);
}
public InMoov2Hand startRightHand(String port) {
speakBlocking(get("STARTINGRIGHTHAND"));
rightHand = (InMoov2Hand) startPeer("rightHand");
isRightHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right");
arduino.connect(port);
arduino.attach(rightHand.thumb);
arduino.attach(rightHand.index);
arduino.attach(rightHand.majeure);
arduino.attach(rightHand.ringFinger);
arduino.attach(rightHand.pinky);
arduino.attach(rightHand.wrist);
} catch (Exception e) {
error(e);
}
}
return rightHand;
}
public Double getUltrasonicRightDistance() {
if (ultrasonicRight != null) {
return ultrasonicRight.range();
} else {
warn("No UltrasonicRight attached");
return 0.0;
}
}
public Double getUltrasonicLeftDistance() {
if (ultrasonicLeft != null) {
return ultrasonicLeft.range();
} else {
warn("No UltrasonicLeft attached");
return 0.0;
}
}
// public void publishPin(Pin pin) {
// log.info("{} - {}", pin.pin, pin.value);
// if (pin.value == 1) {
// lastPIRActivityTime = System.currentTimeMillis();
/// if its PIR & PIR is active & was sleeping - then wake up !
// if (pin == pin.pin && startSleep != null && pin.value == 1) {
// powerUp();
public void startServos(String leftPort, String rightPort) throws Exception {
startHead(leftPort);
startLeftArm(leftPort);
startLeftHand(leftPort);
startRightArm(rightPort);
startRightHand(rightPort);
startTorso(leftPort);
}
// FIXME .. externalize in a json file included in InMoov2
public Simulator startSimulator() throws Exception {
speakBlocking(get("STARTINGVIRTUAL"));
if (simulator != null) {
log.info("start called twice - starting simulator is reentrant");
return simulator;
}
simulator = (JMonkeyEngine) startPeer("simulator");
// DEPRECATED - should just user peer info
isSimulatorActivated = true;
// adding InMoov2 asset path to the jmonkey simulator
String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName();
File check = new File(assetPath);
log.info("loading assets from {}", assetPath);
if (!check.exists()) {
log.warn("%s does not exist");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
// jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into
// /resource/JMonkeyEngine/assets
simulator.loadModels(assetPath);
simulator.setRotation(getName() + ".head.jaw", "x");
simulator.setRotation(getName() + ".head.neck", "x");
simulator.setRotation(getName() + ".head.rothead", "y");
simulator.setRotation(getName() + ".head.rollNeck", "z");
simulator.setRotation(getName() + ".head.eyeY", "x");
simulator.setRotation(getName() + ".head.eyeX", "y");
//simulator.setRotation(getName() + ".head.eyelidLeft", "x");FIXME we need to modelize them in Blender
//simulator.setRotation(getName() + ".head.eyelidRight", "x");FIXME we need to modelize them in Blender
simulator.setRotation(getName() + ".torso.topStom", "z");
simulator.setRotation(getName() + ".torso.midStom", "y");
simulator.setRotation(getName() + ".torso.lowStom", "x");
simulator.setRotation(getName() + ".rightArm.bicep", "x");
simulator.setRotation(getName() + ".leftArm.bicep", "x");
simulator.setRotation(getName() + ".rightArm.shoulder", "x");
simulator.setRotation(getName() + ".leftArm.shoulder", "x");
simulator.setRotation(getName() + ".rightArm.rotate", "y");
simulator.setRotation(getName() + ".leftArm.rotate", "y");
simulator.setRotation(getName() + ".rightArm.omoplate", "z");
simulator.setRotation(getName() + ".leftArm.omoplate", "z");
simulator.setRotation(getName() + ".rightHand.wrist", "y");
simulator.setRotation(getName() + ".leftHand.wrist", "y");
simulator.setMapper(getName() + ".head.jaw", 0, 180, -5, 80);
simulator.setMapper(getName() + ".head.neck", 0, 180, 20, -20);
simulator.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30);
simulator.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140);
simulator.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE
// there
// need
// to be
// two eyeX (left and
// right?)
//simulator.setMapper(getName() + ".head.eyelidLeft", 0, 180, 40, 140);FIXME we need to modelize them in Blender
//simulator.setMapper(getName() + ".head.eyelidRight", 0, 180, 40, 140);FIXME we need to modelize them in Blender
simulator.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80);
simulator.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80);
simulator.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180);
simulator.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180);
simulator.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60);
simulator.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60);
simulator.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30);
simulator.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130);
simulator.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30);
simulator.multiMap(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3");
simulator.setRotation(getName() + ".leftHand.thumb1", "y");
simulator.setRotation(getName() + ".leftHand.thumb2", "x");
simulator.setRotation(getName() + ".leftHand.thumb3", "x");
simulator.multiMap(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3");
simulator.setRotation(getName() + ".leftHand.index", "x");
simulator.setRotation(getName() + ".leftHand.index2", "x");
simulator.setRotation(getName() + ".leftHand.index3", "x");
simulator.multiMap(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3");
simulator.setRotation(getName() + ".leftHand.majeure", "x");
simulator.setRotation(getName() + ".leftHand.majeure2", "x");
simulator.setRotation(getName() + ".leftHand.majeure3", "x");
simulator.multiMap(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3");
simulator.setRotation(getName() + ".leftHand.ringFinger", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger2", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger3", "x");
simulator.multiMap(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3");
simulator.setRotation(getName() + ".leftHand.pinky", "x");
simulator.setRotation(getName() + ".leftHand.pinky2", "x");
simulator.setRotation(getName() + ".leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
simulator.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100);
simulator.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20);
simulator.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20);
// right hand
simulator.multiMap(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3");
simulator.setRotation(getName() + ".rightHand.thumb1", "y");
simulator.setRotation(getName() + ".rightHand.thumb2", "x");
simulator.setRotation(getName() + ".rightHand.thumb3", "x");
simulator.multiMap(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3");
simulator.setRotation(getName() + ".rightHand.index", "x");
simulator.setRotation(getName() + ".rightHand.index2", "x");
simulator.setRotation(getName() + ".rightHand.index3", "x");
simulator.multiMap(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3");
simulator.setRotation(getName() + ".rightHand.majeure", "x");
simulator.setRotation(getName() + ".rightHand.majeure2", "x");
simulator.setRotation(getName() + ".rightHand.majeure3", "x");
simulator.multiMap(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3");
simulator.setRotation(getName() + ".rightHand.ringFinger", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger2", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger3", "x");
simulator.multiMap(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3");
simulator.setRotation(getName() + ".rightHand.pinky", "x");
simulator.setRotation(getName() + ".rightHand.pinky2", "x");
simulator.setRotation(getName() + ".rightHand.pinky3", "x");
simulator.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10);
simulator.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110);
simulator.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150);
simulator.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160);
// We set the correct location view
simulator.cameraLookAt(getName() + ".torso.lowStom");
// additional experimental mappings
/*
* simulator.attach(getName() + ".leftHand.pinky", getName() +
* ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb",
* getName() + ".leftHand.index3"); simulator.setRotation(getName() +
* ".leftHand.index2", "x"); simulator.setRotation(getName() +
* ".leftHand.index3", "x"); simulator.setMapper(getName() +
* ".leftHand.index", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index2", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index3", 0, 180, -90, -270);
*/
return simulator;
}
public InMoov2Torso startTorso() {
return startTorso(null);
}
public InMoov2Torso startTorso(String port) {
if (torso == null) {
speakBlocking(get("STARTINGTORSO"));
isTorsoActivated = true;
torso = (InMoov2Torso) startPeer("torso");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(torso.lowStom);
left.attach(torso.midStom);
left.attach(torso.topStom);
} catch (Exception e) {
error(e);
}
}
}
return torso;
}
/**
* called with only port - will default with defaulted pins
*
* @param port
* port for the sensor
* @return the ultrasonic sensor service
*/
public UltrasonicSensor startUltrasonicRight(String port) {
return startUltrasonicRight(port, 64, 63);
}
/**
* called explicitly with pin values
*
* @param port
* p
* @param trigPin
* trigger pin
* @param echoPin
* echo pin
* @return the ultrasonic sensor
*
*/
public UltrasonicSensor startUltrasonicRight(String port, int trigPin, int echoPin) {
if (ultrasonicRight == null) {
speakBlocking(get("STARTINGULTRASONICRIGHT"));
isUltrasonicRightActivated = true;
ultrasonicRight = (UltrasonicSensor) startPeer("ultrasonicRight");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attach(ultrasonicRight, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultrasonicRight;
}
public UltrasonicSensor startUltrasonicLeft() {
return startUltrasonicLeft(null, 64, 63);
}
public UltrasonicSensor startUltrasonicRight() {
return startUltrasonicRight(null, 64, 63);
}
public UltrasonicSensor startUltrasonicLeft(String port) {
return startUltrasonicLeft(port, 64, 63);
}
public UltrasonicSensor startUltrasonicLeft(String port, int trigPin, int echoPin) {
if (ultrasonicLeft == null) {
speakBlocking(get("STARTINGULTRASONICLEFT"));
isUltrasonicLeftActivated = true;
ultrasonicLeft = (UltrasonicSensor) startPeer("ultrasonicLeft");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(ultrasonicLeft, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultrasonicLeft;
}
public Pir startPir(String port) {
return startPir(port, 23);
}
public Pir startPir(String port, int pin) {
if (pir == null) {
speakBlocking(get("STARTINGPIR"));
isPirActivated = true;
pir = (Pir) startPeer("pir");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attachPinListener(pir, pin);
} catch (Exception e) {
error(e);
}
}
}
return pir;
}
/**
* config delegated startPir ... hopefully
*
* @return
*/
public Pir startPir() {
if (pir == null) {
speakBlocking(get("STARTINGPIR"));
isPirActivated = true;
pir = (Pir) startPeer("pir");
try {
pir.load(); // will this work ?
// would be great if it did - offloading configuration
// to the i01.pir.yml
} catch (Exception e) {
error(e);
}
}
return pir;
}
public ServoMixer startServoMixer() {
servoMixer = (ServoMixer) startPeer("servoMixer");
isServoMixerActivated = true;
speakBlocking(get("STARTINGSERVOMIXER"));
broadcastState();
return servoMixer;
}
public void stop() {
if (head != null) {
head.stop();
}
if (rightHand != null) {
rightHand.stop();
}
if (leftHand != null) {
leftHand.stop();
}
if (rightArm != null) {
rightArm.stop();
}
if (leftArm != null) {
leftArm.stop();
}
if (torso != null) {
torso.stop();
}
}
public void stopChatBot() {
speakBlocking(get("STOPCHATBOT"));
releasePeer("chatBot");
isChatBotActivated = false;
}
public void stopHead() {
speakBlocking(get("STOPHEAD"));
releasePeer("head");
releasePeer("mouthControl");
isHeadActivated = false;
}
public void stopEar() {
speakBlocking(get("STOPEAR"));
releasePeer("ear");
isEarActivated = false;
broadcastState();
}
public void stopOpenCV() {
speakBlocking(get("STOPOPENCV"));
isOpenCvActivated = false;
releasePeer("opencv");
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public void stopLeftArm() {
speakBlocking(get("STOPLEFTARM"));
releasePeer("leftArm");
isLeftArmActivated = false;
}
public void stopLeftHand() {
speakBlocking(get("STOPLEFTHAND"));
releasePeer("leftHand");
isLeftHandActivated = false;
}
public void stopMouth() {
speakBlocking(get("STOPMOUTH"));
releasePeer("mouth");
// TODO - potentially you could set the field to null in releasePeer
mouth = null;
isMouthActivated = false;
}
public void stopRightArm() {
speakBlocking(get("STOPRIGHTARM"));
releasePeer("rightArm");
isRightArmActivated = false;
}
public void stopRightHand() {
speakBlocking(get("STOPRIGHTHAND"));
releasePeer("rightHand");
isRightHandActivated = false;
}
public void stopTorso() {
speakBlocking(get("STOPTORSO"));
releasePeer("torso");
isTorsoActivated = false;
}
public void stopSimulator() {
speakBlocking(get("STOPVIRTUAL"));
releasePeer("simulator");
simulator = null;
isSimulatorActivated = false;
}
public void stopUltrasonicRight() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultrasonicRight");
isUltrasonicRightActivated = false;
}
public void stopUltrasonicLeft() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultrasonicLeft");
isUltrasonicLeftActivated = false;
}
public void stopPir() {
speakBlocking(get("STOPPIR"));
releasePeer("pir");
isPirActivated = false;
}
public void stopNeopixelAnimation() {
if (neopixel != null) {
neopixel.clear();
} else {
warn("No Neopixel attached");
}
}
public void stopServoMixer() {
speakBlocking(get("STOPSERVOMIXER"));
releasePeer("servoMixer");
isServoMixerActivated = false;
}
public void waitTargetPos() {
if (head != null) {
head.waitTargetPos();
}
if (leftArm != null) {
leftArm.waitTargetPos();
}
if (rightArm != null) {
rightArm.waitTargetPos();
}
if (leftHand != null) {
leftHand.waitTargetPos();
}
if (rightHand != null) {
rightHand.waitTargetPos();
}
if (torso != null) {
torso.waitTargetPos();
}
}
public NeoPixel startNeopixel() {
return startNeopixel(getName() + ".right", 2, 16);
}
public NeoPixel startNeopixel(String controllerName) {
return startNeopixel(controllerName, 2, 16);
}
public NeoPixel startNeopixel(String controllerName, int pin, int numPixel) {
if (neopixel == null) {
try {
neopixel = (NeoPixel) startPeer("neopixel");
speakBlocking(get("STARTINGNEOPIXEL"));
// FIXME - lame use peers
isNeopixelActivated = true;
neopixel.attach(Runtime.getService(controllerName));
} catch (Exception e) {
error(e);
}
}
return neopixel;
}
@Override
public void attachTextListener(String name) {
addListener("publishText", name);
}
public Tracking getEyesTracking() {
return eyesTracking;
}
public Tracking getHeadTracking() {
return headTracking;
}
public void startBrain() {
startChatBot();
}
public void startMouthControl() {
speakBlocking(get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) getPeer("mouth"));
}
@Deprecated /* wrong function name should be startPir */
public void startPIR(String port, int pin) {
startPir(port, pin);
}
// These are methods added that were in InMoov1 that we no longer had in
// InMoov2.
// From original InMoov1 so we don't loose the
@Override
public void onJointAngles(Map<String, Double> angleMap) {
log.info("onJointAngles {}", angleMap);
// here we can make decisions on what ik sets we want to use and
// what body parts are to move
for (String name : angleMap.keySet()) {
ServiceInterface si = Runtime.getService(name);
if (si != null && si instanceof ServoControl) {
((Servo) si).moveTo(angleMap.get(name));
}
}
}
@Override
public ServiceConfig getConfig() {
InMoov2Config config = new InMoov2Config();
// config.isController3Activated = isController3Activated;
// config.isController4Activated = isController4Activated;
// config.enableEyelids = isEyeLidsActivated;
config.enableHead = isHeadActivated;
config.enableLeftArm = isLeftArmActivated;
config.enableLeftHand = isLeftHandActivated;
config.enableLeftHandSensor = isLeftHandSensorActivated;
// config.isLeftPortActivated = isLeftPortActivated;
config.enableNeoPixel = isNeopixelActivated;
config.enableOpenCV = isOpenCvActivated;
config.enablePir = isPirActivated;
config.enableUltrasonicRight = isUltrasonicRightActivated;
config.enableUltrasonicLeft = isUltrasonicLeftActivated;
config.enableRightArm = isRightArmActivated;
config.enableRightHand = isRightHandActivated;
config.enableRightHandSensors = isRightHandSensorActivated;
// config.isRightPortActivated = isRightPortActivated;
// config.enableSimulator = isSimulatorActivated;
return config;
}
public void startAudioPlayer() {
startPeer("audioPlayer");
}
public void stopAudioPlayer() {
releasePeer("audioPlayer");
}
public ServiceConfig load(ServiceConfig c) {
InMoov2Config config = (InMoov2Config) c;
try {
if (config.locale != null) {
Runtime.setAllLocales(config.locale);
}
if (config.enableAudioPlayer) {
startAudioPlayer();
} else {
stopAudioPlayer();
}
/**
* <pre>
* FIXME -
* - there simply should be a single reference to the entire config object in InMoov
* e.g. InMoov2Config config member
* - if these booleans are symmetric - there should be corresponding functionality of "stopping/releasing" since they
* are currently starting
* </pre>
*/
/*
* FIXME - very bad - need some coordination with this
*
* if (config.isController3Activated) { startPeer("controller3"); // FIXME
* ... this kills me :P exec("isController3Activated = True"); }
*
* if (config.isController4Activated) { startPeer("controller4"); // FIXME
* ... this kills me :P exec("isController4Activated = True"); }
*/
/*
* if (config.enableEyelids) { // the hell if I know ? }
*/
if (config.enableHead) {
startHead();
} else {
stopHead();
}
if (config.enableLeftArm) {
startLeftArm();
} else {
stopLeftArm();
}
if (config.enableLeftHand) {
startLeftHand();
} else {
stopLeftHand();
}
if (config.enableLeftHandSensor) {
// the hell if I know ?
}
/*
* if (config.isLeftPortActivated) { // the hell if I know ? is this an
* Arduino ? startPeer("left"); } // else release peer ?
*
* if (config.enableNeoPixel) { startNeopixel(); } else { //
* stopNeopixelAnimation(); }
*/
if (config.enableOpenCV) {
startOpenCV();
} else {
stopOpenCV();
}
/*
* if (config.enablePir) { startPir(); } else { stopPir(); }
*/
if (config.enableRightArm) {
startRightArm();
} else {
stopRightArm();
}
if (config.enableRightHand) {
startRightHand();
} else {
stopRightHand();
}
if (config.enableRightHandSensors) {
// the hell if I know ?
}
/*
* if (config.isRightPortActivated) { // the hell if I know ? is this an
* Arduino ? }
*/
if (config.enableServoMixer) {
startServoMixer();
} else {
stopServoMixer();
}
if (config.enableTorso) {
startTorso();
} else {
stopTorso();
}
if (config.enableUltrasonicLeft) {
startUltrasonicLeft();
} else {
stopUltrasonicLeft();
}
if (config.enableUltrasonicRight) {
startUltrasonicRight();
} else {
stopUltrasonicRight();
}
if (config.enablePir) {
startPir();
} else {
stopPir();
}
if (config.enableNeoPixel) {
startNeopixel();
} else {
stopNeopixelAnimation();
}
if (config.loadGestures) {
loadGestures = true;
loadGestures();
// will load in startService
}
if (config.enableSimulator) {
startSimulator();
}
} catch (Exception e) {
error(e);
}
return c;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Platform.setVirtual(true);
// Runtime.start("s01", "Servo");
Runtime.start("intro", "Intro");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
Random random = (Random) Runtime.start("random", "Random");
InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2");
random.addRandom(3000, 8000, "i01", "setLeftArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "setRightArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "moveRightArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0);
random.addRandom(3000, 8000, "i01", "moveLeftArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0);
random.addRandom(3000, 8000, "i01", "setLeftHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "setRightHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "moveRightHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 130.0, 175.0);
random.addRandom(3000, 8000, "i01", "moveLeftHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 5.0, 40.0);
random.addRandom(200, 1000, "i01", "setHeadSpeed", 8.0, 20.0, 8.0, 20.0, 8.0, 20.0);
random.addRandom(200, 1000, "i01", "moveHead", 70.0, 110.0, 65.0, 115.0, 70.0, 110.0);
random.addRandom(200, 1000, "i01", "setTorsoSpeed", 2.0, 5.0, 2.0, 5.0, 2.0, 5.0);
random.addRandom(200, 1000, "i01", "moveTorso", 85.0, 95.0, 88.0, 93.0, 70.0, 110.0);
random.save();
boolean done = true;
if (done) {
return;
}
// i01.setVirtual(false);
// i01.getConfig();
// i01.save();
// Runtime.start("s02", "Servo");
i01.startChatBot();
i01.startAll("COM3", "COM4");
Runtime.start("python", "Python");
// Runtime.start("log", "Log");
/*
* OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV");
* cv.setCameraIndex(2);
*/
// i01.startSimulator();
/*
* Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
* mega.connect("/dev/ttyACM0");
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Plan;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice;
import org.myrobotlab.service.config.InMoov2Config;
import org.myrobotlab.service.config.ServiceConfig;
import org.myrobotlab.service.config.WebGuiConfig;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.IKJointAngleListener;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.ServiceLifeCycleListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.Simulator;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class InMoov2 extends Service implements ServiceLifeCycleListener, TextListener, TextPublisher, JoystickListener, LocaleProvider, IKJointAngleListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2.class);
public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>();
private static final long serialVersionUID = 1L;
static String speechRecognizer = "WebkitSpeechRecognition";
protected boolean loadGestures = true;
/**
* @param someScriptName
* execute a resource script
* @return success or failure
*/
public boolean execScript(String someScriptName) {
try {
Python p = (Python) Runtime.start("python", "Python");
String script = getResourceAsString(someScriptName);
return p.exec(script, true);
} catch (Exception e) {
error("unable to execute script %s", someScriptName);
return false;
}
}
/**
* Single place for InMoov2 service to execute arbitrary code - needed
* initially to set "global" vars in python
*
* @param pythonCode
* @return
*/
public boolean exec(String pythonCode) {
try {
Python p = (Python) Runtime.start("python", "Python");
return p.exec(pythonCode, true);
} catch (Exception e) {
error("unable to execute script %s", pythonCode);
return false;
}
}
/**
* Part of service life cycle - a new servo has been started
*/
public void onStarted(String fullname) {
log.info("{} started", fullname);
try {
ServiceInterface si = Runtime.getService(fullname);
if ("Servo".equals(si.getSimpleName())) {
log.info("sending setAutoDisable true to {}", fullname);
send(fullname, "setAutoDisable", true);
// ServoControl sc = (ServoControl)Runtime.getService(name);
}
} catch (Exception e) {
log.error("onStarted threw", e);
}
}
public void startService() {
super.startService();
Runtime runtime = Runtime.getInstance();
// FIXME - shouldn't need this anymore
Runtime.getInstance().attachServiceLifeCycleListener(getName());
try {
// copy config if it doesn't already exist
String resourceBotDir = FileIO.gluePaths(getResourceDir(), "config");
List<File> files = FileIO.getFileList(resourceBotDir);
for (File f : files) {
String botDir = "data/config/" + f.getName();
File bDir = new File(botDir);
if (bDir.exists() || !f.isDirectory()) {
log.info("skipping data/config/{}", botDir);
} else {
log.info("will copy new data/config/{}", botDir);
try {
FileIO.copy(f.getAbsolutePath(), botDir);
} catch (Exception e) {
error(e);
}
}
}
// copy (if they don't already exist) the chatbots which came with InMoov2
resourceBotDir = FileIO.gluePaths(getResourceDir(), "chatbot/bots");
files = FileIO.getFileList(resourceBotDir);
for (File f : files) {
String botDir = "data/ProgramAB/" + f.getName();
if (new File(botDir).exists()) {
log.info("found data/ProgramAB/{} not copying", botDir);
} else {
log.info("will copy new data/ProgramAB/{}", botDir);
try {
FileIO.copy(f.getAbsolutePath(), botDir);
} catch (Exception e) {
error(e);
}
}
}
} catch (Exception e) {
error(e);
}
if (loadGestures) {
loadGestures();
}
runtime.invoke("publishConfigList");
}
public void onCreated(String fullname) {
log.info("{} created", fullname);
}
/**
* This method will load a python file into the python interpreter.
*
* @param file
* file to load
* @return success/failure
*/
@Deprecated /* use execScript - this doesn't handle resources correctly */
public static boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
boolean result = false;
try {
// This will open a gazillion tabs in InMoov
// result = p.execFile(f.getAbsolutePath(), true);
// old way - not using execFile :(
String script = FileIO.toString(f.getAbsolutePath());
result = p.exec(script, true);
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
boolean autoStartBrowser = false;
transient ProgramAB chatBot;
String currentConfigurationName = "default";
transient SpeechRecognizer ear;
transient OpenCV opencv;
transient Tracking eyesTracking;
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
// FIXME - what the hell is this for ?
Set<String> gestures = new TreeSet<String>();
transient InMoov2Head head;
transient Tracking headTracking;
transient HtmlFilter htmlFilter;
transient UltrasonicSensor ultrasonicRight;
transient UltrasonicSensor ultrasonicLeft;
transient Pir pir;
transient ImageDisplay imageDisplay;
/**
* simple booleans to determine peer state of existence FIXME - should be an
* auto-peer variable
*
* FIXME - sometime in the future there should just be a single simple
* reference to a loaded "config" but at the moment the new UI depends on
* these individual values :(
*
*/
boolean isChatBotActivated = false;
boolean isEarActivated = false;
boolean isOpenCvActivated = false;
boolean isEyeLidsActivated = false;
boolean isHeadActivated = false;
boolean isLeftArmActivated = false;
boolean isLeftHandActivated = false;
boolean isMouthActivated = false;
// adding to the problem :( :( :(
boolean isAudioPlayerActivated = true;
boolean isRightArmActivated = false;
boolean isRightHandActivated = false;
boolean isSimulatorActivated = false;
boolean isTorsoActivated = false;
boolean isNeopixelActivated = false;
boolean isPirActivated = false;
boolean isUltrasonicRightActivated = false;
boolean isUltrasonicLeftActivated = false;
boolean isServoMixerActivated = false;
// TODO - refactor into a Simulator interface when more simulators are borgd
transient JMonkeyEngine simulator;
String lastGestureExecuted;
Long lastPirActivityTime;
transient InMoov2Arm leftArm;
transient InMoov2Hand leftHand;
/**
* supported locales
*/
Map<String, Locale> locales = null;
int maxInactivityTimeSeconds = 120;
transient SpeechSynthesis mouth;
// FIXME ugh - new MouthControl service that uses AudioFile output
transient public MouthControl mouthControl;
boolean mute = false;
transient NeoPixel neopixel;
transient ServoMixer servoMixer;
transient Python python;
transient InMoov2Arm rightArm;
transient InMoov2Hand rightHand;
transient InMoov2Torso torso;
@Deprecated
public Vision vision;
// FIXME - remove all direct references
// transient private HashMap<String, InMoov2Arm> arms = new HashMap<>();
protected List<Voice> voices = null;
protected String voiceSelected;
transient WebGui webgui;
protected List<String> configList;
private boolean isController3Activated;
private boolean isController4Activated;
private boolean isLeftHandSensorActivated;
private boolean isLeftPortActivated;
private boolean isRightHandSensorActivated;
private boolean isRightPortActivated;
public InMoov2(String n, String id) {
super(n, id);
// InMoov2 has a huge amount of peers
// by default all servos will auto-disable
// Servo.setAutoDisableDefault(true); //until peer servo services for
// InMoov2 have the auto disable behavior, we should keep this
// same as created in runtime - send asyc message to all
// registered services, this service has started
// find all servos - set them all to autoDisable(true)
// onStarted(name) will handle all future created servos
List<ServiceInterface> services = Runtime.getServices();
for (ServiceInterface si : services) {
if ("Servo".equals(si.getSimpleName())) {
send(si.getFullName(), "setAutoDisable", true);
}
}
// dynamically gotten from filesystem/bots ?
locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT", "tr-TR");
locale = Runtime.getInstance().getLocale();
// REALLY NEEDS TO BE CLEANED UP - no direct references
// "publish" scripts which should be executed :(
// python = (Python) startPeer("python");
python = (Python) Runtime.start("python", "Python"); // this crud should
// stop
// load(locale.getTag()); WTH ?
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
subscribe(r.getName(), "publishConfigList");
// FIXME - Framework should auto-magically auto-start peers AFTER
// construction - unless explicitly told not to
// peers to start on construction
// imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
@Override /* local strong type - is to be avoided - use name string */
public void addTextListener(TextListener service) {
// CORRECT WAY ! - no direct reference - just use the name in a subscription
addListener("publishText", service.getName());
}
@Override
public void attachTextListener(TextListener service) {
attachTextListener(service.getName());
}
/**
* comes in from runtime which owns the config list
*
* @param configList
* list of configs
*/
public void onConfigList(List<String> configList) {
this.configList = configList;
invoke("publishConfigList");
}
/**
* "re"-publishing runtime config list, because I don't want to fix the js
* subscribeTo :P
*
* @return list of config names
*/
public List<String> publishConfigList() {
return configList;
}
public void attachTextPublisher(String name) {
subscribe(name, "publishText");
}
@Override
public void attachTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
public void closeAllImages() {
// imageDisplay.closeAll();
log.error("implement webgui.closeAllImages");
}
public void cycleGestures() {
// if not loaded load -
// FIXME - this needs alot of "help" :P
// WHY IS THIS DONE ?
if (gestures.size() == 0) {
loadGestures();
}
for (String gesture : gestures) {
try {
String methodName = gesture.substring(0, gesture.length() - 3);
speakBlocking(methodName);
log.info("executing gesture {}", methodName);
python.eval(methodName + "()");
// wait for finish - or timeout ?
} catch (Exception e) {
error(e);
}
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
}
public void displayFullScreen(String src) {
try {
if (imageDisplay == null) {
imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
imageDisplay.displayFullScreen(src);
log.error("implement webgui.displayFullScreen");
} catch (Exception e) {
error("could not display picture %s", src);
}
}
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
}
/**
* This method will try to launch a python command with error handling
*
* @param gesture
* the gesture
* @return gesture result
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void finishedGesture() {
finishedGesture("unknown");
}
// public State publishState(State state) {
// return state;
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
// RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
public void fullSpeed() {
if (head != null) {
head.fullSpeed();
}
if (rightHand != null) {
rightHand.fullSpeed();
}
if (leftHand != null) {
leftHand.fullSpeed();
}
if (rightArm != null) {
rightArm.fullSpeed();
}
if (leftArm != null) {
leftArm.fullSpeed();
}
if (torso != null) {
torso.fullSpeed();
}
}
public String get(String key) {
String ret = localize(key);
if (ret != null) {
return ret;
}
return "not yet translated";
}
public InMoov2Arm getArm(String side) {
if ("left".equals(side)) {
return leftArm;
} else if ("right".equals(side)) {
return rightArm;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Hand getHand(String side) {
if ("left".equals(side)) {
return leftHand;
} else if ("right".equals(side)) {
return rightHand;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Head getHead() {
return head;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (lastPirActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public InMoov2Arm getLeftArm() {
return leftArm;
}
public InMoov2Hand getLeftHand() {
return leftHand;
}
@Override
public Map<String, Locale> getLocales() {
return locales;
}
public InMoov2Arm getRightArm() {
return rightArm;
}
public InMoov2Hand getRightHand() {
return rightHand;
}
public Simulator getSimulator() {
return simulator;
}
public InMoov2Torso getTorso() {
return torso;
}
public void halfSpeed() {
if (head != null) {
head.setSpeed(25.0, 25.0, 25.0, 25.0, 100.0, 25.0);
}
if (rightHand != null) {
rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setSpeed(20.0, 20.0, 20.0);
}
}
public boolean isCameraOn() {
if (opencv != null) {
if (opencv.isCapturing()) {
return true;
}
}
return false;
}
public boolean isEyeLidsActivated() {
return isEyeLidsActivated;
}
public boolean isHeadActivated() {
return isHeadActivated;
}
public boolean isLeftArmActivated() {
return isLeftArmActivated;
}
public boolean isLeftHandActivated() {
return isLeftHandActivated;
}
public boolean isMute() {
return mute;
}
public boolean isNeopixelActivated() {
return isNeopixelActivated;
}
public boolean isRightArmActivated() {
return isRightArmActivated;
}
public boolean isRightHandActivated() {
return isRightHandActivated;
}
public boolean isTorsoActivated() {
return isTorsoActivated;
}
public boolean isPirActivated() {
return isPirActivated;
}
public boolean isUltrasonicRightActivated() {
return isUltrasonicRightActivated;
}
public boolean isUltrasonicLeftActivated() {
return isUltrasonicLeftActivated;
}
// by default all servos will auto-disable
// TODO: KW : make peer servo services for InMoov2 have the auto disable
// behavior.
// Servo.setAutoDisableDefault(true);
public boolean isServoMixerActivated() {
return isServoMixerActivated;
}
public void loadGestures() {
loadGestures(getResourceDir() + fs + "gestures");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
* @return true/false
*/
public boolean loadGestures(String directory) {
speakBlocking(get("STARTINGGESTURES"));
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = new File(directory);
dir.mkdirs();
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
String methodName = f.getName().substring(0, f.getName().length() - 3) + "()";
gestures.add(methodName);
} else {
error("could not load %s", f.getName());
totalError += 1;
}
} else {
log.info("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
broadcastState();
if (totalError > 0) {
speakAlert(get("GESTURE_ERROR"));
return false;
}
return true;
}
public void cameraOff() {
if (opencv != null) {
opencv.stopCapture();
opencv.disableAll();
}
}
public void cameraOn() {
try {
if (opencv == null) {
startOpenCV();
}
opencv.capture();
} catch (Exception e) {
error(e);
}
}
public void moveLeftArm(Double bicep, Double rotate, Double shoulder, Double omoplate) {
moveArm("left", bicep, rotate, shoulder, omoplate);
}
public void moveRightArm(Double bicep, Double rotate, Double shoulder, Double omoplate) {
moveArm("right", bicep, rotate, shoulder, omoplate);
}
public void moveArm(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
info("%s arm not started", which);
return;
}
arm.moveTo(bicep, rotate, shoulder, omoplate);
}
public void moveEyelids(Double eyelidleftPos, Double eyelidrightPos) {
if (head != null) {
head.moveEyelidsTo(eyelidleftPos, eyelidrightPos);
} else {
log.warn("moveEyelids - I have a null head");
}
}
public void moveEyes(Double eyeX, Double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.warn("moveEyes - I have a null head");
}
}
public void moveRightHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
moveHand("right", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveRightHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
moveHand("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void moveLeftHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
moveHand("left", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveLeftHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
moveHand("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
log.warn("{} hand does not exist", hand);
return;
}
hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveHead(Double neck, Double rothead) {
moveHead(neck, rothead, null, null, null, null);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(rollNeck, rothead, null, null, null, rollNeck);
}
public void moveHead(Integer neck, Integer rothead, Integer rollNeck) {
moveHead((double) rollNeck, (double) rothead, null, null, null, (double) rollNeck);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveHeadBlocking(Double neck, Double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
public OpenCVData onOpenCVData(OpenCVData data) {
return data;
}
@Override
public void onText(String text) {
// FIXME - we should be able to "re"-publish text but text is coming from
// different sources
// some might be coming from the ear - some from the mouth ... - there has
// to be a distinction
log.info("onText - {}", text);
invoke("publishText", text);
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
/**
* all published text from InMoov2 - including ProgramAB
*/
@Override
public String publishText(String text) {
return text;
}
public void releaseService() {
try {
disable();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
// FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest
public void rest() {
log.info("InMoov2.rest()");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
}
public void setLeftArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed("left", bicep, rotate, shoulder, omoplate);
}
public void setLeftArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) {
setArmSpeed("left", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate);
}
public void setRightArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed("right", bicep, rotate, shoulder, omoplate);
}
public void setRightArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) {
setArmSpeed("right", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate);
}
public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
warn("%s arm not started", which);
return;
}
arm.setSpeed(bicep, rotate, shoulder, omoplate);
}
@Deprecated
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed(which, bicep, rotate, shoulder, omoplate);
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
/*
* if (eyelids != null) { eyelids.setAutoDisable(param); }
*/
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setLeftHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed("left", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setLeftHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
setHandSpeed("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void setRightHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed("right", thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setRightHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) {
setHandSpeed("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
warn("%s hand not started", which);
return;
}
hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
public void setHeadSpeed(Integer rothead, Integer neck, Integer rollNeck) {
setHeadSpeed((double) rothead, (double) neck, null, null, null, (double) rollNeck);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head == null) {
warn("setHeadSpeed - head not started");
return;
}
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Override
public void setLocale(String code) {
if (code == null) {
log.warn("setLocale null");
return;
}
// filter of the set of supported locales
if (!Locale.hasLanguage(locales, code)) {
error("InMoov does not support %s only %s", code, locales.keySet());
return;
}
locale = new Locale(code);
// super.setLocale(code);
for (ServiceInterface si : Runtime.getLocalServices().values()) {
if (!si.equals(this) && !si.isRuntime()) {
si.setLocale(code);
}
}
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
sendToPeer("mouth", "setMute", mute);
broadcastState();
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public String setSpeechType(String speechType) {
Plan plan = Runtime.getPlan();
plan.remove(getPeerName("mouth"));
Runtime.load(getPeerName("mouth"), speechType);
broadcastState();
return speechType;
}
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
public void setTorsoSpeed(Integer topStom, Integer midStom, Integer lowStom) {
setTorsoSpeed((double) topStom, (double) midStom, (double) lowStom);
}
@Deprecated
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
public boolean setAllVirtual(boolean virtual) {
Runtime.setAllVirtual(virtual);
speakBlocking(get("STARTINGVIRTUALHARD"));
return virtual;
}
public void setVoice(String name) {
if (mouth != null) {
mouth.setVoice(name);
voiceSelected = name;
speakBlocking(String.format("%s %s", get("SETLANG"), name));
}
}
public void speak(String toSpeak) {
sendToPeer("mouth", "speak", toSpeak);
}
public void speakAlert(String toSpeak) {
speakBlocking(get("ALERT"));
speakBlocking(toSpeak);
}
public void speakBlocking(String speak) {
speakBlocking(speak, (Object[]) null);
}
// FIXME - publish text regardless if mouth exists ...
public void speakBlocking(String format, Object... args) {
if (format == null) {
return;
}
String toSpeak = format;
if (args != null) {
toSpeak = String.format(format, args);
}
// FIXME - publish onText when listening
invoke("publishText", toSpeak);
if (!mute && isPeerStarted("mouth")) {
// sendToPeer("mouth", "speakBlocking", toSpeak);
invokePeer("mouth", "speakBlocking", toSpeak);
}
}
public void startAll() throws Exception {
startAll(null, null);
}
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startChatBot();
// startHeadTracking();
// startEyesTracking();
// startOpenCV();
startEar();
startServos();
// startMouthControl(head.jaw, mouth);
speakBlocking(get("STARTINGSEQUENCE"));
}
public ProgramAB startChatBot() {
try {
chatBot = (ProgramAB) startPeer("chatBot");
isChatBotActivated = true;
if (locale != null) {
chatBot.setCurrentBotName(locale.getTag());
}
speakBlocking(get("CHATBOTACTIVATED"));
chatBot.attachTextPublisher(ear);
// this.attach(chatBot); FIXME - attach as a TextPublisher - then
// re-publish
// FIXME - deal with language
// speakBlocking(get("CHATBOTACTIVATED"));
chatBot.repetitionCount(10);
// chatBot.setPath(getResourceDir() + fs + "chatbot");
chatBot.setPath(getDataDir() + fs + "chatbot");
chatBot.startSession("default", locale.getTag());
// reset some parameters to default...
chatBot.setPredicate("topic", "default");
chatBot.setPredicate("questionfirstinit", "");
chatBot.setPredicate("tmpname", "");
chatBot.setPredicate("null", "");
// load last user session
if (!chatBot.getPredicate("name").isEmpty()) {
if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown") || chatBot.getPredicate("lastUsername").equals("default")) {
chatBot.setPredicate("lastUsername", chatBot.getPredicate("name"));
}
}
chatBot.setPredicate("parameterHowDoYouDo", "");
try {
chatBot.savePredicates();
} catch (IOException e) {
log.error("saving predicates threw", e);
}
htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter",
// "HtmlFilter");
chatBot.attachTextListener(htmlFilter);
htmlFilter.attachTextListener((TextListener) getPeer("mouth"));
chatBot.attachTextListener(this);
// start session based on last recognized person
// if (!chatBot.getPredicate("default", "lastUsername").isEmpty() &&
// !chatBot.getPredicate("default", "lastUsername").equals("unknown")) {
// chatBot.startSession(chatBot.getPredicate("lastUsername"));
if (chatBot.getPredicate("default", "firstinit").isEmpty() || chatBot.getPredicate("default", "firstinit").equals("unknown")
|| chatBot.getPredicate("default", "firstinit").equals("started")) {
chatBot.startSession(chatBot.getPredicate("default", "lastUsername"));
chatBot.getResponse("FIRST_INIT");
} else {
chatBot.startSession(chatBot.getPredicate("default", "lastUsername"));
chatBot.getResponse("WAKE_UP");
}
} catch (Exception e) {
speak("could not load chatBot");
error(e.getMessage());
speak(e.getMessage());
}
broadcastState();
return chatBot;
}
public SpeechRecognizer startEar() {
ear = (SpeechRecognizer) startPeer("ear");
isEarActivated = true;
ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth"));
ear.attachTextListener(chatBot);
speakBlocking(get("STARTINGEAR"));
broadcastState();
return ear;
}
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
// RobotCanMoveRandom = false;
}
}
// FIXME - universal (good) way of handling all exceptions - ie - reporting
// back to the user the problem in a short concise way but have
// expandable detail in appropriate places
public OpenCV startOpenCV(){
speakBlocking(get("STARTINGOPENCV"));
opencv = (OpenCV) startPeer("opencv");
subscribeTo(opencv.getName(), "publishOpenCVData");
isOpenCvActivated = true;
return opencv;
}
public OpenCV getOpenCV() {
return opencv;
}
public void setOpenCV(OpenCV opencv) {
this.opencv = opencv;
}
public Tracking startEyesTracking() throws Exception {
if (head == null) {
startHead();
}
// TODO: pass the PID values for the eye tracking
return startHeadTracking(head.eyeX, head.eyeY);
}
public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception {
if (opencv == null) {
startOpenCV();
}
speakBlocking(get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.attach(opencv.getName());
eyesTracking.attachPan(head.eyeX.getName());
eyesTracking.attachTilt(head.eyeY.getName());
return eyesTracking;
}
public InMoov2Head startHead() {
speakBlocking(get("STARTINGHEAD"));
startPeer("head");
startPeer("mouthControl");
return head;
}
public void startHeadTracking() {
if (opencv == null) {
startOpenCV();
}
if (head == null) {
startHead();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.attach(opencv.getName());
headTracking.attachPan(head.rothead.getName());
headTracking.attachTilt(head.neck.getName());
// TODO: where are the PID values?
}
}
public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception {
if (opencv == null) {
startOpenCV();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.attach(opencv.getName());
headTracking.attachPan(rothead.getName());
headTracking.attachTilt(neck.getName());
// TODO: where are the PID values?
}
return headTracking;
}
public InMoov2Arm startLeftArm() {
speakBlocking(get("STARTINGLEFTARM"));
leftArm = (InMoov2Arm) startPeer("leftArm");
isLeftArmActivated = true;
return leftArm;
}
public InMoov2Hand startLeftHand() {
speakBlocking(get("STARTINGLEFTHAND"));
leftHand = (InMoov2Hand) startPeer("leftHand");
isLeftHandActivated = true;
return leftHand;
}
// TODO - general objective "might" be to reduce peers down to something
// that does not need a reference - where type can be switched before creation
// and the only thing needed is pubs/subs that are not handled in abstracts
public SpeechSynthesis startMouth() {
// FIXME - bad to have a reference, should only need the "name" of the
// service !!!
mouth = (SpeechSynthesis) startPeer("mouth");
voices = mouth.getVoices();
Voice voice = mouth.getVoice();
if (voice != null) {
voiceSelected = voice.getName();
}
isMouthActivated = true;
if (mute) {
mouth.setMute(true);
}
mouth.attachSpeechRecognizer(ear);
// mouth.attach(htmlFilter); // same as chatBot not needed
// this.attach((Attachable) mouth);
// if (ear != null) ....
broadcastState();
speakBlocking(get("STARTINGMOUTH"));
if (Platform.isVirtual()) {
speakBlocking(get("STARTINGVIRTUALHARD"));
}
speakBlocking(get("WHATISTHISLANGUAGE"));
return mouth;
}
public InMoov2Arm startRightArm() {
speakBlocking(get("STARTINGRIGHTARM"));
rightArm = (InMoov2Arm) startPeer("rightArm");
isRightArmActivated = true;
return rightArm;
}
public InMoov2Hand startRightHand() {
speakBlocking(get("STARTINGRIGHTHAND"));
rightHand = (InMoov2Hand) startPeer("rightHand");
isRightHandActivated = true;
return rightHand;
}
public Double getUltrasonicRightDistance() {
if (ultrasonicRight != null) {
return ultrasonicRight.range();
} else {
warn("No UltrasonicRight attached");
return 0.0;
}
}
public Double getUltrasonicLeftDistance() {
if (ultrasonicLeft != null) {
return ultrasonicLeft.range();
} else {
warn("No UltrasonicLeft attached");
return 0.0;
}
}
public void startServos() {
startHead();
startLeftArm();
startLeftHand();
startRightArm();
startRightHand();
startTorso();
}
// FIXME .. externalize in a json file included in InMoov2
public Simulator startSimulator() throws Exception {
speakBlocking(get("STARTINGVIRTUAL"));
if (simulator != null) {
log.info("start called twice - starting simulator is reentrant");
return simulator;
}
simulator = (JMonkeyEngine) startPeer("simulator");
// DEPRECATED - should just user peer info
isSimulatorActivated = true;
// adding InMoov2 asset path to the jmonkey simulator
String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName();
File check = new File(assetPath);
log.info("loading assets from {}", assetPath);
if (!check.exists()) {
log.warn("%s does not exist");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
// jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into
// /resource/JMonkeyEngine/assets
simulator.loadModels(assetPath);
simulator.setRotation(getName() + ".head.jaw", "x");
simulator.setRotation(getName() + ".head.neck", "x");
simulator.setRotation(getName() + ".head.rothead", "y");
simulator.setRotation(getName() + ".head.rollNeck", "z");
simulator.setRotation(getName() + ".head.eyeY", "x");
simulator.setRotation(getName() + ".head.eyeX", "y");
// simulator.setRotation(getName() + ".head.eyelidLeft", "x");FIXME we need
// to modelize them in Blender
// simulator.setRotation(getName() + ".head.eyelidRight", "x");FIXME we need
// to modelize them in Blender
simulator.setRotation(getName() + ".torso.topStom", "z");
simulator.setRotation(getName() + ".torso.midStom", "y");
simulator.setRotation(getName() + ".torso.lowStom", "x");
simulator.setRotation(getName() + ".rightArm.bicep", "x");
simulator.setRotation(getName() + ".leftArm.bicep", "x");
simulator.setRotation(getName() + ".rightArm.shoulder", "x");
simulator.setRotation(getName() + ".leftArm.shoulder", "x");
simulator.setRotation(getName() + ".rightArm.rotate", "y");
simulator.setRotation(getName() + ".leftArm.rotate", "y");
simulator.setRotation(getName() + ".rightArm.omoplate", "z");
simulator.setRotation(getName() + ".leftArm.omoplate", "z");
simulator.setRotation(getName() + ".rightHand.wrist", "y");
simulator.setRotation(getName() + ".leftHand.wrist", "y");
simulator.setMapper(getName() + ".head.jaw", 0, 180, -5, 80);
simulator.setMapper(getName() + ".head.neck", 0, 180, 20, -20);
simulator.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30);
simulator.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140);
simulator.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE
// there
// need
// to be
// two eyeX (left and
// right?)
// simulator.setMapper(getName() + ".head.eyelidLeft", 0, 180, 40,
// 140);FIXME we need to modelize them in Blender
// simulator.setMapper(getName() + ".head.eyelidRight", 0, 180, 40,
// 140);FIXME we need to modelize them in Blender
simulator.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80);
simulator.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80);
simulator.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180);
simulator.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180);
simulator.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60);
simulator.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60);
simulator.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30);
simulator.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130);
simulator.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30);
simulator.multiMap(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3");
simulator.setRotation(getName() + ".leftHand.thumb1", "y");
simulator.setRotation(getName() + ".leftHand.thumb2", "x");
simulator.setRotation(getName() + ".leftHand.thumb3", "x");
simulator.multiMap(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3");
simulator.setRotation(getName() + ".leftHand.index", "x");
simulator.setRotation(getName() + ".leftHand.index2", "x");
simulator.setRotation(getName() + ".leftHand.index3", "x");
simulator.multiMap(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3");
simulator.setRotation(getName() + ".leftHand.majeure", "x");
simulator.setRotation(getName() + ".leftHand.majeure2", "x");
simulator.setRotation(getName() + ".leftHand.majeure3", "x");
simulator.multiMap(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3");
simulator.setRotation(getName() + ".leftHand.ringFinger", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger2", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger3", "x");
simulator.multiMap(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3");
simulator.setRotation(getName() + ".leftHand.pinky", "x");
simulator.setRotation(getName() + ".leftHand.pinky2", "x");
simulator.setRotation(getName() + ".leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
simulator.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100);
simulator.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20);
simulator.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20);
// right hand
simulator.multiMap(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3");
simulator.setRotation(getName() + ".rightHand.thumb1", "y");
simulator.setRotation(getName() + ".rightHand.thumb2", "x");
simulator.setRotation(getName() + ".rightHand.thumb3", "x");
simulator.multiMap(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3");
simulator.setRotation(getName() + ".rightHand.index", "x");
simulator.setRotation(getName() + ".rightHand.index2", "x");
simulator.setRotation(getName() + ".rightHand.index3", "x");
simulator.multiMap(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3");
simulator.setRotation(getName() + ".rightHand.majeure", "x");
simulator.setRotation(getName() + ".rightHand.majeure2", "x");
simulator.setRotation(getName() + ".rightHand.majeure3", "x");
simulator.multiMap(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3");
simulator.setRotation(getName() + ".rightHand.ringFinger", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger2", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger3", "x");
simulator.multiMap(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3");
simulator.setRotation(getName() + ".rightHand.pinky", "x");
simulator.setRotation(getName() + ".rightHand.pinky2", "x");
simulator.setRotation(getName() + ".rightHand.pinky3", "x");
simulator.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10);
simulator.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110);
simulator.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150);
simulator.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160);
// We set the correct location view
simulator.cameraLookAt(getName() + ".torso.lowStom");
// additional experimental mappings
/*
* simulator.attach(getName() + ".leftHand.pinky", getName() +
* ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb",
* getName() + ".leftHand.index3"); simulator.setRotation(getName() +
* ".leftHand.index2", "x"); simulator.setRotation(getName() +
* ".leftHand.index3", "x"); simulator.setMapper(getName() +
* ".leftHand.index", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index2", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index3", 0, 180, -90, -270);
*/
return simulator;
}
public InMoov2Torso startTorso() {
return startTorso(null);
}
public InMoov2Torso startTorso(String port) {
speakBlocking(get("STARTINGTORSO"));
isTorsoActivated = true;
torso = (InMoov2Torso) startPeer("torso");
return torso;
}
/**
* called with only port - will default with defaulted pins
*
* @param port
* port for the sensor
* @return the ultrasonic sensor service
*/
public UltrasonicSensor startUltrasonicRight(String port) {
return startUltrasonicRight(port, 64, 63);
}
/**
* called explicitly with pin values
*
* @param port
* p
* @param trigPin
* trigger pin
* @param echoPin
* echo pin
* @return the ultrasonic sensor
*
*/
public UltrasonicSensor startUltrasonicRight(String port, int trigPin, int echoPin) {
if (ultrasonicRight == null) {
speakBlocking(get("STARTINGULTRASONICRIGHT"));
isUltrasonicRightActivated = true;
ultrasonicRight = (UltrasonicSensor) startPeer("ultrasonicRight");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attach(ultrasonicRight, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultrasonicRight;
}
public UltrasonicSensor startUltrasonicLeft() {
return startUltrasonicLeft(null, 64, 63);
}
public UltrasonicSensor startUltrasonicRight() {
return startUltrasonicRight(null, 64, 63);
}
public UltrasonicSensor startUltrasonicLeft(String port) {
return startUltrasonicLeft(port, 64, 63);
}
public UltrasonicSensor startUltrasonicLeft(String port, int trigPin, int echoPin) {
if (ultrasonicLeft == null) {
speakBlocking(get("STARTINGULTRASONICLEFT"));
isUltrasonicLeftActivated = true;
ultrasonicLeft = (UltrasonicSensor) startPeer("ultrasonicLeft");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(ultrasonicLeft, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultrasonicLeft;
}
public Pir startPir(String port) {
return startPir(port, 23);
}
public Pir startPir(String port, int pin) {
if (pir == null) {
speakBlocking(get("STARTINGPIR"));
isPirActivated = true;
pir = (Pir) startPeer("pir");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attachPinListener(pir, pin);
} catch (Exception e) {
error(e);
}
}
}
return pir;
}
/**
* config delegated startPir ... hopefully
*
* @return
*/
public Pir startPir() {
if (pir == null) {
speakBlocking(get("STARTINGPIR"));
isPirActivated = true;
pir = (Pir) startPeer("pir");
try {
pir.load(); // will this work ?
// would be great if it did - offloading configuration
// to the i01.pir.yml
} catch (Exception e) {
error(e);
}
}
return pir;
}
public ServoMixer startServoMixer() {
servoMixer = (ServoMixer) startPeer("servoMixer");
isServoMixerActivated = true;
speakBlocking(get("STARTINGSERVOMIXER"));
broadcastState();
return servoMixer;
}
public void stop() {
if (head != null) {
head.stop();
}
if (rightHand != null) {
rightHand.stop();
}
if (leftHand != null) {
leftHand.stop();
}
if (rightArm != null) {
rightArm.stop();
}
if (leftArm != null) {
leftArm.stop();
}
if (torso != null) {
torso.stop();
}
}
public void stopChatBot() {
speakBlocking(get("STOPCHATBOT"));
releasePeer("chatBot");
isChatBotActivated = false;
}
public void stopHead() {
speakBlocking(get("STOPHEAD"));
releasePeer("head");
releasePeer("mouthControl");
isHeadActivated = false;
}
public void stopEar() {
speakBlocking(get("STOPEAR"));
releasePeer("ear");
isEarActivated = false;
broadcastState();
}
public void stopOpenCV() {
speakBlocking(get("STOPOPENCV"));
isOpenCvActivated = false;
releasePeer("opencv");
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public void stopLeftArm() {
speakBlocking(get("STOPLEFTARM"));
releasePeer("leftArm");
isLeftArmActivated = false;
}
public void stopLeftHand() {
speakBlocking(get("STOPLEFTHAND"));
releasePeer("leftHand");
isLeftHandActivated = false;
}
public void stopMouth() {
speakBlocking(get("STOPMOUTH"));
releasePeer("mouth");
// TODO - potentially you could set the field to null in releasePeer
mouth = null;
isMouthActivated = false;
}
public void stopRightArm() {
speakBlocking(get("STOPRIGHTARM"));
releasePeer("rightArm");
isRightArmActivated = false;
}
public void stopRightHand() {
speakBlocking(get("STOPRIGHTHAND"));
releasePeer("rightHand");
isRightHandActivated = false;
}
public void stopTorso() {
speakBlocking(get("STOPTORSO"));
releasePeer("torso");
isTorsoActivated = false;
}
public void stopSimulator() {
speakBlocking(get("STOPVIRTUAL"));
releasePeer("simulator");
simulator = null;
isSimulatorActivated = false;
}
public void stopUltrasonicRight() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultrasonicRight");
isUltrasonicRightActivated = false;
}
public void stopUltrasonicLeft() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultrasonicLeft");
isUltrasonicLeftActivated = false;
}
public void stopPir() {
speakBlocking(get("STOPPIR"));
releasePeer("pir");
isPirActivated = false;
}
public void stopNeopixelAnimation() {
if (neopixel != null) {
neopixel.clear();
} else {
warn("No Neopixel attached");
}
}
public void stopServoMixer() {
speakBlocking(get("STOPSERVOMIXER"));
releasePeer("servoMixer");
isServoMixerActivated = false;
}
public void waitTargetPos() {
if (head != null) {
head.waitTargetPos();
}
if (leftArm != null) {
leftArm.waitTargetPos();
}
if (rightArm != null) {
rightArm.waitTargetPos();
}
if (leftHand != null) {
leftHand.waitTargetPos();
}
if (rightHand != null) {
rightHand.waitTargetPos();
}
if (torso != null) {
torso.waitTargetPos();
}
}
public NeoPixel startNeopixel() {
return startNeopixel(getName() + ".right", 2, 16);
}
public NeoPixel startNeopixel(String controllerName) {
return startNeopixel(controllerName, 2, 16);
}
public NeoPixel startNeopixel(String controllerName, int pin, int numPixel) {
if (neopixel == null) {
try {
neopixel = (NeoPixel) startPeer("neopixel");
speakBlocking(get("STARTINGNEOPIXEL"));
// FIXME - lame use peers
isNeopixelActivated = true;
neopixel.attach(Runtime.getService(controllerName));
} catch (Exception e) {
error(e);
}
}
return neopixel;
}
@Override
public void attachTextListener(String name) {
addListener("publishText", name);
}
public Tracking getEyesTracking() {
return eyesTracking;
}
public Tracking getHeadTracking() {
return headTracking;
}
public void startBrain() {
startChatBot();
}
public void startMouthControl() {
speakBlocking(get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) getPeer("mouth"));
}
@Deprecated /* wrong function name should be startPir */
public void startPIR(String port, int pin) {
startPir(port, pin);
}
// These are methods added that were in InMoov1 that we no longer had in
// InMoov2.
// From original InMoov1 so we don't loose the
@Override
public void onJointAngles(Map<String, Double> angleMap) {
log.info("onJointAngles {}", angleMap);
// here we can make decisions on what ik sets we want to use and
// what body parts are to move
for (String name : angleMap.keySet()) {
ServiceInterface si = Runtime.getService(name);
if (si != null && si instanceof ServoControl) {
((Servo) si).moveTo(angleMap.get(name));
}
}
}
@Override
public ServiceConfig getConfig() {
InMoov2Config config = new InMoov2Config();
// config.isController3Activated = isController3Activated;
// config.isController4Activated = isController4Activated;
// config.enableEyelids = isEyeLidsActivated;
config.enableChatBot = isChatBotActivated;
config.enableHead = isHeadActivated;
config.enableLeftArm = isLeftArmActivated;
config.enableLeftHand = isLeftHandActivated;
config.enableLeftHandSensor = isLeftHandSensorActivated;
// config.isLeftPortActivated = isLeftPortActivated;
config.enableNeoPixel = isNeopixelActivated;
config.enableOpenCV = isOpenCvActivated;
config.enablePir = isPirActivated;
config.enableUltrasonicRight = isUltrasonicRightActivated;
config.enableUltrasonicLeft = isUltrasonicLeftActivated;
config.enableRightArm = isRightArmActivated;
config.enableRightHand = isRightHandActivated;
config.enableRightHandSensor = isRightHandSensorActivated;
// config.isRightPortActivated = isRightPortActivated;
// config.enableSimulator = isSimulatorActivated;
config.autoStartPeers = false;
return config;
}
public void startAudioPlayer() {
startPeer("audioPlayer");
}
public void stopAudioPlayer() {
releasePeer("audioPlayer");
}
public ServiceConfig apply(ServiceConfig c) {
InMoov2Config config = (InMoov2Config) c;
try {
if (config.locale != null) {
setLocale(config.locale);
}
if (config.enableAudioPlayer) {
startAudioPlayer();
} else {
stopAudioPlayer();
}
/**
* <pre>
* FIXME -
* - there simply should be a single reference to the entire config object in InMoov
* e.g. InMoov2Config config member
* - if these booleans are symmetric - there should be corresponding functionality of "stopping/releasing" since they
* are currently starting
* </pre>
*/
/*
* FIXME - very bad - need some coordination with this
*
* if (config.isController3Activated) { startPeer("controller3"); // FIXME
* ... this kills me :P exec("isController3Activated = True"); }
*
* if (config.isController4Activated) { startPeer("controller4"); // FIXME
* ... this kills me :P exec("isController4Activated = True"); }
*/
/*
* if (config.enableEyelids) { // the hell if I know ? }
*/
loadGestures = config.loadGestures;
if (config.enableHead) {
startHead();
} else {
stopHead();
}
if (config.enableLeftArm) {
startLeftArm();
} else {
stopLeftArm();
}
if (config.enableLeftHand) {
startLeftHand();
} else {
stopLeftHand();
}
if (config.enableLeftHandSensor) {
// the hell if I know ?
}
/*
* if (config.isLeftPortActivated) { // the hell if I know ? is this an
* Arduino ? startPeer("left"); } // else release peer ?
*
* if (config.enableNeoPixel) { startNeopixel(); } else { //
* stopNeopixelAnimation(); }
*/
if (config.enableOpenCV) {
startOpenCV();
} else {
stopOpenCV();
}
/*
* if (config.enablePir) { startPir(); } else { stopPir(); }
*/
if (config.enableRightArm) {
startRightArm();
} else {
stopRightArm();
}
if (config.enableRightHand) {
startRightHand();
} else {
stopRightHand();
}
if (config.enableRightHandSensor) {
// the hell if I know ?
}
/*
* if (config.isRightPortActivated) { // the hell if I know ? is this an
* Arduino ? }
*/
if (config.enableServoMixer) {
startServoMixer();
} else {
stopServoMixer();
}
if (config.enableTorso) {
startTorso();
} else {
stopTorso();
}
if (config.enableUltrasonicLeft) {
startUltrasonicLeft();
} else {
stopUltrasonicLeft();
}
if (config.enableUltrasonicRight) {
startUltrasonicRight();
} else {
stopUltrasonicRight();
}
if (config.enablePir) {
startPir();
} else {
stopPir();
}
if (config.enableNeoPixel) {
startNeopixel();
} else {
stopNeopixelAnimation();
}
if (config.loadGestures) {
loadGestures = true;
loadGestures();
// will load in startService
}
if (config.enableSimulator) {
startSimulator();
}
} catch (Exception e) {
error(e);
}
return c;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Platform.setVirtual(true);
// Runtime.start("s01", "Servo");
Runtime.start("intro", "Intro");
InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2");
Plan plan = Runtime.load("webgui", "WebGui");
WebGuiConfig webgui = (WebGuiConfig) plan.get("webgui");
webgui.autoStartBrowser = false;
Runtime.start("webgui");
boolean done = true;
if (done) {
return;
}
Random random = (Random) Runtime.start("random", "Random");
random.addRandom(3000, 8000, "i01", "setLeftArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "setRightArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "moveRightArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0);
random.addRandom(3000, 8000, "i01", "moveLeftArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0);
random.addRandom(3000, 8000, "i01", "setLeftHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "setRightHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0);
random.addRandom(3000, 8000, "i01", "moveRightHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 130.0, 175.0);
random.addRandom(3000, 8000, "i01", "moveLeftHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 5.0, 40.0);
random.addRandom(200, 1000, "i01", "setHeadSpeed", 8.0, 20.0, 8.0, 20.0, 8.0, 20.0);
random.addRandom(200, 1000, "i01", "moveHead", 70.0, 110.0, 65.0, 115.0, 70.0, 110.0);
random.addRandom(200, 1000, "i01", "setTorsoSpeed", 2.0, 5.0, 2.0, 5.0, 2.0, 5.0);
random.addRandom(200, 1000, "i01", "moveTorso", 85.0, 95.0, 88.0, 93.0, 70.0, 110.0);
random.save();
// i01.setVirtual(false);
// i01.getConfig();
// i01.save();
// Runtime.start("s02", "Servo");
i01.startChatBot();
i01.startAll("COM3", "COM4");
Runtime.start("python", "Python");
// Runtime.start("log", "Log");
/*
* OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV");
* cv.setCameraIndex(2);
*/
// i01.startSimulator();
/*
* Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
* mega.connect("/dev/ttyACM0");
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
@Override
public void onRegistered(Registration registration) {
// TODO Auto-generated method stub
}
@Override
public void onStopped(String name) {
// TODO Auto-generated method stub
}
@Override
public void onReleased(String name) {
// TODO Auto-generated method stub
}
} |
package com.smartcodeunited.lib.bluetooth.managers;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.smartcodeunited.lib.bluetooth.commands.CommandManager;
import com.smartcodeunited.lib.bluetooth.commands.CommandProtocol;
import com.smartcodeunited.lib.bluetooth.tools.LogManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class BLEDeviceManager {
// / send data
private static BluetoothGattCharacteristic writeCharacteristic; // / write
// Characteristicuuid for test.
private static String uuidQppService = "0000fee9-0000-1000-8000-00805f9b34fb";
// Characteristicuuid for test.
private static String uuidQppCharWrite = "d44bc439-abfd-45a2-b575-925416129600";
public static final int qppServerBufferSize = 20;
// / receive data
private static BluetoothGattCharacteristic notifyCharacteristic;
private static ArrayList<BluetoothGattCharacteristic> arrayNtfCharList = new ArrayList<BluetoothGattCharacteristic>();
/**
* notify Characteristic
*/
private static byte notifyCharaIndex = 0;
private static boolean NotifyEnabled = false;
private static final String UUIDDes = "00002902-0000-1000-8000-00805f9b34fb";
public interface OnConnectionListener {
/**
* @param mBluetoothGatt
* @param state connected:1,disconnected:2.
*/
public void onConnectionStateChanged(BluetoothGatt mBluetoothGatt, int state);
}
private static BLEDeviceManager sBLEDeviceManager = new BLEDeviceManager();
private static OnConnectionListener sOnConnectionListener;
private static BluetoothGatt mBluetoothGatt = null;
private Context mContext;
private BluetoothDevice mDevice;
private static Handler handler = new Handler();
protected static final String TAG = BLEDeviceManager.class.getSimpleName();
private BLEDeviceManager() {
}
public static BLEDeviceManager getInstance() {
if (sBLEDeviceManager != null)
sBLEDeviceManager = new BLEDeviceManager();
return sBLEDeviceManager;
}
public static BluetoothGatt getBluetoothGatt() {
return mBluetoothGatt;
}
public static String getAddress() {
String address = null;
if (mBluetoothGatt != null)
address = mBluetoothGatt.getDevice().getAddress();
return address;
}
public static String getName() {
String name = null;
if (mBluetoothGatt != null)
name = mBluetoothGatt.getDevice().getName();
return name;
}
public static boolean isServicesDiscovered;
/**
* Connection status Listener
*
* @param onConnectionListener
*/
public void setOnConnectionListener(OnConnectionListener onConnectionListener) {
sOnConnectionListener = onConnectionListener;
Log.d(TAG, "setOnConnectionListener" + (sOnConnectionListener == null));
}
public void connectBLEDevice(Context context, BluetoothDevice device) {
closeGatt();
mContext = context;
mDevice = device;
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
Log.i("tag", "connect " + mDevice.getName());
}
/**
* Implements callback methods for GATT events that the app cares about. For example,
connection change and services discovered.
*/
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i(TAG, "onConnectionStateChange : " + status + " newState : "
+ newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
closeGatt();
}
sOnConnectionListener.onConnectionStateChanged(gatt, newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
isServicesDiscovered = setEnable(gatt, uuidQppService, uuidQppCharWrite);
}
/**
* Write callback
* @param gatt
* @param characteristic
* @param status
*/
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
// Log.e(TAG, status==BluetoothGatt.GATT_SUCCESS?"Send success!!":"Send failed!!");
Log.d(TAG, status + "--" + Arrays.toString(characteristic.getValue()));
}
/**
* After the feature value is sent to the device, the device feedback application
* @param gatt
* @param characteristic
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
updateValueForNotification(gatt, characteristic);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
setLENextNotify(gatt, true);
}
};
/**
* Initialize some of the necessary UUID
*
* @param bluetoothGatt
* @param qppServiceUUID Modified of ServiceUUID
* @param writeCharUUID Modified of writeCharUUID
* @return
*/
//TODO Can be confused
private boolean setEnable(BluetoothGatt bluetoothGatt,
String qppServiceUUID, String writeCharUUID) {
resetQppField();
if (qppServiceUUID != null)
uuidQppService = qppServiceUUID;
if (writeCharUUID != null)
uuidQppCharWrite = writeCharUUID;
if (bluetoothGatt == null) {//|| qppServiceUUID.isEmpty()|| writeCharUUID.isEmpty()
Log.e(TAG, "invalid arguments");
return false;
}
BluetoothGattService qppService = bluetoothGatt.getService(UUID
.fromString(uuidQppService));
if (qppService == null) {
Log.e(TAG, "Qpp service not found");
return false;
}
List<BluetoothGattCharacteristic> gattCharacteristics = qppService
.getCharacteristics();
for (int j = 0; j < gattCharacteristics.size(); j++) {
BluetoothGattCharacteristic chara = gattCharacteristics.get(j);
if (chara.getUuid().toString().equals(uuidQppCharWrite)) {
// Log.i(TAG,"Wr char is "+chara.getUuid().toString());
writeCharacteristic = chara;
} else if (chara.getProperties() == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
// Log.i(TAG,"NotiChar UUID is : "+chara.getUuid().toString());
notifyCharacteristic = chara;
arrayNtfCharList.add(chara);
}
}
if (!setCharacteristicNotification(bluetoothGatt,arrayNtfCharList.get(0), true))
return false;
notifyCharaIndex++;
return true;
}
private static void resetQppField() {
writeCharacteristic = null;
notifyCharacteristic = null;
arrayNtfCharList.clear();
// NotifyEnabled=false;
notifyCharaIndex = 0;
}
private boolean setLENextNotify(BluetoothGatt bluetoothGatt,
boolean EnableNotifyChara) {
if (notifyCharaIndex == arrayNtfCharList.size()) {
NotifyEnabled = true;
return true;
}
return setCharacteristicNotification(bluetoothGatt,
arrayNtfCharList.get(notifyCharaIndex++), EnableNotifyChara);
}
private boolean setCharacteristicNotification(
BluetoothGatt bluetoothGatt,
BluetoothGattCharacteristic characteristic, boolean enabled) {
if (bluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return false;
}
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
try {
BluetoothGattDescriptor descriptor = characteristic
.getDescriptor(UUID.fromString(UUIDDes));
if (descriptor != null) {
descriptor
.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
return (bluetoothGatt.writeDescriptor(descriptor));
} else {
Log.e(TAG, "descriptor is null");
return false;
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return true;
}
/**
* Receiving device data
*
* @param bluetoothGatt
* @param characteristic
*/
private void updateValueForNotification(BluetoothGatt bluetoothGatt,
BluetoothGattCharacteristic characteristic) {
if (bluetoothGatt == null || characteristic == null) {
Log.e(TAG, "invalid arguments");
return;
}
if (!NotifyEnabled) {
Log.e(TAG, "The notifyCharacteristic not enabled");
return;
}
String strUUIDForNotifyChar = characteristic.getUuid().toString();
final byte[] receiveData = characteristic.getValue();
// if (qppData != null && qppData.length > 0)
// OnVoltageListener.onQppReceiveData(bluetoothGatt, strUUIDForNotifyChar,
// qppData);
LogManager.d(TAG, "receive-->" + receiveData);
// printLog(receiveData);
if (CommandManager.isCommandValid(receiveData)) {
parse(receiveData);
}
}
/**
* send data to device
* @param bluetoothGatt
* @param qppData
* @return
*/
private boolean sendData(BluetoothGatt bluetoothGatt,
String qppData) {
boolean ret = false;
if (bluetoothGatt == null) {
Log.e(TAG, "BluetoothAdapter not initialized !");
return false;
}
if (qppData == null) {
Log.e(TAG, "qppData = null !");
return false;
}
writeCharacteristic.setValue(qppData);
return bluetoothGatt.writeCharacteristic(writeCharacteristic);
}
/**
* send data to device
* @param bluetoothGatt
* @param bytes
* @return
*/
private boolean sendData(BluetoothGatt bluetoothGatt, byte[] bytes) {
boolean ret = false;
if (bluetoothGatt == null) {
Log.e(TAG, "BluetoothAdapter not initialized !");
return false;
}
if (bytes == null) {
Log.e(TAG, "qppData = null !");
return false;
}
writeCharacteristic.setValue(bytes);
return bluetoothGatt.writeCharacteristic(writeCharacteristic);
}
/**
* parse the receive command
* @param commands
*/
private void parse(final byte[] commands) {
handler.post(new Runnable() {
@Override
public void run() {
switch (commands[0]) {
case CommandProtocol.Type.FEEDBACK_INQUIRY: {
}
break;
}
}
});
}
public void closeGatt() {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
public void disConnectBLEDevice() {
if (mBluetoothGatt == null) {
Log.w("Qn Dbg", "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
mBluetoothGatt=null;
}
} |
package org.narwhal.query;
import java.util.Collections;
import java.util.List;
/**
* QueryCreator is a class which is responsible for creating string representation of the CRUD SQL statements.
* */
public class QueryCreator {
/**
* Builds up a string representation of an INSERT SQL statement for the subsequent usage in a prepared statement.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @param columns Array of the table's columns
* @return String representation of the INSERT SQL statement.
* */
public String buildInsertQuery(String tableName, List<String> columns) {
return "INSERT INTO " + tableName + " (" + join(columns, ",") + ") VALUES (" + join("?", columns.size(), ",") + ')';
}
/**
* Builds up a string representation of an SELECT SQL statement for the subsequent usage in a prepared statement.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @param columns Array of the table's columns
* @param primaryKeys Primary column names.
* @return String representation of the SELECT SQL statement.
* */
public String buildSelectQuery(String tableName, List<String> columns, List<String> primaryKeys) {
return "SELECT " + join(columns, ",") + " FROM " + tableName + buildWhereClause(primaryKeys);
}
/**
* Builds up a string representation of an DELETE SQL statement for the subsequent usage in a prepared statement.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @param primaryKeys Primary column names.
* @return String representation of the DELETE SQL statement.
* */
public String buildDeleteQuery(String tableName, List<String> primaryKeys) {
return "DELETE FROM " + tableName + buildWhereClause(primaryKeys);
}
/**
* Builds up a string representation of an UPDATE SQL statement for the subsequent usage in a prepared statement.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @param columns Array of the table's columns
* @param primaryKeys Primary column names.
* @return String representation of the UPDATE SQL statement.
* */
public String buildUpdateQuery(String tableName, List<String> columns, List<String> primaryKeys) {
return "UPDATE " + tableName + " SET " + join(columns, ",", " = ?") + buildWhereClause(primaryKeys);
}
private String buildWhereClause(List<String> primaryKeys) {
return " WHERE " + join(primaryKeys, " AND ", " = ?");
}
private String join(String filler, int size, String delimiter) {
return join(Collections.nCopies(size, filler), delimiter);
}
private String join(List<String> values, String delimiter) {
return join(values, delimiter, "");
}
private String join(List<String> values, String delimiter, String afterValue) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
builder.append(delimiter);
}
builder.append(values.get(i));
builder.append(afterValue);
}
return builder.toString();
}
} |
package gov.nih.nci.evs.browser.test.performance;
import org.LexGrid.LexBIG.DataModel.Core.*;
import org.LexGrid.LexBIG.Utility.Iterators.*;
import gov.nih.nci.evs.browser.properties.*;
import gov.nih.nci.evs.browser.test.utils.*;
import gov.nih.nci.evs.browser.utils.*;
import gov.nih.nci.evs.browser.utils.test.*;
public class SearchUtilsTest extends SearchUtils {
private int _runAmount = 1;
private boolean _suppressOtherMessages = true;
private boolean _displayParameters = false;
private boolean _displayConcepts = false;
private boolean _displayResults = true;
public SearchUtilsTest() {
super(null);
}
public ResolvedConceptReferencesIteratorWrapper searchByName(String scheme,
String version, String matchText, String source, String matchAlgorithm,
boolean ranking, int maxToReturn) {
if (_displayParameters) {
DBG.debug("* Search parameters:");
DBG.debug(" * scheme = " + scheme);
DBG.debug(" * version = " + version);
DBG.debug(" * matchText = " + matchText);
DBG.debug(" * source = " + source);
DBG.debug(" * matchAlgorithm = " + matchAlgorithm);
DBG.debug(" * ranking = " + ranking);
DBG.debug(" * maxToReturn = " + maxToReturn);
}
DBG.debug(DBG.isDisplayDetails(), "* Details: " + matchAlgorithm + " " + matchText);
return super.searchByName(scheme, version, matchText, source,
matchAlgorithm, ranking, maxToReturn);
}
public void searchByNameTest(String scheme, String version, String matchText,
String source, String matchAlgorithm, boolean ranking,
int maxToReturn) throws Exception {
DBG.clearTabbbedValues();
Utils.StopWatch stopWatch = new Utils.StopWatch();
ResolvedConceptReferencesIteratorWrapper wrapper = searchByName(scheme, version, matchText,
source, matchAlgorithm, ranking, maxToReturn);
ResolvedConceptReferencesIterator iterator = wrapper.getIterator();
int n = iterator.numberRemaining(), i=0;
long duration = stopWatch.getDuration();
if (_displayConcepts && n > 0) {
DBG.debug("* List of concepts:");
while (iterator.hasNext()) {
ResolvedConceptReference ref = iterator.next();
String code = ref.getCode();
String name = ref.getEntityDescription().getContent();
DBG.debug(" " + (++i) + ") " + code + " " + name);
}
}
if (_displayResults) {
DBG.debug("* Result: " + matchAlgorithm + " " + matchText);
DBG.debug(" * Number of concepts: " + n);
DBG.debug(" * Total run time: " + stopWatch.getResult(duration));
}
if (DBG.isDisplayTabDelimitedFormat()) {
i=0;
DBG.debugTabbedValue(i++, "* Tabbed", "");
DBG.debugTabbedValue(i++, "Keyword", matchText);
DBG.debugTabbedValue(i++, "Algorithm", matchAlgorithm);
DBG.debugTabbedValue(i++, "Hits", n);
DBG.debugTabbedValue(i++, "Run Time", stopWatch.formatInSec(duration));
DBG.displayTabbedValues();
}
}
private void prompt() {
boolean isTrue = false;
DBG.debug("* Prompt (" + getClass().getSimpleName() + "):");
_runAmount = Prompt.prompt(
" * How many concepts", _runAmount);
_suppressOtherMessages = Prompt.prompt(
" * Suppress other debugging messages", _suppressOtherMessages);
Debug.setDisplay(!_suppressOtherMessages);
_displayParameters = Prompt.prompt(" * Display parameters",
_displayParameters);
isTrue = Prompt.prompt(" * Display details", DBG.isDisplayDetails());
DBG.setDisplayDetails(isTrue);
_displayConcepts = Prompt.prompt(" * Display concepts", _displayConcepts);
_displayResults = Prompt.prompt(" * Display results", _displayResults);
isTrue = Prompt.prompt(" * Display tab delimited",
DBG.isDisplayTabDelimitedFormat());
DBG.setDisplayTabDelimitedFormat(isTrue);
}
private void runTest() throws Exception {
String scheme = "NCI MetaThesaurus";
String version = null;
String matchAlgorithm = "contains";
String source = "ALL";
boolean ranking = true;
int maxToReturn = -1;
String[] matchTexts = new String[] {
"100",
"bone",
"blood",
"allele",
"tumor",
"cancer",
"gene",
"neoplasm",
"grade",
"cell",
"ctcae",
"carcinoma",
"infection",
"event",
// "adverse",
"stage",
"device",
"protein",
"gland",
"injury"
};
// matchAlgorithm = "exactMatch";
// matchTexts = new String[] { "cell" };
NCImBrowserProperties.getInstance();
DBG.debug("* EVS_SERVICE_URL: " + NCImBrowserProperties
.getProperty(NCImBrowserProperties.EVS_SERVICE_URL));
DBG.debug("* matchTexts: " + Utils.toString(matchTexts));
DBG.debug("* matchAlgorithm: " + matchAlgorithm);
prompt();
for (int i = 0; i < matchTexts.length; ++i) {
if (i >= _runAmount)
break;
String matchText = matchTexts[i];
if (DBG.isDisplayDetails()) {
DBG.debug("");
DBG.debug(Utils.SEPARATOR);
}
searchByNameTest(scheme, version, matchText, source, matchAlgorithm,
ranking, maxToReturn);
}
DBG.debug("* Done");
}
public static void main(String[] args) {
try {
DBG.setPerformanceTesting(true);
SearchUtilsTest test = new SearchUtilsTest();
boolean isContinue = true;
do {
test.runTest();
DBG.debug("");
DBG.debug(Utils.SEPARATOR);
isContinue = Prompt.prompt("Rerun", isContinue);
if (!isContinue)
break;
} while (isContinue);
DBG.debug("Done");
DBG.setPerformanceTesting(false);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package org.pfaa.chemica.model;
import java.awt.Color;
import org.pfaa.chemica.model.ChemicalStateProperties.Gas;
import org.pfaa.chemica.model.ChemicalStateProperties.Liquid;
import org.pfaa.chemica.model.ChemicalStateProperties.Liquid.Yaws;
import org.pfaa.chemica.model.ChemicalStateProperties.Solid;
import org.pfaa.chemica.model.Formula.PartFactory;
import org.pfaa.chemica.model.Hazard.SpecialCode;
import org.pfaa.chemica.model.Vaporization.AntoineCoefficients;
public enum Element implements Chemical, PartFactory, Metal {
/*
H He
Li Be B C N O F Ne
Na Mg Al Si P S Cl Ar
K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
R Sr Y Zr Nb Mo Tc Rb Rh Pd Ag Cd In Sn Sb Te I Xe
Cs Ba Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
Ce La Pr Nd ...
.. Th .. U ...
*/
H("hydrogen", Category.DIATOMIC_NONMETAL, null, 1.00, +1), /* See Molecules.H2 for properties */
He("helium", Category.NOBLE_GAS, null, 4.00, 0,
new Solid(0.187,
new Thermo(9.85)), // artificial, He is weird
new Fusion(0.95),
new Liquid(0.13,
new Thermo(-8.33, 18.4E3, -7.72E6, 1.18E9, 3.89E-6, 0.047, 11.8)),
new Vaporization(4.22),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 151))),
Li("lithium", Category.ALKALI_METAL, Strength.WEAK, 6.94, +1,
new Solid(new Color(240, 240, 240), 0.534,
new Thermo(170, -883, 1977, -1487, -1.61, -31.2, 414),
new Hazard(3, 2, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(454),
new Liquid(0.512,
new Thermo(32.5, -2.64, -6.33, 4.23, 0.00569, -7.12, 74.3)
.addSegment(700, 26.0, 5.63, -4.01, 0.874, 0.344, -4.20, 66.4)),
new Vaporization(1603),
new Gas(new Thermo(23.3, -2.77, 0.767, -0.00360, -0.0352, 152, 166))),
Be("beryllium", Category.ALKALINE_EARTH_METAL, Strength.STRONG, 9.01, +2,
new Solid(new Color(40, 40, 40), 1.85,
new Thermo(21.2, 5.69, 0.968, -0.00175, -0.588, -8.55, 30.1)
.addSegment(1527, 30.0, -0.000396, 0.000169, -0.000026, -0.000105, -6.97, 40.8),
new Hazard(3, 1, 0)),
new Fusion(1560),
new Liquid(1.69,
new Thermo(25.4, 2.16, -0.00257, 0.000287, 0.00396, 5.44, 44.5)),
new Vaporization(3243),
new Gas(new Thermo(28.6, -5.38, 1.04, -0.0121, -426, 308, 164))),
B("boron", Category.METALLOID, Strength.VERY_STRONG, 10.8, +3,
new Solid(new Color(82, 53, 7), 2.37,
new Thermo(10.2, 29.2, -18.0, 4.21, -0.551, -6.04, 7.09)
.addSegment(1800, 25.1, 1.98, 0.338, -0.0400, -2.64, -14.4, 25.6),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(2349),
new Liquid(2.08,
new Thermo(48.9, 26.5, 31.8)),
new Vaporization(4200),
new Gas(new Thermo(20.7, 0.226, -0.112, 0.0169, 0.00871, 554, 178))),
C("carbon", Category.POLYATOMIC_NONMETAL, Strength.WEAK /* graphite */, 12.0, +4,
new Solid(new Color(38, 33, 33), 2.27,
new Thermo(0, 6.0, 9.25).addSegment(300, 10.7),
new Hazard(0, 1, 0)),
null,
null,
new Vaporization(3915),
new Gas(new Thermo(21.2, -0.812, 0.449, -0.0433, -0.0131, 710, 184))),
N("nitrogen", Category.DIATOMIC_NONMETAL, null, 14.0, -3), /* see Compounds.N2 for properties */
O("oxygen", Category.DIATOMIC_NONMETAL, null, 16.0, -2), /* See Compounds.O2 for properties */
F("fluorine", Category.DIATOMIC_NONMETAL, null, 19.0, -1), /* See Compounds.F2 for properties, solid density 1.7 */
Ne("neon", Category.NOBLE_GAS, null, 20.2, 0,
new Solid(1.44,
new Thermo(14.3)),
new Fusion(24.6),
new Liquid(1.21,
new Thermo(27.9)),
new Vaporization(3.76, 95.6, -1.50),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 171))),
Na("sodium", Category.ALKALI_METAL, Strength.WEAK, 23.0, +1,
new Solid(new Color(212, 216, 220), 0.968,
new Thermo(72.6, -9.49, -731, 1415, -1.26, -21.8, 155),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(371),
new Liquid(0.927,
new Thermo(40.3, -28.2, 20.7, -3.64, -0.0799, -8.78, 114)),
new Vaporization(2.46, 1874, -416),
new Gas(new Thermo(20.8, 0.277, -0.392, 0.120, -0.00888, 101, 179))),
Mg("magnesium", Category.ALKALINE_EARTH_METAL, Strength.MEDIUM, 24.3, +2,
new Solid(new Color(157, 157, 157), 1.74,
new Thermo(26.5, -1.53, 8.06, 0.572, -0.174, -8.50, 63.9),
new Hazard(0, 1, 1)),
new Fusion(923),
new Liquid(1.58,
new Thermo(4.79, 34.5, 34.3)),
new Vaporization(1363),
new Gas(new Thermo(20.8, 0.0356, -0.0319, 0.00911, 0.000461, 141)
.addSegment(2200, 47.6, -15.4, 2.88, -0.121, -27.0, 97.4, 177))),
Al("aluminum", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 31.0, +5,
new Solid(new Color(177, 177, 177), 2.70,
new Thermo(28.1, -5.41, 8.56, 3.43, -0.277, -9.15, 61.9),
new Hazard(0, 1, 1)),
new Fusion(933),
new Liquid(2.38,
new Thermo(10.6, 39.6, 31.8)),
new Vaporization(5.74, 13204, -24.3),
new Gas(new Thermo(20.4, 0.661, -0.314, 0.0451, 0.0782, 324, 189))),
Si("silicon", Category.METALLOID, Strength.STRONG, 28.1, +4,
new Solid(new Color(206, 227, 231), 2.33,
new Thermo(22.8, 3.90, -0.0829, 0.0421, -0.354, -8.16, 43.3)),
new Fusion(1687),
new Liquid(2.57, new Thermo(48.5, 44.5, 27.2))),
P("phosphorus", Category.POLYATOMIC_NONMETAL, null, 31.0, +5,
new Solid(Color.white, 1.82,
new Thermo(16.5, 43.3, -58.7, 25.6, -0.0867, -6.66, 50.0),
new Hazard(4, 4, 2)),
new Fusion(317.2),
new Liquid(1.74,
new Thermo(26.3, 1.04, -6.12, 1.09, 3.00, -7.23, 74.9)),
new Vaporization(553),
new Gas(new Thermo(20.4, 1.05, -1.10, 0.378, 0.011, 310, 188)
.addSegment(2200, -2.11, 9.31, -0.558, -0.020, 29.3, 354, 190))
),
S("sulfur", Category.POLYATOMIC_NONMETAL, Strength.WEAK, 32.1, +4,
new Solid(new Color(230, 230, 25), 2,
new Thermo(21.2, 3.87, 22.3, -10.3, -0.0123, -7.09, 55.5),
new Hazard()),
new Fusion(388),
new Liquid(1.82,
new Thermo(4541, 26066, -55521, 42012, 54.6, 788, -10826)
.addSegment(432, -37.9, 133, -95.3, 24.0, 7.65, 29.8, -13.2)),
new Vaporization(718),
new Gas(new Thermo(27.5, -13.3, 10.1, -2.66, -0.00558, 269, 204)
.addSegment(1400, 16.6, 2.40, -0.256, 0.00582, 3.56, 278, 195))
),
Cl("chlorine", Category.DIATOMIC_NONMETAL, null, 34.5, -1), /* See Compounds.Cl2 for properties */
Ar("argon", Category.NOBLE_GAS, null, 39.9, 0,
new Solid(1.62,
new Thermo(38)),
new Fusion(83.8),
new Liquid(1.21,
new Thermo(128)),
new Vaporization(3.30, 215, -22.3),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 180))),
K("potassium", Category.ALKALI_METAL, Strength.WEAK, 39.1, +1,
new Solid(new Color(219, 219, 219), 0.862,
new Thermo(-63.5, -3226, 14644, -16229, 16.3, 120, 534),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(337),
new Liquid(0.828, new Thermo(40.3, -30.5, 26.5, -5.73, -0.0635, -8.81, 128)),
new Vaporization(new AntoineCoefficients(4.46, 4692, 24.2)),
new Gas(new Thermo(20.7, 0.392, -0.417, 0.146, 0.00376, 82.8, 185)
.addSegment(1800, 58.7, -27.4, 6.73, -0.421, -25.9, 32.4, 198))),
Ca("calcium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 40.1, +2,
new Solid(new Color(228, 237, 237), 1.55,
new Thermo(19.8, 10.1, 14.5, -5.53, 0.178, -5.86, 62.9),
new Hazard(3, 1, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(1115),
new Liquid(1.38, new Thermo(7.79, 45.5, 35.0)),
new Vaporization(new AntoineCoefficients(2.78, 3121, -595)),
new Gas(new Thermo(122, -75, 19.2, -1.40, -64.5, 42.2, 217))),
// Skipped Sc
Ti("titanium", Category.TRANSITION_METAL, Strength.STRONG, 47.9, +4,
new Solid(new Color(230, 230, 230), 4.51,
new Thermo(23.1, 5.54, -2.06, 1.61, -0.0561, -0.433, 64.1),
new Hazard(1, 1, 2)),
new Fusion(1941),
new Liquid(4.11, new Thermo(13.7, 39.2, -22.1)),
new Vaporization(3560),
new Gas(new Thermo(9.27, 6.09, 0.577, -0.110, 6.50, 483, 204))),
V("vanadium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 50.9, +5,
new Solid(new Color(145, 170, 190), 6.0,
new Thermo(26.3, 1.40, 2.21, 0.404, -0.176, -8.52, 59.3),
new Hazard(2, 1, 0)),
new Fusion(2183),
new Liquid(5.5, new Thermo(17.3, 36.1, 46.2)),
new Vaporization(3680),
new Gas(new Thermo(32.0, -9.12, 2.94, -0.190, 1.41, 505, 220))),
Cr("chromium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 52.0, +3,
new Solid(new Color(212, 216, 220), 7.19,
new Thermo(7.49, 71.5, -91.7, 46.0, 0.138, -4.23, 15.8)
.addSegment(600, 18.5, 5.48, 7.90, -1.15, 1.27, -2.68, 48.1),
new Hazard(2, 1, 1)),
new Fusion(2180),
new Liquid(6.3, new Thermo(21.6, 36.2, 39.3)),
new Vaporization(2944),
new Gas(new Thermo(13.7, -3.42, 0.394, -16.7, 383, 183, 397))),
Mn("manganese", Category.TRANSITION_METAL, Strength.STRONG, 54.9, +4,
new Solid(new Color(212, 216, 220), 7.21,
new Thermo(27.2, 5.24, 7.78, -2.12, -0.282, -9.37, 61.5)
.addSegment(980, 52.3, -28.7, 21.5, -4.98, -2.43, -21.2, 90.7)
.addSegment(1361, 19.1, 31.4, -15.0, 3.21, 1.87, -2.76, 48.8)
.addSegment(1412, -534, 679, -296, 46.4, 161, 469, -394)),
new Fusion(1519),
new Liquid(5.95, new Thermo(16.3, 43.5, 46.0)),
new Vaporization(2334),
new Gas(new Thermo(188, -97.8, 20.2, -1.27, -177, 1.55, 220))),
Fe("iron", Category.TRANSITION_METAL, Strength.STRONG, 55.8, +3,
new Solid(Color.lightGray, 7.87,
new Thermo(24.0, 8.37, 0.000277, -8.60E-5, -5.00E-6, 0.268, 62.1),
new Hazard(1, 1, 0)),
new Fusion(1811),
new Liquid(6.98, new Thermo(12, 35, 46.0)),
new Vaporization(3134),
new Gas(new Thermo(11.3, 6.99, -1.11, 0.122, 5.69, 424, 206))),
Co("cobalt", Category.TRANSITION_METAL, Strength.STRONG, 58.9, +2,
new Solid(Color.lightGray, 8.90,
new Thermo(11.0, 54.4, -55.5, 25.8, 0.165, -4.70, 30.3)
.addSegment(700, -205, 516, -422, 130, 18.0, 94.6, -273)
.addSegment(1394, -12418, 15326, -7087, 1167, 3320, 10139, -10473)),
new Fusion(1768),
new Liquid(7.75,
new Thermo(45.6, -3.81, 1.03, -0.0967, -3.33, -8.14, 78.0)),
new Vaporization(3200),
new Gas(new Thermo(40.7, -8.46, 1.54, -0.0652, -11.1, 397, 213))),
Ni("nickel", Category.TRANSITION_METAL, Strength.MEDIUM, 58.7, +2,
new Solid(new Color(160, 160, 140), 8.91,
new Thermo(13.7, 82.5, -175, 162, -0.0924, -6.83, 27.7)
.addSegment(600, 1248, -1258, 0, 0, -165, -789, 1213)
.addSegment(700, 16.5, 18.7, -6.64, 1.72, 1.87, -0.468, 51.7),
new Hazard(2, 4, 1)),
new Fusion(1728),
new Liquid(7.81, new Thermo(17.5, 41.5, 38.9)),
new Vaporization(3186),
new Gas(new Thermo(27.1, -2.59, 0.295, 0.0152, 0.0418, 421, 214))),
Cu("copper", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2,
new Solid(new Color(208, 147, 29), 8.96,
new Thermo(17.7, 28.1, -31.3, 14.0, 0.0686, -6.06, 47.9),
new Hazard(1, 1, 0)),
new Fusion(1358),
new Liquid(8.02, new Thermo(17.5, 41.5, 32.8)),
new Vaporization(2835),
new Gas(new Thermo(-80.5, 49.4, -7.58, 0.0405, 133, 520, 194))),
Zn("zinc", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2,
new Solid(new Color(230, 230, 230), 7.14,
new Thermo(25.6, -4.41, 20.4, -7.40, -0.0458, -7.56, 72.9),
new Hazard(2, 0, 0)),
new Fusion(673),
new Liquid(6.57, new Thermo(6.52, 50.8, 31.4)),
new Vaporization(1180),
new Gas(new Thermo(18.2, 2.31, -0.737, 0.0800, 1.07, 127, 185))),
Ga("gallium", Category.POST_TRANSITION_METAL, Strength.WEAK, 69.7, +3,
new Solid(new Color(212, 216, 220), 5.91,
new Thermo(102, -348, 603, -361, -1.49, -24.7, 236),
new Hazard(1, 0, 0)),
new Fusion(303),
new Liquid(6.10, new Thermo(24.6, 2.70, -1.27, 0.197, 0.286, -0.909, 89.9)),
new Vaporization(2673),
new Gas(new Thermo(20.3, 0.570, -0.210, 0.0258, 3.05, 273, 201))),
Ge("germanium", Category.METALLOID, Strength.STRONG, 72.6, +4,
new Solid(new Color(212, 216, 220), 5.32,
new Thermo(0, 31.1, 23.7, 3.57, -0.233, -0.125)),
new Fusion(1211),
new Liquid(5.60, new Thermo(60.5, 97.3, 27.6)),
new Vaporization(3106),
new Gas(new Thermo(377, 168, 30.7))),
As("arsenic", Category.METALLOID, Strength.MEDIUM, 74.9, +3,
new Solid(new Color(112, 112, 112), 5.73,
new Thermo(0, 35.1, 21.6, 9.79),
new Hazard(3, 2, 0)),
null, null,
new Vaporization(887),
new Gas(new Thermo(74.3))),
Se("selenium", Category.POLYATOMIC_NONMETAL, null, 79.0, +4,
new Solid(Color.red, 4.39,
new Thermo(0, 42.0, 16.2, 29.4),
new Hazard(2, 0, 0)),
new Fusion(494),
new Liquid(3.99, new Thermo(11.4, 67.8, 35.2)),
new Vaporization(958),
new Gas(new Thermo(227, 177, 20.8))),
Br("bromine", Category.DIATOMIC_NONMETAL, null, 79.9, -1), // see Compounds.Br2
Kr("krypton", Category.NOBLE_GAS, null, 83.8, 0,
new Solid(2.83,
new Thermo(-14.4, 54.9, -0.910, 291, -3844, 17670, 1.39E-6)),
new Fusion(116),
new Liquid(2.41,
new Thermo(-12.8, 69, 10.4)),
new Vaporization(4.21, 539, 8.86),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 189))),
Rb("rubidium", Category.ALKALI_METAL, Strength.WEAK, 85.5, +1,
new Solid(new Color(175, 175, 175), 1.53,
new Thermo(9.45, 65.3, 45.5, -26.8, -0.108, -6.43, 66.3),
new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)),
new Fusion(312),
new Liquid(1.46, new Thermo(35.5, -12.9, 8.55, -0.00283, -0.000119, -7.90, 130)),
new Vaporization(961),
new Gas(new Thermo(20.6, 0.462, -0.495, 0.174, 0.00439, 74.7, 195)
.addSegment(1800, 74.1, -39.2, 9.91, -0.679, -35.1, 4.97, 214))),
Sr("strontium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 87.6, +2,
new Solid(new Color(212, 216, 220), 2.64,
new Thermo(23.9, 9.30, 0.920, 0.0352, 0.00493, -7.53, 81.8),
new Hazard(4, 0, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(1050),
new Liquid(2.38, new Thermo(0.91, 50.9, 39.5)),
new Vaporization(1650),
new Gas(new Thermo(19.4, 3.74, -3.19, 0.871, 0.0540, 158, 187)
.addSegment(2700, -39.0, -1.70, 7.99, -0.852, 188, 355, 243))),
Y("yttrium", Category.TRANSITION_METAL, null, 88.9, +3,
new Solid(new Color(212, 216, 220), 4.47,
new Thermo(0, 44.4, 24.4, 6.99)),
new Fusion(1799),
new Liquid(4.24, new Thermo(50.7)),
new Vaporization(3203),
new Gas(new Thermo(164))),
Zr("zirconium", Category.TRANSITION_METAL, Strength.STRONG, 91.2, +4,
new Solid(new Color(212, 216, 220), 6.52,
new Thermo(29, -12.6, 20.7, -5.91, -0.157, -8.79, 76.0),
new Hazard(1, 1, 0)),
new Fusion(2128),
new Liquid(5.8, new Thermo(17.4, 47.6, 41.8)),
new Vaporization(4650),
new Gas(new Thermo(39.5, -6.52, 2.26, -0.194, -12.5, 578, 212))),
Nb("niobium", Category.TRANSITION_METAL, Strength.STRONG, 92.9, +5,
new Solid(new Color(135, 150, 160), 8.57,
new Thermo(22.0, 9.89, -5.65, 1.76, 0.0218, -6.88, 60.5),
new Hazard(1, 1, 0)),
new Fusion(2750),
new Liquid(Double.NaN, new Thermo(29.7, 47.3, 33.5)),
new Vaporization(5017),
new Gas(new Thermo(-14637, 5142, -675, 31.5, 47657, 42523, 6194))),
Mo("molybdenum", Category.TRANSITION_METAL, Strength.STRONG, 96, +4,
new Solid(new Color(105, 105, 105), 10.3,
new Thermo(24.7, 3.96, -1.27, 1.15, -0.17, -8.11, 56.4)
.addSegment(1900, 1231, -963, 284, -28, -712, -1486, 574),
new Hazard(1, 3, 0)),
new Fusion(2896),
new Liquid(9.33, new Thermo(41.6, 43.1, 37.7)),
new Vaporization(4912),
new Gas(new Thermo(67.9, -40.5, 11.7, -0.819, -22.1, 601, 232))),
// Skipped Tc
Ru("ruthenium", Category.TRANSITION_METAL, Strength.STRONG, 101, +3,
new Solid(new Color(213, 213, 213), 12.5,
new Thermo(0, 28.5, 19.9, 10.4, -2.27, 0.125),
new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)),
new Fusion(2607),
new Liquid(10.7, new Thermo(109, 105, 22.7, 5.12)),
new Vaporization(4423),
new Gas(new Thermo(264))),
Rh("rhodium", Category.TRANSITION_METAL, Strength.STRONG, 103, +3,
new Solid(new Color(213, 213, 213), 12.4,
new Thermo(0, 31.5, 22.0, 9.98)),
new Fusion(2237),
new Liquid(10.7, new Thermo(107)),
new Vaporization(3968)),
Pd("palladium", Category.TRANSITION_METAL, Strength.MEDIUM, 106, +2,
new Solid(new Color(213, 213, 213), 12.0,
new Thermo(0, 37.6, 22.5, 10.0, -2.63, 0.0622)),
new Fusion(1828),
new Liquid(10.4, new Thermo(62.2, 98.9, 37.2)),
new Vaporization(3236),
new Gas(new Thermo(231))),
Ag("silver", Category.TRANSITION_METAL, Strength.MEDIUM, 108, +1,
new Solid(new Color(213, 213, 213), 10.5,
new Thermo(0, 42.6, 23.4, 6.28),
new Hazard(1, 1, 0)),
new Fusion(1235),
new Liquid(9.32, new Thermo(24.7, 52.3, 339, -45)),
new Vaporization(1.95, 2505, -1195),
new Gas(new Thermo(285, 173, Double.NaN))),
Cd("cadmium", Category.TRANSITION_METAL, Strength.WEAK, 112, +2,
new Solid(new Color(190, 190, 210), 8.65,
new Thermo(0, 51.8, 22.8, 10.3),
new Hazard(2, 2, 0)),
new Fusion(594),
new Liquid(8.00, new Thermo(14.4, 62.2, 29.7)),
new Vaporization(1040),
new Gas(new Thermo(112, 168, 20.8))),
In("indium", Category.POST_TRANSITION_METAL, Strength.WEAK, 115, +3,
new Solid(new Color(190, 190, 210), 7.31,
new Thermo(0, 57.8, 21.4, 17.7)),
new Fusion(430),
new Liquid(7.02, new Thermo(6.93, 75.5, 30.1)),
new Vaporization(2345),
new Gas(new Thermo(216))),
Sn("tin", Category.POST_TRANSITION_METAL, Strength.WEAK, 119, +4,
new Solid(new Color(212, 216, 220), 7.28,
new Thermo(0, 51.2, 23.1, 19.6),
new Hazard(1, 3, 3)),
new Fusion(505),
new Liquid(6.97, new Thermo(13.5, 65.1, 28.7)),
new Vaporization(6.60, 16867, 15.5),
new Gas(new Thermo(168))),
Sb("antimony", Category.METALLOID, Strength.MEDIUM, 122, +3,
new Solid(new Color(212, 216, 220), 6.70,
new Thermo(0, 45.7, 23.1, 7.45), // NOTE: heating is extremely dangerous
new Hazard(4, 4, 2)),
new Fusion(904),
new Liquid(6.53, new Thermo(67.6)),
new Vaporization(2.26, 4475, -152),
new Gas(new Thermo(168))),
Te("tellurium", Category.METALLOID, Strength.MEDIUM, 128, +4,
new Solid(new Color(212, 216, 220), 6.24,
new Thermo(0, 49.7, 19.2, 21.8),
new Hazard(2, 0, 0)),
new Fusion(723),
new Liquid(5.70, new Thermo(12.9, 76.0, 37.7)),
new Vaporization(1261),
new Gas(new Thermo(189))),
I("iodine", Category.DIATOMIC_NONMETAL, null, 127, +4),
Xe("xenon", Category.NOBLE_GAS, null, 131, 0,
new Solid(5.89,
new Thermo(63.6)),
new Fusion(116),
new Liquid(2.41,
new Thermo(-15.4, 81.6, 155)),
new Vaporization(2.84, 327, -49.8),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 195))),
Cs("caesium", Category.ALKALI_METAL, Strength.WEAK, 133, +1,
new Solid(new Color(170, 160, 115), 1.93,
new Thermo(57.0, -50.0, 48.6, -16.7, -1.22, -19.3, 160),
new Hazard(4, 3, 3, SpecialCode.WATER_REACTIVE)),
new Fusion(302),
new Liquid(1.84, new Thermo(30.0, 0.506, 0.348, -0.0995, 0.197, -6.23, 129)),
new Vaporization(3.70, 3453, -26.8),
new Gas(new Thermo(76.5, 175, 20.8)
.addSegment(1000, 34.5, -13.8, 4.13, -0.138, -3.95, 58.2, 211)
.addSegment(4000, -181, 80.0, -9.19, 0.330, 374, 518, 242))),
Ba("barium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 137, +2,
new Solid(new Color(70, 70, 70), 3.51,
new Thermo(83.8, -406, 915, -520, -14.6, 248)
.addSegment(583, 76.7, -188, 296, -114, -4.34, -25.6, 189)
.addSegment(768, 26.2, 28.6, -23.7, 6.95, 1.04, -5.80, 90),
new Hazard(2, 1, 2)),
new Fusion(1000),
new Liquid(3.34, new Thermo(55.0, -18.7, 2.76, 1.28, 3.02, -8.42, 135)),
new Vaporization(4.08, 7599, -45.7),
new Gas(new Thermo(-623, 430, -97.0, 7.47, 488, 1077, 19.0)
.addSegment(4000, 770, -284, 41.4, -2.13, -1693, -1666, -26.3))),
// Skipped Lu and Hf
Ta("tantalum", Category.TRANSITION_METAL, Strength.STRONG, 181, +5,
new Solid(new Color(185, 190, 200), 16.7,
new Thermo(20.7, 17.3, -15.7, 5.61, 0.0616, -6.60, 62.4)
.addSegment(1300, -43.9, 73.0, -27.4, 4.00, 26.3, 60.2, 25.7),
new Hazard(1, 1, 0)),
new Fusion(3290),
new Liquid(15, new Thermo(30.8, 50.4, 41.8)),
new Vaporization(5731),
new Gas(new Thermo(29.5, 3.42, -0.566, 0.0697, -4.93, 763, 208))),
W("tungsten", Category.TRANSITION_METAL, Strength.VERY_STRONG, 184, +6,
new Solid(new Color(140, 140, 140), 19.3,
new Thermo(24.0, 2.64, 1.26, -0.255, -0.0484, -7.43, 60.5)
.addSegment(1900, -22.6, 90.3, -44.3, 7.18, -24.1, -9.98, -14.2),
new Hazard(1, 2, 1)),
new Fusion(3695),
new Liquid(17.6, new Thermo(46.9, 45.7, 35.6)),
new Vaporization(6203),
new Gas(new Thermo(174))),
Re("rhenium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 186, +7,
new Solid(new Color(212, 216, 220), 21.0,
new Thermo(0, 36.9, 26.4, 2.22)),
new Fusion(3459),
new Liquid(18.9, new Thermo(54.4))),
Os("osmium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 190, +4,
new Solid(new Color(190, 180, 240), 22.6,
new Thermo(0, 32.6, 23.6, 3.88)),
new Fusion(3306),
new Liquid(20, new Thermo(119))),
Ir("iridium", Category.TRANSITION_METAL, Strength.STRONG, 190, +4,
new Solid(new Color(212, 216, 220), 25.6,
new Thermo(0, 35.5, 25.1)),
new Fusion(2719),
new Liquid(19, new Thermo(106))),
Pt("platinum", Category.TRANSITION_METAL, Strength.MEDIUM, 195, +4,
new Solid(new Color(235, 235, 235), 22.2,
new Thermo(0, 41.6, 24.3, 5.27)),
new Fusion(2041),
new Liquid(19.8, new Thermo(109))),
Au("gold", Category.TRANSITION_METAL, Strength.MEDIUM, 197, +3,
new Solid(new Color(255, 215, 0), 19.3,
new Thermo(0, 47.4, 23.2, 6.16, -0.618, -0.0355),
new Hazard(2, 0, 0)),
new Fusion(1337),
new Liquid(17.3, new Thermo(57.8)), // FIXME: better thermodynamics for liquid gold!
new Vaporization(5.47, 17292, -71),
new Gas(new Thermo(366, 180, 20.8))),
Hg("mercury", Category.TRANSITION_METAL, null, 201, +2,
new Solid(new Color(155, 155, 155), 14.25,
new Thermo(-2.18, 66.1, 21.5, 29.2)),
new Fusion(234),
new Liquid(new Color(188, 188, 188), 13.5,
new Thermo(0, 75.9, 28),
new Hazard(3, 0, 0),
new Yaws(-0.275, 137, 4.18E-6, -1.20E-9)),
new Vaporization(4.86, 3007, -10.0),
new Gas(new Thermo(20.7, 0.179, -0.0801, 0.0105, 0.00701, 55.2, 200))),
// Skipped Tl
Pb("lead", Category.POST_TRANSITION_METAL, Strength.WEAK, 207, +2,
new Solid(new Color(65, 65, 65), 11.3,
new Thermo(25.0, 5.44, 4.06, -1.24, -0.0107, -7.77, 93.2),
new Hazard(2, 0, 0)),
new Fusion(601),
new Liquid(10.7, new Thermo(38.0, -14.6, 7.26, -1.03, -0.331, -7.94, 119)),
new Vaporization(2022),
new Gas(new Thermo(-85.7, 69.3, -13.3, 0.840, 63.1, 333, 170))),
Bi("bismuth", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 209, +3,
new Solid(new Color(213, 213, 213), 9.78,
new Thermo(0, 56.7, 21.1, 14.7)),
new Fusion(545),
new Liquid(10.1, new Thermo(0 /* dummy */, 77.4, 31.8)),
new Vaporization(1837),
new Gas(new Thermo(175))),
// Skipped Po, At, and many others...
Ce("cerium", Category.LANTHANIDE, null, 140, +3,
new Solid(new Color(212, 216, 220), 6.77,
new Thermo(0, 72.0, 24.6, 0.005),
new Hazard(2, 3, 2)),
new Fusion(1068),
new Liquid(6.55, new Thermo(77.1)),
new Vaporization(3716),
new Gas(new Thermo(184))),
La("lanthanum", Category.LANTHANIDE, null, 139, +3,
new Solid(new Color(212, 216, 220), 6.16,
new Thermo(0, 56.9, 24.7, 4),
new Hazard(2, 3, 2)),
new Fusion(1193),
new Liquid(5.94, new Thermo(62.1)),
new Vaporization(3737),
new Gas(new Thermo(169))),
Nd("neodynium", Category.LANTHANIDE, null, 144, +3,
new Solid(new Color(212, 216, 220), 7.01,
new Thermo(0, 71.6, 26.2, 4),
new Hazard(2, 3, 2)),
new Fusion(1297),
new Liquid(6.89, new Thermo(77.1)),
new Vaporization(3347),
new Gas(new Thermo(163))),
Pr("praseodynium", Category.LANTHANIDE, null, 141, +3,
new Solid(new Color(212, 216, 220), 6.77,
new Thermo(0, 73.2, 26.0, 4),
new Hazard(2, 3, 2)),
new Fusion(1208),
new Liquid(6.50, new Thermo(78.9)),
new Vaporization(3403),
new Gas(new Thermo(176))),
Th("thorium", Category.ACTINIDE, Strength.MEDIUM, 232, +4,
new Solid(new Color(64, 69, 70), 11.7,
new Thermo(0, 51.8, 24.3, 10.2)),
new Fusion(2115),
new Liquid(Double.NaN, new Thermo(58.3)),
new Vaporization(5061),
new Gas(new Thermo(160))),
U("uranium", Category.ACTINIDE, Strength.STRONG, 238, +6,
new Solid(new Color(95, 95, 95), 19.1,
new Thermo(0, 50.2, 9.68, 41.0, -2.65, 53.7)
.addSegment(672, 41, 2.93)
.addSegment(772, 42, 4.79)),
new Fusion(1405),
new Liquid(17.3, new Thermo(56.7)),
new Vaporization(4404),
new Gas(new Thermo(200)))
;
public static enum Category {
ALKALI_METAL,
ALKALINE_EARTH_METAL,
LANTHANIDE,
ACTINIDE,
TRANSITION_METAL,
POST_TRANSITION_METAL,
METALLOID,
POLYATOMIC_NONMETAL,
DIATOMIC_NONMETAL,
NOBLE_GAS,
UNKNOWN;
public boolean isMetal() {
return this.ordinal() < METALLOID.ordinal();
}
public boolean isMetallic() {
return this.ordinal() <= METALLOID.ordinal();
}
}
private Chemical delegate;
private double atomicWeight;
private int defaultOxidationState;
private Category category;
private Strength strength;
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid, Vaporization vaporization,
Gas gas)
{
this.atomicWeight = atomicWeight;
this.defaultOxidationState = defaultOxidationState;
this.category = category;
this.strength = strength;
this.delegate = new SimpleChemical(new Formula(this._(1)), name, solid, fusion, liquid,
vaporization, gas);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid, Vaporization vaporization)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, liquid,
vaporization, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, liquid, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid) {
this(name, category, strength, atomicWeight, defaultOxidationState, solid, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState) {
this(name, category, strength, atomicWeight, defaultOxidationState, null);
}
@Override
public Fusion getFusion() {
return delegate.getFusion();
}
@Override
public Vaporization getVaporization() {
return delegate.getVaporization();
}
@Override
public String getOreDictKey() {
return delegate.getOreDictKey();
}
@Override
public ChemicalConditionProperties getProperties(Condition condition) {
return delegate.getProperties(condition);
}
@Override
public Mixture mix(IndustrialMaterial material, double weight) {
return this.delegate.mix(material, weight);
}
@Override
public Formula getFormula() {
return delegate.getFormula();
}
public Formula.Part _(int quantity) {
return new Formula.Part(this, quantity);
}
@Override
public Formula.Part getPart() {
return this._(1);
}
public double getAtomicWeight() {
return this.atomicWeight;
}
public int getDefaultOxidationState() {
return this.defaultOxidationState;
}
public Alloy alloy(Element solute, double weight) {
return new SimpleAlloy(this, solute, weight);
}
public Category getCategory() {
return this.category;
}
@Override
public Strength getStrength() {
return this.strength;
}
}
} |
package react.client.router;
import common.client.Func;
import elemental.client.Browser;
import react.client.ReactDOM;
import react.client.ReactElement;
import javax.inject.Inject;
import javax.inject.Provider;
public abstract class RootModule extends ModuleLoader {
private final RouteComponent root;
@Inject
RootRoute rootRoute;
@Inject
Provider<RouteGatekeeper> routeGatekeeper;
private Route appRoute;
public RootModule(RouteComponent root) {
super("/");
this.root = root;
}
protected History history() {
return ReactRouter.getHashHistory();
}
@Override
protected void loadRouteBuilder(Func.Run1<RoutesBuilder> run1) {
run1.run(null);
}
protected Route appRoute() {
if (appRoute != null) {
return appRoute;
}
return appRoute = new Route()
.path("/")
.component(root)
.getChildRoutes((partialNextState, callback) -> handle(partialNextState.location.getPathname(), partialNextState.location, callback))
.onEnter((nextState, replaceState) -> routeGatekeeper.get().onEnter(rootRoute, nextState, replaceState))
.onLeave(() -> routeGatekeeper.get().onLeave(rootRoute));
}
public void start(String elementId) {
RouterProps routerProps = new RouterProps();
routerProps.history = history();
routerProps.routes = appRoute();
// Create Router.
final ReactElement router = ReactRouter.create(routerProps);
// Try.run(beforeRender);
// Render.
ReactDOM.render(router, Browser.getDocument().getElementById(elementId));
}
} |
package ru.r2cloud.metrics;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry.MetricSupplier;
@SuppressWarnings("rawtypes")
public class Temperature extends FormattedGauge<Double> implements MetricSupplier<Gauge> {
private static final Logger LOG = LoggerFactory.getLogger(Temperature.class);
private final String fileLocation;
public Temperature(String fileLocation) {
super(MetricFormat.NORMAL);
this.fileLocation = fileLocation;
}
@Override
public Double getValue() {
try (BufferedReader fis = new BufferedReader(new FileReader(fileLocation))) {
String line = fis.readLine();
if (line == null) {
return null;
}
return ((double) Long.valueOf(line) / 1000);
} catch (Exception e) {
LOG.error("unable to get temp", e);
return null;
}
}
@Override
public Gauge<?> newMetric() {
return this;
}
public boolean isAvailable() {
return new File(fileLocation).exists();
}
} |
package rx.broadcast;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
public final class InMemoryBroadcast implements Broadcast {
private final Subject<Object, Object> values;
public InMemoryBroadcast() {
values = PublishSubject.create().toSerialized();
}
@Override
public Observable<Void> send(final Object value) {
return Observable.defer(() -> {
values.onNext(value);
return Observable.empty();
});
}
@Override
@SuppressWarnings("unchecked")
public <T> Observable<T> valuesOfType(final Class<T> clazz) {
return values.filter(clazz::isInstance).cast(clazz);
}
} |
package sds.decompile;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import sds.decompile.stack.LocalStack;
import sds.decompile.stack.OperandStack;
import sds.assemble.BaseContent;
import sds.assemble.MethodContent;
import sds.assemble.controlflow.CFNode;
import sds.assemble.controlflow.CFEdge;
import sds.classfile.bytecode.CpRefOpcode;
import sds.classfile.bytecode.Iinc;
import sds.classfile.bytecode.IndexOpcode;
import sds.classfile.bytecode.InvokeInterface;
import sds.classfile.bytecode.MultiANewArray;
import sds.classfile.bytecode.NewArray;
import sds.classfile.bytecode.OpcodeInfo;
import sds.classfile.bytecode.PushOpcode;
import sds.decompile.cond_expr.ConditionalExprBuilder;
import static sds.assemble.controlflow.CFNodeType.LoopEntry;
import static sds.assemble.controlflow.CFNodeType.LoopExit;
import static sds.assemble.controlflow.CFNodeType.Entry;
import static sds.assemble.controlflow.CFNodeType.OneLineEntry;
import static sds.assemble.controlflow.CFNodeType.OneLineEntryBreak;
import static sds.assemble.controlflow.CFNodeType.Exit;
import static sds.assemble.controlflow.CFNodeType.SynchronizedEntry;
import static sds.assemble.controlflow.CFNodeType.SynchronizedExit;
import static sds.assemble.controlflow.CFEdgeType.TrueBranch;
import static sds.assemble.controlflow.CFEdgeType.FalseBranch;
import static sds.classfile.bytecode.MnemonicTable.*;
import static sds.decompile.DecompiledResult.INCREMENT;
import static sds.assemble.controlflow.NodeTypeChecker.check;
import static sds.assemble.controlflow.NodeTypeChecker.checkNone;
import static sds.util.Printer.println;
/**
* This class is for decompiling contents of method.
* @author inagaki
*/
public class MethodDecompiler extends AbstractDecompiler {
private OperandStack opStack;
private LocalStack local;
private String caller;
/**
* constructor.
* @param result decompiled source
* @param caller caller class has this method
*/
public MethodDecompiler(DecompiledResult result, String caller) {
super(result);
this.caller = caller;
}
@Override
public void decompile(BaseContent content) {
MethodContent method = (MethodContent)content;
this.opStack = new OperandStack();
this.local = new LocalStack();
addAnnotation(method.getAnnotation());
addDeclaration(method);
}
@Override
void addDeclaration(BaseContent content) {
MethodContent method = (MethodContent)content;
StringBuilder methodDeclaration = new StringBuilder();
// access flag
methodDeclaration.append(method.getAccessFlag());
// in case of method is not static initializer
if(! method.getName().equals("<clinit>")) {
if(method.getName().contains("<init>")) {
// in case of Constructor, it is unnecessary return type declaration.
methodDeclaration.append(method.getName().replace("<init>", caller)).append("(");
} else {
String desc = method.getDescriptor();
String returnType = desc.substring(desc.indexOf(")") + 1, desc.length());
methodDeclaration.append(returnType).append(" ").append(method.getName()).append("(");
}
// args
if(! method.getAccessFlag().contains("static")) {
// in case of method is not static, the method has own as argument.
local.push("this", caller);
}
String[][] args = method.getArgs();
int length = args.length;
if(length > 0) {
for(int i = 0; i < length - 1 ; i++) {
methodDeclaration.append(args[i][0]).append(" ").append(args[i][1]).append(", ");
String type = args[i][0];
if(type.matches("double|long")) {
local.push(args[i][1], type);
local.push(args[i][1], type);
} else {
local.push(args[i][1], type);
}
}
String type = args[length - 1][0];
methodDeclaration.append(type).append(" ").append(args[length - 1][1]);
if(type.matches("double|long")) {
local.push(args[length - 1][1], type);
local.push(args[length - 1][1], type);
} else {
local.push(args[length - 1][1], type);
}
}
methodDeclaration.append(") ");
}
// throws statement
if(method.getExceptions().length > 0) {
methodDeclaration.append("throws ");
String[] exceptions = method.getExceptions();
for(int i = 0; i < exceptions.length - 1; i++) {
methodDeclaration.append(exceptions[i]).append(", ");
}
methodDeclaration.append(exceptions[exceptions.length - 1]).append(" ");
}
// abstract or other method
if(method.getAccessFlag().contains("abstract")) {
methodDeclaration.append(";");
} else {
methodDeclaration.append("{");
}
// method declaration
// ex). public void method(int i, int k) throws Exception {...
result.write(methodDeclaration.toString());
// method body
result.changeIndent(INCREMENT);
println("\n>>> " + methodDeclaration + " <<<");
buildMethodBody(method.getNodes());
result.writeEndScope();
}
private void buildMethodBody(CFNode[] nodes) {
boolean typePop = true;
Set<CFNode> falseNode = new HashSet<>();
Set<CFNode> elseNode = new HashSet<>();
Set<CFNode> incrementIgnoreNode = new HashSet<>();
for(int i = 0; i < nodes.length; i++) {
CFNode node = nodes[i];
LineBuilder line = new LineBuilder();
OpcodeInfo[] opcodes = node.getOpcodes().getAll();
boolean addSemicolon = true;
ConditionalExprBuilder builder = null;
LoopStatementBuilder loop = null;
if(elseNode.contains(node) || falseNode.contains(node)) {
result.writeEndScope();
}
if(check(node, LoopEntry)) {
loop = new LoopStatementBuilder();
}
if(check(node, Entry, OneLineEntry, OneLineEntryBreak)) {
builder = new ConditionalExprBuilder();
// There is jump point node of Entry-node in case of FALSE,
// and there is case that the node is not Exit-node.
// then, it doesn't unindent and add end scope to source code.
// so, in the case, it holds FALSE-node,
// and unindents and adds end scope at the time of processing FALSE-node.
if(check(node, Entry)) {
falseNode.add(getIfTerminal(i, node, nodes));
}
}
// opcode analysis
for(OpcodeInfo opcode : opcodes) {
// println(opcode);
// println("local: " + local);
// println("stack: " + opStack);
switch(opcode.getOpcodeType()) {
case nop: break;
case aconst_null: opStack.push("null", "null"); break;
case iconst_m1: opStack.push(-1); break;
case iconst_0: opStack.push(0); break;
case iconst_1: opStack.push(1); break;
case iconst_2: opStack.push(2); break;
case iconst_3: opStack.push(3); break;
case iconst_4: opStack.push(4); break;
case iconst_5: opStack.push(5); break;
case lconst_0: opStack.push(0L); break;
case lconst_1: opStack.push(1L); break;
case fconst_0: opStack.push(0.0f); break;
case fconst_1: opStack.push(1.0f); break;
case fconst_2: opStack.push(2.0f); break;
case dconst_0: opStack.push(0.0d); break;
case dconst_1: opStack.push(1.0d); break;
case bipush:
case sipush:
opStack.push(((PushOpcode)opcode).getValue());
break;
case ldc:
case ldc_w:
case ldc2_w:
CpRefOpcode lcdOpcode = (CpRefOpcode)opcode;
opStack.push(lcdOpcode.getOperand(), lcdOpcode.getType());
break;
case iload:
case lload:
case fload:
case dload:
case aload:
load(((IndexOpcode)opcode).getIndex()); break;
case iload_0:
case lload_0:
case fload_0:
case dload_0:
case aload_0:
load(0); break;
case iload_1:
case lload_1:
case fload_1:
case dload_1:
case aload_1:
load(1); break;
case iload_2:
case lload_2:
case fload_2:
case dload_2:
case aload_2:
load(2); break;
case iload_3:
case lload_3:
case fload_3:
case dload_3:
case aload_3:
load(3); break;
case iaload:
case laload:
case faload:
case daload:
case aaload:
case baload:
case caload:
case saload:
String arrayIndex = opStack.pop(typePop);
String refedArray = opStack.pop();
String arrayType = opStack.popType();
opStack.push(refedArray + "[" + arrayIndex + "]", arrayType);
break;
case istore:
case fstore:
case astore:
case lstore:
case dstore:
IndexOpcode inOp = (IndexOpcode)opcode;
line.append(getStored(inOp.getIndex()));
break;
case istore_0:
case fstore_0:
case astore_0:
case lstore_0:
case dstore_0:
line.append(getStored(0)); break;
case istore_1:
case fstore_1:
case astore_1:
case lstore_1:
case dstore_1:
line.append(getStored(1)); break;
case istore_2:
case fstore_2:
case astore_2:
case lstore_2:
case dstore_2:
line.append(getStored(2)); break;
case istore_3:
case fstore_3:
case astore_3:
case lstore_3:
case dstore_3:
line.append(getStored(3)); break;
case iastore:
case lastore:
case fastore:
case dastore:
case aastore:
case bastore:
case castore:
case sastore:
String storingValue = opStack.pop(typePop);
String primIndex = opStack.pop(typePop);
String arrayRef = opStack.pop(typePop);
line.append(arrayRef, "[", primIndex, "]", " = ", storingValue);
break;
case pop:
line.append(opStack.pop(typePop));
break;
case pop2:
opStack.pop(typePop);
opStack.pop(typePop);
break;
case dup:
String dup = opStack.pop();
String dupType = opStack.popType();
opStack.push(dup, dupType);
opStack.push(dup, dupType);
break;
case dup_x1:
String dup_x1_1 = opStack.pop();
String dup_x1_2 = opStack.pop();
String type_x1_1 = opStack.popType();
String type_x1_2 = opStack.popType();
opStack.push(dup_x1_1, type_x1_1);
opStack.push(dup_x1_2, type_x1_2);
opStack.push(dup_x1_1, type_x1_1);
break;
case dup_x2:
String dup_x2_1 = opStack.pop();
String dup_x2_2 = opStack.pop();
String dup_x2_3 = opStack.pop();
String type_x2_1 = opStack.popType();
String type_x2_2 = opStack.popType();
String type_x2_3 = opStack.popType();
opStack.push(dup_x2_1, type_x2_1);
opStack.push(dup_x2_3, type_x2_3);
opStack.push(dup_x2_2, type_x2_2);
opStack.push(dup_x2_1, type_x2_1);
break;
case dup2:
String dup2_1 = opStack.pop();
String dup2_2 = opStack.pop();
String type2_1 = opStack.popType();
String type2_2 = opStack.popType();
opStack.push(dup2_2, type2_2);
opStack.push(dup2_1, type2_1);
opStack.push(dup2_2, type2_2);
opStack.push(dup2_1, type2_1);
break;
case dup2_x1:
String dup2_x1_1 = opStack.pop();
String dup2_x1_2 = opStack.pop();
String dup2_x1_3 = opStack.pop();
String type2_x1_1 = opStack.popType();
String type2_x1_2 = opStack.popType();
String type2_x1_3 = opStack.popType();
opStack.push(dup2_x1_1, type2_x1_1);
opStack.push(dup2_x1_2, type2_x1_2);
opStack.push(dup2_x1_3, type2_x1_3);
opStack.push(dup2_x1_1, type2_x1_1);
opStack.push(dup2_x1_2, type2_x1_2);
break;
case dup2_x2:
String dup2_x2_1 = opStack.pop();
String dup2_x2_2 = opStack.pop();
String dup2_x2_3 = opStack.pop();
String dup2_x2_4 = opStack.pop();
String type2_x2_1 = opStack.popType();
String type2_x2_2 = opStack.popType();
String type2_x2_3 = opStack.popType();
String type2_x2_4 = opStack.popType();
opStack.push(dup2_x2_1, type2_x2_1);
opStack.push(dup2_x2_2, type2_x2_2);
opStack.push(dup2_x2_4, type2_x2_4);
opStack.push(dup2_x2_3, type2_x2_3);
opStack.push(dup2_x2_2, type2_x2_2);
opStack.push(dup2_x2_1, type2_x2_1);
break;
case swap:
String two = opStack.pop();
String one = opStack.pop();
String typeTwo = opStack.popType();
String typeOne = opStack.popType();
opStack.push(two, typeTwo);
opStack.push(one, typeOne);
break;
case iadd: calculate(" + ", "int"); break;
case ladd: calculate(" + ", "long"); break;
case fadd: calculate(" + ", "float"); break;
case dadd: calculate(" + ", "double"); break;
case isub: calculate(" - ", "int"); break;
case lsub: calculate(" - ", "long"); break;
case fsub: calculate(" - ", "float"); break;
case dsub: calculate(" - ", "double"); break;
case imul: calculate(" * ", "int"); break;
case lmul: calculate(" * ", "long"); break;
case fmul: calculate(" * ", "float"); break;
case dmul: calculate(" * ", "double"); break;
case idiv: calculate(" / ", "int"); break;
case ldiv: calculate(" / ", "long"); break;
case fdiv: calculate(" / ", "float"); break;
case ddiv: calculate(" / ", "double"); break;
case irem: calculate(" % ", "int"); break;
case lrem: calculate(" % ", "long"); break;
case frem: calculate(" % ", "float"); break;
case drem: calculate(" % ", "double"); break;
case ineg:
case lneg:
case fneg:
case dneg:
String minus = "-(" + opStack.pop() + ")";
opStack.push(minus, opStack.popType());
break;
case ishl: calculate(" << ", "int"); break;
case lshl: calculate(" << ", "long"); break;
case ishr: calculate(" >> ", "int"); break;
case lshr: calculate(" >> ", "long"); break;
case iushr: calculate(" >>> ", "int"); break;
case lushr: calculate(" >>> ", "long"); break;
case iand: calculate(" & ", "int"); break;
case land: calculate(" & ", "long"); break;
case ior: calculate(" | ", "int"); break;
case lor: calculate(" | ", "long"); break;
case ixor: calculate(" ^ ", "int"); break;
case lxor: calculate(" ^ ", "long"); break;
case iinc:
Iinc inc = (Iinc)opcode;
line.append(local.load(inc.getIndex()));
int _const = inc.getConst();
if(_const == 1) line.append("++");
else if(_const == -1) line.append("
else if(_const > 1) line.append(" += ").append(_const);
else if(_const < -1) line.append(" -= ").append(_const);
// in case of "_const == 0", ignoring
break;
case i2l: castPrimitive("long"); break;
case i2f: castPrimitive("float"); break;
case i2d: castPrimitive("double"); break;
case l2i: castPrimitive("int"); break;
case l2f: castPrimitive("float"); break;
case l2d: castPrimitive("double"); break;
case f2i: castPrimitive("int"); break;
case f2l: castPrimitive("long"); break;
case f2d: castPrimitive("double"); break;
case d2i: castPrimitive("int"); break;
case d2l: castPrimitive("long"); break;
case d2f: castPrimitive("float"); break;
case i2b: castPrimitive("byte"); break;
case i2c: castPrimitive("char"); break;
case i2s: castPrimitive("short"); break;
case lcmp:
case fcmpl:
case fcmpg:
case dcmpl:
case dcmpg:
String cmpNum_2 = opStack.pop(typePop);
String cmpNum_1 = opStack.pop(typePop);
opStack.push("(" + cmpNum_1 + "OPERATOR" + cmpNum_2 + ")", "boolean");
break;
case ifeq: // (x == y)
String eq = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
if(line.toString().matches("java\\.util\\.Iterator .+ = .+\\.iterator\\(\\)")) {
loop.accept(eq, opStack.popType(), " == ", node);
} else {
loop.accept("(" + line + ")", opStack.popType(), " == ", node);
}
} else {
builder.append(eq, opStack.popType(), " == ", node);
}
line.delete();
break;
case ifne: // (x != y)
String ne = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept("(" + line + ")", opStack.popType(), " != ", node);
} else {
builder.append(ne, opStack.popType(), " != ", node);
}
line.delete();
break;
case iflt: // (x < y)
String lt = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept("(" + line + ")", opStack.popType(), " < ", node);
} else {
builder.append(lt, opStack.popType(), " < ", node);
}
line.delete();
break;
case ifge: // (x >= y)
String ge = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept("(" + line + ")", opStack.popType(), " >= ", node);
} else {
builder.append(ge, opStack.popType(), " >= ", node);
}
line.delete();
break;
case ifgt: // (x > y)
String gt = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept("(" + line + ")", opStack.popType(), " < ", node);
// builder.append("(" + line + ")", opStack.popType(), " > ", node);
} else {
builder.append(gt, opStack.popType(), " > ", node);
}
line.delete();
break;
case ifle: // (x <= y)
String le = opStack.pop();
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept("(" + line + ")", opStack.popType(), " <= ", node);
// builder.append("(" + line + ")", opStack.popType(), " <= ", node);
} else {
builder.append(le, opStack.popType(), " <= ", node);
}
line.delete();
break;
case if_icmpeq:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" == ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" == ", line.toString(), node), node);
}
line.delete();
break;
case if_icmpne:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" != ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" != ", line.toString(), node), node);
}
line.delete();
break;
case if_icmplt:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" < ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" < ", line.toString(), node), node);
}
line.delete();
break;
case if_icmpge:
if(check(node, LoopEntry)) {
if(line.dumppedSize() > 1) {
loop.accept(line.getDumpped(), node);
} else {
loop.accept(line.toString(), node);
}
if(loop.isForEachArray()) {
// in case of "for(Type element : ARRAY)",
// LoopExit node has incremental instruction.
// then, it is necessary to delete increment because
// the increment exists in source code.
incrementIgnoreNode.add(node);
}
loop.accept(makeExprInt(" >= ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" >= ", line.toString(), node), node);
}
line.delete();
break;
case if_icmpgt:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" > ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" > ", line.toString(), node), node);
}
line.delete();
break;
case if_icmple:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" <= ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" <= ", line.toString(), node), node);
}
line.delete();
break;
case if_acmpeq:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" <= ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" <= ", line.toString(), node), node);
}
line.delete();
break;
case if_acmpne:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprInt(" != ", line.toString(), node), node);
} else {
builder.append(makeExprInt(" != ", line.toString(), node), node);
}
line.delete();
break;
case _goto:
if(incrementIgnoreNode.contains(node.getChildren().iterator().next().getDest())) {
line.delete();
break;
}
if((line.length() == 0) && (opStack.size() > 0) && node.getEnd().equals(opcode)) {
line.append(opStack.pop(typePop));
}
if(check(node, OneLineEntryBreak)) {
line.append("break");
}
break;
case jsr: break;
case ret: break;
case tableswitch: break;
case lookupswitch: break;
case ireturn:
case lreturn:
case freturn:
case dreturn:
case areturn:
line.append("return ", opStack.pop(typePop));
break;
case _return:
if(i != nodes.length - 1) {
// in case of this return instruction is not end of opcode,
// specifies "return;".
line.append("return");
}
break;
case getstatic:
CpRefOpcode getSta = (CpRefOpcode)opcode;
// Xxx.yyy.FIELD|type
String[] getStaticField = getSta.getOperand().split("\\|");
opStack.push(getStaticField[0], getStaticField[1]);
break;
case putstatic:
CpRefOpcode putSta = (CpRefOpcode)opcode;
String putStaticField = putSta.getOperand().split("\\|")[0];
line.append(putStaticField, " = ", opStack.pop(typePop));
break;
case getfield:
CpRefOpcode getField = (CpRefOpcode)opcode;
String get[] = getField.getOperand().split("\\|");
String getDeclaration = opStack.pop(typePop) + ".";
String[] getNames = get[0].split("\\.");
opStack.push(getDeclaration + getNames[getNames.length - 1], get[1]);
break;
case putfield:
CpRefOpcode putField = (CpRefOpcode)opcode;
String put = putField.getOperand().split("\\|")[0];
String[] putNames = put.split("\\.");
String value = opStack.pop(typePop);
String putCaller = opStack.pop(typePop);
line.append(putCaller, ".", putNames[putNames.length - 1], " = ", value);
break;
case invokevirtual:
CpRefOpcode virOpcode = (CpRefOpcode)opcode;
// 0: xxx.yyy.zzz.method
// 1: (args_1,args_2,...)returnType
String[] virOperand = virOpcode.getOperand().split("\\|");
String virDesc = virOperand[1];
StringBuilder virtual = new StringBuilder();
String virArgs = getMethodArgs(virDesc);
// xxx.yyy.zzz.method
String[] virMethod = virOperand[0].split("\\.");
// caller.method
virtual.append(opStack.pop(typePop)).append(".").append(virMethod[virMethod.length - 1])
// caller.method(args1,args2,...)
.append("(").append(virArgs).append(")");
if(! pushOntoStack(opcodes, opcode, virtual.toString())) {
line.append(virtual.toString());
}
break;
case invokespecial:
CpRefOpcode specialOpcode = (CpRefOpcode)opcode;
String[] specialOperand = specialOpcode.getOperand().split("\\|");
String spMethod = specialOperand[0].replace(".<init>", "");
String spDesc = specialOperand[1];
// stack: [obj, obj, arg_1, ..., arg_N]
// stack: [obj, obj] (after calling getMethodArgs())
String special = "new " + spMethod + "(" + getMethodArgs(spDesc) + ")";
// stack: [obj]
opStack.pop(typePop);
if(! pushOntoStack(opcodes, opcode, special)) {
line.append(special);
} else {
// stack: [obj, invoked_method]
// stack: [obj]
String element = opStack.pop();
String type = opStack.popType();
// stack: []
if(opStack.size() > 0) {
opStack.pop(typePop);
}
// stack: [invoked_method]
opStack.push(element, type);
}
break;
case invokestatic:
CpRefOpcode staticOpcode =(CpRefOpcode)opcode;
String[] staticOperand = staticOpcode.getOperand().split("\\|");
String staticDesc = staticOperand[1];
String st = staticOperand[0] + "(" + getMethodArgs(staticDesc) + ")";
if(! pushOntoStack(opcodes, opcode, st)) {
line.append(st);
}
break;
case invokeinterface:
InvokeInterface interfaceOpcode = (InvokeInterface)opcode;
String[] interOperand = interfaceOpcode.getOperand().split("\\|");
String interDesc = interOperand[1];
String[] interMethod = interOperand[0].split("\\.");
String interArgs = getMethodArgs(interDesc);
StringBuilder inter = new StringBuilder();
inter.append(opStack.pop(typePop)).append(".").append(interMethod[interMethod.length - 1])
.append("(").append(interArgs).append(")");
if(! pushOntoStack(opcodes, opcode, inter.toString())) {
line.append(inter.toString());
}
break;
case inovokedynamic: break;
case _new:
String newClass = ((CpRefOpcode)opcode).getOperand();
String classType = newClass.replace("/", ".");
opStack.push(classType, classType);
break;
case newarray:
String type = ((NewArray)opcode).getType();
String primLen = opStack.pop(typePop);
opStack.push("new " + type + "[" + primLen + "]", type + "[]");
break;
case anewarray:
String objType = ((CpRefOpcode)opcode).getOperand();
String aNewArrayType = objType.replace("/", ".");
String objLen = opStack.pop(typePop);
opStack.push("new " + aNewArrayType + "[" + objLen + "]", aNewArrayType + "[]");
break;
case arraylength:
opStack.push(opStack.pop(typePop) + ".length", "int");
break;
case athrow: break;
case checkcast:
String casted = ((CpRefOpcode)opcode).getOperand().replace("/", ".");
opStack.push("((" + casted + ")" + opStack.pop(typePop) + ")", casted);
break;
case _instanceof:
String instanceType = ((CpRefOpcode)opcode).getOperand().replace("/", ".");
opStack.push("(" + opStack.pop(typePop) + " instanceof " + instanceType + ")", "boolean");
break;
case monitorenter:
line.delete();
line.append("synchronized(", opStack.pop(typePop), ") {");
addSemicolon = false;
break;
case monitorexit: break;
case wide: break;
case multianewarray:
MultiANewArray mana = (MultiANewArray)opcode;
String multiArrayType = mana.getOperand().replace("/", ".");
String[] dimArray = new String[mana.getDimensions()];
for(int j = 0; j < dimArray.length; j++) {
dimArray[j] = opStack.pop(typePop);
}
StringBuilder manArray = new StringBuilder("new ");
// new XXX
manArray.append(multiArrayType.substring(0, multiArrayType.indexOf("]") - 1));
for(int j = dimArray.length - 1; j > 0; j
manArray.append("[").append(dimArray[j]).append("]");
}
// new XXX[n][m]...
manArray.append("[").append(dimArray[0]).append("]");
opStack.push(manArray.toString(), multiArrayType);
break;
case ifnull:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprNull(" == ", line.toString(), node), node);
} else {
builder.append(makeExprNull(" == ", line.toString(), node), node);
}
line.delete();
break;
case ifnonnull:
if(check(node, LoopEntry)) {
loop.accept(line.toString(), node);
loop.accept(makeExprNull(" != ", line.toString(), node), node);
} else {
builder.append(makeExprNull(" != ", line.toString(), node), node);
}
line.delete();
break;
case goto_w: break;
case jsr_w: break;
case breakpoint: break;
case impdep1: break;
case impdep2: break;
default: break;
}
// println("local: " + local);
// println("line: " + line);
// println("stack: " + opStack + "\n");
}
// checking "else" block
if((! isIfNode(node)) && (node.getParents().size() == 1)) {
CFNode dominator = node.getImmediateDominator();
// in general, when current node is "else" block,
// the node is not Entry, OneLineEntry and OneLineEntryBreak.
// in case of immediate dominator node of current node is
// Entry, OneLineEntry or OneLineEntryBreak, current node is "else" block.
// and, it is necessary to hold terminal node of if-else statement
// for to unindent and add end scope of "else" block.
if(getIfElseTerminal(dominator, nodes[i - 1]) != null) {
elseNode.add(getIfElseTerminal(dominator, nodes[i - 1]));
result.write("else {");
result.changeIndent(INCREMENT);
}
}
if(check(node, LoopEntry)) {
String loopDeclare = line.length() > 0 ? loop.build(line.toString()) : loop.build();
if(loopDeclare.contains("#VAL#")) {
String[] separated = line.toString().split(" ");
loopDeclare = loopDeclare.replace("#VAL#", separated[1]);
}
line = new LineBuilder();
line.append(loopDeclare);
addSemicolon = false;
} else if(isIfNode(node)) {
// elif block
String processing = line.toString();
line = new LineBuilder();
if(isElifBlock(node)) {
line.append("else ");
}
line.append("if").append(builder.build()).append(" ");
addSemicolon = checkNone(node, Entry);
if(addSemicolon) {
line.append(processing);
} else {
line.append("{");
}
}
if(line.length() > 0) {
// When the node is not start or end of a statement, (ex. "if(...) {", "}")
// add semicolon and write in the line context.
if(addSemicolon) {
line.append(";");
}
if(checkNone(node, SynchronizedExit)) {
result.write(line.toString());
}
}
indent(node);
}
}
/**
* in case of specified node is terminal of if-else block, the node has more two parents.
* and, (parents_size - 1) of the parents must be TrueBranch.
*/
private boolean isElseBlock(CFNode ifElseTerminal) {
if(ifElseTerminal == null) {
return false;
}
int parentSize = ifElseTerminal.getParents().size();
if(parentSize > 1) {
int count = 0;
for(CFEdge edge : ifElseTerminal.getParents()) {
CFNode dest = edge.getDest();
if(check(dest, OneLineEntry, OneLineEntryBreak, Exit)) {
count++;
}
}
return count == parentSize - 1;
}
return false;
}
private boolean isElifBlock(CFNode node) {
if(node.getParents().size() == 1) {
CFNode dominator = node.getImmediateDominator();
if(isIfNode(dominator)) {
CFEdge edge = node.getParents().iterator().next();
if(check(node,Entry)) {
// this node has Entry node as immediate dominator node.
// in addition, this node connects to the Entry node with FalseBranch.
// then, this node is "else-if" block.
return edge.getType() == FalseBranch;
} else {
// this node has two nodes in case of if-statement is "true" and "false".
// then, this node is "else-if" block.
return dominator.getChildren().size() == 2;
}
}
}
return false;
}
private boolean isIfNode(CFNode node) {
return check(node, Entry, OneLineEntry, OneLineEntryBreak);
}
private void indent(CFNode node) {
if(check(node, LoopEntry, Entry, SynchronizedEntry)) {
result.changeIndent(INCREMENT);
}
if(check(node, LoopExit, Exit, SynchronizedExit)) {
result.writeEndScope();
}
}
private String makeExprInt(String operator, String line, CFNode node) {
String value_2 = opStack.pop(true);
String value_1 = opStack.pop(true);
if(check(node, LoopEntry) && line.contains(" = ")) {
String[] storeLine = line.split(" = ");
// ex). ((x = ??) > y)
if(storeLine[1].equals(value_1)) {
return "((" + line + ")" + operator + value_2 + ")";
} else if(storeLine[1].equals(value_2)) {
return "(" + value_1 + operator + "(" + line + "))";
}
}
return "(" + value_1 + operator + value_2 + ")";
}
private String makeExprNull(String operator, String line, CFNode node) {
String value = opStack.pop(true);
if(check(node, LoopEntry)) {
// ex). ((val = ??) == null)
return "((" + line + ")" + operator + "null)";
}
return "(" + value + operator + "null)";
}
private void calculate(String operator, String type) {
String value_1 = opStack.pop(true); // right
String value_2 = opStack.pop(true); // left
String expr;
if(operator.contains("<") || operator.contains(">")) {
// shift operator
expr = "(" + value_2 + operator + value_1 + ")";
} else {
expr = "(" + value_1 + operator + value_2 + ")";
}
opStack.push(expr, type);
}
private void load(int index) {
opStack.push(local.load(index), local.loadType(index));
}
private void castPrimitive(String type) {
String casted = "((" + type + ")" + opStack.pop(true) + ")";
opStack.push(casted, type);
}
private String getStored(int index) {
String stored = opStack.pop();
String type = opStack.popType();
int before = local.size();
String value = local.load(index, type);
int after = local.size();
if(before == after) {
// storing
return value + " = " + stored;
}
// declaring
return type + " " + value + " = " + stored;
}
private String getMethodArgs(String descriptor) {
StringBuilder sb = new StringBuilder("");
if((descriptor.indexOf("(") + 1) < descriptor.indexOf(")")) {
String[] args;
if(descriptor.contains(",")){
args = new String[descriptor.split(",").length];
} else {
args = new String[1];
}
// get arguments from stack
for(int j = 0; j < args.length; j++) {
args[j] = opStack.pop(true);
}
// build arguments
// argN-1, argN-2, ..., arg1
for(int j = args.length - 1; j > 0; j
sb.append(args[j]).append(", ");
}
// argN-1, argN-2, ..., arg1, arg0
sb.append(args[0]);
}
return sb.toString();
}
private CFNode getIfTerminal(int index, CFNode target, CFNode[] nodes) {
for(CFEdge edge : target.getChildren()) {
if(edge.getType() == FalseBranch) {
CFNode terminal = edge.getDest();
while(! nodes[index].equals(terminal)) {
index++;
}
if(checkNone(nodes[index - 1], Exit)) {
return terminal;
}
}
}
return null;
}
private CFNode getIfElseTerminal(CFNode dominator, CFNode before) {
CFNode ifElseTerminal = null;
if(isIfNode(dominator)) {
if(check(before, Exit)) {
ifElseTerminal = before.getChildren().iterator().next().getDest();
} else {
for(CFEdge edge : dominator.getChildren()) {
if(edge.getType() == TrueBranch) {
ifElseTerminal = edge.getDest();
}
}
}
}
return isElseBlock(ifElseTerminal) ? ifElseTerminal : null;
}
/**
* this method is for invoke method instruction.
*
* push element onto operand stack
* when specified opcode is end in current node has all opcodes.
*
* in case of the opcode is end,
* it is necessary to push element onto openrand stack
* because there are some processing in the next.
*
* on the other hand, in case of that is not end,
* it is necessary to write processing of invoking method on decompiled source
* because no opcode is in the next.
*
* @param opcodes node has all opcodes
* @param opcode one of the node has opcodes.
* @param element element for pushing onto operand stack
* @return whether pushes element onto operand stack.
*/
private boolean pushOntoStack(OpcodeInfo[] opcodes, OpcodeInfo opcode, String element) {
for(int j = opcodes.length - 1; j >= 0; j
if(opcodes[j].getPc() == opcode.getPc()) {
if(j == opcodes.length - 1) {
// end opcode
return false;
}
CpRefOpcode invoke = (CpRefOpcode)opcode;
String[] operand = invoke.getOperand().split("\\|");
String desc = operand[1];
String type = operand[0].endsWith("<init>") ?
operand[0].replace(".<init>", "") : desc.substring(desc.indexOf(")") + 1);
opStack.push(element, type);
return true;
}
}
throw new IllegalArgumentException("the specified opcode is not in the opcodes.");
}
private class LineBuilder {
private StringBuilder sb;
private List<String> list;
public LineBuilder() {
this.sb = new StringBuilder();
this.list = new ArrayList<>();
}
public int dumppedSize() {
return list.size();
}
public String[] getDumpped() {
return list.toArray(new String[0]);
}
public StringBuilder append(String s) {
list.add(s);
return sb.append(s);
}
public StringBuilder append(String... strs) {
StringBuilder sb = new StringBuilder();
for(String s : strs) {
sb.append(s);
}
list.add(sb.toString());
return this.sb.append(sb.toString());
}
public void delete() {
list.clear();
sb.delete(0, sb.length());
}
public int length() {
return sb.length();
}
@Override
public String toString() {
return sb.toString();
}
}
} |
package seedu.unburden.model.task;
import java.util.Objects;
import seedu.unburden.commons.exceptions.IllegalValueException;
import seedu.unburden.commons.util.CollectionUtil;
import seedu.unburden.model.tag.UniqueTagList;
/**
* Represents a Task in the address book.
* Guarantees: details are present and not null, field values are validated.
*/
public class Task implements ReadOnlyTask {
private Name name;
private Date date;
private Time startTime;
private Time endTime;
private UniqueTagList tags;
/**
* Every field must be present and not null.
*/
public Task(Name name,Date date, Time startTime, Time endTime, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, tags);
this.name = name;
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list
}
/**
* Copy constructor.
*/
public Task(ReadOnlyTask source) {
this(source.getName(), source.getDate(), source.getStartTime(), source.getEndTime(), source.getTags());
}
public Task(Name name, UniqueTagList tags) throws IllegalValueException {
assert !CollectionUtil.isAnyNull(name, tags);
this.name = name;
this.date = new Date("00-00-0000");
this.startTime = new Time("0000");
this.endTime = new Time("0000");
this.tags = new UniqueTagList(tags);
}
public Task(Name name, Date date, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name,date, tags);
this.name = name;
this.date = date;
this.startTime = new Time("0000");
this.endTime = new Time("0000");
this.tags = new UniqueTagList(tags);
}
@Override
public Name getName() {
return name;
}
@Override
public Date getDate() {
return date;
}
@Override
public Time getStartTime() {
return startTime;
}
@Override
public Time getEndTime() {
return endTime;
}
@Override
public UniqueTagList getTags() {
return new UniqueTagList(tags);
}
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(name, tags);
}
@Override
public String toString() {
return getAsText();
}
} |
package seedu.unburden.model.task;
import java.util.Objects;
import seedu.unburden.commons.exceptions.IllegalValueException;
import seedu.unburden.commons.util.CollectionUtil;
import seedu.unburden.model.tag.UniqueTagList;
/**
* Represents a Task in the address book.
* Guarantees: details are present and not null, field values are validated.
* @@author A0143095H
*/
public class Task implements ReadOnlyTask {
private Name name;
private TaskDescription taskD;
private Date date;
private Time startTime;
private Time endTime;
private UniqueTagList tags;
private boolean done;
private String getDoneString;
/**
* Every field must be present and not null.
*/
//@@Nathanael Chan A0139678J
// adds event
public Task(Name name, TaskDescription taskD, Date date, Time startTime, Time endTime, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, taskD, date, startTime, endTime, tags);
this.name = name;
this.taskD = taskD;
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
//this.getDoneString = getDoneString;
this.tags = tags; // protect internal tags from changes in the arg list
}
// adds event without description
public Task(Name name,Date date, Time startTime, Time endTime, UniqueTagList tags) throws IllegalValueException {
assert !CollectionUtil.isAnyNull(name, date, startTime, endTime, tags);
this.name = name;
this.taskD = new TaskDescription(" ");
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
this.tags = tags; // protect internal tags from changes in the arg list
}
// adds deadline
public Task(Name name, TaskDescription taskD, Date date, Time endTime, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, taskD, date, endTime, tags);
this.name = name;
this.taskD = taskD;
this.date = date;
this.startTime = new Time(" ");
this.endTime = endTime;
this.tags = tags;
}
// adds deadline without task description
public Task(Name name, Date date, Time endTime, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, date, endTime, tags);
this.name = name;
this.taskD = new TaskDescription(" ");
this.date = date;
this.startTime = new Time(" ");
this.endTime = endTime;
this.tags = tags;
}
// adds deadline without task description and time
public Task(Name name, Date date, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, date, tags);
this.name = name;
this.taskD = new TaskDescription(" ");
this.date = date;
this.startTime = new Time(" ");
this.endTime = new Time(" ");
this.tags = tags;
}
// adds deadline without task description and date
public Task(Name name, Time endTime, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, endTime, tags);
this.name = name;
this.taskD = new TaskDescription(" ");
this.date = new Date(" ");
this.startTime = new Time(" ");
this.endTime = endTime;
this.tags = tags;
}
// adds deadline without date
public Task(Name name, TaskDescription taskD, Time endTime, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, taskD, endTime, tags);
this.name = name;
this.taskD = taskD;
this.date = new Date(" ");
this.startTime = new Time(" ");
this.endTime = endTime;
this.tags = tags;
}
// adds deadline without time
public Task(Name name, TaskDescription taskD, Date date, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, taskD, date, tags);
this.name = name;
this.taskD = taskD;
this.date = date;
this.startTime = new Time(" ");
this.endTime = new Time (" ");
this.tags = tags;
}
// adds floating Task
public Task(Name name, TaskDescription taskD, UniqueTagList tags) throws IllegalValueException {
assert !CollectionUtil.isAnyNull(name, taskD, tags);
this.name = name;
this.taskD = taskD;
this.date = new Date(" ");
this.startTime = new Time(" ");
this.endTime = new Time(" ");
this.tags = tags;
}
// adds floating task without task description
public Task(Name name, UniqueTagList tags) throws IllegalValueException {
assert!CollectionUtil.isAnyNull(name, tags);
this.name = name;
this.taskD = new TaskDescription(" ");
this.date = new Date(" ");
this.startTime = new Time(" ");
this.endTime = new Time(" ");
this.tags = tags;
}
//@@Nathanael Chan
/**
* Copy constructor.
*/
//@@Gauri Joshi A0143095H
public Task(ReadOnlyTask source) {
this(source.getName(), source.getTaskDescription(), source.getDate(), source.getStartTime(), source.getEndTime(), source.getTags());
}
@Override
public Name getName() {
return name;
}
@Override
public TaskDescription getTaskDescription() {
return taskD;
}
@Override
public Date getDate() {
return date;
}
@Override
public Time getStartTime() {
return startTime;
}
@Override
public Time getEndTime() {
return endTime;
}
@Override
public UniqueTagList getTags() {
return new UniqueTagList(tags);
}
//@@Gauri Joshi A0143095H
@Override
public boolean getDone() {
return done;
}
public String getDoneString(){
if(done){
getDoneString = "Done!";
}
else {
getDoneString = "Undone!";
}
return getDoneString;
}
//@@Gauri Joshi A0143095H
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
public void setName(Name name) {
this.name = name;
}
public void setTaskDescription(TaskDescription taskD) {
this.taskD = taskD;
}
public void setDate(Date date) {
this.date = date;
}
public void setStartTime(Time startTime) {
this.startTime = startTime;
}
public void setEndTime(Time endTime) {
this.endTime = endTime;
}
public void setDone(boolean done) {
this.done = done;
}
public boolean done(){
return false;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(name,taskD,date,startTime,endTime, tags);
}
//@@Gauri Joshi
@Override
public String toString() {
return getAsText();
}
} |
package starpunk.screens;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import starpunk.StarPunkGame;
import starpunk.services.MusicResource;
import starpunk.services.SoundResource;
public final class EndGameScreen
extends Base2DScreen
{
public EndGameScreen( final StarPunkGame game )
{
super( game );
}
@Override
public void show()
{
super.show();
getGame().getMusicManager().play( new MusicResource( "src/main/assets/music/menu.ogg" ) );
final Table table = getTable();
table.defaults().spaceBottom( 30 );
table.add( "High scores" ).colspan( 2 );
final String score = String.valueOf( 0 );
table.row();
table.add( "You" );
table.add( new Label( score, getSkin() ) );
final TextButton backButton = new TextButton( "Back to main menu", getSkin() );
backButton.addListener( new ClickListener()
{
@Override
public void touchUp( final InputEvent event, final float x, final float y, final int pointer, final int button )
{
super.touchUp( event, x, y, pointer, button );
getGame().getSoundManager().play( new SoundResource( "src/main/assets/sounds/click.wav" ) );
getGame().setScreen( new GameLoopScreen( getGame() ) );
}
} );
table.row();
table.add( backButton ).size( 250, 60 ).colspan( 2 );
final Texture background = StarPunkGame.getGame().getAssetManager().getBackground();
final Drawable drawable = new TextureRegionDrawable( new TextureRegion( background ) );
table.setBackground( drawable );
}
@Override
public void hide()
{
super.hide();
getGame().getMusicManager().play( null );
}
} |
package water.util;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LinuxProcFileReader {
private String _systemData;
private String _processData;
private String _pid;
private long _systemIdleTicks = -1;
private long _systemTotalTicks = -1;
private long _processTotalTicks = -1;
private long _processRss = -1;
private int _processNumOpenFds = -1;
/**
* Constructor.
*/
public LinuxProcFileReader() {
}
/**
* @return ticks the system was idle. in general: idle + busy == 100%
*/
public long getSystemIdleTicks() { assert _systemIdleTicks > 0; return _systemIdleTicks; }
/**
* @return ticks the system was up.
*/
public long getSystemTotalTicks() { assert _systemTotalTicks > 0; return _systemTotalTicks; }
/**
* @return ticks this process was running.
*/
public long getProcessTotalTicks() { assert _processTotalTicks > 0; return _processTotalTicks; }
/**
* @return resident set size (RSS) of this process.
*/
public long getProcessRss() { assert _processRss > 0; return _processRss; }
/**
* @return number of currently open fds of this process.
*/
public int getProcessNumOpenFds() { assert _processNumOpenFds > 0; return _processNumOpenFds; }
/**
* @return process id for this node as a String.
*/
public String getProcessID() { return _pid; }
/**
* Read and parse data from /proc/stat and /proc/<pid>/stat.
* If this doesn't work for some reason, the values will be -1.
*/
public void read() {
String pid = "-1";
try {
pid = getProcessId();
_pid = pid;
}
catch (Exception xe) {}
File f = new File ("/proc/stat");
if (! f.exists()) {
return;
}
try {
readSystemProcFile();
readProcessProcFile(pid);
readProcessNumOpenFds(pid);
parseSystemProcFile(_systemData);
parseProcessProcFile(_processData);
}
catch (Exception xe) {}
}
/**
* @return true if all the values are ok to use; false otherwise.
*/
public boolean valid() {
return ((_systemIdleTicks >= 0) && (_systemTotalTicks >= 0) && (_processTotalTicks >= 0) &&
(_processNumOpenFds >= 0));
}
private static String getProcessId() throws Exception {
// Note: may fail in some JVM implementations
// therefore fallback has to be provided
// something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
final String jvmName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('@');
if (index < 1) {
// part before '@' empty (index = 0) / '@' not found (index = -1)
throw new Exception ("Can't get process Id");
}
return Long.toString(Long.parseLong(jvmName.substring(0, index)));
}
private String readFile(File f) throws Exception {
char[] buffer = new char[16 * 1024];
FileReader fr = new FileReader(f);
int bytesRead = 0;
while (true) {
int n = fr.read(buffer, bytesRead, buffer.length - bytesRead);
if (n < 0) {
fr.close();
return new String (buffer, 0, bytesRead);
}
else if (n == 0) {
// This is weird.
fr.close();
throw new Exception("LinuxProcFileReader readFile read 0 bytes");
}
bytesRead += n;
if (bytesRead >= buffer.length) {
fr.close();
throw new Exception("LinuxProcFileReader readFile unexpected buffer full");
}
}
}
private void readSystemProcFile() {
try {
_systemData = readFile(new File("/proc/stat"));
}
catch (Exception xe) {}
}
/**
* @param s String containing contents of proc file.
*/
private void parseSystemProcFile(String s) {
if (s == null) return;
try {
BufferedReader reader = new BufferedReader(new StringReader(s));
String line = reader.readLine();
Pattern p = Pattern.compile("cpu\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+).*");
Matcher m = p.matcher(line);
boolean b = m.matches();
if (! b) {
return;
}
long systemUserTicks = Long.parseLong(m.group(1));
long systemNiceTicks = Long.parseLong(m.group(2));
long systemSystemTicks = Long.parseLong(m.group(3));
_systemIdleTicks = Long.parseLong(m.group(4));
_systemTotalTicks = systemUserTicks + systemNiceTicks + systemSystemTicks + _systemIdleTicks;
}
catch (Exception xe) {}
}
private void readProcessProcFile(String pid) {
try {
String s = "/proc/" + pid + "/stat";
_processData = readFile(new File(s));
}
catch (Exception xe) {}
}
private void parseProcessProcFile(String s) {
if (s == null) return;
try {
BufferedReader reader = new BufferedReader(new StringReader(s));
String line = reader.readLine();
Pattern p = Pattern.compile(
"(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" + "\\s+" +
"(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" + "\\s+" +
"(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" + "\\s+" +
"(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" + "\\s+" +
"(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" + ".*");
Matcher m = p.matcher(line);
boolean b = m.matches();
if (! b) {
return;
}
long processUserTicks = Long.parseLong(m.group(14));
long processSystemTicks = Long.parseLong(m.group(15));
_processTotalTicks = processUserTicks + processSystemTicks;
_processRss = Long.parseLong(m.group(24));
}
catch (Exception xe) {}
}
private void readProcessNumOpenFds(String pid) {
try {
String s = "/proc/" + pid + "/fd";
File f = new File(s);
String[] arr = f.list();
if (arr != null) {
_processNumOpenFds = arr.length;
}
}
catch (Exception xe) {}
}
/**
* Main is purely for command-line testing.
*/
public static void main(String[] args) {
final String sysTestData =
"cpu 43559117 24094 1632164 1033740407 245624 29 200080 0 0 0\n"+
"cpu0 1630761 1762 62861 31960072 40486 15 10614 0 0 0\n"+
"cpu1 1531923 86 62987 32118372 13190 0 6806 0 0 0\n"+
"cpu2 1436788 332 66513 32210723 10867 0 6772 0 0 0\n"+
"cpu3 1428700 1001 64574 32223156 8751 0 6811 0 0 0\n"+
"cpu4 1424410 152 62649 32232602 6552 0 6836 0 0 0\n"+
"cpu5 1427172 1478 58744 32233938 5471 0 6708 0 0 0\n"+
"cpu6 1418433 348 60957 32241807 5301 0 6639 0 0 0\n"+
"cpu7 1404882 182 60640 32258150 3847 0 6632 0 0 0\n"+
"cpu8 1485698 3593 67154 32101739 38387 0 9016 0 0 0\n"+
"cpu9 1422404 1601 66489 32193865 15133 0 8800 0 0 0\n"+
"cpu10 1383939 3386 69151 32233567 11219 0 8719 0 0 0\n"+
"cpu11 1376904 3051 65256 32246197 8307 0 8519 0 0 0\n"+
"cpu12 1381437 1496 68003 32237894 6966 0 8676 0 0 0\n"+
"cpu13 1376250 1527 66598 32247951 7020 0 8554 0 0 0\n"+
"cpu14 1364352 1573 65520 32262764 5093 0 8531 0 0 0\n"+
"cpu15 1359076 1176 64380 32269336 5219 0 8593 0 0 0\n"+
"cpu16 1363844 6 29612 32344252 4830 2 4366 0 0 0\n"+
"cpu17 1477797 1019 70211 32190189 6278 0 3731 0 0 0\n"+
"cpu18 1285849 30 29219 32428612 3549 0 3557 0 0 0\n"+
"cpu19 1272308 0 27306 32445340 2089 0 3541 0 0 0\n"+
"cpu20 1326369 5 29152 32386824 2458 0 4416 0 0 0\n"+
"cpu21 1320883 28 31886 32384709 2327 1 4869 0 0 0\n"+
"cpu22 1259498 1 26954 32458931 2247 0 3511 0 0 0\n"+
"cpu23 1279464 0 26694 32439550 1914 0 3571 0 0 0\n"+
"cpu24 1229977 19 32308 32471217 4191 0 4732 0 0 0\n"+
"cpu25 1329079 92 79253 32324092 5267 0 4821 0 0 0\n"+
"cpu26 1225922 30 34837 32475220 4000 0 4711 0 0 0\n"+
"cpu27 1261848 56 43928 32397341 3552 0 5625 0 0 0\n"+
"cpu28 1226707 20 36281 32463498 3935 4 5943 0 0 0\n"+
"cpu29 1379751 19 35593 32317723 2872 4 5913 0 0 0\n"+
"cpu30 1247661 0 32636 32455845 2033 0 4775 0 0 0\n"+
"cpu31 1219016 10 33804 32484916 2254 0 4756 0 0 0\n"+
"intr 840450413 1194 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 55 0 0 0 0 0 0 45 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 593665 88058 57766 41441 62426 61320 39848 39787 522984 116724 99144 95021 113975 99093 78676 78144 0 168858 168858 168858 162 2986764 4720950 3610168 5059579 3251008 2765017 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"+
"ctxt 1506565570\n"+
"btime 1385196580\n"+
"processes 1226464\n"+
"procs_running 21\n"+
"procs_blocked 0\n"+
"softirq 793917930 0 156954983 77578 492842649 1992553 0 7758971 51856558 228040 82206598\n";
final String procTestData = "16790 (java) S 1 16789 16789 0 -1 4202496 6714145 0 0 0 4773058 5391 0 0 20 0 110 0 33573283 64362651648 6467228 18446744073709551615 1073741824 1073778376 140734614041280 140734614032416 140242897981768 0 0 3 16800972 18446744073709551615 0 0 17 27 0 0 0 0 0\n";
LinuxProcFileReader lpfr = new LinuxProcFileReader();
lpfr.parseSystemProcFile(sysTestData);
lpfr.parseProcessProcFile(procTestData);
System.out.println("System idle ticks: " + lpfr.getSystemIdleTicks());
System.out.println("System total ticks: " + lpfr.getSystemTotalTicks());
System.out.println("Process total ticks: " + lpfr.getProcessTotalTicks());
System.out.println("Process RSS: " + lpfr.getProcessRss());
}
} |
package app.sunstreak.yourpisd.net;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import android.app.Application;
import android.graphics.Bitmap;
public class DataGrabber /*implements Parcelable*/ extends Application {
Domain domain;
String username;
String password;
String[] passthroughCredentials;
String[] gradebookCredentials;
String pageUniqueId;
// 1= success. 0 = not tried; <0 = failure.
int editureLogin = 0;
int gradebookLogin = 0;
ArrayList<String> cookies = new ArrayList<String>();
JSONArray classList = null;
int[][] gradeSummary = null;
// Class -> Term
// Date[][] lastUpdated;
int studentId = 0;
int[] classIds;
/**
* key is of the form {classIndex, termIndex}.
*/
Map<Integer[], JSONObject> classGrades = new HashMap<Integer[], JSONObject>();
// SparseArray<JSONObject> classGrades = new SparseArray<JSONObject>();
String studentName = "";
Bitmap studentPictureBitmap;
int[] classMatch;
public void clearData () {
domain = null;
username = null;
password = null;
}
public void setData (Domain domain, String username, String password) {
// public DataGrabber (Domain domain, String username, String password) {
this.domain = domain;
this.username = username;
this.password = password;
/*
* to accept expired certificate of login1.mypisd.net
*/
//acceptAllCertificates();
}
public int login(/*Domain dom, String username, String password*/)
throws MalformedURLException, IllegalUrlException, IOException, PISDException, InterruptedException, ExecutionException {
String response;
int responseCode;
switch (domain.index) {
case 0: // Parent
Object[] cookieAuth = Request.sendPost(
domain.loginAddress,
"password=" + URLEncoder.encode(password,"UTF-8") + "&username=" + URLEncoder.encode(username,"UTF-8") + "&Submit=Login",
cookies);
response = (String) cookieAuth[0];
responseCode = (Integer) cookieAuth[1];
cookies = (ArrayList<String>) cookieAuth[2];
if (Parser.accessGrantedEditure(response)) {
System.out.println("Editure access granted!");
editureLogin = 1;
passthroughCredentials = Parser.passthroughCredentials(response);
return 1;
}
else {
System.out.println("Bad username/password 1!");
System.out.println(response);
editureLogin = -1;
return -1;
}
case 1: // Student
Object[] portalDefaultPage = Request.sendGet(
domain.loginAddress,
cookies);
response = (String) portalDefaultPage[0];
responseCode = (Integer) portalDefaultPage[1];
cookies = (ArrayList<String>) portalDefaultPage[2];
String[][] requestProperties = new String[][] {
{"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{"Accept-Encoding","gzip,deflate,sdch"},
{"Accept-Language","en-US,en;q=0.8,es;q=0.6"},
{"Cache-Control","max-age=0"},
{"Connection","keep-alive"},
//{"Content-Length","75"},
{"Content-Type","application/x-www-form-urlencoded"},
//{"Cookie","JSESSIONID=22DDAFA488B9D839F082FE26EFE8B38B"},
{"Host","sso.portal.mypisd.net"},
{"Origin","https://sso.portal.mypisd.net"},
{"Referer","https://sso.portal.mypisd.net/cas/login?service=http%3A%2F%2Fportal.mypisd.net%2Fc%2Fportal%2Flogin"}
};
ArrayList<String[]> rp = new ArrayList<String[]>(java.util.Arrays.asList(requestProperties));
String lt = Parser.portalLt(response);
String postParams = "username=" + URLEncoder.encode(username, "UTF-8") +
"&password=" + URLEncoder.encode(password, "UTF-8") +
"<=" + lt +
"&_eventId=submit";
try {
Object[] portalLogin = Request.sendPost(
domain.loginAddress,
cookies,
rp,
true,
postParams);
response = (String) portalLogin[0];
responseCode = (Integer) portalLogin[1];
cookies = (ArrayList<String>) portalLogin[2];
// weird AF way of checking for bad password.
if (Request.getRedirectLocation() == null)
return -1;
Object[] ticket = Request.sendGet(
Request.getRedirectLocation(),
cookies);
if (ticket == null)
return -2;
response = (String) ticket[0];
responseCode = (Integer) ticket[1];
cookies = (ArrayList<String>) ticket[2];
passthroughCredentials = Parser.passthroughCredentials(response);
return 1;
} catch (SocketTimeoutException e) {
e.printStackTrace();
return -2;
}
default:
return 0;
}
}
public boolean loginGradebook(String userType, String uID, String email, String password) throws MalformedURLException, IllegalUrlException, IOException, PISDException {
// commented request paramater is allowed for parent account, not allowed for student account. never required.
String url = "https://parentviewer.pisd.edu/EP/PIV_Passthrough.aspx?action=trans&uT=" + userType + "&uID=" + uID /*+ "&submit=Login+to+Parent+Viewer"*/;
String postParams = "password=" + password + "&username=" + email;
Object[] passthrough = Request.sendPost(
url,
postParams,
cookies);
String response = (String) passthrough[0];
int responseCode = (Integer) passthrough[1];
cookies = (ArrayList<String>) passthrough[2];
String[] gradebookCredentials = Parser.getGradebookCredentials(response);
/*
* escapes if access not granted.
*/
if (Parser.accessGrantedGradebook(gradebookCredentials)) {
System.out.println("Gradebook access granted!");
gradebookLogin = 1;
}
else {
System.out.println("Bad username/password 2!");
gradebookLogin
return false;
}
postParams = "userId=" + gradebookCredentials[0] + "&password=" + gradebookCredentials[1];
Object[] link = Request.sendPost("https://gradebook.pisd.edu/Pinnacle/Gradebook/link.aspx?target=InternetViewer",
postParams,
cookies);
response = (String) link[0];
responseCode = (Integer) link[1];
cookies = (ArrayList<String>) link[2];
// for teh cookiez
Object[] defaultAspx = Request.sendPost("https://gradebook.pisd.edu/Pinnacle/Gradebook/Default.aspx",
postParams,
cookies);
response = (String) link[0];
responseCode = (Integer) link[1];
cookies = (ArrayList<String>) link[2];
pageUniqueId = Parser.pageUniqueId(response);
// throws PISDException
studentId = Parser.studentIdPinnacle(cookies);
if (pageUniqueId == null) {
System.out.println("Some error. pageUniqueId is null");
return false;
}
postParams = "{\"studentId\":\"" + studentId + "\"}";
/*
* get the JSON with list of classes, terms, and reports
*/
ArrayList<String[]> requestProperties = new ArrayList<String[]>();
//required for json files
requestProperties.add(new String[] {"Content-Type", "application/json"});
Object[] init = Request.sendPost(
"https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/InternetViewerService.ashx/Init?PageUniqueId=" + pageUniqueId,
cookies,
requestProperties,
true,
postParams);
response = (String) init[0];
responseCode = (Integer) init[1];
cookies = (ArrayList<String>) init[2];
//Store the JSON.
try {
setClassList(response);
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
public void setClassList(String json) throws JSONException {
JSONObject j = new JSONObject(json);
classList = j.getJSONArray("classes");
}
//Stuff to be implemented
// public String getLastUpdated() {
public int[] getClassIds() {
if (classIds != null)
return classIds;
if (classList == null) {
System.out.println("You didn't login!");
return classIds;
}
try {
classIds = new int[classList.length()];
for (int i = 0; i < classList.length(); i++) {
classIds[i] = classList.getJSONObject(i).getInt("classId");
}
} catch (JSONException e) {
e.printStackTrace();
}
return classIds;
}
public int[] getTermIds( int classId ) throws JSONException {
for (int i = 0; i < classList.length(); i++) {
if (classList.getJSONObject(i).getInt("classId") == classId) {
JSONArray terms = classList.getJSONObject(i).getJSONArray("terms");
int[] termIds = new int[terms.length()];
for (int j = 0; j < terms.length(); j++) {
termIds[j] = terms.getJSONObject(j).getInt("termId");
}
return termIds;
}
}
//if class not found.
return null;
}
public int getTermCount (int index) throws JSONException {
return classList.getJSONObject(index).getJSONArray("terms").length();
}
// public int[] getDetailedReport( int classId, int termId ) {
public String getDetailedReport (int classId, int termId, int studentId) throws MalformedURLException, IllegalUrlException, IOException {
String url = "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/StudentAssignments.aspx?" +
"&EnrollmentId=" + classId +
"&TermId=" + termId +
"&ReportType=0&StudentId=" + studentId;
Object[] report = Request.sendGet(url, cookies);
String response = (String) report[0];
int responseCode = (Integer) report[1];
cookies = (ArrayList<String>) report[2];
if (responseCode != 200) {
System.out.println("Response code: " + responseCode);
}
return response;
}
/**
* Uses internet every time.
* @throws ExecutionException
* @throws InterruptedException
*
*/
public int[][] loadGradeSummary () throws JSONException {
try {
String classId = classList.getJSONObject(0).getString("enrollmentId");
String termId = classList.getJSONObject(0).getJSONArray("terms").getJSONObject(0).getString("termId");
String url = "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/GradeSummary.aspx?" +
"&EnrollmentId=" + classId +
"&TermId=" + termId +
"&ReportType=0&StudentId=" + studentId;
Object[] summary = Request.sendGet(url, cookies);
String response = (String) summary[0];
int responseCode = (Integer) summary[1];
cookies = (ArrayList<String>) summary[2];
if (responseCode != 200) {
System.out.println("Response code: " + responseCode);
}
/*
* puts averages in classList, under each term.
*/
Element doc = Jsoup.parse(response);
gradeSummary = Parser.gradeSummary(doc, classList);
studentName = Parser.studentName(doc);
return gradeSummary;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (IllegalUrlException e) {
e.printStackTrace();
return null;
}
}
public int[][] getGradeSummary () {
if (gradeSummary == null)
try {
loadGradeSummary();
} catch (JSONException e) {
return null;
}
return gradeSummary;
}
public void putClassGrade (int classIndex, int termIndex, JSONObject classGrade) {
classGrades.put(new Integer[] {classIndex, termIndex}, classGrade);
}
// public JSONObject getClassGrade (int termIndex, int classIndex) {
// return classGrades.get(new Integer[] {termIndex, classIndex});
public boolean hasClassGrade (int classIndex, int termIndex) {
return classGrades.containsKey(new Integer[] {classIndex, termIndex});
}
public JSONObject getClassGrade( int classIndex, int termIndex ) {
String html = "";
try {
if (classGrades.get(classIndex) != null)
return classGrades.get(classIndex);
int classId = getClassIds()[classIndex];
int termId = getTermIds(classId)[termIndex];
html = getDetailedReport(classId, termId, studentId);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalUrlException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//Parse the teacher name if not already there.
try {
classList.getJSONObject(classIndex).getString("teacher");
} catch (JSONException e) {
// Teacher was not found.
String[] teacher = Parser.teacher(html);
try {
classList.getJSONObject(classIndex).put("teacher", teacher[0]);
classList.getJSONObject(classIndex).put("teacherEmail", teacher[1]);
} catch (JSONException f) {
e.printStackTrace();
}
}
JSONObject classGrade;
try {
classGrade = classList.getJSONObject( classIndex );
JSONArray termGrades = Parser.detailedReport(html);
Object[] termCategory = Parser.termCategoryGrades(html);
JSONArray termCategoryGrades = (JSONArray) termCategory[0];
if ((Integer)termCategory[1] != -1)
classGrade.getJSONArray("terms").getJSONObject(termIndex).put("average", termCategory[1]);
classGrade.getJSONArray("terms").getJSONObject(termIndex).put("grades", termGrades);
classGrade.getJSONArray("terms").getJSONObject(termIndex).put("categoryGrades", termCategoryGrades);
classGrades.put(new Integer[] {classIndex, termIndex}, classGrade);
return classGrade;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// if (classList == null)
// return null;
// if (classIds == null)
// getClassIds();
//// if (classGrades == null)
//// classGrades = classList;
// for (int i = 0; i < classIds.length; i++) {
// for (int j = 0; j < getTermIds(classIds[i]).length; j++) {
// getClassGrade (i , j);
// return classGrades;
/*
public JSONArray getAllClassGrades () throws JSONException {
// if (classList==null)
// try {
// login();
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
classGrades = classList;
//makes sure that classIds is not null.
getClassIds();
// fetch each class
for (int i = 0; i < classIds.length; i++) {
int classId = classIds[i];
int[] termIds = getTermIds(classId);
JSONArray grades = new JSONArray();
// fetch each term
for (int j = 0; j < termIds.length; j++) {
int termId = termIds[j];
String html = getDetailedReport(classId, termId, studentId);
//Parse the teacher name. Only do this once per class.
if (j==0) {
String[] teacher = Parser.teacher(html);
// System.out.println(Arrays.toString(teacher));
// put the teacher and teacherEmail into the class object.
classGrades.getJSONObject(i).put("teacher", teacher[0]);
classGrades.getJSONObject(i).put("teacherEmail", teacher[1]);
}
JSONArray termGrades = Parser.detailedReport(html);
Object[] termCategory = Parser.termCategoryGrades(html);
JSONArray termCategoryGrades = (JSONArray) termCategory[0];
if ((Double)termCategory[1] != -1)
classGrades.getJSONObject(i).getJSONArray("terms").getJSONObject(j).put("average", termCategory[1]);
classGrades.getJSONObject(i).getJSONArray("terms").getJSONObject(j).put("grades", termGrades);
classGrades.getJSONObject(i).getJSONArray("terms").getJSONObject(j).put("categoryGrades", termCategoryGrades);
}
}
Date d = Calendar.getInstance().getTime();
// Gives a last updated time for each CLASS, not each TERM.
lastUpdated = new Date[classIds.length][];
for (int i = 0; i < lastUpdated.length; i++) {
lastUpdated[i] = new Date[getTermCount(i)];
for (int j = 0; j < lastUpdated[i].length; j++) {
lastUpdated[i][j] = d;
}
}
// Possibly do it this way? The only problem is inconsistent term count.
// java.util.Arrays.fill(lastUpdated, d);
return classGrades;
}
*/
/**
* Temporary code. In use because login1.mypisd.net has an expired certificate. with new portal website, should not be necessary.
*/
/*
public static void acceptAllCertificates() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}
*/
public int getEditureLogin() {
return editureLogin;
}
public int getGradebookLogin() {
return gradebookLogin;
}
public String[] getGradebookCredentials() {
return gradebookCredentials;
}
public String[] getPassthroughCredentials() {
return passthroughCredentials;
}
public String getClassName (int classIndex) {
if (classList == null)
return "null";
else
try {
return classList.getJSONObject(classIndex).getString("title");
} catch (JSONException e) {
e.printStackTrace();
return "jsonException";
}
}
public String getStudentName() {
return studentName;
}
private void loadStudentPicture() {
ArrayList<String[]> requestProperties = new ArrayList<String[]>();
requestProperties.add(new String[] {"Content-Type", "image/jpeg"} );
Object[] response = Request.getBitmap("https://gradebook.pisd.edu/Pinnacle/Gradebook/common/picture.ashx?studentId=" + studentId,
cookies,
requestProperties,
true);
studentPictureBitmap = (Bitmap) response[0];
int responseCode = (Integer) response[1];
cookies = (ArrayList<String>) cookies;
}
public Bitmap getStudentPicture() {
if (studentPictureBitmap == null)
loadStudentPicture();
return studentPictureBitmap;
}
public void setClassMatch (int[] classMatch) {
this.classMatch = classMatch;
}
public int[] getClassMatch () {
return classMatch;
}
} |
package cc.mallet.topics;
import cc.mallet.examples.*;
import cc.mallet.util.*;
import cc.mallet.types.*;
import cc.mallet.pipe.*;
//import cc.mallet.pipe.iterator.*;
//import cc.mallet.topics.*;
//import cc.mallet.util.Maths;
//import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
//import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.util.*;
//import java.util.regex.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
public class iMixTopicModelExample {
public enum ExperimentType {
Authors,
Grants,
DBLP,
PM_pdb,
DBLP_ACM,
ACM,
FullGrants
}
public iMixTopicModelExample() throws IOException {
Logger logger = MalletLogger.getLogger(iMixTopicModelExample.class.getName());
int topWords = 10;
int topLabels = 10;
byte numModalities = 4;
//int numIndependentTopics = 0;
double docTopicsThreshold = 0.03;
int docTopicsMax = -1;
//boolean ignoreLabels = true;
boolean calcSimilarities = true;
boolean runTopicModelling = true;
//iMixParallelTopicModel.SkewType skewOn = iMixParallelTopicModel.SkewType.None;
//boolean ignoreSkewness = true;
int numTopics = 100;
int maxNumTopics = 151;
int numIterations = 800;
int independentIterations = 50;
int burnIn = 100;
int optimizeInterval = 40;
ExperimentType experimentType = ExperimentType.FullGrants;
int pruneCnt = 20; //Reduce features to those that occur more than N times
int pruneLblCnt = 5;
double pruneMaxPerc = 0.5;//Remove features that occur in more than (X*100)% of documents. 0.05 is equivalent to IDF of 3.0.
int similarityType = 0; //Cosine 1 jensenShannonDivergence 2 symmetric KLP
//boolean runParametric = true;
boolean DBLP_PPR = false;
String experimentId = numTopics + "T_" + numIterations + "IT_" + independentIterations + "IIT_" + burnIn + "B_" + numModalities + "M_" + "_" + experimentType.toString(); // + "_" + skewOn.toString();
String experimentDescription = "";
String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
if (experimentType == ExperimentType.Grants) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/fundedarxiv.db";
} else if (experimentType == ExperimentType.DBLP) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/DBLPManage/citation-network2.db";
} else if (experimentType == ExperimentType.PM_pdb) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/europepmc.db";
} else if (experimentType == ExperimentType.DBLP_ACM) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/DBLPManage/acm_output.db";
} else if (experimentType == ExperimentType.ACM) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/acmdata1.db";
} else if (experimentType == ExperimentType.FullGrants) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/openairedb.db";
}
Connection connection = null;
//createRefACMTables(SQLLitedb);
// create a database connection
//Reader fileReader = new InputStreamReader(new FileInputStream(new File(args[0])), "UTF-8");
//instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),
//3, 2, 1)); // data, label, name fields
String inputDir = "C:\\UoA\\OpenAire\\Datasets\\NIPS\\AuthorsNIPS12raw";
ArrayList<ArrayList<Instance>> instanceBuffer = new ArrayList<ArrayList<Instance>>(numModalities);
if (runTopicModelling) {
//createCitationGraphFile("C:\\projects\\Datasets\\DBLPManage\\acm_output_NET.csv", "jdbc:sqlite:C:/projects/Datasets/DBLPManage/acm_output.db");
for (byte m = 0; m < numModalities; m++) {
instanceBuffer.add(new ArrayList<Instance>());
}
try {
connection = DriverManager.getConnection(SQLLitedb);
//String sql = "select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,\"\t\") as GrantIds from Doc inner join GrantPerDoc on Doc.DocId=GrantPerDoc.DocId where Doc.source='pubmed' and grantPerDoc.grantId like 'ec%' Group By Doc.DocId, Doc.text";
//String docSource = "pubmed";
String docSource = "arxiv";
String grantType = "FP7";
String sql = "";
if (experimentType == ExperimentType.Grants) {
experimentDescription = "Topic modeling based on:\n1)Full text publications related to " + grantType + "\n2)Research Areas\n3)Venues (e.g., PubMed, Arxiv, ACM)\n4)Grants per Publication Links ";
sql = "select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds,GROUP_CONCAT(Grant.Category2,'\t') as Areas, Doc.Source \n"
+ " from Doc inner join \n"
+ " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId\n"
+ " INNER JOIN Grant on Grant.GrantId= GrantPerDoc.GrantId\n"
+ " where \n"
+ " Grant.Category0='" + grantType + "'\n"
+ " Group By Doc.DocId, Doc.text"
+ " LIMIT 10000";
// " select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds "
// + " from Doc inner join "
// + " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId "
// // + " where "
// // + " Doc.source='" + docSource + "' and "
// // + " grantPerDoc.grantId like '" + grantType + "' "
// + " Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.FullGrants) {
experimentDescription = "Topic modeling based on:\n1)Full text publications related to " + grantType + "\n2)Research Areas\n3)Venues (e.g., PubMed, Arxiv, ACM)\n4)Grants per Publication Links ";
sql = "select pubs.originalid AS DocId, \n" +
"GROUP_CONCAT(CASE WHEN IFNULL(pubs.fulltext,'')='' THEN pubs.abstract ELSE pubs.fulltext END,' ') AS TEXT,\n" +
"GROUP_CONCAT(links.project_code,'\t') as GrantIds,GROUP_CONCAT(FP7projectarea.CD_ABBR,'\t') as Areas, pubs.repository AS Venue\n" +
"from pubs \n" +
"inner join links on links.OriginalId = pubs.originalid and links.funder='FP7'\n" +
"inner join FP7Project on links.project_code=FP7Project.CD_PROJECT_NUMBER and links.funder='FP7'\n" +
"inner join FP7projectarea on FP7projectarea.CD_DIVNAME = FP7Project.CD_WORK_PROGRAMME\n" +
"Group By pubs.originalid\n" +
"\n" +
"UNION \n" +
"\n" +
"select 'FP7_'||Fp7project.CD_PROJECT_NUMBER AS DocId, Fp7project.LB_ABSTRACT AS TEXT, Fp7project.CD_PROJECT_NUMBER AS GrantIds , FP7projectarea.CD_ABBR AS Areas, '' AS Venue\n" +
"from Fp7project\n" +
"inner join FP7projectarea on FP7projectarea.CD_DIVNAME = FP7Project.CD_WORK_PROGRAMME\n" +
"where IFNULL(LB_ABSTRACT,'')<>'' and (Fp7project.CD_PROJECT_NUMBER in (SELECT links.project_code from Links where links.funder='FP7'))";
// + " LIMIT 10000";
// " select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds "
// + " from Doc inner join "
// + " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId "
// // + " where "
// // + " Doc.source='" + docSource + "' and "
// // + " grantPerDoc.grantId like '" + grantType + "' "
// + " Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.Authors) {
experimentDescription = "Topic modeling based on:\n 1)Full text NIPS publications\n2)Authors per publication links ";
sql = " select Doc.DocId,Doc.text, GROUP_CONCAT(AuthorPerDoc.authorID,'\t') as AuthorIds \n"
+ "from Doc \n"
+ "inner join AuthorPerDoc on Doc.DocId=AuthorPerDoc.DocId \n"
+ "Where \n"
+ "Doc.source='NIPS' \n"
+ "Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.DBLP) {
sql = " \n"
+ " select id, title||' '||abstract AS text, Authors, \n"
+ " GROUP_CONCAT(citation.Target,',') as citations\n"
+ " --GROUP_CONCAT(prLinks.Target,',') as citations, GROUP_CONCAT(prLinks.Counts,',') as citationsCnt \n"
+ " from papers\n"
+ "--inner join prLinks on prLinks.Source= papers.id \n"
+ "--AND prLinks.Counts>50\n"
+ "left outer join citation on citation.Source= papers.id \n"
+ " WHERE \n"
+ " (abstract IS NOT NULL) AND (abstract<>'') \n"
+ " Group By papers.id, papers.title, papers.abstract, papers.Authors";
// " select id, title||' '||abstract AS text, Authors, GROUP_CONCAT(prLinks.Target,',') as citations, GROUP_CONCAT(prLinks.Counts,',') as citationsCnt from papers\n"
// + "inner join prLinks on prLinks.Source= papers.id AND prLinks.Counts>50 \n"
// + " WHERE (abstract IS NOT NULL) AND (abstract<>'') \n"
// + " Group By papers.id, papers.title, papers.abstract, papers.Authors\n"
// + " LIMIT 200000"
} else if (experimentType == ExperimentType.PM_pdb) {
sql = " select pubdoc.pmcId, pubdoc.abstract, pubdoc.body, GROUP_CONCAT(pdblink.pdbCode,'\t') as pbdCodes \n"
+ " from pubdoc inner join \n"
+ " pdblink on pdblink.pmcId=pubdoc.pmcId \n"
+ " Group By pubdoc.pmcId, pubdoc.abstract, pubdoc.body";
} else if (experimentType == ExperimentType.DBLP_ACM) {
sql = " select id, title||' '||abstract AS text, Authors, \n"
+ " ref_id as citations\n"
+ " from papers\n"
+ " WHERE \n"
+ " (abstract IS NOT NULL) AND (abstract<>'') \n " //+" AND ref_Id IS NOT NULL AND ref_id<>'' \n"
// + " LIMIT 20000"
;
} else if (experimentType == ExperimentType.ACM) {
sql = " select articleid as id, title||' '||abstract AS text, authors_id AS Authors, \n"
+ " ref_objid as citations, primarycategory||'\t'||othercategory AS categories \n"
+ " from ACMData1 \n";
//+ " LIMIT 1000";
}
// String sql = "select fundedarxiv.file from fundedarxiv inner join funds on file=filename Group By fundedarxiv.file LIMIT 10" ;
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// read the result set
//String lblStr = "[" + rs.getString("GrantIds") + "]" ;//+ rs.getString("text");
//String str = "[" + rs.getString("GrantIds") + "]" + rs.getString("text");
//System.out.println("name = " + rs.getString("file"));
//System.out.println("name = " + rs.getString("fundings"));
//int cnt = rs.getInt("grantsCnt");
switch (experimentType) {
case Grants:
instanceBuffer.get(0).add(new Instance(rs.getString("text"), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "area"));
}
;
if (numModalities > 3) {
instanceBuffer.get(3).add(new Instance(rs.getString("Source"), null, rs.getString("DocId"), "source"));
}
;
break;
case FullGrants:
instanceBuffer.get(0).add(new Instance(rs.getString("text"), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "area"));
}
;
if (numModalities > 3) {
if (!rs.getString("Venue").equals("")) {
instanceBuffer.get(3).add(new Instance(rs.getString("Venue"), null, rs.getString("DocId"), "Venue"));
}
}
;
break;
case Authors:
instanceBuffer.get(0).add(new Instance(rs.getString("text"), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("AuthorIds"), null, rs.getString("DocId"), "author"));
}
break;
case DBLP:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
if (DBLP_PPR) {
String tmpStr = rs.getString("Citations");
String[] citationsCnt = null;
String[] citations = null;
if (tmpStr != null) {
citations = tmpStr.split(",");
citationsCnt = rs.getString("CitationsCnt").split(",");
String citationStr = "";
int index = 0;
while (index < citationsCnt.length) {
int cnt = Integer.parseInt(citationsCnt[index]);
for (int i = 1; i <= cnt / 50; i++) {
if (citationStr != "") {
citationStr += ",";
}
citationStr += citations[index];
}
index++;
}
instanceBuffer.get(1).add(new Instance(citationStr, null, rs.getString("Id"), "citations"));
}
} else {
String tmpStr = rs.getString("Citations");
if (tmpStr != null) {
instanceBuffer.get(1).add(new Instance(tmpStr, null, rs.getString("Id"), "author"));
}
}
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Authors"), null, rs.getString("Id"), "author"));
}
break;
case PM_pdb:
//instanceBuffer.get(0).add(new Instance(rs.getString("abstract") + " " + rs.getString("body"), null, rs.getString("pmcId"), "text"));
instanceBuffer.get(0).add(new Instance(rs.getString("abstract"), null, rs.getString("pmcId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("pbdCodes"), null, rs.getString("pmcId"), "pbdCode"));
}
break;
case DBLP_ACM:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("Authors"), null, rs.getString("Id"), "citation"));
}
if (numModalities > 2) {
String tmpStr = rs.getString("Citations").replace("\t", ",");
instanceBuffer.get(2).add(new Instance(tmpStr, null, rs.getString("Id"), "author"));
}
break;
case ACM:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
String tmpStr = rs.getString("Citations");//.replace("\t", ",");
instanceBuffer.get(1).add(new Instance(tmpStr, null, rs.getString("Id"), "citation"));
}
if (numModalities > 3) {
String tmpAuthorsStr = rs.getString("Authors");//.replace("\t", ",");
instanceBuffer.get(3).add(new Instance(tmpAuthorsStr, null, rs.getString("Id"), "author"));
}
if (numModalities > 2) {
String tmpStr = rs.getString("Categories");//.replace("\t", ",");
instanceBuffer.get(2).add(new Instance(tmpStr, null, rs.getString("Id"), "category"));
}
break;
default:
}
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
logger.info("Read " + instanceBuffer.get(0).size() + " instances modality: " + instanceBuffer.get(0).get(0).getSource().toString());
//numModalities = 2;
// Begin by importing documents from text to feature sequences
ArrayList<Pipe> pipeListText = new ArrayList<Pipe>();
// Pipes: lowercase, tokenize, remove stopwords, map to features
pipeListText.add(new Input2CharSequence(false)); //homer
pipeListText.add(new CharSequenceLowercase());
SimpleTokenizer tokenizer = new SimpleTokenizer(new File("stoplists/en.txt"));
GenerateStoplist(tokenizer, instanceBuffer.get(0), pruneCnt, pruneMaxPerc, false);
tokenizer.stop("cid");
tokenizer.stop("null");
//tokenizer.
pipeListText.add(tokenizer);
Alphabet alphabet = new Alphabet();
pipeListText.add(new StringList2FeatureSequence(alphabet));
/*
Alphabet alphabet = new Alphabet();
CharSequenceLowercase csl = new CharSequenceLowercase();
StringList2FeatureSequence sl2fs = new StringList2FeatureSequence(alphabet);
if (!preserveCase.value) {
pipes.add(csl);
}
pipes.add(prunedTokenizer);
pipes.add(sl2fs);
Pipe serialPipe = new SerialPipes(pipes);
InstanceList instances = new InstanceList(serialPipe);
instances.addThruPipe(reader);
*/
/* orig
pipeListText.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));// Original --> replaced by simpletokenizer in order to use prunedStopiList
pipeListText.add(new TokenSequenceRemoveStopwords(new File("stoplists/en.txt"), "UTF-8", false, false, false)); //Original --> replaced by simpletokenizer
pipeListText.add(new TokenSequence2FeatureSequence());
*/
// Other Modalities
ArrayList<Pipe> pipeListCSV = new ArrayList<Pipe>();
if (experimentType == ExperimentType.DBLP || experimentType == ExperimentType.DBLP_ACM) {
pipeListCSV.add(new CSV2FeatureSequence(","));
} else {
pipeListCSV.add(new CSV2FeatureSequence());
}
InstanceList[] instances = new InstanceList[numModalities];
instances[0] = new InstanceList(new SerialPipes(pipeListText));
instances[0].addThruPipe(instanceBuffer.get(0).iterator());
for (byte m = 1; m < numModalities; m++) {
logger.info("Read " + instanceBuffer.get(m).size() + " instances modality: " + (instanceBuffer.get(m).size() > 0 ? instanceBuffer.get(m).get(0).getSource().toString() : m));
instances[m] = new InstanceList(new SerialPipes(pipeListCSV));
instances[m].addThruPipe(instanceBuffer.get(m).iterator());
}
logger.info(" instances added through pipe");
// pruning for all other modalities no text
for (byte m = 1; m < numModalities; m++) {
if ((m == 0 && pruneCnt > 0) || (m > 0 && pruneLblCnt > 0)) {
// Check which type of data element the instances contain
Instance firstInstance = instances[m].get(0);
if (firstInstance.getData() instanceof FeatureSequence) {
// Version for feature sequences
Alphabet oldAlphabet = instances[m].getDataAlphabet();
Alphabet newAlphabet = new Alphabet();
// It's necessary to create a new instance list in
// order to make sure that the data alphabet is correct.
Noop newPipe = new Noop(newAlphabet, instances[m].getTargetAlphabet());
InstanceList newInstanceList = new InstanceList(newPipe);
// Iterate over the instances in the old list, adding
// up occurrences of features.
int numFeatures = oldAlphabet.size();
double[] counts = new double[numFeatures];
for (int ii = 0; ii < instances[m].size(); ii++) {
Instance instance = instances[m].get(ii);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.addFeatureWeightsTo(counts);
}
Instance instance;
// Next, iterate over the same list again, adding
// each instance to the new list after pruning.
while (instances[m].size() > 0) {
instance = instances[m].get(0);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.prune(counts, newAlphabet, m == 0 ? pruneCnt : pruneLblCnt);
newInstanceList.add(newPipe.instanceFrom(new Instance(fs, instance.getTarget(),
instance.getName(),
instance.getSource())));
instances[m].remove(0);
}
// logger.info("features: " + oldAlphabet.size()
// + " -> " + newAlphabet.size());
// Make the new list the official list.
instances[m] = newInstanceList;
} else {
throw new UnsupportedOperationException("Pruning features from "
+ firstInstance.getClass().getName()
+ " is not currently supported");
}
}
}
logger.info(" instances pruned");
boolean splitCorpus = false;
InstanceList[] testInstances = null;
InstanceList[] trainingInstances = instances;
if (splitCorpus) {
//instances.addThruPipe(new FileIterator(inputDir));
//instances.addThruPipe (new FileIterator ("C:\\UoA\\OpenAire\\Datasets\\YIpapersTXT\\YIpapersTXT"));
//instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),
// Create a model with 100 topics, alpha_t = 0.01, beta_w = 0.01
// Note that the first parameter is passed as the sum over topics, while
// the second is
testInstances = new InstanceList[numModalities];
trainingInstances = new InstanceList[numModalities];
TObjectIntMap<String> entityPosition = new TObjectIntHashMap<String>();
int index = 0;
for (byte m = 0; m < numModalities; m++) {
Noop newPipe = new Noop(instances[m].getDataAlphabet(), instances[m].getTargetAlphabet());
InstanceList newInstanceList = new InstanceList(newPipe);
testInstances[m] = newInstanceList;
InstanceList newInstanceList2 = new InstanceList(newPipe);
trainingInstances[m] = newInstanceList2;
for (int i = 0; i < instances[m].size(); i++) {
Instance instance = instances[m].get(i);
String entityId = (String) instance.getName();
if (i < instances[m].size() * 0.8 && m == 0) {
entityPosition.put(entityId, index);
trainingInstances[m].add(instance);
index++;
} else if (m != 0 && entityPosition.containsKey(entityId)) {
trainingInstances[m].add(instance);
} else {
testInstances[m].add(instance);
}
}
}
}
String outputDir = "C:\\projects\\OpenAIRE\\OUT\\" + experimentId;
File outPath = new File(outputDir);
outPath.mkdir();
String stateFile = outputDir + File.separator + "output_state";
String outputDocTopicsFile = outputDir + File.separator + "output_doc_topics.csv";
String outputTopicPhraseXMLReport = outputDir + File.separator + "topicPhraseXMLReport.xml";
String topicKeysFile = outputDir + File.separator + "output_topic_keys.csv";
String topicWordWeightsFile = outputDir + File.separator + "topicWordWeightsFile.csv";
String stateFileZip = outputDir + File.separator + "output_state.gz";
String modelEvaluationFile = outputDir + File.separator + "model_evaluation.txt";
String modelDiagnosticsFile = outputDir + File.separator + "model_diagnostics.xml";
boolean runNPModel = false;
if (runNPModel) {
NPTopicModel npModel = new NPTopicModel(5.0, 10.0, 0.1);
npModel.addInstances(instances[0], 50);
npModel.setTopicDisplay(20, 10);
npModel.sample(100);
FileWriter fwrite = new FileWriter(outputDir + File.separator + "output_NP_topics.csv");
BufferedWriter NP_Topics_out = new BufferedWriter(fwrite);
NP_Topics_out.write(npModel.topWords(10) + "\n");
NP_Topics_out.flush();
npModel.printState(new File(outputDir + File.separator + "NP_output_state.gz"));
}
boolean runHDPModel = false;
if (runHDPModel) {
//setup HDP parameters(alpha, beta, gamma, initialTopics)
HDP hdp = new HDP(1.0, 0.1, 4.0, numTopics);
hdp.initialize(instances[0]);
//set number of iterations, and display result or not
hdp.estimate(numIterations);
//get topic distribution for first instance
double[] distr = hdp.topicDistribution(0);
//print out
for (int j = 0; j < distr.length; j++) {
System.out.print(distr[j] + " ");
}
//for inferencer
HDPInferencer inferencer = hdp.getInferencer();
inferencer.setInstance(testInstances[0]);
inferencer.estimate(100);
//get topic distribution for first test instance
distr = inferencer.topicDistribution(0);
//print out
for (int j = 0; j < distr.length; j++) {
System.out.print(distr[j] + " ");
}
//get preplexity
double prep = inferencer.getPreplexity();
System.out.println("preplexity for the test set=" + prep);
//10-folds cross validation, with 1000 iteration for each test.
hdp.runCrossValidation(10, 1000);
}
boolean runOrigParallelModel = false;
if (runOrigParallelModel) {
ParallelTopicModel modelOrig = new ParallelTopicModel(numTopics, 1.0, 0.01);
modelOrig.addInstances(instances[0]);
// Use two parallel samplers, which each look at one half the corpus and combine
// statistics after every iteration.
modelOrig.setNumThreads(4);
// Run the model for 50 iterations and stop (this is for testing only,
// for real applications, use 1000 to 2000 iterations)
modelOrig.setNumIterations(numIterations);
modelOrig.optimizeInterval = optimizeInterval;
modelOrig.burninPeriod = burnIn;
//model.optimizeInterval = 0;
//model.burninPeriod = 0;
//model.saveModelInterval=250;
modelOrig.estimate();
}
double[] beta = new double[numModalities];
Arrays.fill(beta, 0.01);
double[] alphaSum = new double[numModalities];
Arrays.fill(alphaSum, 1);
double[] gamma = new double[numModalities];
Arrays.fill(gamma, 1);
double gammaRoot = 4;
//Non parametric model
//iMixParallelTopicModel model = new iMixParallelTopicModel(numTopics, numIndependentTopics, numModalities, alphaSum, beta, ignoreLabels, skewOn);
//parametric model
//iMixParallelTopicModelFixTopics model = new iMixParallelTopicModelFixTopics(numTopics, numModalities, alphaSum, beta);
// iMixLDAParallelTopicModel model = new iMixLDAParallelTopicModel(maxNumTopics, numTopics, numModalities, gamma, gammaRoot, beta,numIterations);
MixLDAParallelTopicModel model = new MixLDAParallelTopicModel(numTopics, numModalities, alphaSum, beta, numIterations);
// ParallelTopicModel model = new ParallelTopicModel(numTopics, 1.0, 0.01);
//model.setNumIterations(numIterations);
model.setIndependentIterations(independentIterations);
model.optimizeInterval = optimizeInterval;
model.burninPeriod = burnIn;
model.addInstances(instances);//trainingInstances);//instances);
logger.info(" instances added");
// Use two parallel samplers, which each look at one half the corpus and combine
// statistics after every iteration.
model.setNumThreads(4);
// Run the model for 50 iterations and stop (this is for testing only,
// for real applications, use 1000 to 2000 iterations)
//model.optimizeInterval = 0;
//model.burninPeriod = 0;
//model.saveModelInterval=250;
model.estimate();
logger.info("Model Metadata: \n" + model.getExpMetadata());
model.saveExperiment(SQLLitedb, experimentId, experimentDescription);
logger.info("Model estimated");
model.saveTopics(SQLLitedb, experimentId);
logger.info("Topics Saved");
model.printTopWords(
new File(topicKeysFile), topWords, topLabels, false);
logger.info("Top words printed");
//model.printTopWords(new File(topicKeysFile), topWords, false);
//model.printTopicWordWeights(new File(topicWordWeightsFile));
//model.printTopicLabelWeights(new File(topicLabelWeightsFile));
model.printState(
new File(stateFileZip));
logger.info("printState finished");
PrintWriter outState = new PrintWriter(new FileWriter((new File(outputDocTopicsFile))));
model.printDocumentTopics(outState, docTopicsThreshold, docTopicsMax, SQLLitedb, experimentId,
0.1);
outState.close();
logger.info("printDocumentTopics finished");
PrintWriter outXMLPhrase = new PrintWriter(new FileWriter((new File(outputTopicPhraseXMLReport))));
model.topicPhraseXMLReport(outXMLPhrase, topWords);
outState.close();
logger.info("topicPhraseXML report finished");
// GunZipper g = new GunZipper(new File(stateFileZip));
// g.unzip(
// new File(stateFile));
// try {
// // outputCsvFiles(outputDir, true, inputDir, numTopics, stateFile, outputDocTopicsFile, topicKeysFile);
// logger.info("outputCsvFiles finished");
// } catch (Exception e) {
// // if the error message is "out of memory",
// // it probably means no database file is found
// System.err.println(e.getMessage());
if (modelEvaluationFile != null) {
try {
// ObjectOutputStream oos =
// new ObjectOutputStream(new FileOutputStream(modelEvaluationFile));
// oos.writeObject(model.getProbEstimator());
// oos.close();
PrintStream docProbabilityStream = null;
docProbabilityStream = new PrintStream(modelEvaluationFile);
//TODO...
double perplexity = 0;
if (splitCorpus) {
perplexity = model.getProbEstimator().evaluateLeftToRight(testInstances[0], 10, false, docProbabilityStream);
}
// System.out.println("perplexity for the test set=" + perplexity);
logger.info("perplexity calculation finished");
//iMixLDATopicModelDiagnostics diagnostics = new iMixLDATopicModelDiagnostics(model, topWords);
MixLDATopicModelDiagnostics diagnostics = new MixLDATopicModelDiagnostics(model, topWords);
diagnostics.saveToDB(SQLLitedb, experimentId, perplexity);
logger.info("full diagnostics calculation finished");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
if (calcSimilarities) {
//calc similarities
logger.info("similarities calculation Started");
try {
// create a database connection
//connection = DriverManager.getConnection(SQLLitedb);
connection = DriverManager.getConnection(SQLLitedb);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
// statement.executeUpdate("drop table if exists person");
// statement.executeUpdate("create table person (id integer, name string)");
// statement.executeUpdate("insert into person values(1, 'leo')");
// statement.executeUpdate("insert into person values(2, 'yui')");
// ResultSet rs = statement.executeQuery("select * from person");
String sql = "";
switch (experimentType) {
case Grants:
sql = "select GrantId, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join GrantPerDoc on topicsPerDoc.DocId= GrantPerDoc.DocId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By GrantId , TopicId order by GrantId , TopicId";
break;
case Authors:
sql = "select AuthorId, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join AuthorPerDoc on topicsPerDoc.DocId= AuthorPerDoc.DocId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By AuthorId , TopicId order by AuthorId , TopicId";
break;
case PM_pdb:
sql = "select pdbCode, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join pdblink on topicsPerDoc.DocId= pdblink.pmcId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By pdbCode , TopicId order by pdbCode , TopicId";
break;
case DBLP:
sql = "select Source, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join prlinks on topicsPerDoc.DocId= prlinks.source"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By Source , TopicId order by Source , TopicId";
break;
default:
}
// String sql = "select fundedarxiv.file from fundedarxiv inner join funds on file=filename Group By fundedarxiv.file LIMIT 10" ;
ResultSet rs = statement.executeQuery(sql);
HashMap<String, SparseVector> labelVectors = null;
HashMap<String, double[]> similarityVectors = null;
if (similarityType == 0) {
labelVectors = new HashMap<String, SparseVector>();
} else {
similarityVectors = new HashMap<String, double[]>();
}
String labelId = "";
int[] topics = new int[maxNumTopics];
double[] weights = new double[maxNumTopics];
int cnt = 0;
double a;
while (rs.next()) {
String newLabelId = "";
switch (experimentType) {
case Grants:
newLabelId = rs.getString("GrantId");
break;
case Authors:
newLabelId = rs.getString("AuthorId");
break;
case PM_pdb:
newLabelId = rs.getString("pdbCode");
break;
case DBLP:
newLabelId = rs.getString("Source");
break;
default:
}
if (!newLabelId.equals(labelId) && !labelId.isEmpty()) {
if (similarityType == 0) {
labelVectors.put(labelId, new SparseVector(topics, weights, topics.length, topics.length, true, true, true));
} else {
similarityVectors.put(labelId, weights);
}
topics = new int[maxNumTopics];
weights = new double[maxNumTopics];
cnt = 0;
}
labelId = newLabelId;
topics[cnt] = rs.getInt("TopicId");
weights[cnt] = rs.getDouble("Weight");
cnt++;
}
cnt = 0;
double similarity = 0;
double similarityThreshold = 0.1;
NormalizedDotProductMetric cosineSimilarity = new NormalizedDotProductMetric();
statement.executeUpdate("create table if not exists EntitySimilarity (EntityType int, EntityId1 nvarchar(50), EntityId2 nvarchar(50), Similarity double, ExperimentId nvarchar(50)) ");
String deleteSQL = String.format("Delete from EntitySimilarity where ExperimentId = '%s'", experimentId);
statement.executeUpdate(deleteSQL);
PreparedStatement bulkInsert = null;
sql = "insert into EntitySimilarity values(?,?,?,?,?);";
try {
connection.setAutoCommit(false);
bulkInsert = connection.prepareStatement(sql);
if (similarityType > 0) {
for (String fromGrantId : similarityVectors.keySet()) {
boolean startCalc = false;
for (String toGrantId : similarityVectors.keySet()) {
if (!fromGrantId.equals(toGrantId) && !startCalc) {
continue;
} else {
startCalc = true;
similarity = Maths.jensenShannonDivergence(similarityVectors.get(fromGrantId), similarityVectors.get(toGrantId)); // the function returns distance not similarity
if (similarity > similarityThreshold && !fromGrantId.equals(toGrantId)) {
bulkInsert.setInt(1, experimentType.ordinal());
bulkInsert.setString(2, fromGrantId);
bulkInsert.setString(3, toGrantId);
bulkInsert.setDouble(4, (double) Math.round(similarity * 1000) / 1000);
bulkInsert.setString(5, experimentId);
bulkInsert.executeUpdate();
}
}
}
}
} else {
for (String fromGrantId : labelVectors.keySet()) {
boolean startCalc = false;
for (String toGrantId : labelVectors.keySet()) {
if (!fromGrantId.equals(toGrantId) && !startCalc) {
continue;
} else {
startCalc = true;
similarity = 1 - Math.abs(cosineSimilarity.distance(labelVectors.get(fromGrantId), labelVectors.get(toGrantId))); // the function returns distance not similarity
if (similarity > similarityThreshold && !fromGrantId.equals(toGrantId)) {
bulkInsert.setInt(1, experimentType.ordinal());
bulkInsert.setString(2, fromGrantId);
bulkInsert.setString(3, toGrantId);
bulkInsert.setDouble(4, (double) Math.round(similarity * 1000) / 1000);
bulkInsert.setString(5, experimentId);
bulkInsert.executeUpdate();
}
}
}
}
}
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException excep) {
System.err.print("Error in insert grantSimilarity");
}
}
} finally {
if (bulkInsert != null) {
bulkInsert.close();
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
logger.info("similarities calculation finished");
}
// if (modelDiagnosticsFile
// != null) {
// PrintWriter out = new PrintWriter(modelDiagnosticsFile);
// MixTopicModelDiagnostics diagnostics = new MixTopicModelDiagnostics(model, topWords, perplexity);
// diagnostics.saveToDB(SQLLitedb, experimentId);
// out.println(diagnostics.toXML()); //preferable than XML???
// out.close();
//If any value in <tt>p2</tt> is <tt>0.0</tt> then the KL-divergence
//double a = Maths.klDivergence();
//model.printTypeTopicCounts(new File (wordTopicCountsFile.value));
// Show the words and topics in the first instance
// The data alphabet maps word IDs to strings
/* Alphabet dataAlphabet = instances.getDataAlphabet();
FeatureSequence tokens = (FeatureSequence) model.getData().get(0).instance.getData();
LabelSequence topics = model.getData().get(0).topicSequence;
Formatter out = new Formatter(new StringBuilder(), Locale.US);
for (int posit= 0; position < tokens.getLength(); position++) {
out.format("%s-%d ", dataAlphabet.lookupObject(tokens.getIndexAtPosition(position)), topics.getIndexAtPosition(position));
}
System.out.println(out);
// Estimate the topic distribution of the first instance,
// given the current Gibbs state.
double[] topicDistribution = model.getTopicProbabilities(0);
// Get an array of sorted sets of word ID/count pairs
ArrayList<TreeSet<IDSorter>> topicSortedWords = model.getSortedWords();
// Show top 5 words in topics with proportions for the first document
for (int topic = 0; topic < numTopics; topic++) {
Iterator<IDSorter> iterator = topicSortedWords.get(topic).iterator();
out = new Formatter(new StringBuilder(), Locale.US);
out.format("%d\t%.3f\t", topic, topicDistribution[topic]);
int rank = 0;
while (iterator.hasNext() && rank < 5) {
IDSorter idCountPair = iterator.next();
out.format("%s (%.0f) ", dataAlphabet.lookupObject(idCountPair.getID()), idCountPair.getWeight());
rank++;
}
System.out.println(out);
}
// Create a new instance with high probability of topic 0
StringBuilder topicZeroText = new StringBuilder();
Iterator<IDSorter> iterator = topicSortedWords.get(0).iterator();
int rank = 0;
while (iterator.hasNext() && rank < 5) {
IDSorter idCountPair = iterator.next();
topicZeroText.append(dataAlphabet.lookupObject(idCountPair.getID()) + " ");
rank++;
}
// Create a new instance named "test instance" with empty target and source fields.
InstanceList testing = new InstanceList(instances.getPipe());
testing.addThruPipe(new Instance(topicZeroText.toString(), null, "test instance", null));
TopicInferencer inferencer = model.getInferencer();
double[] testProbabilities = inferencer.getSampledDistribution(testing.get(0), 10, 1, 5);
System.out.println("0\t" + testProbabilities[0]);
*/
}
private void GenerateStoplist(SimpleTokenizer prunedTokenizer, ArrayList<Instance> instanceBuffer, int pruneCount, double docProportionCutoff, boolean preserveCase)
throws IOException {
ArrayList<Instance> input = new ArrayList<Instance>();
for (Instance instance : instanceBuffer) {
input.add((Instance) instance.clone());
}
ArrayList<Pipe> pipes = new ArrayList<Pipe>();
Alphabet alphabet = new Alphabet();
CharSequenceLowercase csl = new CharSequenceLowercase();
SimpleTokenizer st = prunedTokenizer.deepClone();
StringList2FeatureSequence sl2fs = new StringList2FeatureSequence(alphabet);
FeatureCountPipe featureCounter = new FeatureCountPipe(alphabet, null);
FeatureDocFreqPipe docCounter = new FeatureDocFreqPipe(alphabet, null);
pipes.add(new Input2CharSequence(false)); //homer
if (!preserveCase) {
pipes.add(csl);
}
pipes.add(st);
pipes.add(sl2fs);
if (pruneCount > 0) {
pipes.add(featureCounter);
}
if (docProportionCutoff < 1.0) {
pipes.add(docCounter);
}
Pipe serialPipe = new SerialPipes(pipes);
Iterator<Instance> iterator = serialPipe.newIteratorFrom(input.iterator());
int count = 0;
// We aren't really interested in the instance itself,
// just the total feature counts.
while (iterator.hasNext()) {
count++;
if (count % 100000 == 0) {
System.out.println(count);
}
iterator.next();
}
Iterator<String> wordIter = alphabet.iterator();
while (wordIter.hasNext()) {
String word = (String) wordIter.next();
if (word.contains("cidcid") || word.contains("nullnull") || word.contains("usepackage")) {
prunedTokenizer.stop(word);
}
}
if (pruneCount > 0) {
featureCounter.addPrunedWordsToStoplist(prunedTokenizer, pruneCount);
}
if (docProportionCutoff < 1.0) {
docCounter.addPrunedWordsToStoplist(prunedTokenizer, docProportionCutoff);
}
}
private void outputCsvFiles(String outputDir, Boolean htmlOutputFlag, String inputDir, int numTopics, String stateFile, String outputDocTopicsFile, String topicKeysFile) {
CsvBuilder cb = new CsvBuilder();
cb.createCsvFiles(numTopics, outputDir, stateFile, outputDocTopicsFile, topicKeysFile);
if (htmlOutputFlag) {
HtmlBuilder hb = new HtmlBuilder(cb.getNtd(), new File(inputDir));
hb.createHtmlFiles(new File(outputDir));
}
//clearExtrafiles(outputDir);
}
private void clearExtrafiles(String outputDir) {
String[] fileNames = {"topic-input.mallet", "output_topic_keys.csv", "output_state.gz",
"output_doc_topics.csv", "output_state"};
for (String f : fileNames) {
if (!(new File(outputDir, f).canWrite())) {
System.out.println(f);
}
Boolean b = new File(outputDir, f).delete();
}
}
public void createCitationGraphFile(String outputCsv, String SQLLitedb) {
//String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
Connection connection = null;
try {
FileWriter fwrite = new FileWriter(outputCsv);
BufferedWriter out = new BufferedWriter(fwrite);
String header = "# DBLP citation graph \n"
+ "# fromNodeId, toNodeId \n";
out.write(header);
connection = DriverManager.getConnection(SQLLitedb);
String sql = "select id, ref_id from papers where ref_num >0 ";
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// read the result set
int Id = rs.getInt("Id");
String citationNums = rs.getString("ref_id");
String csvLine = "";//Id + "\t" + citationNums;
String[] str = citationNums.split("\t");
for (int i = 0; i < str.length - 1; i++) {
csvLine = Id + "\t" + str[i];
out.write(csvLine + "\n");
}
}
out.flush();
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println("File input error");
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
}
public void createRefACMTables(String SQLLitedb) {
//String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(SQLLitedb);
Statement statement = connection.createStatement();
statement.executeUpdate("create table if not exists Author (AuthorId nvarchar(50), FirstName nvarchar(50), LastName nvarchar(50), MiddleName nvarchar(10), Affilication TEXT) ");
String deleteSQL = String.format("Delete from Author ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists Citation (CitationId nvarchar(50), Reference TEXT) ");
deleteSQL = String.format("Delete from Citation ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists Category (Category TEXT) ");
deleteSQL = String.format("Delete from Category ");
statement.executeUpdate(deleteSQL);
statement = connection.createStatement();
statement.executeUpdate("create table if not exists PubAuthor (PubId nvarchar(50), AuthorId nvarchar(50)) ");
deleteSQL = String.format("Delete from PubAuthor ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists PubCitation (PubId nvarchar(50), CitationId nvarchar(50)) ");
deleteSQL = String.format("Delete from PubCitation ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists PubCategory (PubId nvarchar(50), Category TEXT) ");
deleteSQL = String.format("Delete from PubCategory ");
statement.executeUpdate(deleteSQL);
PreparedStatement authorBulkInsert = null;
PreparedStatement citationBulkInsert = null;
PreparedStatement categoryBulkInsert = null;
PreparedStatement pubAuthorBulkInsert = null;
PreparedStatement pubCitationBulkInsert = null;
PreparedStatement pubCategoryBulkInsert = null;
String authorInsertsql = "insert into Author values(?,?,?,?,?);";
String citationInsertsql = "insert into Citation values(?,?);";
String categoryInsertsql = "insert into Category values(?);";
String pubAuthorInsertsql = "insert into pubAuthor values(?,?);";
String pubCitationInsertsql = "insert into pubCitation values(?,?);";
String pubCategoryInsertsql = "insert into pubCategory values(?,?);";
TObjectIntHashMap<String> authorsLst = new TObjectIntHashMap<String>();
TObjectIntHashMap<String> citationsLst = new TObjectIntHashMap<String>();
TObjectIntHashMap<String> categorysLst = new TObjectIntHashMap<String>();
try {
connection.setAutoCommit(false);
authorBulkInsert = connection.prepareStatement(authorInsertsql);
citationBulkInsert = connection.prepareStatement(citationInsertsql);
categoryBulkInsert = connection.prepareStatement(categoryInsertsql);
pubAuthorBulkInsert = connection.prepareStatement(pubAuthorInsertsql);
pubCitationBulkInsert = connection.prepareStatement(pubCitationInsertsql);
pubCategoryBulkInsert = connection.prepareStatement(pubCategoryInsertsql);
String sql = " Select articleid,authors_id,authors_firstname,authors_lastname,authors_middlename,authors_affiliation,authors_role, \n"
+ " ref_objid,reftext,primarycategory,othercategory \n"
+ " from ACMData1 \n";
// + " LIMIT 10";
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// read the result set
String Id = rs.getString("articleid");
String authorIdsStr = rs.getString("authors_id");
String[] authorIds = authorIdsStr.split("\t");
String authors_firstnamesStr = rs.getString("authors_firstname");
String[] authors_firstnames = authors_firstnamesStr.split("\t");
String authors_lastnamesStr = rs.getString("authors_lastname");
String[] authors_lastnames = authors_lastnamesStr.split("\t");
String authors_middlenamesStr = rs.getString("authors_middlename");
String[] authors_middlenames = authors_middlenamesStr.split("\t");
String authors_affiliationsStr = rs.getString("authors_affiliation");
String[] authors_affiliations = authors_affiliationsStr.split("\t");
for (int i = 0; i < authorIds.length - 1; i++) {
String authorId = authorIds[i];
if (!authorsLst.containsKey(authorId)) {
authorsLst.put(authorId, 1);
String lstName = authors_lastnames.length - 1 > i ? authors_lastnames[i] : "";
String fstName = authors_firstnames.length - 1 > i ? authors_firstnames[i] : "";
String mName = authors_middlenames.length - 1 > i ? authors_middlenames[i] : "";
String affiliation = authors_affiliations.length - 1 > i ? authors_affiliations[i] : "";
authorBulkInsert.setString(1, authorId);
authorBulkInsert.setString(2, lstName);
authorBulkInsert.setString(3, fstName);
authorBulkInsert.setString(4, mName);
authorBulkInsert.setString(5, affiliation);
authorBulkInsert.executeUpdate();
}
pubAuthorBulkInsert.setString(1, Id);
pubAuthorBulkInsert.setString(2, authorId);
pubAuthorBulkInsert.executeUpdate();
}
String citationIdsStr = rs.getString("ref_objid");
String[] citationIds = citationIdsStr.split("\t");
String citationsStr = rs.getString("reftext");
String[] citations = citationsStr.split("\t");
for (int i = 0; i < citationIds.length - 1; i++) {
String citationId = citationIds[i];
if (!citationsLst.containsKey(citationId)) {
citationsLst.put(citationId, 1);
String ref = citations.length - 1 > i ? citations[i] : "";
citationBulkInsert.setString(1, citationId);
citationBulkInsert.setString(2, ref);
citationBulkInsert.executeUpdate();
}
pubCitationBulkInsert.setString(1, Id);
pubCitationBulkInsert.setString(2, citationId);
pubCitationBulkInsert.executeUpdate();
}
String prCategoriesStr = rs.getString("primarycategory");
String[] prCategories = prCategoriesStr.split("\t");
String categoriesStr = rs.getString("othercategory");
String[] categories = categoriesStr.split("\t");
for (int i = 0; i < prCategories.length - 1; i++) {
String category = prCategories[i];
if (!categorysLst.containsKey(category)) {
categorysLst.put(category, 1);
categoryBulkInsert.setString(1, category);
categoryBulkInsert.executeUpdate();
}
pubCategoryBulkInsert.setString(1, Id);
pubCategoryBulkInsert.setString(2, category);
pubCategoryBulkInsert.executeUpdate();
}
for (int i = 0; i < categories.length - 1; i++) {
String category = categories[i];
if (!categorysLst.containsKey(category)) {
categorysLst.put(category, 1);
categoryBulkInsert.setString(1, category);
categoryBulkInsert.executeUpdate();
}
pubCategoryBulkInsert.setString(1, Id);
pubCategoryBulkInsert.setString(2, category);
pubCategoryBulkInsert.executeUpdate();
}
}
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException excep) {
System.err.print("Error in ACMReferences extraction");
}
}
} finally {
if (authorBulkInsert != null) {
authorBulkInsert.close();
}
if (categoryBulkInsert != null) {
categoryBulkInsert.close();
}
if (citationBulkInsert != null) {
citationBulkInsert.close();
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println("File input error");
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
}
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
iMixTopicModelExample trainer = new iMixTopicModelExample();
}
} |
package net.nanase.nanasetter.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
* @author Tomona Nanase
* @since Nanasetter 0.1
*/
public class Version implements Comparable<Version> {
private static final Pattern parsePattern;
public final int major;
public final int minor;
public final int build;
public final int revision;
public final String suffix;
static {
parsePattern = Pattern.compile("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?)?([^\\. ]\\S*)?$");
}
/**
*
*
* @param major
*/
public Version(int major) {
this(major, -1, -1, -1, null);
}
/**
*
*
* @param major
* @param minor
*/
public Version(int major, int minor) {
this(major, minor, -1, -1, null);
}
/**
*
*
* @param major
* @param minor
* @param build
*/
public Version(int major, int minor, int build) {
this(major, minor, build, -1, null);
}
/**
*
*
* @param major
* @param minor
* @param build
* @param revision
*/
public Version(int major, int minor, int build, int revision) {
this(major, minor, build, revision, null);
}
/**
*
*
* @param major
* @param minor
* @param build
* @param revision
* @param suffix
* null
*/
public Version(int major, int minor, int build, int revision, String suffix) {
this.major = major;
this.minor = minor;
this.build = build;
this.revision = revision;
this.suffix = (suffix == null) ? "" : suffix;
}
@Override
public int hashCode() {
return this.toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Version))
return false;
Version other = (Version) obj;
return (this.major == other.major) &&
(this.minor == other.minor) &&
(this.build == other.build) &&
(this.revision == other.revision) &&
this.suffix.equals(other.suffix);
}
@Override
public String toString() {
return String.format("%d%s%s%s%s",
this.major,
(this.minor > -1) ? "." + this.minor : "",
(this.build > -1) ? "." + this.build : "",
(this.revision > -1) ? "." + this.revision : "",
this.suffix);
}
@Override
public int compareTo(Version o) {
if (o == null)
throw new NullPointerException();
if (this.major > o.major)
return 1;
else if (this.major < o.major)
return -1;
if (this.minor > o.minor)
return 1;
else if (this.minor < o.minor)
return -1;
if (this.build > o.build)
return 1;
else if (this.build < o.build)
return -1;
if (this.revision > o.revision)
return 1;
else if (this.revision < o.revision)
return -1;
// suffix ()
return 0;
}
/**
* Version
*
* @param text
* '.'
* @return Version
*/
public static Version parse(String text) {
if (text == null)
throw new IllegalArgumentException("null");
Matcher m = parsePattern.matcher(text);
if (!m.find())
throw new IllegalArgumentException(text);
String major = m.group(1);
String minor = m.group(2);
String build = m.group(3);
String revision = m.group(4);
if (major == null || major.isEmpty())
throw new IllegalArgumentException(text);
return new Version(
Integer.parseInt(major),
(minor == null || minor.isEmpty()) ? -1 : Integer.parseInt(minor),
(build == null || build.isEmpty()) ? -1 : Integer.parseInt(build),
(revision == null || revision.isEmpty()) ? -1 : Integer.parseInt(revision),
m.group(5));
}
} |
package am.userInterface;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import am.AMException;
import am.GlobalStaticVariables;
import am.Utility;
import am.app.Core;
import am.app.feedback.ui.SelectionPanel;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.Alignment;
import am.app.mappingEngine.AlignmentSet;
import am.app.mappingEngine.MatcherFactory;
import am.app.mappingEngine.MatchersRegistry;
import am.app.mappingEngine.manualMatcher.UserManualMatcher;
import am.app.ontology.Ontology;
import am.tools.ThresholdAnalysis.ThresholdAnalysis;
import am.tools.WordNetLookup.WordNetLookupPanel;
import am.tools.seals.SealsPanel;
import am.userInterface.find.FindDialog;
import am.userInterface.find.FindInterface;
import am.userInterface.table.MatchersTablePanel;
import am.userInterface.vertex.VertexDescriptionPane;
public class UIMenu implements ActionListener {
// create Top Level menus
private JMenu fileMenu, editMenu, viewMenu, helpMenu, matchingMenu, toolsMenu, ontologyMenu;
// File menu.
private JMenuItem xit, openSource, openTarget, openMostRecentPair,
closeSource, closeTarget;
private JMenu menuRecentSource, menuRecentTarget;
// Edit menu.
private JMenuItem itemFind;
//private JMenuItem undo, redo;
// View menu.
private JMenuItem colorsItem, itemViewsCanvas;
private JCheckBoxMenuItem smoMenuItem; // Menu item for toggling "Selected Matchings Only" view mode.
private JMenu menuViews; // Views submenu. TODO: Rename this to something more descriptive.
// Ontology menu.
private JMenuItem ontologyDetails;
// Tools menu.
private JMenuItem wordnetLookupItem, sealsItem;
// Matching menu.
private JMenuItem manualMapping, userFeedBack,
newMatching, runMatching, copyMatching, deleteMatching, clearAll,
doRemoveDuplicates,
saveMatching,
refEvaluateMatching,
thresholdAnalysis;
// Help menu.
private JMenuItem howToUse, aboutItem;
//creates a menu bar
private JMenuBar myMenuBar;
private UI ui; // reference to the main ui.
private JCheckBoxMenuItem disableVisualizationItem;
private JCheckBoxMenuItem showLabelItem;
private JCheckBoxMenuItem showLocalNameItem;
public UIMenu(UI ui){
this.ui=ui;
init();
}
public void refreshRecentMenus() {
refreshRecentMenus( menuRecentSource, menuRecentTarget);
}
/**
* This function will update the Recent File Menus with the most up to date recent files
* @param recentsource
* @param recenttarget
*/
private void refreshRecentMenus( JMenu recentsource, JMenu recenttarget ) {
AppPreferences prefs = ui.getAppPreferences();
// first we start by removing all sub menus
recentsource.removeAll();
recenttarget.removeAll();
// then populate the menus again.
for( int i = 0; i < prefs.countRecentSources(); i++) {
JMenuItem menuitem = new JMenuItem(i + ". " + prefs.getRecentSourceFileName(i));
menuitem.setActionCommand("source" + i);
menuitem.setMnemonic( 48 + i);
menuitem.addActionListener(this);
menuRecentSource.add(menuitem);
}
for( int i = 0; i < prefs.countRecentTargets(); i++) {
JMenuItem menuitem = new JMenuItem(i + ". " + prefs.getRecentTargetFileName(i));
menuitem.setActionCommand("target" + i);
menuitem.setMnemonic( 48 + i);
menuitem.addActionListener(this);
menuRecentTarget.add(menuitem);
}
}
public void actionPerformed (ActionEvent ae){
try {
Object obj = ae.getSource();
MatchersControlPanel controlPanel = ui.getControlPanel();
if (obj == xit){
// confirm exit
confirmExit();
// if it is no, then do nothing
} else if ( obj == itemFind ) {
// we are going to be searching throught the currently visible tab
Object visibleTab = Core.getUI().getCurrentTab();
if( visibleTab instanceof FindInterface ) {
FindDialog fd = new FindDialog( (FindInterface) visibleTab);
fd.setVisible(true);
}
}else if (obj == colorsItem){
new Legend();
}else if (obj == howToUse){
Utility.displayTextAreaPane(Help.getHelpMenuString(), "Help");
}else if (obj == openSource){
openAndReadFilesForMapping(GlobalStaticVariables.SOURCENODE);
if( Core.getInstance().sourceIsLoaded() ) {
openSource.setEnabled(false);
menuRecentSource.setEnabled(false);
closeSource.setEnabled(true);
}
}else if (obj == openTarget){
openAndReadFilesForMapping(GlobalStaticVariables.TARGETNODE);
if( Core.getInstance().targetIsLoaded() ) {
openTarget.setEnabled(false);
menuRecentTarget.setEnabled(false);
closeTarget.setEnabled(true);
}
}else if (obj == openMostRecentPair){
AppPreferences prefs = new AppPreferences();
int position = 0;
ui.openFile( prefs.getRecentSourceFileName(position), GlobalStaticVariables.SOURCENODE,
prefs.getRecentSourceSyntax(position), prefs.getRecentSourceLanguage(position), prefs.getRecentSourceSkipNamespace(position), prefs.getRecentSourceNoReasoner(position));
ui.openFile( prefs.getRecentTargetFileName(position), GlobalStaticVariables.TARGETNODE,
prefs.getRecentTargetSyntax(position), prefs.getRecentTargetLanguage(position), prefs.getRecentTargetSkipNamespace(position), prefs.getRecentTargetNoReasoner(position));
closeSource.setEnabled(true);
closeTarget.setEnabled(true);
openSource.setEnabled(false);
openTarget.setEnabled(false);
menuRecentSource.setEnabled(false);
menuRecentTarget.setEnabled(false);
openMostRecentPair.setEnabled(false);
}else if (obj == aboutItem){
new AboutDialog();
//displayOptionPane("Agreement Maker 3.0\nAdvis research group\nThe University of Illinois at Chicago 2004","About Agreement Maker");
}
else if( obj == disableVisualizationItem ) {
// Save the SMO setting that has been changed
AppPreferences prefs = ui.getAppPreferences();
boolean disableVis = disableVisualizationItem.isSelected();
prefs.saveSelectedMatchingsOnly(disableVis);
ui.getCanvas().setDisableVisualization(disableVis);
ui.redisplayCanvas();
}
else if( obj == smoMenuItem ) {
// Save the SMO setting that has been changed
AppPreferences prefs = ui.getAppPreferences();
boolean smoStatus = smoMenuItem.isSelected();
prefs.saveSelectedMatchingsOnly(smoStatus);
ui.getCanvas().setSMO(smoStatus);
ui.redisplayCanvas();
}
else if( obj == showLabelItem || obj == showLocalNameItem ) {
// Save the setting that has been changed
AppPreferences prefs = ui.getAppPreferences();
boolean showLabel = showLabelItem.isSelected();
prefs.saveShowLabel(showLabel);
ui.getCanvas().setShowLabel(showLabel);
boolean showLocalname = showLocalNameItem.isSelected();
prefs.saveShowLocalname(showLocalname);
ui.getCanvas().setShowLocalName(showLocalname);
ui.redisplayCanvas();
}
else if( obj == sealsItem ) {
// open up the SEALS Interface tab
SealsPanel sp = new SealsPanel();
ui.addTab("SEALS", null, sp, "SEALS Interface");
}
else if( obj == wordnetLookupItem ) {
// open up the WordNet lookup interface
WordNetLookupPanel wnlp = new WordNetLookupPanel();
ui.addTab("WordNet", null, wnlp, "Query the WordNet dictionary.");
}
else if( obj == userFeedBack ) {
SelectionPanel sp = new SelectionPanel(ui);
sp.showScreen_Start();
ui.addTab("User Feedback Loop", null, sp, "User Feedback Loop");
}
else if( obj == manualMapping) {
Utility.displayMessagePane("To edit or create a manual mapping select any number of source and target nodes.\nLeft click on a node to select it, use Ctrl and/or Shift for multiple selections.", "Manual Mapping");
}
else if(obj == newMatching) {
controlPanel.newManual();
}
else if(obj == runMatching) {
controlPanel.matchSelected();
}
else if(obj == copyMatching) {
controlPanel.copy();
}
else if(obj == deleteMatching) {
controlPanel.delete();
}
else if(obj == saveMatching) {
controlPanel.export();
}
else if(obj == refEvaluateMatching) {
controlPanel.evaluate();
}
else if(obj == clearAll) {
controlPanel.clearAll();
}
else if(obj == ontologyDetails) {
ontologyDetails();
}
else if( obj == itemViewsCanvas ) {
JPanel CanvasPanel = new JPanel();
CanvasPanel.setLayout(new BorderLayout());
Canvas goodOldCanvas = new Canvas(ui);
goodOldCanvas.setFocusable(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setWheelScrollingEnabled(true);
scrollPane.getVerticalScrollBar().setUnitIncrement(20);
scrollPane.setViewportView(goodOldCanvas);
goodOldCanvas.setScrollPane(scrollPane);
JPanel jPanel = null;
System.out.println("opening file");
jPanel = new VertexDescriptionPane(GlobalStaticVariables.ONTFILE);//takes care of fields for XML files as well
jPanel.setMinimumSize(new Dimension(200,480));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane, jPanel);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(1.0);
splitPane.setMinimumSize(new Dimension(640,480));
splitPane.setPreferredSize(new Dimension(640,480));
splitPane.getLeftComponent().setPreferredSize(new Dimension(640,480));
// add scrollpane to the panel and add the panel to the frame's content pane
CanvasPanel.add(splitPane, BorderLayout.CENTER);
//frame.getContentPane().add(splitPane, BorderLayout.CENTER);
//panelControlPanel = new ControlPanel(this, uiMenu, canvas);
MatchersControlPanel matcherControlPanel = new MatchersControlPanel();
CanvasPanel.add(matcherControlPanel, BorderLayout.PAGE_END);
//frame.getContentPane().add(matcherControlPanel, BorderLayout.PAGE_END);
ui.addTab("Canvas View", null, CanvasPanel, "Canvas View");
}
else if( obj == doRemoveDuplicates ) {
// TODO: Get rid of this from here.
MatchersTablePanel m = controlPanel.getTablePanel();
int[] selectedRows = m.getTable().getSelectedRows();
if(selectedRows.length != 2) {
Utility.displayErrorPane("You must select two matchers.", null);
}
else {
int i, j;
Core core = Core.getInstance();
AbstractMatcher firstMatcher = core.getMatcherInstances().get(selectedRows[0]);
AbstractMatcher secondMatcher = core.getMatcherInstances().get(selectedRows[1]);
AlignmentSet<Alignment> firstClassSet = firstMatcher.getClassAlignmentSet();
AlignmentSet<Alignment> secondClassSet = secondMatcher.getClassAlignmentSet();
AlignmentSet<Alignment> firstPropertiesSet = firstMatcher.getPropertyAlignmentSet();
AlignmentSet<Alignment> secondPropertiesSet = secondMatcher.getPropertyAlignmentSet();
AlignmentSet<Alignment> combinedClassSet = new AlignmentSet<Alignment>();
AlignmentSet<Alignment> combinedPropertiesSet = new AlignmentSet<Alignment>();
// double nested loop, later I will write a better algorithm -cos
for( i = 0; i < firstClassSet.size(); i++ ) {
Alignment candidate = firstClassSet.getAlignment(i);
boolean foundDuplicate = false;
for( j = 0; j < secondClassSet.size(); j++ ) {
Alignment test = secondClassSet.getAlignment(j);
int sourceNode1 = candidate.getEntity1().getIndex();
int targetNode1 = candidate.getEntity2().getIndex();
int sourceNode2 = test.getEntity1().getIndex();
int targetNode2 = test.getEntity2().getIndex();
if(sourceNode1 == sourceNode2 && targetNode1 == targetNode2 ) {
// we found a duplicate
foundDuplicate = true;
break;
}
}
if( !foundDuplicate ) combinedClassSet.addAlignment(candidate);
}
for( i = 0; i < secondClassSet.size(); i++ ) {
Alignment candidate = secondClassSet.getAlignment(i);
boolean foundDuplicate = false;
for( j = 0; j < firstClassSet.size(); j++ ) {
Alignment test = firstClassSet.getAlignment(j);
int sourceNode1 = candidate.getEntity1().getIndex();
int targetNode1 = candidate.getEntity2().getIndex();
int sourceNode2 = test.getEntity1().getIndex();
int targetNode2 = test.getEntity2().getIndex();
if(sourceNode1 == sourceNode2 && targetNode1 == targetNode2 ) {
// we found a duplicate
foundDuplicate = true;
break;
}
}
if( !foundDuplicate ) combinedClassSet.addAlignment(candidate);
}
// now the properties.
// double nested loop, later I will write a better algorithm -cos
for( i = 0; i < firstPropertiesSet.size(); i++ ) {
Alignment candidate = firstPropertiesSet.getAlignment(i);
boolean foundDuplicate = false;
for( j = 0; j < secondPropertiesSet.size(); j++ ) {
Alignment test = secondPropertiesSet.getAlignment(j);
int sourceNode1 = candidate.getEntity1().getIndex();
int targetNode1 = candidate.getEntity2().getIndex();
int sourceNode2 = test.getEntity1().getIndex();
int targetNode2 = test.getEntity2().getIndex();
if(sourceNode1 == sourceNode2 && targetNode1 == targetNode2 ) {
// we found a duplicate
foundDuplicate = true;
break;
}
}
if( !foundDuplicate ) combinedPropertiesSet.addAlignment(candidate);
}
for( i = 0; i < secondPropertiesSet.size(); i++ ) {
Alignment candidate = secondPropertiesSet.getAlignment(i);
boolean foundDuplicate = false;
for( j = 0; j < firstPropertiesSet.size(); j++ ) {
Alignment test = firstPropertiesSet.getAlignment(j);
int sourceNode1 = candidate.getEntity1().getIndex();
int targetNode1 = candidate.getEntity2().getIndex();
int sourceNode2 = test.getEntity1().getIndex();
int targetNode2 = test.getEntity2().getIndex();
if(sourceNode1 == sourceNode2 && targetNode1 == targetNode2 ) {
// we found a duplicate
foundDuplicate = true;
break;
}
}
if( !foundDuplicate ) combinedPropertiesSet.addAlignment(candidate);
}
AbstractMatcher newMatcher = new UserManualMatcher();
newMatcher.setClassesAlignmentSet(combinedClassSet);
newMatcher.setPropertiesAlignmentSet(combinedClassSet);
newMatcher.setName(MatchersRegistry.UniqueMatchings);
newMatcher.setID( Core.getInstance().getNextMatcherID());
m.addMatcher(newMatcher);
}
} else if( obj == closeSource ) {
if( Core.getInstance().targetIsLoaded() ) {
// confirm with the user that we should reset matchings
if( controlPanel.clearAll() ) {
Core.getInstance().removeOntology( Core.getInstance().getSourceOntology() );
closeSource.setEnabled(false); // the source ontology has been removed, grey out the menu entry
// and we need to enable the source ontology loading menu entries
openSource.setEnabled(true);
menuRecentSource.setEnabled(true);
}
} else {
// if there is no target loaded, we don't have to reset matchings.
//controlPanel.resetMatchings();
Core.getInstance().removeOntology( Core.getInstance().getSourceOntology() );
closeSource.setEnabled(false); // the source ontology has been removed, grey out the menu entry
// and we need to enable the source ontology loading menu entries
openSource.setEnabled(true);
menuRecentSource.setEnabled(true);
ui.redisplayCanvas();
}
if( !Core.getInstance().sourceIsLoaded() && !Core.getInstance().targetIsLoaded() ) openMostRecentPair.setEnabled(true);
} else if( obj == closeTarget ) {
if( Core.getInstance().sourceIsLoaded() ) {
// confirm with the user that we should reset any matchings
if( controlPanel.clearAll() ) {
Core.getInstance().removeOntology( Core.getInstance().getTargetOntology() );
closeTarget.setEnabled(false); // the target ontology has been removed, grey out the menu entry
// and we need to enable the target ontology loading menu entries
openTarget.setEnabled(true);
menuRecentTarget.setEnabled(true);
}
} else {
// if there is no source ontology loaded, we don't have to ask the user
Core.getInstance().removeOntology( Core.getInstance().getTargetOntology() );
closeTarget.setEnabled(false); // the target ontology has been removed, grey out the menu entrys
// and we need to enable the target ontology loading menu entries
openTarget.setEnabled(true);
menuRecentTarget.setEnabled(true);
ui.redisplayCanvas();
}
if( !Core.getInstance().sourceIsLoaded() && !Core.getInstance().targetIsLoaded() ) openMostRecentPair.setEnabled(true);
} else if( obj == thresholdAnalysis ) {
// decide if we are running in a single mode or batch mode
if( Utility.displayConfirmPane("Are you running a batch mode?", "Batch mode?") ) {
String batchFile = JOptionPane.showInputDialog(null, "Batch File?");
String outputDirectory = JOptionPane.showInputDialog(null, "Output Directory?");
String matcherName = Core.getUI().getControlPanel().getComboboxSelectedItem();
MatchersRegistry matcher = MatcherFactory.getMatchersRegistryEntry(matcherName);
if( Utility.displayConfirmPane("Using matcher: " + matcherName, "Ok?") ) {
ThresholdAnalysis than = new ThresholdAnalysis(matcher);
than.setBatchFile(batchFile);
than.setOutputDirectory(outputDirectory);
than.execute();
}
} else {
// single mode
String referenceAlignment = JOptionPane.showInputDialog(null, "Reference Alignment?");
String outputDirectory = JOptionPane.showInputDialog(null, "Output Directory?");
String prefix = JOptionPane.showInputDialog(null, "File name? (leave empty to use matcher name)");
if( prefix != null ) prefix.trim();
int[] rowsIndex = Core.getUI().getControlPanel().getTablePanel().getTable().getSelectedRows();
if( rowsIndex.length == 0 ) { Utility.displayErrorPane("You must select a matcher from the control panel when running in single mode.", "Error"); return; }
AbstractMatcher matcherToBeAnalyzed = Core.getInstance().getMatcherInstances().get(rowsIndex[0]);
if( Utility.displayConfirmPane("Using matcher: " + matcherToBeAnalyzed.getName().getMatcherName(), "Ok?") ) {
ThresholdAnalysis than = new ThresholdAnalysis(matcherToBeAnalyzed);
than.setReferenceAlignment(referenceAlignment);
than.setOutputDirectory(outputDirectory);
if( prefix != null && !prefix.isEmpty() ) than.setOutputPrefix(matcherToBeAnalyzed.getClass().getSimpleName() + "_" + System.currentTimeMillis() + "_");
than.execute();
}
}
}
// TODO: find a Better way to do this
String command = ae.getActionCommand(); // get the command string we set
if( command.length() == 7 ) { // the only menus that set an action command are the recent menus, so we're ok.
AppPreferences prefs = new AppPreferences();
char index[] = new char[1]; // '0' - '9'
char ontotype[] = new char[1]; // 's' or 't' (source or target)
command.getChars(0, 1 , ontotype, 0); // get the first character of the sting
command.getChars(command.length() - 1, command.length(), index, 0); // get the last character of the string
// based on the first and last characters of the action command, we can tell which menu was clicked.
// the rest is easy
int position = index[0] - 48; // 0 - 9
switch( ontotype[0] ) {
case 's':
ui.openFile( prefs.getRecentSourceFileName(position), GlobalStaticVariables.SOURCENODE,
prefs.getRecentSourceSyntax(position), prefs.getRecentSourceLanguage(position), prefs.getRecentSourceSkipNamespace(position), prefs.getRecentSourceNoReasoner(position));
prefs.saveRecentFile(prefs.getRecentSourceFileName(position), GlobalStaticVariables.SOURCENODE,
prefs.getRecentSourceSyntax(position), prefs.getRecentSourceLanguage(position), prefs.getRecentSourceSkipNamespace(position), prefs.getRecentSourceNoReasoner(position));
ui.getUIMenu().refreshRecentMenus(); // after we update the recent files, refresh the contents of the recent menus.
// Now that we have loaded a source ontology, disable all the source ontology loading menu entries ...
openSource.setEnabled(false);
menuRecentSource.setEnabled(false);
openMostRecentPair.setEnabled(false);
// ... and enable the close menu entry
closeSource.setEnabled(true);
break;
case 't':
ui.openFile( prefs.getRecentTargetFileName(position), GlobalStaticVariables.TARGETNODE,
prefs.getRecentTargetSyntax(position), prefs.getRecentTargetLanguage(position), prefs.getRecentTargetSkipNamespace(position), prefs.getRecentTargetNoReasoner(position));
prefs.saveRecentFile(prefs.getRecentTargetFileName(position), GlobalStaticVariables.TARGETNODE,
prefs.getRecentTargetSyntax(position), prefs.getRecentTargetLanguage(position), prefs.getRecentTargetSkipNamespace(position), prefs.getRecentTargetNoReasoner(position));
ui.getUIMenu().refreshRecentMenus(); // after we update the recent files, refresh the contents of the recent menus.
// Now that we have loaded a source ontology, disable all the source ontology loading menu entries ...
openTarget.setEnabled(false);
menuRecentTarget.setEnabled(false);
openMostRecentPair.setEnabled(false);
// ... and enable the close menu entry
closeTarget.setEnabled(true);
break;
default:
break;
}
}
}
catch(AMException ex2) {
Utility.displayMessagePane(ex2.getMessage(), null);
}
catch(Exception ex) {
ex.printStackTrace();
Utility.displayErrorPane(Utility.UNEXPECTED_ERROR, null);
}
}
public void ontologyDetails() {
Core c = Core.getInstance();
Ontology sourceO = c.getSourceOntology();
Ontology targetO = c.getTargetOntology();
String sourceClassString = "Not loaded\n";
String sourcePropString = "Not loaded\n";
String targetClassString = "Not loaded\n";
String targetPropString = "Not loaded\n";
if(c.sourceIsLoaded()) {
sourceClassString = sourceO.getClassDetails();
sourcePropString = sourceO.getPropDetails();
}
if(c.targetIsLoaded()) {
targetClassString = targetO.getClassDetails();
targetPropString = targetO.getPropDetails();
}
String report = "Ontology details\n\n";
report+= "Hierarchies \t#concepts\tdepth\tUC-diameter\tLC-diameter\t#roots\t#leaves\n";
report+= "Source Classes:\t"+sourceClassString;
report+= "Target Classes:\t"+targetClassString;
report+= "Source Properties:\t"+sourcePropString;
report+= "Target Properties:\t"+targetPropString;
Utility.displayTextAreaWithDim(report,"Reference Evaluation Report", 10, 60);
}
public void displayOptionPane(String desc, String title){
JOptionPane.showMessageDialog(null,desc,title, JOptionPane.PLAIN_MESSAGE);
}
public void init(){
// need AppPreferences for smoItem, to get if is checked or not.
AppPreferences prefs = new AppPreferences();
//Creating the menu bar
myMenuBar = new JMenuBar();
ui.getUIFrame().setJMenuBar(myMenuBar);
// building the file menu
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
myMenuBar.add(fileMenu);
//add openGFile menu item to file menu
openSource = new JMenuItem("Open Source Ontology...",new ImageIcon("../images/fileImage.gif"));
//openSource.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
//openSource.setMnemonic(KeyEvent.VK_O);
openSource.addActionListener(this);
fileMenu.add(openSource);
//add openGFile menu item to file menu
openTarget = new JMenuItem("Open Target Ontology...",new ImageIcon("../images/fileImage.gif"));
//openTarget.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
//openTarget.setMnemonic(KeyEvent.VK_O);
openTarget.addActionListener(this);
fileMenu.add(openTarget);
// add separator
fileMenu.addSeparator();
// Construct the recent files menu.
menuRecentSource = new JMenu("Recent Sources...");
menuRecentSource.setMnemonic('u');
menuRecentTarget = new JMenu("Recent Targets...");
menuRecentTarget.setMnemonic('a');
refreshRecentMenus(menuRecentSource, menuRecentTarget);
/*
menuRecentSourceList = new JMenuItem[10];
Preferences prefs = Preferences.userRoot().node("/com/advis/agreementMaker");
int lastsynt = prefs.getInt(PREF_LASTSYNT, 0);
int lastlang = prefs.getInt(PREF_LASTLANG, 1);
*/
//menuRecentSource.add( new JMenu());
fileMenu.add(menuRecentSource);
fileMenu.add(menuRecentTarget);
openMostRecentPair = new JMenuItem("Open most recent pair");
openMostRecentPair.addActionListener(this);
fileMenu.add(openMostRecentPair);
fileMenu.addSeparator();
//private JMenuItem menuRecentSource, menuRecentTarget;
//private JMenuItem menuRecentSourceList[], menuRecentTargetList[]; // the list of recent files
closeSource = new JMenuItem("Close Source Ontology");
closeSource.addActionListener(this);
closeSource.setEnabled(false); // there is no source ontology loaded at the beginning
closeTarget = new JMenuItem("Close Target Ontology");
closeTarget.addActionListener(this);
closeTarget.setEnabled(false); // there is no target ontology loaded at the beginning
fileMenu.add(closeSource);
fileMenu.add(closeTarget);
fileMenu.addSeparator();
// add exit menu item to file menu
xit = new JMenuItem("Exit", KeyEvent.VK_X);
xit.addActionListener(this);
fileMenu.add(xit);
// build the Edit menu
editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
myMenuBar.add(editMenu);
itemFind = new JMenuItem("Find", KeyEvent.VK_F);
itemFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
itemFind.addActionListener(this);
editMenu.add(itemFind);
// Build view menu in the menu bar: TODO
viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
myMenuBar.add(viewMenu);
//All show and hide details has been removed right now
// add separator
//viewMenu.addSeparator();
// add keyItem
colorsItem = new JMenuItem("Colors",KeyEvent.VK_K);
colorsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
colorsItem.addActionListener(this);
viewMenu.add(colorsItem);
viewMenu.addSeparator();
// add "Disable Visualization" option to the view menu
disableVisualizationItem = new JCheckBoxMenuItem("Disable hierarchies visualization");
disableVisualizationItem.addActionListener(this);
disableVisualizationItem.setSelected(prefs.getDisableVisualization());
// viewMenu.add(disableVisualizationItem);
// add "Selected Matchings Only" option to the view menu
smoMenuItem = new JCheckBoxMenuItem("Selected Matchings Only");
smoMenuItem.addActionListener(this);
smoMenuItem.setSelected(prefs.getSelectedMatchingsOnly());
//viewMenu.add(smoMenuItem);
showLocalNameItem = new JCheckBoxMenuItem("Show localnames");
showLocalNameItem.addActionListener(this);
showLocalNameItem.setSelected(prefs.getShowLocalname());
viewMenu.add(showLocalNameItem);
showLabelItem = new JCheckBoxMenuItem("Show labels");
showLabelItem.addActionListener(this);
showLabelItem.setSelected(prefs.getShowLabel());
viewMenu.add(showLabelItem);
//viewMenu.addSeparator();
menuViews = new JMenu("New view");
itemViewsCanvas = new JMenuItem("Canvas");
itemViewsCanvas.addActionListener(this);
//itemViewsCanvas2 = new JMenuItem("Canvas2");
//itemViewsCanvas2.addActionListener(this);
menuViews.add(itemViewsCanvas);
//menuViews.add(itemViewsCanvas2);
//viewMenu.add(menuViews);
/*
evaluationMenu = new JMenu("Evaluation");
myMenuBar.add(ontologyMenu);
*/
//ontology menu
ontologyMenu = new JMenu("Ontology");
ontologyMenu.setMnemonic('O');
ontologyDetails = new JMenuItem("Ontology details");
ontologyDetails.addActionListener(this);
ontologyMenu.add(ontologyDetails);
myMenuBar.add(ontologyMenu);
matchingMenu = new JMenu("Matching");
matchingMenu.setMnemonic('M');
manualMapping = new JMenuItem("Manual Mapping");
manualMapping.addActionListener(this);
matchingMenu.add(manualMapping);
userFeedBack = new JMenuItem("User Feedback Loop");
userFeedBack.addActionListener(this);
//matchingMenu.add(userFeedBack); // Remove UFL for distribution.
matchingMenu.addSeparator();
newMatching = new JMenuItem("New empty matching");
newMatching.addActionListener(this);
matchingMenu.add(newMatching);
runMatching = new JMenuItem("Run selected matcher");
runMatching.addActionListener(this);
matchingMenu.add(runMatching);
copyMatching = new JMenuItem("Copy selected matchings");
copyMatching.addActionListener(this);
matchingMenu.add(copyMatching);
deleteMatching = new JMenuItem("Delete selected matchings");
deleteMatching.addActionListener(this);
matchingMenu.add(deleteMatching);
clearAll = new JMenuItem("Clear All");
clearAll.addActionListener(this);
matchingMenu.add(clearAll);
matchingMenu.addSeparator();
doRemoveDuplicates = new JMenuItem("Remove Duplicate Alignments");
doRemoveDuplicates.addActionListener(this);
//matchingMenu.add(doRemoveDuplicates);
//matchingMenu.addSeparator();
saveMatching = new JMenuItem("Save selected matchings into a file");
saveMatching.addActionListener(this);
matchingMenu.add(saveMatching);
matchingMenu.addSeparator();
refEvaluateMatching = new JMenuItem("Evaluate with reference file");
refEvaluateMatching.addActionListener(this);
matchingMenu.add(refEvaluateMatching);
thresholdAnalysis = new JMenuItem("Threshold Analysis");
thresholdAnalysis.addActionListener(this);
matchingMenu.add(thresholdAnalysis);
myMenuBar.add(matchingMenu);
toolsMenu = new JMenu("Tools");
toolsMenu.setMnemonic('T');
myMenuBar.add(toolsMenu);
// Tools -> Wordnet lookup panel...
wordnetLookupItem = new JMenuItem("Wordnet Lookup ...");
wordnetLookupItem.setMnemonic(KeyEvent.VK_W);
wordnetLookupItem.addActionListener(this);
toolsMenu.add(wordnetLookupItem); // Wordnet lookup is not done yet.
// Tools -> SEALS Interface...
sealsItem = new JMenuItem("SEALS Interface...");
sealsItem.setMnemonic(KeyEvent.VK_S);
sealsItem.addActionListener(this);
toolsMenu.add(sealsItem);
// Build help menu in the menu bar.
helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
myMenuBar.add(helpMenu);
// add menu item to help menu
howToUse = new JMenuItem("Help", new ImageIcon("images/helpImage.gif"));
howToUse.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK));
howToUse.setMnemonic(KeyEvent.VK_H);
howToUse.addActionListener(this);
helpMenu.add(howToUse);
// add about item to help menu
aboutItem = new JMenuItem("About AgreementMaker", new ImageIcon("images/aboutImage.gif"));
aboutItem.setMnemonic(KeyEvent.VK_A);
//aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
aboutItem.addActionListener(this);
helpMenu.add(aboutItem);
}
/**
* This method reads the XML or OWL files and creates trees for mapping
*/
public void openAndReadFilesForMapping(int fileType){
new OpenOntologyFileDialog(fileType, ui);
}
/**
* Function that is called when to user wants to close the program.
*/
public void confirmExit() {
int n = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit ?","Exit Agreement Maker",JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION)
{
System.out.println("Exiting the program.\n");
System.exit(0);
}
}
} |
package org.lp20.aikuma.model;
import android.os.Environment;
import android.os.Parcel;
import android.util.Log;
import org.lp20.aikuma.Aikuma;
import org.lp20.aikuma.util.FileIO;
import org.lp20.aikuma.util.IdUtils;
import org.lp20.aikuma.util.StandardDateFormat;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import static junit.framework.Assert.assertTrue;
/**
* The class that stores the metadata of a recording, including it's ID,
* creator's ID, name, date, group ID, and languages.
*
* @author Oliver Adams <oliver.adams@gmail.com>
* @author Florian Hanke <florian.hanke@gmail.com>
*/
public class Recording extends FileModel {
// String tag for debugging
private static final String TAG = "Recording";
/** sample file duration in sec */
public static final long SAMPLE_SEC = 15;
/**
* The constructor used when first creating a Recording.
*
* @param recordingUUID the temporary UUID of the recording in question.
* (recording can be wav or movie(mp4))
* @param name The recording's name.
* @param date The date of creation.
* * @param versionName The recording's version(v0x)
* @param ownerId The recording owner's ID(Google account)
* @param languages The languages associated with the recording
* @param speakersIds The IDs of the speakers associated with the
* recording
* @param deviceName The model name of the device
* @param androidID The android ID of the device that created the
* recording
* @param groupId The ID of the group of recordings this recording
* belongs in (Some source recording and respeakings/commentaries)
* @param sourceVerId The version-ID of the source recording of this recording
* @param sampleRate The sample rate of the recording.
* @param durationMsec The duration of the recording in milliseconds.
* @param format The mime type
* @param bitsPerSample The bits per sample of the audio
* @param numChannels The number of channels of the audio
* @param latitude The location data
* @param longitude The location data
*/
public Recording(UUID recordingUUID, String name, Date date,
String versionName, String ownerId,
List<Language> languages, List<String> speakersIds,
String deviceName, String androidID, String groupId, String sourceVerId,
long sampleRate, int durationMsec, String format, int numChannels,
int bitsPerSample, Double latitude, Double longitude) {
super(versionName, ownerId, null, null, format);
this.recordingUUID = recordingUUID;
setName(name);
setDate(date);
setLanguages(languages);
setSpeakersIds(speakersIds);
setDeviceName(deviceName);
setAndroidID(androidID);
setSampleRate(sampleRate);
setDurationMsec(durationMsec);
setGroupId(groupId);
this.sourceVerId = sourceVerId;
this.numChannels = numChannels;
this.bitsPerSample = bitsPerSample;
this.latitude = latitude;
this.longitude = longitude;
// If there isn't an group Id, ie this is an original
if (groupId == null) {
setGroupId(createGroupId());
setRespeakingId("");
} else {
// Then we must generate the 4 digit respeaking ID.
setRespeakingId(IdUtils.randomDigitString(6));
}
setId(determineId());
setFileType(sourceVerId, languages);
}
/**
* The constructor used when reading in an existing Recording.
*
* @param name The recording's name.
* @param date The date of creation.
* @param versionName The recording's version(v0x)
* @param ownerId The recording owner's ID(Google account)
* @param sourceVerId The source's version and Id (if not respeaking, null)
* @param format The file format
* @param fileType The file type
* @param languages The languages associated with the recording
* @param speakersIds The IDs of the speakers associated with the
* recording
* @param androidID The android ID of the device that created the
* recording
* @param groupId The ID of the group of recordings this recording
* belongs in (Some source recording and respeakings/commentaries)
* @param respeakingId The ID of the recording that this recording
* is a respeaking of
* @param sampleRate The sample rate of the recording.
* @param durationMsec The duration of the recording in milliseconds.
*/
public Recording(String name, Date date,
String versionName, String ownerId, String sourceVerId,
List<Language> languages, List<String> speakersIds,
String androidID, String groupId, String respeakingId,
long sampleRate, int durationMsec, String format, String fileType) {
super(versionName, ownerId, null, null, format);
setName(name);
setDate(date);
setLanguages(languages);
setSpeakersIds(speakersIds);
setAndroidID(androidID);
setSampleRate(sampleRate);
setDurationMsec(durationMsec);
setGroupId(groupId);
setRespeakingId(respeakingId);
setId(determineId());
this.sourceVerId = sourceVerId;
this.fileType = fileType;
}
private String determineId() {
// Build up the filename prefix
StringBuilder id = new StringBuilder();
id.append(getGroupId());
id.append("-");
id.append(getOwnerId());
id.append("-");
if (isOriginal()) {
id.append("source");
} else {
id.append("respeaking-");
id.append(respeakingId);
}
return id.toString();
}
/**
* Returns true if the Recording is an original; false if respeaking
*
* @return True if the recording is an original.
*/
public boolean isOriginal() {
return respeakingId != null && respeakingId.length() == 0;
}
// Moves a WAV file with a temporary UUID from a no-sync directory to
// its rightful place in the connected world of Aikuma, with a proper name
// and where it will find it's best friend - a JSON metadata file.
private void importWav(UUID wavUUID, String id) throws IOException {
importWav(wavUUID + ".wav", id + ".wav");
}
private void importWav(String wavUUIDExt, String idExt)
throws IOException {
File wavFile = new File(getNoSyncRecordingsPath(), wavUUIDExt);
Log.i(TAG, "importwav: " + wavFile.length());
FileUtils.moveFile(wavFile, this.getFile(idExt));
Log.i("Recording", wavFile.getAbsolutePath() + " move to " + this.getFile(idExt).getAbsolutePath());
}
// Moves a video File from a no-sync directory to its rightful place
private void importMov(UUID videoUUID, String id)
throws IOException {
File movFile = new File(getNoSyncRecordingsPath(), videoUUID + ".mp4");
FileUtils.moveFile(movFile, this.getFile());
Log.i("Recording", movFile.getAbsolutePath() + " move to " + this.getFile().getAbsolutePath());
}
// Similar to importWav, except for the mapping file.
private void importMapping(UUID wavUUID, String id)
throws IOException {
File mapFile = new File(getNoSyncRecordingsPath(), wavUUID + ".map");
FileUtils.moveFile(mapFile, getMapFile());
}
// Create a group ID (the prefix for recordings)
private String createGroupId() {
return IdUtils.sampleFromAlphabet(12, "abcdefghijklmnopqrstuvwxyz");
}
/**
* Returns a File that refers to the actual recording file.
*
* @return The file the recording is stored in.
*/
public File getFile() {
String extension = (this.isMovie())? ".mp4" : ".wav";
return getFile(id + extension);
}
private File getFile(String idExt) {
return new File(getRecordingsPath(), getGroupId() + "/"
+ idExt);
}
/**
* Returns a File that refers to the recording's transcript file.
*
* @return The transcript file of the recording.
*/
public File getTranscriptFile() {
File f = new File(getRecordingsPath(), getGroupId() + "/"
+ getTranscriptId() + ".txt");
if(f.exists())
return f;
else
return null;
}
/**
* Returns a File that refers to the recording's preview file.
*
* @return The preview(sample) file of the recording.
*/
public File getPreviewFile() {
File f = new File(getRecordingsPath(), getGroupId() + "/"
+ getPreviewId() + ".wav");
if(f.exists())
return f;
else
return null;
}
/**
* Returns a File that refers to the respeaking's mapping file.
*
* @return The mapping file of the respeaking.
*/
public File getMapFile() {
if(isOriginal())
return null;
return new File(getRecordingsPath(), getGroupId() + "/" +
id + MAPPING_SUFFIX);
}
public String getMapId() {
return (id + MAPPING_SUFFIX.substring(0, MAPPING_SUFFIX.lastIndexOf('.')));
}
public String getPreviewId() {
return (id + SAMPLE_SUFFIX.substring(0, SAMPLE_SUFFIX.lastIndexOf('.')));
}
public String getTranscriptId() {
return (getGroupId() + "-" + getOwnerId() +
TRANSCRIPT_SUFFIX.substring(0, TRANSCRIPT_SUFFIX.lastIndexOf('.')));
}
/**
* Returns an identifier used in cloud-storage
* @return a relative-path of recording to 'aikuma/'
*/
public String getCloudIdentifier() {
String ownerIdDirName = IdUtils.getOwnerDirName(ownerId);
String ownerDirStr = (versionName + "/" +
ownerIdDirName.substring(0, 1) + "/" +
ownerIdDirName.substring(0, 2) + "/" + ownerId + "/");
String extension = (this.isMovie())? ".mp4" : ".wav";
return (ownerDirStr + PATH + getGroupId() + "/" + id + extension);
}
/**
* Name accessor; returns an empty string if the name is null
*
* @return The name of the recording.
*/
public String getName() {
if (name != null) {
return name;
} else {
return "";
}
}
public Date getDate() {
return date;
}
public List<Language> getLanguages() {
return languages;
}
/**
* Returns the first language code as a string, or an empty string if there
* is none.
*
* @return The language code of the first language associated with the
* recording.
*/
public String getFirstLangCode() {
if (getLanguages().size() > 0) {
return getLanguages().get(0).getCode();
} else {
return "";
}
}
/**
* Returns the name and language of the recording in a single string.
*
* @return The name and langugage of the recording in a string.
*/
public String getNameAndLang() {
if (getFirstLangCode().equals("")) {
return getName();
} else {
return getName() + " (" + getFirstLangCode() + ")";
}
}
/**
* speakersIds accessor.
*
* @return A list of IDs representing the speakers of the recording.
*/
public List<String> getSpeakersIds() {
return speakersIds;
}
/**
* speakers' file-models accessor.
* @return a list of File-model instances of the recording's speakers
*/
public List<FileModel> getSpeakers() {
List<FileModel> speakers = new ArrayList<FileModel>();
for(String speakerId : speakersIds) {
speakers.add(new FileModel(this.versionName, this.ownerId, speakerId, "speaker", "jpg"));
}
return speakers;
}
/**
* Returns true if the Recording has at least one language; false otherwise.
*
* @return true if the Recording has at least one language; false otherwise.
*/
public boolean hasALanguage() {
if (this.languages.size() == 0) {
return false;
}
return true;
}
/**
* Returns true if the recording is a movie file
* (Currently movie file is only stored with .mp4 extension
*
* @return true if this is a movie
*/
public boolean isMovie() {
return this.format.equals("mp4");
}
/**
* androidID accessor
*
* @return The Andorid of the device that made the recording.
*/
public String getAndroidID() {
return androidID;
}
/**
* groupId accessor.
*
* @return The Id of the group this recording belongs in.
* of.
*/
public String getGroupId() {
return groupId;
}
public String getRespeakingId() {
return respeakingId;
}
/**
* sampleRate accessor
*
* @return The sample rate of the recording as a long.
*/
public long getSampleRate() {
return sampleRate;
}
/**
* durationMsec accessor
*
* @return The duration of the recording in milliseconds as an int.
*/
public int getDurationMsec() {
return durationMsec;
}
/**
* Encode the Recording as a corresponding JSONObject.
*
* @return A JSONObject instance representing the Recording;
*/
public JSONObject encode() {
JSONObject encodedRecording = new JSONObject();
encodedRecording.put("name", this.name);
encodedRecording.put("date", new StandardDateFormat().format(this.date));
encodedRecording.put("version", this.versionName);
encodedRecording.put("user_id", this.ownerId);
encodedRecording.put("languages", Language.encodeList(languages));
JSONArray speakersIdsArray = new JSONArray();
for (String id : speakersIds) {
speakersIdsArray.add(id.toString());
}
encodedRecording.put("speakers", speakersIdsArray);
encodedRecording.put("device", deviceName);
encodedRecording.put("androidID", this.androidID);
encodedRecording.put("sampleRate", getSampleRate());
encodedRecording.put("durationMsec", getDurationMsec());
encodedRecording.put("item_id", this.groupId);
encodedRecording.put("suffix", this.respeakingId);
encodedRecording.put("source", this.sourceVerId);
if(latitude != null && longitude != null) {
JSONArray locationData = new JSONArray();
locationData.add(latitude);
locationData.add(longitude);
encodedRecording.put("location", locationData);
} else {
encodedRecording.put("location", null);
}
encodedRecording.put("file_type", getFileType());
encodedRecording.put("Format", this.format);
encodedRecording.put("BitsPerSample", this.bitsPerSample);
encodedRecording.put("NumChannels", this.numChannels);
return encodedRecording;
}
/**
* Make an index-file at the application root path
*
* @param srcVerId (source's versionName)-(source's ID)
* @param respkVerId (respeaking's versionName)-(respeaking's ID)
* @throws IOException thrown by read/write function
*/
private static void index(String srcVerId, String respkVerId) throws IOException {
File indexFile = new File(FileIO.getAppRootPath(), "index.json");
JSONObject indices = null;
try {
indices = FileIO.readJSONObject(indexFile);
} catch (IOException e) {
indices = new JSONObject();
}
String srcId = srcVerId.substring(4);
String[] splitRespeakName = respkVerId.split("-");
String val = splitRespeakName[0] + "-" + splitRespeakName[1] + "-" + splitRespeakName[2];
JSONArray values = (JSONArray) indices.get(srcId);
if(values == null) {
values = new JSONArray();
}
if(!values.contains(val)) {
values.add(val);
indices.put(srcId, values);
FileIO.writeJSONObject(indexFile, indices);
}
}
/**
* Write the recording's metadata string to path
*
* @param path Path to a file of the metadata
* @param metadataJSONStr JSON string of metadata
* @throws IOException thrown by write/index functions
*/
public static void write(File path, String metadataJSONStr) throws IOException {
FileIO.write(path, metadataJSONStr);
JSONParser parser = new JSONParser();
JSONObject jsonObj;
try {
jsonObj = (JSONObject) parser.parse(metadataJSONStr);
} catch (org.json.simple.parser.ParseException e) {
throw new IOException(e);
}
String jsonSrcVerId = (String) jsonObj.get("source");
// if the recording is a respeaking.
if(jsonSrcVerId != null) {
String jsonVerName = (String) jsonObj.get("version");
String jsonGroupId = (String) jsonObj.get("item_id");
String jsonOwnerId = (String) jsonObj.get("user_id");
// Write the index file
index(jsonSrcVerId, jsonVerName + "-" + jsonGroupId + "-" + jsonOwnerId);
}
}
/**
* Write the Recording to file in a subdirectory of the recordings and move
* the recording WAV data to that directory
*
* @throws IOException If the recording metadata could not be written.
*/
public void write() throws IOException {
// Ensure the directory exists
File dir = new File(getRecordingsPath(), getGroupId());
dir.mkdir();
Log.i(TAG, "write: " + dir.getAbsolutePath());
// Import the wave file into the new recording directory.
if(this.isMovie()) {
importMov(recordingUUID, getId());
} else {
importWav(recordingUUID, getId());
}
// if the recording is original
if (isOriginal()) {
// Import the sample wave file into the new recording directory
importWav(recordingUUID + SAMPLE_SUFFIX, getId() + SAMPLE_SUFFIX);
} else {
// Try and import the mapping file
importMapping(recordingUUID, getId());
// Write the index file
index(sourceVerId, getVersionName() + "-" + getId());
}
JSONObject encodedRecording = this.encode();
// Write the json metadata.
FileIO.writeJSONObject(new File(
getRecordingsPath(), getGroupId() + "/" +
id + METADATA_SUFFIX),
encodedRecording);
}
/**
* Deletes the JSON File associated with the recording.
*
* @return true if successful; false otherwise.
*/
/*
public boolean delete() {
File file = new File(getRecordingsPath(), this.getUUID().toString() +
".json");
if (!isOriginal()) {
File mapFile = new File(getRecordingsPath(),
this.getUUID().toString() + ".map");
boolean result;
result = mapFile.delete();
if (!result) {
return false;
}
}
return file.delete();
}
*/
/**
* Returns this recordings original.
*
* @return The original recording
* @throws IOException If there is an issue reading the originals JSON
* file
*/
public Recording getOriginal() throws IOException {
String[] splitSourceName = sourceVerId.split("-");
File ownerDir =
FileIO.getOwnerPath(splitSourceName[0], splitSourceName[2]);
File groupDir =
new File(getRecordingsPath(ownerDir), getGroupId());
// Filter for files that are source metadata
File[] groupMetadataFileArray = groupDir.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String filename) {
String[] splitFilename = filename.split("-");
if (splitFilename[2].equals("source") &&
filename.endsWith(METADATA_SUFFIX)) {
return true;
}
return false;
}
});
assertTrue(groupMetadataFileArray.length == 1);
return Recording.read(groupMetadataFileArray[0]);
}
/**
* Read a recording corresponding to the given filename prefix.
*
* @param verName The recording's versionName
* @param ownerAccount The recording's ownerID
* @param id The recording's ID
* @return A Recording object corresponding to the json file.
* @throws IOException If the recording metadata cannot be read.
*/
public static Recording read(String verName, String ownerAccount,
String id) throws IOException {
String groupId = getGroupIdFromId(id);
File ownerDir = FileIO.getOwnerPath(verName, ownerAccount);
File metadataFile =
new File(getRecordingsPath(ownerDir),
groupId + "/" + id + METADATA_SUFFIX);
Log.i(TAG, metadataFile.getAbsolutePath());
return read(metadataFile);
}
/**
* Read a recording from the file containing JSON describing the Recording
*
* @param metadataFile The file containing the metadata of the recording.
* @return A Recording object corresponding to the json file.
* @throws IOException If the recording metadata cannot be read.
*/
public static Recording read(File metadataFile) throws IOException {
JSONObject jsonObj = FileIO.readJSONObject(metadataFile);
return read(jsonObj);
}
/**
* Read a recording from JSON object describing the Recording
*
* @param jsonObj JSON Object containing the metadata of the recording.
* @return A Recording object corresponding to the json object.
* @throws IOException If the recording metadata doesn't exist.
*/
public static Recording read(JSONObject jsonObj) throws IOException {
String groupId = (String) jsonObj.get("item_id");
if (groupId == null) {
throw new IOException("Null groupId in the JSON file.");
}
String name = (String) jsonObj.get("name");
String dateString = (String) jsonObj.get("date");
if (dateString == null) {
throw new IOException("Null date in the JSON file.");
}
Date date;
try {
date = new StandardDateFormat().parse(dateString);
} catch (ParseException e) {
throw new IOException(e);
}
String versionName = (String) jsonObj.get("version");
String ownerId = (String) jsonObj.get("user_id");
String sourceVerId = (String) jsonObj.get("source");
String format = (String) jsonObj.get("Format");
String fileType = (String) jsonObj.get("file_type");
JSONArray languageArray = (JSONArray) jsonObj.get("languages");
if (languageArray == null) {
throw new IOException("Null languages in the JSON file.");
}
List<Language> languages = Language.decodeJSONArray(languageArray);
JSONArray speakerIdArray = (JSONArray) jsonObj.get("speakers");
if (speakerIdArray == null) {
throw new IOException("Null speakersIds in the JSON file.");
}
List<String> speakersIds = Speaker.decodeJSONArray(speakerIdArray);
String androidID = (String) jsonObj.get("androidID");
if (androidID == null) {
throw new IOException("Null androidID in the JSON file.");
}
String respeakingId = (String) jsonObj.get("suffix");
if (respeakingId == null) {
throw new IOException("Null respeakingId in the JSON file.");
}
long sampleRate;
if (jsonObj.get("sampleRate") == null) {
sampleRate = -1;
} else {
sampleRate = (Long) jsonObj.get("sampleRate");
}
int durationMsec;
if (jsonObj.get("durationMsec") == null) {
durationMsec = -1;
Log.i(TAG, "reading: null");
} else {
durationMsec = ((Long) jsonObj.get("durationMsec")).intValue();
Log.i(TAG, "reading: " + durationMsec);
}
Recording recording = new Recording(name, date, versionName, ownerId,
sourceVerId, languages, speakersIds, androidID, groupId,
respeakingId, sampleRate, (Integer) durationMsec, format, fileType);
return recording;
}
/**
* Returns a list of all the respeakings of this Recording. Ff it is a
* respeaking it will return an list of the other respeakings in the
* group.
* (If this is called by a respeaking, empty arraylist is returned)
*
* @return A list of all the respeakings of the recording.
* (an error can return an empty list)
*/
public List<Recording> getRespeakings() {
List<File> groupDirList = new ArrayList<File>();
List<Recording> respeakings = new ArrayList<Recording>();
if(!this.isOriginal()) return respeakings;
File indexFile = new File(FileIO.getAppRootPath(), "index.json");
JSONObject indices = null;
try {
indices = FileIO.readJSONObject(indexFile);
} catch (IOException e1) {
// TODO: How to deal with no index-file?
Log.e(TAG, "getRespeakings(): error in reading index file");
indices = new JSONObject();
//return respeakings;
}
// Collect directories where related respeakings exist form index file
JSONArray respkList = (JSONArray) indices.get(getId());
if(respkList == null) {
// TODO: How to deal with no index-file?
respkList = new JSONArray();
//return respeakings;
}
for (int i = 0; i < respkList.size(); i++) {
String[] splitRespkName = ((String)respkList.get(i)).split("-");
File ownerDir =
FileIO.getOwnerPath(splitRespkName[0], splitRespkName[2]);
File groupDir =
new File(getRecordingsPath(ownerDir), splitRespkName[1]);
groupDirList.add(groupDir);
}
// For the respeakings existing in the same folder of original
File currentDir = new File(getRecordingsPath(), getGroupId());
if(!groupDirList.contains(currentDir)) {
groupDirList.add(currentDir);
}
// Read metadata files
for(File groupDir: groupDirList) {
File[] groupDirMetaFiles = groupDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(METADATA_SUFFIX);
}
});
if(groupDirMetaFiles != null) {
Recording recording;
for (File recordingMetaFile : groupDirMetaFiles) {
try {
recording = Recording.read(recordingMetaFile);
if (!recording.isOriginal()) {
respeakings.add(recording);
}
} catch (IOException e) {
// Well we can't read the recordings metadata file, so just
// continue on.
}
}
}
}
return respeakings;
}
/**
* Read all recordings
*
* @return A list of all the recordings in the Aikuma directory.
*/
public static List<Recording> readAll() {
return readAll(null);
}
/**
* Read all recordings of the user
*
* @param userId The user's ID
* @return A list of all the user's recordings in the Aikuma directory.
*/
public static List<Recording> readAll(String userId) {
List<Recording> recordings = new ArrayList<Recording>();
// Get a list of version directories
File[] versionDirs =
FileIO.getAppRootPath().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith("v") && filename.substring(1).matches("\\d+");
}
});
for(File f1 : versionDirs) {
File[] firstHashDirs = f1.listFiles();
for(File f2 : firstHashDirs) {
File[] secondHashDirs = f2.listFiles();
for(File f3 : secondHashDirs) {
File[] ownerIdDirs = f3.listFiles();
for(File f : ownerIdDirs) {
if(userId == null || f.getName().equals(userId)) {
Log.i(TAG, "readAll: " + f.getPath());
addRecordingsInDir(recordings, f);
}
}
}
}
}
return recordings;
}
private static void addRecordingsInDir(List<Recording> recordings, File dir) {
// Constructs a list of directories in the recordings directory.
File[] recordingPathFiles = getRecordingsPath(dir).listFiles();
if (recordingPathFiles == null) {
return;
}
for (File f : recordingPathFiles) {
if (f.isDirectory()) {
// For each of those subdirectories, creates a list of files
// within that end in .json
File[] groupDirFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(METADATA_SUFFIX);
}
});
// Iterate over those recording metadata files and add the
// recordings they refer to to the recordings list
for (File jsonFile : groupDirFiles) {
try {
Recording rec = Recording.read(jsonFile);
recordings.add(rec);
} catch (IOException e) {
// Couldn't read that recording for whateve rreason
// (perhaps json file wasn't formatted correctly).
// Let's just ignore that user.
Log.e(TAG, "read exception(" + e.getMessage() + "): " + jsonFile.getName());
}
}
}
}
}
/**
* Index all recordings and create a index file
*
* @throws IOException while writing a index file
*/
public static void indexAll() throws IOException {
File indexFile = new File(FileIO.getAppRootPath(), "index.json");
JSONObject indices = new JSONObject();
List<String> originals = new ArrayList<String>();
JSONObject itemDirPaths = new JSONObject();
// Get a list of version directories
File[] versionDirs =
FileIO.getAppRootPath().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith("v") && filename.substring(1).matches("\\d+");
}
});
for(File f1 : versionDirs) {
File[] firstHashDirs = f1.listFiles();
for(File f2 : firstHashDirs) {
File[] secondHashDirs = f2.listFiles();
for(File f3 : secondHashDirs) {
File[] ownerIdDirs = f3.listFiles();
for(File f4 : ownerIdDirs) {
Log.i(TAG, "indexAll: " + f4.getPath());
File[] itemDirs = getRecordingsPath(f4).listFiles();
for(File f5 : itemDirs) {
if (f5.isDirectory()) {
// Record the path to this item folder
String itemName = f5.getName();
JSONArray values = (JSONArray) itemDirPaths.get(itemName);
String val = f1.getName() + "-" + itemName + "-" + f4.getName();
if(values == null) {
values = new JSONArray();
}
if(!values.contains(val)) {
values.add(val);
itemDirPaths.put(f5.getName(), values);
}
// Record the original
File[] files = f5.listFiles();
for(File f : files) {
String fileName = f.getName();
String srcId = fileName.substring(0, fileName.lastIndexOf('.'));
if(srcId.endsWith("source")) {
// At most one source file can exist in one item folder
if(!originals.contains(srcId))
originals.add(srcId);
break;
}
}
}
}
}
}
}
}
for(String srcId : originals) {
String itemId = srcId.split("-")[0];
indices.put(srcId, itemDirPaths.get(itemId));
}
FileIO.writeJSONObject(indexFile, indices);
}
/**
* Updates all recording metadata files of versionNum
* 1. Update or create fields existing in newJSONFields
* 2. After 1, Change field keys existing in newJSONKeys(oldkey -> newkey)
*
* @param versionNum obsolete file-format's version
* @param newJSONFields Map structure of new field-pairs(key:value)
* @param newJSONKeys Map structure of new key-pairs(oldkey:newkey)
*/
public static void updateAll(Integer versionNum,
Map<String, Object> newJSONFields, Map<String, String> newJSONKeys) {
if(newJSONFields == null && newJSONKeys == null)
return;
switch(versionNum) {
case 0:
File[] firstHashDirs = new File(FileIO.getAppRootPath(), "v01").listFiles();
for(File f2 : firstHashDirs) {
File[] secondHashDirs = f2.listFiles();
for(File f3 : secondHashDirs) {
File[] ownerIdDirs = f3.listFiles();
for(File f : ownerIdDirs) {
Log.i(TAG, "updateAll: " + f.getPath());
updateMetadataInDir(f, newJSONFields, newJSONKeys);
}
}
}
return;
}
}
private static void updateMetadataInDir(File dir,
Map<String, Object> newJSONFields, Map<String, String> newJSONKeys) {
boolean isFields = (newJSONFields != null);
boolean isKeys = (newJSONKeys != null);
// Constructs a list of directories in the recordings directory.
File[] recordingPathFiles = getRecordingsPath(dir).listFiles();
if (recordingPathFiles == null) {
return;
}
for (File f : recordingPathFiles) {
if (f.isDirectory()) {
// For each of those subdirectories, creates a list of files
// within that end in .json
File[] groupDirFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(METADATA_SUFFIX);
}
});
// Iterate over those recording metadata files and add the
// recordings they refer to to the recordings list
for (File jsonFile : groupDirFiles) {
try {
JSONObject newJSONObject =
FileIO.readJSONObject(jsonFile);
if(isFields) {
newJSONObject.putAll(newJSONFields);
}
if(isKeys) {
for(String oldKey : newJSONKeys.keySet()) {
Object val = newJSONObject.remove(oldKey);
if(val != null) {
String newKey = newJSONKeys.get(oldKey);
newJSONObject.put(newKey, val);
}
}
}
FileIO.writeJSONObject(jsonFile, newJSONObject);
} catch (IOException e) {
Log.e(TAG, "Metadata update failed: " + e.toString());
}
}
}
}
}
/**
* Compares the given object with the Recording, and returns true if the
* Recording's name, date, languages, androidID, groupId and
* respeakingId are equal
*
* @param obj The object to be compared.
* @return true most fields are the same; false otherwise
*/
public boolean equals(Object obj) {
if (obj == null) {return false;}
if (obj == this) {return true;}
if (obj.getClass() != getClass()) {return false;}
Recording rhs = (Recording) obj;
return new EqualsBuilder()
.append(name, rhs.name)
.append(date, rhs.date)
.append(languages, rhs.languages)
.append(speakersIds, rhs.speakersIds)
.append(androidID, rhs.androidID)
.append(groupId, rhs.groupId)
.append(respeakingId, rhs.respeakingId)
.append(sampleRate, rhs.sampleRate)
.isEquals();
}
/**
* Name mutator.
*/
private void setName(String name) {
this.name = name;
}
// Sets the date; the date cannot be null.
private void setDate(Date date) {
if (date == null) {
throw new IllegalArgumentException(
"Recording date cannot be null.");
}
this.date = date;
}
// Sets the file-type
private void setFileType(String sourceVerId, List<Language> languages) {
if (sourceVerId == null) {
this.fileType = "source";
} else {
// Then this is either a respeaking or a translation.
try {
if (languages.equals(getOriginal().getLanguages())) {
this.fileType = "respeaking";
} else {
this.fileType = "translation";
}
} catch (IOException e) {
// There is an issue reading the original. A type won't be
// written.
}
}
}
// Sets the languages
private void setLanguages(List<Language> languages) {
if (languages == null) {
throw new IllegalArgumentException(
"Recording languages cannot be null. " +
"Set as an empty List<Language> instead.");
}
this.languages = languages;
}
/**
* Add's another language to the Recording's language list
*
* @param language The language to be added to the Recording's list of
* languages.
*/
private void addLanguage(Language language) {
if (language == null) {
throw new IllegalArgumentException(
"A language for the recording cannot be null");
}
this.languages.add(language);
}
// Sets the speakers Ids, but won't accept a null list (empty lists are
// fine).
private void setSpeakersIds(List<String> speakersIds) {
if (speakersIds == null) {
throw new IllegalArgumentException(
"Recording speakersIds cannot be null. " +
"Set as an empty List<String> instead.");
}
this.speakersIds = speakersIds;
}
/**
* Add's another speaker to the Recording's speaker list
*
* @param speaker The speaker to be added to the Recording's list of
* speaker.
*/
private void addSpeakerId(Speaker speaker) {
if (speaker == null) {
throw new IllegalArgumentException(
"A speaker for the recording cannot be null");
}
this.speakersIds.add(speaker.getId());
}
private void setDeviceName(String deviceName) {
if (deviceName == null) {
throw new IllegalArgumentException(
"The model name cannot be null");
}
this.deviceName = deviceName.toUpperCase();
}
// Sets the android ID but won't accept a null string.
private void setAndroidID(String androidID) {
if (androidID == null) {
throw new IllegalArgumentException(
"The androidID for the recording cannot be null");
}
this.androidID = androidID;
}
private void setGroupId(String groupId) {
this.groupId = groupId;
}
private void setId(String id) {
this.id = id;
}
private void setSampleRate(long sampleRate) {
this.sampleRate = sampleRate;
}
private void setRespeakingId(String respeakingId) {
this.respeakingId = respeakingId;
}
private void setDurationMsec(int durationMsec) {
this.durationMsec = durationMsec;
}
/**
* Get the applications recordings directory
*
* @param ownerDir A File representing the path of owner's directory
* @return A File representing the path of the recordings directory
*/
public static File getRecordingsPath(File ownerDir) {
File path = new File(ownerDir, PATH);
path.mkdirs();
return path;
}
/**
* Get the recording owner's directory
*
* @return A file representing the path of the recording owner's dir
*/
public File getRecordingsPath() {
File path = new File(
FileIO.getOwnerPath(versionName, ownerId), PATH);
path.mkdirs();
return path;
}
/**
* Get the applications recording directory that isn't synced.
*
* @return A File representing the path of the recordings directory in the
* no-sync Aikuma directory.
*/
public static File getNoSyncRecordingsPath() {
File path = new File(FileIO.getNoSyncPath(), PATH);
path.mkdirs();
return path;
}
/**
* Returns the groupId given an id
*
* @param id The filename prefix of the file whose
* groupId we seek
* @return The corresponding group ID.
*/
public static String getGroupIdFromId(String id) {
String[] splitId = id.split("-");
assertTrue(splitId.length >= 3);
return splitId[0];
}
/**
* Star the recording with this phone's androidID
*
* @param currentVerName Current aikuma's version
* @param userId ID of an user who liked this recording
* @throws IOException In case there is an issue writing the star file.
* Note that this will not be thrown if the file already exists.
*/
public void star(String currentVerName, String userId) throws IOException {
String androidID = Aikuma.getAndroidID();
File starFile = new File(FileIO.getOwnerPath(currentVerName, userId),
"/social/" + getId() + "-like");
starFile.getParentFile().mkdirs();
starFile.createNewFile();
}
/**
* Flag the recording with this phone's androidID
*
* @param currentVerName Current aikuma's version
* @param userId ID of an user who dis-liked this recording
* @throws IOException In case there is an issue writing the flag file.
* Note that this will not be thrown if the file already exists.
*/
public void flag(String currentVerName, String userId) throws IOException {
String androidID = Aikuma.getAndroidID();
File flagFile = new File(FileIO.getOwnerPath(currentVerName, userId),
"/social/" + getId() + "-report");
flagFile.getParentFile().mkdirs();
flagFile.createNewFile();
}
/**
* Make the archived recording's metadata
* @param backupDate when upload finished
* @param downloadUrl url where the recording file can be downloaded
* @throws IOException In case of an issue writing the archiveMetadata file.
* Note that this will not be thrown if the file already exists.
*/
public void archive(String backupDate, String downloadUrl) throws IOException {
JSONObject archiveMetadata = new JSONObject();
archiveMetadata.put("name", this.name);
archiveMetadata.put("recording", this.groupId);
archiveMetadata.put("backupDate", backupDate);
archiveMetadata.put("download_url", downloadUrl);
FileIO.writeJSONObject(new File(getRecordingsPath(),
getGroupId() + "/" + id + "-archive.json"),
archiveMetadata);
}
/**
* Tells us whether this phone has already starred the Recording
*
* @param currentVerName Current aikuma's version
* @param userId ID of an user who liked this recording
* @return true if a star file with this androidID is present; false
* otherwise
*/
public boolean isStarredByThisPhone(String currentVerName, String userId) {
String androidID = Aikuma.getAndroidID();
File starFile =
new File(FileIO.getOwnerPath(currentVerName, userId), "/social/" +
getId() + "-like");
return starFile.exists();
}
/**
* Tells us whether this phone has already flagged the Recording
*
* @param currentVerName Current aikuma's version
* @param userId ID of an user who dis-liked this recording
* @return true if a flag file with this androidID is present; false
* otherwise
*/
public boolean isFlaggedByThisPhone(String currentVerName, String userId) {
String androidID = Aikuma.getAndroidID();
File flagFile =
new File(FileIO.getOwnerPath(currentVerName, userId), "/social/" +
getId() + "-report");
return flagFile.exists();
}
/**
* Tells us whether this recording has been archived
*
* @return true if a archiveMetadata file is present; false otherwise
*/
public boolean isArchived() {
File archiveMetaFile = new File(getRecordingsPath(),
getGroupId() + "/" + getId() + "-archive.json");
return archiveMetaFile.exists();
}
/**
* Gives the number of stars this recording has received.
*
* @return The number of stars this recording has recieved
*/
public int numStars() {
// TODO: New file-storage model needs to be decided (1. create index / 2. put these in app-root folder)
File starDir = new File(FileIO.getOwnerPath(versionName, ownerId),
"/social/" +
getGroupId() + "/" + getId());
File[] starFiles = starDir.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String filename) {
if (filename.endsWith(".star")) {
return true;
}
return false;
}
});
if (starFiles == null) {
return 0;
}
return starFiles.length;
}
/**
* Gives the number of flags this recording has received.
*
* @return The number of flags this recording has recieved
*/
public int numFlags() {
// TODO: New file-storage model needs to be decided (1. create index / 2. put these in app-root folder)
File socialDir = new File(FileIO.getOwnerPath(versionName, ownerId),
"/social/" +
getGroupId() + "/" + getId());
File[] flagFiles = socialDir.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String filename) {
if (filename.endsWith(".flag")) {
return true;
}
return false;
}
});
if (flagFiles == null) {
return 0;
}
return flagFiles.length;
}
/**
* Gives the number of times this recording has been views.
*
* @return The number of times this recording has been viewed.
*/
public int numViews() {
//TODO: New file-storage model for the number of views need to be decided
File socialDir = new File(FileIO.getOwnerPath(versionName, ownerId),
"/views/" +
getGroupId() + "/" + getId());
File[] flagFiles = socialDir.listFiles();
if (flagFiles == null) {
return 0;
}
return flagFiles.length;
}
/**
* Indicates that this recording is allowed to be synced by moving it to a
* directory that the SyncUtil synchronizes.
*
* @return A transcript of this recording
* @param id The ID of the recording to sync.
* @throws IOException If it cannot be moved to the synced directory.
*/
/*
public static void enableSync(String id) throws IOException {
File wavFile = new File(getNoSyncRecordingsPath(), uuid + ".wav");
FileUtils.moveFileToDirectory(wavFile, getRecordingsPath(), false);
}
*/
/**
* Returns the transcript for this recording, or an empty transcript.
*
* @return A transcript of this recording
*/
public TempTranscript getTranscript() {
// Find all the transcript files
File recordingDir = new File(getRecordingsPath(), getGroupId());
File[] transcriptFiles = recordingDir.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String filename) {
if (filename.split("-")[2].equals("transcript")) {
Log.i(TAG, "filename: " + filename);
Log.i(TAG, "split[2]: " +
filename.split("-")[2]);
return true;
}
return false;
}
});
if(transcriptFiles == null)
return null;
// Take the first one
for (File transcriptFile : transcriptFiles) {
Log.i(TAG, "transcriptFile: " + transcriptFile);
try {
return new TempTranscript(this, transcriptFile);
} catch (IOException e) {
continue;
}
}
// Just return an empty transcript
// return new TempTranscript();
return null;
}
@Override
public int describeContents() {
return 0;
}
/**
* Creates a Parcel object representing the Recording.
*
* @param out The parcel to be written to
* @param _flags Unused additional flags about how the object should be
* written.
*/
public void writeToParcel(Parcel out, int _flags) {
//TODO: IF needed later
}
/**
* The recording's name.
*/
private String name;
/**
* The recording's date.
*/
private Date date;
/**
* The languages of the recording.
*/
private List<Language> languages;
/**
* The speakers of the recording.
*/
private List<String> speakersIds;
/**
* The device model name
*/
private String deviceName;
/**
* The Android ID of the device that the recording was made on.
*/
private String androidID;
/**
* The ID that represents the group of recordings.
*/
private String groupId;
/**
* The sample rate of the recording in Hz
*/
private long sampleRate;
/**
* The duration of the recording in seconds (floored)
*/
private int durationMsec;
// The UUID of the source WAV.
private UUID recordingUUID;
// The respeaking ID that is at the end of the filename prefix.
private String respeakingId;
// The ID of a recording, which is of one of the following structures:
// (inherited from super-class)
// <groupId>-<ownerId>-source (for originals)
// <groupId>-<ownerId>-<respeaking type>-<respeakingId> (for
// respeakings, transcriptions, commentaries, etc.)
// private String id;
//The ID of the source recording.
private String sourceVerId;
// Some info regarding the recording format.
//private String format;
private int bitsPerSample;
private int numChannels;
//Location data
private Double latitude;
private Double longitude;
/**
* Relative path where recording files are stored
*/
public static final String PATH = "items/";
} |
package com.docusign.esignature;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.xml.sax.InputSource;
import com.docusign.esignature.json.Document;
import com.docusign.esignature.json.EnvelopeInformation;
import com.docusign.esignature.json.LoginAccount;
import com.docusign.esignature.json.LoginResult;
import com.docusign.esignature.json.RecipientInformation;
import com.docusign.esignature.json.RequestSignatureFromDocuments;
import com.docusign.esignature.json.RequestSignatureFromTemplate;
import com.docusign.esignature.json.RequestSignatureResponse;
import com.docusign.esignature.json.StatusInformation;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DocuSignClient {
private String email;
private String password;
private List<LoginAccount> loginAccounts = new ArrayList<LoginAccount>();
private String accountId;
private String integratorKey;
// this defaults to demo,
private String serverUrl = "https://demo.docusign.net";
private String baseUrl = "";
private String lastResponse;
private String lastRequest;
private String lastError;
private String accessToken;
// constructors
public DocuSignClient(String email, String password, String integratorKey) {
this.email = email;
this.password = password;
this.integratorKey = integratorKey;
}
public DocuSignClient(String email, String password, String accountId, String integratorKey) {
this.email = email;
this.password = password;
this.accountId = accountId;
this.integratorKey = integratorKey;
}
public DocuSignClient(String integratorKey) {
this(integratorKey, null);
}
public DocuSignClient(String integratorKey, String accessToken) {
this.integratorKey = integratorKey;
this.accessToken = accessToken;
}
/**
* login will set the baseUrl and accountId to the default account.
* you can retrieve logged in accounts and use other accounts if you wish.
* @throws IOException
* @throws MalformedURLException
*/
public boolean login() throws MalformedURLException, IOException {
String loginUrl = serverUrl + "/restapi/v2/login_information";
HttpURLConnection conn = null;
try {
conn = getRestConnection(loginUrl);
int status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return false;
}
BufferedInputStream bufferStream = extractAndSaveOutput(conn);
ObjectMapper mapper = new ObjectMapper();
LoginResult loginResult = mapper.readValue( bufferStream, LoginResult.class );
loginAccounts = loginResult.getLoginAccounts();
// NOTE: there should never be a time when we get a positive result and less than one account.
accountId = loginAccounts.get(0).getAccountId();
baseUrl = loginAccounts.get(0).getBaseUrl();
}
finally
{
if( conn != null )
conn.disconnect();
}
return true;
}
/**
* this is the easiest way to send documents for signature. It allows you to
* set up the signature workflow in DocuSign through WYSIWYG way -
* just log into DocuSign, create a template and remember the role name
* and the template ID. Once you have that you can use this function
* @param request
* @return envelopeId string if successful, empty string if not.
* @throws MalformedURLException
* @throws IOException
*/
public String requestSignatureFromTemplate( RequestSignatureFromTemplate request ) throws MalformedURLException, IOException {
HttpURLConnection conn = null;
try
{
// append "/envelopes" to the baseUrl and use in the request
conn = getRestConnection(baseUrl + "/envelopes");
ObjectMapper mapper = new ObjectMapper();
lastRequest = mapper.writeValueAsString(request);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(lastRequest.length()));
// Write body of the POST request
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(lastRequest); dos.flush(); dos.close();
int status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return "";
}
// Read the response
RequestSignatureResponse response = mapper.readValue(conn.getInputStream(), RequestSignatureResponse.class);
return response.getEnvelopeId();
}
finally
{
if( conn != null )
conn.disconnect();
}
}
public String requestSignatureFromDocuments(RequestSignatureFromDocuments request, InputStream[] stream)
throws MalformedURLException, IOException {
// TODO: lastRequest is not properly logged here
if( stream == null || stream.length == 0 )
throw new IllegalArgumentException("You need to pass in at least one file");
if( stream.length != request.getDocuments().size() )
throw new IllegalArgumentException("The number of file bytes should be equal to the number of documents in the request. Got " + stream.length + " byte arrays, and " + request.getDocuments().size() + " file definitions.");
HttpURLConnection conn = null;
try {
// append "/envelopes" to the baseUrl and use in the request
conn = getRestConnection(baseUrl + "/envelopes");
ObjectMapper mapper = new ObjectMapper();
String jsonBody = mapper.writeValueAsString(request);
String startRequest = "\r\n\r\n--BOUNDARY\r\n" +
"Content-Type: application/json\r\n" +
"Content-Disposition: form-data\r\n" +
"\r\n" + jsonBody;
// we break this up into two string since the PDF doc bytes go here and are not in string format.
// see further below where we write to the outputstream...
String endBoundary = "\r\n" + "--BOUNDARY--\r\n\r\n";
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=BOUNDARY");
// write the body of the request...
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(startRequest.toString());
for( int i = 0; i < stream.length; ++i) {
Document next = request.getDocuments().get(i);
String contentType = next.getContentType();
if(contentType == null){
contentType = "application/pdf";
}
String boundary = "\r\n--BOUNDARY\r\n" + // opening boundary for next document
"Content-Type: " + contentType + "\r\n" +
"Content-Disposition: file; filename=\"" + next.getName() + "\"; documentId=" + next.getDocumentId() + "\r\n" +
"\r\n";
dos.writeBytes(boundary);
byte[] buffer = new byte[1024];
int len;
while ((len = stream[i].read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
}
dos.writeBytes(endBoundary);
dos.flush();
dos.close();
int status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return "";
}
// Read the response
RequestSignatureResponse response = mapper.readValue(conn.getInputStream(), RequestSignatureResponse.class);
return response.getEnvelopeId();
}
finally
{
if( conn != null )
conn.disconnect();
}
}
public String reqeustSignatureFromDocuments(RequestSignatureFromDocuments request, File[] files) throws MalformedURLException, IOException
{
// Convert the files to input streams
List<InputStream> streams = new ArrayList<InputStream>();
for (int i=0; i<files.length; i++){
streams.add(new FileInputStream(files[i]));
}
return requestSignatureFromDocuments(request, streams.toArray(new InputStream[streams.size()]));
}
/**
* You can use this function after login() to get a URL with an authenticated view
* into DocuSign. It is useful for SSO-like functionality where your app
* authenticates DocuSign and then allows users to just get into their
* console with one click.
* @return URL to the authenticated DocuSign console.
* @throws IOException
*/
public String requestConsoleView() throws IOException {
HttpURLConnection conn = null;
// construct an outgoing xml request body
lastRequest = "<consoleViewRequest xmlns=\"http:
"<accountId>" + getAccountId() + "</accountId>" +
"</consoleViewRequest>";
// append "/views/console" to the baseUrl and use in the request
try {
conn = getRestConnection(getBaseUrl() + "/views/console");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("Content-Length", Integer.toString(lastRequest.length()));
// write the body of the request...
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(lastRequest); dos.flush(); dos.close();
int status = conn.getResponseCode();
if( status != 201 ) // 201 = Created
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return "";
}
// Read the response
String line;
InputStreamReader isr = new InputStreamReader( extractAndSaveOutput(conn) );
BufferedReader br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
/**
* Use this function to get an authenticated sending view. This is useful
* if you have document or recipient information in your application but
* you want your users to review or finish defining the workflow before the
* envelope is sent out.
* @param envelopeId identifies pre-created envelope
* @param returnUrl is where the user is going to be sent once they are done sending
* @return a URL to the authenticated sending session
* @throws MalformedURLException
* @throws IOException
*/
public String requestSendingView(String envelopeId, String returnUrl) throws MalformedURLException, IOException {
HttpURLConnection conn = null;
try
{
lastRequest = "{\"returnUrl\": \"" + returnUrl + "\"}";
conn = getRestConnection(getBaseUrl() + "/envelopes/" + envelopeId + "/views/sender");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(lastRequest.length()));
conn.setRequestProperty("Accept", "application/xml");
// write the body of the request...
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(lastRequest); dos.flush(); dos.close();
int status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return "";
}
// Read the response
String line;
InputStreamReader isr = new InputStreamReader( extractAndSaveOutput(conn) );
BufferedReader br = new BufferedReader(isr);
StringBuilder response3 = new StringBuilder();
while ( (line = br.readLine()) != null)
response3.append(line);
/**
* If you sent documents and defined one of the recipients as "embedded", meaning
* you will be in charge of presenting the signing to that person you can use this function
* to get the authenticated URL to present.
* @param envelopeId is the envelope that you have previously created
* @param userName of the recipient who is going to be presented with signing
* @param email of the recipient who is going to be presented with signing
* @param clientUserId is your internal ID of the recipient who is going to be presented with signing
* @param returnUrl is where the recipient is going to be sent once they are done signing
* @param authenticationMethod is a way for you to flag how you authenticated this session. This goes into the secure audit log.
* @return an authenticated URL that you can embedd in your application
* @throws MalformedURLException
* @throws IOException
*/
public String requestRecipientView(String envelopeId, String userName, String email, String clientUserId, String returnUrl, String authenticationMethod) throws MalformedURLException, IOException {
HttpURLConnection conn = null;
try
{
lastRequest = "{\"authenticationMethod\": \"" + authenticationMethod
+ "\",\"email\": \"" + email
+ "\",\"returnUrl\": \"" + returnUrl
+ "\",\"userName\": \"" + userName
+ "\",\"clientUserId\": \"" + clientUserId + "\"}";
conn = getRestConnection(getBaseUrl() + "/envelopes/" + envelopeId + "/views/recipient");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(lastRequest.length()));
conn.setRequestProperty("Accept", "application/xml");
// write the body of the request...
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(lastRequest); dos.flush(); dos.close();
int status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return "";
}
// Read the response
String line;
InputStreamReader isr = new InputStreamReader( extractAndSaveOutput(conn) );
BufferedReader br = new BufferedReader(isr);
StringBuilder response3 = new StringBuilder();
while ( (line = br.readLine()) != null)
response3.append(line);
/**
* a way to get status of all envelopes
* @param accountId
* @param fromDate
* @param fromToStatus
* @return
* @throws MalformedURLException
* @throws IOException
*/
public StatusInformation requestStatusInformation(Date fromDate, String fromToStatus) throws MalformedURLException, IOException {
String fromDateStr = new SimpleDateFormat("MM/dd/yyyy").format(fromDate);
String envelopeUrl = baseUrl + "/envelopes?from_date=" + URLEncoder.encode(fromDateStr, "UTF-8") + "&from_to_status=" + fromToStatus;
HttpURLConnection conn = null;
try {
conn = getRestConnection(envelopeUrl);
int status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return null;
}
BufferedInputStream bufferStream = extractAndSaveOutput(conn);
ObjectMapper mapper = new ObjectMapper();
StatusInformation statusInformation = mapper.readValue( bufferStream, StatusInformation.class );
return statusInformation;
}
finally
{
if( conn != null )
conn.disconnect();
}
}
/**
* a way to get envelope properties such as status, date signed and many more
* @param envelopeId is the identifier of the envelope you are interested in
* @return
* @throws MalformedURLException
* @throws IOException
*/
public EnvelopeInformation requestEnvelopeInformation(String envelopeId) throws MalformedURLException, IOException {
String envelopeUrl = baseUrl + "/envelopes/" + envelopeId;
HttpURLConnection conn = null;
try {
conn = getRestConnection(envelopeUrl);
int status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return null;
}
BufferedInputStream bufferStream = extractAndSaveOutput(conn);
ObjectMapper mapper = new ObjectMapper();
EnvelopeInformation envelopeInformation = mapper.readValue( bufferStream, EnvelopeInformation.class );
return envelopeInformation;
}
finally
{
if( conn != null )
conn.disconnect();
}
}
/**
* this function will get you a combined document of all the the files in an envelope that were sent out together
* @param envelopeId is the identifier of the envelope you'd like to get a copy of
* @param output stream that you can write out to a location of your choice
* @throws MalformedURLException
* @throws IOException
*/
public void requestCombinedDocument(String envelopeId, OutputStream stream ) throws MalformedURLException, IOException {
String envelopeUrl = baseUrl + "/envelopes/" + envelopeId + "/documents/combined";
HttpURLConnection conn = null;
try
{
conn = getRestConnection(envelopeUrl);
conn.setRequestProperty("Accept", "application/pdf");
int status = conn.getResponseCode();
if( status != 200 ) // 200 = OK
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
} else {
IOUtils.copy(conn.getInputStream(), stream);
}
}
finally
{
if( conn != null )
conn.disconnect();
}
}
/**
* call this function to get the status and information of the recipients
* in an envelope. You can get the information like whether or not they signed
* the envelope and also the data fields they sent out.
* @param envelopeId
* @return
* @throws MalformedURLException
* @throws IOException
*/
public RecipientInformation requestRecipientInformation(String envelopeId) throws MalformedURLException, IOException
{
String envelopeUrl = baseUrl + "/envelopes/" + envelopeId + "/recipients";
HttpURLConnection conn = null;
try
{
conn = getRestConnection(envelopeUrl);
int status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
String errorText = getErrorDetails(conn);
System.err.println("Error calling webservice, status is: " + status);
System.err.println("Error calling webservice, error message is: " + errorText );
return null;
}
BufferedInputStream bufferStream = extractAndSaveOutput(conn);
ObjectMapper mapper = new ObjectMapper();
RecipientInformation info = mapper.readValue( bufferStream, RecipientInformation.class );
return info;
}
finally
{
if( conn != null )
conn.disconnect();
}
}
/**
* you can call this function to get a HTTP connection
* which you can then use to make other REST calls that don't have wrappers in this class
* @param url
* @return
* @throws IOException
* @throws MalformedURLException
*/
public HttpURLConnection getRestConnection(String url) throws IOException, MalformedURLException {
HttpURLConnection conn;
conn = (HttpURLConnection)new URL(url).openConnection();
if(this.accessToken != null){
conn.setRequestProperty("Authorization", "bearer "+this.accessToken);
}else{
conn.setRequestProperty("X-DocuSign-Authentication", getAuthHeader());
}
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
return conn;
}
public String getLastError(){
return lastError;
}
public void setLastError(String str){
String lastError = str;
}
private String getErrorDetails(HttpURLConnection conn) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getErrorStream()));
StringBuilder responseText = new StringBuilder();
String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
lastError = responseText.toString();
return lastError;
}
private BufferedInputStream extractAndSaveOutput(HttpURLConnection conn) throws IOException {
BufferedInputStream bufferStream = new BufferedInputStream(conn.getInputStream(), 1024*1024);
bufferStream.mark(0);
BufferedReader br = new BufferedReader( new InputStreamReader( bufferStream ) );
String line = null;
StringBuilder responseText = new StringBuilder();
while ( (line = br.readLine()) != null)
responseText.append(line);
lastResponse = responseText.toString();
bufferStream.reset();
return bufferStream;
}
public String getAuthHeader() {
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
return authenticateStr;
}
// getters and setters
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountId() {
return accountId;
}
public String getIntegratorKey() {
return integratorKey;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String getServerUrl() {
return serverUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getBaseUrl() {
return baseUrl;
}
public String getLastResponseText() {
return lastResponse;
}
public String getLastRequestText() {
return lastRequest;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
/**
* you can call this after calling login to see if other accounts have been returned
* @return the list of accounts that were retrieved
*/
public List<LoginAccount> getLoginAccounts() {
return this.loginAccounts;
}
} |
package com.ecyrd.jspwiki.search;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.WikiPage;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages searching the Wiki.
*
* @author Arent-Jan Banck for Informatica
* @since 2.2.21.
*/
public class SearchManager
{
private static final Logger log = Logger.getLogger(SearchManager.class);
private static String DEFAULT_SEARCHPROVIDER = "com.ecyrd.jspwiki.search.LuceneSearchProvider";
public static final String PROP_USE_LUCENE = "jspwiki.useLucene";
public static final String PROP_SEARCHPROVIDER = "jspwiki.searchProvider";
private SearchProvider m_searchProvider = null;
public SearchManager( WikiEngine engine, Properties properties )
throws WikiException
{
initialize( engine, properties );
}
/**
* This particular method starts off indexing and all sorts of various activities,
* so you need to run this last, after things are done.
*
* @param engine
* @param properties
* @throws WikiException
*/
public void initialize(WikiEngine engine, Properties properties)
throws WikiException
{
loadSearchProvider(properties);
try
{
m_searchProvider.initialize(engine, properties);
}
catch (NoRequiredPropertyException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadSearchProvider(Properties properties)
{
// See if we're using Lucene, and if so, ensure that its
// index directory is up to date.
String useLucene = properties.getProperty(PROP_USE_LUCENE);
// FIXME: Obsolete, remove, or change logic to first load searchProvder?
// If the old jspwiki.useLucene property is set we use that instead of the searchProvider class.
if( useLucene != null )
{
log.info( PROP_USE_LUCENE+" is deprecated; please use "+PROP_SEARCHPROVIDER+"=<your search provider> instead." );
if( TextUtil.isPositive( useLucene ) )
{
m_searchProvider = new LuceneSearchProvider();
}
else
{
m_searchProvider = new BasicSearchProvider();
}
log.debug("useLucene was set, loading search provider " + m_searchProvider);
return;
}
String providerClassName = properties.getProperty( PROP_SEARCHPROVIDER,
DEFAULT_SEARCHPROVIDER );
try
{
Class providerClass = ClassUtil.findClass( "com.ecyrd.jspwiki.search", providerClassName );
m_searchProvider = (SearchProvider)providerClass.newInstance();
}
catch( ClassNotFoundException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
catch( InstantiationException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
catch( IllegalAccessException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
if( null == m_searchProvider )
{
// FIXME: Make a static with the default search provider
m_searchProvider = new BasicSearchProvider();
}
log.debug("Loaded search provider " + m_searchProvider);
}
public SearchProvider getSearchEngine()
{
return m_searchProvider;
}
public Collection findPages( String query )
{
return m_searchProvider.findPages( query );
}
/**
* Removes the page from the search cache (if any).
* @param page The page to remove
*/
public void deletePage(WikiPage page)
{
m_searchProvider.deletePage(page);
}
public void addToQueue(WikiPage page)
{
m_searchProvider.addToQueue(page);
}
} |
package com.eirb.projets9;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Application;
import android.graphics.Typeface;
import com.eirb.projets9.objects.Beacon;
import com.eirb.projets9.objects.Building;
import com.eirb.projets9.objects.Conference;
import com.eirb.projets9.objects.Coordinate;
import com.eirb.projets9.objects.Floor;
import com.eirb.projets9.objects.MapBeacon;
import com.eirb.projets9.objects.Notification;
import com.eirb.projets9.objects.Room;
import com.eirb.projets9.objects.Session;
import com.eirb.projets9.objects.Talk;
import com.eirb.projets9.objects.Track;
import com.eirb.projets9.scanner.BeaconRecord;
import com.eirb.projets9.scanner.NotificationService;
public class ReferenceApplication extends Application {
// public BackgroundPowerSaver mBackgroundPowerSaver; // Seems to kill the background service if the screen is off
/* VARIABLES */
// Time before being notified
public static final int TIME_TO_BE_NOTIFIED = 10;
// Maximum distance to be notified
public static final double DISTANCE_TO_BE_NOTIFIED = 2;
// Display records in logcat ?
public static boolean displayRecords = false;
// Beacons records
public static ArrayList<BeaconRecord> records;
public static ArrayList<MapBeacon> mapBeacons;
// Notification service, used for callbacks
public static NotificationService notificationService;
public static ArrayList<Notification> notificationList;
// Conference File Path
public static String conferenceFile;
public static String buildingFile;
public static String beaconsFile;
public static String notificationsFile;
public static long lastTimestamp = 0;
public static double lastX = -1;
public static double lastY = -1;
public static int lastNumberofBeacons = 0;
/* FONTS */
public static Typeface fontMedium;
public static Typeface fontThin;
public static Typeface fontLight;
public static MainActivity mainActivity;
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate Application");
// mBackgroundPowerSaver = new BackgroundPowerSaver(this);
records = new ArrayList<BeaconRecord>();
mapBeacons = new ArrayList<MapBeacon>();
conferenceFile = getFilesDir().getAbsolutePath().concat("/conference");
buildingFile = getFilesDir().getAbsolutePath().concat("/building");
beaconsFile = getFilesDir().getAbsolutePath().concat("/beacons");
notificationsFile = getFilesDir().getAbsolutePath().concat("/notifications");
// Fonts
fontMedium = Typeface.createFromAsset(getAssets(), "HelveticaNeueLTStd-Md.otf");
fontThin = Typeface.createFromAsset(getAssets(), "HelveticaNeueLTStd-Th.otf");
fontLight = Typeface.createFromAsset(getAssets(), "HelveticaNeueLTStd-Lt.otf");
if(new File(notificationsFile).exists()){
notificationList = deserializeNotifications();
}
// TODO : To be removed
// mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","238",-1,-1,new Coordinate(120, 660)));
// mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","232",-1,-1,new Coordinate(980, 660)));
// mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","42",-1,-1,new Coordinate(980, 1300)));
mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","11",-1,-1,new Coordinate(915, 445)));
mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","12",-1,-1,new Coordinate(990, 445)));
mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","42",-1,-1,new Coordinate(990, 572)));
mapBeacons.add(new MapBeacon("3d4f13b4-d1fd-4049-80e5-d3edcc840b6a","61298","232",-1,-1,new Coordinate(915, 572)));
};
/* Notification callback */
public static void setNotificationService(NotificationService service){
notificationService = service;
}
/* Record callback */
public static void recordAdded(){
notificationService.recordCallback();
}
/* Save object to file */
public static void serializeConference(Conference conf){
try{
FileOutputStream fout = new FileOutputStream(conferenceFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(conf);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void serializeBuilding(Building build) {
try{
FileOutputStream fout = new FileOutputStream(buildingFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(build);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void serializeBeaconList(
ArrayList<com.eirb.projets9.objects.Beacon> beaconList) {
try{
FileOutputStream fout = new FileOutputStream(beaconsFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(beaconList);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void serializeNotifications() {
try{
FileOutputStream fout = new FileOutputStream(notificationsFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(notificationList);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
/* Get object from file */
public static Conference deserializeConference(){
Conference conf;
try{
FileInputStream fin = new FileInputStream(conferenceFile);
ObjectInputStream ois = new ObjectInputStream(fin);
conf = (Conference) ois.readObject();
ois.close();
return conf;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
public static Building deserializeBuilding(){
Building build;
try{
FileInputStream fin = new FileInputStream(buildingFile);
ObjectInputStream ois = new ObjectInputStream(fin);
build = (Building) ois.readObject();
ois.close();
return build;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
public static ArrayList<com.eirb.projets9.objects.Beacon> deserializeBeacons() {
ArrayList<com.eirb.projets9.objects.Beacon> beacons;
try {
FileInputStream fin = new FileInputStream(beaconsFile);
ObjectInputStream ois = new ObjectInputStream(fin);
beacons = (ArrayList<Beacon>) ois.readObject();
ois.close();
return beacons;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private ArrayList<Notification> deserializeNotifications() {
ArrayList<Notification> notifs;
try {
FileInputStream fin = new FileInputStream(notificationsFile);
ObjectInputStream ois = new ObjectInputStream(fin);
notifs = (ArrayList<Notification>) ois.readObject();
ois.close();
return notifs;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/* Get Coordinates of a beacon for a given uuid - major - minor */
public static Coordinate getCoordinate(String uuid, String major, String minor){
for (int i = 0 ; i < mapBeacons.size() ; i++){
MapBeacon mapBeacon = mapBeacons.get(i);
if (mapBeacon.getUuid().equals(uuid) && mapBeacon.getMajor().equals(major) && mapBeacon.getMinor().equals(minor)){
return mapBeacon.getCoordinate();
}
}
return new Coordinate(-1, -1);
}
public static boolean isInMapBeacon(BeaconRecord br){
for (int i = 0; i < mapBeacons.size() ; i++){
MapBeacon mb = mapBeacons.get(i);
if (br.getUuid().equals(mb.getUuid()))
if(br.getMajor().equals(mb.getMajor()))
if(br.getMinor().equals(mb.getMinor()))
return true;
}
return false;
}
public static String getRoomName(Building building, int id ){
ArrayList<Floor> fl = building.getList();
for (int i = 0 ; i < fl.size();i++){
ArrayList<Room> rl = fl.get(i).getList();
for (int j = 0 ; j< rl.size();j++){
if (rl.get(j).getId() == id)
return rl.get(j).getName();
}
}
return null;
}
public static Talk getNextTalk(int roomID){
Conference c = deserializeConference();
if (c == null)
return null;
for (int i = 0; i < c.getList().size() ; i++){
Track track = c.getList().get(i);
for (int j = 0 ; j < track.getList().size() ; j++){
Session session = track.getList().get(j);
if(session.getRoom_id() == roomID){
ArrayList<Talk> list = session.getList();
Collections.sort(list);
if(list.size() > 0){
return list.get(0);
}
}
}
}
return null;
}
} |
package com.example.rehab_coachv1;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HomeActivity extends Activity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ArrayList<String> activity_names_list = new ArrayList<String>();
ArrayList<Integer> activity_ids_list = new ArrayList<Integer>();
int theme = 0;
private SQLiteDatabase database;
private void getActivities(){
ExternalDbOpenHelper dbHelper = new ExternalDbOpenHelper(this, "rehab_coach");
database = dbHelper.openDataBase();
Cursor activityCursor = database.query("activity", new String[]{"_id","name"}, null,null,null,null,null);
activityCursor.moveToFirst();
while(!activityCursor.isAfterLast()){
/*This is a hacky way to keep track of what names and id's go with the activities that are being represented on the screen.
Because the ArrayAdapter needed an array of Strings, it was easier to do this than to make an array of tuples and try to decompose them for the String ArrayAdapter */
activity_names_list.add(activityCursor.getString(activityCursor.getColumnIndex("name")));
activity_ids_list.add(activityCursor.getInt(activityCursor.getColumnIndex("_id")));
activityCursor.moveToNext();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivities();
theme = getIntent().getIntExtra("theme", 0);
if (theme == 0)
{
setTheme(android.R.style.Theme_Holo_Light);
}
else
{
setTheme(android.R.style.Theme_Holo);
}
setContentView(R.layout.activity_home_drawer);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.home_list_layout, activity_names_list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent remind = new Intent (HomeActivity.this, ReminderActivity.class);
remind.putExtra("act", activity_names_list.get(position));
remind.putExtra("theme", theme);
//position starts at index 0. We need to pass in the activity_id, which will be position+1 for now
//This will likely change when we have a prioritized activity list
remind.putExtra("act_id", activity_ids_list.get(position));
startActivity(remind);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if (theme == 1)
{
getMenuInflater().inflate(R.menu.dark, menu);
}
else
{
getMenuInflater().inflate(R.menu.light, menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.home_screen:
openHome();
return true;
case R.id.profile_screen:
openProfile();
return true;
case R.id.help_screen:
openHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openHome() {
Intent remind = new Intent (this, HomeActivity.class);
remind.putExtra("theme", theme);
startActivity(remind);
}
public void openProfile() {
Intent remind = new Intent (this, ProfileActivity.class);
remind.putExtra("theme", theme);
startActivity(remind);
}
public void openHelp() {
Intent remind = new Intent (this, HelpActivity.class);
remind.putExtra("theme", theme);
startActivity(remind);
}
public void changetheme(View view)
{
if (theme == 0)
{
theme = 1;
Intent remind = new Intent (this, HomeActivity.class);
remind.putExtra("theme", theme);
startActivity(remind);
}
else
{
theme = 0;
Intent remind = new Intent (this, HomeActivity.class);
remind.putExtra("theme", theme);
startActivity(remind);
}
}
} |
package com.yunpian.sdk.api;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.Test;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsBatchSend;
import com.yunpian.sdk.model.SmsRecord;
import com.yunpian.sdk.model.SmsReply;
import com.yunpian.sdk.model.SmsSingleSend;
import com.yunpian.sdk.model.SmsStatus;
import com.yunpian.sdk.util.ApiUtil;
public class TestSmsApi extends TestYunpianClient {
@Test
public void single_sendTest() {
Map<String, String> param = clnt.newParam(2);
param.put(MOBILE, "");
param.put(TEXT, "1234");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsSingleSend> r = clnt.sms().single_send(param);
System.out.println(r);
}
@Test
public void batch_sendTest() {
Map<String, String> param = clnt.newParam(5);
param.put(MOBILE, "11111111111");
param.put(TEXT, "1234");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsBatchSend> r = clnt.sms().batch_send(param);
System.out.println(r);
}
@Test
public void multi_sendTest() {
Map<String, String> param = clnt.newParam(5);
param.put(MOBILE, "18611111111,18611111112");
param.put(TEXT, ApiUtil.urlEncodeAndLink("utf-8", ",", ",1234", "1234"));
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsBatchSend> r = clnt.sms().multi_send(param);
System.out.println(r);
}
@Test
@Deprecated
public void tpl_single_sendTest() {
Map<String, String> param = clnt.newParam(5);
param.put(MOBILE, "11111111111");
param.put(TPL_ID, "1");
param.put(TPL_VALUE, "#company#=");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsSingleSend> r = clnt.sms().tpl_single_send(param);
System.out.println(r);
}
@Test
@Deprecated
public void tpl_batch_sendTest() {
Map<String, String> param = clnt.newParam(5);
param.put(MOBILE, "11111111111");
param.put(TPL_ID, "1");
param.put(TPL_VALUE, "#company#=");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsBatchSend> r = clnt.sms().tpl_batch_send(param);
System.out.println(r);
}
@Test
public void pull_statusTest() {
Map<String, String> param = clnt.newParam(1);
param.put(PAGE_SIZE, "20");
Result<List<SmsStatus>> r = clnt.sms().pull_status(param);
System.out.println(r);
// r = ((SmsApi) clnt.sms().version(VERSION_V1)).pull_status(param);
// System.out.println(r);
}
@Test
public void pull_replyTest() {
Map<String, String> param = clnt.newParam(1);
param.put(PAGE_SIZE, "20");
Result<List<SmsReply>> r = clnt.sms().pull_reply(param);
System.out.println(r);
// r = ((SmsApi) clnt.sms().version(VERSION_V1)).pull_reply(param);
// System.out.println(r);
}
@Test
public void get_recordTest() {
Map<String, String> param = clnt.newParam(1);
param.put(START_TIME, "2013-08-11 00:00:00");
param.put(END_TIME, "2016-12-05 00:00:00");
param.put(PAGE_NUM, "1");
param.put(PAGE_SIZE, "20");
// param.put(MOBILE, "11111111111");
Result<List<SmsRecord>> r = clnt.sms().get_record(param);
System.out.println(r);
r = ((SmsApi) clnt.sms().version(VERSION_V1)).get_record(param);
System.out.println(r);
}
@Test
public void get_black_wordTest() {
Map<String, String> param = clnt.newParam(1);
param.put(TEXT, ",");
Result<List<String>> r = clnt.sms().get_black_word(param);
System.out.println(r);
// r = ((SmsApi) clnt.sms().version(VERSION_V1)).get_black_word(param);
// System.out.println(r);
}
@Test
@Deprecated
public void sendTest() {
Map<String, String> param = clnt.newParam(5);
param.put(MOBILE, "11111111111");
param.put(TEXT, "1234");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
Result<SmsSingleSend> r = ((SmsApi) clnt.sms().version(VERSION_V1)).send(param);
System.out.println(r);
}
@Test
public void get_replyTest() {
Map<String, String> param = clnt.newParam(5);
param.put(START_TIME, "2013-08-11 00:00:00");
param.put(END_TIME, "2016-12-05 00:00:00");
param.put(PAGE_NUM, "1");
param.put(PAGE_SIZE, "20");
// param.put(MOBILE, "11111111111");
Result<List<SmsReply>> r = clnt.sms().get_reply(param);
System.out.println(r);
// r = ((SmsApi) clnt.sms().version(VERSION_V1)).get_reply(param);
// System.out.println(r);
}
@Test
@Deprecated
public void tpl_sendTest() {
Map<String, String> param = clnt.newParam(5);
int n = ThreadLocalRandom.current().nextInt(10);
param.put(MOBILE, "1861601112" + n);
param.put(TPL_ID, "1");
param.put(TPL_VALUE, "#company#=");
// param.put(EXTEND, "001");
// param.put(UID, "10001");
long s1 = System.currentTimeMillis();
Result<SmsSingleSend> r = ((SmsApi) clnt.sms().version(VERSION_V1)).tpl_send(param);
System.out.println(r + "time-" + (System.currentTimeMillis() - s1));
}
@Deprecated
public void tpl_sendPTest() {
int t = 6;
final CountDownLatch sl = new CountDownLatch(1);
final CountDownLatch el = new CountDownLatch(t);
for (int i = 0; i < t; i++) {
new Thread() {
public void run() {
try {
sl.await();
tpl_sendTest();
} catch (Exception e) {
} finally {
el.countDown();
}
}
}.start();
}
sl.countDown();
try {
el.await();
} catch (InterruptedException e) {
}
}
@Test
public void countTest() {
Map<String, String> param = clnt.newParam(5);
param.put(START_TIME, "2013-08-11 00:00:00");
param.put(END_TIME, "2016-12-05 00:00:00");
param.put(PAGE_NUM, "1");
param.put(PAGE_SIZE, "20");
// param.put(MOBILE, "11111111111");
Result<Integer> r = clnt.sms().count(param);
System.out.println(r);
r = ((SmsApi) clnt.sms().version(VERSION_V1)).count(param);
System.out.println(r);
}
} |
package com.jetbrains.idear.asr;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.Pair;
import com.intellij.util.Consumer;
import com.jetbrains.idear.GoogleHelper;
import com.jetbrains.idear.actions.ExecuteVoiceCommandAction;
import com.jetbrains.idear.recognizer.CustomLiveSpeechRecognizer;
import com.jetbrains.idear.recognizer.CustomMicrophone;
import com.jetbrains.idear.tts.TTSService;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ASRServiceImpl implements ASRService {
public static final double MASTER_GAIN = 0.85;
public static final double CONFIDENCE_LEVEL_THRESHOLD = 0.5;
private final Thread speechThread = new Thread(new ASRControlLoop(), "ASR Thread");
private static final String ACOUSTIC_MODEL = "resource:/edu.cmu.sphinx.models.en-us/en-us";
private static final String DICTIONARY_PATH = "resource:/edu.cmu.sphinx.models.en-us/cmudict-en-us.dict";
private static final String GRAMMAR_PATH = "resource:/com.jetbrains.idear/grammars";
private static final Logger logger = Logger.getLogger(ASRServiceImpl.class.getSimpleName());
private CustomLiveSpeechRecognizer recognizer;
private Robot robot;
private final AtomicReference<Status> status = new AtomicReference<>(Status.INIT);
public void init() {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath(ACOUSTIC_MODEL);
configuration.setDictionaryPath(DICTIONARY_PATH);
configuration.setGrammarPath(GRAMMAR_PATH);
configuration.setUseGrammar(true);
configuration.setGrammarName("command");
try {
recognizer = new CustomLiveSpeechRecognizer(configuration);
// recognizer.setMasterGain(MASTER_GAIN);
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't initialize speech recognizer:", e);
}
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
// Start-up recognition facilities
recognizer.startRecognition(true);
// Fire up control-loop
speechThread.start();
}
public void dispose() {
// Deactivate in the first place, therefore actually
// prevent activation upon the user-input
deactivate();
terminate();
}
private void terminate() {
recognizer.stopRecognition();
}
private Status setStatus(Status s) {
return status.getAndSet(s);
}
@Override
public Status getStatus() {
return status.get();
}
@Override
public Status activate() {
if (getStatus() == Status.ACTIVE)
return Status.ACTIVE;
// if (getStatus() == Status.INIT) {
// // Cold start prune cache
// recognizer.startRecognition(true);
return setStatus(Status.ACTIVE);
}
@Override
public Status deactivate() {
return setStatus(Status.STANDBY);
}
private class ASRControlLoop implements Runnable {
public static final String FUCK = "fuck";
public static final String OPEN = "open";
public static final String SETTINGS = "settings";
public static final String RECENT = "recent";
public static final String TERMINAL = "terminal";
public static final String FOCUS = "focus";
public static final String EDITOR = "editor";
public static final String PROJECT = "project";
public static final String SELECTION = "selection";
public static final String EXPAND = "expand";
public static final String SHRINK = "shrink";
public static final String PRESS = "press";
public static final String DELETE = "delete";
public static final String ENTER = "enter";
public static final String ESCAPE = "escape";
public static final String TAB = "tab";
public static final String UNDO = "undo";
public static final String NEXT = "next";
public static final String LINE = "line";
public static final String PAGE = "page";
public static final String METHOD = "method";
public static final String PREVIOUS = "previous";
public static final String INSPECT_CODE = "inspect code";
public static final String OKAY_GOOGLE = "okay google";
public static final String OK_GOOGLE = "ok google";
public static final String OKAY_IDEA = "okay idea";
public static final String OK_IDEA = "ok idea";
public static final String HI_IDEA = "hi idea";
@Override
public void run() {
while (!isTerminated()) {
// This blocks on a recognition result
String result = getResultFromRecognizer();
if (isInit()) {
if (result.equals(HI_IDEA)) {
// Greet invoker
say("Hi");
invokeAction("Idear.Start");
}
} else if (isActive()) {
logger.log(Level.INFO, "Recognized: " + result);
applyAction(result);
}
}
}
private String getResultFromRecognizer() {
SpeechResult result = recognizer.getResult();
logger.info("Recognized: ");
logger.info("\tTop H: " + result.getResult() + " / " + result.getResult().getBestToken() + " / " + result.getResult().getBestPronunciationResult());
logger.info("\tTop 3H: " + result.getNbest(3));
return result.getHypothesis();
}
private void applyAction(String c) {
if (c.equals(HI_IDEA)) {
// Greet some more
say("Hi, again!");
}
else if (c.equals(FUCK)) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_Z);
//invokeAction(IdeActions.ACTION_UNDO);
}
else if (c.startsWith(OPEN)) {
if (c.endsWith(SETTINGS)) {
invokeAction(IdeActions.ACTION_SHOW_SETTINGS);
} else if (c.endsWith(RECENT)) {
invokeAction(IdeActions.ACTION_RECENT_FILES);
} else if (c.endsWith(TERMINAL)) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_F12);
}
}
else if (c.startsWith("focus")) {
if (c.endsWith("editor")) {
pressKeystroke(KeyEvent.VK_ESCAPE);
} else if (c.endsWith("project")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_1);
}
}
else if (c.endsWith("selection")) {
if (c.startsWith("expand")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_W);
} else if (c.startsWith("shrink")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_W);
}
}
else if (c.startsWith("press")) {
if (c.contains("delete")) {
pressKeystroke(KeyEvent.VK_DELETE);
} else if (c.contains("return")) {
pressKeystroke(KeyEvent.VK_ENTER);
} else if (c.contains("escape")) {
pressKeystroke(KeyEvent.VK_ESCAPE);
} else if (c.contains("tab")) {
pressKeystroke(KeyEvent.VK_TAB);
} else if (c.contains("undo")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_Z);
}
}
else if (c.startsWith("next")) {
if (c.endsWith("line")) {
pressKeystroke(KeyEvent.VK_DOWN);
} else if (c.endsWith("page")) {
pressKeystroke(KeyEvent.VK_PAGE_DOWN);
} else if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_DOWN);
}
}
else if (c.startsWith("previous")) {
if (c.endsWith("line")) {
pressKeystroke(KeyEvent.VK_UP);
} else if (c.endsWith("page")) {
pressKeystroke(KeyEvent.VK_PAGE_UP);
} else if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_UP);
}
}
else if (c.startsWith("extract this")) {
if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_M);
} else if (c.endsWith("parameter")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_P);
}
}
else if (c.startsWith("inspect code")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_SHIFT, KeyEvent.VK_I);
}
else if (c.startsWith("speech pause")) {
pauseSpeech();
}
else if (c.startsWith(OK_IDEA) || c.startsWith(OKAY_IDEA)) {
beep();
fireVoiceCommand();
}
else if (c.startsWith(OKAY_GOOGLE) || c.startsWith(OK_GOOGLE)) {
beep();
fireGoogleSearch();
}
else if(c.contains("break point")) {
if (c.startsWith("toggle")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_F8);
} else if(c.startsWith("view")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_F8);
}
}
else if (c.startsWith("step")) {
if (c.endsWith("over")) {
pressKeystroke(KeyEvent.VK_F8);
} else if (c.endsWith("into")) {
pressKeystroke(KeyEvent.VK_F7);
}
}
}
private void fireVoiceCommand() {
try {
Pair<String, Double> commandTuple = GoogleHelper.getBestTextForUtterance(CustomMicrophone.recordFromMic());
if (commandTuple == null || commandTuple.first.isEmpty() /* || searchQuery.second < CONFIDENCE_LEVEL_THRESHOLD */)
return;
// Notify of successful proceed
beep();
invokeAction(
"Idear.VoiceAction",
dataContext -> new AnActionEvent(
null,
SimpleDataContext.getSimpleContext(ExecuteVoiceCommandAction.KEY.getName(), commandTuple.first, dataContext),
ActionPlaces.UNKNOWN,
new Presentation(),
ActionManager.getInstance(),
0
)
);
} catch (IOException e) {
logger.log(Level.SEVERE, "Panic! Failed to dump WAV", e);
}
}
private void fireGoogleSearch() {
try {
Pair<String, Double> searchQueryTuple = GoogleHelper.getBestTextForUtterance(CustomMicrophone.recordFromMic());
if (searchQueryTuple == null || searchQueryTuple.first.isEmpty() /* || searchQuery.second < CONFIDENCE_LEVEL_THRESHOLD */)
return;
ServiceManager
.getService(TTSService.class)
.say("I think you said " + searchQueryTuple.first + ", searching Google now");
GoogleHelper.searchGoogle(searchQueryTuple.first);
} catch (IOException e) {
logger.log(Level.SEVERE, "Panic! Failed to dump WAV", e);
}
}
private void pauseSpeech() {
String result;
while (isActive()) {
result = getResultFromRecognizer();
if (result.equals("speech resume")) {
break;
}
}
}
}
private boolean isTerminated() {
return getStatus() == Status.TERMINATED;
}
public boolean isInit() {
return getStatus() == Status.INIT;
}
private boolean isActive() {
return getStatus() == Status.ACTIVE;
}
private void pressKeystroke(final int... keys) {
for (int key : keys) {
robot.keyPress(key);
}
for (int key : keys) {
robot.keyRelease(key);
}
}
private void invokeAction(final String action) {
invokeAction(
action,
dataContext ->
new AnActionEvent(null,
dataContext,
ActionPlaces.UNKNOWN,
new Presentation(),
ActionManager.getInstance(),
0
)
);
}
private void invokeAction(String action, Function<DataContext, AnActionEvent> actionFactory) {
DataManager.getInstance().getDataContextFromFocus().doWhenDone(
(Consumer<DataContext>) dataContext -> EventQueue.invokeLater(() -> {
AnAction anAction = ActionManager.getInstance().getAction(action);
anAction.actionPerformed(actionFactory.apply(dataContext));
})
);
}
// Helpers
public static synchronized void say(String something) {
ServiceManager .getService(TTSService.class)
.say(something);
}
public static synchronized void beep() {
Thread t = new Thread(() -> {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
ASRServiceImpl.class.getResourceAsStream("/com.jetbrains.idear/sounds/beep.wav"));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
});
t.start();
try {
t.join();
} catch (InterruptedException _) {}
}
// This is for testing purposes solely
public static void main(String[] args) {
ASRServiceImpl asrService = new ASRServiceImpl();
asrService.init();
asrService.activate();
}
} |
package com.jetbrains.ther.psi;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.jetbrains.ther.TheRFileType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor;
public class TheRElementType extends IElementType {
protected Class<? extends PsiElement> myPsiElementClass;
private Constructor<? extends PsiElement> myConstructor;
private static final Class[] PARAMETER_TYPES = new Class[]{ASTNode.class};
public TheRElementType(@NotNull @NonNls final String debugName) {
super(debugName, TheRFileType.INSTANCE.getLanguage());
}
public TheRElementType(@NotNull @NonNls final String debugName, @NotNull final Class<? extends PsiElement> psiElementClass) {
super(debugName, TheRFileType.INSTANCE.getLanguage());
myPsiElementClass = psiElementClass;
}
@NotNull
public PsiElement createElement(@NotNull final ASTNode node) {
if (myPsiElementClass == null) {
throw new IllegalStateException("Cannot create an element for " + node.getElementType() + " without element class");
}
try {
if (myConstructor == null) {
myConstructor = myPsiElementClass.getConstructor(PARAMETER_TYPES);
}
return myConstructor.newInstance(node);
}
catch (Exception e) {
throw new IllegalStateException("No necessary constructor for " + node.getElementType(), e);
}
}
} |
package com.jtolds.android.dualnback;
import android.util.Log;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Button;
import android.view.MenuItem;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.graphics.Color;
import android.speech.tts.TextToSpeech;
import android.content.Intent;
import android.content.Context;
import java.util.Random;
import java.util.Locale;
public class DualNBack extends Activity {
private Random GENERATOR = new Random();
private long MILLIS_BETWEEN_TICKS = 3000;
private int DATA_CHECK_CODE_1 = 1;
private double CHOOSE_MATCH_PROB = .1;
private boolean m_gameRunning = false;
private boolean m_auditoryClicked = false;
private boolean m_visualClicked = false;
private TextView[] m_positions = new TextView[8];
private String[] m_letters = new String[8];
private int[] m_colors = new int[4];
private int[] m_textColors = new int[4];
private TextView[] m_positionHistory = new TextView[0];
private String[] m_letterHistory = new String[0];
private int m_n = 2;
private int m_trials = 0;
private int m_successes = 0;
private int m_currentColor = 0;
private TextToSpeech m_tts = null;
private Handler m_handler = new Handler();
private Runnable m_tick = new Runnable() {
public void run() {
m_handler.postDelayed(this, MILLIS_BETWEEN_TICKS);
gameTick();
}
};
private PowerManager.WakeLock m_wl = null;
public void log(String msg) {
Log.d(getString(R.string.app_name), msg);
}
@Override
public void onCreate(Bundle savedInstanceState) {
log("onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_wl = ((PowerManager)getSystemService(Context.POWER_SERVICE)
).newWakeLock(PowerManager.FULL_WAKE_LOCK, "dualnback");
m_positions[0] = (TextView)findViewById(R.id.cell_0);
m_positions[1] = (TextView)findViewById(R.id.cell_1);
m_positions[2] = (TextView)findViewById(R.id.cell_2);
m_positions[3] = (TextView)findViewById(R.id.cell_3);
m_positions[4] = (TextView)findViewById(R.id.cell_8);
m_positions[5] = (TextView)findViewById(R.id.cell_5);
m_positions[6] = (TextView)findViewById(R.id.cell_6);
m_positions[7] = (TextView)findViewById(R.id.cell_7);
// m_positions[8] = (TextView)findViewById(R.id.cell_4);
m_letters[0] = "C";
m_letters[1] = "R";
m_letters[2] = "T";
m_letters[3] = "S";
m_letters[4] = "H";
m_letters[5] = "J";
m_letters[6] = "M";
m_letters[7] = "Q";
// m_letters[8] = "L";
m_colors[0] = Color.rgb(0, 255, 0);
m_colors[1] = Color.rgb(0, 127, 255);
m_colors[2] = Color.rgb(255, 0, 255);
m_colors[3] = Color.rgb(255, 127, 0);
m_textColors[0] = Color.rgb(0, 0, 0);
m_textColors[1] = Color.rgb(255, 255, 255);
m_textColors[2] = Color.rgb(255, 255, 255);
m_textColors[3] = Color.rgb(255, 255, 255);
((TextView)findViewById(R.id.n_value)).setText("N = " + m_n);
((Button)findViewById(R.id.auditory_button)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
auditory();
}
});
((Button)findViewById(R.id.visual_button)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
visual();
}
});
((Button)findViewById(R.id.both_button)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
auditory();
visual();
}
});
((Button)findViewById(R.id.smaller_n_button)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
log("smaller n");
if(m_n <= 1) return;
m_n -= 1;
((TextView)findViewById(R.id.n_value)).setText("N = " + m_n);
}
});
((Button)findViewById(R.id.larger_n_button)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
log("larger n");
m_n += 1;
((TextView)findViewById(R.id.n_value)).setText("N = " + m_n);
}
});
m_tts = null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
log("onActivityResult " + requestCode + " " + resultCode);
if(requestCode == DATA_CHECK_CODE_1) {
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
m_tts = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
public void onInit(int status) {}
});
if(m_tts.isLanguageAvailable(Locale.US) ==
TextToSpeech.LANG_AVAILABLE)
m_tts.setLanguage(Locale.US);
}
}
}
@Override
public void onPause() {
log("onPause");
stopGame();
super.onPause();
}
@Override
public void onDestroy() {
log("onDestroy");
disableSound();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
log("onCreateOptionsMenu");
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
log("onOptionsItemSelected " + item.getItemId());
switch (item.getItemId()) {
case R.id.start_game:
startGame();
return true;
case R.id.stop_game:
stopGame();
return true;
case R.id.disable_sound:
disableSound();
return true;
case R.id.enable_sound:
enableSound();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
log("onKeyDown " + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_A:
auditory();
return true;
case KeyEvent.KEYCODE_L:
visual();
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
public void startGame() {
log("startGame");
if(m_gameRunning) return;
m_positionHistory = new TextView[0];
m_letterHistory = new String[0];
m_auditoryClicked = false;
m_visualClicked = false;
m_trials = 0;
m_successes = 0;
m_gameRunning = true;
if(m_wl != null) m_wl.acquire();
m_tick.run();
}
public void stopGame() {
log("stopGame");
if(!m_gameRunning) return;
m_handler.removeCallbacks(m_tick);
turnOffCell();
((TextView)findViewById(R.id.status)).setText(getString(
R.string.status_stopped));
((TextView)findViewById(R.id.skill)).setText("");
if(m_wl != null) m_wl.release();
m_gameRunning = false;
}
public void auditory() {
log("auditory");
m_auditoryClicked = true;
}
public void visual() {
log("visual");
m_visualClicked = true;
}
public void gameTick() {
log("gameTick");
turnOffCell();
if(m_positionHistory.length <= m_n) {
switch (m_n - m_positionHistory.length) {
case 0:
((TextView)findViewById(R.id.status)).setText("Go!");
break;
case 1:
((TextView)findViewById(R.id.status)).setText("Get set...");
break;
case 2:
((TextView)findViewById(R.id.status)).setText("On your mark...");
break;
default:
((TextView)findViewById(R.id.status)).setText("Wait...");
break;
}
TextView[] new_positionHistory = new TextView[
m_positionHistory.length + 1];
String[] new_letterHistory = new String[m_letterHistory.length + 1];
for(int i = 0; i < m_positionHistory.length; i++) {
new_positionHistory[i] = m_positionHistory[i];
new_letterHistory[i] = m_letterHistory[i];
}
m_positionHistory = new_positionHistory;
m_letterHistory = new_letterHistory;
} else {
String status = "";
m_trials += 2;
if(m_letterHistory[0] == m_letterHistory[m_n]) {
if(m_auditoryClicked) {
status += " - GOT LETTER!";
m_successes += 1;
} else {
status += " - MISSED LETTER!";
}
} else {
if(m_auditoryClicked) {
status += " - NO LETTER!";
} else {
m_successes += 1;
}
}
if(m_positionHistory[0] == m_positionHistory[m_n]) {
if(m_visualClicked) {
status += " - GOT POSITION!";
m_successes += 1;
} else {
status += " - MISSED POSITION!";
}
} else {
if(m_visualClicked) {
status += " - NO POSITION!";
} else {
m_successes += 1;
}
}
((TextView)findViewById(R.id.status)).setText(status);
}
m_auditoryClicked = false;
m_visualClicked = false;
for(int i = m_positionHistory.length - 1; i > 0; i
m_positionHistory[i] = m_positionHistory[i-1];
m_letterHistory[i] = m_letterHistory[i-1];
}
if(m_positionHistory.length > m_n &&
GENERATOR.nextDouble() < CHOOSE_MATCH_PROB) {
m_positionHistory[0] = m_positionHistory[m_n];
} else {
m_positionHistory[0] = m_positions[GENERATOR.nextInt(
m_positions.length)];
}
if(m_positionHistory.length > m_n &&
GENERATOR.nextDouble() < CHOOSE_MATCH_PROB) {
m_letterHistory[0] = m_letterHistory[m_n];
} else {
m_letterHistory[0] = m_letters[GENERATOR.nextInt(m_letters.length)];
}
((TextView)findViewById(R.id.skill)).setText(
"" + m_successes + "/" + m_trials);
turnOnCell();
if(m_tts != null)
m_tts.speak(m_letterHistory[0], TextToSpeech.QUEUE_FLUSH, null);
}
public void turnOnCell() {
if(m_positionHistory.length == 0) return;
TextView cell = m_positionHistory[0];
cell.setText(m_letterHistory[0]);
m_currentColor = (m_currentColor + 1) % m_colors.length;
cell.setBackgroundColor(m_colors[m_currentColor]);
cell.setTextColor(m_textColors[m_currentColor]);
}
public void turnOffCell() {
if(m_positionHistory.length == 0) return;
TextView cell = m_positionHistory[0];
cell.setText("");
cell.setBackgroundColor(Color.TRANSPARENT);
}
public void enableSound() {
if(m_tts != null) return;
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, DATA_CHECK_CODE_1);
}
public void disableSound() {
if(m_tts == null) return;
m_tts.shutdown();
m_tts = null;
}
} |
package com.mick88.dittimetable;
import java.util.List;
import android.content.Context;
import android.util.Log;
import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;
public class DatabaseHelper extends MSQLiteOpenHelper
{
private static final String name = "timetables.db";
private static final int version = 1;
private static final String TAG = "SQLite";
public DatabaseHelper(Context context) {
super(context, name, null, version, new Class<?>[]{
Timetable.class,
});
}
public Timetable getTimetable(String course, int year, String weeks)
{
List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
new String[]{course, String.valueOf(year), weeks},
null, "1");
if (timetables.isEmpty()) return null;
Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
return timetables.get(0);
}
public void saveTimetable(Timetable timetable)
{
replace(timetable);
Log.d(TAG, "Timetable saved: "+timetable.describe());
}
/**
* returns all timetables saved in database
* @return
*/
public List<Timetable> getSavedTimetables()
{
return selectAll(Timetable.class);
}
} |
package com.mowforth.rhinode.dispatch;
import akka.actor.ActorSystem;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.actor.Cancellable;
import akka.agent.Agent;
import akka.dispatch.Future;
import akka.dispatch.Futures;
import akka.japi.Function;
import akka.util.Duration;
import java.lang.Runnable;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class Dispatch {
private static ActorSystem system;
public static void setupSystem() {
if (system == null) system = ActorSystem.create("RhinodeMaster");
}
public static ActorSystem getSystem() {
return system;
}
public static Future<Object> future(Callable<Object> work, Completion<Object> callback) {
Future<Object> f = Futures.future(work, system.dispatcher()).andThen(callback);
return f;
}
public static Agent<Object> agent(Object initial) {
return new Agent<Object>(initial, system);
}
public static Cancellable doOnce(Runnable work, int delay) {
Duration d = Duration.create(delay, TimeUnit.MILLISECONDS);
return system.scheduler().scheduleOnce(d, newActor(), work);
}
public static Cancellable doRegularly(Runnable work, int delay) {
Duration d = Duration.create(delay, TimeUnit.MILLISECONDS);
return system.scheduler().schedule(Duration.Zero(), d, newActor(), work);
}
public static ActorRef newActor() {
ActorRef actor = system.actorOf(new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new UntypedActor() {
public void onReceive(Object message) {
if (message instanceof Runnable) {
Runnable work = (Runnable)message;
work.run();
} else {
unhandled(message);
}
}
};
}
}));
return actor;
}
} |
import java.net.InetAddress;
import java.net.DatagramSocket;
import java.util.Scanner;
import java.lang.InterruptedException;
public class Chatterbox {
private static final Logger log = new Logger("chatter");
private static final Logger.Level LOG_LEVEL = Logger.Level.DEBUG;
private RecvChannel receiver = null;
private SendChannel sender = null;
public Chatterbox(final java.io.InputStream messages, final String destHostName, final int destPort) {
final DatagramSocket outSock = AssertNetwork.mustOpenSocket(
"setup: failed opening socket to send [via %s] from port %d: %s\n");
// TODO(zacsh) refactor split into SendChannel and ReceiveClient, and just have single-looper
// that golang-esque selects on the current situation:
// - an outgoing message is ready, so send()
// -- internal data struct api to enqueue currently composed, out-bound messages
// (eg: windowing/UI-thread should be able to pass a new message over to cause this select
// case to trigger (when the next selection happens in some SOCKET_WAIT_MILLIS milliseconds
// - an we've spent SOCKET_WAIT_MILLIS receive()ing messages
final DatagramSocket inSocket = AssertNetwork.mustOpenSocket(
"setup: failed opening receiving socket on %s:%d: %s\n");
final InetAddress destAddr = AssertNetwork.mustResolveHostName(
destHostName, "setup: failed resolving destination host '%s': %s\n");
this.receiver = new RecvChannel(inSocket).setLogLevel(LOG_LEVEL);
this.sender = new SendChannel(
new Scanner(messages),
destAddr,
destPort, outSock).setLogLevel(LOG_LEVEL);
Chatterbox.log.printf("setup: listener & sender setups complete.\n\n");
}
private static Chatterbox parseFromCli(String[] args) {
final String usageDoc = "DESTINATION_HOST DEST_PORT";
final int expectedArgs = 2;
if (args.length != expectedArgs) {
Chatterbox.log.printf(
"Error: got %d argument(s), but expected %d...\nusage: %s\n",
args.length, expectedArgs, usageDoc);
System.exit(1);
}
final String destHostName = args[0].trim();
final int destPort = AssertNetwork.mustParsePort(args[1], "DEST_PORT");
return new Chatterbox(System.in, destHostName, destPort);
}
public static void main(String[] args) {
Chatterbox chatter = Chatterbox.parseFromCli(args);
chatter.receiver.report().start();
chatter.sender.report().start();
try {
chatter.sender.thread().join(); // block on send channel's own exit
} catch(InterruptedException e) {
Chatterbox.log.errorf(e, "failed waiting on sender thread\n");
}
System.out.printf("\n");
Chatterbox.log.printf("cleaning up recvr thread\n");
try {
chatter.receiver.stop().join(RecvChannel.SOCKET_WAIT_MILLIS * 2 /*millis*/);
} catch(InterruptedException e) {
Chatterbox.log.errorf(e, "problem stopping receiver");
}
if (!chatter.sender.isFailed()) {
System.exit(1);
}
}
} |
package com.team254.frc2013.subsystems;
import com.team254.frc2013.Constants;
import com.team254.lib.control.ControlledSubsystem;
import com.team254.lib.control.PeriodicSubsystem;
import com.team254.lib.util.Debouncer;
import com.team254.lib.util.ThrottledPrinter;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
/**
* Class representing the shooter wheels, managing its motors and sensors.
*
* @author richard@team254.com (Richard Lin)
* @author tom@team254.com (Tom Bottiglieri)
* @author eric.vanlare14@bcp.org (Eric van Lare)
* @author eliwu26@gmail.com (Elias Wu)
*/
public class Shooter extends PeriodicSubsystem implements ControlledSubsystem {
public static final int PRESET_BACK_PYRAMID = 0;
public static final int PRESET_FRONT_PYRAMID = 1;
public static final int PRESET_PYRAMID_GOAL = 2;
private Talon frontMotor = new Talon(Constants.frontShooterPort.getInt());
private Talon backMotor = new Talon(Constants.backShooterPort.getInt());
private Solenoid loader = new Solenoid(Constants.shooterLoaderPort.getInt());
private Solenoid angle = new Solenoid(Constants.shooterAnglePort.getInt());
private Solenoid indexer = new Solenoid(Constants.indexerPort.getInt());
Debouncer debouncer = new Debouncer(.125);
AnalogChannel discSensor = new AnalogChannel(Constants.discSensorPort.getInt());
ThrottledPrinter p = new ThrottledPrinter(.1);
private DigitalInput indexerDownSensor =
new DigitalInput(Constants.indexerDownSensorPort.getInt());
private DigitalInput shooterBackSensor =
new DigitalInput(Constants.shooterBackSensorPort.getInt());
private double frontPower;
private double backPower;
private boolean shooterOn;
private int loadState = 0;
private boolean wantShoot = false;
private Timer stateTimer = new Timer();
public void setIndexerUp(boolean up) {
indexer.set(!up);
}
// Load a frisbee into shooter by retracting the piston
public void load() {
loader.set(false);
}
// Extend piston to prepare for loading in another frisbee
public void extend() {
loader.set(true);
}
public boolean tryShoot() {
//if (loadState == 0) {
// wantShoot = true;
//return loadState == 0;
return false;
}
public void setHighAngle(boolean high) {
angle.set(high);
}
public boolean isHighAngle() {
return angle.get();
}
public boolean getLoaderState() {
return loader.get();
}
public boolean isIndexerDown() {
// The sensor reads true when the indexer is down.
return !indexerDownSensor.get();
}
public boolean isShooterBack() {
// The sensor reads true when the shooter is back.
return !shooterBackSensor.get();
}
// State machine
public void update() {
/*
//p.println(loadState + " " + discSensor.getValue());
int nextState = loadState;
boolean hasDisk = debouncer.update(discSensor.getValue() > 400);
switch (loadState) {
case 0: // frisbee loaded
setIndexerUp(true);
if (wantShoot) {
System.out.println("shooting in here");
wantShoot = false;
nextState++;
}
break;
case 1: // Shooting
extend();
if (stateTimer.get() > .2) {
nextState++;
Notifier.publish(Messages.SHOT_TAKEN);
}
break;
case 2:
setIndexerUp(false);
if (stateTimer.get() > .2)
nextState++;
break;
case 3:
load();
if (stateTimer.get() > .5)
nextState++;
break;
case 4:
if (hasDisk)
nextState = 0;
break;
default:
nextState = 0;
break;
}
if (nextState != loadState) {
stateTimer.reset();
loadState = nextState;
}
*/
}
public Shooter() {
super();
setPreset(PRESET_BACK_PYRAMID);
shooterOn = false;
stateTimer.start();
}
public void setPreset(int preset) {
switch (preset) {
case PRESET_FRONT_PYRAMID:
setHighAngle(true);
setPowers(1, 1);
break;
case PRESET_PYRAMID_GOAL:
setHighAngle(true);
setPowers(0.8, 0.8);
break;
case PRESET_BACK_PYRAMID:
default:
setHighAngle(false);
setPowers(1, 1);
}
}
private void setPowers(double frontPower, double backPower) {
this.frontPower = (frontPower < 0) ? 0 : frontPower;
this.backPower = (backPower < 0) ? 0 : backPower;
setShooterOn(shooterOn);
}
public void setShooterOn(boolean isOn) {
shooterOn = isOn;
if (isOn) {
frontMotor.set(frontPower);
backMotor.set(backPower);
} else {
frontMotor.set(0);
backMotor.set(0);
}
}
protected void initDefaultCommand() {
}
} |
package ibxm;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Image;
public class PatternDisplay extends Canvas {
public static final int CHANNEL_WIDTH = 88;
private int pan, channels = 0;
private Image charset, image;
private boolean[] muted;
private short[][] buffer;
private int[] fxclr = new int[] {
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1,1,1,1,1,7,7,5,5,4,0,0,0,0,0,0,
/* @ A B C D E F G H I J K L M N O */
0,5,6,5,6,0,6,5,5,0,0,0,4,0,0,0,
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
5,0,4,0,5,0,0,0,1,0,0,0,0,0,0,0,
/* ` a b c d e f g h i j k l m n o */
0,6,6,6,5,1,1,1,1,5,1,7,7,0,0,4,
/* p q r s t u v w x y z { | } ~ */
0,4,5,0,6,1,5,0,0,0,0,0,0,0,0
};
private int[] exclr = new int[] {
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F */
0,1,1,1,1,1,6,5,0,4,0,0,0,0,0,0,0,5,5,4,4,4,4
};
private int[] sxclr = new int[] {
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F */
5,4,1,1,5,0,0,0,5,0,0,0,0,0,0,0,0,5,4,4,4,4,4
};
private int[] vcclr = new int[] {
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F */
5,5,5,5,5,0,5,5,5,5,0,0,0,0,0,0,0,1,1,5,5,5,1
};
private synchronized void drawBuffer( int x0, int y0, int x1, int y1 ) {
int cols = getBufferWidth();
int rows = getBufferHeight();
if( charset == null ) {
initCharset();
}
if( image == null ) {
image = createImage( cols * 8, rows * 16 );
}
//System.out.println(x0 + "," + x1 + "," +y0 + "," +y1);
if( x0 < cols && y0 < rows ) {
if( x0 < 0 ) x0 = 0;
if( y0 < 0 ) y0 = 0;
if( x1 > cols ) x1 = cols;
if( y1 > rows ) y1 = rows;
Graphics gfx = image.getGraphics();
if( buffer == null ) {
gfx.setColor( java.awt.Color.BLACK );
gfx.fillRect( x0, y0, x1 * 8, y1 * 16 );
} else {
for( int y = y0; y < y1; y++ ) {
for( int x = x0; x < x1; x++ ) {
int chr = buffer[ y ][ x ];
gfx.setClip( x * 8, y * 16, 8, 16 );
gfx.drawImage( charset, ( x - ( chr & 0xFF ) + 32 ) * 8,
( y - ( chr >> 8 ) ) * 16, this );
}
}
}
gfx.dispose();
}
}
public void paint( Graphics g ) {
int cw = getWidth();
int ch = getHeight();
int bw = getBufferWidth() * 8;
int bh = getBufferHeight() * 16;
drawBuffer( pan / 8, 0, ( pan + cw ) / 8, ch / 16 );
g.drawImage( image, -pan, 0, this );
g.setColor( java.awt.Color.BLACK );
if( cw > ( bw - pan ) ) {
g.fillRect( bw - pan, 0, cw - bw + pan, bh );
}
if( ch > bh ) {
g.fillRect( 0, bh, cw, ch - bh );
}
}
public void update( Graphics g ) {
paint( g );
}
@Override
public java.awt.Dimension getPreferredSize() {
return new java.awt.Dimension( getBufferWidth() * 8, getBufferHeight() * 16 );
}
private int getBufferWidth() {
return channels * 11 + 4;
}
private int getBufferHeight() {
return 16;
}
public void setPan( int x ) {
pan = x;
repaint();
}
public int getChannel( int x ) {
x = x - 32 + pan;
int channel = x / CHANNEL_WIDTH;
if( x < 0 || channel >= channels ) {
channel = -1;
}
return channel;
}
public void setMuted( int channel, boolean mute ) {
if( channel < 0 ) {
for( int idx = 0; idx < channels; idx++ ) {
muted[ idx ] = mute;
}
} else if( channel < channels ) {
muted[ channel ] = mute;
}
}
public boolean isMuted( int channel ) {
return muted[ channel ];
}
public synchronized void display( ibxm.Module module, int pat, int row ) {
ibxm.Pattern pattern = module.patterns[ pat ];
if( buffer == null || module.numChannels != channels ) {
channels = module.numChannels;
muted = new boolean[ channels ];
buffer = new short[ getBufferHeight() ][ getBufferWidth() ];
if( image != null ) {
image.flush();
image = null;
}
}
drawInt( pat, 0, 0, 3, 3 );
drawChar( ' ', 0, 3, 0 );
for( int c = 0; c < channels; c++ ) {
if( muted[ c ] ) {
drawString( " Muted ", 0, c * 11 + 4, 3 );
drawInt( c, 0, c * 11 + 12, 3, 2 );
} else {
drawString( "Channel ", 0, c * 11 + 4, 0 );
drawInt( c, 0, c * 11 + 12, 0, 2 );
}
drawString( " ", 0, c * 11 + 14, 0 );
}
ibxm.Note note = new ibxm.Note();
char[] chars = new char[ 10 ];
for( int y = 1; y < 16; y++ ) {
int r = row - 8 + y;
if( r >= 0 && r < pattern.numRows ) {
int bcol = ( y == 8 ) ? 8 : 0;
drawInt( r, y, 0, bcol, 3 );
drawChar( ' ', y, 3, bcol );
for( int c = 0; c < channels; c++ ) {
int x = 4 + c * 11;
pattern.getNote( r * module.numChannels + c, note ).toChars( chars );
if( muted[ c ] ) {
for( int idx = 0; idx < 10; idx++ ) {
drawChar( chars[ idx ], y, x + idx, bcol );
}
} else {
int clr = chars[ 0 ] == '-' ? bcol : bcol + 2;
for( int idx = 0; idx < 3; idx++ ) {
drawChar( chars[ idx ], y, x + idx, clr );
}
for( int idx = 3; idx < 5; idx++ ) {
clr = chars[ idx ] == '-' ? bcol : bcol + 3;
drawChar( chars[ idx ], y, x + idx, clr );
}
clr = bcol;
if( chars[ 5 ] >= '0' && chars[ 5 ] <= 'F' ) {
clr = bcol + vcclr[ chars[ 5 ] - '0' ];
}
drawChar( chars[ 5 ], y, x + 5, clr );
drawChar( chars[ 6 ], y, x + 6, clr );
if( chars[ 7 ] == 'E' ) {
clr = bcol;
if( chars[ 8 ] >= '0' && chars[ 8 ] <= 'F' ) {
clr = clr + exclr[ chars[ 8 ] - '0' ];
}
} else if( chars[ 7 ] == 's' ) {
clr = bcol;
if( chars[ 8 ] >= '0' && chars[ 8 ] <= 'F' ) {
clr = clr + sxclr[ chars[ 8 ] - '0' ];
}
} else {
clr = bcol;
if( chars[ 7 ] >= '0' && chars[ 7 ] <= '~' ) {
clr = clr + fxclr[ chars[ 7 ] - '0' ];
}
}
for( int idx = 7; idx < 10; idx++ ) {
drawChar( chars[ idx ], y, x + idx, clr );
}
}
drawChar( ' ', y, x + 10, 0 );
}
} else {
drawString( " ", y, 0, 0 );
for( int c = 0; c < channels; c++ ) {
drawString( " ", y, 4 + c * 11, 0 );
}
}
}
repaint();
}
private void drawInt( int val, int row, int col, int clr, int len ) {
while( len > 0 ) {
len = len - 1;
drawChar( '0' + val % 10, row, col + len, clr );
val = val / 10;
}
}
private void drawString( String str, int row, int col, int clr ) {
for( int idx = 0, len = str.length(); idx < len; idx++ ) {
drawChar( str.charAt( idx ), row, col + idx, clr );
}
}
private void drawChar( int chr, int row, int col, int clr ) {
buffer[ row ][ col ] = ( short ) ( ( clr << 8 ) | chr );
}
private void initCharset() {
int[] pal = new int[] {
/* Blue Green Cyan Red Magenta Yellow White */
0x00C0, 0x8000, 0x8080, 0x800000, 0x800080, 0x806000, 0x808080, 0x608000,
0x60FF, 0xFF00, 0xFFFF, 0xFF0000, 0xFF00FF, 0xFFC000, 0xFFFFFF, 0xC0FF00 };
java.net.URL png = PatternDisplay.class.getResource( "topaz8.png" );
Image mask = java.awt.Toolkit.getDefaultToolkit().getImage( png );
charset = createImage( 8 * 96, 16 * pal.length );
Graphics g = charset.getGraphics();
for( int r = 0; r < pal.length; r++ ) {
g.setColor( java.awt.Color.BLACK );
g.setClip( 0, r * 16, 8, 16 );
g.fillRect( 0, r * 16, 8, 16 );
java.awt.Color clr = new java.awt.Color( pal[ r ] );
for( int c = 1; c < 96; c++ ) {
g.setClip( c * 8, r * 16, 8, 16 );
int x = c - ( ( c - 1 ) & 0x1F );
int y = r - ( ( c - 1 ) >> 5 );
while( !g.drawImage( mask, x * 8, y * 16, clr, null ) ) {
try{ Thread.sleep( 10 ); } catch( InterruptedException e ) {}
}
}
}
g.dispose();
}
} |
package database;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import casta.Casta;
import gson.CastaInstanceCreator;
import gson.EquipoInstanceCreator;
import gson.HabilidadInstanceCreator;
import gson.PersonajeInstanceCreator;
import habilidad.*;
import interfaces.Equipo;
import item.FactoriaItemLanzable;
import item.ItemEquipo;
import item.ItemLanzable;
import personaje.FactoriaPersonaje;
import personaje.Personaje;
public class SQLiteJDBC
{
private static SQLiteJDBC instance = null;
private static Connection c = null;
protected SQLiteJDBC() throws ClassNotFoundException, SQLException {
// Exists only to defeat instantiation.
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:juego.db");
c.setAutoCommit(false);
}
public boolean autenticarUsuario(String username, String password) throws SQLException{
Statement stmt = null;
username = username.toLowerCase();
boolean resultado = false;
stmt = c.createStatement();
String consulta = "SELECT id_player FROM jugadores WHERE username = '"+username+"' AND password = '"+password+"' LIMIT 1;";
ResultSet rs = stmt.executeQuery(consulta);
resultado = rs.next();
//boolean resultado = true;
/*while ( rs.next() ) {
int id = rs.getInt("id_player");
}*/
rs.close();
stmt.close();
return resultado;
}
public static Map<String,Habilidad> obtenerHabilidades() throws SQLException{
Statement stmt = null;
Map<String,Habilidad> habilidades = new HashMap<String,Habilidad>();
stmt = c.createStatement();
String consulta = "SELECT * FROM habilidad;";
ResultSet rs = stmt.executeQuery(consulta);
while ( rs.next() ) {
Habilidad aux = FactoriaHabilidades.getHabilidad(
rs.getString("nombre"), rs.getString("efecto"), rs.getString("descripcion"),
rs.getInt("costo"), rs.getInt("nivel"), rs.getInt("cantEfecto"), rs.getInt("velocidad"));
habilidades.put(rs.getString("key"), aux);
}
rs.close();
stmt.close();
return habilidades;
}
public static Map<String,ItemLanzable> obtenerLanzables() throws SQLException{
Statement stmt = null;
Map<String,ItemLanzable> lanzables = new HashMap<String,ItemLanzable>();
stmt = c.createStatement();
String consulta = "SELECT * FROM itemLanzable;";
ResultSet rs = stmt.executeQuery(consulta);
while ( rs.next() ) {
ItemLanzable aux = FactoriaItemLanzable.getItemLanzable(
rs.getString("key"), rs.getInt("nivel"),rs.getString("nombre"), rs.getString("descripcion"),
rs.getInt("cantEfecto"), rs.getString("efecto"),1, rs.getInt("velocidad"));
lanzables.put(rs.getString("key"), aux);
}
rs.close();
stmt.close();
return lanzables;
}
public static Map<String,ItemEquipo> obtenerEquipables() throws SQLException{
Statement stmt = null;
Map<String,ItemEquipo> equipables = new HashMap<String,ItemEquipo>();
stmt = c.createStatement();
String consulta = "SELECT * FROM itemEquipable;";
ResultSet rs = stmt.executeQuery(consulta);
while ( rs.next() ) {
ItemEquipo aux = new ItemEquipo(
rs.getString("key"), rs.getInt("nivel"), rs.getString("nombre"),
rs.getString("descripcion"),rs.getInt("fuerza"), rs.getInt("intelecto"),
rs.getInt("destreza"),rs.getInt("vitalidad"), rs.getInt("ataqueFisico"),
rs.getInt("ataqueMagico"),rs.getInt("defensaFisica"), rs.getInt("defensaMagica"),rs.getString("tipo"));
equipables.put(rs.getString("key"), aux);
}
rs.close();
stmt.close();
return equipables;
}
public boolean crearUsuario(String username, String password) throws SQLException{
Statement stmt = null;
username = username.toLowerCase();
stmt = c.createStatement();
String sql = "INSERT INTO jugadores (username,password) " +
"VALUES ('"+username+"', '"+password+"');";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
return true;
}
public boolean guardarPersonaje(Personaje per) throws SQLException{
Statement stmt = null;
final Gson gson = new Gson();
stmt = c.createStatement();
String sql = "UPDATE jugadores SET json = '" +
gson.toJson(per) +
"' WHERE username = '"+per.getNombre()+"';";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
return true;
}
public void cerrar() throws SQLException{
c.close();
}
public static SQLiteJDBC getInstance() throws ClassNotFoundException, SQLException {
if(instance == null) {
instance = new SQLiteJDBC();
}
return instance;
}
public Personaje getPersonaje(String username) throws SQLException {
Statement stmt = null;
username = username.toLowerCase();
Personaje resultado = null;
stmt = c.createStatement();
String consulta = "SELECT json FROM jugadores WHERE username = '"+username+"' LIMIT 1;";
ResultSet rs = stmt.executeQuery(consulta);
if(rs.next()){
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Casta.class, new CastaInstanceCreator());
gsonBuilder.registerTypeAdapter(Personaje.class, new PersonajeInstanceCreator());
gsonBuilder.registerTypeAdapter(Equipo.class, new EquipoInstanceCreator());
gsonBuilder.registerTypeAdapter(Habilidad.class,new HabilidadInstanceCreator());
Gson gson = gsonBuilder.create();
String stringRes = rs.getString("json");
resultado = gson.fromJson(stringRes, Personaje.class);
////resultado = FactoriaPersonaje.reconstruirPersonaje(resultado);
}
rs.close();
stmt.close();
return resultado;
}
} |
package edu.berkeley.eecs.emission.cordova.tracker.location.actions;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.support.v4.content.LocalBroadcastManager;
import edu.berkeley.eecs.emission.cordova.tracker.ConfigManager;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.NotificationHelper;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.LocationTrackingConfig;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import edu.berkeley.eecs.emission.cordova.tracker.location.GeofenceExitIntentService;
public class GeofenceActions {
private static final String GEOFENCE_REQUEST_ID = "DYNAMIC_EXIT_GEOFENCE";
private static final int GEOFENCE_IN_NUMBERS = 43633623; // GEOFENCE
// TODO: need to check what the definition of a city block is
// Apparently city block sizes vary dramatically depending on the city.
// this ranges from 79m in Portland to 120m in Sacramento.
// Let's pick 100 as a nice round number. If we are using this for privacy
// and not just battery life, it should really be dependent on the density
// of the location.
private static final String TAG = "CreateGeofenceAction";
private Context mCtxt;
private GoogleApiClient mGoogleApiClient;
// Used only when the last location from the manager is null, or invalid and so we have
// to read a new one. This is a private variable for synchronization
private Location newLastLocation;
public GeofenceActions(Context ctxt, GoogleApiClient googleApiClient) {
this.mCtxt = ctxt;
this.mGoogleApiClient = googleApiClient;
}
/*
* Actually creates the geofence. We want to create the geofence at the last known location, so
* we retrieve it from the location services. If this is not null, we call createGeofenceRequest to
* create the geofence request and register it.
*
* see @GeofenceActions.createGeofenceRequest
*/
public PendingResult<Status> create() {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
Log.d(mCtxt, TAG, "Last location would have been " + mLastLocation +" if we hadn't reset it");
if (isValidLocation(mCtxt, mLastLocation)) {
Log.d(mCtxt, TAG, "Last location is " + mLastLocation + " using it");
return createGeofenceAtLocation(mLastLocation);
} else {
Log.w(mCtxt, TAG, "mLastLocationTime = null, launching callback to read it and then" +
"create the geofence");
Location newLoc = readAndReturnCurrentLocation();
if (newLoc != null) {
Log.d(mCtxt, TAG, "New last location is " + newLoc + " using it");
return createGeofenceAtLocation(newLoc);
} else {
Log.d(mCtxt, TAG, "Was not able to read new location, skipping geofence creation");
return null;
}
}
}
private PendingResult<Status> createGeofenceAtLocation(Location currLoc) {
Log.d(mCtxt, TAG, "creating geofence at location " + currLoc);
// This is also an asynchronous call. We can either wait for the result,
// or we can provide a callback. Let's provide a callback to keep the async
// logic in place
return LocationServices.GeofencingApi.addGeofences(mGoogleApiClient,
createGeofenceRequest(currLoc.getLatitude(), currLoc.getLongitude()),
getGeofenceExitPendingIntent(mCtxt));
}
private Location readAndReturnCurrentLocation() {
Intent geofenceLocIntent = new Intent(mCtxt, GeofenceLocationIntentService.class);
final PendingIntent geofenceLocationIntent = PendingIntent.getService(mCtxt, 0,
geofenceLocIntent, PendingIntent.FLAG_UPDATE_CURRENT);
LocalBroadcastManager.getInstance(mCtxt).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
synchronized(GeofenceActions.this) {
GeofenceActions.this.newLastLocation = intent.getParcelableExtra(GeofenceLocationIntentService.INTENT_RESULT_KEY);
GeofenceActions.this.notify();
}
}
}, new IntentFilter(GeofenceLocationIntentService.INTENT_NAME));
PendingResult<Status> locationReadingResult =
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
getHighAccuracyHighFrequencyRequest(), geofenceLocationIntent);
Status result = locationReadingResult.await(1L, TimeUnit.MINUTES);
if (result.getStatusCode() == CommonStatusCodes.SUCCESS) {
Log.d(mCtxt, TAG, "Successfully started tracking location, about to start waiting for location update");
} else {
Log.w(mCtxt, TAG, "Error "+result+"while getting location, returning null ");
return null;
}
synchronized (this) {
try {
Log.d(mCtxt, TAG, "About to start waiting for location");
this.wait(10 * 60 * 1000); // 10 minutes * 60 secs * 1000 milliseconds
// If we stop the location tracking in the broadcast listener, before the notify, we can run into races
// in which the notify has happened before we start waiting, which means that we wait forever.
// Putting the stop in here means that we will continue to notify until the message is received
// which should be safe.
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, geofenceLocationIntent);
Log.d(mCtxt, TAG, "After waiting for location reading result, location is " + this.newLastLocation);
return this.newLastLocation;
} catch (InterruptedException e) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, geofenceLocationIntent);
Log.w(mCtxt, TAG, "Timed out waiting for location result, returning null ");
return null;
}
}
}
// Consistent with iOS, we say that the location is invalid if it is null, its accuracy is too low,
// or it is too old
static boolean isValidLocation(Context mCtxt, Location testLoc) {
if (testLoc == null) {
return false; // Duh!
}
LocationTrackingConfig cfg = ConfigManager.getConfig(mCtxt);
if (testLoc.getAccuracy() > cfg.getAccuracyThreshold()) {
return false; // too inaccurate. Note that a high accuracy number means a larger radius
// of validity which effectively means a low accuracy
}
int fiveMins = 5 * 60 * 1000;
if ((testLoc.getTime() - System.currentTimeMillis()) > fiveMins * 60) {
return false; // too old
}
return true;
}
private static LocationRequest getHighAccuracyHighFrequencyRequest() {
LocationRequest defaultRequest = LocationRequest.create();
return defaultRequest.setInterval(1)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void notifyFailure() {
Log.w(mCtxt, TAG,
"Unable to detect current location even after forcing, will retry at next sync");
NotificationHelper.createNotification(mCtxt, GEOFENCE_IN_NUMBERS,
"Unable to detect current location even after forcing, will retry at next sync");
}
/*
* Returns the geofence request object to be used with the geofencing API.
* Called from the previous create() call.
*/
public GeofencingRequest createGeofenceRequest(double lat, double lng) {
Log.d(mCtxt, TAG, "creating geofence at location "+lat+", "+lng);
LocationTrackingConfig cfg = ConfigManager.getConfig(this.mCtxt);
Geofence currGeofence =
new Geofence.Builder().setRequestId(GEOFENCE_REQUEST_ID)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setCircularRegion(lat, lng, cfg.getGeofenceRadius())
.setNotificationResponsiveness(cfg.getResponsiveness()) // 5 secs
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
.build();
return new GeofencingRequest.Builder()
.addGeofence(currGeofence)
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT)
.build();
}
public PendingResult<Status> remove() {
Log.d(mCtxt, TAG, "Removing geofence with ID = "+GEOFENCE_REQUEST_ID);
return LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient,
Arrays.asList(GEOFENCE_REQUEST_ID));
}
public static PendingIntent getGeofenceExitPendingIntent(Context ctxt) {
Intent innerIntent = new Intent(ctxt, GeofenceExitIntentService.class);
/*
* Setting FLAG_UPDATE_CURRENT so that sending the PendingIntent again updates the original.
* We only want to have one geofence active at one point of time.
*/
return PendingIntent.getService(ctxt, 0, innerIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.