answer
stringlengths
17
10.2M
package se.kth.nada.kmr.collaborilla.ldap; import java.net.URI; import java.net.URISyntaxException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.StringTokenizer; import com.novell.ldap.util.Base64; /** * Provides methods to do basic conversions and manipulations of URI and LDAP * Distinctive Name (DN) Strings. * <p> * All methods are also statically accessible. * * @author Hannes Ebner * @version $Id$ */ public class LDAPStringHelper { private String uri; private String serverDN; private String entryMainID = "ou"; private String root = null; /** * Using Base64 requires JLDAP to be in the classpath. It is in the package * com.novell.ldap.util.Base64. */ private static final int ENCODING_BASE64 = 1; private static final int ENCODING_ESCAPE = 2; private static final int ENCODING = ENCODING_ESCAPE; /* * Constructors */ /** * Initializes the object with the Distinctive Name (DN) of the LDAP server * connection and the URI which should be converted. * * @param serverDN * Distinctive Name (DN) of the server connection * @param uri * URI */ public LDAPStringHelper(String serverDN, String uri) { this.serverDN = serverDN; this.uri = uri; } /** * Initializes the object with the Distinctive Name (DN) of the LDAP server * connection, the URI which should be converted and the ID of the leaf * entry. * * @param serverDN * Distinctive Name (DN) of the server connection * @param uri * URI * @param entryMainID * Identifier of the leaf entry.&nbsp;Example: "cn" */ public LDAPStringHelper(String root, String serverDN, String uri, String entryMainID) { this(serverDN, uri); this.entryMainID = entryMainID; this.root = root; } /* * Setters for the private variables */ /** * Sets the URI. * * @param uri * URI */ public void setUri(String uri) { this.uri = uri; } /** * Sets the Server Distinctive Name (DN). * * @param serverDN * Server Distinctive Name (DN).&nbsp;Example: "dc=test,dc=com" */ public void setServerDN(String serverDN) { this.serverDN = serverDN; } /* * Getters for the private variables */ /** * Returns the current URI. * * @return URI */ public String getUri() { return this.uri; } /** * Returns the current server Distinctive Name (DN). * * @return Server Distinctive Name (DN) */ public String getServerDN() { return this.serverDN; } /** * Returns the Distinctive Name (DN) of the parent entry of the current URI. * * @return DN of the parent entry */ public String getParentDN() { return dnToParentDN(this.getBaseDN()); } /** * Returns the Distinctive Name (DN) of the parent entry. * * @param dn * DN of which the parent DN is demanded * @return DN of the parent entry */ public static String dnToParentDN(String dn) { return dn.substring(dn.indexOf(",") + 1); } /** * Converts a URI to a Distinctive Name (DN) and returns the parent DN. * * @param serverDN * Server Distinctive Name (DN) * @param uri * URI * @param entryMainID * Identifier of the leaf entry.&nbsp;Example: "cn" * @return Parent Distinctive Name (DN) */ public static String uriToParentDN(String root, String serverDN, String uri, String entryMainID) { return dnToParentDN(uriToBaseDN(root, serverDN, uri, entryMainID)); } /** * Get the ID of the LDAP Distinctive Name (DN) out of a URI or DN. Returns * for example "test", and not "cn=test". * * @return Relative DN of the LDAP entry */ public String getEntryID() { return dnToEntryID(this.getBaseDN()); } /** * Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns * for example "test", and not "cn=test". * * @param dn * Full Distinctive Name (DN) * @return Relative Distinctive Name (DN) */ public static String dnToEntryID(String dn) { return dn.substring(dn.indexOf("=") + 1, dn.indexOf(",")); } /** * Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns * for example "test", and not "cn=test". * * @param serverDN * Server Distinctive Name (DN) * @param uri * URI * @param entryMainID * Identifier of the leaf entry.&nbsp;Example: "cn" * @return Relative Distinctive Name (DN) */ public static String uriToEntryID(String root, String serverDN, String uri, String entryMainID) { return dnToEntryID(uriToBaseDN(root, serverDN, uri, entryMainID)); } /* * URI helpers */ /** * Constructs the parent out of a given URI. * * @param uri * A valid URI. * @return Returns a parent URI to the given one. Returns null if the URI is * toplevel already, or if the URI is invalid. */ public static String getParentURI(String uri) { String tmp = uri; // Perform a check whether this URI is valid: we convert it to a Java // URI and check for an exception. try { new URI(uri); } catch (URISyntaxException e) { // valid URI."); // We just return null for now return null; } if (tmp.endsWith("/")) { tmp = tmp.substring(0, tmp.length() - 2); } if (tmp.indexOf("/") == tmp.lastIndexOf("/")) { return null; } tmp = tmp.substring(0, tmp.lastIndexOf("/")); return tmp; } /* * URI -> DN conversion */ /** * Returns a Distinctive Name (DN). * * @return Base Distinctive Name (DN) */ public String getBaseDN() { return this.uriToBaseDN(); } /** * Converts a URI to a Distinctive Name (DN). * * @return Base Distinctive Name (DN) */ public String uriToBaseDN() { return uriToBaseDN(this.root, this.serverDN, this.uri, this.entryMainID); } /** * Converts a URI to a Distinctive Name (DN). * * @param serverDN * Server Distinctive Name (DN) * @param uriIn * URI * @param entryMainID * Identifier of the leaf entry.&nbsp;Example: "cn" * @return Base Distinctive Name (DN) */ public static String uriToBaseDN(String root, String serverDN, String uriIn, String entryMainID) { String checkSep1 = ": String checkSep2 = ":/"; String sep = checkSep2; String uri = null; int pos = -1; if (uriIn.indexOf("/") == -1) { return null; } if (uriIn.indexOf(checkSep1) > -1) { sep = checkSep1; } // workaround to avoid and IndexOutOfBoundsException String uriToConvert = uriIn + "/"; if ((pos = uriToConvert.indexOf(sep)) > -1) { /* construct a suitable uri out of a generic <type>:/[/]<path> */ /* get the type */ String type = uriToConvert.substring(0, pos); /* get the path and the host */ uri = uriToConvert.substring(pos + sep.length()); String hostPart = uri.substring(0, uri.indexOf("/")); uri = uri.substring(uri.indexOf("/")); /* split the host into TLD, second level domain, subdomain, etc */ StringTokenizer stHostPart = new StringTokenizer(hostPart, "."); while (stHostPart.hasMoreTokens()) { uri = "d:" + stHostPart.nextToken() + "/" + uri; } /* construct the generic uri */ uri = "/_" + type + "/" + uri; } else if (uriToConvert.startsWith("/")) { /* we already get a "good" uri */ uri = "/_generic" + uriToConvert; } else { return null; } if ((root != null) && (root.length() > 0)) { /* we prepend the root entry */ uri = "/" + root + uri; } /* finally we construct an LDAP Base DN */ String baseDN = new String(); StringTokenizer st = new StringTokenizer(uri, "/"); while (st.hasMoreTokens()) { baseDN = entryMainID + "=" + st.nextToken() + "," + baseDN; } return baseDN += serverDN; } /* * Other helpers */ /** * Encodes a given String. The type of "encoding" is hard-wired in the * header of this class. * * @param input * String in normal representation. * @return Encoded string. */ public static String encode(String input) { if (input == null) { return null; } switch (ENCODING) { case ENCODING_BASE64: String encodedString = Base64.encode(input.getBytes()); String escapedString = encodedString.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r"); return escapedString; case ENCODING_ESCAPE: return input.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r"); default: return input; } } /** * Decodes a given String to the original representation. The type of * "encoding" is hard-wired in the header of this class. * * @param input * Encoded string. * @return Decoded string. */ public static String decode(String input) { if (input == null) { return null; } switch (ENCODING) { case ENCODING_BASE64: String unescapedString = input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r"); String decodedString = new String(Base64.decode(unescapedString)); return decodedString; case ENCODING_ESCAPE: return input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r"); default: return input; } } /** * Parses an X.208 formatted timestamp and creates a Date object. * * @param utcTimestamp * X.208 formatted timestamp. * @return Converted Date object. */ public static Date parseTimestamp(String utcTimestamp) { Date date = null; // Setup a generalized X.208 date/time formatter DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); try { // parse UTC into Date date = formatter.parse(utcTimestamp); } catch (ParseException pe) { } return date; } }
package net.drewke.tdme.tools.shared.views; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import net.drewke.tdme.engine.Engine; import net.drewke.tdme.engine.Entity; import net.drewke.tdme.engine.ModelUtilities; import net.drewke.tdme.engine.Object3D; import net.drewke.tdme.engine.PartitionNone; import net.drewke.tdme.engine.fileio.models.DAEReader; import net.drewke.tdme.engine.fileio.models.TMReader; import net.drewke.tdme.engine.model.Model; import net.drewke.tdme.engine.primitives.BoundingBox; import net.drewke.tdme.engine.primitives.Capsule; import net.drewke.tdme.engine.primitives.ConvexMesh; import net.drewke.tdme.engine.primitives.OrientedBoundingBox; import net.drewke.tdme.engine.primitives.Sphere; import net.drewke.tdme.gui.events.GUIInputEventHandler; import net.drewke.tdme.math.Vector3; import net.drewke.tdme.tools.shared.controller.ModelViewerScreenController; import net.drewke.tdme.tools.shared.files.ModelMetaDataFileExport; import net.drewke.tdme.tools.shared.files.ModelMetaDataFileImport; import net.drewke.tdme.tools.shared.model.LevelEditorEntity; import net.drewke.tdme.tools.shared.model.LevelEditorEntityBoundingVolume; import net.drewke.tdme.tools.shared.model.PropertyModelClass; import net.drewke.tdme.tools.shared.tools.Tools; import com.jogamp.opengl.GLAutoDrawable; /** * TDME Model Viewer View * @author Andreas Drewke * @version $Id$ */ public class ModelViewerView extends View implements GUIInputEventHandler { private final int MODEL_BOUNDINGVOLUME_COUNT = 8; private final static String[] MODEL_BOUNDINGVOLUME_IDS = { "model_bv.0", "model_bv.1", "model_bv.2", "model_bv.3", "model_bv.4", "model_bv.5", "model_bv.6", "model_bv.7", }; protected Engine engine; private PopUps popUps; private ModelViewerScreenController modelViewerScreenController; private LevelEditorEntity entity; private boolean loadModelRequested; private boolean initModelRequested; private File modelFile; private boolean displayGroundPlate = false; private boolean displayShadowing = false; private boolean displayBoundingVolume = false; private CameraRotationInputHandler cameraRotationInputHandler; /** * Public constructor * @param pop ups view */ public ModelViewerView(PopUps popUps) { this.popUps = popUps; engine = Engine.getInstance(); modelViewerScreenController = null; loadModelRequested = false; initModelRequested = false; entity = null; modelFile = null; cameraRotationInputHandler = new CameraRotationInputHandler(engine); } /** * @return pop up views */ public PopUps getPopUpsViews() { return popUps; } /** * @return display ground plate */ public boolean isDisplayGroundPlate() { return displayGroundPlate; } /** * Set up ground plate visibility * @param ground plate visible */ public void setDisplayGroundPlate(boolean groundPlate) { this.displayGroundPlate = groundPlate; } /** * @return display shadowing */ public boolean isDisplayShadowing() { return displayShadowing; } /** * Set up shadow rendering * @param shadow rendering */ public void setDisplayShadowing(boolean shadowing) { this.displayShadowing = shadowing; } /** * @return display bounding volume */ public boolean isDisplayBoundingVolume() { return displayBoundingVolume; } /** * Set up bounding volume visibility * @param bounding volume */ public void setDisplayBoundingVolume(boolean displayBoundingVolume) { this.displayBoundingVolume = displayBoundingVolume; } /** * @return entity */ public LevelEditorEntity getEntity() { return entity; } /** * Set entity */ public void setEntity(LevelEditorEntity entity) { this.entity = entity; initModelRequested = true; } /** * Init model */ protected void initModel(GLAutoDrawable drawable) { if (entity == null) return; modelFile = new File(entity.getFileName()); // set up model in engine Tools.setupModel(entity, engine, cameraRotationInputHandler.getLookFromRotations(), cameraRotationInputHandler.getScale()); // Make model screenshot Tools.oseThumbnail(drawable, entity); // max axis dimension cameraRotationInputHandler.setMaxAxisDimension(Tools.computeMaxAxisDimension(entity.getModel().getBoundingBox())); // set up model statistics ModelUtilities.ModelStatistics stats = ModelUtilities.computeModelStatistics(entity.getModel()); modelViewerScreenController.setStatistics(stats.getOpaqueFaceCount(), stats.getTransparentFaceCount(), stats.getMaterialCount()); updateGUIElements(); } /** * Reset bounding volume * @param idx */ public void resetBoundingVolume(int idx) { // set up oriented bounding box BoundingBox aabb = entity.getModel().getBoundingBox(); OrientedBoundingBox obb = new OrientedBoundingBox(aabb); // set up sphere modelViewerScreenController.setupSphere( idx, obb.getCenter(), obb.getHalfExtension().computeLength() ); // set up capsule { Vector3 a = new Vector3(); Vector3 b = new Vector3(); float radius = 0.0f; float[] halfExtensionXYZ = obb.getHalfExtension().getArray(); // determine a, b if (halfExtensionXYZ[0] > halfExtensionXYZ[1] && halfExtensionXYZ[0] > halfExtensionXYZ[2]) { radius = (float)Math.sqrt(halfExtensionXYZ[1] * halfExtensionXYZ[1] + halfExtensionXYZ[2] * halfExtensionXYZ[2]); a.set(obb.getAxes()[0]); a.scale(-(halfExtensionXYZ[0] - radius)); a.add(obb.getCenter()); b.set(obb.getAxes()[0]); b.scale(+(halfExtensionXYZ[0] - radius)); b.add(obb.getCenter()); } else if (halfExtensionXYZ[1] > halfExtensionXYZ[0] && halfExtensionXYZ[1] > halfExtensionXYZ[2]) { radius = (float)Math.sqrt(halfExtensionXYZ[0] * halfExtensionXYZ[0] + halfExtensionXYZ[2] * halfExtensionXYZ[2]); a.set(obb.getAxes()[1]); a.scale(-(halfExtensionXYZ[1] - radius)); a.add(obb.getCenter()); b.set(obb.getAxes()[1]); b.scale(+(halfExtensionXYZ[1] - radius)); b.add(obb.getCenter()); } else { radius = (float)Math.sqrt(halfExtensionXYZ[0] * halfExtensionXYZ[0] + halfExtensionXYZ[1] * halfExtensionXYZ[1]); a.set(obb.getAxes()[2]); a.scale(-(halfExtensionXYZ[2] - radius)); a.add(obb.getCenter()); b.set(obb.getAxes()[2]); b.scale(+(halfExtensionXYZ[2] - radius)); b.add(obb.getCenter()); } // setup capsule modelViewerScreenController.setupCapsule(idx,a, b, radius); } // set up AABB bounding box modelViewerScreenController.setupBoundingBox(idx, aabb.getMin(), aabb.getMax()); // set up oriented bounding box modelViewerScreenController.setupOrientedBoundingBox( idx, obb.getCenter(), obb.getAxes()[0], obb.getAxes()[1], obb.getAxes()[2], obb.getHalfExtension() ); modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.NONE); } /** * Set bounding volumes */ private void setBoundingVolumes() { // set up default bounding volumes for (int i = 0; i < MODEL_BOUNDINGVOLUME_COUNT; i++) { resetBoundingVolume(i); } // set up existing bounding volumes for (int i = 0; i < entity.getBoundingVolumeCount(); i++) { LevelEditorEntityBoundingVolume bv = entity.getBoundingVolumeAt(i); if (bv == null) { modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.NONE); continue; } else if (bv.getBoundingVolume() instanceof Sphere) { Sphere sphere = (Sphere)bv.getBoundingVolume(); modelViewerScreenController.setupSphere(i, sphere.getCenter(), sphere.getRadius()); modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.SPHERE); } else if (bv.getBoundingVolume() instanceof Capsule) { Capsule capsule = (Capsule)bv.getBoundingVolume(); modelViewerScreenController.setupCapsule(i, capsule.getA(), capsule.getB(), capsule.getRadius()); modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.CAPSULE); } else if (bv.getBoundingVolume() instanceof BoundingBox) { BoundingBox aabb = (BoundingBox)bv.getBoundingVolume(); modelViewerScreenController.setupBoundingBox(i, aabb.getMin(), aabb.getMax()); modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.BOUNDINGBOX); } else if (bv.getBoundingVolume() instanceof OrientedBoundingBox) { OrientedBoundingBox obb = (OrientedBoundingBox)bv.getBoundingVolume(); modelViewerScreenController.setupOrientedBoundingBox( i, obb.getCenter(), obb.getAxes()[0], obb.getAxes()[1], obb.getAxes()[2], obb.getHalfExtension() ); modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.ORIENTEDBOUNDINGBOX); } else if (bv.getBoundingVolume() instanceof ConvexMesh) { modelViewerScreenController.setupConvexMesh(i, bv.getModelMeshFile()); modelViewerScreenController.selectBoundingVolume(i, ModelViewerScreenController.BoundingVolumeType.CONVEXMESH); } // enable bounding volume and set type in GUI modelViewerScreenController.enableBoundingVolume(i); modelViewerScreenController.setupModelBoundingVolumeType(i); } } /** * Unset bounding volumes */ private void unsetBoundingVolumes() { for (int i = 0; i < MODEL_BOUNDINGVOLUME_COUNT; i++) { modelViewerScreenController.disableBoundingVolume(i); } } /** * @return current model file name */ public String getFileName() { if (modelFile == null) return ""; return modelFile.getName(); } /** * Issue file loading */ public void loadFile(String pathName, String fileName) { loadModelRequested = true; modelFile = new File(pathName, fileName); } /** * Triggers saving a map */ public void saveFile(String pathName, String fileName) throws Exception { ModelMetaDataFileExport.export(new File(pathName, fileName).getCanonicalPath(), entity); } /** * Issue file reloading */ public void reloadFile() { loadModelRequested = true; } /** * Apply pivot * @param x * @param y * @param z */ public void pivotApply(float x, float y, float z) { if (entity == null) return; entity.getPivot().set(x, y, z); } /* * (non-Javadoc) * @see net.drewke.tdme.gui.events.GUIInputEventHandler#handleInputEvents() */ public void handleInputEvents() { cameraRotationInputHandler.handleInputEvents(); } /** * Renders the scene */ public void display(GLAutoDrawable drawable) { // load model if (loadModelRequested == true) { initModelRequested = true; loadModelRequested = false; loadModel(); cameraRotationInputHandler.reset(); } // init model if (initModelRequested == true) { engine.reset(); initModel(drawable); initModelRequested = false; } // apply settings from gui if (entity != null) { Entity model = engine.getEntity("model"); Entity ground = engine.getEntity("ground"); model.setDynamicShadowingEnabled(displayShadowing); ground.setEnabled(displayGroundPlate); for (int i = 0; i < MODEL_BOUNDINGVOLUME_IDS.length; i++) { Entity modelBoundingVolume = engine.getEntity(MODEL_BOUNDINGVOLUME_IDS[i]); if (modelBoundingVolume != null) { modelBoundingVolume.setEnabled(displayBoundingVolume); } } } // do GUI engine.getGUI().render(); engine.getGUI().handleEvents(); } /** * Init GUI elements */ public void updateGUIElements() { if (entity != null) { modelViewerScreenController.setScreenCaption("Model Viewer - " + entity.getName()); PropertyModelClass preset = entity.getProperty("preset"); modelViewerScreenController.setEntityProperties(preset != null ? preset.getValue() : null, entity.getProperties(), null); modelViewerScreenController.setEntityData(entity.getName(), entity.getDescription()); modelViewerScreenController.setPivot(entity.getPivot()); setBoundingVolumes(); } else { modelViewerScreenController.setScreenCaption("Model Viewer - no entity loaded"); modelViewerScreenController.unsetEntityProperties(); modelViewerScreenController.unsetEntityData(); modelViewerScreenController.unsetPivot(); unsetBoundingVolumes(); } } /** * Store settings */ private void storeSettings() { FileOutputStream fos = null; try { fos = new FileOutputStream("./settings/modelviewer.properties"); Properties settings = new Properties(); settings.put("display.boundingvolumes", displayBoundingVolume == true?"true":"false"); settings.put("display.groundplate", displayGroundPlate?"true":"false"); settings.put("display.shadowing", displayShadowing?"true":"false"); settings.put("model.path", modelViewerScreenController.getModelPath()); settings.store(fos, null); fos.close(); } catch (Exception ioe) { if (fos != null) try { fos.close(); } catch (IOException ioeInner) {} ioe.printStackTrace(); } } /** * Shutdown */ public void dispose(GLAutoDrawable drawable) { // store settings storeSettings(); // reset engine Engine.getInstance().reset(); } /** * On init additional screens * @param drawable */ public void onInitAdditionalScreens() { } /** * Load settings */ private void loadSettings() { // read settings FileInputStream fis = null; Object tmp; try { fis = new FileInputStream("./settings/modelviewer.properties"); Properties settings = new Properties(); settings.load(fis); displayBoundingVolume = (tmp = settings.get("display.boundingvolumes")) != null?tmp.equals("true") == true:false; displayGroundPlate = (tmp = settings.get("display.groundplate")) != null?tmp.equals("true") == true:false; displayShadowing = (tmp = settings.get("display.shadowing")) != null?tmp.equals("true") == true:false; modelViewerScreenController.setModelPath((tmp = settings.get("model.path")) != null?tmp.toString():""); fis.close(); } catch (Exception ioe) { if (fis != null) try { fis.close(); } catch (IOException ioeInner) {} ioe.printStackTrace(); } } /** * Initialize */ public void init(GLAutoDrawable drawable) { // reset engine and partition engine.reset(); engine.setPartition(new PartitionNone()); try { modelViewerScreenController = new ModelViewerScreenController(this); modelViewerScreenController.init(); engine.getGUI().addScreen(modelViewerScreenController.getScreenNode().getId(), modelViewerScreenController.getScreenNode()); modelViewerScreenController.getScreenNode().setInputEventHandler(this); } catch (Exception e) { e.printStackTrace(); } // load settings loadSettings(); // set up display modelViewerScreenController.setupDisplay(); // set up bounding volume types for (int i = 0; i < MODEL_BOUNDINGVOLUME_COUNT; i++) { modelViewerScreenController.setupBoundingVolumeTypes( i, new String[] { "None", "Sphere", "Capsule", "Bounding Box", "Oriented Bounding Box", "Convex Mesh" } ); modelViewerScreenController.selectBoundingVolume( i, ModelViewerScreenController.BoundingVolumeType.NONE ); } // set up gui updateGUIElements(); engine.getGUI().resetRenderScreens(); engine.getGUI().addRenderScreen(modelViewerScreenController.getScreenNode().getId()); onInitAdditionalScreens(); engine.getGUI().addRenderScreen(popUps.getFileDialogScreenController().getScreenNode().getId()); engine.getGUI().addRenderScreen(popUps.getInfoDialogScreenController().getScreenNode().getId()); } /** * On load model * @param oldModel * @oaram entity */ public void onLoadModel(LevelEditorEntity oldModel, LevelEditorEntity model) { } /** * Load a model */ private void loadModel() { System.out.println("Model file: " + modelFile); // scene try { LevelEditorEntity oldModel = entity; // add entity to library entity = loadModel( modelFile.getName(), "", modelFile.getParentFile().getAbsolutePath(), modelFile.getName(), new Vector3() ); onLoadModel(oldModel, entity); } catch (Exception exception) { popUps.getInfoDialogScreenController().show("Warning", exception.getMessage()); } } /** * Select bounding volume type * @param idx * @param bounding volume type */ public void selectBoundingVolumeType(int idx, int bvTypeId) { switch (bvTypeId) { case 0: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.NONE); break; case 1: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.SPHERE); break; case 2: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.CAPSULE); break; case 3: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.BOUNDINGBOX); break; case 4: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.ORIENTEDBOUNDINGBOX); break; case 5: modelViewerScreenController.selectBoundingVolume(idx, ModelViewerScreenController.BoundingVolumeType.CONVEXMESH); break; } } /** * Load model * @param name * @param description * @param path name * @param file name * @param pivot * @return level editor entity * @throws Exception */ protected LevelEditorEntity loadModel(String name, String description, String pathName, String fileName, Vector3 pivot) throws Exception { if (fileName.toLowerCase().endsWith(".dae")) { Model model = DAEReader.read(modelFile.getParentFile().getCanonicalPath(), modelFile.getName()); BoundingBox boundingBox = ModelUtilities.createBoundingBox(model); LevelEditorEntity levelEditorEntity = new LevelEditorEntity( LevelEditorEntity.ID_NONE, LevelEditorEntity.EntityType.MODEL, name, description, null, pathName + File.separator + fileName, model.getId(). replace("\\", "_"). replace("/", "_"). replace(":", "_") + ".png", model, pivot ); levelEditorEntity.setDefaultBoundingVolumes(); return levelEditorEntity; } else if (fileName.toLowerCase().endsWith(".tm")) { Model model = TMReader.read(modelFile.getParentFile().getCanonicalPath(), modelFile.getName()); BoundingBox boundingBox = ModelUtilities.createBoundingBox(model); LevelEditorEntity levelEditorEntity = new LevelEditorEntity( LevelEditorEntity.ID_NONE, LevelEditorEntity.EntityType.MODEL, name, description, null, pathName + File.separator + fileName, model.getId(). replace("\\", "_"). replace("/", "_"). replace(":", "_") + ".png", model, pivot ); levelEditorEntity.setDefaultBoundingVolumes(); return levelEditorEntity; } else if (fileName.toLowerCase().endsWith(".tmm")) { LevelEditorEntity levelEditorEntity = ModelMetaDataFileImport.doImport( LevelEditorEntity.ID_NONE, pathName, fileName ); levelEditorEntity.setDefaultBoundingVolumes(); return levelEditorEntity; } return null; } /** * Update model bounding volume * @param entity */ private void updateModelBoundingVolume(int idx) { LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); // remove old bv String id = MODEL_BOUNDINGVOLUME_IDS[idx]; Entity modelBoundingVolumeObject = engine.getEntity(id); if (modelBoundingVolumeObject != null) { engine.removeEntity(id); } // add new bv if (entityBoundingVolume.getModel() == null) return; modelBoundingVolumeObject = new Object3D(id, entityBoundingVolume.getModel()); modelBoundingVolumeObject.setEnabled(displayBoundingVolume); engine.addEntity(modelBoundingVolumeObject); } /** * On bounding volume none apply * @param bounding volume index */ public void applyBoundingVolumeNone(int idx) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupNone(); updateModelBoundingVolume(idx); } /** * On bounding volume sphere apply * @param bounding volume index * @param sphere center * @param radius */ public void applyBoundingVolumeSphere(int idx, Vector3 center, float radius) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupSphere(center, radius); updateModelBoundingVolume(idx); } /** * On bounding volume capsule apply * @param bounding volume index * @param point a * @param point b * @param radius */ public void applyBoundingVolumeCapsule(int idx, Vector3 a, Vector3 b, float radius) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupCapsule(a, b, radius); updateModelBoundingVolume(idx); } /** * On bounding volume AABB apply * @param bounding volume index * @param AABB min vector * @param AABB max vector */ public void applyBoundingVolumeAabb(int idx, Vector3 min, Vector3 max) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupAabb(min, max); updateModelBoundingVolume(idx); } /** * On bounding volume OBB apply * @param bounding volume index * @param OBB center * @param OBB axis 0 * @param OBB axis 1 * @param OBB axis 2 * @param OBB half extension */ public void applyBoundingVolumeObb(int idx, Vector3 center, Vector3 axis0, Vector3 axis1, Vector3 axis2, Vector3 halfExtension) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupObb(center, axis0, axis1, axis2, halfExtension); updateModelBoundingVolume(idx); } /** * On bounding volume convex mesh apply * @param bounding volume index * @param file */ public void applyBoundingVolumeConvexMesh(int idx, String file) { // exit if no entity if (entity == null) return; LevelEditorEntityBoundingVolume entityBoundingVolume = entity.getBoundingVolumeAt(idx); entityBoundingVolume.setupConvexMesh(file); updateModelBoundingVolume(idx); } /** * On set entity data hook */ public void onSetEntityData() { } }
package com.gmail.nossr50.listeners; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.inventory.ItemStack; import com.gmail.nossr50.Combat; import com.gmail.nossr50.Users; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.LoadProperties; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.datatypes.SkillType; import com.gmail.nossr50.locale.mcLocale; import com.gmail.nossr50.party.Party; import com.gmail.nossr50.skills.Acrobatics; import com.gmail.nossr50.skills.BlastMining; import com.gmail.nossr50.skills.Skills; import com.gmail.nossr50.skills.Taming; public class mcEntityListener implements Listener { private final mcMMO plugin; public mcEntityListener(final mcMMO plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { //Check for world pvp flag if(event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent eventb = (EntityDamageByEntityEvent)event; if(eventb.getEntity() instanceof Player && eventb.getDamager() instanceof Player && !event.getEntity().getWorld().getPVP()) return; } /* * CHECK FOR INVULNERABILITY */ if(event.getEntity() instanceof Player) { Player defender = (Player)event.getEntity(); PlayerProfile PPd = Users.getProfile(defender); if(defender != null && PPd.getGodMode()) event.setCancelled(true); if(PPd == null) Users.addUser(defender); } /* * Demolitions Expert */ if(event.getCause() == DamageCause.BLOCK_EXPLOSION) { if(event.getEntity() instanceof Player) { Player player = (Player)event.getEntity(); BlastMining.demolitionsExpertise(player, event); } } if(event.getEntity() instanceof LivingEntity) { { LivingEntity entityliving = (LivingEntity)event.getEntity(); if(entityliving.getNoDamageTicks() < entityliving.getMaximumNoDamageTicks()/2.0F) { Entity x = event.getEntity(); DamageCause type = event.getCause(); if(event.getEntity() instanceof Wolf && ((Wolf)event.getEntity()).isTamed() && Taming.getOwner(((Wolf)event.getEntity()), plugin) != null) { Wolf theWolf = (Wolf) event.getEntity(); Player master = Taming.getOwner(theWolf, plugin); PlayerProfile PPo = Users.getProfile(master); if(master == null || PPo == null) return; //Environmentally Aware if((event.getCause() == DamageCause.CONTACT || event.getCause() == DamageCause.LAVA || event.getCause() == DamageCause.FIRE) && PPo.getSkillLevel(SkillType.TAMING) >= 100) { if(event.getDamage() < ((Wolf) event.getEntity()).getHealth()) { event.getEntity().teleport(Taming.getOwner(theWolf, plugin).getLocation()); master.sendMessage(mcLocale.getString("mcEntityListener.WolfComesBack")); //$NON-NLS-1$ event.getEntity().setFireTicks(0); } } if(event.getCause() == DamageCause.FALL && PPo.getSkillLevel(SkillType.TAMING) >= 100) { event.setCancelled(true); } //Thick Fur if(event.getCause() == DamageCause.FIRE_TICK) { event.getEntity().setFireTicks(0); } } /* * ACROBATICS */ if(x instanceof Player){ Player player = (Player)x; if(type == DamageCause.FALL){ Acrobatics.acrobaticsCheck(player, event); } } /* * Entity Damage by Entity checks */ if(event instanceof EntityDamageByEntityEvent && !event.isCancelled()) { EntityDamageByEntityEvent eventb = (EntityDamageByEntityEvent) event; Entity f = eventb.getDamager(); Entity e = event.getEntity(); /* * PARTY CHECKS */ if(e instanceof Player && f instanceof Player) { Player defender = (Player)e; Player attacker = (Player)f; if(Party.getInstance().inSameParty(defender, attacker)) event.setCancelled(true); } Combat.combatChecks(event, plugin); } /* * Check to see if the defender took damage so we can apply recently hurt */ if(event.getEntity() instanceof Player) { Player herpderp = (Player)event.getEntity(); if(!event.isCancelled() && event.getDamage() >= 1) { Users.getProfile(herpderp).setRecentlyHurt(System.currentTimeMillis()); } } } } } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { Entity x = event.getEntity(); x.setFireTicks(0); //Remove bleed track if(plugin.misc.bleedTracker.contains((LivingEntity)x)) plugin.misc.addToBleedRemovalQue((LivingEntity)x); Skills.arrowRetrievalCheck(x, plugin); if(x instanceof Player){ Player player = (Player)x; Users.getProfile(player).setBleedTicks(0); } } @EventHandler public void onCreatureSpawn(CreatureSpawnEvent event) { SpawnReason reason = event.getSpawnReason(); if(reason == SpawnReason.SPAWNER && !LoadProperties.xpGainsMobSpawners) { plugin.misc.mobSpawnerList.add(event.getEntity()); } } @EventHandler (priority = EventPriority.LOW) public void onExplosionPrime(ExplosionPrimeEvent event) { if(event.getEntity() instanceof TNTPrimed) { Block block = event.getEntity().getLocation().getBlock(); if(plugin.misc.tntTracker.get(block) != null) { int skillLevel = plugin.misc.tntTracker.get(block); BlastMining.biggerBombs(skillLevel, event); } } } @EventHandler (priority = EventPriority.LOW) public void onEnitityExplode(EntityExplodeEvent event) { if(event.getEntity() instanceof TNTPrimed) { Block block = event.getLocation().getBlock(); if(plugin.misc.tntTracker.get(block) != null) { int skillLevel = plugin.misc.tntTracker.get(block); BlastMining.dropProcessing(skillLevel, event, plugin); } } } @EventHandler (priority = EventPriority.LOW) public void onFoodLevelChange(FoodLevelChangeEvent event) { if(event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); PlayerProfile PP = Users.getProfile(player); int currentFoodLevel = player.getFoodLevel(); int newFoodLevel = event.getFoodLevel(); if(newFoodLevel > currentFoodLevel) { int food = player.getItemInHand().getTypeId(); if(food == 297 || food == 357 || food == 360 || food == 282) { int foodChange = newFoodLevel - currentFoodLevel; int herbLevel = PP.getSkillLevel(SkillType.HERBALISM); if(herbLevel < 200) foodChange = foodChange + 1; if(herbLevel >= 200 && herbLevel < 400) foodChange = foodChange + 2; if(herbLevel >= 400 && herbLevel < 600) foodChange = foodChange + 3; if(herbLevel >= 600 && herbLevel < 800) foodChange = foodChange + 4; if(herbLevel >= 800 && herbLevel < 1000) foodChange = foodChange + 5; if(herbLevel >= 1000) foodChange = foodChange + 6; newFoodLevel = currentFoodLevel + foodChange; if(newFoodLevel > 20) event.setFoodLevel(20); if(newFoodLevel <= 20) event.setFoodLevel(newFoodLevel); } } } } public boolean isBow(ItemStack is){ if (is.getTypeId() == 261){ return true; } else { return false; } } public boolean isPlayer(Entity entity){ if (entity instanceof Player) { return true; } else{ return false; } } }
package net.java.sip.communicator.launcher; import com.apple.eio.*; /** * A simple implementation of the BrowserLauncherService. Checks the operating * system and launches the appropriate browser. * * @author Yana Stamcheva */ public class BrowserLauncher { /** * Creates a <tt>LaunchBrowser</tt> thread for the specified <tt>url</tt>. * * @param url the url we'd like to launch a browser for. */ public void openURL(String url) { new LaunchBrowser(url).start(); } /** * Launch browser in a separate thread. */ private static class LaunchBrowser extends Thread { /** * The URL we'd be launching a browser for. */ private final String url; /** * Creates a new instance. * * @param url the url we'd like to launch a browser for. */ public LaunchBrowser(String url) { this.url = url; } /** * On mac, asks FileManager to open the the url, on Windows uses * FileProtocolHandler to do so, on Linux, loops through a list of * known browsers until we find one that seems to work. */ @SuppressWarnings("deprecation") //FileManager.openURL - no choice public void run() { try { /* * XXX The detection of the operating systems is the * responsibility of OSUtils. It used to reside in the util.jar * which is in the classpath but it is now in libjitsi.jar which * is not in the classpath. */ String osName = System.getProperty("os.name"); if ((osName != null) && osName.startsWith("Mac")) { FileManager.openURL(url); } else if ((osName != null) && osName.startsWith("Windows")) { Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url); } else { /* Linux and other Unix systems */ String[] browsers = {"firefox", "iceweasel", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; String browser = null; for (int i = 0; i < browsers.length && browser == null; i ++) { if (Runtime.getRuntime().exec( new String[] {"which", browsers[i]}).waitFor() == 0) browser = browsers[i]; } if (browser == null) throw new Exception("Could not find web browser"); else Runtime.getRuntime().exec(new String[] {browser, url}); } } catch (Exception e) { e.printStackTrace(); } } } }
package com.googlecode.javaewah; import java.util.*; import java.io.*; public final class EWAHCompressedBitmap implements Cloneable, Externalizable, Iterable<Integer>, BitmapStorage, LogicalElement<EWAHCompressedBitmap> { /** * Creates an empty bitmap (no bit set to true). */ public EWAHCompressedBitmap() { this.buffer = new long[defaultbuffersize]; this.rlw = new RunningLengthWord(this.buffer, 0); } /** * Sets explicitly the buffer size (in 64-bit words). The initial memory usage * will be "buffersize * 64". For large poorly compressible bitmaps, using * large values may improve performance. * * @param buffersize * number of 64-bit words reserved when the object is created) */ public EWAHCompressedBitmap(final int buffersize) { this.buffer = new long[buffersize]; this.rlw = new RunningLengthWord(this.buffer, 0); } /** * Adding words directly to the bitmap (for expert use). * * This is normally how you add data to the array. So you add bits in streams * of 8*8 bits. * * Example: if you add 321, you are have added (in binary notation) * 0b101000001, so you have effectively called set(0), set(6), set(8) * in sequence. * * @param newdata * the word */ public void add(final long newdata) { add(newdata, wordinbits); } /** * Adding words directly to the bitmap (for expert use). * * @param newdata * the word * @param bitsthatmatter * the number of significant bits (by default it should be 64) */ public void add(final long newdata, final int bitsthatmatter) { this.sizeinbits += bitsthatmatter; if (newdata == 0) { addEmptyWord(false); } else if (newdata == ~0l) { addEmptyWord(true); } else { addLiteralWord(newdata); } } /** * For internal use. * * @param v * the boolean value */ private void addEmptyWord(final boolean v) { final boolean noliteralword = (this.rlw.getNumberOfLiteralWords() == 0); final long runlen = this.rlw.getRunningLength(); if ((noliteralword) && (runlen == 0)) { this.rlw.setRunningBit(v); } if ((noliteralword) && (this.rlw.getRunningBit() == v) && (runlen < RunningLengthWord.largestrunninglengthcount)) { this.rlw.setRunningLength(runlen + 1); return; } push_back(0); this.rlw.position = this.actualsizeinwords - 1; this.rlw.setRunningBit(v); this.rlw.setRunningLength(1); return; } /** * For internal use. * * @param newdata * the literal word */ private void addLiteralWord(final long newdata) { final int numbersofar = this.rlw.getNumberOfLiteralWords(); if (numbersofar >= RunningLengthWord.largestliteralcount) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; this.rlw.setNumberOfLiteralWords(1); push_back(newdata); } this.rlw.setNumberOfLiteralWords(numbersofar + 1); push_back(newdata); } /** * if you have several literal words to copy over, this might be faster. * * * @param data * the literal words * @param start * the starting point in the array * @param number * the number of literal words to add */ public void addStreamOfLiteralWords(final long[] data, final int start, final int number) { int leftovernumber = number; while(leftovernumber > 0) { final int NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords(); final int whatwecanadd = number < RunningLengthWord.largestliteralcount - NumberOfLiteralWords ? number : RunningLengthWord.largestliteralcount - NumberOfLiteralWords; this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd); leftovernumber -= whatwecanadd; push_back(data, start, whatwecanadd); this.sizeinbits += whatwecanadd * wordinbits; if (leftovernumber > 0) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; } } } /** * For experts: You want to add many zeroes or ones? This is the method you * use. * * @param v * the boolean value * @param number * the number */ public void addStreamOfEmptyWords(final boolean v, long number) { if (number == 0) return; this.sizeinbits += number * wordinbits; if ((this.rlw.getRunningBit() != v) && (this.rlw.size() == 0)) { this.rlw.setRunningBit(v); } else if ((this.rlw.getNumberOfLiteralWords() != 0) || (this.rlw.getRunningBit() != v)) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); } final long runlen = this.rlw.getRunningLength(); final long whatwecanadd = number < RunningLengthWord.largestrunninglengthcount - runlen ? number : RunningLengthWord.largestrunninglengthcount - runlen; this.rlw.setRunningLength(runlen + whatwecanadd); number -= whatwecanadd; while (number >= RunningLengthWord.largestrunninglengthcount) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); this.rlw.setRunningLength(RunningLengthWord.largestrunninglengthcount); number -= RunningLengthWord.largestrunninglengthcount; } if (number > 0) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); this.rlw.setRunningLength(number); } } /** * Same as addStreamOfLiteralWords, but the words are negated. * * @param data * the literal words * @param start * the starting point in the array * @param number * the number of literal words to add */ public void addStreamOfNegatedLiteralWords(final long[] data, final int start, final int number) { int leftovernumber = number; while (leftovernumber > 0) { final int NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords(); final int whatwecanadd = number < RunningLengthWord.largestliteralcount - NumberOfLiteralWords ? number : RunningLengthWord.largestliteralcount - NumberOfLiteralWords; this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd); leftovernumber -= whatwecanadd; negative_push_back(data, start, whatwecanadd); this.sizeinbits += whatwecanadd * wordinbits; if (leftovernumber > 0) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; } } } /** * Returns a new compressed bitmap containing the bitwise AND values of the * current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * If you are not planning on adding to the resulting bitmap, you may call the trim() * method to reduce memory usage. * * @since 0.4.3 * @param a * the other bitmap * @return the EWAH compressed bitmap */ public EWAHCompressedBitmap and(final EWAHCompressedBitmap a) { final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); container .reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords : a.actualsizeinwords); andToContainer(a, container); return container; } /** * Computes new compressed bitmap containing the bitwise AND values of the * current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * @since 0.4.0 * @param a * the other bitmap * @param container * where we store the result */ public void andToContainer(final EWAHCompressedBitmap a, final BitmapStorage container) { final EWAHIterator i = a.getEWAHIterator(); final EWAHIterator j = getEWAHIterator(); final IteratingBufferedRunningLengthWord rlwi = new IteratingBufferedRunningLengthWord(i); final IteratingBufferedRunningLengthWord rlwj = new IteratingBufferedRunningLengthWord(j); while ((rlwi.size()>0) && (rlwj.size()>0)) { while ((rlwi.getRunningLength() > 0) || (rlwj.getRunningLength() > 0)) { final boolean i_is_prey = rlwi.getRunningLength() < rlwj .getRunningLength(); final IteratingBufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj; final IteratingBufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi; if (predator.getRunningBit() == false) { container.addStreamOfEmptyWords(false, predator.getRunningLength()); prey.discardFirstWords(predator.getRunningLength()); predator.discardFirstWords(predator.getRunningLength()); } else { final long index = prey.discharge(container, predator.getRunningLength()); container.addStreamOfEmptyWords(false, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } } final int nbre_literal = Math.min(rlwi.getNumberOfLiteralWords(), rlwj.getNumberOfLiteralWords()); if (nbre_literal > 0) { for (int k = 0; k < nbre_literal; ++k) container.add(rlwi.getLiteralWordAt(k) & rlwj.getLiteralWordAt(k)); rlwi.discardFirstWords(nbre_literal); rlwj.discardFirstWords(nbre_literal); } } if(adjustContainerSizeWhenAggregating) { final boolean i_remains = rlwi.size()>0; final IteratingBufferedRunningLengthWord remaining = i_remains ? rlwi : rlwj; remaining.dischargeAsEmpty(container); container.setSizeInBits(Math.max(sizeInBits(), a.sizeInBits())); } } /** * Returns the cardinality of the result of a bitwise AND of the values of the * current bitmap with some other bitmap. Avoids needing to allocate an * intermediate bitmap to hold the result of the OR. * * @since 0.4.0 * @param a * the other bitmap * @return the cardinality */ public int andCardinality(final EWAHCompressedBitmap a) { final BitCounter counter = new BitCounter(); andToContainer(a, counter); return counter.getCount(); } /** * Returns a new compressed bitmap containing the bitwise AND NOT values of * the current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * If you are not planning on adding to the resulting bitmap, you may call the trim() * method to reduce memory usage. * * @param a * the other bitmap * @return the EWAH compressed bitmap */ public EWAHCompressedBitmap andNot(final EWAHCompressedBitmap a) { final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); container .reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords : a.actualsizeinwords); andNotToContainer(a, container); return container; } /** * Returns a new compressed bitmap containing the bitwise AND NOT values of * the current bitmap with some other bitmap. This method is expected to * be faster than doing A.and(((EWAHCompressedBitmap) B.clone()).not()). * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * @since 0.4.0 * @param a the other bitmap * @param container where to store the result */ public void andNotToContainer(final EWAHCompressedBitmap a, final BitmapStorage container) { final EWAHIterator i = getEWAHIterator(); final EWAHIterator j = a.getEWAHIterator(); final IteratingBufferedRunningLengthWord rlwi = new IteratingBufferedRunningLengthWord(i); final IteratingBufferedRunningLengthWord rlwj = new IteratingBufferedRunningLengthWord(j); while ((rlwi.size()>0) && (rlwj.size()>0)) { while ((rlwi.getRunningLength() > 0) || (rlwj.getRunningLength() > 0)) { final boolean i_is_prey = rlwi.getRunningLength() < rlwj .getRunningLength(); final IteratingBufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj; final IteratingBufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi; if ( ((predator.getRunningBit() == true) && (i_is_prey)) || ((predator.getRunningBit() == false) && (!i_is_prey))){ container.addStreamOfEmptyWords(false, predator.getRunningLength()); prey.discardFirstWords(predator.getRunningLength()); predator.discardFirstWords(predator.getRunningLength()); } else if (i_is_prey) { long index = prey.discharge(container, predator.getRunningLength()); container.addStreamOfEmptyWords(false, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } else { long index = prey.dischargeNegated(container, predator.getRunningLength()); container.addStreamOfEmptyWords(true, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } } final int nbre_literal = Math.min(rlwi.getNumberOfLiteralWords(), rlwj.getNumberOfLiteralWords()); if (nbre_literal > 0) { for (int k = 0; k < nbre_literal; ++k) container.add(rlwi.getLiteralWordAt(k) & (~rlwj.getLiteralWordAt(k))); rlwi.discardFirstWords(nbre_literal); rlwj.discardFirstWords(nbre_literal); } } final boolean i_remains = rlwi.size()>0; final IteratingBufferedRunningLengthWord remaining = i_remains ? rlwi : rlwj; if(i_remains) remaining.discharge(container); else if(adjustContainerSizeWhenAggregating) remaining.dischargeAsEmpty(container); if(adjustContainerSizeWhenAggregating) container.setSizeInBits(Math.max(sizeInBits(), a.sizeInBits())); } /** * Returns the cardinality of the result of a bitwise AND NOT of the values of * the current bitmap with some other bitmap. Avoids needing to allocate an * intermediate bitmap to hold the result of the OR. * * @since 0.4.0 * @param a * the other bitmap * @return the cardinality */ public int andNotCardinality(final EWAHCompressedBitmap a) { final BitCounter counter = new BitCounter(); andNotToContainer(a, counter); return counter.getCount(); } /** * reports the number of bits set to true. Running time is proportional to * compressed size (as reported by sizeInBytes). * * @return the number of bits set to true */ public int cardinality() { int counter = 0; final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); while (i.hasNext()) { RunningLengthWord localrlw = i.next(); if (localrlw.getRunningBit()) { counter += wordinbits * localrlw.getRunningLength(); } for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) { counter += Long.bitCount(i.buffer()[i.literalWords() + j]); } } return counter; } /** * Clear any set bits and set size in bits back to 0 */ public void clear() { this.sizeinbits = 0; this.actualsizeinwords = 1; this.rlw.position = 0; // buffer is not fully cleared but any new set operations should overwrite // stale data this.buffer[0] = 0; } /* * @see java.lang.Object#clone() */ @Override public EWAHCompressedBitmap clone() throws java.lang.CloneNotSupportedException { final EWAHCompressedBitmap clone = (EWAHCompressedBitmap) super.clone(); clone.buffer = this.buffer.clone(); clone.rlw = new RunningLengthWord(clone.buffer, this.rlw.position); clone.actualsizeinwords = this.actualsizeinwords; clone.sizeinbits = this.sizeinbits; return clone; } /** * Deserialize. * * @param in * the DataInput stream * @throws IOException * Signals that an I/O exception has occurred. */ public void deserialize(DataInput in) throws IOException { this.sizeinbits = in.readInt(); this.actualsizeinwords = in.readInt(); if (this.buffer.length < this.actualsizeinwords) { this.buffer = new long[this.actualsizeinwords]; } for (int k = 0; k < this.actualsizeinwords; ++k) this.buffer[k] = in.readLong(); this.rlw = new RunningLengthWord(this.buffer, in.readInt()); } /** * Check to see whether the two compressed bitmaps contain the same set bits. * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (o instanceof EWAHCompressedBitmap) { try { this.xorToContainer((EWAHCompressedBitmap) o, new NonEmptyVirtualStorage()); return true; } catch (NonEmptyVirtualStorage.NonEmptyException e) { return false; } } return false; } /** * For experts: You want to add many zeroes or ones faster? * * This method does not update sizeinbits. * * @param v * the boolean value * @param number * the number (must be greater than 0) */ private void fastaddStreamOfEmptyWords(final boolean v, long number) { if ((this.rlw.getRunningBit() != v) && (this.rlw.size() == 0)) { this.rlw.setRunningBit(v); } else if ((this.rlw.getNumberOfLiteralWords() != 0) || (this.rlw.getRunningBit() != v)) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); } final long runlen = this.rlw.getRunningLength(); final long whatwecanadd = number < RunningLengthWord.largestrunninglengthcount - runlen ? number : RunningLengthWord.largestrunninglengthcount - runlen; this.rlw.setRunningLength(runlen + whatwecanadd); number -= whatwecanadd; while (number >= RunningLengthWord.largestrunninglengthcount) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); this.rlw.setRunningLength(RunningLengthWord.largestrunninglengthcount); number -= RunningLengthWord.largestrunninglengthcount; } if (number > 0) { push_back(0); this.rlw.position = this.actualsizeinwords - 1; if (v) this.rlw.setRunningBit(v); this.rlw.setRunningLength(number); } } /** * Gets an EWAHIterator over the data. This is a customized iterator which * iterates over run length word. For experts only. * * @return the EWAHIterator */ public EWAHIterator getEWAHIterator() { return new EWAHIterator(this.buffer, this.actualsizeinwords); } /** * @return the IteratingRLW iterator corresponding to this bitmap */ public IteratingRLW getIteratingRLW() { return new IteratingBufferedRunningLengthWord(this); } /** * get the locations of the true values as one vector. (may use more memory * than iterator()) * * @return the positions */ public List<Integer> getPositions() { final ArrayList<Integer> v = new ArrayList<Integer>(); final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); int pos = 0; while (i.hasNext()) { RunningLengthWord localrlw = i.next(); if (localrlw.getRunningBit()) { for (int j = 0; j < localrlw.getRunningLength(); ++j) { for (int c = 0; c < wordinbits; ++c) v.add(new Integer(pos++)); } } else { pos += wordinbits * localrlw.getRunningLength(); } for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) { long data = i.buffer()[i.literalWords() + j]; while (data != 0) { final int ntz = Long.numberOfTrailingZeros(data); data ^= (1l << ntz); v.add(new Integer(ntz + pos)); } pos += wordinbits; } } while ((v.size() > 0) && (v.get(v.size() - 1).intValue() >= this.sizeinbits)) v.remove(v.size() - 1); return v; } /** * Returns a customized hash code (based on Karp-Rabin). Naturally, if the * bitmaps are equal, they will hash to the same value. * */ @Override public int hashCode() { int karprabin = 0; final int B = 31; final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); while( i.hasNext() ) { i.next(); if (i.rlw.getRunningBit() == true) { karprabin += B * karprabin + (i.rlw.getRunningLength() & ((1l << 32) - 1)); karprabin += B * karprabin + (i.rlw.getRunningLength() >>> 32); } for (int k = 0; k < i.rlw.getNumberOfLiteralWords(); ++k) { karprabin += B * karprabin + (this.buffer[i.literalWords() + k] & ((1l << 32) - 1)); karprabin += B * karprabin + (this.buffer[i.literalWords() + k] >>> 32); } } return karprabin; } /** * Return true if the two EWAHCompressedBitmap have both at least one true bit * in the same position. Equivalently, you could call "and" and check whether * there is a set bit, but intersects will run faster if you don't need the * result of the "and" operation. * * @since 0.3.2 * @param a * the other bitmap * @return whether they intersect */ public boolean intersects(final EWAHCompressedBitmap a) { NonEmptyVirtualStorage nevs = new NonEmptyVirtualStorage(); try { this.andToContainer(a, nevs); } catch (NonEmptyVirtualStorage.NonEmptyException nee) { return true; } return false; } /** * Iterator over the set bits (this is what most people will want to use to * browse the content if they want an iterator). The location of the set bits * is returned, in increasing order. * * @return the int iterator */ public IntIterator intIterator() { return new IntIteratorImpl( new EWAHIterator(this.buffer, this.actualsizeinwords)); } /** * iterate over the positions of the true values. This is similar to * intIterator(), but it uses Java generics. * * @return the iterator */ public Iterator<Integer> iterator() { return new Iterator<Integer>() { public boolean hasNext() { return this.under.hasNext(); } public Integer next() { return new Integer(this.under.next()); } public void remove() { throw new UnsupportedOperationException("bitsets do not support remove"); } final private IntIterator under = intIterator(); }; } /** * For internal use. * * @param data * the array of words to be added * @param start * the starting point * @param number * the number of words to add */ private void negative_push_back(final long[] data, final int start, final int number) { while (this.actualsizeinwords + number >= this.buffer.length) { final long oldbuffer[] = this.buffer; if((this.actualsizeinwords + number) < 32768) this.buffer = new long[ (this.actualsizeinwords + number) * 2]; else if((this.actualsizeinwords + number) * 3 / 2 < this.actualsizeinwords + number) // overflow this.buffer = new long[Integer.MAX_VALUE]; else this.buffer = new long[(this.actualsizeinwords + number) * 3 / 2]; System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length); this.rlw.array = this.buffer; } for (int k = 0; k < number; ++k) this.buffer[this.actualsizeinwords + k] = ~data[start + k]; this.actualsizeinwords += number; } /** * Negate (bitwise) the current bitmap. To get a negated copy, do * EWAHCompressedBitmap x= ((EWAHCompressedBitmap) mybitmap.clone()); x.not(); * * The running time is proportional to the compressed size (as reported by * sizeInBytes()). * */ public void not() { final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); if (!i.hasNext()) return; while (true) { final RunningLengthWord rlw1 = i.next(); rlw1.setRunningBit(!rlw1.getRunningBit()); for (int j = 0; j < rlw1.getNumberOfLiteralWords(); ++j) { i.buffer()[i.literalWords() + j] = ~i.buffer()[i.literalWords() + j]; } if (!i.hasNext()) {// must potentially adjust the last literal word final int usedbitsinlast = this.sizeinbits % wordinbits; if (usedbitsinlast == 0) return; if (rlw1.getNumberOfLiteralWords() == 0) { if((rlw1.getRunningLength()>0) && (rlw1.getRunningBit())) { rlw1.setRunningLength(rlw1.getRunningLength()-1); this.addLiteralWord((~0l) >>> (wordinbits - usedbitsinlast)); } return; } i.buffer()[i.literalWords() + rlw1.getNumberOfLiteralWords() - 1] &= ((~0l) >>> (wordinbits - usedbitsinlast)); return; } } } /** * Returns a new compressed bitmap containing the bitwise OR values of the * current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * If you are not planning on adding to the resulting bitmap, you may call the trim() * method to reduce memory usage. * * @param a * the other bitmap * @return the EWAH compressed bitmap */ public EWAHCompressedBitmap or(final EWAHCompressedBitmap a) { final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); container.reserve(this.actualsizeinwords + a.actualsizeinwords); orToContainer(a, container); return container; } /** * Computes the bitwise or between the current bitmap and the bitmap "a". * Stores the result in the container. * * @since 0.4.0 * @param a * the other bitmap * @param container * where we store the result */ public void orToContainer(final EWAHCompressedBitmap a, final BitmapStorage container) { final EWAHIterator i = a.getEWAHIterator(); final EWAHIterator j = getEWAHIterator(); final IteratingBufferedRunningLengthWord rlwi = new IteratingBufferedRunningLengthWord(i); final IteratingBufferedRunningLengthWord rlwj = new IteratingBufferedRunningLengthWord(j); while ((rlwi.size()>0) && (rlwj.size()>0)) { while ((rlwi.getRunningLength() > 0) || (rlwj.getRunningLength() > 0)) { final boolean i_is_prey = rlwi.getRunningLength() < rlwj .getRunningLength(); final IteratingBufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj; final IteratingBufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi; if (predator.getRunningBit() == true) { container.addStreamOfEmptyWords(true, predator.getRunningLength()); prey.discardFirstWords(predator.getRunningLength()); predator.discardFirstWords(predator.getRunningLength()); } else { long index = prey.discharge(container, predator.getRunningLength()); container.addStreamOfEmptyWords(false, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } } final int nbre_literal = Math.min(rlwi.getNumberOfLiteralWords(), rlwj.getNumberOfLiteralWords()); if (nbre_literal > 0) { for (int k = 0; k < nbre_literal; ++k) { container.add(rlwi.getLiteralWordAt(k) | rlwj.getLiteralWordAt(k)); } rlwi.discardFirstWords(nbre_literal); rlwj.discardFirstWords(nbre_literal); } } final boolean i_remains = rlwi.size()>0; final IteratingBufferedRunningLengthWord remaining = i_remains ? rlwi : rlwj; remaining.discharge(container); container.setSizeInBits(Math.max(sizeInBits(), a.sizeInBits())); } /** * Returns the cardinality of the result of a bitwise OR of the values of the * current bitmap with some other bitmap. Avoids needing to allocate an * intermediate bitmap to hold the result of the OR. * * @since 0.4.0 * @param a * the other bitmap * @return the cardinality */ public int orCardinality(final EWAHCompressedBitmap a) { final BitCounter counter = new BitCounter(); orToContainer(a, counter); return counter.getCount(); } /** * For internal use. * * @param data * the word to be added */ private void push_back(final long data) { if (this.actualsizeinwords == this.buffer.length) { final long oldbuffer[] = this.buffer; if(oldbuffer.length < 32768) this.buffer = new long[ oldbuffer.length * 2]; else if(oldbuffer.length * 3 / 2 < oldbuffer.length) // overflow this.buffer = new long[Integer.MAX_VALUE]; else this.buffer = new long[oldbuffer.length * 3 / 2]; System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length); this.rlw.array = this.buffer; } this.buffer[this.actualsizeinwords++] = data; } /** * For internal use. * * @param data * the array of words to be added * @param start * the starting point * @param number * the number of words to add */ private void push_back(final long[] data, final int start, final int number) { if (this.actualsizeinwords + number >= this.buffer.length) { final long oldbuffer[] = this.buffer; if(this.actualsizeinwords + number < 32768) this.buffer = new long[(this.actualsizeinwords + number) * 2]; else if ((this.actualsizeinwords + number) * 3 / 2 < this.actualsizeinwords + number) // overflow this.buffer = new long[Integer.MAX_VALUE]; else this.buffer = new long[( this.actualsizeinwords + number) * 3 / 2]; System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length); this.rlw.array = this.buffer; } System.arraycopy(data, start, this.buffer, this.actualsizeinwords, number); this.actualsizeinwords += number; } /* * @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ public void readExternal(ObjectInput in) throws IOException { deserialize(in); } /** * For internal use (trading off memory for speed). * * @param size * the number of words to allocate * @return True if the operation was a success. */ private boolean reserve(final int size) { if (size > this.buffer.length) { final long oldbuffer[] = this.buffer; this.buffer = new long[size]; System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length); this.rlw.array = this.buffer; return true; } return false; } /** * Serialize. * * @param out * the DataOutput stream * @throws IOException * Signals that an I/O exception has occurred. */ public void serialize(DataOutput out) throws IOException { out.writeInt(this.sizeinbits); out.writeInt(this.actualsizeinwords); for (int k = 0; k < this.actualsizeinwords; ++k) out.writeLong(this.buffer[k]); out.writeInt(this.rlw.position); } /** * Report the size required to serialize this bitmap * * @return the size in bytes */ public int serializedSizeInBytes() { return this.sizeInBytes() + 3 * 4; } /** * set the bit at position i to true, the bits must be set in increasing * order. For example, set(15) and then set(7) will fail. You must do set(7) * and then set(15). * * @param i * the index * @return true if the value was set (always true when i greater or equal to sizeInBits()). * @throws IndexOutOfBoundsException * if i is negative or greater than Integer.MAX_VALUE - 64 */ public boolean set(final int i) { if ((i > Integer.MAX_VALUE - wordinbits) || (i < 0)) throw new IndexOutOfBoundsException("Set values should be between 0 and " + (Integer.MAX_VALUE - wordinbits)); if (i < this.sizeinbits) return false; // distance in words: final int dist = (i + wordinbits) / wordinbits - (this.sizeinbits + wordinbits - 1) / wordinbits; this.sizeinbits = i + 1; if (dist > 0) {// easy if (dist > 1) fastaddStreamOfEmptyWords(false, dist - 1); addLiteralWord(1l << (i % wordinbits)); return true; } if (this.rlw.getNumberOfLiteralWords() == 0) { this.rlw.setRunningLength(this.rlw.getRunningLength() - 1); addLiteralWord(1l << (i % wordinbits)); return true; } this.buffer[this.actualsizeinwords - 1] |= 1l << (i % wordinbits); if (this.buffer[this.actualsizeinwords - 1] == ~0l) { this.buffer[this.actualsizeinwords - 1] = 0; --this.actualsizeinwords; this.rlw.setNumberOfLiteralWords(this.rlw.getNumberOfLiteralWords() - 1); // next we add one clean word addEmptyWord(true); } return true; } /** * Set the size in bits. This does not change the compressed bitmap. * * @since 0.4.0 */ public void setSizeInBits(final int size) { this.sizeinbits = size; } /** * Change the reported size in bits of the *uncompressed* bitmap represented * by this compressed bitmap. It may change the underlying compressed bitmap. * It is not possible to reduce the sizeInBits, but * it can be extended. The new bits are set to false or true depending on the * value of defaultvalue. * * @param size * the size in bits * @param defaultvalue * the default boolean value * @return true if the update was possible */ public boolean setSizeInBits(final int size, final boolean defaultvalue) { if (size < this.sizeinbits) return false; if (defaultvalue == false) extendEmptyBits(this, this.sizeinbits, size); else { // next bit could be optimized while (((this.sizeinbits % wordinbits) != 0) && (this.sizeinbits < size)) { this.set(this.sizeinbits); } this.addStreamOfEmptyWords(defaultvalue, (size / wordinbits) - this.sizeinbits / wordinbits); // next bit could be optimized while (this.sizeinbits < size) { this.set(this.sizeinbits); } } this.sizeinbits = size; return true; } /** * Returns the size in bits of the *uncompressed* bitmap represented by this * compressed bitmap. Initially, the sizeInBits is zero. It is extended * automatically when you set bits to true. * * @return the size in bits */ public int sizeInBits() { return this.sizeinbits; } /** * Report the *compressed* size of the bitmap (equivalent to memory usage, * after accounting for some overhead). * * @return the size in bytes */ public int sizeInBytes() { return this.actualsizeinwords * (wordinbits / 8); } /** * Populate an array of (sorted integers) corresponding to the location of the * set bits. * * @return the array containing the location of the set bits */ public int[] toArray() { int[] ans = new int[this.cardinality()]; int inanspos = 0; int pos = 0; final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); while (i.hasNext()) { RunningLengthWord localrlw = i.next(); if (localrlw.getRunningBit()) { for (int j = 0; j < localrlw.getRunningLength(); ++j) { for (int c = 0; c < wordinbits; ++c) { ans[inanspos++] = pos++; } } } else { pos += wordinbits * localrlw.getRunningLength(); } for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) { long data = i.buffer()[i.literalWords() + j]; if (!usetrailingzeros) { for (int c = 0; c < wordinbits; ++c) { if ((data & (1l << c)) != 0) ans[inanspos++] = c + pos; } pos += wordinbits; } else { while (data != 0) { final int ntz = Long.numberOfTrailingZeros(data); data ^= (1l << ntz); ans[inanspos++] = ntz + pos; } pos += wordinbits; } } } return ans; } /** * A more detailed string describing the bitmap (useful for debugging). * * @return the string */ public String toDebugString() { String ans = " EWAHCompressedBitmap, size in bits = " + this.sizeinbits + " size in words = " + this.actualsizeinwords + "\n"; final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords); while (i.hasNext()) { RunningLengthWord localrlw = i.next(); if (localrlw.getRunningBit()) { ans += localrlw.getRunningLength() + " 1x11\n"; } else { ans += localrlw.getRunningLength() + " 0x00\n"; } ans += localrlw.getNumberOfLiteralWords() + " dirties\n"; for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) { long data = i.buffer()[i.literalWords() + j]; ans += "\t" + data + "\n"; } } return ans; } /** * A string describing the bitmap. * * @return the string */ @Override public String toString() { StringBuffer answer = new StringBuffer(); IntIterator i = this.intIterator(); answer.append("{"); if (i.hasNext()) answer.append(i.next()); while (i.hasNext()) { answer.append(","); answer.append(i.next()); } answer.append("}"); return answer.toString(); } /** * swap the content of the bitmap with another. * @param other bitmap to swap with */ public void swap(final EWAHCompressedBitmap other) { long[] tmp = this.buffer; this.buffer = other.buffer; other.buffer = tmp; RunningLengthWord tmp2 = this.rlw; this.rlw = other.rlw; other.rlw = tmp2; int tmp3 = this.actualsizeinwords; this.actualsizeinwords = other.actualsizeinwords; other.actualsizeinwords = tmp3; int tmp4 = this.sizeinbits; this.sizeinbits = other.sizeinbits; other.sizeinbits = tmp4; } /** * Reduce the internal buffer to its minimal allowable size (given * by this.actualsizeinwords). This can free memory. */ public void trim() { this.buffer = Arrays.copyOf(this.buffer, this.actualsizeinwords); } /* * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ public void writeExternal(ObjectOutput out) throws IOException { serialize(out); } /** * Returns a new compressed bitmap containing the bitwise XOR values of the * current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * If you are not planning on adding to the resulting bitmap, you may call the trim() * method to reduce memory usage. * * @param a * the other bitmap * @return the EWAH compressed bitmap */ public EWAHCompressedBitmap xor(final EWAHCompressedBitmap a) { final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); container.reserve(this.actualsizeinwords + a.actualsizeinwords); xorToContainer(a, container); return container; } /** * Computes a new compressed bitmap containing the bitwise XOR values of the * current bitmap with some other bitmap. * * The running time is proportional to the sum of the compressed sizes (as * reported by sizeInBytes()). * * @since 0.4.0 * @param a * the other bitmap * @param container * where we store the result */ public void xorToContainer(final EWAHCompressedBitmap a, final BitmapStorage container) { final EWAHIterator i = a.getEWAHIterator(); final EWAHIterator j = getEWAHIterator(); final IteratingBufferedRunningLengthWord rlwi = new IteratingBufferedRunningLengthWord(i); final IteratingBufferedRunningLengthWord rlwj = new IteratingBufferedRunningLengthWord(j); while ((rlwi.size()>0) && (rlwj.size()>0)) { while ((rlwi.getRunningLength() > 0) || (rlwj.getRunningLength() > 0)) { final boolean i_is_prey = rlwi.getRunningLength() < rlwj .getRunningLength(); final IteratingBufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj; final IteratingBufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi; if (predator.getRunningBit() == false) { long index = prey.discharge(container, predator.getRunningLength()); container.addStreamOfEmptyWords(false, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } else { long index = prey.dischargeNegated(container, predator.getRunningLength()); container.addStreamOfEmptyWords(true, predator.getRunningLength() - index); predator.discardFirstWords(predator.getRunningLength()); } } final int nbre_literal = Math.min(rlwi.getNumberOfLiteralWords(), rlwj.getNumberOfLiteralWords()); if (nbre_literal > 0) { for (int k = 0; k < nbre_literal; ++k) container.add(rlwi.getLiteralWordAt(k) ^ rlwj.getLiteralWordAt(k)); rlwi.discardFirstWords(nbre_literal); rlwj.discardFirstWords(nbre_literal); } } final boolean i_remains = rlwi.size()>0; final IteratingBufferedRunningLengthWord remaining = i_remains ? rlwi : rlwj; remaining.discharge(container); container.setSizeInBits(Math.max(sizeInBits(), a.sizeInBits())); } /** * Returns the cardinality of the result of a bitwise XOR of the values of the * current bitmap with some other bitmap. Avoids needing to allocate an * intermediate bitmap to hold the result of the OR. * * @since 0.4.0 * @param a * the other bitmap * @return the cardinality */ public int xorCardinality(final EWAHCompressedBitmap a) { final BitCounter counter = new BitCounter(); xorToContainer(a, counter); return counter.getCount(); } /** * For internal use. Computes the bitwise and of the provided bitmaps and * stores the result in the container. * * @param container * where the result is stored * @param bitmaps * bitmaps to AND * @since 0.4.3 */ public static void andWithContainer(final BitmapStorage container, final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) throw new IllegalArgumentException("Need at least one bitmap"); if(bitmaps.length == 2) { bitmaps[0].andToContainer(bitmaps[1],container); return; } EWAHCompressedBitmap answer = new EWAHCompressedBitmap(); EWAHCompressedBitmap tmp = new EWAHCompressedBitmap(); bitmaps[0].andToContainer(bitmaps[1], answer); for(int k = 2; k < bitmaps.length - 1; ++k) { answer.andToContainer(bitmaps[k], tmp); tmp.swap(answer); tmp.clear(); } answer.andToContainer(bitmaps[bitmaps.length - 1], container); } public static EWAHCompressedBitmap and(final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) return bitmaps[0]; if(bitmaps.length == 2) return bitmaps[0].and(bitmaps[1]); EWAHCompressedBitmap answer = new EWAHCompressedBitmap(); EWAHCompressedBitmap tmp = new EWAHCompressedBitmap(); bitmaps[0].andToContainer(bitmaps[1], answer); for(int k = 2; k < bitmaps.length; ++k) { answer.andToContainer(bitmaps[k], tmp); tmp.swap(answer); tmp.clear(); } return answer; } /** * Returns the cardinality of the result of a bitwise AND of the values of the * provided bitmaps. Avoids needing to allocate an intermediate bitmap to hold * the result of the AND. * * @since 0.4.3 * @param bitmaps * bitmaps to AND * @return the cardinality */ public static int andCardinality(final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) return bitmaps[0].cardinality(); final BitCounter counter = new BitCounter(); andWithContainer(counter, bitmaps); return counter.getCount(); } /** * Return a bitmap with the bit set to true at the given * positions. The positions should be given in sorted order. * * (This is a convenience method.) * * @since 0.4.5 * @param setbits list of set bit positions * @return the bitmap */ public static EWAHCompressedBitmap bitmapOf(int ... setbits) { EWAHCompressedBitmap a = new EWAHCompressedBitmap(); for (int k : setbits) a.set(k); return a; } /** * For internal use. This simply adds a stream of words made of zeroes so that * we pad to the desired size. * * @param storage * bitmap to extend * @param currentSize * current size (in bits) * @param newSize * new desired size (in bits) * @since 0.4.3 */ private static void extendEmptyBits(final BitmapStorage storage, final int currentSize, final int newSize) { final int currentLeftover = currentSize % wordinbits; final int finalLeftover = newSize % wordinbits; storage.addStreamOfEmptyWords(false, (newSize / wordinbits) - currentSize / wordinbits + (finalLeftover != 0 ? 1 : 0) + (currentLeftover != 0 ? -1 : 0)); } /** * Uses an adaptive technique to compute the logical OR. * Mostly for internal use. * * @param container where the aggregate is written. * @param bitmaps to be aggregated */ public static void orWithContainer(final BitmapStorage container, final EWAHCompressedBitmap... bitmaps) { if (bitmaps.length < 2) throw new IllegalArgumentException("You should provide at least two bitmaps, provided "+bitmaps.length); long size = 0L; long sinbits = 0L; for (EWAHCompressedBitmap b : bitmaps) { size += b.sizeInBytes(); if (sinbits < b.sizeInBits()) sinbits = b.sizeInBits(); } if (size * 8 > sinbits) { FastAggregation.bufferedorWithContainer(container, 65536, bitmaps); } else { FastAggregation.orToContainer(container, bitmaps); } } /** * Uses an adaptive technique to compute the logical XOR. * Mostly for internal use. * * @param container where the aggregate is written. * @param bitmaps to be aggregated */ public static void xorWithContainer(final BitmapStorage container, final EWAHCompressedBitmap... bitmaps) { if (bitmaps.length < 2) throw new IllegalArgumentException("You should provide at least two bitmaps, provided "+bitmaps.length); long size = 0L; long sinbits = 0L; for (EWAHCompressedBitmap b : bitmaps) { size += b.sizeInBytes(); if (sinbits < b.sizeInBits()) sinbits = b.sizeInBits(); } if (size * 8 > sinbits) { FastAggregation.bufferedxorWithContainer(container, 65536, bitmaps); } else { FastAggregation.xorToContainer(container, bitmaps); } } public static EWAHCompressedBitmap or(final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) return bitmaps[0]; final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); int largestSize = 0; for (EWAHCompressedBitmap bitmap : bitmaps) { largestSize = Math.max(bitmap.actualsizeinwords, largestSize); } container.reserve((int) (largestSize * 1.5)); orWithContainer(container, bitmaps); return container; } public static EWAHCompressedBitmap xor(final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) return bitmaps[0]; final EWAHCompressedBitmap container = new EWAHCompressedBitmap(); int largestSize = 0; for (EWAHCompressedBitmap bitmap : bitmaps) { largestSize = Math.max(bitmap.actualsizeinwords, largestSize); } container.reserve((int) (largestSize * 1.5)); xorWithContainer(container, bitmaps); return container; } /** * Returns the cardinality of the result of a bitwise OR of the values of the * provided bitmaps. Avoids needing to allocate an intermediate bitmap to hold * the result of the OR. * * @since 0.4.0 * @param bitmaps * bitmaps to OR * @return the cardinality */ public static int orCardinality(final EWAHCompressedBitmap... bitmaps) { if(bitmaps.length == 1) return bitmaps[0].cardinality(); final BitCounter counter = new BitCounter(); orWithContainer(counter, bitmaps); return counter.getCount(); } /** The actual size in words. */ int actualsizeinwords = 1; /** The buffer (array of 64-bit words) */ long buffer[] = null; /** The current (last) running length word. */ RunningLengthWord rlw = null; /** sizeinbits: number of bits in the (uncompressed) bitmap. */ int sizeinbits = 0; /** * The Constant defaultbuffersize: default memory allocation when the object * is constructed. */ static final int defaultbuffersize = 4; /** optimization option **/ public static final boolean usetrailingzeros = true; /** whether we adjust after some aggregation by adding in zeroes **/ public static final boolean adjustContainerSizeWhenAggregating = false; /** The Constant wordinbits represents the number of bits in a long. */ public static final int wordinbits = 64; }
package com.client.core.base.tools.test; import com.bullhorn.apiservice.query.DtoQuery; import com.bullhorn.entity.AbstractDto; import com.bullhorn.entity.ApiEntityName; import com.bullhorn.entity.candidate.CandidateEducationDto; import com.bullhorn.entity.candidate.CandidateReferenceDto; import com.bullhorn.entity.candidate.CandidateWorkHistoryDto; import com.bullhorn.entity.job.JobOrderDto; import com.bullhornsdk.data.api.BullhornData; import com.client.core.ApplicationSettings; import com.client.core.formtrigger.model.form.impl.*; import com.client.core.formtrigger.workflow.traversing.impl.*; import com.client.core.scheduledtasks.model.helper.CustomSubscriptionEvent; import com.client.core.scheduledtasks.tools.enumeration.EventType; import com.client.core.scheduledtasks.workflow.traversing.impl.*; import com.client.core.soap.service.BullhornAPI; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import java.text.DateFormat; import java.util.*; public class TestUtil { @Autowired private TestEntities testEntities; @Autowired private BullhornAPI bullhornApi; @Autowired private BullhornData bullhornData; @Autowired @Qualifier("appSettings") private ApplicationSettings appSettings; public TestUtil() { super(); } public static CustomSubscriptionEvent event(Integer entityID, ApiEntityName entityName, EventType eventType, String[] updatedProperties, Integer updatingUserID) { CustomSubscriptionEvent event = new CustomSubscriptionEvent(); event.setEntityId(entityID); event.setEntityName(entityName.value()); event.setEventType(eventType.value()); event.setUpdatingUserId(updatingUserID); if(updatedProperties != null) { event.setUpdatedProperties(Sets.newHashSet(updatedProperties)); } return event; } public JobSubmissionEventTraverser jobSubmissionEventTraverser(EventType eventType, String[] updatedProperties) { CustomSubscriptionEvent event = TestUtil.event(getTestEntities().getJobSubmissionId(), ApiEntityName.JOB_SUBMISSION, eventType, updatedProperties, getTestEntities().getCorporateUserId()); return jobSubmissionEventTraverser(event); } public SendoutEventTraverser sendoutEventTraverser(EventType eventType, String[] updatedProperties) { CustomSubscriptionEvent event = TestUtil.event(getTestEntities().getSendoutId(), ApiEntityName.SENDOUT, eventType, updatedProperties, getTestEntities().getCorporateUserId()); return sendoutEventTraverser(event); } public PlacementEventTraverser placementEventTraverser(EventType eventType, String[] updatedProperties) { CustomSubscriptionEvent event = TestUtil.event(getTestEntities().getPlacementId(), ApiEntityName.PLACEMENT, eventType, updatedProperties, getTestEntities().getCorporateUserId()); return placementEventTraverser(event); } public JobEventTraverser jobEventTraverser(EventType eventType, String[] updatedProperties) { CustomSubscriptionEvent event = TestUtil.event(getTestEntities().getJobOrderId(), ApiEntityName.JOB_ORDER, eventType, updatedProperties, getTestEntities().getCorporateUserId()); return jobEventTraverser(event); } public JobSubmissionEventTraverser jobSubmissionEventTraverser(CustomSubscriptionEvent event) { return new JobSubmissionEventTraverser(event, bullhornData); } public PlacementEventTraverser placementEventTraverser(CustomSubscriptionEvent event) { return new PlacementEventTraverser(event, bullhornData); } public PlacementChangeRequestEventTraverser placementChangeRequestEventTraverser(CustomSubscriptionEvent event) { return new PlacementChangeRequestEventTraverser(event, bullhornData); } public CandidateEventTraverser candidateEventTraverser(CustomSubscriptionEvent event) { return new CandidateEventTraverser(event, bullhornData); } public ClientContactEventTraverser clientContactEventTraverser(CustomSubscriptionEvent event) { return new ClientContactEventTraverser(event, bullhornData); } public SendoutEventTraverser sendoutEventTraverser(CustomSubscriptionEvent event) { return new SendoutEventTraverser(event, bullhornData); } public JobEventTraverser jobEventTraverser(CustomSubscriptionEvent event) { return new JobEventTraverser(event, bullhornData); } public JobSubmissionFormTriggerTraverser getJobSubmissionFormTriggerTraverser(String status, int candidateID) { FormJobSubmissionDto dto = new FormJobSubmissionDto(); dto.setComments("Comments on submission"); dto.setJobPostingID(getTestEntities().getJobOrderId().toString()); dto.setJobResponseID(getTestEntities().getJobSubmissionId()); dto.setSendingUserID(2); dto.setUserID(candidateID+""); dto.setStatus(status); JobSubmissionFormTriggerTraverser traverser = new JobSubmissionFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } public PlacementFormTriggerTraverser getPlacementFormTriggerTraverser(String status) { FormPlacementDto dto = new FormPlacementDto(); dto.setJobPostingID(getTestEntities().getJobOrderId()); dto.setUserID(getTestEntities().getCandidateId()); dto.setPlacementID(getTestEntities().getPlacementId()); dto.setStatus(status); PlacementFormTriggerTraverser traverser = new PlacementFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } public PlacementChangeRequestFormTriggerTraverser getPlacementChangeRequestFormTriggerTraverser(String status) { FormPlacementChangeRequestDto dto = new FormPlacementChangeRequestDto(); dto.setPlacementChangeRequestID(getTestEntities().getPlacementChangeRequestId()); dto.setPlacementID(getTestEntities().getPlacementId()); dto.setStatus(status); PlacementChangeRequestFormTriggerTraverser traverser = new PlacementChangeRequestFormTriggerTraverser(dto, getTestEntities() .getCorporateUserId(), true, bullhornData); return traverser; } public JobFormTriggerTraverser getJobFormTriggerTraverser() { FormJobOrderDto dto = new FormJobOrderDto(); dto.setJobPostingID(getTestEntities().getJobOrderId()); dto.setClientUserID(getTestEntities().getClientContactId()); dto.setClientCorporationID(getTestEntities().getClientCorporationId()); dto.setUserID(testEntities.getCorporateUserId()); JobFormTriggerTraverser traverser = new JobFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } public CandidateFormTriggerTraverser getCandidateFormTriggerTraverser() { FormCandidateDto dto = new FormCandidateDto(); dto.setUserID(getTestEntities().getCandidateId().toString()); dto.setRecruiterUserID(getTestEntities().getCorporateUserId().toString()); CandidateFormTriggerTraverser traverser = new CandidateFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } public ClientContactFormTriggerTraverser getClientContactFormTriggerTraverser() { FormClientContactDto dto = new FormClientContactDto(); dto.setUserID(getTestEntities().getCandidateId()); dto.setRecruiterUserID(getTestEntities().getCorporateUserId().toString()); dto.setClientCorporationID(getTestEntities().getClientCorporationId()); ClientContactFormTriggerTraverser traverser = new ClientContactFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } public ClientCorporationFormTriggerTraverser getClientCorporationFormTriggerTraverser() { FormClientCorporationDto dto = new FormClientCorporationDto(); dto.setClientCorporationID(getTestEntities().getClientCorporationId()); ClientCorporationFormTriggerTraverser traverser = new ClientCorporationFormTriggerTraverser(dto, getTestEntities() .getCorporateUserId(), true, bullhornData); return traverser; } public NoteFormTriggerTraverser getNoteFormTriggerTraverser() { FormNoteDto dto = new FormNoteDto(); dto.setUserCommentID(getTestEntities().getNoteId()); dto.setCommentingUserID(getTestEntities().getCorporateUserId()); NoteFormTriggerTraverser traverser = new NoteFormTriggerTraverser(dto, getTestEntities().getCorporateUserId(), true, bullhornData); return traverser; } /** * Returns a valid CandidateWorkHistoryDto * * @return */ public CandidateWorkHistoryDto validWorkHistory() { CandidateWorkHistoryDto entity = findCandidateInfo(ApiEntityName.CANDIDATE_WORK_HISTORY); return entity; } /** * Returns a valid CandidateEducationDto * * @return */ public CandidateEducationDto validEducation() { CandidateEducationDto entity = findCandidateInfo(ApiEntityName.CANDIDATE_EDUCATION); return entity; } /** * Returns a valid CandidateReferenceDto * * @return */ public CandidateReferenceDto validReference() { CandidateReferenceDto entity = findCandidateInfo(ApiEntityName.CANDIDATE_REFERENCE); return entity; } /** * Returns a valid JobOrderDto * * @return */ public JobOrderDto validJob() { JobOrderDto entity = bullhornApi.findEntity(ApiEntityName.JOB_ORDER.value(), testEntities.getJobOrderId()); return entity; } public <T extends AbstractDto> T findCandidateInfo(ApiEntityName entityName) { String whereClause = "userID = " + testEntities.getCandidateId() + " and isDeleted = 0"; DtoQuery dtoQuery = new DtoQuery(); dtoQuery.setEntityName(entityName.value()); dtoQuery.setMaxResults(1); if (whereClause != null && whereClause.trim().length() > 0) { dtoQuery.setWhere(whereClause); } List<T> queryResult = bullhornApi.getQueryResults(entityName.value(), dtoQuery); return queryResult.get(0); } public static byte[] convertObjectToFormUrlEncodedBytes(Object object) { return convertObjectToFormUrlParameters(object).getBytes(); } public static String convertObjectToFormUrlParameters(Object object) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.registerModule(new JodaModule()); Map<String, Object> propertyValues = mapper.convertValue(object, Map.class); Set<String> propertyNames = propertyValues.keySet(); Iterator<String> nameIter = propertyNames.iterator(); StringBuilder formUrlEncoded = new StringBuilder(); for (int index = 0; index < propertyNames.size(); index++) { String currentKey = nameIter.next(); Object currentValue = propertyValues.get(currentKey); formUrlEncoded.append(currentKey); formUrlEncoded.append("="); formUrlEncoded.append(currentValue); if (nameIter.hasNext()) { formUrlEncoded.append("&"); } } return formUrlEncoded.toString(); } public static Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(dateFormat); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.registerModule(new JodaModule()); TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() { }; Map<String, ?> returnValues = mapper.convertValue(object, typeRef); return returnValues; } public TestEntities getTestEntities() { return testEntities; } public void setTestEntities(TestEntities testEntities) { this.testEntities = testEntities; } public BullhornAPI getBullhornApi() { return bullhornApi; } public void setBullhornApi(BullhornAPI bullhornApi) { this.bullhornApi = bullhornApi; } }
package org.aikodi.chameleon.stub; import java.util.Collection; import java.util.List; import org.aikodi.chameleon.core.declaration.Declaration; import org.aikodi.chameleon.core.declaration.DeclarationContainer; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.element.ElementImpl; import org.aikodi.chameleon.core.lookup.DeclarationSelector; import org.aikodi.chameleon.core.lookup.LookupContext; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.lookup.SelectionResult; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.util.association.Multi; /** * A stub declaration that can be used e.g. for testing. * * @author Marko van Dooren */ public class StubDeclarationContainer extends ElementImpl implements DeclarationContainer { public void add(Declaration declaration) { add(_declarations, declaration); } public void addAll(Collection<Declaration> declarations) { for(Declaration declaration: declarations) { add(declaration); } } @Override public List<? extends Declaration> declarations() { return _declarations.getOtherEnds(); } private Multi<Declaration> _declarations = new Multi<Declaration>(this); @Override public List<? extends Declaration> locallyDeclaredDeclarations() throws LookupException { return _declarations.getOtherEnds(); } @Override public <D extends Declaration> List<? extends SelectionResult> declarations(DeclarationSelector<D> selector) throws LookupException { return selector.selection(declarations()); } @Override public StubDeclarationContainer cloneSelf() { return new StubDeclarationContainer(); } @Override public Verification verifySelf() { return Valid.create(); } @Override public LookupContext lookupContext(Element child) throws LookupException { if(_lexical == null) { _lexical = language().lookupFactory().createLexicalLookupStrategy(targetContext(), this); } return _lexical; } public LookupContext targetContext() throws LookupException { if(_local == null) { _local = language().lookupFactory().createLocalLookupStrategy(this); } return _local; } private LookupContext _local; private LookupContext _lexical; @Override public LookupContext localContext() throws LookupException { return targetContext(); } }
package com.googlecode.javaewah.datastructure; import java.util.Arrays; import java.util.Iterator; import com.googlecode.javaewah.IntIterator; /** * This is an optimized version of Java's BitSet. In many cases, it can be used * as a drop-in replacement. * * It differs from the basic Java BitSet class in the following ways: * <ul> * <li>It only aggregate BitSets having the same number of bits. This is * the desired behavior in many cases where BitSets are supposed to span * the same number of bits and differences are indicative of a programming * issue. You can always resize your BitSets.</li> * <li>You can iterate over set bits using a simpler syntax <code>for(int bs: mybitset)</code>.</li> * <li>You can compute the cardinality of an intersection and union without writing it out * or modifying your BitSets (see methods such as andcardinality).</li> * </ul> * * @author Daniel Lemire * @since 0.8.0 **/ public class BitSet implements Cloneable, Iterable<Integer> { /** * Construct a bitset with the specified number of bits (initially all * false). The number of bits is rounded up to the nearest multiple of * 64. * * @param sizeinbits * the size in bits */ public BitSet(final int sizeinbits) { this.data = new long[(sizeinbits + 63) / 64]; } /** * Compute bitwise AND, assumes that both bitsets have the same length. * * @param bs * other bitset */ public void and(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); for (int k = 0; k < this.data.length; ++k) { this.data[k] &= bs.data[k]; } } /** * Compute cardinality of bitwise AND, assumes that both bitsets have * the same length. * * @param bs * other bitset * @return cardinality */ public int andcardinality(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); int sum = 0; for (int k = 0; k < this.data.length; ++k) { sum += Long.bitCount(this.data[k] & bs.data[k]); } return sum; } /** * Compute bitwise AND NOT, assumes that both bitsets have the same * length. * * @param bs * other bitset */ public void andNot(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); for (int k = 0; k < this.data.length; ++k) { this.data[k] &= ~bs.data[k]; } } /** * Compute cardinality of bitwise AND NOT, assumes that both bitsets * have the same length. * * @param bs * other bitset * @return cardinality */ public int andNotcardinality(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); int sum = 0; for (int k = 0; k < this.data.length; ++k) { sum += Long.bitCount(this.data[k] & (~bs.data[k])); } return sum; } /** * Compute the number of bits set to 1 * * @return the number of bits */ public int cardinality() { int sum = 0; for (long l : this.data) sum += Long.bitCount(l); return sum; } /** * Reset all bits to false */ public void clear() { Arrays.fill(this.data, 0); } @Override public BitSet clone() { BitSet b; try { b = (BitSet) super.clone(); b.data = Arrays.copyOf(this.data, this.data.length); return b; } catch (CloneNotSupportedException e) { return null; } } @Override public boolean equals(Object o) { if (!(o instanceof BitSet)) return false; return Arrays.equals(this.data, ((BitSet) o).data); } /** * @param i * index * @return value of the bit */ public boolean get(final int i) { return (this.data[i / 64] & (1l << (i % 64))) != 0; } @Override public int hashCode() { return Arrays.hashCode(this.data); } /** * Iterate over the set bits * * @return an iterator */ public IntIterator intIterator() { return new IntIterator() { @Override public boolean hasNext() { return this.i >= 0; } @Override public int next() { this.j = this.i; this.i = BitSet.this.nextSetBit(this.i + 1); return this.j; } int i = BitSet.this.nextSetBit(0); int j; }; } @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return this.i >= 0; } @Override public Integer next() { this.j = this.i; this.i = BitSet.this.nextSetBit(this.i + 1); return new Integer(this.j); } @Override public void remove() { BitSet.this.unset(this.j); } int i = BitSet.this.nextSetBit(0); int j; }; } /** * Usage: for(int i=bs.nextSetBit(0); i&gt;=0; i=bs.nextSetBit(i+1)) { * operate on index i here } * * @param i * current set bit * @return next set bit or -1 */ public int nextSetBit(final int i) { int x = i / 64; if (x >= this.data.length) return -1; long w = this.data[x]; w >>>= (i % 64); if (w != 0) { return i + Long.numberOfTrailingZeros(w); } ++x; for (; x < this.data.length; ++x) { if (this.data[x] != 0) { return x * 64 + Long.numberOfTrailingZeros(this.data[x]); } } return -1; } /** * Usage: for(int i=bs.nextUnsetBit(0); i&gt;=0; i=bs.nextUnsetBit(i+1)) * { operate on index i here } * * @param i * current unset bit * @return next unset bit or -1 */ public int nextUnsetBit(final int i) { int x = i / 64; if (x >= this.data.length) return -1; long w = ~this.data[x]; w >>>= (i % 64); if (w != 0) { return i + Long.numberOfTrailingZeros(w); } ++x; for (; x < this.data.length; ++x) { if (this.data[x] != ~0) { return x * 64 + Long.numberOfTrailingZeros(~this.data[x]); } } return -1; } /** * Compute bitwise OR, assumes that both bitsets have the same length. * * @param bs * other bitset */ public void or(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); for (int k = 0; k < this.data.length; ++k) { this.data[k] |= bs.data[k]; } } /** * Compute cardinality of bitwise OR, assumes that both bitsets have the * same length. * * @param bs * other bitset * @return cardinality */ public int orcardinality(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); int sum = 0; for (int k = 0; k < this.data.length; ++k) { sum += Long.bitCount(this.data[k] | bs.data[k]); } return sum; } /** * Resize the bitset * * @param sizeinbits * new number of bits */ public void resize(int sizeinbits) { this.data = Arrays.copyOf(this.data, (sizeinbits + 63) / 64); } /** * Set to true * * @param i * index of the bit */ public void set(final int i) { this.data[i / 64] |= (1l << (i % 64)); } /** * @param i * index * @param b * value of the bit */ public void set(final int i, final boolean b) { if (b) set(i); else unset(i); } /** * Query the size * * @return the size in bits. */ public int size() { return this.data.length * 64; } /** * Set to false * * @param i * index of the bit */ public void unset(final int i) { this.data[i / 64] &= ~(1l << (i % 64)); } /** * Iterate over the unset bits * * @return an iterator */ public IntIterator unsetIntIterator() { return new IntIterator() { @Override public boolean hasNext() { return this.i >= 0; } @Override public int next() { this.j = this.i; this.i = BitSet.this.nextUnsetBit(this.i + 1); return this.j; } int i = BitSet.this.nextUnsetBit(0); int j; }; } /** * Compute bitwise XOR, assumes that both bitsets have the same length. * * @param bs * other bitset */ public void xor(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); for (int k = 0; k < this.data.length; ++k) { this.data[k] ^= bs.data[k]; } } /** * Compute cardinality of bitwise XOR, assumes that both bitsets have * the same length. * * @param bs * other bitset * @return cardinality */ public int xorcardinality(BitSet bs) { if (this.data.length != bs.data.length) throw new IllegalArgumentException( "incompatible bitsets"); int sum = 0; for (int k = 0; k < this.data.length; ++k) { sum += Long.bitCount(this.data[k] ^ bs.data[k]); } return sum; } long[] data; }
package org.apache.xerces.validators.schema; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.validators.common.Grammar; import org.apache.xerces.validators.common.GrammarResolver; import org.apache.xerces.validators.common.GrammarResolverImpl; import org.apache.xerces.validators.common.XMLElementDecl; import org.apache.xerces.validators.common.XMLAttributeDecl; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.XUtil; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.utils.StringPool; import org.w3c.dom.Element; //REVISIT: for now, import everything in the DOM package import org.w3c.dom.*; import java.util.*; import java.net.URL; import java.net.MalformedURLException; //Unit Test import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.validators.common.XMLValidator; import org.apache.xerces.validators.datatype.DatatypeValidator.*; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.framework.XMLParser; import org.apache.xerces.framework.XMLDocumentScanner; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import java.io.IOException; import org.w3c.dom.Document; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.apache.xerces.validators.schema.SchemaSymbols; /** * Instances of this class get delegated to Traverse the Schema and * to populate the Grammar internal representation by * instances of Grammar objects. * Traverse a Schema Grammar: * As of April 07, 2000 the following is the * XML Representation of Schemas and Schema components, * Chapter 4 of W3C Working Draft. * <schema * attributeFormDefault = qualified | unqualified * blockDefault = #all or (possibly empty) subset of {equivClass, extension, restriction} * elementFormDefault = qualified | unqualified * finalDefault = #all or (possibly empty) subset of {extension, restriction} * id = ID * targetNamespace = uriReference * version = string> * Content: ((include | import | annotation)* , ((simpleType | complexType | element | group | attribute | attributeGroup | notation) , annotation*)+) * </schema> * * * <attribute * form = qualified | unqualified * id = ID * name = NCName * ref = QName * type = QName * use = default | fixed | optional | prohibited | required * value = string> * Content: (annotation? , simpleType?) * </> * * <element * abstract = boolean * block = #all or (possibly empty) subset of {equivClass, extension, restriction} * default = string * equivClass = QName * final = #all or (possibly empty) subset of {extension, restriction} * fixed = string * form = qualified | unqualified * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * nullable = boolean * ref = QName * type = QName> * Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*) * </> * * * <complexType * abstract = boolean * base = QName * block = #all or (possibly empty) subset of {extension, restriction} * content = elementOnly | empty | mixed | textOnly * derivedBy = extension | restriction * final = #all or (possibly empty) subset of {extension, restriction} * id = ID * name = NCName> * Content: (annotation? , (((minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern)* | (element | group | all | choice | sequence | any)*) , ((attribute | attributeGroup)* , anyAttribute?))) * </> * * * <attributeGroup * id = ID * name = NCName * ref = QName> * Content: (annotation?, (attribute|attributeGroup), anyAttribute?) * </> * * <anyAttribute * id = ID * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}> * Content: (annotation?) * </anyAttribute> * * <group * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * ref = QName> * Content: (annotation? , (element | group | all | choice | sequence | any)*) * </> * * <all * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </all> * * <choice * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </choice> * * <sequence * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </sequence> * * * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace} * processContents = lax | skip | strict> * Content: (annotation?) * </any> * * <unique * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </unique> * * <key * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </key> * * <keyref * id = ID * name = NCName * refer = QName> * Content: (annotation? , (selector , field+)) * </keyref> * * <selector> * Content: XPathExprApprox : An XPath expression * </selector> * * <field> * Content: XPathExprApprox : An XPath expression * </field> * * * <notation * id = ID * name = NCName * public = A public identifier, per ISO 8879 * system = uriReference> * Content: (annotation?) * </notation> * * <annotation> * Content: (appinfo | documentation)* * </annotation> * * <include * id = ID * schemaLocation = uriReference> * Content: (annotation?) * </include> * * <import * id = ID * namespace = uriReference * schemaLocation = uriReference> * Content: (annotation?) * </import> * * <simpleType * abstract = boolean * base = QName * derivedBy = | list | restriction : restriction * id = ID * name = NCName> * Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* ) * </simpleType> * * <length * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </length> * * <minLength * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </minLength> * * <maxLength * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </maxLength> * * * <pattern * id = ID * value = string> * Content: ( annotation? ) * </pattern> * * * <enumeration * id = ID * value = string> * Content: ( annotation? ) * </enumeration> * * <maxInclusive * id = ID * value = string> * Content: ( annotation? ) * </maxInclusive> * * <maxExclusive * id = ID * value = string> * Content: ( annotation? ) * </maxExclusive> * * <minInclusive * id = ID * value = string> * Content: ( annotation? ) * </minInclusive> * * * <minExclusive * id = ID * value = string> * Content: ( annotation? ) * </minExclusive> * * <precision * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </precision> * * <scale * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </scale> * * <encoding * id = ID * value = | hex | base64 > * Content: ( annotation? ) * </encoding> * * * <duration * id = ID * value = timeDuration> * Content: ( annotation? ) * </duration> * * <period * id = ID * value = timeDuration> * Content: ( annotation? ) * </period> * * * @author Jeffrey Rodriguez * Eric Ye * @see org.apache.xerces.validators.common.Grammar * * @version $Id$ */ public class TraverseSchema implements NamespacesScope.NamespacesHandler{ //CONSTANTS private static final int TOP_LEVEL_SCOPE = -1; //debuggin private static boolean DEBUGGING = false; //private data members private XMLErrorReporter fErrorReporter = null; private StringPool fStringPool = null; private GrammarResolver fGrammarResolver = null; private SchemaGrammar fSchemaGrammar = null; private Element fSchemaRootElement; private DatatypeValidatorFactoryImpl fDatatypeRegistry = DatatypeValidatorFactoryImpl.getDatatypeRegistry(); private Hashtable fComplexTypeRegistry = new Hashtable(); private Hashtable fAttributeDeclRegistry = new Hashtable(); private Vector fIncludeLocations = new Vector(); private Vector fImportLocations = new Vector(); private int fAnonTypeCount =0; private int fScopeCount=0; private int fCurrentScope=TOP_LEVEL_SCOPE; private int fSimpleTypeAnonCount = 0; private Stack fCurrentTypeNameStack = new Stack(); private Hashtable fElementRecurseComplex = new Hashtable(); private boolean fElementDefaultQualified = false; private boolean fAttributeDefaultQualified = false; private int fTargetNSURI; private String fTargetNSURIString = ""; private NamespacesScope fNamespacesScope = null; private String fCurrentSchemaURL = ""; private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); // REVISIT: maybe need to be moved into SchemaGrammar class public class ComplexTypeInfo { public String typeName; public DatatypeValidator baseDataTypeValidator; public ComplexTypeInfo baseComplexTypeInfo; public int derivedBy; public int blockSet; public int finalSet; public int scopeDefined = -1; public int contentType; public int contentSpecHandle = -1; public int templateElementIndex = -1; public int attlistHead = -1; public DatatypeValidator datatypeValidator; } //REVISIT: verify the URI. public final static String SchemaForSchemaURI = "http: private TraverseSchema( ) { // new TraverseSchema() is forbidden; } public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } public void startNamespaceDeclScope(int prefix, int uri){ //TO DO } public void endNamespaceDeclScope(int prefix){ //TO DO, do we need to do anything here? } private String resolvePrefixToURI (String prefix) throws Exception { String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix))); if (uriStr == null) { // REVISIT: Localize reportGenericSchemaError("prefix : [" + prefix +"] can not be resolved to a URI"); } //REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype. if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && ! fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { uriStr = ""; } return uriStr; } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver, XMLErrorReporter errorReporter, String schemaURL ) throws Exception { fErrorReporter = errorReporter; fCurrentSchemaURL = schemaURL; doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver ) throws Exception { doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public void doTraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver) throws Exception { fNamespacesScope = new NamespacesScope(this); fSchemaRootElement = root; fStringPool = stringPool; fSchemaGrammar = schemaGrammar; fGrammarResolver = grammarResolver; if (root == null) { // REVISIT: Anything to do? return; } //Make sure namespace binding is defaulted String rootPrefix = root.getPrefix(); if( rootPrefix == null || rootPrefix.length() == 0 ){ String xmlns = root.getAttribute("xmlns"); if( xmlns.length() == 0 ) root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA ); } //Retrieve the targetnamespace URI information fTargetNSURIString = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (fTargetNSURIString==null) { fTargetNSURIString=""; } fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString); if (fGrammarResolver == null) { // REVISIT: Localize reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema"); } else{ fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry); fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry); fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry); fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar); } // Retrived the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; checkTopLevelDuplicateNames(root); //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { //traverseAttributeGroupDecl(child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { //traverseAttributeDecl( child ); } else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) { traverseWildcardDecl( child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { //traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { ; //TO DO } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { traverseInclude(child); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } } // for each child node } // traverseSchema(Element) private void checkTopLevelDuplicateNames(Element root) { //TO DO : !!! } private void extractTopLevel3Components(Element root){ for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fSchemaGrammar.topLevelAttrGrpDecls.put(name, child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { fSchemaGrammar.topLevelAttrDecls.put(name, child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { fSchemaGrammar.topLevelGroupDecls.put(name, child); } } // for each child node } /** * Expands a system id and returns the system id as a URL, if * it can be expanded. A return value of null means that the * identifier is already expanded. An exception thrown * indicates a failure to expand the id. * * @param systemId The systemId to be expanded. * * @return Returns the URL object representing the expanded system * identifier. A null value indicates that the given * system identifier is already expanded. * */ private String expandSystemId(String systemId, String currentSystemId) throws Exception{ String id = systemId; // check for bad parameters id if (id == null || id.length() == 0) { return systemId; } // if id already expanded, return try { URL url = new URL(id); if (url != null) { return systemId; } } catch (MalformedURLException e) { // continue on... } // normalize id id = fixURI(id); // normalize base URL base = null; URL url = null; try { if (currentSystemId == null) { String dir; try { dir = fixURI(System.getProperty("user.dir")); } catch (SecurityException se) { dir = ""; } if (!dir.endsWith("/")) { dir = dir + "/"; } base = new URL("file", "", dir); } else { base = new URL(currentSystemId); } // expand id url = new URL(base, id); } catch (Exception e) { // let it go through } if (url == null) { return systemId; } return url.toString(); } /** * Fixes a platform dependent filename to standard URI form. * * @param str The string to fix. * * @return Returns the fixed URI string. */ private static String fixURI(String str) { // handle platform dependent strings str = str.replace(java.io.File.separatorChar, '/'); // Windows fix if (str.length() >= 2) { char ch1 = str.charAt(1); if (ch1 == ':') { char ch0 = Character.toUpperCase(str.charAt(0)); if (ch0 >= 'A' && ch0 <= 'Z') { str = "/" + str; } } } // done return str; } private void traverseInclude(Element includeDecl) throws Exception { //TO DO: !!!!! location needs to be resolved first. String location = includeDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION); location = expandSystemId(location, fCurrentSchemaURL); if (fIncludeLocations.contains((Object)location)) { return; } fIncludeLocations.addElement((Object)location); DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( location); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { //e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) { // REVISIT: Localize reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"'"); } else { boolean saveElementDefaultQualified = fElementDefaultQualified; boolean saveAttributeDefaultQualified = fAttributeDefaultQualified; int saveScope = fCurrentScope; String savedSchemaURL = fCurrentSchemaURL; Element saveRoot = fSchemaRootElement; fSchemaRootElement = root; fCurrentSchemaURL = location; traverseIncludedSchema(root); fCurrentSchemaURL = savedSchemaURL; fCurrentScope = saveScope; fElementDefaultQualified = saveElementDefaultQualified; fAttributeDefaultQualified = saveAttributeDefaultQualified; fSchemaRootElement = saveRoot; } } } private void traverseIncludedSchema(Element root) throws Exception { // Retrived the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; checkTopLevelDuplicateNames(root); //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { //traverseAttributeGroupDecl(child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { //traverseAttributeDecl( child ); } else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) { traverseWildcardDecl( child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { //traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { ; //TO DO } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { traverseInclude(child); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } } // for each child node } private void traverseImport(Element importDecl) throws Exception { String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION); location = expandSystemId(location, fCurrentSchemaURL); String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE); SchemaGrammar importedGrammar = new SchemaGrammar(); if (fGrammarResolver.getGrammar(namespaceString) != null) { importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString); } if (fImportLocations.contains((Object)location)) { return; } fImportLocations.addElement((Object)location); DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( location); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (!targetNSURI.equals(namespaceString) ) { // REVISIT: Localize reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"' from what is declared '"+namespaceString+"'."); } else new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location); } else { reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location); } } /** * No-op - Traverse Annotation Declaration * * @param comment */ private void traverseAnnotationDecl(Element comment) { //TO DO return ; } /** * Traverse SimpleType declaration: * <simpleType * abstract = boolean * base = QName * derivedBy = | list | restriction : restriction * id = ID * name = NCName> * Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* ) * </simpleType> * * @param simpleTypeDecl * @return */ private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception { String varietyProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); if (varietyProperty.length() == 0) { varietyProperty = SchemaSymbols.ATTVAL_RESTRICTION; } String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME ); String baseTypeQNameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ); String abstractProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); int newSimpleTypeName = -1; if ( nameProperty.equals("")) { // anonymous simpleType newSimpleTypeName = fStringPool.addSymbol( "http: } else newSimpleTypeName = fStringPool.addSymbol( nameProperty ); int basetype; DatatypeValidator baseValidator = null; if( baseTypeQNameProperty!= null ) { basetype = fStringPool.addSymbol( baseTypeQNameProperty ); String prefix = ""; String localpart = baseTypeQNameProperty; int colonptr = baseTypeQNameProperty.indexOf(":"); if ( colonptr > 0) { prefix = baseTypeQNameProperty.substring(0,colonptr); localpart = baseTypeQNameProperty.substring(colonptr+1); } baseValidator = fDatatypeRegistry.getDatatypeValidator( localpart ); if (baseValidator == null) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ), simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME) }); return -1; } } // Any Children if so then check Content otherwise bail out Element content = XUtil.getFirstChildElement( simpleTypeDecl ); int numFacets = 0; Hashtable facetData = null; if( content != null ) { //Content follows: ( annotation? , facets* ) //annotation ? ( 0 or 1 ) if( content.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( content ); content = XUtil.getNextSiblingElement(content); } //TODO: If content is annotation again should raise validation error // if( content.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) { // throw ValidationException(); } //facets * ( 0 or more ) int numEnumerationLiterals = 0; facetData = new Hashtable(); Vector enumData = new Vector(); while (content != null) { if (content.getNodeType() == Node.ELEMENT_NODE) { Element facetElt = (Element) content; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; String enumVal = facetElt.getAttribute(SchemaSymbols.ATT_VALUE); enumData.addElement(enumVal); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( content ); } //TODO: If enumContent is encounter again should raise validation error // enumContent.getNextSibling(); // if( enumContent.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) { // throw ValidationException(); } } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } //content = (Element) content.getNextSibling(); content = XUtil.getNextSiblingElement(content); } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } } // create & register validator for "generated" type if it doesn't exist try { String nameOfType = fStringPool.toString( newSimpleTypeName ); DatatypeValidator newValidator = fDatatypeRegistry.getDatatypeValidator( nameOfType ); if( newValidator == null ) { // not previously registered boolean derivedByList = varietyProperty.equals( SchemaSymbols.ATTVAL_LIST ) ? true:false; fDatatypeRegistry.createDatatypeValidator( nameOfType, baseValidator, facetData, derivedByList ); } } catch (Exception e) { //e.printStackTrace(System.err); reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() }); } return newSimpleTypeName; } /** * Traverse ComplexType Declaration. * * <complexType * abstract = boolean * base = QName * block = #all or (possibly empty) subset of {extension, restriction} * content = elementOnly | empty | mixed | textOnly * derivedBy = extension | restriction * final = #all or (possibly empty) subset of {extension, restriction} * id = ID * name = NCName> * Content: (annotation? , (((minExclusive | minInclusive | maxExclusive * | maxInclusive | precision | scale | length | minLength * | maxLength | encoding | period | duration | enumeration * | pattern)* | (element | group | all | choice | sequence | any)*) , * ((attribute | attributeGroup)* , anyAttribute?))) * </complexType> * @param complexTypeDecl * @return */ //REVISIT: TO DO, base and derivation ??? private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception{ String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE); String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK ); String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT); String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL ); String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID ); String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME); boolean isNamedType = false; if ( DEBUGGING ) System.out.println("traversing complex Type : " + typeName +","+base+","+content+"."); if (typeName.equals("")) { // gensym a unique name typeName = "#"+fAnonTypeCount++; } else { fCurrentTypeNameStack.push(typeName); isNamedType = true; } if (isTopLevel(complexTypeDecl)) { String fullName = fTargetNSURIString+","+typeName; ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName); if (temp != null ) { return fStringPool.addSymbol(fullName); } } int scopeDefined = fScopeCount++; int previousScope = fCurrentScope; fCurrentScope = scopeDefined; Element child = null; int contentSpecType = -1; int csnType = 0; int left = -2; int right = -2; ComplexTypeInfo baseTypeInfo = null; //if base is a complexType; DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType DatatypeValidator simpleTypeValidator = null; int baseTypeSymbol = -1; String fullBaseName = ""; boolean baseIsSimpleSimple = false; boolean baseIsComplexSimple = false; boolean derivedByRestriction = true; boolean derivedByExtension = false; int baseContentSpecHandle = -1; Element baseTypeNode = null; //int parsedderivedBy = parseComplexDerivedBy(derivedBy); //handle the inhreitance here. if (base.length()>0) { //first check if derivedBy is present if (derivedBy.length() == 0) { // REVISIT: Localize reportGenericSchemaError("derivedBy must be present when base is present in " +SchemaSymbols.ELT_COMPLEXTYPE +" "+ typeName); } else { if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) { derivedByRestriction = false; } String prefix = ""; String localpart = base; int colonptr = base.indexOf(":"); if ( colonptr > 0) { prefix = base.substring(0,colonptr); localpart = base.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String typeURI = resolvePrefixToURI(prefix); // check if the base type is from the same Schema; if ( ! typeURI.equals(fTargetNSURIString) && ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && ! (typeURI.length() == 0) ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{ baseTypeInfo = getTypeInfoFromNS(typeURI, localpart); if (baseTypeInfo == null) { baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart); if (baseTypeValidator == null) { //TO DO: report error here; System.out.println("Could not find base type " +localpart + " in schema " + typeURI); } else{ baseIsSimpleSimple = true; } } } else { fullBaseName = typeURI+","+localpart; // assume the base is a complexType and try to locate the base type first baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName); // if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet; // 2: base is SimpleTYpe; if (baseTypeInfo == null) { baseTypeValidator = fDatatypeRegistry.getDatatypeValidator(localpart); if (baseTypeValidator == null) { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode ); baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName; } else { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode ); simpleTypeValidator = baseTypeValidator = fDatatypeRegistry.getDatatypeValidator(localpart); if (simpleTypeValidator == null) { //TO DO: signal error here. } baseIsSimpleSimple = true; } else { // REVISIT: Localize reportGenericSchemaError("Base type could not be found : " + base); } } } else { simpleTypeValidator = baseTypeValidator; baseIsSimpleSimple = true; } } } //Schema Spec : 5.11: Complex Type Definition Properties Correct : 2 if (baseIsSimpleSimple && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName); } //if the base is a complexType if (baseTypeInfo != null ) { //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 // 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1 if (derivedByRestriction) { //REVISIT: check base Type's finalset does not include "restriction" } else { //REVISIT: check base Type's finalset doest not include "extension" } if ( baseTypeInfo.contentSpecHandle > -1) { if (derivedByRestriction) { //REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10 checkParticleDerivationOK(complexTypeDecl, baseTypeNode); } baseContentSpecHandle = baseTypeInfo.contentSpecHandle; } else if ( baseTypeInfo.datatypeValidator != null ) { baseTypeValidator = baseTypeInfo.datatypeValidator; baseIsComplexSimple = true; } } //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 if (baseIsComplexSimple && !derivedByRestriction ) { // REVISIT: Localize reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName); } } // END of if (derivedBy.length() == 0) {} else {} } // END of if (base.length() > 0) {} // skip refinement and annotations child = null; if (baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; int numEnumerationLiterals = 0; int numFacets = 0; Hashtable facetData = new Hashtable(); Vector enumData = new Vector(); //REVISIT: there is a better way to do this, for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) || child.getNodeName().equals(SchemaSymbols.ELT_SCALE) || child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) || child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) || child.getNodeName().equals(SchemaSymbols.ELT_DURATION) || child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) || child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) || child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)); child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeType() == Node.ELEMENT_NODE ) { Element facetElt = (Element) child; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE)); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( child ); } // TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } //if (numFacets > 0) // baseTypeValidator.setFacets(facetData, derivedBy ); if (numFacets > 0) { simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator, facetData, false ); } else simpleTypeValidator = baseTypeValidator; if (child != null) { // REVISIT: Localize reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName + "', because it restricts another complexSimpleType"); } } // if content = textonly, base is a datatype if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { //TO DO if (base.length() == 0) { simpleTypeValidator = baseTypeValidator = fDatatypeRegistry.getDatatypeValidator(SchemaSymbols.ATTVAL_STRING); } else if (fDatatypeRegistry.getDatatypeValidator(base) == null && baseTypeInfo.datatypeValidator==null ) // must be datatype reportSchemaError(SchemaMessageProvider.NotADatatype, new Object [] { base }); //REVISIT check forward refs //handle datatypes contentSpecType = XMLElementDecl.TYPE_SIMPLE; /** * Traverses Schema attribute declaration. * * <attribute * form = qualified | unqualified * id = ID * name = NCName * ref = QName * type = QName * use = default | fixed | optional | prohibited | required * value = string> * Content: (annotation? , simpleType?) * <attribute/> * * @param attributeDecl * @return * @exception Exception */ private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo ) throws Exception { String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME); int attName = fStringPool.addSymbol(attNameStr);// attribute name String isQName = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute DatatypeValidator dv = null; // attribute type int attType = -1; boolean attIsList = false; int dataTypeSymbol = -1; String ref = attrDecl.getAttribute(SchemaSymbols.ATT_REF); String datatype = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE); String localpart = null; if (!ref.equals("")) { if (XUtil.getFirstChildElement(attrDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo); return -1; // TO DO // REVISIT: different NS, not supported yet. // REVISIT: Localize //reportGenericSchemaError("Feature not supported: see an attribute from different NS"); } Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart); if (referredAttribute != null) { traverseAttributeDecl(referredAttribute, typeInfo); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attribute " + ref); } return -1; } if (datatype.equals("")) { Element child = XUtil.getFirstChildElement(attrDecl); while (child != null && !child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE)) child = XUtil.getNextSiblingElement(child); if (child != null && child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE)) { attType = XMLAttributeDecl.TYPE_SIMPLE; dataTypeSymbol = traverseSimpleTypeDecl(child); localpart = fStringPool.toString(dataTypeSymbol); } else { attType = XMLAttributeDecl.TYPE_SIMPLE; localpart = "string"; dataTypeSymbol = fStringPool.addSymbol(localpart); } localpart = fStringPool.toString(dataTypeSymbol); } else { String prefix = ""; localpart = datatype; int colonptr = datatype.indexOf(":"); if ( colonptr > 0) { prefix = datatype.substring(0,colonptr); localpart = datatype.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); dataTypeSymbol = fStringPool.addSymbol(localpart); if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) || typeURI.length()==0) { if (localpart.equals("ID")) { attType = XMLAttributeDecl.TYPE_ID; } else if (localpart.equals("IDREF")) { attType = XMLAttributeDecl.TYPE_IDREF; } else if (localpart.equals("IDREFS")) { attType = XMLAttributeDecl.TYPE_IDREF; attIsList = true; } else if (localpart.equals("ENTITY")) { attType = XMLAttributeDecl.TYPE_ENTITY; } else if (localpart.equals("ENTITIES")) { attType = XMLAttributeDecl.TYPE_ENTITY; attIsList = true; } else if (localpart.equals("NMTOKEN")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; } else if (localpart.equals("NMTOKENS")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; attIsList = true; } else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) { attType = XMLAttributeDecl.TYPE_NOTATION; } else { attType = XMLAttributeDecl.TYPE_SIMPLE; } } else { // REVISIT: Danger: assuming all other ATTR types are datatypes //REVISIT check against list of validators to ensure valid type name // check if the type is from the same Schema if (!typeURI.equals(fTargetNSURIString) && typeURI.length() != 0 ) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; System.out.println("Counld not find simpleType " +localpart + " in schema " + typeURI); } } else { dv = fDatatypeRegistry.getDatatypeValidator(localpart); } attType = XMLAttributeDecl.TYPE_SIMPLE; } } // attribute default type int attDefaultType = -1; int attDefaultValue = -1; String use = attrDecl.getAttribute(SchemaSymbols.ATT_USE); boolean required = use.equals(SchemaSymbols.ATTVAL_REQUIRED); if(dv==null){ dv = fDatatypeRegistry.getDatatypeValidator(localpart); if ( dv == null ) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { traverseSimpleTypeDecl( topleveltype ); dv = fDatatypeRegistry.getDatatypeValidator(localpart); // TO DO: the Default and fixed attribute handling should be here. }else { // REVISIT: Localize reportGenericSchemaError("simpleType not found : " + localpart); } } } if (dv == null) { // REVISIT: Localize reportGenericSchemaError("null validator for datatype : " + fStringPool.toString(dataTypeSymbol)); } if (required) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED; } else { if (use.equals(SchemaSymbols.ATTVAL_FIXED)) { String fixed = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE); if (!fixed.equals("")) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_FIXED; attDefaultValue = fStringPool.addString(fixed); } } else if (use.equals(SchemaSymbols.ATTVAL_DEFAULT)) { // attribute default value String defaultValue = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE); if (!defaultValue.equals("")) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_DEFAULT; attDefaultValue = fStringPool.addString(defaultValue); } } else if (use.equals(SchemaSymbols.ATTVAL_PROHIBITED)) { attDefaultType = fStringPool.addSymbol("#PROHIBITED"); //attDefaultValue = fStringPool.addString(""); } else { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED; } // check default value is valid for the datatype. if (attType == XMLAttributeDecl.TYPE_SIMPLE && attDefaultValue != -1) { try { if (dv != null) //REVISIT dv.validate(fStringPool.toString(attDefaultValue), null); else reportSchemaError(SchemaMessageProvider.NoValidatorFor, new Object [] { datatype }); } catch (InvalidDatatypeValueException idve) { reportSchemaError(SchemaMessageProvider.IncorrectDefaultType, new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); } catch (Exception e) { e.printStackTrace(); System.out.println("Internal error in attribute datatype validation"); } } } int uriIndex = -1; if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fAttributeDefaultQualified || isTopLevel(attrDecl) ) { uriIndex = fTargetNSURI; } QName attQName = new QName(-1,attName,attName,uriIndex); if ( DEBUGGING ) System.out.println(" the dataType Validator for " + fStringPool.toString(attName) + " is " + dv); //put the top-levels in the attribute decl registry. if (isTopLevel(attrDecl)) { fTempAttributeDecl.datatypeValidator = dv; fTempAttributeDecl.name.setValues(attQName); fTempAttributeDecl.type = attType; fTempAttributeDecl.defaultType = attDefaultType; if (attDefaultValue != -1 ) { fTempAttributeDecl.defaultValue = new String(fStringPool.toString(attDefaultValue)); } fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl)); } // add attribute to attr decl pool in fSchemaGrammar, fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attQName, attType, dataTypeSymbol, attDefaultType, fStringPool.toString( attDefaultValue), dv); return -1; } // end of method traverseAttribute private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #addAttributeDeclFromAnotherSchema, schema uri : " + uriStr); return -1; } Hashtable attrRegistry = aGrammar.getAttirubteDeclRegistry(); if (attrRegistry == null) { // REVISIT: Localize reportGenericSchemaError("no attribute was defined in schema : " + uriStr); return -1; } XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name); if (tempAttrDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute named \"" + name + "\" was defined in schema : " + uriStr); return -1; } fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, tempAttrDecl.name, tempAttrDecl.type, -1, tempAttrDecl.defaultType, tempAttrDecl.defaultValue, tempAttrDecl.datatypeValidator); return 0; } /* * * <attributeGroup * id = ID * name = NCName * ref = QName> * Content: (annotation?, (attribute|attributeGroup), anyAttribute?) * </> * */ private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo ) throws Exception { // attribute name int attGrpName = fStringPool.addSymbol(attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME)); String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF); // attribute type int attType = -1; int enumeration = -1; if (!ref.equals("")) { if (XUtil.getFirstChildElement(attrGrpDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo); return -1; // TO DO // REVISIST: different NS, not supported yet. // REVISIT: Localize //reportGenericSchemaError("Feature not supported: see an attribute from different NS"); } Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart); if (referredAttrGrp != null) { traverseAttributeGroupDecl(referredAttrGrp, typeInfo); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attributegroup " + ref); } return -1; } for ( Element child = XUtil.getFirstChildElement(attrGrpDecl); child != null ; child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ traverseAttributeDecl(child, typeInfo); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child, typeInfo); } else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) { // REVISIT: what about appInfo } } return -1; } // end of method traverseAttributeGroup private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr, ComplexTypeInfo typeInfo ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr); return -1; } // attribute name Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName); if (attGrpDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute group named \"" + attGrpName + "\" was defined in schema : " + uriStr); return -1; } // attribute type int attType = -1; int enumeration = -1; for ( Element child = XUtil.getFirstChildElement(attGrpDecl); child != null ; child = XUtil.getNextSiblingElement(child)) { //child attribute couldn't be a top-level attribute DEFINITION, if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME); if ( childAttName.length() > 0 ) { Hashtable attDeclRegistry = aGrammar.getAttirubteDeclRegistry(); if (attDeclRegistry != null) { if (attDeclRegistry.get((Object)childAttName) != null ){ addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo); return -1; } } } else traverseAttributeDecl(child, typeInfo); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child, typeInfo); } else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) { // REVISIT: what about appInfo } } return -1; } // end of method traverseAttributeGroupFromAnotherSchema /** * Traverse element declaration: * <element * abstract = boolean * block = #all or (possibly empty) subset of {equivClass, extension, restriction} * default = string * equivClass = QName * final = #all or (possibly empty) subset of {extension, restriction} * fixed = string * form = qualified | unqualified * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * nullable = boolean * ref = QName * type = QName> * Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*) * </element> * * * The following are identity-constraint definitions * <unique * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </unique> * * <key * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </key> * * <keyref * id = ID * name = NCName * refer = QName> * Content: (annotation? , (selector , field+)) * </keyref> * * <selector> * Content: XPathExprApprox : An XPath expression * </selector> * * <field> * Content: XPathExprApprox : An XPath expression * </field> * * * @param elementDecl * @return * @exception Exception */ private QName traverseElementDecl(Element elementDecl) throws Exception { int contentSpecType = -1; int contentSpecNodeIndex = -1; int typeNameIndex = -1; int scopeDefined = -2; //signal a error if -2 gets gets through //cause scope can never be -2. DatatypeValidator dv = null; String name = elementDecl.getAttribute(SchemaSymbols.ATT_NAME); if ( DEBUGGING ) System.out.println("traversing element decl : " + name ); String ref = elementDecl.getAttribute(SchemaSymbols.ATT_REF); String type = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE); String minOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS); String maxOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS); String dflt = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String fixed = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED); String equivClass = elementDecl.getAttribute(SchemaSymbols.ATT_EQUIVCLASS); // form attribute String isQName = elementDecl.getAttribute(SchemaSymbols.ATT_FORM); String fromAnotherSchema = null; if (isTopLevel(elementDecl)) { int nameIndex = fStringPool.addSymbol(name); int eltKey = fSchemaGrammar.getElementDeclIndex(nameIndex,TOP_LEVEL_SCOPE); if (eltKey > -1 ) { return new QName(-1,nameIndex,nameIndex,fTargetNSURI); } } int attrCount = 0; if (!ref.equals("")) attrCount++; if (!type.equals("")) attrCount++; //REVISIT top level check for ref & archref if (attrCount > 1) reportSchemaError(SchemaMessageProvider.OneOfTypeRefArchRef, null); if (!ref.equals("")) { if (XUtil.getFirstChildElement(elementDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriString = resolvePrefixToURI(prefix); QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1, localpartIndex, fStringPool.addSymbol(ref), uriString != null ? fStringPool.addSymbol(uriString) : -1); //if from another schema, just return the element QName if (! uriString.equals(fTargetNSURIString) ) { return eltName; } int elementIndex = fSchemaGrammar.getElementDeclIndex(localpartIndex, TOP_LEVEL_SCOPE); //if not found, traverse the top level element that if referenced if (elementIndex == -1 ) { Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart); if (targetElement == null ) { // REVISIT: Localize reportGenericSchemaError("Element " + localpart + " not found in the Schema"); //REVISIT, for now, the QName anyway return eltName; //return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString)); } else { // do nothing here, other wise would cause infinite loop for // <element name="recur"><complexType><element ref="recur"> ... //eltName= traverseElementDecl(targetElement); } } return eltName; } Element equivClassElementDecl = null; boolean noErrorSoFar = true; if ( equivClass.length() > 0 ) { equivClassElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, getLocalPart(equivClass)); if (equivClassElementDecl == null) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("Equivclass affiliation element " +equivClass +" in element declaration " +name); } } //ComplexTypeInfo typeInfo = new ComplexTypeInfo(); ComplexTypeInfo typeInfo = null; // element has a single child element, either a datatype or a type, null if primitive Element child = XUtil.getFirstChildElement(elementDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); boolean haveAnonType = false; if (child != null) { String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous complexType in element '" + name +"' has a name attribute"); } else typeNameIndex = traverseComplexTypeDecl(child); if (typeNameIndex != -1 ) { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse complexType error in element '" + name +"'"); } //System.out.println("typeInfo.scopeDefined : " + typeInfo.typeName+","+"["+typeInfo.scopeDefined+"]" // +", base is " + fSchemaGrammar.getElementDeclIndex(fStringPool.addSymbol("heater"), typeInfo.baseComplexTypeInfo.scopeDefined)); haveAnonType = true; } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { // TO DO: the Default and fixed attribute handling should be here. if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous simpleType in element '" + name +"' has a name attribute"); } else typeNameIndex = traverseSimpleTypeDecl(child); if (typeNameIndex != -1) { dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse simpleType error in element '" + name +"'"); } contentSpecType = XMLElementDecl.TYPE_SIMPLE; haveAnonType = true; } else if (type.equals("")) { // "ur-typed" leaf contentSpecType = XMLElementDecl.TYPE_ANY; //REVISIT: is this right? //contentSpecType = fStringPool.addSymbol("UR_TYPE"); // set occurrence count contentSpecNodeIndex = -1; } else { System.out.println("unhandled case in TraverseElementDecl"); } } if (haveAnonType && (type.length()>0)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError( "Element '"+ name + "' have both a type attribute and a annoymous type child" ); } // type specified as an attribute and no child is type decl. else if (!type.equals("")) { if (equivClassElementDecl != null) { checkEquivClassOK(elementDecl, equivClassElementDecl); } String prefix = ""; String localpart = type; int colonptr = type.indexOf(":"); if ( colonptr > 0) { prefix = type.substring(0,colonptr); localpart = type.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); // check if the type is from the same Schema if ( !typeURI.equals(fTargetNSURIString) && !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && !(typeURI.length() == 0) ) { fromAnotherSchema = typeURI; typeInfo = getTypeInfoFromNS(typeURI, localpart); if (typeInfo == null) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type " +localpart + " in schema " + typeURI); } } } else { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart); if (typeInfo == null) { dv = fDatatypeRegistry.getDatatypeValidator(localpart); if (dv == null) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (topleveltype != null) { if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { //then we found a recursive element using complexType. // REVISIT: this will be broken when recursing happens between 2 schemas fElementRecurseComplex.put(name+","+fCurrentScope, localpart); return new QName(-1, fStringPool.addSymbol(name), fStringPool.addSymbol(name), -1); } else { typeNameIndex = traverseComplexTypeDecl( topleveltype ); typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } } else { topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { typeNameIndex = traverseSimpleTypeDecl( topleveltype ); dv = fDatatypeRegistry.getDatatypeValidator(localpart); // TO DO: the Default and fixed attribute handling should be here. } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + localpart); } } } } } } else if (haveAnonType){ if (equivClassElementDecl != null ) { checkEquivClassOK(elementDecl, equivClassElementDecl); } } // this element is ur-type else { // if there is equivClass affiliation, then grab its type and stick it to this element if (equivClassElementDecl != null) { int equivClassElementDeclIndex = fSchemaGrammar.getElementDeclIndex(getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE); if ( equivClassElementDeclIndex == -1) { traverseElementDecl(equivClassElementDecl); equivClassElementDeclIndex = fSchemaGrammar.getElementDeclIndex(getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE); } ComplexTypeInfo equivClassEltType = fSchemaGrammar.getElementComplexTypeInfo( equivClassElementDeclIndex ); } } if (typeInfo == null && dv==null) { if (noErrorSoFar) { // Actually this Element's type definition is ur-type; contentSpecType = XMLElementDecl.TYPE_ANY; // REVISIT, need to wait till we have wildcards implementation. // ADD attribute wildcards here } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError ("untyped element : " + name ); } } // if element belongs to a compelx type if (typeInfo!=null) { contentSpecNodeIndex = typeInfo.contentSpecHandle; contentSpecType = typeInfo.contentType; scopeDefined = typeInfo.scopeDefined; dv = typeInfo.datatypeValidator; } // if element belongs to a simple type if (dv!=null) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; } // Create element decl int elementNameIndex = fStringPool.addSymbol(name); int localpartIndex = elementNameIndex; int uriIndex = -1; int enclosingScope = fCurrentScope; if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified || isTopLevel(elementDecl) ) { uriIndex = fTargetNSURI; enclosingScope = TOP_LEVEL_SCOPE; } //There can never be two elements with the same name in the same scope. if (fSchemaGrammar.getElementDeclIndex(localpartIndex, enclosingScope) > -1) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("duplicate element decl in the same scope : " + fStringPool.toString(localpartIndex)); } QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex); // add element decl to pool int attrListHead = -1 ; // copy up attribute decls from type object if (typeInfo != null) { attrListHead = typeInfo.attlistHead; } int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined, contentSpecType, contentSpecNodeIndex, attrListHead, dv); if ( DEBUGGING ) { System.out.println(" +" eltType:"+name+" contentSpecType:"+contentSpecType+ " SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope + " scopeDefined: " +scopeDefined); } if (typeInfo != null) { fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); } else { fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); // REVISIT: should we report error from here? } // mark element if its type belongs to different Schema. fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema); return eltQName; }// end of method traverseElementDecl(Element) int getLocalPartIndex(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return fStringPool.addSymbol(localpart); } String getLocalPart(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return localpart; } private void checkEquivClassOK(Element elementDecl, Element equivClassElementDecl){ //TO DO!! } private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception { Element child = XUtil.getFirstChildElement(fSchemaRootElement); if (child == null) { return null; } while (child != null ){ if ( child.getNodeName().equals(componentCategory)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) { return child; } } child = XUtil.getNextSiblingElement(child); } return null; } private boolean isTopLevel(Element component) { //REVISIT, is this the right way to check ? /** * Traverse attributeGroup Declaration * * <attributeGroup * id = ID * ref = QName> * Content: (annotation?) * </> * * @param elementDecl * @exception Exception */ /*private int traverseAttributeGroupDecl( Element attributeGroupDecl ) throws Exception { int attributeGroupID = fStringPool.addSymbol( attributeGroupDecl.getAttribute( SchemaSymbols.ATTVAL_ID )); int attributeGroupName = fStringPool.addSymbol( attributeGroupDecl.getAttribute( SchemaSymbols.ATT_NAME )); return -1; }*/ /** * Traverse Group Declaration. * * <group * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * ref = QName> * Content: (annotation? , (element | group | all | choice | sequence | any)*) * <group/> * * @param elementDecl * @return * @exception Exception */ private int traverseGroupDecl( Element groupDecl ) throws Exception { String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME); String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF); if (!ref.equals("")) { if (XUtil.getFirstChildElement(groupDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { return traverseGroupDeclFromAnotherSchema(localpart, uriStr); } int contentSpecIndex = -1; Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart); if (referredGroup == null) { // REVISIT: Localize reportGenericSchemaError("Group " + localpart + " not found in the Schema"); //REVISIT, this should be some custom Exception throw new Exception("Group " + localpart + " not found in the Schema"); } else { contentSpecIndex = traverseGroupDecl(referredGroup); } return contentSpecIndex; } boolean traverseElt = true; if (fCurrentScope == TOP_LEVEL_SCOPE) { traverseElt = false; } Element child = XUtil.getFirstChildElement(groupDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; int allChildren[] = null; int allChildCount = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; boolean seeAll = false; boolean seeParticle = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean illegalChild = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); //seeParticle = true; seeAll = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else { illegalChild = true; reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if ( ! illegalChild ) { index = expandContentModel( index, child); } if (seeParticle && seeAll) { reportSchemaError( SchemaMessageProvider.GroupContentRestricted, new Object [] { "'all' needs to be 'the' only Child", childName}); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+ "schema uri: " + uriStr +", groupName: " + groupName); return -1; } Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName); if (groupDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no group named \"" + groupName + "\" was defined in schema : " + uriStr); return -1; } boolean traverseElt = true; if (fCurrentScope == TOP_LEVEL_SCOPE) { traverseElt = false; } Element child = XUtil.getFirstChildElement(groupDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; int allChildren[] = null; int allChildCount = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); int childNameIndex = fStringPool.addSymbol(childName); String formAttrVal = child.getAttribute(SchemaSymbols.ATT_FORM); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } // end of method traverseGroupDeclFromAnotherSchema /** * * Traverse the Sequence declaration * * <sequence * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </sequence> * **/ int traverseSequence (Element sequenceDecl) throws Exception { Element child = XUtil.getFirstChildElement(sequenceDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } /** * * Traverse the Sequence declaration * * <choice * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </choice> * **/ int traverseChoice (Element choiceDecl) throws Exception { // REVISIT: traverseChoice, traverseSequence can be combined Element child = XUtil.getFirstChildElement(choiceDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } /** * * Traverse the "All" declaration * * <all * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </all> * **/ int traverseAll( Element allDecl) throws Exception { Element child = XUtil.getFirstChildElement(allDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int allChildren[] = null; int allChildCount = 0; int left = -2; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } try { allChildren[allChildCount] = index; } catch (NullPointerException ne) { allChildren = new int[32]; allChildren[allChildCount] = index; } catch (ArrayIndexOutOfBoundsException ae) { int[] newArray = new int[allChildren.length*2]; System.arraycopy(allChildren, 0, newArray, 0, allChildren.length); allChildren[allChildCount] = index; } allChildCount++; } left = buildAllModel(allChildren,allChildCount); return left; } /** builds the all content model */ private int buildAllModel(int children[], int count) throws Exception { // build all model if (count > 1) { // create and initialize singletons XMLContentSpec choice = new XMLContentSpec(); choice.type = XMLContentSpec.CONTENTSPECNODE_CHOICE; choice.value = -1; choice.otherValue = -1; int[] exactChildren = new int[count]; System.arraycopy(children,0,exactChildren,0,count); // build all model sort(exactChildren, 0, count); int index = buildAllModel(exactChildren, 0, choice); return index; } if (count > 0) { return children[0]; } return -1; } /** Builds the all model. */ private int buildAllModel(int src[], int offset, XMLContentSpec choice) throws Exception { // swap last two places if (src.length - offset == 2) { int seqIndex = createSeq(src); if (choice.value == -1) { choice.value = seqIndex; } else { if (choice.otherValue != -1) { choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } choice.otherValue = seqIndex; } swap(src, offset, offset + 1); seqIndex = createSeq(src); if (choice.value == -1) { choice.value = seqIndex; } else { if (choice.otherValue != -1) { choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } choice.otherValue = seqIndex; } return fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } // recurse for (int i = offset; i < src.length - 1; i++) { choice.value = buildAllModel(src, offset + 1, choice); choice.otherValue = -1; sort(src, offset, src.length - offset); shift(src, offset, i + 1); } int choiceIndex = buildAllModel(src, offset + 1, choice); sort(src, offset, src.length - offset); return choiceIndex; } // buildAllModel(int[],int,ContentSpecNode,ContentSpecNode):int /** Creates a sequence. */ private int createSeq(int src[]) throws Exception { int left = src[0]; int right = src[1]; for (int i = 2; i < src.length; i++) { left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, left, right, false); right = src[i]; } return fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, left, right, false); } // createSeq(int[]):int /** Shifts a value into position. */ private void shift(int src[], int pos, int offset) { int temp = src[offset]; for (int i = offset; i > pos; i src[i] = src[i - 1]; } src[pos] = temp; } // shift(int[],int,int) /** Simple sort. */ private void sort(int src[], final int offset, final int length) { for (int i = offset; i < offset + length - 1; i++) { int lowest = i; for (int j = i + 1; j < offset + length; j++) { if (src[j] < src[lowest]) { lowest = j; } } if (lowest != i) { int temp = src[i]; src[i] = src[lowest]; src[lowest] = temp; } } } // sort(int[],int,int) /** Swaps two values. */ private void swap(int src[], int i, int j) { int temp = src[i]; src[i] = src[j]; src[j] = temp; } // swap(int[],int,int) /** * Traverse Wildcard declaration * * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace} * processContents = lax | skip | strict> * Content: (annotation?) * </any> * @param elementDecl * @return * @exception Exception */ private int traverseWildcardDecl( Element wildcardDecl ) throws Exception { int wildcardID = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATTVAL_ID )); int wildcardMaxOccurs = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_MAXOCCURS )); int wildcardMinOccurs = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_MINOCCURS )); int wildcardNamespace = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_NAMESPACE )); int wildcardProcessContents = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_PROCESSCONTENTS )); int wildcardContent = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_CONTENT )); return -1; } // utilities from Tom Watson's SchemaParser class // TO DO: Need to make this more conformant with Schema int type parsing private int parseInt (String intString) throws Exception { if ( intString.equals("*") ) { return SchemaSymbols.INFINITY; } else { return Integer.parseInt (intString); } } private int parseSimpleDerivedBy (String derivedByString) throws Exception { if ( derivedByString.equals (SchemaSymbols.ATTVAL_LIST) ) { return SchemaSymbols.LIST; } else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { return SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ("SimpleType: Invalid value for 'derivedBy'"); return -1; } } private int parseComplexDerivedBy (String derivedByString) throws Exception { if ( derivedByString.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { return SchemaSymbols.EXTENSION; } else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { return SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "ComplexType: Invalid value for 'derivedBy'" ); return -1; } } private int parseSimpleFinal (String finalString) throws Exception { if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST+SchemaSymbols.REPRODUCTION; } else { int enumerate = 0; int restrict = 0; int list = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ("restriction in set twice"); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( list == 0 ) { list = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ("list in set twice"); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid value (" + finalString + ")" ); } } return enumerate+restrict+list+reproduce; } } private int parseComplexContent (String contentString) throws Exception { if ( contentString.equals (SchemaSymbols.ATTVAL_EMPTY) ) { return XMLElementDecl.TYPE_EMPTY; } else if ( contentString.equals (SchemaSymbols.ATTVAL_ELEMENTONLY) ) { return XMLElementDecl.TYPE_CHILDREN; } else if ( contentString.equals (SchemaSymbols.ATTVAL_TEXTONLY) ) { return XMLElementDecl.TYPE_SIMPLE; } else if ( contentString.equals (SchemaSymbols.ATTVAL_MIXED) ) { return XMLElementDecl.TYPE_MIXED; } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid value for content" ); return -1; } } private int parseDerivationSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private int parseBlockSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) { if ( extend == 0 ) { extend = SchemaSymbols.EQUIVCLASS; } else { // REVISIT: Localize reportGenericSchemaError ( "'equivClass' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( extend == 0 ) { extend = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ( "'list' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private int parseFinalSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) { if ( extend == 0 ) { extend = SchemaSymbols.EQUIVCLASS; } else { // REVISIT: Localize reportGenericSchemaError ( "'equivClass' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( extend == 0 ) { extend = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ( "'list' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private void reportGenericSchemaError (String error) throws Exception { if (fErrorReporter == null) { System.err.println("__TraverseSchemaError__ : " + error); } else { reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error }); } } private void reportSchemaError(int major, Object args[]) throws Exception { if (fErrorReporter == null) { System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]); for (int i=0; i< args.length ; i++) { System.out.println((String)args[i]); } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, major, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } //Unit Test here public static void main(String args[] ) { if( args.length != 1 ) { System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" ); System.exit(0); } DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( args[0]); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar OutputFormat format = new OutputFormat( document ); java.io.StringWriter outWriter = new java.io.StringWriter(); XMLSerializer serial = new XMLSerializer( outWriter,format); TraverseSchema tst = null; try { Element root = document.getDocumentElement();// This is what we pass to TraverserSchema //serial.serialize( root ); //System.out.println(outWriter.toString()); tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() ); } catch (Exception e) { e.printStackTrace(System.err); } parser.getDocument(); } static class Resolver implements EntityResolver { private static final String SYSTEM[] = { "http: "http: "http: }; private static final String PATH[] = { "structures.dtd", "datatypes.dtd", "versionInfo.ent", }; public InputSource resolveEntity(String publicId, String systemId) throws IOException { // looking for the schema DTDs? for (int i = 0; i < SYSTEM.length; i++) { if (systemId.equals(SYSTEM[i])) { InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i])); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } // use default resolution return null; } // resolveEntity(String,String):InputSource } // class Resolver static class ErrorHandler implements org.xml.sax.ErrorHandler { /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); throw ex; } // Private methods /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String } }
package com.github.dakusui.crest; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import java.util.function.Function; import java.util.function.Predicate; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @RunWith(Enclosed.class) public class FormattableTest { public static class FunctionTest extends CrestUnit { Function<String, String> appendA = Formattable.function("append[A]", s -> s + "A"); Function<String, String> appendB = Formattable.function("append[B]", s -> s + "B"); @Test public void givenFunctionReturnedByCompose$whenApply$thenWorksRight() { Function<String, String> composed = appendA.compose(appendB); assertEquals("HELLO:BA", composed.apply("HELLO:")); } @Test public void givenFunctionReturnedByCompose$whenToString$thenLooksGood() { Function<String, String> composed = appendA.compose(appendB); assertEquals("append[B]->append[A]", composed.toString()); } @Test public void givenFunctionReturnedByAndThen$whenApply$thenWorksRight() { Function<String, String> andThen = appendA.andThen(appendB); assertEquals("HELLO:AB", andThen.apply("HELLO:")); } @Test public void givenFunctionReturnedByAndThen$whenToString$thenLooksGood() { Function<String, String> andThen = appendA.andThen(appendB); assertEquals("append[A]->append[B]", andThen.toString()); } } public static class PredicateTest extends CrestUnit { Predicate<String> isA = Formattable.predicate("is[A]", "A"::equals); Predicate<String> isB = Formattable.predicate("is[B]", "B"::equals); @Test public void givenPredicateReturnedByAnd$whenTest$thenWorksRight() { assertFalse(isA.and(isB).test("A")); assertFalse(isA.and(isB).test("B")); assertTrue(isA.and(isB.negate()).test("A")); } @Test public void givenPredicateReturnedByAnd$whenToString$thenLooksGood() { assertEquals("(is[A]&&is[B])", isA.and(isB).toString()); } @Test public void givenPredicateReturnedByOr$whenTest$thenWorksRight() { assertTrue(isA.or(isB).test("B")); assertTrue(isA.or(isB).test("A")); assertFalse(isA.or(isB).test("C")); } @Test public void givenPredicateReturnedByOr$whenToString$thenWorksRight() { assertEquals("(is[A]||is[B])", isA.or(isB).toString()); } @Test public void givenPredicateReturnedByNegate$whenTest$thenWorksRight() { assertFalse(isA.negate().test("A")); assertTrue(isA.negate().test("B")); } @Test public void givenPredicateReturnedByNegate$whenToString$thenWorksRight() { assertEquals("!is[A]", isA.negate().toString()); } } }
/* Description: * TODO: * */ package controllers; import java.util.List; import models.DataPoint; import models.FileSystem; import models.Resource; import models.Stream; import models.User; import models.Vfile; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import play.Logger; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import play.mvc.Http.HeaderNames; import views.html.streamPage; public class CtrlStream extends Controller { static private Form<Stream> streamForm = Form.form(Stream.class); private static boolean canWrite(User user, Stream stream) { return (stream != null && user != null && stream.owner.equals(user)); } private static boolean canRead(User user, Stream stream) { return stream.canRead(user); } // do we push simple handlers down to the Ctrls? or keep in Application? /*@Security.Authenticated(Secured.class) public static Result streams() { User currentUser = Secured.getCurrentUser(); return ok(resourcesPage.render(currentUser.streamList, "")); }*/ @Security.Authenticated(Secured.class) public static Result getById(Long id) { User currentUser = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (stream== null) { return badRequest("Stream does not exist: " + id); } streamForm = streamForm.fill(stream); return ok(streamPage.render(currentUser.streamList, stream, streamForm, "")); } @Security.Authenticated(Secured.class) public static Result modify(Long id) { Form<Stream> theForm = streamForm.bindFromRequest(); if (theForm.hasErrors()) { return badRequest("Bad request: " + theForm.errorsAsJson().toString()); } else { Stream submitted = theForm.get(); User currentUser = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (stream == null || !stream.canWrite(currentUser)) { return unauthorized("Unauthorized!"); } // probably not the correct way to do it if (submitted.latitude != 0.0) { //String lon = streamForm.field("longtitude").value(); //String lat = streamForm.field("latitude").value(); //Logger.error("form latlon: "+lat+","+lon); //Location location = new Location(lon,lat); //submitted.location.setLatLon(lat,lon); } else { Logger.error("location not set"); } stream.updateStream(submitted); } return redirect(routes.Application.viewStream(id)); } @Security.Authenticated(Secured.class) public static Result download(Long id) { final User currentUser = Secured.getCurrentUser(); final Stream stream = Stream.get(id); final List<? extends DataPoint> dataSet = stream.getDataPoints(); if (stream.canRead(currentUser)) { final String streamName = "# SicsthSense "+currentUser.userName+" "+stream.file.getPath()+"\n"; response().setContentType("text/plain"); response().setHeader("Content-Disposition", "attachment; filename="+stream.resource.label+"-Stream.txt"); Chunks<String> chunks = new StringChunks() { // Called when the stream is ready public void onReady(Chunks.Out<String> out) { if (dataSet == null) { out.close(); return; } out.write(streamName); for (DataPoint dp: dataSet) { out.write(dp.toTSV()+"\n"); } out.close(); } }; return ok(chunks); } return unauthorized(); } @Security.Authenticated(Secured.class) public static Result delete(Long id) { final User currentUser = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (canWrite(currentUser, stream)) { stream.delete(); currentUser.sortStreamList(); // reorder streams return ok(); } return unauthorized(); } public static Result deleteByKey(String key) { final Stream stream = Stream.getByKey(key); if (stream == null) { return notFound(); } stream.delete(); return ok(); } @Security.Authenticated(Secured.class) public static Result clear(Long id) { final User user = Secured.getCurrentUser(); // if(user == null) return notFound(); Stream stream = Stream.get(id); if (canWrite(user, stream)) { stream.clearStream(); return ok(); } return unauthorized(); } public static Result clearByKey(String key) { final Stream stream = Stream.getByKey(key); if (stream == null) { return notFound(); } stream.clearStream(); return ok(); } @Security.Authenticated(Secured.class) public static Result setPublicAccess(Long id, Boolean pub) { final User user = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (canWrite(user, stream)) { return ok(Boolean.toString(stream.setPublicAccess(pub))); } return unauthorized(); } // @Security.Authenticated(Secured.class) public static Result isPublicAccess(Long id) { Stream stream = Stream.get(id); if(stream == null) { return notFound(); } return ok(Boolean.toString(stream.publicAccess)); } @Security.Authenticated(Secured.class) public static Result setPublicSearch(Long id, Boolean pub) { final User user = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (canWrite(user, stream)) { return ok(Boolean.toString(stream.setPublicSearch(pub))); } return unauthorized(); } //@Security.Authenticated(Secured.class) public static Result isPublicSearch(Long id) { Stream stream = Stream.get(id); if(stream == null) { return notFound(); } return ok(Boolean.toString(stream.publicSearch)); } public static Result getByKey(String key, Long tail, Long last, Long since) { final Stream stream = Stream.getByKey(key); if (stream == null) return notFound(); return getData(stream.owner, stream, tail, last, since); } // List data points of a user's path public static Result getByPath(String path, Long tail, Long last, Long since) { final User user = Secured.getCurrentUser(); if(user == null) { return notFound(); } return getByUserPath(user.userName, path, tail, last, since); } public static Result getByUserPath(String username, String path, Long tail, Long last, Long since) { path=Utils.decodePath(path); final Stream stream = Stream.getByUserPath(username,"/"+path); final User owner = User.getByUserName(username); final User currentUser = Secured.getCurrentUser(); if (stream == null) { return notFound(); } if (!stream.canRead(currentUser)) { // don't reveal this stream exists return notFound(); } return getData(currentUser, stream, tail, last, since); } public static Result postByPath(String path) { final User user = Secured.getCurrentUser(); if (user == null) { return notFound(); } String username = user.userName; path = Utils.decodePath(path); final Stream stream = Stream.getByUserPath(username, "/" + path); if (stream == null) return notFound(); return post(user, stream); } public static Result postByKey(String key) { final Stream stream = Stream.getByKey(key); if (stream == null) return notFound(); return post(stream.owner, stream); } @Security.Authenticated(Secured.class) public static Result post(Long id) { final User user = Secured.getCurrentUser(); Stream stream = Stream.get(id); if(stream == null) { return notFound(); } return post(user, stream); } private static Result post(User user, Stream stream) { boolean success = false; long currentTime = Utils.currentTime(); String textBody=""; try { if (canWrite(user, stream)) { // Logger.info("StreamParser: parseResponse(): post: "+stream.file.getPath()); if ("application/json".equalsIgnoreCase(request().getHeader( HeaderNames.CONTENT_TYPE)) || "text/json".equalsIgnoreCase(request().getHeader(HeaderNames.CONTENT_TYPE))) { JsonNode jsonBody = request().body().asJson(); textBody += jsonBody.asText(); // Logger.info("[StreamParser] as json"); success = parseJsonResponse(stream, jsonBody, currentTime); } else { textBody = request().body().asText(); // request.body().asRaw().toString(); // Logger.info("[StreamParser] as text"); double number = Double.parseDouble(textBody); success = stream.post(number, currentTime); } if (!success) { return badRequest("Bad request: Error! " + textBody); } else { return ok("ok"); } } } catch (Exception e) { return badRequest("Bad request: Error! " + e.getMessage()); } return unauthorized(); } private static boolean parseJsonResponse(Stream stream, JsonNode root, Long currentTime) { // TODO check concat path against inputParser, get the goal and stop // TODO (linear time) form a list of nested path elements from the gui, and if (root == null) { return false; } JsonNode node = root; if (node.isValueNode()) { // it is a simple primitive Logger.info("posting: " + node.getDoubleValue() + " " + Utils.currentTime()); return stream.post(node.getDoubleValue(), Utils.currentTime()); } else if (node.get("value") != null) { // it may be value:X double value = node.get("value").getDoubleValue(); // should be resource timestamp if (node.get("time") != null) { // it may have time:Y currentTime = node.get("time").getLongValue(); } Logger.info("posting: " + node.getDoubleValue() + " " + Utils.currentTime()); return stream.post(value, currentTime); } return false; } @Security.Authenticated(Secured.class) public static Result getData(String ownerName, String path, Long tail, Long last, Long since) { final User user = Secured.getCurrentUser(); final User owner = User.getByUserName(ownerName); // if(user == null) return notFound(); return getData(user, owner, path, tail, last, since); } @Security.Authenticated(Secured.class) public static Result getDataById(Long id, Long tail, Long last, Long since) { final User user = Secured.getCurrentUser(); Stream stream = Stream.get(id); return getData(user, stream, tail, last, since); } @Security.Authenticated(Secured.class) public static Result regenerateKey(Long id) { User currentUser = Secured.getCurrentUser(); Stream stream = Stream.get(id); if (stream == null || stream.owner.id != currentUser.id) { return badRequest("Stream does not exist: " + id); } String key = stream.updateKey(); //return ok("Stream key reset successfully: " + id + " New key: " + key); return ok(key); } // @Security.Authenticated(Secured.class) private static Result getData(User currentUser, User owner, String path, Long tail, Long last, Long since) { Vfile f = FileSystem.readFile(owner, path); if (f == null) { return notFound(); } Stream stream = f.getLink(); if (stream == null) { return notFound(); } return getData(currentUser, stream, tail, last, since); } //tail: number of points, last: point during last {seconds}, since: Unix timestamp private static Result getData(User currentUser, Stream stream, Long tail, Long last, Long since) { if (stream == null) { return notFound(); } if (!stream.canRead(currentUser)) return unauthorized("Private stream!"); List<? extends DataPoint> dataSet = null; if (tail < 0 && last < 0 && since < 0) { tail = 1L; } if (tail >= 0) { dataSet = stream.getDataPointsTail(tail); } else if (last >= 0) { dataSet = stream.getDataPointsLast(last*1000); } else if (since >= 0) { dataSet = stream.getDataPointsSince(since); } else { throw new RuntimeException("This cannot happen!"); } ObjectNode result = Json.newObject(); ArrayNode time = result.putArray("time"); ArrayNode data = result.putArray("data"); if (dataSet!= null) { for (DataPoint dataPoint : dataSet) { time.add(dataPoint.timestamp); if (stream.getType() == Stream.StreamType.DOUBLE) { data.add((Double) dataPoint.getData()); } } } return ok(result); } }
package mb.statix.spec; import static mb.nabl2.terms.build.TermBuild.B; import static mb.nabl2.terms.matching.TermPattern.P; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.immutables.serial.Serial; import org.immutables.value.Value; import org.metaborg.util.collection.CapsuleUtil; import org.metaborg.util.functions.Action1; import com.google.common.collect.ImmutableList; import io.usethesource.capsule.Set; import io.usethesource.capsule.util.stream.CapsuleCollectors; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.ITermVar; import mb.nabl2.terms.matching.Pattern; import mb.nabl2.terms.substitution.FreshVars; import mb.nabl2.terms.substitution.IRenaming; import mb.nabl2.terms.substitution.ISubstitution; import mb.nabl2.terms.unification.ud.PersistentUniDisunifier; import mb.nabl2.util.TermFormatter; import mb.statix.constraints.Constraints; import mb.statix.solver.Delay; import mb.statix.solver.IConstraint; import mb.statix.solver.completeness.ICompleteness; import mb.statix.spec.ApplyMode.Safety; @Value.Immutable @Serial.Version(42L) public abstract class ARule { @Value.Default public String label() { return ""; } @Value.Parameter public abstract String name(); @Value.Parameter public abstract List<Pattern> params(); @Value.Lazy public Set.Immutable<ITermVar> paramVars() { return params().stream().flatMap(t -> t.getVars().stream()).collect(CapsuleCollectors.toSet()); } @Value.Parameter public abstract IConstraint body(); @Value.Default public @Nullable ICompleteness.Immutable bodyCriticalEdges() { return null; } @Value.Lazy public Optional<Boolean> isAlways() throws InterruptedException { final List<ITermVar> args = IntStream.range(0, params().size()).mapToObj(idx -> B.newVar("", "arg" + idx)) .collect(Collectors.toList()); final ApplyResult applyResult; try { if((applyResult = RuleUtil.apply(PersistentUniDisunifier.Immutable.of(), (Rule) this, args, null, ApplyMode.STRICT, Safety.SAFE).orElse(null)) == null) { return Optional.empty(); } } catch(Delay d) { return Optional.empty(); } if(applyResult.guard().isPresent()) { return Optional.empty(); } return Constraints.trivial(body()); } private volatile Set.Immutable<ITermVar> freeVars; public Set.Immutable<ITermVar> freeVars() { Set.Immutable<ITermVar> result = freeVars; if(freeVars == null) { final Set.Transient<ITermVar> _freeVars = CapsuleUtil.transientSet(); doVisitFreeVars(_freeVars::__insert); result = _freeVars.freeze(); freeVars = result; } return result; } public void visitFreeVars(Action1<ITermVar> onFreeVar) { freeVars().forEach(onFreeVar::apply); } private void doVisitFreeVars(Action1<ITermVar> onFreeVar) { final Set.Immutable<ITermVar> paramVars = paramVars(); body().visitFreeVars(v -> { if(!paramVars.contains(v)) { onFreeVar.apply(v); } }); } protected Rule setFreeVars(Set.Immutable<ITermVar> freeVars) { this.freeVars = freeVars; return (Rule) this; } /** * Apply capture avoiding substitution. */ public Rule apply(ISubstitution.Immutable subst) { ISubstitution.Immutable localSubst = subst.removeAll(paramVars()).retainAll(freeVars()); if(localSubst.isEmpty()) { return (Rule) this; } List<Pattern> params = this.params(); IConstraint body = this.body(); ICompleteness.Immutable bodyCriticalEdges = this.bodyCriticalEdges(); Set.Immutable<ITermVar> freeVars = this.freeVars; if(freeVars != null) { // before renaming is included in localSubst freeVars = freeVars.__removeAll(localSubst.domainSet()).__insertAll(localSubst.rangeSet()); } final FreshVars fresh = new FreshVars(localSubst.domainSet(), localSubst.rangeSet(), freeVars()); final IRenaming ren = fresh.fresh(paramVars()); fresh.fix(); if(!ren.isEmpty()) { params = params().stream().map(p -> p.apply(ren)).collect(ImmutableList.toImmutableList()); localSubst = ren.asSubstitution().compose(localSubst); } body = body.apply(localSubst); if(bodyCriticalEdges != null) { bodyCriticalEdges = bodyCriticalEdges.apply(localSubst); } return Rule.of(name(), params, body).withBodyCriticalEdges(bodyCriticalEdges).setFreeVars(freeVars); } /** * Apply unguarded substitution, which may result in capture. */ public Rule unsafeApply(ISubstitution.Immutable subst) { ISubstitution.Immutable localSubst = subst.removeAll(paramVars()); if(localSubst.isEmpty()) { return (Rule) this; } List<Pattern> params = this.params(); IConstraint body = this.body(); ICompleteness.Immutable bodyCriticalEdges = this.bodyCriticalEdges(); body = body.unsafeApply(localSubst); if(bodyCriticalEdges != null) { bodyCriticalEdges = bodyCriticalEdges.apply(localSubst); } return Rule.of(name(), params, body).withBodyCriticalEdges(bodyCriticalEdges); } /** * Apply variable renaming. */ public Rule apply(IRenaming subst) { List<Pattern> params = this.params(); IConstraint body = this.body(); ICompleteness.Immutable bodyCriticalEdges = this.bodyCriticalEdges(); params = params().stream().map(p -> p.apply(subst)).collect(ImmutableList.toImmutableList()); body = body.apply(subst); if(bodyCriticalEdges != null) { bodyCriticalEdges = bodyCriticalEdges.apply(subst); } return Rule.of(name(), params, body).withBodyCriticalEdges(bodyCriticalEdges); } public String toString(TermFormatter termToString) { final StringBuilder sb = new StringBuilder(); if(!label().isEmpty()) { sb.append("[").append(label()).append("] "); } if(name().isEmpty()) { sb.append("{ "); } else { sb.append(name()).append("("); } sb.append(params().stream().map(Pattern::toString).collect(Collectors.joining(", "))); if(!name().isEmpty()) { sb.append(")"); } sb.append(" :- "); sb.append(body().toString(termToString)); if(name().isEmpty()) { sb.append(" }"); } else { sb.append("."); } return sb.toString(); } @Override public String toString() { return toString(ITerm::toString); } /** * Note: this comparator imposes orderings that are inconsistent with equals. */ public static final LeftRightOrder leftRightPatternOrdering = new LeftRightOrder(); /** * Note: this comparator imposes orderings that are inconsistent with equals. */ public static class LeftRightOrder { public Optional<Integer> compare(Rule r1, Rule r2) { final Pattern p1 = P.newTuple(r1.params()); final Pattern p2 = P.newTuple(r2.params()); return Pattern.leftRightOrdering.compare(p1, p2); } public Comparator<Rule> asComparator() { return (r1, r2) -> LeftRightOrder.this.compare(r1, r2).orElse(0); } } }
package com.nhn.pinpoint.bootstrap; import com.nhn.pinpoint.ProductInfo; import com.nhn.pinpoint.common.PinpointConstants; import com.nhn.pinpoint.common.util.TransactionIdUtils; import com.nhn.pinpoint.profiler.config.ProfilerConfig; import java.io.UnsupportedEncodingException; import java.lang.instrument.Instrumentation; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class PinpointBootStrap { private static final Logger logger = Logger.getLogger(PinpointBootStrap.class.getName()); private static final int LIMIT_LENGTH = 24; private static final String DELIMITER = TransactionIdUtils.TRANSACTION_ID_DELIMITER; public static final String BOOT_CLASS = "com.nhn.pinpoint.profiler.DefaultAgent"; public static void premain(String agentArgs, Instrumentation instrumentation) { if (agentArgs != null) { logger.info(ProductInfo.CAMEL_NAME + " agentArgs:" + agentArgs); } ClassPathResolver classPathResolver = new ClassPathResolver(); boolean agentJarNotFound = classPathResolver.findAgentJar(); if (!agentJarNotFound) { // TODO . logger.severe("pinpoint-bootstrap-x.x.x.jar not found."); return; } if (!checkProfilerIdSize("pinpoint.agentId", PinpointConstants.AGENT_NAME_MAX_LEN)) { return; } if (!checkProfilerIdSize("pinpoint.applicationName", PinpointConstants.APPLICATION_NAME_MAX_LEN)) { return; } String configPath = getConfigPath(classPathResolver); if (configPath == null ) { return; } // properties . saveLogFilePath(classPathResolver); try { // bootstrap ? ProfilerConfig profilerConfig = new ProfilerConfig(); profilerConfig.readConfigFile(configPath); // lib List. List<URL> libUrlList = resolveLib(classPathResolver); AgentClassLoader agentClassLoader = new AgentClassLoader(libUrlList.toArray(new URL[libUrlList.size()])); agentClassLoader.setBootClass(BOOT_CLASS); logger.info("pinpoint agent start."); agentClassLoader.boot(agentArgs, instrumentation, profilerConfig); logger.info("pinpoint agent start success."); } catch (Exception e) { logger.log(Level.SEVERE, ProductInfo.CAMEL_NAME + " start fail. Caused:" + e.getMessage(), e); } } private static boolean checkProfilerIdSize(String propertyName, int maxSize) { logger.info("check -D" + propertyName); String value = System.getProperty(propertyName); if (value != null) { value = value.trim(); final byte[] bytes; try { bytes = toBytes(value); } catch (UnsupportedEncodingException e) { logger.severe("toBytes() fail. propertyName:" + propertyName + " propertyValue:" + value); return false; } if (bytes.length == 0) { logger.severe("invalid " + propertyName + ". agentId is empty. length:" + bytes.length + " value:" + value); return false; } if (bytes.length > maxSize) { logger.severe("invalid " + propertyName + ". too large bytes. length:" + bytes.length + " value:" + value); return false; } logger.info("check success. -D" + propertyName + ":" + value + " length:" + bytes.length); return true; } else { logger.severe("-D" + propertyName + " is null."); return false; } } private static byte[] toBytes(String property) throws UnsupportedEncodingException { return property.getBytes("UTF-8"); } private static void saveLogFilePath(ClassPathResolver classPathResolver) { String agentLogFilePath = classPathResolver.getAgentLogFilePath(); logger.info("logPath:" + agentLogFilePath); System.setProperty(ProductInfo.NAME + "." + "log", agentLogFilePath); } private static String getConfigPath(ClassPathResolver classPathResolver) { final String configName = ProductInfo.NAME + ".config"; String pinpointConfigFormSystemProperty = System.getProperty(configName); if (pinpointConfigFormSystemProperty != null) { logger.info(configName + " systemProperty found. " + pinpointConfigFormSystemProperty); return pinpointConfigFormSystemProperty; } String classPathAgentConfigPath = classPathResolver.getAgentConfigPath(); if (classPathAgentConfigPath != null) { logger.info("classpath " + configName + " found. " + classPathAgentConfigPath); return classPathAgentConfigPath; } logger.severe(configName + " file not found."); return null; } private static List<URL> resolveLib(ClassPathResolver classPathResolver) { // . (./../agentlib/lib) . String agentJarFullPath = classPathResolver.getAgentJarFullPath(); String agentLibPath = classPathResolver.getAgentLibPath(); List<URL> urlList = classPathResolver.resolveLib(); String agentConfigPath = classPathResolver.getAgentConfigPath(); if (logger.isLoggable(Level.INFO)) { logger.info("agentJarPath:" + agentJarFullPath); logger.info("agentLibPath:" + agentLibPath); logger.info("agent lib list:" + urlList); logger.info("agent config:" + agentConfigPath); } return urlList; } }
package com.github.gchudnov.squel; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Expression Tests. */ public class ExpressionTest { @Test public void and() { String actual = Squel.expr() .and("bla") .toString(); String expected = "bla"; assertEquals(expected, actual); } @Test public void or() { String actual = Squel.expr() .or("bla") .toString(); String expected = "bla"; assertEquals(expected, actual); } @Test public void simpleAnd() { String actual = Squel.expr() .and("test = 3") .toString(); String expected = "test = 3"; assertEquals(expected, actual); } @Test public void twoAnd() { String actual = Squel.expr() .and("test = 3") .and("flight = '4'") .toString(); String expected = "test = 3 AND flight = '4'"; assertEquals(expected, actual); } @Test public void andOr() { String actual = Squel.expr() .and("test = 3") .and("flight = '4'") .or("dummy IN (1,2,3)") .toString(); String expected = "test = 3 AND flight = '4' OR dummy IN (1,2,3)"; assertEquals(expected, actual); } @Test public void composite() { String actual = Squel.expr() .and("test = 4") .and_begin() .or("inner = 1") .or("inner = 2") .end() .or_begin() .and("inner = 3") .and("inner = 4") .or_begin() .or("inner = 5") .end() .end() .toString(); String expected = "test = 4 AND (inner = 1 OR inner = 2) OR (inner = 3 AND inner = 4 OR (inner = 5))"; assertEquals(expected, actual); } }
package fi.jumi.test; import fi.jumi.launcher.daemon.Daemon; import fi.jumi.test.PartiallyParameterized.NonParameterized; import fi.jumi.test.util.XmlUtils; import org.hamcrest.Matcher; import org.hamcrest.core.CombinableMatcher; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import org.objectweb.asm.tree.ClassNode; import org.w3c.dom.*; import javax.annotation.concurrent.*; import javax.xml.xpath.*; import java.io.*; import java.util.*; import java.util.jar.*; import static fi.jumi.test.util.AsmUtils.*; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertTrue; @RunWith(PartiallyParameterized.class) public class BuildTest { private static final String POM_FILES = "META-INF/maven/fi.jumi/"; private static final String BASE_PACKAGE = "fi/jumi/"; private static final String[] DOES_NOT_NEED_JSR305_ANNOTATIONS = { // shaded classes "fi/jumi/daemon/INTERNAL/", "fi/jumi/launcher/INTERNAL/", // generated classes "fi/jumi/core/events/", // ignore, because the ThreadSafetyAgent anyways won't checked itself "fi/jumi/threadsafetyagent/", }; private final String artifactId; private final List<String> expectedDependencies; private final List<String> expectedContents; public BuildTest(String artifactId, List<String> expectedDependencies, List<String> expectedContents) { this.artifactId = artifactId; this.expectedDependencies = expectedDependencies; this.expectedContents = expectedContents; } @Parameters @SuppressWarnings("unchecked") public static Collection<Object[]> data() { return asList(new Object[][]{ {"jumi-actors", asList(), asList( POM_FILES, BASE_PACKAGE + "actors/") }, {"jumi-api", asList(), asList( POM_FILES, BASE_PACKAGE + "api/") }, {"jumi-core", asList( "fi.jumi:jumi-actors", "fi.jumi:jumi-api"), asList( POM_FILES, BASE_PACKAGE + "core/") }, {"jumi-daemon", asList(), asList( POM_FILES, BASE_PACKAGE + "actors/", BASE_PACKAGE + "api/", BASE_PACKAGE + "core/", BASE_PACKAGE + "daemon/") }, {"jumi-launcher", asList( "fi.jumi:jumi-core"), asList( POM_FILES, BASE_PACKAGE + "launcher/") }, {"thread-safety-agent", asList(), asList( POM_FILES, BASE_PACKAGE + "threadsafetyagent/") }, }); } @Test public void pom_contains_only_allowed_dependencies() throws Exception { File pomFile = TestEnvironment.getProjectPom(artifactId); Document pom = XmlUtils.parseXml(pomFile); List<String> dependencies = getRuntimeDependencies(pom); assertThat("dependencies of " + artifactId, dependencies, is(expectedDependencies)); } @Test public void jar_contains_only_allowed_files() throws Exception { File jarFile = TestEnvironment.getProjectJar(artifactId); assertJarContainsOnly(jarFile, expectedContents); } @Test @NonParameterized public void embedded_daemon_jar_contains_only_jumi_classes() throws IOException { assertJarContainsOnly(Daemon.getDaemonJarAsStream(), asList( POM_FILES, BASE_PACKAGE )); } @Test public void none_of_the_artifacts_may_have_dependencies_to_external_libraries() { for (String dependency : expectedDependencies) { assertThat("artifact " + artifactId, dependency, startsWith("fi.jumi:")); } } @Test @SuppressWarnings({"unchecked"}) public void none_of_the_artifacts_may_contain_classes_from_external_libraries_without_shading_them() { for (String content : expectedContents) { // XXX: doesn't work inlined, Java's/Hamcrest's generics are broken (and FEST-Assert doesn't have "or") Matcher m1 = startsWith(POM_FILES); Matcher m2 = startsWith(BASE_PACKAGE); CombinableMatcher matcher = either(m2).or(m1); assertThat("artifact " + artifactId, content, matcher); } } @Test public void all_classes_must_be_annotated_with_JSR305_concurrent_annotations() throws Exception { File jarFile = TestEnvironment.getProjectJar(artifactId); JarInputStream in = new JarInputStream(new FileInputStream(jarFile)); JarEntry entry; AssertionError errors = null; while ((entry = in.getNextJarEntry()) != null) { if (!shouldHaveJsr305ConcurrencyAnnotation(entry)) { continue; } ClassNode cn = readClass(in); if (isInterface(cn)) { continue; } if (isSynthetic(cn)) { continue; } try { assertThat(cn, is(annotatedWithOneOf(Immutable.class, NotThreadSafe.class, ThreadSafe.class))); } catch (AssertionError e) { errors = (AssertionError) e.initCause(errors); } } if (errors != null) { throw errors; } in.close(); } private static boolean shouldHaveJsr305ConcurrencyAnnotation(JarEntry entry) { if (entry.isDirectory()) { return false; } if (!entry.getName().endsWith(".class")) { return false; } for (String prefix : DOES_NOT_NEED_JSR305_ANNOTATIONS) { if (entry.getName().startsWith(prefix)) { return false; } } return true; } // helper methods private static void assertJarContainsOnly(File jar, List<String> whitelist) throws IOException { try { assertJarContainsOnly(new FileInputStream(jar), whitelist); } catch (AssertionError e) { throw (AssertionError) new AssertionError(jar + " " + e.getMessage()).initCause(e); } } private static void assertJarContainsOnly(InputStream jarAsStream, List<String> whitelist) throws IOException { JarInputStream in = new JarInputStream(jarAsStream); JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { assertIsWhitelisted(entry, whitelist); } } private static void assertIsWhitelisted(JarEntry entry, List<String> whitelist) { boolean allowed = false; for (String s : whitelist) { allowed |= entry.getName().startsWith(s); allowed |= s.startsWith(entry.getName()); } assertTrue("contained a not allowed entry: " + entry, allowed); } private static List<String> getRuntimeDependencies(Document doc) throws XPathExpressionException { NodeList nodes = (NodeList) XmlUtils.xpath( "/project/dependencies/dependency[not(scope) or scope='compile' or scope='runtime']", doc, XPathConstants.NODESET); List<String> results = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { Node dependency = nodes.item(i); String groupId = XmlUtils.xpath("groupId", dependency); String artifactId = XmlUtils.xpath("artifactId", dependency); results.add(groupId + ":" + artifactId); } return results; } }
package mb.statix.spec; import static mb.nabl2.terms.build.TermBuild.B; import static mb.nabl2.terms.matching.TermPattern.P; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import org.immutables.serial.Serial; import org.immutables.value.Value; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.ITermVar; import mb.nabl2.terms.matching.Pattern; import mb.nabl2.terms.substitution.ISubstitution; import mb.nabl2.terms.unification.IUnifier; import mb.nabl2.terms.unification.PersistentUnifier; import mb.nabl2.util.TermFormatter; import mb.statix.constraints.CExists; import mb.statix.solver.Delay; import mb.statix.solver.IConstraint; import mb.statix.solver.log.NullDebugContext; import mb.statix.solver.persistent.Solver; import mb.statix.solver.persistent.State; @Value.Immutable @Serial.Version(42L) public abstract class ARule { @Value.Default public String label() { return ""; } @Value.Parameter public abstract String name(); @Value.Parameter public abstract List<Pattern> params(); @Value.Lazy public Set<ITermVar> paramVars() { return params().stream().flatMap(t -> t.getVars().stream()).collect(ImmutableSet.toImmutableSet()); } @Value.Parameter public abstract IConstraint body(); @Value.Lazy public Optional<Boolean> isAlways(Spec spec) throws InterruptedException { // 1. Create arguments final ImmutableList.Builder<ITermVar> argsBuilder = ImmutableList.builder(); for(int i = 0; i < params().size(); i++) { argsBuilder.add(B.newVar("", "arg" + Integer.toString(i))); } final ImmutableList<ITermVar> args = argsBuilder.build(); // 2. Instantiate body final IConstraint instBody; try { if((instBody = apply(args, PersistentUnifier.Immutable.of()).orElse(null)) == null) { return Optional.of(false); } } catch(Delay e) { return Optional.of(false); } // 3. Solve constraint try { final IConstraint constraint = new CExists(args, instBody); return Optional.of(Solver.entails(State.of(spec), constraint, (s, l, st) -> true, new NullDebugContext())); } catch(Delay d) { return Optional.empty(); } } public Rule apply(ISubstitution.Immutable subst) { final IConstraint newBody = body().apply(subst.removeAll(paramVars())); return Rule.of(name(), params(), newBody); } public Optional<IConstraint> apply(List<? extends ITerm> args, IUnifier unifier) throws Delay { return apply(args, unifier, null); } public Optional<IConstraint> apply(List<? extends ITerm> args, IUnifier unifier, @Nullable IConstraint cause) throws Delay { final ISubstitution.Transient subst; final Optional<ISubstitution.Immutable> matchResult = P.match(params(), args, unifier).orElseThrow(vars -> Delay.ofVars(vars)); if((subst = matchResult.map(u -> u.melt()).orElse(null)) == null) { return Optional.empty(); } final ISubstitution.Immutable isubst = subst.freeze(); final IConstraint newBody = body().apply(isubst); return Optional.of(newBody.withCause(cause)); } public String toString(TermFormatter termToString) { final StringBuilder sb = new StringBuilder(); if(!label().isEmpty()) { sb.append("[").append(label()).append("] "); } if(name().isEmpty()) { sb.append("{ ").append(params()); } else { sb.append(name()).append("(").append(params()).append(")"); } sb.append(" :- "); sb.append(body().toString(termToString)); if(name().isEmpty()) { sb.append(" }"); } else { sb.append("."); } return sb.toString(); } @Override public String toString() { return toString(ITerm::toString); } /** * Note: this comparator imposes orderings that are inconsistent with equals. */ public static final LeftRightOrder leftRightPatternOrdering = new LeftRightOrder(); /** * Note: this comparator imposes orderings that are inconsistent with equals. */ public static class LeftRightOrder { public Optional<Integer> compare(Rule r1, Rule r2) { final Pattern p1 = P.newTuple(r1.params()); final Pattern p2 = P.newTuple(r2.params()); return Pattern.leftRightOrdering.compare(p1, p2); } public Comparator<Rule> asComparator() { return new Comparator<Rule>() { @Override public int compare(Rule r1, Rule r2) { return LeftRightOrder.this.compare(r1, r2).orElse(0); } }; } } }
package org.jetbrains.plugins.scala.compiler; import com.intellij.compiler.CompilerException; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.compiler.impl.javaCompiler.BackendCompilerWrapper; import com.intellij.compiler.make.CacheCorruptedException; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.compiler.TranslatingCompiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.JavaModuleType; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.scala.ScalaBundle; import org.jetbrains.plugins.scala.ScalaFileType; /** * @author ven, ilyas */ public class ScalaCompiler implements TranslatingCompiler { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.scala.compiler.ScalaCompiler"); private Project myProject; private static final FileTypeManager FILE_TYPE_MANAGER = FileTypeManager.getInstance(); public ScalaCompiler(Project project) { myProject = project; } @NotNull public String getDescription() { return ScalaBundle.message("scala.compiler.description"); } public boolean isCompilableFile(VirtualFile file, CompileContext context) { final FileType fileType = FILE_TYPE_MANAGER.getFileTypeByFile(file); Module module = context.getModuleByFile(file); return fileType.equals(ScalaFileType.SCALA_FILE_TYPE) || context.getProject() != null && fileType.equals(StdFileTypes.JAVA) && ScalacSettings.getInstance(context.getProject()).SCALAC_BEFORE && module != null && module.getModuleType() instanceof JavaModuleType; } public ExitStatus compile(CompileContext context, VirtualFile[] files) { final BackendCompiler backEndCompiler = getBackEndCompiler(); final BackendCompilerWrapper wrapper = new BackendCompilerWrapper(myProject, files, (CompileContextEx) context, backEndCompiler); OutputItem[] outputItems; try { outputItems = wrapper.compile(); } catch (CompilerException e) { outputItems = EMPTY_OUTPUT_ITEM_ARRAY; context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); } catch (CacheCorruptedException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); outputItems = EMPTY_OUTPUT_ITEM_ARRAY; } return new ExitStatusImpl(outputItems, wrapper.getFilesToRecompile()); } public boolean validateConfiguration(CompileScope scope) { return getBackEndCompiler().checkCompiler(scope); } private BackendCompiler getBackEndCompiler() { return new ScalacCompiler(myProject); } private static class ExitStatusImpl implements ExitStatus { private OutputItem[] myOuitputItems; private VirtualFile[] myMyFilesToRecompile; public ExitStatusImpl(OutputItem[] ouitputItems, VirtualFile[] myFilesToRecompile) { myOuitputItems = ouitputItems; myMyFilesToRecompile = myFilesToRecompile; } public OutputItem[] getSuccessfullyCompiled() { return myOuitputItems; } public VirtualFile[] getFilesToRecompile() { return myMyFilesToRecompile; } } }
package com.github.rconner.anansi; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import static com.github.rconner.anansi.WalkTest.assertWalkContains; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public final class TraversersTest { // We'll be using Multimaps to define adjacency for test cases. // Lacking a key (vertex) means that there are no walks leaving that vertex. There is no way, using this // representation, to denote whether or not a vertex is present. Any vertex is present. private final Multimap<String, Walk<String, String>> empty = ImmutableMultimap.of(); private final Multimap<String, Walk<String, String>> singleEdge = ImmutableMultimap.of( "A", Walk.single( "A", "B", "A->B" ) ); // Warning! Do not perform a post-order traversal on this graph. private final Multimap<String, Walk<String, String>> loop = ImmutableMultimap.of( "A", Walk.single( "A", "A", "A->A" ) ); // Warning! Do not perform a post-order traversal on this graph. private final Multimap<String, Walk<String, String>> cycle = ImmutableListMultimap.<String, Walk<String, String>>builder() .put( "A", Walk.single( "A", "B", "A->B" ) ) .put( "B", Walk.single( "B", "C", "B->C" ) ) .put( "C", Walk.single( "C", "A", "C->A" ) ) .build(); private final Multimap<String, Walk<String, String>> tree = ImmutableListMultimap.<String, Walk<String, String>>builder() .put( "A", Walk.single( "A", "B", "A->B" ) ) .put( "A", Walk.single( "A", "C", "A->C" ) ) .put( "B", Walk.single( "B", "D", "B->D" ) ) .put( "B", Walk.single( "B", "E", "B->E" ) ) .put( "C", Walk.single( "C", "F", "C->F" ) ) .put( "C", Walk.single( "C", "G", "C->G" ) ) .build(); // Has two paths from A to D. private final Multimap<String, Walk<String, String>> dag = ImmutableListMultimap.<String, Walk<String, String>>builder() .put( "A", Walk.single( "A", "B", "A->B" ) ) .put( "A", Walk.single( "A", "C", "A->C" ) ) .put( "B", Walk.single( "B", "D", "B->D" ) ) .put( "B", Walk.single( "B", "E", "B->E" ) ) .put( "C", Walk.single( "C", "D", "C->D" ) ) .put( "D", Walk.single( "D", "G", "D->G" ) ) .build(); private static Traverser<String, String> adjacencyFor( final Multimap<String, Walk<String, String>> graph ) { return new Traverser<String, String>() { @Override public Iterable<Walk<String, String>> apply( final String input ) { return graph.get( input ); } }; } static <V, E> void assertTraversalContains( final Iterable<Walk<V, E>> traversal, final Object[][] actualWalks ) { Iterator<Walk<V, E>> iterator = traversal.iterator(); for( Object[] actualWalk : actualWalks ) { assertThat( iterator.hasNext(), is( true ) ); assertWalkContains( iterator.next(), actualWalk ); } assertThat( iterator.hasNext(), is( false ) ); try { iterator.next(); fail( "Should have thrown a NoSuchElementException." ); } catch( NoSuchElementException ignored ) { // success } } static <V, E> void assertTraversalBegins( final Iterable<Walk<V, E>> traversal, final Object[][] actualWalks ) { Iterator<Walk<V, E>> iterator = traversal.iterator(); for( Object[] actualWalk : actualWalks ) { assertThat( iterator.hasNext(), is( true ) ); assertWalkContains( iterator.next(), actualWalk ); } assertThat( iterator.hasNext(), is( true ) ); } // empty() @Test public void empty() { final Traverser<String, String> traverser = Traversers.empty(); assertTraversalContains( traverser.apply( "A" ), new Object[][] { } ); } // preOrder( Traverser ) @Test public void preOrderEmpty() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( empty ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" } } ); } @Test public void preOrderSingleEdge() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( singleEdge ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" } } ); } @Test public void preOrderLoop() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( loop ) ); assertTraversalBegins( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->A", "A" }, { "A", "A->A", "A", "A->A", "A" }, { "A", "A->A", "A", "A->A", "A", "A->A", "A" } } ); } @Test public void preOrderCycle() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( cycle ) ); assertTraversalBegins( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->B", "B", "B->C", "C" }, { "A", "A->B", "B", "B->C", "C", "C->A", "A" }, { "A", "A->B", "B", "B->C", "C", "C->A", "A", "A->B", "B" } } ); } @Test public void preOrderTree() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( tree ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C" }, { "A", "A->C", "C", "C->F", "F" }, { "A", "A->C", "C", "C->G", "G" } } ); } @Test public void preOrderDag() { final Traverser<String, String> traverser = Traversers.preOrder( adjacencyFor( dag ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->D", "D", "D->G", "G" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C" }, { "A", "A->C", "C", "C->D", "D" }, { "A", "A->C", "C", "C->D", "D", "D->G", "G" } } ); } // FIXME: Test pre-order prune() // postOrder( Traverser ) @Test public void postOrderEmpty() { final Traverser<String, String> traverser = Traversers.postOrder( adjacencyFor( empty ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" } } ); } @Test public void postOrderSingleEdge() { final Traverser<String, String> traverser = Traversers.postOrder( adjacencyFor( singleEdge ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B" }, { "A" } } ); } @Test public void postOrderTree() { final Traverser<String, String> traverser = Traversers.postOrder( adjacencyFor( tree ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->B", "B" }, { "A", "A->C", "C", "C->F", "F" }, { "A", "A->C", "C", "C->G", "G" }, { "A", "A->C", "C" }, { "A" } } ); } @Test public void postOrderDag() { final Traverser<String, String> traverser = Traversers.postOrder( adjacencyFor( dag ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B", "B->D", "D", "D->G", "G" }, { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->B", "B" }, { "A", "A->C", "C", "C->D", "D", "D->G", "G" }, { "A", "A->C", "C", "C->D", "D" }, { "A", "A->C", "C" }, { "A" } } ); } // breadthFirst( Traverser ) @Test public void breadthFirstEmpty() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( empty ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" } } ); } @Test public void breadthFirstSingleEdge() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( singleEdge ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" } } ); } @Test public void breadthFirstLoop() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( loop ) ); assertTraversalBegins( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->A", "A" }, { "A", "A->A", "A", "A->A", "A" }, { "A", "A->A", "A", "A->A", "A", "A->A", "A" } } ); } @Test public void breadthFirstCycle() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( cycle ) ); assertTraversalBegins( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->B", "B", "B->C", "C" }, { "A", "A->B", "B", "B->C", "C", "C->A", "A" }, { "A", "A->B", "B", "B->C", "C", "C->A", "A", "A->B", "B" } } ); } @Test public void breadthFirstTree() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( tree ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->C", "C" }, { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C", "C->F", "F" }, { "A", "A->C", "C", "C->G", "G" } } ); } @Test public void breadthFirstDag() { final Traverser<String, String> traverser = Traversers.breadthFirst( adjacencyFor( dag ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" }, { "A", "A->B", "B" }, { "A", "A->C", "C" }, { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C", "C->D", "D" }, { "A", "A->B", "B", "B->D", "D", "D->G", "G" }, { "A", "A->C", "C", "C->D", "D", "D->G", "G" } } ); } // FIXME: Test breadth-first prune() // leaves( Traverser ) @Test public void leavesEmpty() { final Traverser<String, String> traverser = Traversers.leaves( adjacencyFor( empty ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A" } } ); } @Test public void leavesSingleEdge() { final Traverser<String, String> traverser = Traversers.leaves( adjacencyFor( singleEdge ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B" } } ); } @Test public void leavesTree() { final Traverser<String, String> traverser = Traversers.leaves( adjacencyFor( tree ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B", "B->D", "D" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C", "C->F", "F" }, { "A", "A->C", "C", "C->G", "G" } } ); } @Test public void leavesDag() { final Traverser<String, String> traverser = Traversers.leaves( adjacencyFor( dag ) ); assertTraversalContains( traverser.apply( "A" ), new Object[][] { { "A", "A->B", "B", "B->D", "D", "D->G", "G" }, { "A", "A->B", "B", "B->E", "E" }, { "A", "A->C", "C", "C->D", "D", "D->G", "G" } } ); } // These all return something precisely because an empty map/iterable/array *is* a leaf. // TODO // elements() // leafElements() // elementPath() @Test public void elementsEmptyMap() { Object root = Collections.emptyMap(); Iterator<Walk<Object, String>> iterator = Traversers.leafElements().apply( root ).iterator(); Walk<Object, String> walk = iterator.next(); assertThat( walk.getTo(), is( ( Object ) root ) ); assertThat( Traversers.elementPath( walk ), is( "" ) ); assertThat( iterator.hasNext(), is( false ) ); } @Test public void elementsEmptyList() { Object root = Collections.emptyList(); Iterator<Walk<Object, String>> iterator = Traversers.leafElements().apply( root ).iterator(); Walk<Object, String> walk = iterator.next(); assertThat( walk.getTo(), is( ( Object ) root ) ); assertThat( Traversers.elementPath( walk ), is( "" ) ); assertThat( iterator.hasNext(), is( false ) ); } @Test public void elementsEmptyArray() { Object root = new int[ 0 ]; Iterator<Walk<Object, String>> iterator = Traversers.leafElements().apply( root ).iterator(); Walk<Object, String> walk = iterator.next(); assertThat( walk.getTo(), is( root ) ); assertThat( Traversers.elementPath( walk ), is( "" ) ); assertThat( iterator.hasNext(), is( false ) ); } static void assertElementsContains( final Iterable<Walk<Object, String>> traversal, final Object[][] actualElements ) { Iterator<Walk<Object, String>> iterator = traversal.iterator(); for( Object[] element : actualElements ) { assertThat( iterator.hasNext(), is( true ) ); final Walk<Object, String> walk = iterator.next(); assertThat( Traversers.elementPath( walk ), is( element[ 0 ] ) ); assertThat( walk.getTo(), is( element[ 1 ] ) ); } assertThat( iterator.hasNext(), is( false ) ); try { iterator.next(); fail( "Should have thrown a NoSuchElementException." ); } catch( NoSuchElementException ignored ) { // success } } @SuppressWarnings( "unchecked" ) @Test public void nestedElements() { final Map<?, ?> map = ImmutableMap.builder() .put( "string", "A String" ) .put( "integer", 42 ) .put( "list", Arrays.asList( "zero", "one", "two", "three" ) ) .put( "array", new Object[] { "four", "five", "six" } ) .put( "boolean.array", new boolean[] { false, true, true, false, true } ) .put( "map", ImmutableMap.builder() .put( "foo[abc]bar", "Another String" ) .put( "people", Arrays.asList( ImmutableMap.of( "name", "Alice", "age", 37 ), ImmutableMap.of( "name", "Bob", "age", 55 ), ImmutableMap.of( "name", "Carol", "age", 23 ), ImmutableMap.of( "name", "Dave", "age", 27 ) ) ) .put( "owner", ImmutableMap.of( "name", "Elise", "age", 43 ) ) .build() ) .build(); assertElementsContains( Traversers.leafElements().apply( map ), new Object[][] { { "string", "A String" }, { "integer", 42 }, { "list[0]", "zero" }, { "list[1]", "one" }, { "list[2]", "two" }, { "list[3]", "three" }, { "array[0]", "four" }, { "array[1]", "five" }, { "array[2]", "six" }, { "boolean\\.array[0]", false }, { "boolean\\.array[1]", true }, { "boolean\\.array[2]", true }, { "boolean\\.array[3]", false }, { "boolean\\.array[4]", true }, { "map.foo\\[abc\\]bar", "Another String" }, { "map.people[0].name", "Alice" }, { "map.people[0].age", 37 }, { "map.people[1].name", "Bob" }, { "map.people[1].age", 55 }, { "map.people[2].name", "Carol" }, { "map.people[2].age", 23 }, { "map.people[3].name", "Dave" }, { "map.people[3].age", 27 }, { "map.owner.name", "Elise" }, { "map.owner.age", 43 } } ); } }
package org.neo4j.com; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.helpers.Exceptions; import org.neo4j.helpers.Pair; import org.neo4j.helpers.Predicate; import org.neo4j.helpers.Triplet; import org.neo4j.helpers.collection.ClosableIterable; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.kernel.AbstractGraphDatabase; import org.neo4j.kernel.Config; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource; import org.neo4j.kernel.impl.transaction.XaDataSourceManager; import org.neo4j.kernel.impl.transaction.xaframework.InMemoryLogBuffer; import org.neo4j.kernel.impl.transaction.xaframework.LogBuffer; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.LogExtractor; public class MasterUtil { private static File getBaseDir( GraphDatabaseService graphDb ) { File file = new File( ((AbstractGraphDatabase) graphDb).getStoreDir() ); try { return file.getCanonicalFile().getAbsoluteFile(); } catch ( IOException e ) { return file.getAbsoluteFile(); } } private static String relativePath( File baseDir, File storeFile ) throws IOException { String prefix = baseDir.getCanonicalPath(); String path = storeFile.getCanonicalPath(); if ( !path.startsWith( prefix ) ) throw new FileNotFoundException(); path = path.substring( prefix.length() ); if ( path.startsWith( File.separator ) ) return path.substring( 1 ); return path; } public static SlaveContext rotateLogsAndStreamStoreFiles( GraphDatabaseService graphDb, StoreWriter writer ) { File baseDir = getBaseDir( graphDb ); XaDataSourceManager dsManager = ((AbstractGraphDatabase) graphDb).getConfig().getTxModule().getXaDataSourceManager(); Collection<XaDataSource> sources = dsManager.getAllRegisteredDataSources(); @SuppressWarnings( "unchecked" ) Pair<String, Long>[] appliedTransactions = new Pair[sources.size()]; int i = 0; for ( XaDataSource ds : sources ) { appliedTransactions[i++] = Pair.of( ds.getName(), ds.getLastCommittedTxId() ); try { ds.getXaContainer().getResourceManager().rotateLogicalLog(); } catch ( IOException e ) { // TODO: what about error message? throw new MasterFailureException( e ); } } SlaveContext context = SlaveContext.anonymous( appliedTransactions ); ByteBuffer temporaryBuffer = ByteBuffer.allocateDirect( 1024*1024 ); for ( XaDataSource ds : sources ) { try { ClosableIterable<File> files = ds.listStoreFiles(); try { for ( File storefile : files ) { FileInputStream stream = new FileInputStream( storefile ); try { writer.write( relativePath( baseDir, storefile ), stream.getChannel(), temporaryBuffer, storefile.length() > 0 ); } finally { stream.close(); } } } finally { files.close(); } } catch ( IOException e ) { // TODO: what about error message? throw new MasterFailureException( e ); } } return context; } public static <T> Response<T> packResponse( GraphDatabaseService graphDb, SlaveContext context, T response, Predicate<Long> filter ) { List<Triplet<String, Long, TxExtractor>> stream = new ArrayList<Triplet<String, Long, TxExtractor>>(); Set<String> resourceNames = new HashSet<String>(); XaDataSourceManager dsManager = ((AbstractGraphDatabase) graphDb).getConfig().getTxModule().getXaDataSourceManager(); final List<LogExtractor> logExtractors = new ArrayList<LogExtractor>(); try { for ( Pair<String, Long> txEntry : context.lastAppliedTransactions() ) { String resourceName = txEntry.first(); final XaDataSource dataSource = dsManager.getXaDataSource( resourceName ); if ( dataSource == null ) { throw new RuntimeException( "No data source '" + resourceName + "' found" ); } resourceNames.add( resourceName ); long masterLastTx = dataSource.getLastCommittedTxId(); LogExtractor logExtractor; try { logExtractor = dataSource.getLogExtractor( txEntry.other()+1, masterLastTx ); } catch ( IOException ioe ) { throw new RuntimeException( ioe ); } final LogExtractor finalLogExtractor = logExtractor; logExtractors.add( finalLogExtractor ); for ( long txId = txEntry.other() + 1; txId <= masterLastTx; txId++ ) { if ( filter.accept( txId ) ) { final long tx = txId; TxExtractor extractor = new TxExtractor() { @Override public ReadableByteChannel extract() { InMemoryLogBuffer buffer = new InMemoryLogBuffer(); extract( buffer ); return buffer; } @Override public void extract( LogBuffer buffer ) { try { long extractedTxId = finalLogExtractor.extractNext( buffer ); if ( extractedTxId == -1 ) throw new RuntimeException( "Txs not found" ); if ( extractedTxId != tx ) throw new RuntimeException( "Expected txId " + tx + ", but was " + extractedTxId ); } catch ( IOException e ) { throw new RuntimeException( e ); } } }; stream.add( Triplet.of( resourceName, txId, extractor ) ); } } } StoreId storeId = ((NeoStoreXaDataSource) dsManager.getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME )).getStoreId(); return new Response<T>( response, storeId, createTransactionStream( resourceNames, stream, logExtractors ) ); } catch ( Throwable t ) { // If there's an error in here then close the log extractors, otherwise if we're // successful the TransactionStream will close it. for ( LogExtractor extractor : logExtractors ) extractor.close(); throw Exceptions.launderedException( t ); } } private static TransactionStream createTransactionStream( Collection<String> resourceNames, final List<Triplet<String, Long, TxExtractor>> stream, final List<LogExtractor> logExtractors ) { return new TransactionStream( resourceNames.toArray( new String[resourceNames.size()] ) ) { private final Iterator<Triplet<String, Long, TxExtractor>> iterator = stream.iterator(); @Override protected Triplet<String, Long, TxExtractor> fetchNextOrNull() { return iterator.hasNext() ? iterator.next() : null; } @Override public void close() { for ( LogExtractor extractor : logExtractors ) extractor.close(); } }; } public static <T> Response<T> packResponseWithoutTransactionStream( GraphDatabaseService graphDb, SlaveContext context, T response ) { XaDataSource ds = ((AbstractGraphDatabase) graphDb).getConfig().getTxModule() .getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); StoreId storeId = ((NeoStoreXaDataSource) ds).getStoreId(); return new Response<T>( response, storeId, TransactionStream.EMPTY ); } public static final Predicate<Long> ALL = new Predicate<Long>() { @Override public boolean accept( Long item ) { return true; } }; public static <T> void applyReceivedTransactions( Response<T> response, GraphDatabaseService graphDb, TxHandler txHandler ) throws IOException { XaDataSourceManager dataSourceManager = ((AbstractGraphDatabase) graphDb).getConfig().getTxModule().getXaDataSourceManager(); for ( Triplet<String, Long, TxExtractor> tx : IteratorUtil.asIterable( response.transactions() ) ) { String resourceName = tx.first(); XaDataSource dataSource = dataSourceManager.getXaDataSource( resourceName ); txHandler.accept( tx, dataSource ); ReadableByteChannel txStream = tx.third().extract(); try { dataSource.applyCommittedTransaction( tx.second(), txStream ); } finally { txStream.close(); } } } public interface TxHandler { void accept( Triplet<String, Long, TxExtractor> tx, XaDataSource dataSource ); } public static final TxHandler NO_ACTION = new TxHandler() { @Override public void accept( Triplet<String, Long, TxExtractor> tx, XaDataSource dataSource ) { // Do nothing } }; public static TxHandler txHandlerForFullCopy() { return new TxHandler() { private final Set<String> visitedDataSources = new HashSet<String>(); @Override public void accept( Triplet<String, Long, TxExtractor> tx, XaDataSource dataSource ) { if ( visitedDataSources.add( tx.first() ) ) { dataSource.setLastCommittedTxId( tx.second()-1 ); } } }; } }
package org.muckebox.android.ui.fragment; import org.muckebox.android.R; import org.muckebox.android.db.MuckeboxContract.CacheEntry; import org.muckebox.android.db.MuckeboxContract.DownloadEntry; import org.muckebox.android.db.MuckeboxContract.TrackDownloadCacheAlbumPlaylistJoin; import org.muckebox.android.db.MuckeboxContract.TrackEntry; import org.muckebox.android.db.MuckeboxProvider; import org.muckebox.android.db.PlaylistHelper; import org.muckebox.android.net.RefreshTracksTask; import org.muckebox.android.services.DownloadService; import org.muckebox.android.services.PlayerService; import org.muckebox.android.ui.utils.ExpandableCursorAdapter; import org.muckebox.android.ui.utils.TimeFormatter; import org.muckebox.android.ui.widgets.RefreshableListFragment; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.annotation.SuppressLint; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SearchView.OnCloseListener; import android.widget.SimpleCursorAdapter.ViewBinder; import android.widget.TextView; public class TrackListFragment extends RefreshableListFragment implements OnCloseListener, LoaderManager.LoaderCallbacks<Cursor> { private static final String ALBUM_ID_ARG = "album_id"; private static final String ALBUM_TITLE_ARG = "album_title"; private TrackListCursorAdapter mAdapter; private boolean mListLoaded = false; private HandlerThread mHelperThread; private Handler mHelperHandler; private Handler mMainHandler; MenuItem mPinAllItem; MenuItem mRemoveAllItem; private class TrackListCursorAdapter extends ExpandableCursorAdapter { private OnClickListener mPlayListener; private OnClickListener mDownloadListener; private OnClickListener mPinListener; private OnClickListener mDiscardListener; public TrackListCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); mPlayListener = new OnClickListener() { public void onClick(View v) { final int index = getItemIndex(v); mHelperHandler.post(new Runnable() { public void run() { final Uri playlistUri = PlaylistHelper.rebuildFromTrackList( getActivity(), getCursorUri(), index); mMainHandler.post(new Runnable() { public void run() { PlayerService.playPlaylistItem(getActivity(), Integer.parseInt(playlistUri.getLastPathSegment())); } }); } }); toggleExpanded(v); } }; mDownloadListener = new OnClickListener() { public void onClick(View v) { DownloadService.downloadTrack(getActivity(), getTrackId(getItemIndex(v))); toggleExpanded(v); } }; mPinListener = new OnClickListener() { public void onClick(View v) { DownloadService.pinTrack(getActivity(), getTrackId(getItemIndex(v))); toggleExpanded(v); } }; mDiscardListener = new OnClickListener() { public void onClick(View v) { DownloadService.discardTrack(getActivity(), getTrackId(getItemIndex(v))); toggleExpanded(v); } }; } public int getTrackId(int position) { Cursor c = getCursor(); c.moveToPosition(position); return c.getInt(c.getColumnIndex(TrackEntry.SHORT_ID)); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View ret = super.getView(position, convertView, parent); if (ret.getTag() == null) { ret.findViewById(R.id.track_list_play).setOnClickListener(mPlayListener); ret.findViewById(R.id.track_list_download).setOnClickListener(mDownloadListener); ret.findViewById(R.id.track_list_pin).setOnClickListener(mPinListener); ret.findViewById(R.id.track_list_discard).setOnClickListener(mDiscardListener); ret.setTag(true); } return ret; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelperThread = new HandlerThread("TrackListHelper"); mHelperThread.start(); mHelperHandler = new Handler(mHelperThread.getLooper()); mMainHandler = new Handler(); } @Override public void onDestroy() { super.onDestroy(); mHelperThread.quit(); } private class TracklistViewBinder implements ViewBinder { @SuppressLint("DefaultLocale") public boolean setViewValue(View view, Cursor cursor, int columnIndex) { ImageView icon; TextView textView; switch (view.getId()) { case R.id.track_list_duration: textView = (TextView) view; String text = TimeFormatter.formatDuration( cursor.getInt(columnIndex)); textView.setText(text); return true; case R.id.track_list_download_status: icon = (ImageView) view; if (cursor.isNull(columnIndex)) { icon.setVisibility(View.GONE); } else { icon.setVisibility(View.VISIBLE); switch (cursor.getInt(columnIndex)) { case DownloadEntry.STATUS_VALUE_QUEUED: icon.setImageResource(R.drawable.device_access_time); break; case DownloadEntry.STATUS_VALUE_DOWNLOADING: icon.setImageResource(R.drawable.av_download); break; } } return true; case R.id.track_list_cache_status: icon = (ImageView) view; if (cursor.isNull(columnIndex)) { icon.setVisibility(View.GONE); } else { icon.setVisibility(View.VISIBLE); switch (cursor.getInt(columnIndex)) { case 0: icon.setImageResource(R.drawable.navigation_accept); break; case 1: icon.setImageResource(R.drawable.av_make_available_offline); break; } } return true; case R.id.track_list_buttons: boolean downloading; int pinStatus; int downloadStatusIndex = cursor.getColumnIndex(DownloadEntry.ALIAS_STATUS); int pinStatusIndex = cursor.getColumnIndex(CacheEntry.ALIAS_PINNED); downloading = ! cursor.isNull(downloadStatusIndex); pinStatus = cursor.isNull(pinStatusIndex) ? -1 : cursor.getInt(pinStatusIndex); ImageButton downloadButton = (ImageButton) view.findViewById(R.id.track_list_download); ImageButton pinButton = (ImageButton) view.findViewById(R.id.track_list_pin); ImageButton discardButton = (ImageButton) view.findViewById(R.id.track_list_discard); if (! downloading && pinStatus == -1) { downloadButton.setVisibility(View.VISIBLE); pinButton.setVisibility(View.VISIBLE); discardButton.setVisibility(View.GONE); } else if (downloading) { downloadButton.setVisibility(View.GONE); pinButton.setVisibility(View.GONE); discardButton.setVisibility(View.VISIBLE); discardButton.setImageResource(R.drawable.navigation_cancel); } else { downloadButton.setVisibility(View.GONE); pinButton.setVisibility(pinStatus == 0 ? View.VISIBLE : View.GONE); discardButton.setVisibility(View.VISIBLE); discardButton.setImageResource(R.drawable.content_discard); } return true; case R.id.track_list_play_status: int playing = cursor.getInt(columnIndex); view.setVisibility(playing > 0 ? View.VISIBLE : View.GONE); return true; } return false; } } public static TrackListFragment newInstanceFromAlbum(long album_id, String title) { TrackListFragment f = new TrackListFragment(); Bundle args = new Bundle(); args.putLong(ALBUM_ID_ARG, album_id); args.putString(ALBUM_TITLE_ARG, title); f.setArguments(args); return f; } public long getAlbumId() { Bundle args = getArguments(); if (args == null) return -1; return args.getLong(ALBUM_ID_ARG, -1); } public boolean hasAlbumId() { return getAlbumId() != -1; } public String getAlbumTitle() { Bundle args = getArguments(); return args.getString(ALBUM_TITLE_ARG, ""); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_track_browse, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); mAdapter = new TrackListCursorAdapter(getActivity(), R.layout.list_row_track, null, new String[] { TrackEntry.ALIAS_TITLE, TrackEntry.ALIAS_DISPLAY_ARTIST, TrackEntry.ALIAS_LENGTH, DownloadEntry.ALIAS_STATUS, CacheEntry.ALIAS_PINNED, TrackDownloadCacheAlbumPlaylistJoin.ALIAS_CANCELABLE, TrackDownloadCacheAlbumPlaylistJoin.ALIAS_PLAYING }, new int[] { R.id.track_list_title, R.id.track_list_artist, R.id.track_list_duration, R.id.track_list_download_status, R.id.track_list_cache_status, R.id.track_list_buttons, R.id.track_list_play_status }, 0); mAdapter.setViewBinder(new TracklistViewBinder()); TextView header = (TextView) getActivity().findViewById(R.id.track_list_title_strip); header.setText(getAlbumTitle()); setListAdapter(mAdapter); getLoaderManager().initLoader(0, null, this); if (! mListLoaded) onRefreshRequested(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.track_list, menu); mPinAllItem = menu.findItem(R.id.track_list_action_pin); mRemoveAllItem = menu.findItem(R.id.track_list_action_remove); mRemoveAllItem.setVisible(false); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (super.onOptionsItemSelected(item)) return true; if (item == mPinAllItem) { Cursor c = mAdapter.getCursor(); int trackIdIndex = c.getColumnIndex(TrackEntry.SHORT_ID); c.moveToPosition(-1); while (c.moveToNext()) DownloadService.pinTrack(getActivity(), c.getInt(trackIdIndex)); return true; } else if (item == mRemoveAllItem) { Cursor c = mAdapter.getCursor(); int trackIdIndex = c.getColumnIndex(TrackEntry.SHORT_ID); c.moveToPosition(-1); while (c.moveToNext()) DownloadService.discardTrack(getActivity(), c.getInt(trackIdIndex)); return true; } return false; } protected void onRefreshRequested() { new RefreshTracksTask().setCallbacks(this).execute(getAlbumId()); mListLoaded = true; } @Override public boolean onClose() { return true; } public Uri getCursorUri() { Uri ret; if (hasAlbumId()) { ret = MuckeboxProvider.URI_TRACKS_WITH_DETAILS_ALBUM.buildUpon().appendPath( Long.toString(getAlbumId())).build(); } else { ret = MuckeboxProvider.URI_TRACKS_WITH_DETAILS; } return ret; } public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), getCursorUri(), null, null, null, null); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.swapCursor(data); data.moveToPosition(-1); boolean oneCached = false; boolean oneNotPinned = false; int cachedIndex = data.getColumnIndex(CacheEntry.ALIAS_PINNED); int downloadingIndex = data.getColumnIndex(DownloadEntry.ALIAS_STATUS); while (data.moveToNext()) { if (data.isNull(cachedIndex) && data.isNull(downloadingIndex)) oneNotPinned = true; else oneCached = true; if (oneNotPinned && oneCached) break; } if (mPinAllItem != null) mPinAllItem.setVisible(oneNotPinned); if (mRemoveAllItem != null) mRemoveAllItem.setVisible(oneCached); } public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } }
package com.oljalatinovic.oljaee.service; import com.oljalatinovic.oljaee.entity.Address; import com.oljalatinovic.oljaee.entity.Country; import com.oljalatinovic.oljaee.entity.MainMenu; import com.oljalatinovic.oljaee.entity.Users; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.sql.DataSourceDefinition; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; @DataSourceDefinition( name = "java:global/jdbc/oljaDS", className = "org.apache.derby.jdbc.ClientDataSource", portNumber = 1527, serverName = "localhost", databaseName = "oljaDB", user = "olja88", password = "password1" ) @Singleton @Startup public class DBPopulator { private Country serbia; private Users admin; private Users user; private Users olja; private MainMenu administracija; @Inject private MainMenuService mainMenuService; @Inject private UsersService userService; @Inject private CountryService countryService; @PostConstruct private void populateDB() { try { serbia = countryService.findCountry("SERBIA"); } catch (Exception e) { serbia = new Country("SR", "SERBIA", "Serbia", "SER", "111"); countryService.createCountry(serbia); } if (serbia == null) { serbia = new Country("SR", "SERBIA", "Serbia", "SER", "111"); countryService.createCountry(serbia); } try { user = userService.findUser("user"); } catch (Exception e) { user = new Users("User", "User", "user", "user", "user@oljaee.com", new Address("Moja ulica i broj", "A i grad", "44", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(user); } if (user == null) { user = new Users("User", "User", "user", "user", "user@oljaee.com", new Address("Moja ulica i broj", "A i grad", "44", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(user); } try { admin = userService.findUser("admin"); } catch (Exception e) { admin = new Users("Admin", "Admin", "admin", "admin", "admin@oljaee.com", new Address("Takodje samo 44", "Grad do", "32", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(admin); } if (admin == null) { admin = new Users("Admin", "Admin", "admin", "admin", "admin@oljaee.com", new Address("Takodje samo 44", "Grad do", "32", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(admin); } try { olja = userService.findUser("olja88"); } catch (Exception e) { olja = new Users("Olja", "Latinović", "olja88", "password1", "olja@oljaee.com", new Address("Licau jbro55", "Dgra", "12", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(olja); } if (olja == null) { olja = new Users("Olja", "Latinović", "olja88", "password1", "olja@oljaee.com", new Address("Licau jbro55", "Dgra", "12", new Country("SR", "SERBIA", "Serbia", "SER", "1"))); userService.createUser(olja); } try { administracija = mainMenuService.findMainMenu("Administracija"); } catch (Exception e) { administracija = new MainMenu("Administracija", "Administracija", "Administracija", olja, olja, new Date(), new Date(), null /*Boolean.TRUE*/ , null, "imgAdmin"); mainMenuService.createMainMenu(administracija); } if (administracija == null) { administracija = new MainMenu("Administracija", "Administracija", "Administracija", olja, olja, new Date(), new Date(), null /*Boolean.TRUE*/ , null, "imgAdmin"); mainMenuService.createMainMenu(administracija); } } @PreDestroy private void clearDB() { olja = userService.findUser("Olja"); if (olja != null) { userService.removeUser(olja); } user = userService.findUser("User"); if (user != null) { userService.removeUser(user); } admin = userService.findUser("Admin"); if (admin != null) { userService.removeUser(admin); } serbia = countryService.findCountry("SERBIA"); if (serbia != null) { countryService.removeCountry(serbia); } } }
package com.squareup.protoparser; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.ANY; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.BYTES; import static com.squareup.protoparser.DataType.ScalarType.DOUBLE; import static com.squareup.protoparser.DataType.ScalarType.FIXED32; import static com.squareup.protoparser.DataType.ScalarType.FIXED64; import static com.squareup.protoparser.DataType.ScalarType.FLOAT; import static com.squareup.protoparser.DataType.ScalarType.INT32; import static com.squareup.protoparser.DataType.ScalarType.INT64; import static com.squareup.protoparser.DataType.ScalarType.SFIXED32; import static com.squareup.protoparser.DataType.ScalarType.SFIXED64; import static com.squareup.protoparser.DataType.ScalarType.SINT32; import static com.squareup.protoparser.DataType.ScalarType.SINT64; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.DataType.ScalarType.UINT32; import static com.squareup.protoparser.DataType.ScalarType.UINT64; import static com.squareup.protoparser.FieldElement.Label.ONE_OF; import static com.squareup.protoparser.FieldElement.Label.OPTIONAL; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static com.squareup.protoparser.TestUtils.list; import static com.squareup.protoparser.TestUtils.map; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public final class ProtoParserTest { @Test public void typeParsing() { String proto = "" + "message Types {\n" + " required any f1 = 1;\n" + " required bool f2 = 2;\n" + " required bytes f3 = 3;\n" + " required double f4 = 4;\n" + " required float f5 = 5;\n" + " required fixed32 f6 = 6;\n" + " required fixed64 f7 = 7;\n" + " required int32 f8 = 8;\n" + " required int64 f9 = 9;\n" + " required sfixed32 f10 = 10;\n" + " required sfixed64 f11 = 11;\n" + " required sint32 f12 = 12;\n" + " required sint64 f13 = 13;\n" + " required string f14 = 14;\n" + " required uint32 f15 = 15;\n" + " required uint64 f16 = 16;\n" + " required map<string, bool> f17 = 17;\n" + " required map<arbitrary, nested.nested> f18 = 18;\n" + " required arbitrary f19 = 19;\n" + " required nested.nested f20 = 20;\n" + "}\n"; ProtoFile expected = ProtoFile.builder("test.proto") .addType(MessageElement.builder() .name("Types") .addField(FieldElement.builder().label(REQUIRED).type(ANY).name("f1").tag(1).build()) .addField(FieldElement.builder().label(REQUIRED).type(BOOL).name("f2").tag(2).build()) .addField(FieldElement.builder().label(REQUIRED).type(BYTES).name("f3").tag(3).build()) .addField(FieldElement.builder().label(REQUIRED).type(DOUBLE).name("f4").tag(4).build()) .addField(FieldElement.builder().label(REQUIRED).type(FLOAT).name("f5").tag(5).build()) .addField( FieldElement.builder().label(REQUIRED).type(FIXED32).name("f6").tag(6).build()) .addField( FieldElement.builder().label(REQUIRED).type(FIXED64).name("f7").tag(7).build()) .addField(FieldElement.builder().label(REQUIRED).type(INT32).name("f8").tag(8).build()) .addField(FieldElement.builder().label(REQUIRED).type(INT64).name("f9").tag(9).build()) .addField( FieldElement.builder().label(REQUIRED).type(SFIXED32).name("f10").tag(10).build()) .addField( FieldElement.builder().label(REQUIRED).type(SFIXED64).name("f11").tag(11).build()) .addField( FieldElement.builder().label(REQUIRED).type(SINT32).name("f12").tag(12).build()) .addField( FieldElement.builder().label(REQUIRED).type(SINT64).name("f13").tag(13).build()) .addField( FieldElement.builder().label(REQUIRED).type(STRING).name("f14").tag(14).build()) .addField( FieldElement.builder().label(REQUIRED).type(UINT32).name("f15").tag(15).build()) .addField( FieldElement.builder().label(REQUIRED).type(UINT64).name("f16").tag(16).build()) .addField(FieldElement.builder() .label(REQUIRED) .type(MapType.create(STRING, BOOL)) .name("f17") .tag(17) .build()) .addField(FieldElement.builder() .label(REQUIRED) .type(MapType.create(NamedType.create("arbitrary"), NamedType.create("nested.nested"))) .name("f18") .tag(18) .build()) .addField(FieldElement.builder() .label(REQUIRED) .type(NamedType.create("arbitrary")) .name("f19") .tag(19) .build()) .addField(FieldElement.builder() .label(REQUIRED) .type(NamedType.create("nested.nested")) .name("f20") .tag(20) .build()) .build()) .build(); assertThat(ProtoParser.parse("test.proto", proto)).isEqualTo(expected); } @Test public void singleLineComment() { String proto = "" + "// Test all the things!\n" + "message Test {}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo("Test all the things!"); } @Test public void multipleSingleLineComments() { String proto = "" + "// Test all\n" + "// the things!\n" + "message Test {}"; String expected = "" + "Test all\n" + "the things!"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo(expected); } @Test public void singleLineJavadocComment() { String proto = "" + "/** Test */\n" + "message Test {}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo("Test"); } @Test public void multilineJavadocComment() { String proto = "" + "/**\n" + " * Test\n" + " *\n" + " * Foo\n" + " */\n" + "message Test {}"; String expected = "" + "Test\n" + "\n" + "Foo"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo(expected); } @Test public void multipleSingleLineCommentsWithLeadingWhitespace() { String proto = "" + "// Test\n" + "// All\n" + "// The\n" + "// Things!\n" + "message Test {}"; String expected = "" + "Test\n" + " All\n" + " The\n" + " Things!"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo(expected); } @Test public void multilineJavadocCommentWithLeadingWhitespace() { String proto = "" + "/**\n" + " * Test\n" + " * All\n" + " * The\n" + " * Things!\n" + " */\n" + "message Test {}"; String expected = "" + "Test\n" + " All\n" + " The\n" + " Things!"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo(expected); } @Test public void multilineJavadocCommentWithoutLeadingAsterisks() { // We do not honor leading whitespace when the comment lacks leading asterisks. String proto = "" + "/**\n" + " Test\n" + " All\n" + " The\n" + " Things!\n" + " */\n" + "message Test {}"; String expected = "" + "Test\n" + "All\n" + "The\n" + "Things!"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); TypeElement type = parsed.typeElements().get(0); assertThat(type.documentation()).isEqualTo(expected); } @Test public void messageFieldTrailingComment() { // Trailing message field comment. String proto = "" + "message Test {\n" + " optional string name = 1; // Test all the things!\n" + "}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); MessageElement message = (MessageElement) parsed.typeElements().get(0); FieldElement field = message.fields().get(0); assertThat(field.documentation()).isEqualTo("Test all the things!"); } @Test public void messageFieldLeadingAndTrailingCommentAreCombined() { String proto = "" + "message Test {\n" + " // Test all...\n" + " optional string name = 1; // ...the things!\n" + "}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); MessageElement message = (MessageElement) parsed.typeElements().get(0); FieldElement field = message.fields().get(0); assertThat(field.documentation()).isEqualTo("Test all...\n...the things!"); } @Test public void trailingCommentNotAssignedToFollowingField() { String proto = "" + "message Test {\n" + " optional string first_name = 1; // Testing!\n" + " optional string last_name = 2;\n" + "}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); MessageElement message = (MessageElement) parsed.typeElements().get(0); FieldElement field1 = message.fields().get(0); assertThat(field1.documentation()).isEqualTo("Testing!"); FieldElement field2 = message.fields().get(1); assertThat(field2.documentation()).isEqualTo(""); } @Test public void enumValueTrailingComment() { String proto = "" + "enum Test {\n" + " FOO = 1; // Test all the things!\n" + "}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); EnumElement enumElement = (EnumElement) parsed.typeElements().get(0); EnumConstantElement value = enumElement.constants().get(0); assertThat(value.documentation()).isEqualTo("Test all the things!"); } @Test public void enumValueLeadingAndTrailingCommentsAreCombined() { String proto = "" + "enum Test {\n" + " // Test all...\n" + " FOO = 1; // ...the things!\n" + "}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); EnumElement enumElement = (EnumElement) parsed.typeElements().get(0); EnumConstantElement value = enumElement.constants().get(0); assertThat(value.documentation()).isEqualTo("Test all...\n...the things!"); } @Test public void syntaxNotRequired() throws Exception { String proto = "message Foo {}"; ProtoFile parsed = ProtoParser.parse("test.proto", proto); assertThat(parsed.syntax()).isNull(); } @Test public void syntaxSpecified() throws Exception { String proto = "" + "syntax \"proto3\";\n" + "message Foo {}"; ProtoFile expected = ProtoFile.builder("test.proto") .syntax(ProtoFile.Syntax.PROTO_3) .addType(MessageElement.builder().name("Foo").build()) .build(); assertThat(ProtoParser.parse("test.proto", proto)).isEqualTo(expected); } @Test public void invalidSyntaxValueThrows() throws Exception { String proto = "" + "syntax \"proto4\";\n" + "message Foo {}"; try { ProtoParser.parse("test.proto", proto); } catch (IllegalStateException e) { assertThat(e).hasMessage( "Syntax error in test.proto at 1:16: 'syntax' must be 'proto2' or 'proto3'. Found: proto4"); } } @Test public void syntaxInWrongContextThrows() { String proto = "" + "message Foo {\n" + " syntax \"proto2\";\n" + "}"; try { ProtoParser.parse("test.proto", proto); } catch (IllegalStateException e) { assertThat(e).hasMessage("Syntax error in test.proto at 2:9: 'syntax' in MESSAGE"); } } @Test public void parseMessageAndFields() throws Exception { String proto = "" + "message SearchRequest {\n" + " required string query = 1;\n" + " optional int32 page_number = 2;\n" + " optional int32 result_per_page = 3;\n" + "}"; ProtoFile expected = ProtoFile.builder("search.proto") .addType(MessageElement.builder() .name("SearchRequest") .addField(FieldElement.builder() .label(REQUIRED) .type(STRING) .name("query") .tag(1) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(INT32) .name("page_number") .tag(2) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(INT32) .name("result_per_page") .tag(3) .build()) .build()) .build(); assertThat(ProtoParser.parse("search.proto", proto)).isEqualTo(expected); } @Test public void parseMessageAndOneOf() throws Exception { String proto = "" + "message SearchRequest {\n" + " required string query = 1;\n" + " oneof page_info {\n" + " int32 page_number = 2;\n" + " int32 result_per_page = 3;\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("search.proto") .addType(MessageElement.builder() .name("SearchRequest") .addField(FieldElement.builder() .label(REQUIRED) .type(STRING) .name("query") .tag(1) .build()) .addOneOf(OneOfElement.builder() .name("page_info") .addField(FieldElement.builder() .label(ONE_OF) .type(INT32) .name("page_number") .tag(2) .build()) .addField(FieldElement.builder() .label(ONE_OF) .type(INT32) .name("result_per_page") .tag(3) .build()) .build()) .build()) .build(); assertThat(ProtoParser.parse("search.proto", proto)).isEqualTo(expected); } @Test public void parseEnum() throws Exception { String proto = "" + "/**\n" + " * What's on my waffles.\n" + " * Also works on pancakes.\n" + " */\n" + "enum Topping {\n" + " FRUIT = 1;\n" + " /** Yummy, yummy cream. */\n" + " CREAM = 2;\n" + "\n" + " // Quebec Maple syrup\n" + " SYRUP = 3;\n" + "}\n"; ProtoFile expected = ProtoFile.builder("waffles.proto") .addType(EnumElement.builder() .name("Topping") .documentation("What's on my waffles.\nAlso works on pancakes.") .addConstant(EnumConstantElement.builder().name("FRUIT").tag(1).build()) .addConstant(EnumConstantElement.builder() .name("CREAM") .tag(2) .documentation("Yummy, yummy cream.") .build()) .addConstant(EnumConstantElement.builder() .name("SYRUP") .tag(3) .documentation("Quebec Maple syrup") .build()) .build()) .build(); assertThat(ProtoParser.parse("waffles.proto", proto)).isEqualTo(expected); } @Test public void parseEnumWithOptions() throws Exception { String proto = "" + "/**\n" + " * What's on my waffles.\n" + " * Also works on pancakes.\n" + " */\n" + "enum Topping {\n" + " option (max_choices) = 2;\n" + "\n" + " FRUIT = 1 [(healthy) = true];\n" + " /** Yummy, yummy cream. */\n" + " CREAM = 2;\n" + "\n" + " // Quebec Maple syrup\n" + " SYRUP = 3;\n" + "}\n"; ProtoFile expected = ProtoFile.builder("waffles.proto") .addType(EnumElement.builder() .name("Topping") .qualifiedName("Topping") .documentation("What's on my waffles.\nAlso works on pancakes.") .addOption(OptionElement.create("max_choices", Kind.NUMBER, "2", true)) .addConstant(EnumConstantElement.builder() .name("FRUIT") .tag(1) .addOption(OptionElement.create("healthy", Kind.BOOLEAN, "true", true)) .build()) .addConstant(EnumConstantElement.builder() .name("CREAM") .tag(2) .documentation("Yummy, yummy cream.") .build()) .addConstant(EnumConstantElement.builder() .name("SYRUP") .tag(3) .documentation("Quebec Maple syrup") .build()) .build()) .build(); assertThat(ProtoParser.parse("waffles.proto", proto)).isEqualTo(expected); } @Test public void packageDeclaration() throws Exception { String proto = "" + "package google.protobuf;\n" + "option java_package = \"com.google.protobuf\";\n" + "\n" + "// The protocol compiler can output a FileDescriptorSet containing the .proto\n" + "// files it parses.\n" + "message FileDescriptorSet {\n" + "}\n"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .packageName("google.protobuf") .addType(MessageElement.builder() .name("FileDescriptorSet") .qualifiedName("google.protobuf.FileDescriptorSet") .documentation( "The protocol compiler can output a FileDescriptorSet containing the .proto\nfiles it parses.") .build()) .addOption(OptionElement.create("java_package", Kind.STRING, "com.google.protobuf")) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void nestingInMessage() throws Exception { String proto = "" + "message FieldOptions {\n" + " optional CType ctype = 1 [default = STRING, deprecated=true];\n" + " enum CType {\n" + " STRING = 0[(opt_a) = 1, (opt_b) = 2];\n" + " };\n" + " // Clients can define custom options in extensions of this message. See above.\n" + " extensions 500;\n" + " extensions 1000 to max;\n" + "}\n"; TypeElement enumElement = EnumElement.builder() .name("CType") .qualifiedName("FieldOptions.CType") .addConstant(EnumConstantElement.builder() .name("STRING") .tag(0) .addOption(OptionElement.create("opt_a", Kind.NUMBER, "1", true)) .addOption(OptionElement.create("opt_b", Kind.NUMBER, "2", true)) .build()) .build(); FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("CType")) .name("ctype") .tag(1) .addOption(OptionElement.create("default", Kind.ENUM, "STRING")) .addOption(OptionElement.create("deprecated", Kind.BOOLEAN, "true")) .build(); assertThat(field.options()).containsOnly( OptionElement.create("default", Kind.ENUM, "STRING"), OptionElement.create("deprecated", Kind.BOOLEAN, "true")); TypeElement messageElement = MessageElement.builder() .name("FieldOptions") .addField(field) .addType(enumElement) .addExtensions(ExtensionsElement.create(500, 500, "Clients can define custom options in extensions of this message. See above.")) .addExtensions(ExtensionsElement.create(1000, ProtoFile.MAX_TAG_VALUE)) .build(); ProtoFile expected = ProtoFile.builder("descriptor.proto").addType(messageElement).build(); ProtoFile actual = ProtoParser.parse("descriptor.proto", proto); assertThat(actual).isEqualTo(expected); } @Test public void optionParentheses() throws Exception { String proto = "" + "message Chickens {\n" + " optional bool koka_ko_koka_ko = 1 [default = true];\n" + " optional bool coodle_doodle_do = 2 [(delay) = 100, default = false];\n" + " optional bool coo_coo_ca_cha = 3 [default = true, (delay) = 200];\n" + " optional bool cha_chee_cha = 4;\n" + "}\n"; ProtoFile expected = ProtoFile.builder("chickens.proto") .addType(MessageElement.builder() .name("Chickens") .addField(FieldElement.builder() .label(OPTIONAL) .type(BOOL) .name("koka_ko_koka_ko") .tag(1) .addOption(OptionElement.create("default", Kind.BOOLEAN, "true")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(BOOL) .name("coodle_doodle_do") .tag(2) .addOption(OptionElement.create("delay", Kind.NUMBER, "100", true)) .addOption(OptionElement.create("default", Kind.BOOLEAN, "false")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(BOOL) .name("coo_coo_ca_cha") .tag(3) .addOption(OptionElement.create("default", Kind.BOOLEAN, "true")) .addOption(OptionElement.create("delay", Kind.NUMBER, "200", true)) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(BOOL) .name("cha_chee_cha") .tag(4) .build()) .build()) .build(); assertThat(ProtoParser.parse("chickens.proto", proto)).isEqualTo(expected); } @Test public void imports() throws Exception { String proto = "import \"src/test/resources/unittest_import.proto\";\n"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addDependency("src/test/resources/unittest_import.proto") .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void publicImports() throws Exception { String proto = "import public \"src/test/resources/unittest_import.proto\";\n"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addPublicDependency("src/test/resources/unittest_import.proto") .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void extend() throws Exception { String proto = "" + "// Extends Foo\n" + "extend Foo {\n" + " optional int32 bar = 126;\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addExtendDeclaration(ExtendElement.builder() .name("Foo") .documentation("Extends Foo") .addField( FieldElement.builder().label(OPTIONAL).type(INT32).name("bar").tag(126).build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void extendInMessage() throws Exception { String proto = "" + "message Bar {\n" + " extend Foo {\n" + " optional Bar bar = 126;\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addType(MessageElement.builder().name("Bar").build()) .addExtendDeclaration(ExtendElement.builder() .name("Foo") .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("Bar")) .name("bar") .tag(126) .build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void extendInMessageWithPackage() throws Exception { String proto = "" + "package kit.kat;\n" + "" + "message Bar {\n" + " extend Foo {\n" + " optional Bar bar = 126;\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .packageName("kit.kat") .addType(MessageElement.builder().name("Bar").qualifiedName("kit.kat.Bar").build()) .addExtendDeclaration(ExtendElement.builder() .name("Foo") .qualifiedName("kit.kat.Foo") .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("Bar")) .name("bar") .tag(126) .build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void fqcnExtendInMessage() throws Exception { String proto = "" + "message Bar {\n" + " extend example.Foo {\n" + " optional Bar bar = 126;\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addType(MessageElement.builder().name("Bar").build()) .addExtendDeclaration(ExtendElement.builder() .name("example.Foo") .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("Bar")) .name("bar") .tag(126) .build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void fqcnExtendInMessageWithPackage() throws Exception { String proto = "" + "package kit.kat;\n" + "" + "message Bar {\n" + " extend example.Foo {\n" + " optional Bar bar = 126;\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .packageName("kit.kat") .addType(MessageElement.builder().name("Bar").qualifiedName("kit.kat.Bar").build()) .addExtendDeclaration(ExtendElement.builder() .name("example.Foo") .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("Bar")) .name("bar") .tag(126) .build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void defaultFieldWithParen() throws Exception { String proto = "" + "message Foo {\n" + " optional string claim_token = 2 [(squareup.redacted) = true];\n" + "}"; FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(STRING) .name("claim_token") .tag(2) .addOption(OptionElement.create("squareup.redacted", Kind.BOOLEAN, "true", true)) .build(); assertThat(field.options()).containsOnly( OptionElement.create("squareup.redacted", Kind.BOOLEAN, "true", true)); TypeElement messageElement = MessageElement.builder().name("Foo").addField(field).build(); ProtoFile expected = ProtoFile.builder("descriptor.proto").addType(messageElement).build(); assertThat(ProtoParser.parse("descriptor.proto", proto)) .isEqualTo(expected); } // Parse \a, \b, \f, \n, \r, \t, \v, \[0-7]{1-3}, and \[xX]{0-9a-fA-F]{1,2} @Test public void defaultFieldWithStringEscapes() throws Exception { String proto = "" + "message Foo {\n" + " optional string name = 1 " + "[default = \"\\a\\b\\f\\n\\r\\t\\v\1f\01\001\11\011\111\\xe\\Xe\\xE\\xE\\x41\\X41\"];\n" + "}"; FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(STRING) .name("name") .tag(1) .addOption(OptionElement.create("default", Kind.STRING, "\u0007\b\f\n\r\t\u000b\u0001f\u0001\u0001\u0009\u0009I\u000e\u000e\u000e\u000eAA")) .build(); assertThat(field.options()).containsOnly(OptionElement.create("default", Kind.STRING, "\u0007\b\f\n\r\t\u000b\u0001f\u0001\u0001\u0009\u0009I\u000e\u000e\u000e\u000eAA")); TypeElement messageElement = MessageElement.builder().name("Foo").addField(field).build(); ProtoFile expected = ProtoFile.builder("foo.proto").addType(messageElement).build(); assertThat(ProtoParser.parse("foo.proto", proto)) .isEqualTo(expected); } @Test public void invalidHexStringEscape() throws Exception { String proto = "" + "message Foo {\n" + " optional string name = 1 " + "[default = \"\\xW\"];\n" + "}"; try { ProtoParser.parse("foo.proto", proto); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage().contains("expected a digit after \\x or \\X")); } } @Test public void service() throws Exception { String proto = "" + "service SearchService {\n" + " option (default_timeout) = 30;\n" + "\n" + " rpc Search (SearchRequest) returns (SearchResponse);" + " rpc Purchase (PurchaseRequest) returns (PurchaseResponse) {\n" + " option (squareup.sake.timeout) = 15; \n" + " option (squareup.a.b) = {" + " value: [" + " FOO," + " BAR" + " ]" + " };\n" + " }\n" + "}"; ProtoFile expected = ProtoFile.builder("descriptor.proto") .addService(ServiceElement.builder() .name("SearchService") .addOption(OptionElement.create("default_timeout", Kind.NUMBER, "30", true)) .addRpc(RpcElement.builder() .name("Search") .requestType(NamedType.create("SearchRequest")) .responseType(NamedType.create("SearchResponse")) .build()) .addRpc(RpcElement.builder() .name("Purchase") .requestType(NamedType.create("PurchaseRequest")) .responseType(NamedType.create("PurchaseResponse")) .addOption(OptionElement.create("squareup.sake.timeout", Kind.NUMBER, "15", true)) .addOption(OptionElement.create("squareup.a.b", Kind.MAP, map("value", list("FOO", "BAR")), true)) .build()) .build()) .build(); assertThat(ProtoParser.parse("descriptor.proto", proto)).isEqualTo(expected); } @Test public void serviceTypesMustBeNamed() { try { String proto = "" + "service SearchService {\n" + " rpc Search (string) returns (SearchResponse);" + "}"; ProtoParser.parse("test.proto", proto); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Syntax error in test.proto at 2:21: expected message but was string"); } try { String proto = "" + "service SearchService {\n" + " rpc Search (SearchRequest) returns (string);" + "}"; ProtoParser.parse("test.proto", proto); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Syntax error in test.proto at 2:45: expected message but was string"); } } @Test public void hexTag() throws Exception { String proto = "" + "message HexTag {\n" + " required string hex = 0x10;\n" + "}"; ProtoFile expected = ProtoFile.builder("hex.proto") .addType(MessageElement.builder() .name("HexTag") .addField(FieldElement.builder() .label(REQUIRED) .type(STRING) .name("hex") .tag(16) .build()) .build()) .build(); assertThat(ProtoParser.parse("hex.proto", proto)).isEqualTo(expected); } @Test public void structuredOption() throws Exception { String proto = "" + "message ExoticOptions {\n" + " option (squareup.one) = {name: \"Name\", class_name:\"ClassName\"};\n" + " option (squareup.two.a) = {[squareup.options.type]: EXOTIC};\n" + " option (squareup.two.b) = {names: [\"Foo\", \"Bar\"]};\n" + " option (squareup.three) = {x: {y: 1 y: 2}};\n" // NOTE: Omitted optional comma + " option (squareup.four) = {x: {y: {z: 1}, y: {z: 2}}};\n" + "}"; MessageElement.Builder expectedBuilder = MessageElement.builder().name("ExoticOptions"); Map<String, String> option_one_map = new LinkedHashMap<>(); option_one_map.put("name", "Name"); option_one_map.put("class_name", "ClassName"); expectedBuilder.addOption(OptionElement.create("squareup.one", Kind.MAP, option_one_map, true)); Map<String, Object> option_two_a_map = new LinkedHashMap<>(); option_two_a_map.put("[squareup.options.type]", "EXOTIC"); expectedBuilder.addOption(OptionElement.create("squareup.two.a", Kind.MAP, option_two_a_map, true)); Map<String, List<String>> option_two_b_map = new LinkedHashMap<>(); option_two_b_map.put("names", Arrays.asList("Foo", "Bar")); expectedBuilder.addOption(OptionElement.create("squareup.two.b", Kind.MAP, option_two_b_map, true)); Map<String, Map<String, ?>> option_three_map = new LinkedHashMap<>(); Map<String, Object> option_three_nested_map = new LinkedHashMap<>(); option_three_nested_map.put("y", Arrays.asList("1", "2")); option_three_map.put("x", option_three_nested_map); expectedBuilder.addOption(OptionElement.create("squareup.three", Kind.MAP, option_three_map, true)); Map<String, Map<String, ?>> option_four_map = new LinkedHashMap<>(); Map<String, Object> option_four_map_1 = new LinkedHashMap<>(); Map<String, Object> option_four_map_2_a = new LinkedHashMap<>(); option_four_map_2_a.put("z", "1"); Map<String, Object> option_four_map_2_b = new LinkedHashMap<>(); option_four_map_2_b.put("z", "2"); option_four_map_1.put("y", Arrays.asList(option_four_map_2_a, option_four_map_2_b)); option_four_map.put("x", option_four_map_1); expectedBuilder.addOption(OptionElement.create("squareup.four", Kind.MAP, option_four_map, true)); ProtoFile expected = ProtoFile.builder("exotic.proto").addType(expectedBuilder.build()).build(); assertThat(ProtoParser.parse("exotic.proto", proto)).isEqualTo(expected); } @Test public void optionsWithNestedMapsAndTrailingCommas() throws Exception { String proto = "" + "message StructuredOption {\n" + " optional field.type has_options = 3 [\n" + " (option_map) = {\n" + " nested_map: {key:\"value\" key2:[\"value2a\",\"value2b\"]},\n" + " }\n" + " (option_string) = [\"string1\",\"string2\"]\n" + " ];\n" + "}"; FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("field.type")) .name("has_options") .tag(3) .addOption(OptionElement.create("option_map", Kind.MAP, map("nested_map", map("key", "value", "key2", list("value2a", "value2b"))), true)) .addOption(OptionElement.create("option_string", Kind.LIST, list("string1", "string2"), true)) .build(); assertThat(field.options()).containsOnly( OptionElement.create("option_map", Kind.MAP, map("nested_map", map("key", "value", "key2", list("value2a", "value2b"))), true), OptionElement.create("option_string", Kind.LIST, list("string1", "string2"), true)); TypeElement expected = MessageElement.builder().name("StructuredOption").addField(field).build(); ProtoFile protoFile = ProtoFile.builder("nestedmaps.proto").addType(expected).build(); assertThat(ProtoParser.parse("nestedmaps.proto", proto)) .isEqualTo(protoFile); } @Test public void optionNumericalBounds() { String proto = "" + "message Test {" + " optional int32 default_int32 = 401 [default = 2147483647 ];\n" + " optional uint32 default_uint32 = 402 [default = 4294967295 ];\n" + " optional sint32 default_sint32 = 403 [default = -2147483648 ];\n" + " optional fixed32 default_fixed32 = 404 [default = 4294967295 ];\n" + " optional sfixed32 default_sfixed32 = 405 [default = -2147483648 ];\n" + " optional int64 default_int64 = 406 [default = 9223372036854775807 ];\n" + " optional uint64 default_uint64 = 407 [default = 18446744073709551615 ];\n" + " optional sint64 default_sint64 = 408 [default = -9223372036854775808 ];\n" + " optional fixed64 default_fixed64 = 409 [default = 18446744073709551615 ];\n" + " optional sfixed64 default_sfixed64 = 410 [default = -9223372036854775808 ];\n" + " optional bool default_bool = 411 [default = true ];\n" + " optional float default_float = 412 [default = 123.456e7 ];\n" + " optional double default_double = 413 [default = 123.456e78 ];\n" + " optional string default_string = 414 [default = \"çok\\a\\b\\f\\n\\r\\t\\v\\1\\01\\001\\17\\017\\176\\x1\\x01\\x11\\X1\\X01\\X11güzel\" ];\n" + " optional bytes default_bytes = 415 [default = \"çok\\a\\b\\f\\n\\r\\t\\v\\1\\01\\001\\17\\017\\176\\x1\\x01\\x11\\X1\\X01\\X11güzel\" ];\n" + " optional NestedEnum default_nested_enum = 416 [default = A ];" + "}"; ProtoFile expected = ProtoFile.builder("test.proto") .addType(MessageElement.builder() .name("Test") .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.INT32) .name("default_int32") .tag(401) .addOption(OptionElement.create("default", Kind.NUMBER, "2147483647")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.UINT32) .name("default_uint32") .tag(402) .addOption(OptionElement.create("default", Kind.NUMBER, "4294967295")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.SINT32) .name("default_sint32") .tag(403) .addOption(OptionElement.create("default", Kind.NUMBER, "-2147483648")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.FIXED32) .name("default_fixed32") .tag(404) .addOption(OptionElement.create("default", Kind.NUMBER, "4294967295")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.SFIXED32) .name("default_sfixed32") .tag(405) .addOption(OptionElement.create("default", Kind.NUMBER, "-2147483648")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.INT64) .name("default_int64") .tag(406) .addOption(OptionElement.create("default", Kind.NUMBER, "9223372036854775807")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.UINT64) .name("default_uint64") .tag(407) .addOption(OptionElement.create("default", Kind.NUMBER, "18446744073709551615")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.SINT64) .name("default_sint64") .tag(408) .addOption(OptionElement.create("default", Kind.NUMBER, "-9223372036854775808")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.FIXED64) .name("default_fixed64") .tag(409) .addOption(OptionElement.create("default", Kind.NUMBER, "18446744073709551615")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.SFIXED64) .name("default_sfixed64") .tag(410) .addOption(OptionElement.create("default", Kind.NUMBER, "-9223372036854775808")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.BOOL) .name("default_bool") .tag(411) .addOption(OptionElement.create("default", Kind.BOOLEAN, "true")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.FLOAT) .name("default_float") .tag(412) .addOption(OptionElement.create("default", Kind.NUMBER, "123.456e7")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.DOUBLE) .name("default_double") .tag(413) .addOption(OptionElement.create("default", Kind.NUMBER, "123.456e78")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.STRING) .name("default_string") .tag(414) .addOption(OptionElement.create("default", Kind.STRING, "çok\u0007\b\f\n\r\t\u000b\u0001\u0001\u0001\u000f\u000f~\u0001\u0001\u0011\u0001\u0001\u0011güzel")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(ScalarType.BYTES) .name("default_bytes") .tag(415) .addOption(OptionElement.create("default", Kind.STRING, "çok\u0007\b\f\n\r\t\u000b\u0001\u0001\u0001\u000f\u000f~\u0001\u0001\u0011\u0001\u0001\u0011güzel")) .build()) .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("NestedEnum")) .name("default_nested_enum") .tag(416) .addOption(OptionElement.create("default", Kind.ENUM, "A")) .build()) .build()) .build(); assertThat(ProtoParser.parse("test.proto", proto)).isEqualTo(expected); } @Test public void extensionWithNestedMessage() throws Exception { String proto = "" + "message Foo {\n" + " optional int32 bar = 1 [\n" + " (validation.range).min = 1,\n" + " (validation.range).max = 100,\n" + " default = 20\n" + " ];\n" + "}"; FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(INT32) .name("bar") .tag(1) .addOption(OptionElement.create("validation.range", Kind.OPTION, OptionElement.create("min", Kind.NUMBER, "1"), true)) .addOption(OptionElement.create("validation.range", Kind.OPTION, OptionElement.create("max", Kind.NUMBER, "100"), true)) .addOption(OptionElement.create("default", Kind.NUMBER, "20")) .build(); assertThat(field.options()).containsOnly( OptionElement.create("validation.range", Kind.OPTION, OptionElement.create("min", Kind.NUMBER, "1"), true), OptionElement.create("validation.range", Kind.OPTION, OptionElement.create("max", Kind.NUMBER, "100"), true), OptionElement.create("default", Kind.NUMBER, "20")); TypeElement expected = MessageElement.builder().name("Foo").addField(field).build(); ProtoFile protoFile = ProtoFile.builder("foo.proto").addType(expected).build(); assertThat(ProtoParser.parse("foo.proto", proto)).isEqualTo(protoFile); } @Test public void noWhitespace() { String proto = "message C {optional A.B ab = 1;}"; ProtoFile expected = ProtoFile.builder("test.proto") .addType(MessageElement.builder() .name("C") .addField(FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("A.B")) .name("ab") .tag(1) .build()) .build()) .build(); assertThat(ProtoParser.parse("test.proto", proto)).isEqualTo(expected); } }
package com.safecharge.biz; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.safecharge.request.AddUPOAPMRequest; import com.safecharge.request.AddUPOCreditCardByTempTokenRequest; import com.safecharge.request.AddUPOCreditCardByTokenRequest; import com.safecharge.request.AddUPOCreditCardRequest; import com.safecharge.request.Authorization3DRequest; import com.safecharge.request.CancelSubscriptionRequest; import com.safecharge.request.CardTokenizationRequest; import com.safecharge.request.CreateUserRequest; import com.safecharge.request.CreateSubscriptionRequest; import com.safecharge.request.DeleteUPORequest; import com.safecharge.request.Dynamic3DRequest; import com.safecharge.request.EditUPOAPMRequest; import com.safecharge.request.EditUPOCreditCardRequest; import com.safecharge.request.EnableUPORequest; import com.safecharge.request.GetMerchantPaymentMethodsRequest; import com.safecharge.request.GetOrderDetailsRequest; import com.safecharge.request.GetSessionTokenRequest; import com.safecharge.request.GetSubscriptionPlansRequest; import com.safecharge.request.GetSubscriptionsListRequest; import com.safecharge.request.GetUserDetailsRequest; import com.safecharge.request.GetUserUPOsRequest; import com.safecharge.request.OpenOrderRequest; import com.safecharge.request.Payment3DRequest; import com.safecharge.request.PaymentAPMRequest; import com.safecharge.request.PaymentCCRequest; import com.safecharge.request.PayoutRequest; import com.safecharge.request.RefundTransactionRequest; import com.safecharge.request.SafechargeBaseRequest; import com.safecharge.request.SafechargeRequest; import com.safecharge.request.SettleTransactionRequest; import com.safecharge.request.SuspendUPORequest; import com.safecharge.request.UpdateOrderRequest; import com.safecharge.request.UpdateUserRequest; import com.safecharge.request.VoidTransactionRequest; import com.safecharge.response.AddUPOAPMResponse; import com.safecharge.response.AddUPOCreditCardByTempTokenResponse; import com.safecharge.response.AddUPOCreditCardByTokenResponse; import com.safecharge.response.AddUPOCreditCardResponse; import com.safecharge.response.Authorization3DResponse; import com.safecharge.response.CancelSubscriptionResponse; import com.safecharge.response.CardTokenizationResponse; import com.safecharge.response.DeleteUPOResponse; import com.safecharge.response.Dynamic3DResponse; import com.safecharge.response.EditUPOAPMResponse; import com.safecharge.response.EditUPOCreditCardResponse; import com.safecharge.response.EnableUPOResponse; import com.safecharge.response.GetUserDetailsResponse; import com.safecharge.response.GetUserUPOsResponse; import com.safecharge.response.SuspendUPOResponse; import com.safecharge.response.UserResponse; import com.safecharge.response.CreateSubscriptionResponse; import com.safecharge.response.GetMerchantPaymentMethodsResponse; import com.safecharge.response.GetOrderDetailsResponse; import com.safecharge.response.GetSessionTokenResponse; import com.safecharge.response.GetSubscriptionPlansResponse; import com.safecharge.response.GetSubscriptionsListResponse; import com.safecharge.response.OpenOrderResponse; import com.safecharge.response.Payment3DResponse; import com.safecharge.response.PaymentAPMResponse; import com.safecharge.response.PaymentCCResponse; import com.safecharge.response.PayoutResponse; import com.safecharge.response.RefundTransactionResponse; import com.safecharge.response.SafechargeResponse; import com.safecharge.response.SettleTransactionResponse; import com.safecharge.response.UpdateOrderResponse; import com.safecharge.response.VoidTransactionResponse; import com.safecharge.util.APIConstants; public class SafechargeRequestExecutor { private static final Log logger = LogFactory.getLog(SafechargeRequestExecutor.class); private static final Map<Class<? extends SafechargeBaseRequest>, Class<? extends SafechargeResponse>> RESPONSE_TYPE_BY_REQUEST_TYPE = new HashMap<Class<? extends SafechargeBaseRequest>, Class<? extends SafechargeResponse>>() { private static final long serialVersionUID = -5429154998138428048L; { put(GetSessionTokenRequest.class, GetSessionTokenResponse.class); put(OpenOrderRequest.class, OpenOrderResponse.class); put(UpdateOrderRequest.class, UpdateOrderResponse.class); put(GetOrderDetailsRequest.class, GetOrderDetailsResponse.class); put(PaymentCCRequest.class, PaymentCCResponse.class); put(PaymentAPMRequest.class, PaymentAPMResponse.class); put(Authorization3DRequest.class, Authorization3DResponse.class); put(Dynamic3DRequest.class, Dynamic3DResponse.class); put(CardTokenizationRequest.class, CardTokenizationResponse.class); put(Payment3DRequest.class, Payment3DResponse.class); put(AddUPOCreditCardByTempTokenRequest.class, AddUPOCreditCardByTempTokenResponse.class); put(SettleTransactionRequest.class, SettleTransactionResponse.class); put(VoidTransactionRequest.class, VoidTransactionResponse.class); put(RefundTransactionRequest.class, RefundTransactionResponse.class); put(AddUPOCreditCardRequest.class, AddUPOCreditCardResponse.class); put(AddUPOAPMRequest.class, AddUPOAPMResponse.class); put(GetMerchantPaymentMethodsRequest.class, GetMerchantPaymentMethodsResponse.class); put(CancelSubscriptionRequest.class, CancelSubscriptionResponse.class); put(CreateSubscriptionRequest.class, CreateSubscriptionResponse.class); put(GetSubscriptionsListRequest.class, GetSubscriptionsListResponse.class); put(GetSubscriptionPlansRequest.class, GetSubscriptionPlansResponse.class); put(PayoutRequest.class, PayoutResponse.class); put(CreateUserRequest.class, UserResponse.class); put(UpdateUserRequest.class, UserResponse.class); put(GetUserDetailsRequest.class, GetUserDetailsResponse.class); put(AddUPOCreditCardByTokenRequest.class, AddUPOCreditCardByTokenResponse.class); put(GetUserUPOsRequest.class, GetUserUPOsResponse.class); put(EditUPOCreditCardRequest.class, EditUPOCreditCardResponse.class); put(EditUPOAPMRequest.class, EditUPOAPMResponse.class); put(EnableUPORequest.class, EnableUPOResponse.class); put(DeleteUPORequest.class, DeleteUPOResponse.class); put(SuspendUPORequest.class, SuspendUPOResponse.class); } }; private static final Map<Class<? extends SafechargeBaseRequest>, String> REQUEST_URL_BY_REQUEST_TYPE = new HashMap<Class<? extends SafechargeBaseRequest>, String>() { private static final long serialVersionUID = -6533247180543051173L; { put(GetSessionTokenRequest.class, APIConstants.GET_SESSION_TOKEN_URL); put(OpenOrderRequest.class, APIConstants.OPEN_ORDER_URL); put(UpdateOrderRequest.class, APIConstants.UPDATE_ORDER_URL); put(GetOrderDetailsRequest.class, APIConstants.GET_ORDER_DETAILS_URL); put(PaymentCCRequest.class, APIConstants.PAYMENT_CC_URL); put(PaymentAPMRequest.class, APIConstants.PAYMENT_APM_URL); put(Authorization3DRequest.class, APIConstants.AUTHORIZATION_3D_URL); put(Dynamic3DRequest.class, APIConstants.DYNAMIC_3D_URL); put(CardTokenizationRequest.class, APIConstants.CARD_TOKENIZATION_URL); put(Payment3DRequest.class, APIConstants.PAYMENT_3D_URL); put(AddUPOCreditCardByTempTokenRequest.class, APIConstants.ADD_UPO_CREDIT_CARD_BY_TEMP_TOKEN_URL); put(SettleTransactionRequest.class, APIConstants.SETTLE_TRANSACTION_URL); put(VoidTransactionRequest.class, APIConstants.VOID_TRANSACTION_URL); put(RefundTransactionRequest.class, APIConstants.REFUND_TRANSACTION_URL); put(AddUPOCreditCardRequest.class, APIConstants.ADD_UPO_CREDIT_CARD_URL); put(AddUPOAPMRequest.class, APIConstants.ADD_UPO_APM_URL); put(GetMerchantPaymentMethodsRequest.class, APIConstants.GET_MERCHANT_PAYMENT_METHODS_REQUEST_URL); put(CancelSubscriptionRequest.class, APIConstants.CANCEL_SUBSCRIPTION_REQUEST_URL); put(CreateSubscriptionRequest.class, APIConstants.CREATE_SUBSCRIPTION_REQUEST_URL); put(GetSubscriptionsListRequest.class, APIConstants.GET_SUBSCRIPTION_LIST_REQUEST_URL); put(GetSubscriptionPlansRequest.class, APIConstants.GET_SUBSCRIPTION_PLANS_REQUEST_URL); put(PayoutRequest.class, APIConstants.PAYOUT_URL); put(CreateUserRequest.class, APIConstants.CREATE_USER_URL); put(UpdateUserRequest.class, APIConstants.UPDATE_USER_URL); put(GetUserDetailsRequest.class, APIConstants.GET_USER_DETAILS_URL); put(AddUPOCreditCardByTokenRequest.class, APIConstants.ADD_UPO_CREDIT_CARD_BY_TOKEN_URL); put(GetUserUPOsRequest.class, APIConstants.GET_USER_UPOS_REQUEST); put(EditUPOCreditCardRequest.class, APIConstants.EDIT_UPO_CREDIT_CARD_URL); put(EditUPOAPMRequest.class, APIConstants.EDIT_UPO_APM_URL); put(EnableUPORequest.class, APIConstants.ENABLE_UPO_URL); put(DeleteUPORequest.class, APIConstants.DELETE_UPO_APM_URL); put(SuspendUPORequest.class, APIConstants.SUSPEND_UPO_APM_URL); } }; private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); private static SafechargeRequestExecutor instance = null; private static HttpClient httpClient; private static boolean isInitialized = false; private SafechargeRequestExecutor() { } /** * Obtains the single instance of {@link SafechargeRequestExecutor} * * @return the single instance of {@link SafechargeRequestExecutor} */ public static SafechargeRequestExecutor getInstance() { if (instance == null) { instance = new SafechargeRequestExecutor(); } return instance; } /** * This method initiates the {@link SafechargeRequestExecutor} with a default Safecharge's {@link HttpClient} and server information. */ public void init() { init(SafechargeHttpClient.createDefault()); } /** * This method initiates the {@link SafechargeRequestExecutor} with a configured {@link HttpClient} and server information. * * @param httpClient to get the client's properties from */ public void init(HttpClient httpClient) { if (isInitialized) { // already initialized if (logger.isDebugEnabled()) { logger.debug(SafechargeRequestExecutor.class.getSimpleName() + " is already initialized!"); } return; } SafechargeRequestExecutor.httpClient = httpClient; isInitialized = true; } /** * Sends a {@link SafechargeRequest} to SafeCharge's API via HTTP POST method. * * @param request {@link SafechargeRequest} API request object * @return {@link SafechargeResponse} API response object or null if the response can't be parsed */ public SafechargeResponse executeRequest(SafechargeBaseRequest request) { if (!isInitialized) { init(); } GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); try { Class requestClass = request.getClass(); String serviceUrl = request.getServerHost() + REQUEST_URL_BY_REQUEST_TYPE.get(requestClass); request.setServerHost(null); // remove API url from request String requestJSON = gson.toJson(request); String responseJSON = executeJsonRequest(requestJSON, serviceUrl, requestClass); return (SafechargeResponse)gson.fromJson(responseJSON, RESPONSE_TYPE_BY_REQUEST_TYPE.get(request.getClass())); } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug(e.getMessage()); } } return null; } /** * Sends a POST request to the service at {@code serviceUrl} with a payload of {@code requestJSON}. * * @param requestJSON A {@link String} representation of a JSON object * @param serviceUrl The service URL to sent the request to * @return {@link String} response from the service (representing JSON object) * @throws IOException if the connection is interrupted or the response is unparsable */ public String executeJsonRequest(String requestJSON, String serviceUrl, Class requestClass) throws IOException { return executeRequest(requestJSON, serviceUrl, APIConstants.REQUEST_HEADERS, requestClass); } /** * Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}. * The request type is determined by the {@code headers} param. * * @param request A {@link String} representation of a request object. Can be JSON object, form data, etc... * @param serviceUrl The service URL to sent the request to * @param headers An array of {@link Header} objects, used to determine the request type * @param requestClass The Type Of request Used * @return {@link String} response from the service (representing JSON object) * @throws IOException if the connection is interrupted or the response is unparsable */ public String executeRequest(String request, String serviceUrl, Header[] headers, Class requestClass) throws IOException { HttpPost httpPost = new HttpPost(serviceUrl); httpPost.setHeaders(headers); httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8"))); if (logger.isDebugEnabled()) { logger.debug(requestClass.getSimpleName() + " Sent " + request); } HttpResponse response = httpClient.execute(httpPost); String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET); if (logger.isDebugEnabled()) { Class responseClass = RESPONSE_TYPE_BY_REQUEST_TYPE.get(requestClass); logger.debug(responseClass.getSimpleName() + " Received " + responseJSON); } return responseJSON; } }
package de.dhbw.humbuch.model.entity; import static org.junit.Assert.assertEquals; import java.util.Date; import org.junit.Test; public class StudentTest { @Test public void testStudentBuilder() { final int ID = 4; final String FIRST_NAME = "John"; final String LAST_NAME = "Doe"; final Date DATE = new Date(); final Grade GRADE = null; Student student = new Student.Builder(ID, FIRST_NAME, LAST_NAME, DATE, GRADE).build(); assertEquals(ID, student.getId()); assertEquals(FIRST_NAME, student.getFirstname()); assertEquals(LAST_NAME, student.getLastname()); assertEquals(DATE, student.getBirthday()); assertEquals(GRADE, student.getGrade()); } }
package com.ideaheap.sound.control; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.ideaheap.sound.R; import com.ideaheap.sound.service.AudioLevelListener; import com.ideaheap.sound.service.AudioRecordService; import com.ideaheap.sound.service.AudioUpdateListener; import com.ideaheap.sound.service.RepositoryService; public class RecordController extends TabController implements AudioLevelListener, AudioUpdateListener{ private final AudioRecordService recorder; private final RepositoryService repo; private ImageButton recButton; private boolean ignoreSilence; private String saveFile = "soundheap.ogg"; private final SherlockFragmentActivity activity; private Runnable getRecordSession(final String saveFile) { return new Runnable() { public void run() { try { if (ignoreSilence) { // TODO add the smarts back in here recorder.startRecording(repo.createNewVorbis(saveFile)); } else { recorder.startRecording(repo.createNewVorbis(saveFile)); } } catch (IOException e) { e.printStackTrace(); } } }; } public RecordController( SherlockFragmentActivity activity, TabListener listener, AudioRecordService recorder, RepositoryService repo) { super(activity, R.string.record_title, listener); this.activity = activity; this.recorder = recorder; this.repo = repo; recorder.setAudioLevelListener(this); } public void setupView(View view) { updateRecordInfo(view, recorder.isRecording(), saveFile); } private void updateRecordInfo(View v, boolean recording, String saveFile) { recButton = (ImageButton)v.findViewById(R.id.RecordButton); TextView recText = (TextView)v.findViewById(R.id.RecordText); if (recording) { recButton.setImageResource(R.drawable.device_access_mic); recButton.setBackgroundResource(R.drawable.circle_button_selected); recText.setText(R.string.recording); toggleInteractiveNaming(v, true, saveFile); } else { recButton.setImageResource(R.drawable.device_access_mic_muted); recButton.setBackgroundResource(R.drawable.circle_button); recText.setText(R.string.ready); toggleInteractiveNaming(v, false, saveFile); } } private void toggleInteractiveNaming(View v, boolean lock, String saveFile) { int interactiveVisibility = View.VISIBLE; int lockedinVisibility = View.VISIBLE; if (lock) interactiveVisibility = View.INVISIBLE; else lockedinVisibility = View.INVISIBLE; TextView actualFileToSave = (TextView)v.findViewById(R.id.RecordFileName); TextView saveFileEnding = (TextView)v.findViewById(R.id.RecordFilePostFix); EditText saveFilePrefix = (EditText)v.findViewById(R.id.RecordFilePrefix); actualFileToSave.setText(saveFile); actualFileToSave.setVisibility(lockedinVisibility); saveFileEnding.setVisibility(interactiveVisibility); saveFilePrefix.setVisibility(interactiveVisibility); } public void toggleRecord(View v) { // Figure out the save file's name final EditText filePrefix = (EditText) v.findViewById(R.id.RecordFilePrefix); Calendar c = Calendar.getInstance(); String timestamp = new SimpleDateFormat("yy.MM.dd-HH.mm.ss").format(c.getTime()); saveFile = filePrefix.getText().toString() + "." + timestamp + ".ogg"; if (recorder.isRecording()) { recorder.stopRecording(); updateRecordInfo(v, false, saveFile); } else { new Thread(getRecordSession(saveFile)).start(); updateRecordInfo(v, true, saveFile); } } public void setIgnoreSilence(boolean ignoreSilence) { this.ignoreSilence = ignoreSilence; } @Override public void onLevelChange(final int level) { //TODO } @Override public void onUpdate(int trackLocation) { //TODO } }
package org.pentaho.di.job.entries.mail; import java.nio.charset.Charset; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.gui.WindowProperty; import org.pentaho.di.core.widget.LabelText; import org.pentaho.di.core.widget.LabelTextVar; import org.pentaho.di.core.widget.TextVar; import org.pentaho.di.job.dialog.JobDialog; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.trans.step.BaseStepDialog; import org.pentaho.di.trans.steps.textfileinput.VariableButtonListenerFactory; /** * Dialog that allows you to edit a JobEntryMail object. * * @author Matt * @since 19-06-2003 */ public class JobEntryMailDialog extends Dialog implements JobEntryDialogInterface { private LabelText wName; private FormData fdName; private LabelTextVar wDestination; private LabelTextVar wDestinationCc; private LabelTextVar wDestinationBCc; private FormData fdDestination; private FormData fdDestinationCc; private FormData fdDestinationBCc; private LabelTextVar wServer; private FormData fdServer; private LabelTextVar wPort; private FormData fdPort; private Label wlUseAuth; private Button wUseAuth; private FormData fdlUseAuth, fdUseAuth; private Label wlUseSecAuth; private Button wUseSecAuth; private FormData fdlUseSecAuth, fdUseSecAuth; private LabelTextVar wAuthUser; private FormData fdAuthUser; private LabelTextVar wAuthPass; private FormData fdAuthPass; private LabelTextVar wReply; private FormData fdReply; private LabelTextVar wSubject; private FormData fdSubject; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlIncludeFiles; private Button wIncludeFiles; private FormData fdlIncludeFiles, fdIncludeFiles; private Label wlTypes; private List wTypes; private FormData fdlTypes, fdTypes; private Label wlZipFiles; private Button wZipFiles; private FormData fdlZipFiles, fdZipFiles; private LabelTextVar wZipFilename; private FormData fdZipFilename; private LabelTextVar wPerson; private FormData fdPerson; private LabelTextVar wPhone; private FormData fdPhone; private Label wlComment; private Text wComment; private FormData fdlComment, fdComment; private Label wlOnlyComment, wlUseHTML; private Button wOnlyComment, wUseHTML; private FormData fdlOnlyComment, fdOnlyComment, fdlUseHTML, fdUseHTML; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private JobEntryMail jobEntry; private boolean backupDate, backupChanged; private Props props; private Display display; private boolean gotEncodings = false; public JobEntryMailDialog(Shell parent, JobEntryMail jobEntry) { super(parent, SWT.NONE); props = Props.getInstance(); this.jobEntry = jobEntry; } public JobEntryInterface open() { Shell parent = getParent(); display = parent.getDisplay(); shell = new Shell(parent, props.getJobsDialogStyle()); props.setLook(shell); JobDialog.setShellImage(shell, jobEntry); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { jobEntry.setChanged(); } }; backupChanged = jobEntry.hasChanged(); backupDate = jobEntry.getIncludeDate(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("JobMail.Header")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wName = new LabelText(shell, Messages.getString("JobMail.NameOfEntry.Label"), Messages .getString("JobMail.NameOfEntry.Tooltip")); wName.addModifyListener(lsMod); fdName = new FormData(); fdName.top = new FormAttachment(0, 0); fdName.left = new FormAttachment(0, 0); fdName.right = new FormAttachment(100, 0); wName.setLayoutData(fdName); // Destination line wDestination = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddress.Label"), Messages .getString("JobMail.DestinationAddress.Tooltip")); wDestination.addModifyListener(lsMod); fdDestination = new FormData(); fdDestination.left = new FormAttachment(0, 0); fdDestination.top = new FormAttachment(wName, margin); fdDestination.right = new FormAttachment(100, 0); wDestination.setLayoutData(fdDestination); // Destination Cc wDestinationCc = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddressCc.Label"), Messages .getString("JobMail.DestinationAddressCc.Tooltip")); wDestinationCc.addModifyListener(lsMod); fdDestinationCc = new FormData(); fdDestinationCc.left = new FormAttachment(0, 0); fdDestinationCc.top = new FormAttachment(wDestination, margin); fdDestinationCc.right = new FormAttachment(100, 0); wDestinationCc.setLayoutData(fdDestinationCc); // Destination BCc wDestinationBCc = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddressBCc.Label"), Messages .getString("JobMail.DestinationAddressBCc.Tooltip")); wDestinationBCc.addModifyListener(lsMod); fdDestinationBCc = new FormData(); fdDestinationBCc.left = new FormAttachment(0, 0); fdDestinationBCc.top = new FormAttachment(wDestinationCc, margin); fdDestinationBCc.right = new FormAttachment(100, 0); wDestinationBCc.setLayoutData(fdDestinationBCc); // Server line wServer = new LabelTextVar(shell, Messages.getString("JobMail.SMTPServer.Label"), Messages .getString("JobMail.SMTPServer.Tooltip")); wServer.addModifyListener(lsMod); fdServer = new FormData(); fdServer.left = new FormAttachment(0, 0); fdServer.top = new FormAttachment(wDestinationBCc, margin); fdServer.right = new FormAttachment(100, 0); wServer.setLayoutData(fdServer); // Port line wPort = new LabelTextVar(shell, Messages.getString("JobMail.Port.Label"), Messages .getString("JobMail.Port.Tooltip")); wPort.addModifyListener(lsMod); fdPort = new FormData(); fdPort.left = new FormAttachment(0, 0); fdPort.top = new FormAttachment(wServer, margin); fdPort.right = new FormAttachment(100, 0); wPort.setLayoutData(fdPort); // Include Files? wlUseAuth = new Label(shell, SWT.RIGHT); wlUseAuth.setText(Messages.getString("JobMail.UseAuthentication.Label")); props.setLook(wlUseAuth); fdlUseAuth = new FormData(); fdlUseAuth.left = new FormAttachment(0, 0); fdlUseAuth.top = new FormAttachment(wPort, margin); fdlUseAuth.right = new FormAttachment(middle, -margin); wlUseAuth.setLayoutData(fdlUseAuth); wUseAuth = new Button(shell, SWT.CHECK); props.setLook(wUseAuth); fdUseAuth = new FormData(); fdUseAuth.left = new FormAttachment(middle, margin); fdUseAuth.top = new FormAttachment(wPort, margin); fdUseAuth.right = new FormAttachment(100, 0); wUseAuth.setLayoutData(fdUseAuth); wUseAuth.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // AuthUser line wAuthUser = new LabelTextVar(shell, Messages.getString("JobMail.AuthenticationUser.Label"), Messages.getString("JobMail.AuthenticationUser.Tooltip")); wAuthUser.addModifyListener(lsMod); fdAuthUser = new FormData(); fdAuthUser.left = new FormAttachment(0, 0); fdAuthUser.top = new FormAttachment(wUseAuth, margin); fdAuthUser.right = new FormAttachment(100, 0); wAuthUser.setLayoutData(fdAuthUser); // AuthPass line wAuthPass = new LabelTextVar(shell, Messages .getString("JobMail.AuthenticationPassword.Label"), Messages .getString("JobMail.AuthenticationPassword.Tooltip")); wAuthPass.setEchoChar('*'); wAuthPass.addModifyListener(lsMod); fdAuthPass = new FormData(); fdAuthPass.left = new FormAttachment(0, 0); fdAuthPass.top = new FormAttachment(wAuthUser, margin); fdAuthPass.right = new FormAttachment(100, 0); wAuthPass.setLayoutData(fdAuthPass); // Use authentication? wlUseSecAuth = new Label(shell, SWT.RIGHT); wlUseSecAuth.setText(Messages.getString("JobMail.UseSecAuthentication.Label")); props.setLook(wlUseSecAuth); fdlUseSecAuth = new FormData(); fdlUseSecAuth.left = new FormAttachment(0, 0); fdlUseSecAuth.top = new FormAttachment(wAuthPass, margin); fdlUseSecAuth.right = new FormAttachment(middle, -margin); wlUseSecAuth.setLayoutData(fdlUseSecAuth); wUseSecAuth = new Button(shell, SWT.CHECK); props.setLook(wUseSecAuth); fdUseSecAuth = new FormData(); fdUseSecAuth.left = new FormAttachment(middle, margin); fdUseSecAuth.top = new FormAttachment(wAuthPass, margin); fdUseSecAuth.right = new FormAttachment(100, 0); wUseSecAuth.setLayoutData(fdUseSecAuth); wUseSecAuth.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // Reply line wReply = new LabelTextVar(shell, Messages.getString("JobMail.ReplyAddress.Label"), Messages .getString("JobMail.ReplyAddress.Tooltip")); wReply.addModifyListener(lsMod); fdReply = new FormData(); fdReply.left = new FormAttachment(0, 0); fdReply.top = new FormAttachment(wUseSecAuth, margin); fdReply.right = new FormAttachment(100, 0); wReply.setLayoutData(fdReply); // Subject line wSubject = new LabelTextVar(shell, Messages.getString("JobMail.Subject.Label"), Messages .getString("JobMail.Subject.Tooltip")); wSubject.addModifyListener(lsMod); fdSubject = new FormData(); fdSubject.left = new FormAttachment(0, 0); fdSubject.top = new FormAttachment(wReply, margin); fdSubject.right = new FormAttachment(100, 0); wSubject.setLayoutData(fdSubject); // Add date to logfile name? wlAddDate = new Label(shell, SWT.RIGHT); wlAddDate.setText(Messages.getString("JobMail.IncludeDate.Label")); props.setLook(wlAddDate); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(wSubject, margin); fdlAddDate.right = new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate = new Button(shell, SWT.CHECK); props.setLook(wAddDate); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment(middle, margin); fdAddDate.top = new FormAttachment(wSubject, margin); fdAddDate.right = new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Include Files? wlIncludeFiles = new Label(shell, SWT.RIGHT); wlIncludeFiles.setText(Messages.getString("JobMail.AttachFiles.Label")); props.setLook(wlIncludeFiles); fdlIncludeFiles = new FormData(); fdlIncludeFiles.left = new FormAttachment(0, 0); fdlIncludeFiles.top = new FormAttachment(wAddDate, margin); fdlIncludeFiles.right = new FormAttachment(middle, -margin); wlIncludeFiles.setLayoutData(fdlIncludeFiles); wIncludeFiles = new Button(shell, SWT.CHECK); props.setLook(wIncludeFiles); fdIncludeFiles = new FormData(); fdIncludeFiles.left = new FormAttachment(middle, margin); fdIncludeFiles.top = new FormAttachment(wAddDate, margin); fdIncludeFiles.right = new FormAttachment(100, 0); wIncludeFiles.setLayoutData(fdIncludeFiles); wIncludeFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // Include Files? wlTypes = new Label(shell, SWT.RIGHT); wlTypes.setText(Messages.getString("JobMail.SelectFileTypes.Label")); props.setLook(wlTypes); fdlTypes = new FormData(); fdlTypes.left = new FormAttachment(0, 0); fdlTypes.top = new FormAttachment(wIncludeFiles, margin); fdlTypes.right = new FormAttachment(middle, -margin); wlTypes.setLayoutData(fdlTypes); wTypes = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wTypes); fdTypes = new FormData(); fdTypes.left = new FormAttachment(middle, margin); fdTypes.top = new FormAttachment(wIncludeFiles, margin); fdTypes.bottom = new FormAttachment(wIncludeFiles, margin + 150); fdTypes.right = new FormAttachment(100, 0); wTypes.setLayoutData(fdTypes); for (int i = 0; i < ResultFile.getAllTypeDesc().length; i++) { wTypes.add(ResultFile.getAllTypeDesc()[i]); } // Zip Files? wlZipFiles = new Label(shell, SWT.RIGHT); wlZipFiles.setText(Messages.getString("JobMail.ZipFiles.Label")); props.setLook(wlZipFiles); fdlZipFiles = new FormData(); fdlZipFiles.left = new FormAttachment(0, 0); fdlZipFiles.top = new FormAttachment(wTypes, margin); fdlZipFiles.right = new FormAttachment(middle, -margin); wlZipFiles.setLayoutData(fdlZipFiles); wZipFiles = new Button(shell, SWT.CHECK); props.setLook(wZipFiles); fdZipFiles = new FormData(); fdZipFiles.left = new FormAttachment(middle, margin); fdZipFiles.top = new FormAttachment(wTypes, margin); fdZipFiles.right = new FormAttachment(100, 0); wZipFiles.setLayoutData(fdZipFiles); wZipFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // ZipFilename line wZipFilename = new LabelTextVar(shell, Messages.getString("JobMail.ZipFilename.Label"), Messages.getString("JobMail.ZipFilename.Tooltip")); wZipFilename.addModifyListener(lsMod); fdZipFilename = new FormData(); fdZipFilename.left = new FormAttachment(0, 0); fdZipFilename.top = new FormAttachment(wZipFiles, margin); fdZipFilename.right = new FormAttachment(100, 0); wZipFilename.setLayoutData(fdZipFilename); // ZipFilename line wPerson = new LabelTextVar(shell, Messages.getString("JobMail.ContactPerson.Label"), Messages.getString("JobMail.ContactPerson.Tooltip")); wPerson.addModifyListener(lsMod); fdPerson = new FormData(); fdPerson.left = new FormAttachment(0, 0); fdPerson.top = new FormAttachment(wZipFilename, margin); fdPerson.right = new FormAttachment(100, 0); wPerson.setLayoutData(fdPerson); // Phone line wPhone = new LabelTextVar(shell, Messages.getString("JobMail.ContactPhone.Label"), Messages .getString("JobMail.ContactPhone.Tooltip")); wPhone.addModifyListener(lsMod); fdPhone = new FormData(); fdPhone.left = new FormAttachment(0, 0); fdPhone.top = new FormAttachment(wPerson, margin); fdPhone.right = new FormAttachment(100, 0); wPhone.setLayoutData(fdPhone); // Some buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, null); // Only send the comment in the mail body wlOnlyComment = new Label(shell, SWT.RIGHT); wlOnlyComment.setText(Messages.getString("JobMail.OnlyCommentInBody.Label")); props.setLook(wlOnlyComment); fdlOnlyComment = new FormData(); fdlOnlyComment.left = new FormAttachment(0, 0); fdlOnlyComment.bottom = new FormAttachment(wOK, -margin * 2); fdlOnlyComment.right = new FormAttachment(middle, -margin); wlOnlyComment.setLayoutData(fdlOnlyComment); wOnlyComment = new Button(shell, SWT.CHECK); props.setLook(wOnlyComment); fdOnlyComment = new FormData(); fdOnlyComment.left = new FormAttachment(middle, margin); fdOnlyComment.bottom = new FormAttachment(wOK, -margin * 2); fdOnlyComment.right = new FormAttachment(100, 0); wOnlyComment.setLayoutData(fdOnlyComment); wOnlyComment.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Encoding wlEncoding=new Label(shell, SWT.RIGHT); wlEncoding.setText(Messages.getString("JobMail.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.bottom = new FormAttachment(wOnlyComment, -margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(shell, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, margin); fdEncoding.bottom = new FormAttachment(wOnlyComment,-margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); // HTML format ? wlUseHTML = new Label(shell, SWT.RIGHT); wlUseHTML.setText(Messages.getString("JobMail.UseHTMLInBody.Label")); props.setLook(wlUseHTML); fdlUseHTML = new FormData(); fdlUseHTML.left = new FormAttachment(0, 0); fdlUseHTML.bottom = new FormAttachment(wEncoding, -margin ); fdlUseHTML.right = new FormAttachment(middle, -margin); wlUseHTML.setLayoutData(fdlUseHTML); wUseHTML = new Button(shell, SWT.CHECK); props.setLook(wUseHTML); fdUseHTML = new FormData(); fdUseHTML.left = new FormAttachment(middle, margin); fdUseHTML.bottom = new FormAttachment(wEncoding, -margin ); fdUseHTML.right = new FormAttachment(100, 0); wUseHTML.setLayoutData(fdUseHTML); wUseHTML.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { SetEnabledEncoding(); jobEntry.setChanged(); } }); // Comment line wlComment = new Label(shell, SWT.RIGHT); wlComment.setText(Messages.getString("JobMail.Comment.Label")); props.setLook(wlComment); fdlComment = new FormData(); fdlComment.left = new FormAttachment(0, 0); fdlComment.top = new FormAttachment(wPhone, margin); fdlComment.right = new FormAttachment(middle, margin); wlComment.setLayoutData(fdlComment); wComment = new Text(shell, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wComment); wComment.addModifyListener(lsMod); fdComment = new FormData(); fdComment.left = new FormAttachment(middle, margin); fdComment.top = new FormAttachment(wPhone, margin); fdComment.right = new FormAttachment(100, 0); fdComment.bottom = new FormAttachment(wUseHTML, -margin); wComment.setLayoutData(fdComment); SelectionAdapter lsVar = VariableButtonListenerFactory.getSelectionAdapter(shell, wComment); wComment.addKeyListener(TextVar.getControlSpaceKeyListener(wComment, lsVar)); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wOK.addListener(SWT.Selection, lsOK); wCancel.addListener(SWT.Selection, lsCancel); lsDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wName.addSelectionListener(lsDef); wServer.addSelectionListener(lsDef); wSubject.addSelectionListener(lsDef); wDestination.addSelectionListener(lsDef); wDestinationCc.addSelectionListener(lsDef); wDestinationBCc.addSelectionListener(lsDef); wReply.addSelectionListener(lsDef); wPerson.addSelectionListener(lsDef); wPhone.addSelectionListener(lsDef); wZipFilename.addSelectionListener(lsDef); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } }); // BaseStepDialog.setTraverseOrder(new Control[] {wName, wDestination, wServer, wUseAuth, // wAuthUser, wAuthPass, wReply, // wSubject, wAddDate, wIncludeFiles, wTypes, wZipFiles, wZipFilename, wPerson, wPhone, // wComment, wOK, wCancel }); getData(); SetEnabledEncoding(); BaseStepDialog.setSize(shell); shell.open(); props.setDialogSize(shell, "JobMailDialogSize"); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return jobEntry; } private void SetEnabledEncoding () { wEncoding.setEnabled(wUseHTML.getSelection()); wlEncoding.setEnabled(wUseHTML.getSelection()); } protected void setFlags() { wlTypes.setEnabled(wIncludeFiles.getSelection()); wTypes.setEnabled(wIncludeFiles.getSelection()); wlZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFilename.setEnabled(wIncludeFiles.getSelection() && wZipFiles.getSelection()); wAuthUser.setEnabled(wUseAuth.getSelection()); wAuthPass.setEnabled(wUseAuth.getSelection()); wUseSecAuth.setEnabled(wUseAuth.getSelection()); } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } public void getData() { if (jobEntry.getName() != null) wName.setText(jobEntry.getName()); if (jobEntry.getDestination() != null) wDestination.setText(jobEntry.getDestination()); if (jobEntry.getDestinationCc() != null) wDestinationCc.setText(jobEntry.getDestinationCc()); if (jobEntry.getDestinationBCc() != null) wDestinationBCc.setText(jobEntry.getDestinationBCc()); if (jobEntry.getServer() != null) wServer.setText(jobEntry.getServer()); if (jobEntry.getPort() != null) wPort.setText(jobEntry.getPort()); if (jobEntry.getReplyAddress() != null) wReply.setText(jobEntry.getReplyAddress()); if (jobEntry.getSubject() != null) wSubject.setText(jobEntry.getSubject()); if (jobEntry.getContactPerson() != null) wPerson.setText(jobEntry.getContactPerson()); if (jobEntry.getContactPhone() != null) wPhone.setText(jobEntry.getContactPhone()); if (jobEntry.getComment() != null) wComment.setText(jobEntry.getComment()); wAddDate.setSelection(jobEntry.getIncludeDate()); wIncludeFiles.setSelection(jobEntry.isIncludingFiles()); if (jobEntry.getFileType() != null) { int types[] = jobEntry.getFileType(); wTypes.setSelection(types); } wZipFiles.setSelection(jobEntry.isZipFiles()); if (jobEntry.getZipFilename() != null) wZipFilename.setText(jobEntry.getZipFilename()); wUseAuth.setSelection(jobEntry.isUsingAuthentication()); wUseSecAuth.setSelection(jobEntry.isUsingSecureAuthentication()); if (jobEntry.getAuthenticationUser() != null) wAuthUser.setText(jobEntry.getAuthenticationUser()); if (jobEntry.getAuthenticationPassword() != null) wAuthPass.setText(jobEntry.getAuthenticationPassword()); wOnlyComment.setSelection(jobEntry.isOnlySendComment()); wUseHTML.setSelection(jobEntry.isUseHTML()); if (jobEntry.getEncoding()!=null) { wEncoding.setText(""+jobEntry.getEncoding()); }else { wEncoding.setText("UTF-8"); } setFlags(); } private void cancel() { jobEntry.setChanged(backupChanged); jobEntry.setIncludeDate(backupDate); jobEntry = null; dispose(); } private void ok() { jobEntry.setName(wName.getText()); jobEntry.setDestination(wDestination.getText()); jobEntry.setDestinationCc(wDestinationCc.getText()); jobEntry.setDestinationBCc(wDestinationBCc.getText()); jobEntry.setServer(wServer.getText()); jobEntry.setPort(wPort.getText()); jobEntry.setReplyAddress(wReply.getText()); jobEntry.setSubject(wSubject.getText()); jobEntry.setContactPerson(wPerson.getText()); jobEntry.setContactPhone(wPhone.getText()); jobEntry.setComment(wComment.getText()); jobEntry.setIncludeDate(wAddDate.getSelection()); jobEntry.setIncludingFiles(wIncludeFiles.getSelection()); jobEntry.setFileType(wTypes.getSelectionIndices()); jobEntry.setZipFilename(wZipFilename.getText()); jobEntry.setZipFiles(wZipFiles.getSelection()); jobEntry.setAuthenticationUser(wAuthUser.getText()); jobEntry.setAuthenticationPassword(wAuthPass.getText()); jobEntry.setUsingAuthentication(wUseAuth.getSelection()); jobEntry.setUsingSecureAuthentication(wUseSecAuth.getSelection()); jobEntry.setOnlySendComment(wOnlyComment.getSelection()); jobEntry.setUseHTML(wUseHTML.getSelection()); jobEntry.setEncoding(wEncoding.getText()); dispose(); } private void setEncodings() { // Encoding of the text file: if (!gotEncodings) { gotEncodings = true; wEncoding.removeAll(); java.util.List<Charset> values = new ArrayList<Charset>(Charset.availableCharsets().values()); for (Charset charSet:values) { wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8"); int idx = Const.indexOfString(defEncoding, wEncoding.getItems() ); if (idx>=0) wEncoding.select( idx ); } } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms.util; import jssc.SerialPortEvent; import org.junit.jupiter.api.*; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; /** * Test class for {@link EKGSerialPort}. * * @since December 14, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ class EKGSerialPortTest { private static long READ_DURATION = (long) 3e9; // 3 seconds, expressed in nanoseconds private EKGSerialPort serialPort; @BeforeEach void setUp() { serialPort = new EKGSerialPort() { @Override public void serialEvent(SerialPortEvent serialPortEvent) { } }; serialPort.openPort(); } @AfterEach void tearDown() { serialPort.closePort(); } @Test void testInTerminal() { byte[] data; long startTime = System.nanoTime(); do { data = serialPort.readData(); if (data != null && data.length > 0) { System.out.println(Arrays.toString(data)); } } while (System.nanoTime() - startTime < READ_DURATION); } }
package com.sentibrand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.OptionalDouble; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.http.ResponseEntity.unprocessableEntity; import static org.springframework.web.bind.annotation.RequestMethod.POST; @RestController @RequestMapping("/sentiment") public class SentimentProcessingController { private static final Logger logger = LoggerFactory.getLogger(SentimentProcessingController.class); private final SentimentProcessingService sentimentProcessingService; private final SentimentResponseFactory sentimentResponseFactory; @Autowired public SentimentProcessingController(final SentimentProcessingService sentimentProcessingService, final SentimentResponseFactory sentimentResponseFactory) { this.sentimentProcessingService = sentimentProcessingService; this.sentimentResponseFactory = sentimentResponseFactory; } @RequestMapping(method = POST) public ResponseEntity<SentimentResponse> sentiment(@RequestBody SentimentRequest sentimentRequest) { logger.info(String.format("Processing sentiment for text: %s", sentimentRequest.getText())); OptionalDouble optionalDouble = sentimentProcessingService.forText(sentimentRequest.getText()); return optionalDouble.isPresent() ? ok(sentimentResponseFactory.create(sentimentRequest, optionalDouble.getAsDouble())) : unprocessableEntity().body(null); } }
package com.cognitect.transducers; import junit.framework.TestCase; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.cognitect.transducers.Fns.*; //import static com.cognitect.transducers.Base.*; public class FnsTest extends TestCase { private List<Integer> ints(final int n) { return new ArrayList<Integer>(n) {{ for(int i = 0; i < n; i++) { add(i); } }}; } public void testMap() throws Exception { ITransducer<String, Integer> xf = map(new Function<Integer, String>() { @Override public String apply(Integer i) { return i.toString(); } }); String s = transduce(xf, new IStepFunction<String, String>() { @Override public String apply(String result, String input, AtomicBoolean reduced) { return result + input + " "; } }, "", ints(10)); assertEquals(s, "0 1 2 3 4 5 6 7 8 9 "); ITransducer<Integer, Integer> xn = map(new Function<Integer, Integer>() { @Override public Integer apply(Integer i) { return i; } }); List<Integer> nums = transduce(xn, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input + 1); return result; } }, new ArrayList<Integer>(), ints(10)); Integer[] expected = {1,2,3,4,5,6,7,8,9,10}; assertTrue(nums.equals(Arrays.asList(expected))); } public void testFilter() throws Exception { ITransducer<Integer, Integer> xf = filter(new Predicate<Integer>() { @Override public boolean test(Integer integer) { return integer.intValue() % 2 != 0; } }); List<Integer> odds = transduce(xf, new IStepFunction<ArrayList<Integer>, Integer>() { @Override public ArrayList<Integer> apply(ArrayList<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(10)); Integer[] expected = {1,3,5,7,9}; assertTrue(odds.equals(Arrays.asList(expected))); } public void testCat() throws Exception { ITransducer<Integer, Iterable<Integer>> xf = cat(); List<Iterable<Integer>> data = new ArrayList<Iterable<Integer>>() {{ add(ints(10)); add(ints(20)); }}; List<Integer> vals = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), data); int i=0; List<Integer> nums = ints(10); for(int j=0; j<nums.size(); j++) { assertEquals((int)nums.get(j), (int)vals.get(i)); i += 1; } nums = ints(20); for(int j=0; j<nums.size(); j++) { assertEquals((int)nums.get(j), (int)vals.get(i)); i += 1; } } public void testMapcat() throws Exception { ITransducer<Character, Integer> xf = mapcat(new Function<Integer, Iterable<Character>>() { @Override public Iterable<Character> apply(Integer integer) { final String s = integer.toString(); return new ArrayList<Character>(s.length()) {{ for (char c : s.toCharArray()) add(c); }}; } }); List<Character> vals = transduce(xf, new IStepFunction<List<Character>, Character>() { @Override public List<Character> apply(List<Character> result, Character input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Character>(), ints(10)); Character[] expected = {'0','1','2','3','4','5','6','7','8','9'}; assertTrue(vals.equals(Arrays.asList(expected))); } public void testComp() throws Exception { ITransducer<Integer, Integer> f = filter(new Predicate<Integer>() { @Override public boolean test(Integer integer) { return integer.intValue() % 2 != 0; } }); ITransducer<String, Integer> m = map(new Function<Integer, String>() { @Override public String apply(Integer i) { return i.toString(); } }); ITransducer<String, Integer> xf = f.comp(m); List<String> odds = transduce(xf, new IStepFunction<List<String>, String>() { @Override public List<String> apply(List<String> result, String input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<String>(), ints(10)); String[] expected = {"1","3","5","7","9"}; assertTrue(odds.equals(Arrays.asList(expected))); } public void testTake() throws Exception { ITransducer<Integer, Integer> xf = take(5); List<Integer> five = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(20)); Integer[] expected = {0,1,2,3,4}; assertTrue(five.equals(Arrays.asList(expected))); } public void testTakeWhile() throws Exception { ITransducer<Integer, Integer> xf = takeWhile(new Predicate<Integer>() { @Override public boolean test(Integer integer) { return integer < 10; } }); List<Integer> ten = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(20)); Integer[] expected = {0,1,2,3,4,5,6,7,8,9}; assertTrue(ten.equals(Arrays.asList(expected))); } public void testDrop() throws Exception { ITransducer<Integer, Integer> xf = drop(5); List<Integer> five = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(10)); Integer[] expected = {5,6,7,8,9}; assertTrue(five.equals(Arrays.asList(expected))); } public void testDropWhile() throws Exception { ITransducer<Integer, Integer> xf = dropWhile(new Predicate<Integer>() { @Override public boolean test(Integer integer) { return integer < 10; } }); List<Integer> ten = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(20)); Integer[] expected = {10,11,12,13,14,15,16,17,18,19}; assertTrue(ten.equals(Arrays.asList(expected))); } public void testTakeNth() throws Exception { ITransducer<Integer, Integer> xf = takeNth(2); List<Integer> evens = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(10)); Integer[] expected = {0,2,4,6,8}; assertTrue(evens.equals(Arrays.asList(expected))); } public void testReplace() throws Exception { ITransducer<Integer, Integer> xf = replace(new HashMap<Integer, Integer>() {{ put(3, 42); }}); List<Integer> evens = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(5)); Integer[] expected = {0,1,2,42,4}; assertTrue(evens.equals(Arrays.asList(expected))); } public void testKeep() throws Exception { ITransducer<Integer, Integer> xf = keep(new Function<Integer, Integer>() { @Override public Integer apply(Integer integer) { return (integer % 2 == 0) ? null : integer; } }); List<Integer> odds = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), ints(10)); Integer[] expected = {1,3,5,7,9}; assertTrue(odds.equals(Arrays.asList(expected))); } public void testDedupe() throws Exception { Integer[] seed = {1,2,2,3,4,5,5,5,5,5,5,5,0}; ITransducer<Integer, Integer> xf = dedupe(); List<Integer> nums = transduce(xf, new IStepFunction<List<Integer>, Integer>() { @Override public List<Integer> apply(List<Integer> result, Integer input, AtomicBoolean reduced) { result.add(input); return result; } }, new ArrayList<Integer>(), Arrays.asList(seed)); Integer[] expected = {1,2,3,4,5,0}; assertTrue(nums.equals(Arrays.asList(expected))); } public void testPartitionBy() throws Exception { Integer[] seed = {1,1,1,2,2,3,4,5,5}; ITransducer<Iterable<Integer>, Integer> xf = partitionBy(new Function<Integer, Integer>() { @Override public Integer apply(final Integer integer) { return integer; } }); List<Integer> vals = transduce(xf, new IReducingFunction<List<Integer>, Iterable<Integer>>() { @Override public List<Integer> apply() { return new ArrayList<Integer>(); } @Override public List<Integer> apply(List<Integer> result) { return result; } @Override public List<Integer> apply(List<Integer> result, Iterable<Integer> input, AtomicBoolean reduced) { for(Integer i : input) { result.add(i); } return result; } }, new ArrayList<Integer>(), Arrays.asList(seed)); System.out.println(vals.toString()); //assertTrue(vals.equals(Arrays.asList(expected))); } }
package org.pentaho.di.trans.steps.exceloutput; import java.io.File; import java.util.Locale; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.write.DateFormat; import jxl.write.DateFormats; import jxl.write.DateTime; import jxl.write.Label; import jxl.write.NumberFormat; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Converts input rows to excel cells and then writes this information to one or more files. * * @author Matt * @since 7-sep-2006 */ public class ExcelOutput extends BaseStep implements StepInterface { private ExcelOutputMeta meta; private ExcelOutputData data; public ExcelOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; Object[] r; boolean result=true; r=getRow(); // This also waits for a row to be finished. if (first) { // get the RowMeta data.previousMeta = (RowMetaInterface) getInputRowMeta().clone(); //do not set first=false, below is another part that uses first } if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) || ( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && ((linesOutput+1)%meta.getSplitEvery())==0) ) { if (data.headerrow!=null) { if ( meta.isFooterEnabled() ) { writeHeader(); } } // Not finished: open another file... if (r!=null) { closeFile(); if (!openNewFile()) { logError("Unable to open new file (split #"+data.splitnr+"..."); setErrors(1); return false; } if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++; } } if (r==null) // no more input to be expected... { setOutputDone(); return false; } result=writeRowToFile(r); if (!result) { setErrors(1); stopAll(); return false; } putRow(data.previousMeta, r); // in case we want it to go further... if (checkFeedback(linesOutput)) logBasic("linenr "+linesOutput); return result; } private boolean writeRowToFile(Object[] r) { Object v; try { if (first) { first=false; if ( meta.isHeaderEnabled() || meta.isFooterEnabled()) // See if we have to write a header-line) { data.headerrow=data.previousMeta.cloneRow(r); // copy the row for the footer! if (meta.isHeaderEnabled() && data.headerrow!=null) { if (writeHeader() ) { return false; } } } data.fieldnrs=new int[meta.getOutputFields().length]; for (int i=0;i<meta.getOutputFields().length;i++) { data.fieldnrs[i]=data.previousMeta.indexOfValue(meta.getOutputFields()[i].getName()); if (data.fieldnrs[i]<0) { logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!"); setErrors(1); stopAll(); return false; } } } if (meta.getOutputFields()==null || meta.getOutputFields().length==0) { /* * Write all values in stream to text file. */ for (int i=0;i<data.previousMeta.size();i++) { v=r[i]; if(!writeField(v, data.previousMeta.getValueMeta(i), null, i)) return false; } // go to the next line data.positionX = 0; data.positionY++; } else { /* * Only write the fields specified! */ for (int i=0;i<meta.getOutputFields().length;i++) { v=r[data.fieldnrs[i]]; if(!writeField(v, data.previousMeta.getValueMeta(data.fieldnrs[i]), meta.getOutputFields()[i], i)) return false; } // go to the next line data.positionX = 0; data.positionY++; } } catch(Exception e) { logError("Error writing line :"+e.toString()); return false; } linesOutput++; return true; } /** * Write a value to Excel, increasing data.positionX with one afterwards. * @param v The value to write * @param vMeta The valueMeta to write * @param excelField the field information (if any, otherwise : null) * @param column the excel column for getting the template format * @return */ private boolean writeField(Object v, ValueMetaInterface vMeta, ExcelField excelField, int column) { return writeField(v, vMeta, excelField, column, false); } /** * Write a value to Excel, increasing data.positionX with one afterwards. * @param v The value to write * @param vMeta The valueMeta to write * @param excelField the field information (if any, otherwise : null) * @param column the excel column for getting the template format * @param isHeader true if this is part of the header/footer * @return */ private boolean writeField(Object v, ValueMetaInterface vMeta, ExcelField excelField, int column, boolean isHeader) { try { String hashName = vMeta.getName(); if (isHeader) hashName = "____header_field____"; // all strings, can map to the same format. WritableCellFormat cellFormat=(WritableCellFormat) data.formats.get(hashName); // when template is used, take over the column format if (cellFormat==null && meta.isTemplateEnabled() && !isHeader) { try { if (column<data.templateColumns) { cellFormat=new WritableCellFormat(data.sheet.getColumnView(column).getFormat()); data.formats.put(hashName, cellFormat); // save for next time around... } } catch (RuntimeException e) { //ignore if the column is not found, format as usual } } switch(vMeta.getType()) { case ValueMetaInterface.TYPE_DATE: { if (v!=null && vMeta.getDate(v)!=null) { if (cellFormat==null) { if (excelField!=null && excelField.getFormat()!=null) { DateFormat dateFormat = new DateFormat(excelField.getFormat()); cellFormat=new WritableCellFormat(dateFormat); } else { cellFormat = new WritableCellFormat(DateFormats.FORMAT9); } data.formats.put(hashName, cellFormat); // save for next time around... } DateTime dateTime = new DateTime(data.positionX, data.positionY, vMeta.getDate(v), cellFormat); data.sheet.addCell(dateTime); } else { data.sheet.addCell(new Label(data.positionX, data.positionY, "")); } } break; case ValueMetaInterface.TYPE_STRING: case ValueMetaInterface.TYPE_BOOLEAN: case ValueMetaInterface.TYPE_BINARY: { if (v!=null) { if (cellFormat==null) { cellFormat = new WritableCellFormat(data.writableFont); data.formats.put(hashName, cellFormat); } Label label = new Label(data.positionX, data.positionY, vMeta.getString(v), cellFormat); data.sheet.addCell(label); } else { data.sheet.addCell(new Label(data.positionX, data.positionY, "")); } } break; case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_BIGNUMBER: case ValueMetaInterface.TYPE_INTEGER: { if (v!=null) { if (cellFormat==null) { String format; if (excelField!=null && excelField.getFormat()!=null) { format=excelField.getFormat(); } else { format = " } NumberFormat numberFormat = new NumberFormat(format); cellFormat = new WritableCellFormat(numberFormat); data.formats.put(vMeta.getName(), cellFormat); // save for next time around... } jxl.write.Number number = new jxl.write.Number(data.positionX, data.positionY, vMeta.getNumber(v), cellFormat); data.sheet.addCell(number); } else { data.sheet.addCell(new Label(data.positionX, data.positionY, "")); } } break; default: break; } } catch(Exception e) { logError("Error writing field ("+data.positionX+","+data.positionY+") : "+e.toString()); logError(Const.getStackTracker(e)); return false; } finally { data.positionX++; // always advance :-) } return true; } private boolean writeHeader() { boolean retval=false; Object[] r=data.headerrow; try { // If we have fields specified: list them in this order! if (meta.getOutputFields()!=null && meta.getOutputFields().length>0) { for (int i=0;i<meta.getOutputFields().length;i++) { String fieldName = meta.getOutputFields()[i].getName(); ValueMetaInterface vMeta=new ValueMeta(fieldName, ValueMetaInterface.TYPE_STRING); writeField(new String(fieldName), vMeta, null, i, true); } } else if (r!=null) // Just put all field names in the header/footer { for (int i=0;i<data.previousMeta.size();i++) { String fieldName = data.previousMeta.getFieldNames()[i]; ValueMetaInterface vMeta=new ValueMeta(fieldName, ValueMetaInterface.TYPE_STRING); writeField(new String(fieldName), vMeta, null, i, true); } } } catch(Exception e) { logError("Error writing header line: "+e.toString()); logError(Const.getStackTracker(e)); retval=true; } finally { data.positionX=0; data.positionY++; } linesOutput++; return retval; } public String buildFilename() { return meta.buildFilename(this, getCopy(), data.splitnr); } public boolean openNewFile() { boolean retval=false; try { WorkbookSettings ws = new WorkbookSettings(); ws.setLocale(Locale.getDefault()); if (!Const.isEmpty(meta.getEncoding())) { ws.setEncoding(meta.getEncoding()); } FileObject file = KettleVFS.getFileObject(buildFilename()); // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with an Excel output step"); addResultFile(resultFile); // Create the workboook if (!meta.isTemplateEnabled()) { // Create a new Workbook data.workbook = Workbook.createWorkbook(file.getContent().getOutputStream(), ws); // Create a sheet? data.sheet = data.workbook.createSheet("Sheet1", 0); } else { // create the openFile from the template Workbook tmpWorkbook=Workbook.getWorkbook( new File(environmentSubstitute(meta.getTemplateFileName()))); data.workbook = Workbook.createWorkbook(file.getContent().getOutputStream(), tmpWorkbook); tmpWorkbook.close(); // use only the first sheet as template data.sheet = data.workbook.getSheet(0); // save inital number of columns data.templateColumns = data.sheet.getColumns(); } // Renamme Sheet if (!Const.isEmpty(meta.getSheetname(this))) { data.sheet.setName(meta.getSheetname(this)); } if (meta.isSheetProtected()) { // Protect Sheet by setting password data.sheet.getSettings().setProtected(true); data.sheet.getSettings().setPassword(meta.getPassword(this)); } // Set the initial position... data.positionX = 0; if (meta.isTemplateEnabled() && meta.isTemplateAppend()) { data.positionY = data.sheet.getRows(); } else { data.positionY = 0; } retval=true; } catch(Exception e) { logError("Error opening new file : "+e.toString()); } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; } private boolean closeFile() { boolean retval=false; try { data.workbook.write(); data.workbook.close(); data.formats.clear(); // Explicitly call garbage collect to have file handle // released. Bug tracker: PDI-48 System.gc(); retval=true; } catch(Exception e) { logError("Unable to close openFile file : "+e.toString()); } return retval; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; if (super.init(smi, sdi)) { data.splitnr=0; try { // Create the default font TODO: allow to change this later on. data.writableFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD); } catch(Exception we) { logError("Unexpected error preparing to write to Excel file : "+we.toString()); logError(Const.getStackTracker(we)); return false; } if (openNewFile()) { return true; } else { logError("Couldn't open file "+meta.getFileName()); setErrors(1L); stopAll(); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; closeFile(); super.dispose(smi, sdi); } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "+t.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package com.teamwizardry.refraction.api; import com.teamwizardry.librarianlib.common.util.ConfigPropertyBoolean; import com.teamwizardry.librarianlib.common.util.ConfigPropertyDouble; import com.teamwizardry.librarianlib.common.util.ConfigPropertyInt; /** * @author WireSegal * Created at 12:18 AM on 12/8/16. */ public final class ConfigValues { @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "max_beam_range", comment = "This will specify how far a beam can go", defaultValue = 128) public static int BEAM_RANGE; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "distance_loss", comment = "The factor to multiply the potency - distance by.", defaultValue = 1) public static int DISTANCE_LOSS; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "solar_strength", comment = "This will specify the strength the sun will provide to magnifiers. Max: 255", defaultValue = 16) public static int SOLAR_ALPHA; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "glowstone_strength", comment = "This will specify the strength glowstone will provide to the glowstone laser. Max: 255 ", defaultValue = 64) public static int GLOWSTONE_ALPHA; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "electric_strength", comment = "This will specify the strength electricity will provide to the Electric Laser. Max: 255 ", defaultValue = 64) public static int ELECTRIC_ALPHA; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "glowstone_fuel_expire_delay", comment = "Change this and it'll set how long glowstone fuel will last in the glowstone powered laser", defaultValue = 500) public static int GLOWSTONE_FUEL_EXPIRE_DELAY; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "max_tesla_for_electric_laser", comment = "Change this and it'll set how much tesla can be stored in the Electric Laser", defaultValue = 100000) public static int MAX_TESLA; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "beam_electricity_per_tick", comment = "Change this and it'll set how much tesla/tick is required to feed the Electric Laser", defaultValue = 50) public static int TESLA_PER_TICK; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "beam_particle_life", comment = "Change this and it'll set how long beams will stay. Higher numbers will make beams feel laggier but they just VISUALLY stay longer. This is useful if you have terrible TPS issues and/or beams exciterPos flickering for whatever reason.", defaultValue = 8) public static int BEAM_PARTICLE_LIFE; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "disco_ball_beam_bounce_limit", comment = "The disco ball's beams have a bounce/reflecting limit of 4 times. This is to prevent tps drops. This number is kind of a sweet spot in an enclosed cube of reflective alloy blocks. If you set it to a higher value, it will reflect a lot more beams but will drop your tps if you cannot handleBeam it.", defaultValue = 2) public static int DISCO_BALL_BEAM_BOUNCE_LIMIT; @ConfigPropertyInt(modid = Constants.MOD_ID, category = "general", id = "beam_bounce_limit", comment = "The amount of times a beam is allowed to bounce or reflect MAXIMUM. If this number is decreased, beams will stop after reflecting or bouncing for that amount of times. This is mainly a safety check against trapped infinitely bouncing beams.", defaultValue = 50) public static int BEAM_BOUNCE_LIMIT; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "general", id = "player_beam_reflect_strength_division", comment = "When a player wearing full reflective alloy armor stands infront of a beam, it will reflect the beam but divide it's strength by this amount.", defaultValue = 1.4) public static double PLAYER_BEAM_REFLECT_STRENGTH_DIVSION; @ConfigPropertyBoolean(modid = Constants.MOD_ID, category = "guns", id = "disable_photon_cannon", comment = "Setting this to true will completely remove the gun item from the game", defaultValue = false) public static boolean DISABLE_PHOTON_CANNON; @ConfigPropertyBoolean(modid = Constants.MOD_ID, category = "laser_rendering", id = "enable_additive_blending", comment = "If disabled, will make beams opaque and not blend visually.", defaultValue = true) public static boolean ADDITIVE_BLENDING; @ConfigPropertyBoolean(modid = Constants.MOD_ID, category = "laser_rendering", id = "use_flat_beam_texture", comment = "If enabled, will use a completely flat texture for beams. It's a nice minimalistic style.", defaultValue = false) public static boolean USE_FLAT_BEAM_TEXTURE; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "index_of_refraction", id = "air_ior", comment = "IOR of air", defaultValue = 1) public static double AIR_IOR; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "index_of_refraction", id = "glass_ior", comment = "IOR of glass", defaultValue = 1.2) public static double GLASS_IOR; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "index_of_refraction", id = "red_ior", comment = "IOR of red", defaultValue = 0.6) public static double RED_IOR; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "index_of_refraction", id = "green_ior", comment = "IOR of green", defaultValue = 0.4) public static double GREEN_IOR; @ConfigPropertyDouble(modid = Constants.MOD_ID, category = "index_of_refraction", id = "blue_ior", comment = "IOR of blue", defaultValue = 0.2) public static double BLUE_IOR; }
package net.openhft.chronicle.map; import net.openhft.chronicle.core.Jvm; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; public class AutoResizeTest { @BeforeClass public static void setup() { Jvm.setExceptionHandlers(null, null, null); } @AfterClass public static void reset() { Jvm.resetExceptionHandlers(); } /** * test that the auto resizes are not zero upon a restart * * @throws IOException IOException */ @Test public void testAutoResizeNotZeroUponRestart() throws IOException { File cmap = File.createTempFile("chron", "cmap"); try (ChronicleMap<String, String> map = ChronicleMapBuilder .of(String.class, String.class) .averageKeySize(10).averageValueSize(10) .entries(100).actualSegments(10).maxBloatFactor(10).replication((byte) 1) .createOrRecoverPersistedTo(cmap)) { int actual = map.remainingAutoResizes(); Assert.assertNotEquals(0.0, actual); } // if the file already exists it will reuse the existing settings, set above try (ChronicleMap<String, String> map = ChronicleMapBuilder .of(String.class, String.class) .createOrRecoverPersistedTo(cmap)) { int actual = map.remainingAutoResizes(); Assert.assertNotEquals(0.0, actual); } } @Test public void testAutoResizeNotZeroUponRestart2() { try (ChronicleMap<String, String> map = ChronicleMapBuilder .of(String.class, String.class) .averageKeySize(10).averageValueSize(10) .entries(100).actualSegments(10).maxBloatFactor(10).replication((byte) 1) .create()) { int actual = map.remainingAutoResizes(); Assert.assertNotEquals(0.0, actual); } } }
package org.pentaho.di.trans.steps.tableoutput; import java.sql.BatchUpdateException; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.exception.KettleDatabaseBatchException; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Writes rows to a database table. * * @author Matt Casters * @since 6-apr-2003 */ public class TableOutput extends BaseStep implements StepInterface { private static Class<?> PKG = TableOutputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private TableOutputMeta meta; private TableOutputData data; public TableOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; Object[] r=getRow(); // this also waits for a previous step to be finished. if (r==null) // no more input to be expected... { return false; } if (first) { first=false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); if ( ! meta.specifyFields() ) { // Just take the input row data.insertRowMeta = getInputRowMeta().clone(); } else { data.insertRowMeta = new RowMeta(); // Cache the position of the compare fields in Row row data.valuenrs = new int[meta.getFieldDatabase().length]; for (int i=0;i<meta.getFieldDatabase().length;i++) { data.valuenrs[i]=getInputRowMeta().indexOfValue(meta.getFieldStream()[i]); if (data.valuenrs[i]<0) { throw new KettleStepException(BaseMessages.getString(PKG, "TableOutput.Exception.FieldRequired",meta.getFieldStream()[i])); //$NON-NLS-1$ } } for (int i=0;i<meta.getFieldDatabase().length;i++) { ValueMetaInterface insValue = getInputRowMeta().searchValueMeta( meta.getFieldStream()[i]); if ( insValue != null ) { ValueMetaInterface insertValue = insValue.clone(); insertValue.setName(meta.getFieldDatabase()[i]); data.insertRowMeta.addValueMeta( insertValue ); } else { throw new KettleStepException(BaseMessages.getString(PKG, "TableOutput.Exception.FailedToFindField", meta.getFieldStream()[i])); //$NON-NLS-1$ } } } } try { Object[] outputRowData = writeToTable(getInputRowMeta(), r); if (outputRowData!=null) { putRow(data.outputRowMeta, outputRowData); // in case we want it go further... incrementLinesOutput(); } if (checkFeedback(getLinesRead())) { if(log.isBasic()) logBasic("linenr "+getLinesRead()); //$NON-NLS-1$ } } catch(KettleException e) { logError("Because of an error, this step can't continue: ", e); setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } return true; } private Object[] writeToTable(RowMetaInterface rowMeta, Object[] r) throws KettleException { if (r==null) // Stop: last line or error encountered { if (log.isDetailed()) logDetailed("Last line inserted: stop"); return null; } PreparedStatement insertStatement = null; Object[] insertRowData; Object[] outputRowData = r; String tableName = null; boolean sendToErrorRow=false; String errorMessage = null; boolean rowIsSafe = false; int[] updateCounts = null; List<Exception> exceptionsList = null; boolean batchProblem = false; Object generatedKey = null; if ( meta.isTableNameInField() ) { // Cache the position of the table name field if (data.indexOfTableNameField<0) { String realTablename=environmentSubstitute(meta.getTableNameField()); data.indexOfTableNameField = rowMeta.indexOfValue(realTablename); if (data.indexOfTableNameField<0) { String message = "Unable to find table name field ["+realTablename+"] in input row"; logError(message); throw new KettleStepException(message); } if (!meta.isTableNameInTable() && !meta.specifyFields()) { data.insertRowMeta.removeValueMeta(data.indexOfTableNameField); } } tableName = rowMeta.getString(r, data.indexOfTableNameField); if ( !meta.isTableNameInTable() && !meta.specifyFields() ) { // If the name of the table should not be inserted itself, remove the table name // from the input row data as well. This forcibly creates a copy of r insertRowData = RowDataUtil.removeItem(rowMeta.cloneRow(r), data.indexOfTableNameField); } else { insertRowData = r; } } else if ( meta.isPartitioningEnabled() && ( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) && ( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 ) ) { // Initialize some stuff! if (data.indexOfPartitioningField<0) { data.indexOfPartitioningField = rowMeta.indexOfValue(environmentSubstitute(meta.getPartitioningField())); if (data.indexOfPartitioningField<0) { throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!"); } if (meta.isPartitioningDaily()) { data.dateFormater = new SimpleDateFormat("yyyyMMdd"); } else { data.dateFormater = new SimpleDateFormat("yyyyMM"); } } ValueMetaInterface partitioningValue = rowMeta.getValueMeta(data.indexOfPartitioningField); if (!partitioningValue.isDate() || r[data.indexOfPartitioningField]==null) { throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!"); } Object partitioningValueData = rowMeta.getDate(r, data.indexOfPartitioningField); tableName=environmentSubstitute(meta.getTablename())+"_"+data.dateFormater.format((Date)partitioningValueData); insertRowData = r; } else { tableName = data.tableName; insertRowData = r; } if ( meta.specifyFields() ) { // The values to insert are those in the fields sections insertRowData = new Object[data.valuenrs.length]; for (int idx=0;idx<data.valuenrs.length;idx++) { insertRowData[idx] = r[ data.valuenrs[idx] ]; } } if (Const.isEmpty(tableName)) { throw new KettleStepException("The tablename is not defined (empty)"); } insertStatement = (PreparedStatement) data.preparedStatements.get(tableName); if (insertStatement==null) { String sql = data.db.getInsertStatement( environmentSubstitute(meta.getSchemaName()), tableName, data.insertRowMeta); if (log.isDetailed()) logDetailed("Prepared statement : "+sql); insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys()); data.preparedStatements.put(tableName, insertStatement); } try { // For PG & GP, we add a savepoint before the row. // Then revert to the savepoint afterwards... (not a transaction, so hopefully still fast) if (data.specialErrorHandling) { data.savepoint = data.db.setSavepoint(); } data.db.setValues(data.insertRowMeta, insertRowData, insertStatement); data.db.insertRow(insertStatement, data.batchMode, false); //false: no commit, it is handled in this step different if (log.isRowLevel()) { logRowlevel("Written row: "+data.insertRowMeta.getString(insertRowData)); } // Get a commit counter per prepared statement to keep track of separate tables, etc. Integer commitCounter = data.commitCounterMap.get(tableName); if (commitCounter==null) { commitCounter=Integer.valueOf(1); } else { commitCounter++; } data.commitCounterMap.put(tableName, Integer.valueOf(commitCounter.intValue())); // Release the savepoint if needed if (data.specialErrorHandling) { if (data.releaseSavepoint) { data.db.releaseSavepoint(data.savepoint); } } // Perform a commit if needed if ((data.commitSize>0) && ((commitCounter%data.commitSize)==0)) { if (data.batchMode) { try { insertStatement.executeBatch(); data.db.commit(); insertStatement.clearBatch(); } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); // 'seed' the loop with the root exception SQLException nextException = ex; do { exceptions.add(nextException); // while current exception has next exception, add to list } while ((nextException = nextException.getNextException())!=null); kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { throw new KettleDatabaseException("Error inserting row", ex); } catch(Exception ex) { throw new KettleDatabaseException("Unexpected error inserting row", ex); } } else { // insertRow normal commit data.db.commit(); } // Clear the batch/commit counter... data.commitCounterMap.put(tableName, Integer.valueOf(0)); rowIsSafe=true; } else { rowIsSafe=false; } // See if we need to get back the keys as well... if (meta.isReturningGeneratedKeys()) { RowMetaAndData extraKeys = data.db.getGeneratedKeys(insertStatement); if ( extraKeys.getRowMeta().size()>0 ) { // Send out the good word! // Only 1 key at the moment. (should be enough for now :-) generatedKey = extraKeys.getRowMeta().getInteger(extraKeys.getData(), 0); } else { // we have to throw something here, else we don't know what the // type is of the returned key(s) and we would violate our own rule // that a hop should always contain rows of the same type. throw new KettleStepException("No generated keys while \"return generated keys\" is active!"); } } } catch(KettleDatabaseBatchException be) { errorMessage = be.toString(); batchProblem = true; sendToErrorRow = true; updateCounts = be.getUpdateCounts(); exceptionsList = be.getExceptionsList(); if (getStepMeta().isDoingErrorHandling()) { data.db.clearBatch(insertStatement); data.db.commit(true); } else { data.db.clearBatch(insertStatement); data.db.rollback(); StringBuffer msg = new StringBuffer("Error batch inserting rows into table ["+tableName+"]."); msg.append(Const.CR); msg.append("Errors encountered (first 10):").append(Const.CR); for (int x = 0 ; x < be.getExceptionsList().size() && x < 10 ; x++) { Exception exception = be.getExceptionsList().get(x); if (exception.getMessage()!=null) msg.append(exception.getMessage()).append(Const.CR); } throw new KettleException(msg.toString(), be); } } catch(KettleDatabaseException dbe) { if (getStepMeta().isDoingErrorHandling()) { if (log.isRowLevel()) { logRowlevel("Written row to error handling : "+getInputRowMeta().getString(r)); } if (data.specialErrorHandling) { data.db.rollback(data.savepoint); if (data.releaseSavepoint) { data.db.releaseSavepoint(data.savepoint); } // data.db.commit(true); // force a commit on the connection too. } sendToErrorRow = true; errorMessage = dbe.toString(); } else { if (meta.ignoreErrors()) { if (data.warnings<20) { if(log.isBasic()) logBasic("WARNING: Couldn't insert row into table: "+rowMeta.getString(r)+Const.CR+dbe.getMessage()); } else if (data.warnings==20) { if(log.isBasic()) logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+rowMeta.getString(r)+Const.CR+dbe.getMessage()); } data.warnings++; } else { setErrors(getErrors()+1); data.db.rollback(); throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+rowMeta.getString(r), dbe); } } } // We need to add a key if (generatedKey!=null) { outputRowData = RowDataUtil.addValueData(outputRowData, rowMeta.size(), generatedKey); } if (data.batchMode) { if (sendToErrorRow) { if (batchProblem) { data.batchBuffer.add(outputRowData); outputRowData = null; processBatchException(errorMessage, updateCounts, exceptionsList); } else { // Simply add this row to the error row putError(rowMeta, r, 1L, errorMessage, null, "TOP001"); outputRowData=null; } } else { data.batchBuffer.add(outputRowData); outputRowData=null; if (rowIsSafe) // A commit was done and the rows are all safe (no error) { for (int i=0;i<data.batchBuffer.size();i++) { Object[] row = (Object[]) data.batchBuffer.get(i); putRow(data.outputRowMeta, row); incrementLinesOutput(); } // Clear the buffer data.batchBuffer.clear(); } } } else { if (sendToErrorRow) { putError(rowMeta, r, 1, errorMessage, null, "TOP001"); outputRowData=null; } } return outputRowData; } private void processBatchException(String errorMessage, int[] updateCounts, List<Exception> exceptionsList) throws KettleException { // There was an error with the commit // We should put all the failing rows out there... if (updateCounts!=null) { int errNr = 0; for (int i=0;i<updateCounts.length;i++) { Object[] row = (Object[]) data.batchBuffer.get(i); if (updateCounts[i]>0) { // send the error foward putRow(data.outputRowMeta, row); incrementLinesOutput(); } else { String exMessage = errorMessage; if (errNr<exceptionsList.size()) { SQLException se = (SQLException) exceptionsList.get(errNr); errNr++; exMessage = se.toString(); } putError(data.outputRowMeta, row, 1L, exMessage, null, "TOP0002"); } } } else { // If we don't have update counts, it probably means the DB doesn't support it. // In this case we don't have a choice but to consider all inserted rows to be error rows. for (int i=0;i<data.batchBuffer.size();i++) { Object[] row = (Object[]) data.batchBuffer.get(i); putError(data.outputRowMeta, row, 1L, errorMessage, null, "TOP0003"); } } // Clear the buffer afterwards... data.batchBuffer.clear(); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; if (super.init(smi, sdi)) { try { data.databaseMeta = meta.getDatabaseMeta(); // get the boolean that indicates whether or not we can release savepoints // and set in in data. data.releaseSavepoint = data.databaseMeta.getDatabaseInterface().releaseSavepoint(); data.commitSize = Integer.parseInt(environmentSubstitute(meta.getCommitSize())); data.batchMode = data.commitSize>0 && meta.useBatchUpdate(); // Batch updates are not supported on PostgreSQL (and look-a-likes) together with error handling (PDI-366) data.specialErrorHandling = getStepMeta().isDoingErrorHandling() && meta.getDatabaseMeta().supportsErrorHandlingOnBatchUpdates(); // Batch updates are not supported in case we are running with transactions in the transformation. // It is also disabled when we return keys... data.specialErrorHandling |= meta.isReturningGeneratedKeys() || getTransMeta().isUsingUniqueConnections(); if (data.batchMode && data.specialErrorHandling ) { data.batchMode = false; if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "TableOutput.Log.BatchModeDisabled")); } if (meta.getDatabaseMeta()==null) { throw new KettleException(BaseMessages.getString(PKG, "TableOutput.Exception.DatabaseNeedsToBeSelected")); } data.db=new Database(this, meta.getDatabaseMeta()); data.db.shareVariablesWith(this); if (getTransMeta().isUsingUniqueConnections()) { synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); } } else { data.db.connect(getPartitionID()); } if(log.isBasic()) logBasic("Connected to database ["+meta.getDatabaseMeta()+"] (commit="+data.commitSize+")"); // Postpone commit as long as possible. PDI-2091 if (data.commitSize==0) { data.commitSize = Integer.MAX_VALUE; } data.db.setCommit(data.commitSize); if (!meta.isPartitioningEnabled() && !meta.isTableNameInField()) { data.tableName = environmentSubstitute(meta.getTablename()); // Only the first one truncates in a non-partitioned step copy if (meta.truncateTable() && ( ( getCopy()==0 && getUniqueStepNrAcrossSlaves()==0 ) || !Const.isEmpty(getPartitionID())) ) { data.db.truncateTable(environmentSubstitute(meta.getSchemaName()), environmentSubstitute(meta.getTablename())); } } return true; } catch(KettleException e) { logError("An error occurred intialising this step: "+e.getMessage()); stopAll(); setErrors(1); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; try { for (String schemaTable : data.preparedStatements.keySet()) { // Get a commit counter per prepared statement to keep track of separate tables, etc. Integer batchCounter = data.commitCounterMap.get(schemaTable); if (batchCounter==null) { batchCounter = 0; } PreparedStatement insertStatement = data.preparedStatements.get(schemaTable); data.db.emptyAndCommit(insertStatement, data.batchMode, batchCounter); } for (int i=0;i<data.batchBuffer.size();i++) { Object[] row = (Object[]) data.batchBuffer.get(i); putRow(data.outputRowMeta, row); incrementLinesOutput(); } // Clear the buffer data.batchBuffer.clear(); } catch(KettleDatabaseBatchException be) { if (getStepMeta().isDoingErrorHandling()) { // Right at the back we are experiencing a batch commit problem... // OK, we have the numbers... try { processBatchException(be.toString(), be.getUpdateCounts(), be.getExceptionsList()); } catch(KettleException e) { logError("Unexpected error processing batch error", e); setErrors(1); stopAll(); } } else { logError("Unexpected batch update error committing the database connection.", be); setErrors(1); stopAll(); } } catch(Exception dbe) { logError("Unexpected error committing the database connection.", dbe); logError(Const.getStackTracker(dbe)); setErrors(1); stopAll(); } finally { setOutputDone(); if (getErrors()>0) { try { if (data.db!=null) data.db.rollback(); } catch(KettleDatabaseException e) { logError("Unexpected error rolling back the database connection.", e); } } if (data.db!=null) { data.db.disconnect(); } super.dispose(smi, sdi); } } }
package com.testdroid.jenkins.utils; import com.testdroid.api.APIClient; import com.testdroid.api.DefaultAPIClient; import com.testdroid.api.APIKeyClient; import com.testdroid.jenkins.TestdroidCloudSettings; import com.testdroid.jenkins.remotesupport.MachineIndependentTask; import hudson.Extension; import jenkins.model.Jenkins; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHost; @Extension public class TestdroidApiUtil { private ApiClientAdapter apiClientAdapter; public static TestdroidApiUtil getInstance() { return Jenkins.get().getExtensionList(TestdroidApiUtil.class).stream().findFirst().get(); } public static ApiClientAdapter getGlobalApiClient() { if (getInstance().apiClientAdapter == null) { createGlobalApiClient(new TestdroidCloudSettings.DescriptorImpl()); } return getInstance().apiClientAdapter; } public static ApiClientAdapter createGlobalApiClient(TestdroidCloudSettings.DescriptorImpl settings) { getInstance().apiClientAdapter = getInstance().createApiClientHelper(settings); return getInstance().apiClientAdapter; } public static ApiClientAdapter createApiClient(TestdroidCloudSettings.DescriptorImpl settings) { return getInstance().createApiClientHelper(settings); } public static ApiClientAdapter createNewApiClient(MachineIndependentTask machineIndependentTask) { APIClient apiClient; if (StringUtils.isNotEmpty(machineIndependentTask.password)) { // If the password is set, try username and password authentication if (machineIndependentTask.isProxy) { HttpHost proxy = machineIndependentTask.proxyPort != null ? new HttpHost(machineIndependentTask.proxyHost, machineIndependentTask.proxyPort, "http") : new HttpHost(machineIndependentTask.proxyHost); apiClient = StringUtils.isBlank(machineIndependentTask.proxyUser) ? new DefaultAPIClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, machineIndependentTask.password, proxy, machineIndependentTask.noCheckCertificate) : new DefaultAPIClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, machineIndependentTask.password, proxy, machineIndependentTask.proxyUser, machineIndependentTask.proxyPassword, machineIndependentTask.noCheckCertificate); } else { apiClient = new DefaultAPIClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, machineIndependentTask.password, machineIndependentTask.noCheckCertificate); } } else { // Try the username as an apikey if (machineIndependentTask.isProxy) { HttpHost proxy = machineIndependentTask.proxyPort != null ? new HttpHost(machineIndependentTask.proxyHost, machineIndependentTask.proxyPort, "http") : new HttpHost(machineIndependentTask.proxyHost); apiClient = StringUtils.isBlank(machineIndependentTask.proxyUser) ? new APIKeyClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, proxy, machineIndependentTask.noCheckCertificate) : new APIKeyClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, proxy, machineIndependentTask.proxyUser, machineIndependentTask.proxyPassword, machineIndependentTask.noCheckCertificate); } else { apiClient = new APIKeyClient(machineIndependentTask.cloudUrl, machineIndependentTask.user, machineIndependentTask.noCheckCertificate); } } return new ApiClientAdapter(apiClient); } private ApiClientAdapter createApiClientHelper(TestdroidCloudSettings.DescriptorImpl settings) { String cloudURL = settings.getCloudUrl(); String email = settings.getEmail(); String password = settings.getPassword(); boolean dontCheckCert = settings.getNoCheckCertificate(); APIClient apiClient; if (StringUtils.isNotEmpty(password)) { // If the password is set, try username and password authentication if (settings.getIsProxy()) { HttpHost proxy = settings.getProxyPort() != null ? new HttpHost(settings.getProxyHost(), settings.getProxyPort(), "http") : new HttpHost(settings.getProxyHost()); apiClient = StringUtils.isBlank(settings.getProxyUser()) ? new DefaultAPIClient(cloudURL, email, password, proxy, dontCheckCert) : new DefaultAPIClient(cloudURL, email, password, proxy, settings.getProxyUser(), settings.getProxyPassword(), dontCheckCert); } else { apiClient = new DefaultAPIClient(cloudURL, email, password, dontCheckCert); } } else { // Try the username as an apikey if (settings.getIsProxy()) { HttpHost proxy = settings.getProxyPort() != null ? new HttpHost(settings.getProxyHost(), settings.getProxyPort(), "http") : new HttpHost(settings.getProxyHost()); apiClient = StringUtils.isBlank(settings.getProxyUser()) ? new APIKeyClient(cloudURL, email, dontCheckCert) : new APIKeyClient(cloudURL, email, proxy, settings.getProxyUser(), settings.getProxyPassword(), dontCheckCert); } else { apiClient = new APIKeyClient(cloudURL, email, dontCheckCert); } } return new ApiClientAdapter(apiClient); } }
package org.animotron.statement.operator; import junit.framework.Assert; import org.animotron.ATest; import org.animotron.expression.Expression; import org.animotron.expression.JExpression; import org.junit.Test; import org.neo4j.graphdb.Relationship; import static org.animotron.expression.JExpression._; import static org.animotron.graph.Properties.UUID; import static org.animotron.graph.RelationshipTypes.REV; import static org.neo4j.graphdb.Direction.OUTGOING; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class TheTest extends ATest { @Test public void testTHE() throws Exception { JExpression A = new JExpression( _(THE._, "A", _(THE._, "B", _(THE._, "C"))) ); assertAnimoResult(A, "the A the B the C."); assertAnimo(A, "the A the B the C."); } @Test public void testREV() throws Exception { Expression e; e = testAnimo("the e 1."); String uuid1 = (String) UUID.get(e); e = testAnimo("the e 2."); String uuid2 = (String) UUID.get(e); Relationship rev1 = e.getEndNode().getSingleRelationship(REV, OUTGOING); Assert.assertNotNull(rev1); Assert.assertEquals("", UUID.get(rev1), uuid1); e = testAnimo("the e 3."); String uuid3 = (String) UUID.get(e); Relationship rev2 = e.getEndNode().getSingleRelationship(REV, OUTGOING).getEndNode().getSingleRelationship(REV, OUTGOING); Assert.assertNotNull(rev2); Assert.assertEquals("", UUID.get(rev2), uuid1); Assert.assertFalse(uuid1.equals(uuid2)); Assert.assertFalse(uuid2.equals(uuid3)); } @Test public void testREV_01() throws Exception { Expression e; e = testAnimo("the e name (lang-en \"name\") (lang-ru \" \")."); System.out.println(UUID.get(e)); e = testAnimo("the e name (lang-en \"corrected name\") (lang-ru \" \")."); System.out.println(UUID.get(e)); } }
package org.plantuml.idea.action; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.fileChooser.FileSaverDescriptor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWrapper; import org.jetbrains.annotations.NotNull; import org.plantuml.idea.plantuml.PlantUml; import org.plantuml.idea.util.UIUtils; import java.io.File; import java.io.IOException; /** * @author Eugene Steinberg */ public abstract class AbstractSaveDiagramAction extends DumbAwareAction { public static final String[] extensions; public static VirtualFile homeDir = null; private static VirtualFile lastDir = null; public static final String FILENAME = "diagram"; Logger logger = Logger.getInstance(SaveDiagramToFileAction.class); static { PlantUml.ImageFormat[] values = PlantUml.ImageFormat.values(); extensions = new String[values.length]; for (int i = 0; i < values.length; i++) { extensions[i] = values[i].toString().toLowerCase(); } homeDir = LocalFileSystem.getInstance().findFileByPath(System.getProperty("user.home")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { FileSaverDescriptor fsd = new FileSaverDescriptor("Save diagram", "Please choose where to save diagram", extensions); VirtualFile baseDir = lastDir; if (baseDir == null) { if (e.getProject() == null) { baseDir = homeDir; } else { baseDir = e.getProject().getBaseDir(); } } String defaultFileName = getDefaultFileName(e.getProject()); final VirtualFileWrapper wrapper = FileChooserFactory.getInstance().createSaveFileDialog( fsd, e.getProject()).save(baseDir, defaultFileName); if (wrapper != null) { try { VirtualFile virtualFile = wrapper.getVirtualFile(true); if (virtualFile != null) { lastDir = virtualFile.getParent(); logger.info("lastDir set to " + lastDir); } File file = wrapper.getFile(); String[] tokens = file.getAbsolutePath().split("\\.(?=[^\\.]+$)"); String base = tokens[0]; String extension = tokens.length < 2 ? "" : tokens[1]; PlantUml.ImageFormat imageFormat; try { imageFormat = PlantUml.ImageFormat.valueOf(extension.toUpperCase()); } catch (Exception ex) { throw new IOException("Extension '" + extension + "' is not supported"); } String selectedSource = getSource(e.getProject()); String fileNameTemplate = base + "-%03d." + extension; PlantUml.renderAndSave(selectedSource, UIUtils.getSelectedDir(e.getProject()), imageFormat, file.getAbsolutePath(), fileNameTemplate); } catch (IOException e1) { String title = "Error writing diagram"; String message = title + " to file:" + wrapper.getFile() + " : " + e1.toString(); logger.warn(message); Messages.showErrorDialog(message, title); } } } protected abstract String getSource(Project project); private String getDefaultFileName(Project myProject) { VirtualFile selectedFile = UIUtils.getSelectedFile(myProject); return selectedFile == null ? FILENAME : selectedFile.getNameWithoutExtension(); } }
package com.opentable.jvm; import java.util.function.Function; import org.junit.Assert; import org.junit.Test; public class MemoryTest { /** * @see NmtTest */ @Test public void formatNmt() { Assert.assertNotNull(Memory.formatNmt()); } // Not parallel-safe. @Test public void dumpHeapTmpDirDefault() { final String propName = "java.io.tmpdir"; final String old = System.clearProperty(propName); if (old == null) { throw new AssertionError("we were going to be the one to kill this"); } Assert.assertEquals(Memory.getTmpDir().toString(), Memory.DEFAULT_TMP_PATH); System.setProperty(propName, old); } // Not parallel-safe. Probably not worth it to do DI. @Test public void getHeapDumpDirMesos() { final String testValue = "/bing/bing/bam/bam"; final Function<String, String> old = Memory.getenv; Memory.getenv = name -> { if (name.equals("MESOS_SANDBOX")) { return testValue; } throw new AssertionError("unexpected environment inspection"); }; Assert.assertEquals(Memory.getHeapDumpDir().toString(), testValue); Memory.getenv = old; } @Test public void formatBytes1() { Assert.assertEquals(Memory.formatBytes(1024), "1.00 KiB"); } @Test public void formatBytes2() { Assert.assertEquals(Memory.formatBytes(20), "20 B"); } @Test public void formatBytes3() { Assert.assertEquals(Memory.formatBytes(3 * 1024 * 1024), "3.00 MiB"); } }
package com.textbasedrpgmaker.core.scenario; import java.util.Scanner; import com.textbasedrpgmaker.core.item.Inventory; import com.textbasedrpgmaker.core.item.Item; public abstract class Location implements ScenarioState { private Item item; private ScenarioState nextStep; public Location(){ } public Location(Item item){ this.item = item; } @Override public abstract void showDescription(); @Override public abstract ScenarioState northLocation(); @Override public abstract ScenarioState southLocation(); @Override public abstract ScenarioState eastLocation(); @Override public abstract ScenarioState westLocation(); @Override public void behavior(){ showDescription(); showItem(); showOptions(); } @Override public void move(ScenarioState state){ if (state.isLocked() && !Inventory.getItens().contains(state.unlockingItem())){ System.out.println("O caminho está bloqueado!"); nextStep = this; } else { System.out.println("Indo para outro cenário!"); nextStep = state; } } @Override public ScenarioState getNextStep() { return nextStep; } private boolean hasItem() { if(Inventory.getItens().contains(this.item)) return true; else return false; } @Override public ScenarioState getItem() { if(!hasItem()){ Inventory.addItemToInventory(this.item); System.out.println("O item " + this.item.getName() + " foi adicionado ao inventário"); } else { this.item = null; } return this; } @Override public void showItem() { if(item != null && !hasItem()) System.out.println(item.getDescription()); } private boolean canMove(ScenarioState scenario) { if(scenario == null) { System.out.println("Não posso mover daqui"); return false; } else { move(scenario); return true; } } public abstract String optionA(); public abstract String optionB(); public abstract String optionC(); public abstract String optionD(); public abstract String optionItem(); private void showMenu() { System.out.println("Escolha alguma opção: "); System.out.println("a) " + optionA()); System.out.println("b) " + optionB()); System.out.println("c) " + optionC()); System.out.println("d) " + optionD()); if(this.item != null && !hasItem()) System.out.println("e) " + optionItem()); } @Override public void showOptions() { boolean exit; @SuppressWarnings("resource") Scanner keyboard = new Scanner(System.in); String choice = "null"; do { exit = true; showMenu(); // System.out.println("a) Ir para o norte."); // System.out.println("b) Ir para o sul."); // System.out.println("c) Ir para o oeste."); // System.out.println("d) Ir para o leste."); // System.out.println("e) Pegar item."); choice = keyboard.nextLine(); switch(choice) { case "a": exit = canMove(northLocation()); break; case "b": exit = canMove(southLocation()); break; case "c": exit = canMove(westLocation()); break; case "d": exit = canMove(eastLocation()); break; case "e": exit = false; if (this.item != null && !hasItem()) this.getItem(); else System.out.println("Não há nada para pegar"); break; default: System.out.println("Escolha uma opção válida"); exit = false; break; } } while(!exit); } @Override public Item unlockingItem() { return null; } @Override public boolean isLocked() { return false; } }
package org.basex.test.performance; import static org.junit.Assert.*; import java.util.Arrays; import java.util.List; import java.util.Random; import org.basex.core.Context; import org.basex.core.Prop; import org.basex.core.cmd.CreateDB; import org.basex.core.cmd.DropDB; import org.basex.core.cmd.Set; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.util.Util; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public final class IncUpdateTest { /** * Test parameters. * @return parameters */ @Parameters public static List<Object[]> params() { return Arrays.asList(new Object[][] { {false}, {true} }); } /** Test database name. */ private static final String DB = Util.name(IncUpdateTest.class); /** Database context. */ protected static final Context CONTEXT = new Context(); /** Number of steps. */ private static final int STEPS = 10; /** Maximum number of entries. */ private static final int MAX = 2000 / STEPS; /** Incremental index update flag. */ private final boolean ixupdate; /** * Constructor. * @param u incremental index update flag. */ public IncUpdateTest(final boolean u) { ixupdate = u; } /** * Initializes the test. * @throws Exception exception */ @Before public void init() throws Exception { new Set(Prop.UPDINDEX, ixupdate).execute(CONTEXT); new CreateDB(DB, "<xml/>").execute(CONTEXT); new Set(Prop.AUTOFLUSH, false).execute(CONTEXT); } /** * Finishes the test. * @throws Exception exception */ @After public void finish() throws Exception { new DropDB(DB).execute(CONTEXT); } /** * Incremental test. * @throws Exception exception */ @Test public void insertInto() throws Exception { for(int a = 0; a < STEPS; a++) { final int n = MAX * a; for(int i = 0; i < n; i++) { /** * Incremental test. * @throws Exception exception */ @Test public void insertBefore() throws Exception { for(int a = 0; a < STEPS; a++) { final int n = MAX * a; for(int i = 0; i < n; i++) { /** * Incremental test. * @throws Exception exception */ @Test public void insertAfter() throws Exception { for(int a = 0; a < STEPS; a++) { final int n = MAX * a; for(int i = 0; i < n; i++) { /** * Incremental test. * @throws Exception exception */ @Test public void insertDeep() throws Exception { for(int a = 0; a < STEPS; a++) { final int n = MAX * a; for(int i = 0; i < n; i++) { /** * Incremental test. * @throws Exception exception */ @Test public void replaceValue() throws Exception { final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(); for(int i = 0; i < MAX * STEPS; i++) { sb.append((char) ('@' + (rnd.nextInt() & 0x1F))); /** * Runs the specified query. * @param query query string * @return result * @throws QueryException database exception */ protected static String query(final String query) throws QueryException { final QueryProcessor qp = new QueryProcessor(query, CONTEXT); try { return qp.execute().toString().replaceAll("(\\r|\\n) *", ""); } finally { try { qp.close(); } catch(final QueryException ex) { } } } /** * Checks if a query yields the specified string. * @param query query to be run * @param result query result * @throws QueryException database exception */ protected static void query(final String query, final Object result) throws QueryException { assertEquals(result.toString(), query(query)); } }
package com.opentok.test; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.opentok.Archive; import com.opentok.Archive.OutputMode; import com.opentok.ArchiveLayout; import com.opentok.ArchiveList; import com.opentok.ArchiveMode; import com.opentok.ArchiveProperties; import com.opentok.MediaMode; import com.opentok.OpenTok; import com.opentok.Role; import com.opentok.Session; import com.opentok.SessionProperties; import com.opentok.SignalProperties; import com.opentok.Sip; import com.opentok.SipProperties; import com.opentok.Stream; import com.opentok.StreamList; import com.opentok.TokenOptions; import com.opentok.exception.InvalidArgumentException; import com.opentok.exception.OpenTokException; import com.opentok.exception.RequestException; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class OpenTokTest { private final String SESSION_CREATE = "/session/create"; private int apiKey = 123456; private String archivePath = "/v2/project/" + apiKey + "/archive"; private String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; private String apiUrl = "http://localhost:8080"; private OpenTok sdk; @Rule public WireMockRule wireMockRule = new WireMockRule(8080); @Before public void setUp() throws OpenTokException { // read system properties for integration testing int anApiKey = 0; boolean useMockKey = false; String anApiKeyProp = System.getProperty("apiKey"); String anApiSecret = System.getProperty("apiSecret"); try { anApiKey = Integer.parseInt(anApiKeyProp); } catch (NumberFormatException e) { useMockKey = true; } if (!useMockKey && anApiSecret != null && !anApiSecret.isEmpty()) { // TODO: figure out when to turn mocking off based on this apiKey = anApiKey; apiSecret = anApiSecret; archivePath = "/v2/project/" + apiKey + "/archive"; } sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(apiUrl).build(); } @Test public void testSignalAllConnections() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptySessionID() throws OpenTokException { String sessionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); } } @Test public void testSignalWithEmoji() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; Boolean exceptionThrown = false; SignalProperties properties = new SignalProperties.Builder().type("test").data("\uD83D\uDE01").build(); try { sdk.signal(sessionId, properties); } catch (RequestException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } @Test public void testSignalSingleConnection() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, connectionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptyConnectionID() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithConnectionIDAndEmptySessionID() throws OpenTokException { String sessionId = ""; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithEmptySessionAndConnectionID() throws OpenTokException { String sessionId = ""; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(ArchiveMode.MANUAL, session.getProperties().archiveMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) .withRequestBody(matching(".*p2p.preference=enabled.*")) .withRequestBody(matching(".*archiveMode=manual.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateRoutedSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .mediaMode(MediaMode.ROUTED) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // NOTE: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*p2p.preference=disabled.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateLocationHintSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .location(locationHint) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(locationHint, session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*location="+locationHint+".*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateAlwaysArchivedSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .archiveMode(ArchiveMode.ALWAYS) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(ArchiveMode.ALWAYS, session.getProperties().archiveMode()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*archiveMode=always.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test(expected = InvalidArgumentException.class) public void testCreateBadSession() throws OpenTokException { SessionProperties properties = new SessionProperties.Builder() .location("NOT A VALID IP") .build(); } // This is not part of the API because it would introduce a backwards incompatible change. // @Test(expected = InvalidArgumentException.class) // public void testCreateInvalidAlwaysArchivedAndRelayedSession() throws OpenTokException { // SessionProperties properties = new SessionProperties.Builder() // .mediaMode(MediaMode.RELAYED) // .archiveMode(ArchiveMode.ALWAYS) // .build(); // TODO: test session creation conditions that result in errors @Test public void testTokenDefault() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = opentok.generateToken(sessionId); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals(Integer.toString(apiKey), tokenData.get("partner_id")); assertNotNull(tokenData.get("create_time")); assertNotNull(tokenData.get("nonce")); } @Test public void testTokenLayoutClass() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = sdk.generateToken(sessionId, new TokenOptions.Builder() .initialLayoutClassList(Arrays.asList("full", "focus")) .build()); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals("full focus", tokenData.get("initial_layout_class_list")); } @Test public void testTokenRoles() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; Role role = Role.SUBSCRIBER; String defaultToken = opentok.generateToken(sessionId); String roleToken = sdk.generateToken(sessionId, new TokenOptions.Builder() .role(role) .build()); assertNotNull(defaultToken); assertNotNull(roleToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(roleToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals("publisher", defaultTokenData.get("role")); Map<String, String> roleTokenData = Helpers.decodeToken(roleToken); assertEquals(role.toString(), roleTokenData.get("role")); } @Test public void testTokenExpireTime() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); long now = System.currentTimeMillis() / 1000L; long inOneHour = now + (60 * 60); long inOneDay = now + (60 * 60 * 24); long inThirtyDays = now + (60 * 60 * 24 * 30); ArrayList<Exception> exceptions = new ArrayList<Exception>(); String defaultToken = opentok.generateToken(sessionId); String oneHourToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inOneHour) .build()); try { String earlyExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(now - 10) .build()); } catch (Exception exception) { exceptions.add(exception); } try { String lateExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inThirtyDays + (60 * 60 * 24) /* 31 days */) .build()); } catch (Exception exception) { exceptions.add(exception); } assertNotNull(defaultToken); assertNotNull(oneHourToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(oneHourToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals(Long.toString(inOneDay), defaultTokenData.get("expire_time")); Map<String, String> oneHourTokenData = Helpers.decodeToken(oneHourToken); assertEquals(Long.toString(inOneHour), oneHourTokenData.get("expire_time")); assertEquals(2, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testTokenConnectionData() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); // purposely contains some exotic characters String actualData = "{\"name\":\"%foo ç &\"}"; Exception tooLongException = null; String defaultToken = opentok.generateToken(sessionId); String dataBearingToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(actualData) .build()); try { String dataTooLongToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(StringUtils.repeat("x", 1001)) .build()); } catch (InvalidArgumentException e) { tooLongException = e; } assertNotNull(defaultToken); assertNotNull(dataBearingToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(dataBearingToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertNull(defaultTokenData.get("connection_data")); Map<String, String> dataBearingTokenData = Helpers.decodeToken(dataBearingToken); assertEquals(actualData, dataBearingTokenData.get("connection_data")); assertEquals(InvalidArgumentException.class, tooLongException.getClass()); } @Test public void testTokenBadSessionId() throws OpenTokException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); ArrayList<Exception> exceptions = new ArrayList<Exception>(); try { String nullSessionToken = opentok.generateToken(null); } catch (Exception e) { exceptions.add(e); } try { String emptySessionToken = opentok.generateToken(""); } catch (Exception e) { exceptions.add(e); } try { String invalidSessionToken = opentok.generateToken("NOT A VALID SESSION ID"); } catch (Exception e) { exceptions.add(e); } assertEquals(3, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } /* TODO: find a way to match JSON without caring about spacing .withRequestBody(matching("."+".")) in the following archive tests */ @Test public void testGetArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F" + archiveId + "%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Si" + "gnature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(apiKey, archive.getPartnerId()); assertEquals(archiveId, archive.getId()); assertEquals(1395187836000L, archive.getCreatedAt()); assertEquals(62, archive.getDuration()); assertEquals("", archive.getName()); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(8347554, archive.getSize()); assertEquals(Archive.Status.AVAILABLE, archive.getStatus()); assertEquals("http://tokbox.com.archive2.s3.amazonaws.com/123456%2F"+archiveId +"%2Farchive.mp4?Expires=13951" + "94362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", archive.getUrl()); verify(getRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test get archive failure scenarios @Test public void testListArchives() throws OpenTokException { stubFor(get(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionIdOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1&sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId, 1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionId() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithEmptySessionID() throws OpenTokException { int exceptionCount = 0; int testCount = 2; try { ArchiveList archives = sdk.listArchives(""); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session Id cannot be null or empty"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(null); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session Id cannot be null or empty"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testListArchivesWithWrongOffsetCountValues() throws OpenTokException { int exceptionCount = 0; int testCount = 4; try { ArchiveList archives = sdk.listArchives(-2,0); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(0,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,12); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testStartArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().name(null).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartArchiveWithResolution() throws OpenTokException { String sessionId = "SESSIONID"; ArchiveProperties properties = new ArchiveProperties.Builder().resolution("1280x720").build(); stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"resolution\" : \"1280x720\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertEquals(archive.getResolution(),"1280x720"); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartArchiveWithResolutionInIndividualMode() throws OpenTokException { String sessionId = "SESSIONID"; ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).resolution("1280x720").build(); try { sdk.startArchive(sessionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"The resolution cannot be specified for individual output mode."); } } @Test public void testSetArchiveLayoutVertical() throws OpenTokException { String archiveId = "ARCHIVEID"; ArchiveProperties properties = new ArchiveProperties.Builder().layout(new ArchiveLayout(ArchiveLayout.Type.VERTICAL)).build(); String url = "/v2/project/" + this.apiKey + "/archive/" + archiveId + "/layout"; stubFor(put(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json"))); sdk.setArchiveLayout(archiveId, properties); verify(putRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(putRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testSetArchiveLayoutCustom() throws OpenTokException { String archiveId = "ARCHIVEID"; ArchiveProperties properties = new ArchiveProperties.Builder().layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }")).build(); String url = "/v2/project/" + this.apiKey + "/archive/" + archiveId + "/layout"; stubFor(put(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json"))); sdk.setArchiveLayout(archiveId, properties); verify(putRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(putRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testSetArchiveLayoutCustomWithNoStyleSheet() throws OpenTokException { boolean exception = false; String archiveId = "ARCHIVEID"; ArchiveProperties properties = new ArchiveProperties.Builder().layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM)).build(); String url = "/v2/project/" + this.apiKey + "/archive/" + archiveId + "/layout"; try { sdk.setArchiveLayout(archiveId, properties); } catch (RequestException e) { exception = true; } assertTrue (exception); } @Test public void testSetArchiveLayoutNonCustomWithStyleSheet() throws OpenTokException { boolean exception = false; String archiveId = "ARCHIVEID"; ArchiveProperties properties = new ArchiveProperties.Builder().layout(new ArchiveLayout(ArchiveLayout.Type.BESTFIT, "stream { position: absolute; }")).build(); String url = "/v2/project/" + this.apiKey + "/archive/" + archiveId + "/layout"; try { sdk.setArchiveLayout(archiveId, properties); } catch (RequestException e) { exception = true; } assertTrue (exception); } @Test public void testSetArchiveLayoutWithNoProperties() throws OpenTokException { boolean exception = false; String archiveId = "ARCHIVEID"; String url = "/v2/project/" + this.apiKey + "/archive/" + archiveId + "/layout"; try { sdk.setArchiveLayout(archiveId, null); } catch (InvalidArgumentException e) { exception = true; } assertTrue (exception); } @Test public void testStartArchiveWithName() throws OpenTokException { String sessionId = "SESSIONID"; String name = "archive_name"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"archive_name\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.startArchive(sessionId, name); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertEquals(name, archive.getName()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartVoiceOnlyArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"hasVideo\" : false,\n" + " \"hasAudio\" : true\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().hasVideo(false).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchiveWithLayout() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }")) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartIndividualArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"individual\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.INDIVIDUAL, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } // TODO: test start archive with name // TODO: test start archive failure scenarios @Test public void testStopArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(post(urlEqualTo(archivePath + "/" + archiveId + "/stop")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 0,\n" + " \"id\" : \"ARCHIVEID\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"stopped\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.stopArchive(archiveId); assertNotNull(archive); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(archiveId, archive.getId()); verify(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))))); Helpers.verifyUserAgent(); } // TODO: test stop archive failure scenarios @Test public void testDeleteArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(delete(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.deleteArchive(archiveId); verify(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test delete archive failure scenarios // NOTE: this test is pretty sloppy @Test public void testGetExpiredArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.EXPIRED, archive.getStatus()); } // NOTE: this test is pretty sloppy @Test public void testGetPausedArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"paused\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.PAUSED, archive.getStatus()); } @Test public void testGetArchiveWithUnknownProperties() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null,\n" + " \"thisisnotaproperty\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); } @Test public void testGetStreamWithId() throws OpenTokException { String sessionID = "SESSIONID"; String streamID = "STREAMID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream/" + streamID; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"id\" : \"" + streamID + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }"))); Stream stream = sdk.getStream(sessionID, streamID); assertNotNull(stream); assertEquals(streamID, stream.getId()); assertEquals("", stream.getName()); assertEquals("camera", stream.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListStreams() throws OpenTokException { String sessionID = "SESSIONID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 2,\n" + " \"items\" : [ {\n" + " \"id\" : \"" + 1234 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }, {\n" + " \"id\" : \"" + 5678 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"screen\",\n" + " \"layoutClassList\" : [] \n" + " } ]\n" + " }"))); StreamList streams = sdk.listStreams(sessionID); assertNotNull(streams); assertEquals(2,streams.getTotalCount()); Stream stream1 = streams.get(0); Stream stream2 = streams.get(1); assertEquals("1234", stream1.getId()); assertEquals("", stream1.getName()); assertEquals("camera", stream1.getVideoType()); assertEquals("5678", stream2.getId()); assertEquals("", stream2.getName()); assertEquals("screen", stream2.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testSipDialWithEmptyNullParams() throws OpenTokException { int exceptionCaughtCount = 0; SipProperties properties = new SipProperties.Builder() .sipUri("sip:user@sip.partner.com;transport=tls") .userName("username") .password("password") .build(); try { Sip sip = sdk.sipDial("", "TOKEN", properties); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } try { Sip sip = sdk.sipDial(null, "TOKEN", properties); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } try { Sip sip = sdk.sipDial("SESSIONID", "", properties); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } try { Sip sip = sdk.sipDial("SESSIONID", null, properties); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } try { Sip sip = sdk.sipDial("SESSIONID", "TOKEN", null); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } properties = new SipProperties.Builder() .userName("username") .password("password") .build(); try { Sip sip = sdk.sipDial("SESSIONID", "TOKEN", properties); } catch (InvalidArgumentException e) { exceptionCaughtCount += 1; } assertTrue(exceptionCaughtCount == 6); } @Test public void testSipDial() throws OpenTokException { String sessionId = "SESSIONID"; String token = "TOKEN"; String url = "/v2/project/" + this.apiKey + "/dial"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"connectionId\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"streamId\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\"\n" + " }"))); Character dQuote = '"'; String headerKey = dQuote + "X-someKey" + dQuote; String headerValue = dQuote + "someValue" + dQuote; String headerJson = "{" + headerKey + ": " + headerValue + "}"; SipProperties properties = new SipProperties.Builder() .sipUri("sip:user@sip.partner.com;transport=tls") .from("from@example.com") .headersJsonStartingWithXDash(headerJson) .userName("username") .password("password") .secure(true) .build(); Sip sip = sdk.sipDial(sessionId, token, properties); assertNotNull(sip); assertNotNull(sip.getId()); assertNotNull(sip.getConnectionId()); assertNotNull(sip.getStreamId()); verify(postRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testforceDisconnect() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId ; stubFor(delete(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.forceDisconnect(sessionId,connectionId); verify(deleteRequestedFor(urlMatching(path))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException { WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig(); proxyConfig.dynamicPort(); WireMockServer proxyingService = new WireMockServer(proxyConfig); proxyingService.start(); WireMock proxyingServiceAdmin = new WireMock(proxyingService.port()); String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port(); proxyingServiceAdmin.register(any(urlMatching(".*")).atPriority(10) .willReturn(aResponse() .proxiedFrom(targetServiceBaseUrl))); String sessionId = "SESSIONID"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port())); sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(targetServiceBaseUrl).proxy(proxy).build(); stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); verify(postRequestedFor(urlMatching(SESSION_CREATE))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } }
package com.timepath.launcher.ui.swing; import com.timepath.launcher.DownloadManager.DownloadMonitor; import com.timepath.launcher.Launcher; import com.timepath.maven.Package; import com.timepath.launcher.Program; import com.timepath.launcher.Repository; import com.timepath.launcher.util.IOUtils; import com.timepath.launcher.util.JARUtils; import com.timepath.launcher.util.SwingUtils; import com.timepath.launcher.util.Utils; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; @SuppressWarnings("serial") public class LauncherFrame extends JFrame { private static final Logger LOG = Logger.getLogger(LauncherFrame.class.getName()); protected JPanel aboutPanel; private Launcher launcher; private RepositoryManagerImpl repositoryManager; private DownloadPanel downloadPanel; private JButton launchButton; private JScrollPane newsScroll; private JTree programList; private JSplitPane programSplit; public LauncherFrame(Launcher l) { launcher = l; launcher.getDownloadManager().addListener(new DownloadMonitor() { @Override public void submit(Package pkg) { downloadPanel.getTableModel().add(pkg); } @Override public void update(Package pkg) { downloadPanel.getTableModel().update(pkg); } }); repositoryManager = new RepositoryManagerImpl(); initComponents(); updateList(); // set frame properties setJMenuBar(new JMenuBar() {{ add(new JMenu() {{ setText("Tools"); add(new JMenuItem(new AbstractAction("Repository management") { @Override public void actionPerformed(final ActionEvent e) { JOptionPane.showMessageDialog(LauncherFrame.this, repositoryManager, "Repository manager", JOptionPane.PLAIN_MESSAGE); } })); add(new JMenuItem(new AbstractAction("Preferences") { @Override public void actionPerformed(final ActionEvent e) { JOptionPane.showMessageDialog(LauncherFrame.this, new ThemeSelector(), "Select theme", JOptionPane.PLAIN_MESSAGE); } })); }}); add(new JMenu() {{ setText("Help"); add(new JMenuItem(new AbstractAction("About") { @Override public void actionPerformed(final ActionEvent e) { JOptionPane.showMessageDialog(LauncherFrame.this, aboutPanel); } })); }}); }}); setTitle("TimePath's program hub"); setBounds(0, 0, 700, 500); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); Point mid = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint(); setSize(new Dimension(mid.x, mid.y)); setLocationRelativeTo(null); LOG.log(Level.INFO, "Created UI at {0}ms", System.currentTimeMillis() - Utils.START_TIME); } private void updateList() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); new SwingWorker<List<Repository>, Void>() { @Override protected List<Repository> doInBackground() throws Exception { return launcher.getRepositories(); } @Override protected void done() { try { LOG.log(Level.INFO, "Listing at {0}ms", System.currentTimeMillis() - Utils.START_TIME); List<Repository> repos = get(); // update the repository manager int i = repositoryManager.model.getRowCount(); while(i > 0) { repositoryManager.model.removeRow(--i); } for(Repository repo : repos) { repositoryManager.model.addRow(new Object[] { repo }); } // update the program list DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); for(Repository repo : repos) { DefaultMutableTreeNode repoNode = rootNode; // create a new pseudo root node if there are multiple repositories if(repos.size() > 1) { repoNode = new DefaultMutableTreeNode(repo.getName()); rootNode.add(repoNode); } for(Program p : repo.getExecutions()) { repoNode.add(new DefaultMutableTreeNode(p)); } } programList.setModel(new DefaultTreeModel(rootNode)); // hack to pack the SplitPane PropertyChangeListener pcl = new PropertyChangeListener() { /** * Flag to ignore the first event */ boolean ignore = true; @Override public void propertyChange(PropertyChangeEvent evt) { if(ignore) { ignore = false; return; } programSplit.removePropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, this); programSplit.setDividerLocation(Math.max((int) evt.getNewValue(), programList.getPreferredScrollableViewportSize().width)); } }; programSplit.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, pcl); programSplit.setDividerLocation(-1); // show update notification if(!Utils.DEBUG && launcher.updateRequired()) { JOptionPane.showMessageDialog(LauncherFrame.this, "Please update", "A new version is available", JOptionPane.INFORMATION_MESSAGE, null); } } catch(InterruptedException | ExecutionException ex) { LOG.log(Level.SEVERE, null, ex); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }.execute(); } private void initComponents() { aboutPanel = new JPanel(new BorderLayout()) {{ add(initAboutPanel(), BorderLayout.CENTER); }}; setContentPane(new JTabbedPane() {{ addTab("Programs", programSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true) {{ setLeftComponent(new JScrollPane(programList = new JTree((TreeModel) null) {{ setRootVisible(false); setShowsRootHandles(true); getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { news(getSelected(getLastSelectedPathComponent())); } }); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { start(getSelected(getLastSelectedPathComponent())); } } }); MouseAdapter adapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(select(e) == -1) { return; } if(SwingUtilities.isLeftMouseButton(e) && ( e.getClickCount() >= 2 )) { Program p = getSelected(getLastSelectedPathComponent()); start(p); } } @Override public void mousePressed(MouseEvent e) { select(e); } @Override public void mouseDragged(MouseEvent e) { select(e); } private int select(MouseEvent e) { int selRow = getClosestRowForLocation(e.getX(), e.getY()); setSelectionRow(selRow); return selRow; } }; addMouseMotionListener(adapter); addMouseListener(adapter); }})); setRightComponent(new JPanel(new BorderLayout()) {{ add(newsScroll = new JScrollPane() {{ getVerticalScrollBar().setUnitIncrement(16); }}, BorderLayout.CENTER); add(launchButton = new JButton(new AbstractAction("Launch") { @Override public void actionPerformed(final ActionEvent e) { start(getSelected(programList.getLastSelectedPathComponent())); } }), BorderLayout.SOUTH); }}); }}); addTab("Downloads", downloadPanel = new DownloadPanel()); }}); } public void news(Program p) { // handle things other than programs if(p == null) { newsScroll.setViewportView(null); launchButton.setEnabled(false); } else { newsScroll.setViewportView(p.getPanel()); launchButton.setEnabled(!p.getPackage().isLocked()); } } public void start(final Program program) { // handle things other than programs if(program == null) return; setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); launchButton.setEnabled(false); new SwingWorker<Set<Package>, Void>() { @Override protected Set<Package> doInBackground() { return launcher.update(program); } @Override protected void done() { try { Set<Package> updates = get(); if(updates != null) { // ready to start Package parent = program.getPackage(); boolean run = true; if(!Utils.DEBUG && parent.isSelf()) { // alert on self update if(updates.contains(parent)) { run = false; JOptionPane.showMessageDialog(null, "Restart to apply", "Update downloaded", JOptionPane.INFORMATION_MESSAGE, null); } else { run = false; JOptionPane.showMessageDialog(null, "Launcher is up to date", "Launcher is up to date", JOptionPane.INFORMATION_MESSAGE, null); } } if(run) { launcher.start(program); } launchButton.setEnabled(true); } } catch(InterruptedException | ExecutionException e) { LOG.log(Level.SEVERE, null, e); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }.execute(); } private static Program getSelected(Object selected) { if(!( selected instanceof DefaultMutableTreeNode )) { return null; } Object obj = ( (DefaultMutableTreeNode) selected ).getUserObject(); if(!( obj instanceof Program )) { return null; } return (Program) obj; } private JEditorPane initAboutPanel() { final JEditorPane pane = new JEditorPane("text/html", "") {{ setEditable(false); setOpaque(false); setBackground(new Color(255, 255, 255, 0)); addHyperlinkListener(SwingUtils.HYPERLINK_LISTENER); }}; String buildDate = "unknown"; long time = JARUtils.CURRENT_VERSION; final DateFormat df = new SimpleDateFormat("EEE dd MMM yyyy, hh:mm:ss a z"); if(time != 0) { buildDate = df.format(new Date(time)); } String aboutText = IOUtils.loadPage(getClass().getResource("/com/timepath/launcher/swing/about.html")) .replace("${buildDate}", buildDate) .replace("${steamGroup}", "http://steamcommunity.com/gid/103582791434775526") .replace("${steamChat}", "steam://friends/joinchat/103582791434775526"); final String[] split = aboutText.split(Pattern.quote("${localtime}")); pane.setText(split[0] + "calculating..." + split[1]); df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney")); final Timer timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final String time = df.format(System.currentTimeMillis()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { int i = pane.getSelectionStart(); int j = pane.getSelectionEnd(); pane.setText(split[0] + time + split[1]); pane.select(i, j); } }); } }); addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if(( e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED ) != 0) { if(isDisplayable()) { timer.setInitialDelay(0); timer.start(); } else { timer.stop(); } } } }); return pane; } private class RepositoryManagerImpl extends RepositoryManager { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); RepositoryManagerImpl() { model.setColumnCount(1); } @Override protected void addActionPerformed(ActionEvent evt) { String in = JOptionPane.showInputDialog(LauncherFrame.this, "Enter URL"); if(in == null) { return; } Repository r = Repository.fromIndex(in); Launcher.addRepository(r); updateList(); } @Override protected void removeActionPerformed(ActionEvent evt) { for(int row : jTable1.getSelectedRows()) { Launcher.removeRepository((Repository) model.getValueAt(row, 0)); } updateList(); } } }
package org.myrobotlab.service; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.myrobotlab.logging.LoggerFactory; import org.slf4j.Logger; @Ignore public class JMonkeyEngineTest extends AbstractTest { public final static Logger log = LoggerFactory.getLogger(JMonkeyEngineTest.class); static JMonkeyEngine jme = null; static SwingGui swing = null; static final String TEST_DIR = "src/test/resources/JMonkeyEngine/"; static final String TEST_FACE_FILE_JPEG = "src/test/resources/JMonkeyEngine/multipleFaces.jpg"; static final String TEST_TRANSPARENT_FILE_PNG = "src/test/resources/JMonkeyEngine/transparent-bubble.png"; static final String TEST_INPUT_DIR = "src/test/resources/JMonkeyEngine/kinect-data"; // TODO - getClassifictions publishClassifications // TODO - getFaces publishFaces // TODO - chaos monkey filter tester @BeforeClass public static void setUpBeforeClass() throws Exception { jme = (JMonkeyEngine) Runtime.start("jme", "JMonkeyEngine"); Runtime.setLogLevel("info"); if (!isHeadless()) { swing = (SwingGui) Runtime.start("gui", "SwingGui"); } } @AfterClass public static void tearDownAfterClass() throws Exception { jme.releaseService(); if (!isHeadless()) { // Runtime.release("gui"); } } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } // FIXME - do the following test // test all frame grabber types // test all filters ! // test remote file source // test mpeg streamer @Test public final void putTextTest() throws Exception { log.info("=======JMonkeyEngineTest chaosCaptureTest======="); // check after the monkeys have pounded on it - it still works ! OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); jme.attach(cv); jme.putText("stat: 1\nstat: 2\nstat: 3", 10, 10); jme.putText("stat: 5\nstat: 6\nstat: 7", 10, 10); jme.putText("IS THIS OVERLAYED", 10, 10, "#FF0000"); jme.putText("this is new text", 10, 20); jme.putText("this is moved new text", 100, 20); jme.putText("this is moved new text - replaced", 100, 20); // jme.subscribe("cv", "publishPointCloud"); cv.addFilter("floor", "KinectPointCloud"); // absolute jme movements /** * <pre> * jme.updatePosition("i01.head.jaw", 70.0); * jme.updatePosition("i01.head.jaw", 80.0); * jme.updatePosition("i01.head.jaw", 90.0); * jme.updatePosition("i01.head.jaw", 100.0); * * jme.updatePosition("i01.head.rothead", 90.0); * jme.updatePosition("i01.head.rothead", 70.0); * jme.updatePosition("i01.head.rothead", 85.0); * jme.updatePosition("i01.head.rothead", 130.0); * // head.moveTo(90, 90); * </pre> */ VirtualServoController vsc = (VirtualServoController) Runtime.start("i01.left", "VirtualServoController"); vsc.attachSimulator(jme); vsc = (VirtualServoController) Runtime.start("i01.right", "VirtualServoController"); vsc.attachSimulator(jme); InMoov i01 = (InMoov) Runtime.create("i01", "InMoov");// has attach ... // runtime does // dynamic binding // anyway... InMoovHead head = i01.startHead("COM98"); Servo s = (Servo) Runtime.getService("i01.head.rothead"); Servo jaw = (Servo) Runtime.getService("i01.head.jaw"); // is this necessary ??? head.rest(); // <- WRONG should not have to do this .. it should be // assumed :P // FIXME - there has to be a "default" speed for virtual servos s.setVelocity(40); s.moveTo(0); // goes to 30 for rothead - because "min" <-- WRONG 0 should // be 30 .. but start position should be 90 !!! s.moveTo(180); s.moveTo(90); s.moveTo(0); for (int i = 90; i < 180; ++i) { /// head.moveTo(i, i); s.moveTo(i); sleep(100); } // jme.putText("test", 5, 5, 5); // cv.capture("../1543648225286"); // jme.startServoController("i01.left"); // GAH won't work :( // jme.startServoController("i01.right"); // Runtime.start("i01.left", "Jme3ServoController"); GAH won't work :( // Runtime.start("i01.right", "Jme3ServoController"); // jme.start(); // jme.onPointCloud(cv.getPointCloud()); } public static void main(String[] args) { try { // LoggingFactory.init("INFO"); setUpBeforeClass(); JMonkeyEngineTest test = new JMonkeyEngineTest(); test.putTextTest(); boolean quitNow = true; if (quitNow) { return; } } catch (Exception e) { log.error("main threw", e); } } }
package de.osiam.client; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.exception.ConflictException; import org.osiam.client.oauth.GrantType; import org.osiam.client.update.UpdateUser; import org.osiam.resources.scim.Address; import org.osiam.resources.scim.MultiValuedAttribute; import org.osiam.resources.scim.Name; import org.osiam.resources.scim.User; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.UUID; import static junit.framework.Assert.assertNotSame; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup("/database_seed.xml") public class UpdateUserIT extends AbstractIntegrationTestBase{ private UUID ID_EXISITNG_USER = UUID.fromString("7d33bcbe-a54c-43d8-867e-f6146164941e"); private UpdateUser UPDATE_USER; private User RETURN_USER; private User ORIGINAL_USER; private String IRRELEVANT = "Irrelevant"; @Test public void delete_multivalue_attributes(){ getOriginalUser("dma"); createUpdateUserWithMultiDeleteFields(); updateUser(); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getEmails(), "hsimpson@atom-example.com")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getEmails(), "hsimpson@atom-example.com")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getPhoneNumbers(), "0245817964")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getPhoneNumbers(), "0245817964")); // assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getEntitlements(), "right2"));TODO at the second run it will fail // assertFalse(isValuePartOfMultivalueList(RETURN_USER.getEntitlements(), "right2"));TODO at the second run it will fail //assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));TODO Gruppen werden nicht gespeicher //assertFalse(isValuePartOfMultivalueList(RETURN_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")); TODO Gruppen werden nicht gespeicher assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getIms(), "ims01")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getIms(), "ims01")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getPhotos(), "photo01.jpg")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getPhotos(), "photo01.jpg")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getRoles(), "role01")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getRoles(), "role01")); //assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getX509Certificates(), "certificate01"));//TODO at the second run it will fail //assertFalse(isValuePartOfMultivalueList(RETURN_USER.getX509Certificates(), "certificate01"));//TODO at the second run it will fail } @Test public void delete_all_multivalue_attributes(){ getOriginalUser("dama"); createUpdateUserWithMultiAllDeleteFields(); updateUser(); assertNotNull(ORIGINAL_USER.getEmails()); assertNull(RETURN_USER.getEmails()); assertNull(RETURN_USER.getAddresses()); //assertNull(RETURN_USER.getEntitlements());TODO at the second run it will fail assertNull(RETURN_USER.getGroups());//TODO da Gruppen nicht gespeichert werden sind sie immer null assertNull(RETURN_USER.getIms()); assertNull(RETURN_USER.getPhoneNumbers()); assertNull(RETURN_USER.getPhotos()); assertNull(RETURN_USER.getRoles()); assertNull(RETURN_USER.getX509Certificates()); } @Test public void delete_multivalue_attributes_which_is_not_available(){ getOriginalUser("dma"); createUpdateUserWithWrongEmail(); updateUser(); } @Test public void add_multivalue_attributes(){ getOriginalUser("ama"); createUpdateUserWithMultiAddFields(); String userString = getUpdateUser(); updateUser(); assertEquals(ORIGINAL_USER.getPhoneNumbers().size() + 1, RETURN_USER.getPhoneNumbers().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getPhoneNumbers(), "99999999991")); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getEmails(), "mac@muster.de")); getAddress(RETURN_USER.getAddresses(), "new Address"); //assertEquals(ORIGINAL_USER.getEntitlements().size() + 1, RETURN_USER.getEntitlements().size());TODO at the second run it will fail //assertTrue(isValuePartOfMultivalueList(RETURN_USER.getEntitlements(), "right3"));TODO at the second run it will fail //assertEquals(ORIGINAL_USER.getGroups().size() + 1, RETURN_USER.getGroups().size());TODO gruppen werden aktuell nicht gespeichert //assertTrue(isValuePartOfMultivalueList(RETURN_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));TODO gruppen werden aktuell nicht gespeichert assertEquals(ORIGINAL_USER.getIms().size() + 1, RETURN_USER.getIms().size()); assertEquals(ORIGINAL_USER.getPhotos().size() + 1, RETURN_USER.getPhotos().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getPhotos(), "photo03.jpg")); assertEquals(ORIGINAL_USER.getRoles().size() + 1, RETURN_USER.getRoles().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getRoles(), "role03")); //assertEquals(ORIGINAL_USER.getX509Certificates().size() + 1, RETURN_USER.getX509Certificates().size());//TODO at the second run it will fail //assertTrue(isValuePartOfMultivalueList(RETURN_USER.getX509Certificates(), "certificate03"));//TODO at the second run it will fail } @Test public void update_multivalue_attributes(){ getOriginalUser("uma"); createUpdateUserWithMultiUpdateFields(); updateUser(); //phonenumber MultiValuedAttribute multi = getSingleMultiValueAttribute(RETURN_USER.getPhoneNumbers(), "+497845/1157"); //assertFalse(multi.isPrimary());TODO primary wird beim telefon nicht gesetzt multi = getSingleMultiValueAttribute(RETURN_USER.getPhoneNumbers(), "0245817964"); //assertTrue(multi.isPrimary());TODO primary wird beim telefon nicht gesetzt //email //MultiValuedAttribute multi = getSingleMultiValueAttribute(RETURN_USER.getEmails(), "hsimpson@atom-example.com"); //multi = getSingleMultiValueAttribute(RETURN_USER.getEmails(), "hsimpson@home-example.com"); //assertTrue(multi.isPrimary()); //assertEquals("other", multi.getType()); multi = getSingleMultiValueAttribute(RETURN_USER.getIms(), "ims01"); //assertEquals("icq", multi.getType());//TODO der type wird nicht upgedatet multi = getSingleMultiValueAttribute(RETURN_USER.getPhotos(), "photo01.jpg"); //assertEquals("photo", multi.getType());//TODO der type wird nicht upgedatet //multi = getSingleMultiValueAttribute(RETURN_USER.getGroups(), "69e1a5dc-89be-4343-976c-b5541af249f4"); //TODO gruppen werden nicht angelegt //assertEquals("indirect", multi.getType()); } @Test public void update_all_single_values(){ getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); assertNotEquals(ORIGINAL_USER.getUserName(), RETURN_USER.getUserName()); assertNotEquals(ORIGINAL_USER.getNickName(), RETURN_USER.getNickName()); assertNotEquals(ORIGINAL_USER.isActive(), RETURN_USER.isActive()); assertNotEquals(ORIGINAL_USER.getDisplayName(), RETURN_USER.getDisplayName()); assertNotEquals(ORIGINAL_USER.getExternalId(), RETURN_USER.getExternalId()); assertNotEquals(ORIGINAL_USER.getLocale(), RETURN_USER.getLocale()); assertNotEquals(ORIGINAL_USER.getPreferredLanguage(), RETURN_USER.getPreferredLanguage()); assertNotEquals(ORIGINAL_USER.getProfileUrl(), RETURN_USER.getProfileUrl()); assertNotEquals(ORIGINAL_USER.getTimezone(), RETURN_USER.getTimezone()); assertNotEquals(ORIGINAL_USER.getTitle(), RETURN_USER.getTitle()); assertNotEquals(ORIGINAL_USER.getUserType(), RETURN_USER.getUserType()); assertNotEquals(ORIGINAL_USER.getName().getFamilyName(), RETURN_USER.getName().getFamilyName()); } @Test public void delete_all_single_values(){ getOriginalUser("desv"); createUpdateUserWithDeleteFields(); updateUser(); assertNull(RETURN_USER.getNickName()); assertNull(RETURN_USER.getDisplayName()); assertNull(RETURN_USER.getLocale()); assertNull(RETURN_USER.getPreferredLanguage()); assertNull(RETURN_USER.getProfileUrl()); assertNull(RETURN_USER.getTimezone()); assertNull(RETURN_USER.getTitle()); assertNull(RETURN_USER.getUserType()); assertNull(RETURN_USER.getName()); } @Test public void update_password() { getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); makeNewConnectionWithNewPassword(); } @Test public void update_attributes_doesnt_change_the_password() { getOriginalUser("uadctp"); createUpdateUserWithUpdateFieldsWithoutPassword(); updateUser(); makeNewConnection(); } @Test public void change_nickName_and_other_attributes_are_the_same(){ getOriginalUser("cnaoaats"); createUpdateUserWithJustOtherNickname(); updateUser(); assertNotEquals(ORIGINAL_USER.getNickName(), RETURN_USER.getNickName()); assertEquals(ORIGINAL_USER.isActive(), RETURN_USER.isActive()); assertEquals(ORIGINAL_USER.getDisplayName(), RETURN_USER.getDisplayName()); assertEquals(ORIGINAL_USER.getExternalId(), RETURN_USER.getExternalId()); assertEquals(ORIGINAL_USER.getLocale(), RETURN_USER.getLocale()); assertEquals(ORIGINAL_USER.getPreferredLanguage(), RETURN_USER.getPreferredLanguage()); assertEquals(ORIGINAL_USER.getProfileUrl(), RETURN_USER.getProfileUrl()); assertEquals(ORIGINAL_USER.getTimezone(), RETURN_USER.getTimezone()); assertEquals(ORIGINAL_USER.getTitle(), RETURN_USER.getTitle()); assertEquals(ORIGINAL_USER.getUserType(), RETURN_USER.getUserType()); assertEquals(ORIGINAL_USER.getName().getFamilyName(), RETURN_USER.getName().getFamilyName()); } @Test (expected = ConflictException.class) public void invalid_email_type_in_update_User_is_thrown_probaly(){ getOriginalUser("ietiuuitp"); createUpdateUserWithInvalidEmailType(); updateUser(); } private String getUpdateUser(){ ObjectMapper mapper = new ObjectMapper(); mapper.configure( SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false ); String userAsString = null; try { userAsString = mapper.writeValueAsString(UPDATE_USER.getUserToUpdate()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return userAsString; } public boolean isValuePartOfMultivalueList(List<MultiValuedAttribute> list, String value){ if(list != null){ for (MultiValuedAttribute actAttribute : list) { if(actAttribute.getValue().equals(value)){ return true; } } } return false; } public MultiValuedAttribute getSingleMultiValueAttribute(List<MultiValuedAttribute> multiValues, Object value){ if(multiValues != null){ for (MultiValuedAttribute actMultiValuedAttribute : multiValues) { if(actMultiValuedAttribute.getValue().equals(value)){ return actMultiValuedAttribute; } } } fail("The value " + value + " could not be found"); return null; //Can't be reached } public void getOriginalUser(String userName){ User.Builder userBuilder = new User.Builder(userName); MultiValuedAttribute email01 = new MultiValuedAttribute.Builder().setValue("hsimpson@atom-example.com").setType("work").setPrimary(true).build(); MultiValuedAttribute email02 = new MultiValuedAttribute.Builder().setValue("hsimpson@home-example.com").setType("work").build(); List<MultiValuedAttribute> emails = new ArrayList<>(); emails.add(email01); emails.add(email02); MultiValuedAttribute phoneNumber01 = new MultiValuedAttribute.Builder().setValue("+497845/1157").setType("work").setPrimary(true).build(); MultiValuedAttribute phoneNumber02 = new MultiValuedAttribute.Builder().setValue("0245817964").setType("home").build(); List<MultiValuedAttribute> phoneNumbers = new ArrayList<>(); phoneNumbers.add(phoneNumber01); phoneNumbers.add(phoneNumber02); Address simpleAddress01 = new Address.Builder().setCountry("de").setFormatted("formated address").setLocality("Berlin").setPostalCode("111111").build(); Address simpleAddress02 = new Address.Builder().setCountry("en").setFormatted("address formated").setLocality("New York").setPostalCode("123456").build(); List<Address> addresses = new ArrayList<>(); addresses.add(simpleAddress01); addresses .add(simpleAddress02); MultiValuedAttribute entitlement01 = new MultiValuedAttribute.Builder().setValue("right1").build(); MultiValuedAttribute entitlement02 = new MultiValuedAttribute.Builder().setValue("right2").build(); List<MultiValuedAttribute> entitlements = new ArrayList<>(); entitlements.add(entitlement01); entitlements.add(entitlement02); MultiValuedAttribute group01 = new MultiValuedAttribute.Builder().setValue("69e1a5dc-89be-4343-976c-b5541af249f4").setType("direct").build(); MultiValuedAttribute group02 = new MultiValuedAttribute.Builder().setValue("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578").build(); List<MultiValuedAttribute> groups = new ArrayList<>(); groups.add(group01); groups.add(group02); MultiValuedAttribute ims01 = new MultiValuedAttribute.Builder().setValue("ims01").setType("skype").build(); MultiValuedAttribute ims02 = new MultiValuedAttribute.Builder().setValue("ims02").build(); List<MultiValuedAttribute> ims = new ArrayList<>(); ims.add(ims01); ims.add(ims02); MultiValuedAttribute photo01 = new MultiValuedAttribute.Builder().setValue("photo01.jpg").setType("thumbnail").build(); MultiValuedAttribute photo02 = new MultiValuedAttribute.Builder().setValue("photo02.jpg").build(); List<MultiValuedAttribute> photos = new ArrayList<>(); photos.add(photo01); photos.add(photo02); MultiValuedAttribute role01 = new MultiValuedAttribute.Builder().setValue("role01").setType("some").build(); MultiValuedAttribute role02 = new MultiValuedAttribute.Builder().setValue("role02").build(); List<MultiValuedAttribute> roles = new ArrayList<>(); roles.add(role01); roles.add(role02); MultiValuedAttribute certificate01 = new MultiValuedAttribute.Builder().setValue("certificate01").setType("some").build(); MultiValuedAttribute certificate02 = new MultiValuedAttribute.Builder().setValue("certificate02").build(); List<MultiValuedAttribute> certificates = new ArrayList<>(); certificates.add(certificate01); certificates.add(certificate02); Name name = new Name.Builder().setFamilyName("familiyName").setFormatted("formatted Name").setGivenName("givenName").build(); userBuilder.setNickName("irgendwas") .setEmails(emails) .setPhoneNumbers(phoneNumbers) .setActive(false) .setDisplayName("irgendwas") .setLocale("de") .setPassword("geheim") .setPreferredLanguage("de") .setProfileUrl("irgendwas") .setTimezone("irgendwas") .setTitle("irgendwas") .setUserType("irgendwas") .setAddresses(addresses) .setGroups(groups) .setIms(ims) .setPhotos(photos) .setRoles(roles) .setName(name) //.setX509Certificates(certificates) //.setEntitlements(entitlements)TODO at the second run it will fail ; User newUser = userBuilder.build(); ORIGINAL_USER = oConnector.createUser(newUser, accessToken); ID_EXISITNG_USER = UUID.fromString(ORIGINAL_USER.getId()); } private void createUpdateUserWithUpdateFields(){ Name newName = new Name.Builder().setFamilyName("newFamilyName").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) .updateNickName(IRRELEVANT) .updateExternalId(IRRELEVANT) .updateDisplayName(IRRELEVANT) .updatePassword(IRRELEVANT) .updateLocal(IRRELEVANT) .updatePreferredLanguage(IRRELEVANT) .updateProfileUrl(IRRELEVANT) .updateTimezone(IRRELEVANT) .updateTitle(IRRELEVANT) .updateUserType(IRRELEVANT) .updateName(newName) .setActive(true).build(); } private void createUpdateUserWithUpdateFieldsWithoutPassword(){ Name newName = new Name.Builder().setFamilyName("newFamilyName").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) .updateNickName(IRRELEVANT) .updateExternalId(IRRELEVANT) .updateDisplayName(IRRELEVANT) .updateLocal(IRRELEVANT) .updatePreferredLanguage(IRRELEVANT) .updateProfileUrl(IRRELEVANT) .updateTimezone(IRRELEVANT) .updateTitle(IRRELEVANT) .updateUserType(IRRELEVANT) .updateName(newName) .setActive(true).build(); } private void createUpdateUserWithJustOtherNickname(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT)//TODO bug in Server .updateNickName(IRRELEVANT) .build(); } private void createUpdateUserWithInvalidEmailType(){ MultiValuedAttribute email = new MultiValuedAttribute.Builder().setValue("some@thing.com").setType("wrong").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT)//TODO bug in Server .addEmail(email) .build(); } private void createUpdateUserWithMultiUpdateFields(){ MultiValuedAttribute email = new MultiValuedAttribute.Builder() .setValue("hsimpson@home-example.com").setType("other").setPrimary(true).build(); MultiValuedAttribute phoneNumber = new MultiValuedAttribute.Builder().setValue("0245817964").setType("other") .setPrimary(true).build(); //Now the other should not be primary anymore MultiValuedAttribute ims = new MultiValuedAttribute.Builder().setValue("ims01").setType("icq").build(); MultiValuedAttribute photo = new MultiValuedAttribute.Builder().setValue("photo01.jpg").setType("photo").build(); MultiValuedAttribute role = new MultiValuedAttribute.Builder().setValue("role01").setType("other").build(); MultiValuedAttribute group = new MultiValuedAttribute.Builder().setValue("69e1a5dc-89be-4343-976c-b5541af249f4").setType("indirect").build(); new MultiValuedAttribute.Builder().setValue("test").setType("other").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .updateEmail(email) .updatePhoneNumber(phoneNumber) .updateIms(ims) .updateRole(role) .updateGroup(group) .build(); } private void createUpdateUserWithDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteDisplayName() .deleteNickName() .deleteLocal() .deletePreferredLanguage() .deleteProfileUrl() .deleteTimezone() .deleteTitle() .deleteUserType() .deleteName() .build(); } private void createUpdateUserWithMultiDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteEmail("hsimpson@atom-example.com") //.deleteEntitlement("right2")TODO at the second run it will fail .deleteGroup(UUID.fromString("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")) .deleteIms("ims01") .deletePhoneNumber("0245817964") .deletePhoto("photo01.jpg") .deleteRole("role01") //.deleteX509Certificate("certificate01") .build(); } private void createUpdateUserWithWrongEmail(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteEmail("test@test.com") .build(); } private void createUpdateUserWithMultiAddFields(){ MultiValuedAttribute email = new MultiValuedAttribute.Builder() .setValue("mac@muster.de").setType("home").build(); MultiValuedAttribute phonenumber = new MultiValuedAttribute.Builder() .setValue("99999999991").setType("home").build(); Address newSimpleAddress = new Address.Builder().setCountry("fr").setFormatted("new Address").setLocality("New City").setPostalCode("66666").build(); MultiValuedAttribute entitlement = new MultiValuedAttribute.Builder().setValue("right3").build(); MultiValuedAttribute ims = new MultiValuedAttribute.Builder().setValue("ims03").build(); MultiValuedAttribute photo = new MultiValuedAttribute.Builder().setValue("photo03.jpg").build(); MultiValuedAttribute role = new MultiValuedAttribute.Builder().setValue("role03").build(); MultiValuedAttribute certificate = new MultiValuedAttribute.Builder().setValue("certificate03").setType("some").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .addEmail(email) .addPhoneNumber(phonenumber) .addAddress(newSimpleAddress) //.addEntitlement(entitlement)//TODO at the second run it will fail .addGroup(UUID.fromString("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")) //TODO Gruppen werden nicht gespeichert .addIms(ims) .addPhotos(photo) .addRole(role) //.addX509Certificate(certificate)//TODO at the second run it will fail .build(); } private void createUpdateUserWithMultiAllDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteEmails() .deleteAddresses() //.deleteEntitlements()TODO at the second run it will fail .deleteGroups() .deleteIms() .deletePhoneNumbers() .deletePhotos() .deleteRoles() .deleteX509Certificates() .build(); } private void updateUser(){ RETURN_USER = oConnector.updateUser(ID_EXISITNG_USER, UPDATE_USER, accessToken); } private void makeNewConnectionWithNewPassword() { OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder(endpointAddress). setClientId(clientId). setClientSecret(clientSecret). setGrantType(GrantType.PASSWORD). setUsername(IRRELEVANT). setPassword(IRRELEVANT); oConnector = oConBuilder.build(); oConnector.retrieveAccessToken(); } private void makeNewConnection() { OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder(endpointAddress). setClientId(clientId). setClientSecret(clientSecret). setGrantType(GrantType.PASSWORD). setUsername("marissa"). setPassword("koala"); oConnector = oConBuilder.build(); oConnector.retrieveAccessToken(); } public Address getAddress(List<Address> addresses, String formated){ if(addresses != null){ for (Address actAddress : addresses) { if(actAddress.getFormatted().equals(formated)){ return actAddress; } } } fail("The address with the formated part of " + formated + " could not be found"); return null; //Can't be reached } }
package com.yahoo.sketches.quantiles; import static com.yahoo.sketches.quantiles.PreambleUtil.BIG_ENDIAN_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.SER_VER; import static com.yahoo.sketches.quantiles.Util.bufferElementCapacity; import com.yahoo.sketches.Family; import com.yahoo.sketches.memory.Memory; public abstract class QuantilesSketch { static final int MIN_BASE_BUF_SIZE = 4; //This is somewhat arbitrary /** * Returns a new builder * @return a new builder */ public static final QuantilesSketchBuilder builder() { return new QuantilesSketchBuilder(); } /** * Updates this sketch with the given double data item * @param dataItem an item from a stream of items. NaNs are ignored. */ public abstract void update(double dataItem); /** * This returns an approximation to the value of the data item * that would be preceded by the given fraction of a hypothetical sorted * version of the input stream so far. * * <p> * We note that this method has a fairly large overhead (microseconds instead of nanoseconds) * so it should not be called multiple times to get different quantiles from the same * sketch. Instead use getQuantiles(). which pays the overhead only once. * * @param fraction the specified fractional position in the hypothetical sorted stream. * If fraction = 0.0, the true minimum value of the stream is returned. * If fraction = 1.0, the true maximum value of the stream is returned. * * @return the approximation to the value at the above fraction */ public abstract double getQuantile(double fraction); /** * This is a more efficent multiple-query version of getQuantile(). * <p> * This returns an array that could have been generated by * mapping getQuantile() over the given array of fractions. * However, the computational overhead of getQuantile() is shared * amongst the multiple queries. Therefore, we strongly recommend this method * instead of multiple calls to getQuantile(). * * @param fractions given array of fractional positions in the hypothetical sorted stream. * It is recommended that these be in increasing order. * * @return array of approximations to the given fractions in the same order as given fractions array. */ public abstract double[] getQuantiles(double[] fractions); /** * Get the rank error normalized as a fraction between zero and one. * The error of this sketch is specified as a fraction of the normalized rank of the hypothetical * sorted stream of items presented to the sketch. * * <p>Suppose the sketch is presented with N values. The raw rank (0 to N-1) of an item * would be its index position in the sorted version of the input stream. If we divide the * raw rank by N, it becomes the normalized rank, which is between 0 and 1.0. * * <p>For example, choosing a K of 227 yields a normalized rank error of about 1%. * The upper bound on the median value obtained by getQuantile(0.5) would be the value in the * hypothetical ordered stream of values at the normalized rank of 0.51. * The lower bound would be the value in the hypothetical ordered stream of values at the * normalized rank of 0.49. * * <p>The error of this sketch cannot be translated into an error (relative or absolute) of the * returned quantile values. * * @return the rank error normalized as a fraction between zero and one. */ public abstract double getNormalizedRankError(); /** * Returns an approximation to the Probability Mass Function (PMF) of the input stream * given a set of splitPoints (values). * * The resulting approximations have a probabilistic guarantee that be obtained from the * getNormalizedRankError() function. * * @param splitPoints an array of <i>m</i> unique, monotonically increasing doubles * that divide the real number line into <i>m+1</i> consecutive disjoint intervals. * * @return an array of m+1 doubles each of which is an approximation * to the fraction of the input stream values that fell into one of those intervals. * The definition of an "interval" is inclusive of the left splitPoint and exclusive of the right * splitPoint. */ public abstract double[] getPMF(double[] splitPoints); /** * Returns an approximation to the Cumulative Distribution Function (CDF), which is the * cumulative analog of the PMF, of the input stream given a set of splitPoint (values). * <p> * More specifically, the value at array position j of the CDF is the * sum of the values in positions 0 through j of the PMF. * * @param splitPoints an array of <i>m</i> unique, monotonically increasing doubles * that divide the real number line into <i>m+1</i> consecutive disjoint intervals. * * @return an approximation to the CDF of the input stream given the splitPoints. */ public abstract double[] getCDF(double[] splitPoints); //Internal parameters /** * Returns the configured value of K * @return the configured value of K */ public abstract int getK(); /** * Returns the length of the input stream so far. * @return the length of the input stream so far */ public abstract long getN(); /** * Returns the min value of the stream * @return the min value of the stream */ public abstract double getMinValue(); /** * Returns the max value of the stream * @return the max value of the stream */ public abstract double getMaxValue(); /** * Returns true if this sketch is empty * @return true if this sketch is empty */ public boolean isEmpty() { return getN() == 0; } /** * Returns true if this sketch accesses its internal data using the Memory package * @return true if this sektch accesses its internal data using the Memory package */ public abstract boolean isDirect(); /** * Resets this sketch to a virgin state, but retains the original value of k. */ public abstract void reset(); /** * Serialize this sketch to a byte array form. * @return byte array of this sketch */ public abstract byte[] toByteArray(); /** * Returns summary information about this sketch. */ @Override public String toString() { return toString(true, false); } /** * Returns summary information about this sketch. Used for debugging. * @param sketchSummary if true includes sketch summary * @param dataDetail if true includes data detail * @return summary information about the sketch. */ public abstract String toString(boolean sketchSummary, boolean dataDetail); /** * Merges the given sketch into this one * @param qsSource the given source sketch */ public abstract void merge(QuantilesSketch qsSource); /** * Modifies the source sketch into the target sketch * @param qsSource The source sketch * @param qsTarget The target sketch */ public abstract void mergeInto(QuantilesSketch qsSource, QuantilesSketch qsTarget); /** * Heapify takes the sketch image in Memory and instantiates an on-heap Sketch, * The resulting sketch will not retain any link to the source Memory. * @param srcMem an image of a Sketch. * <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a> * @return a heap-based Sketch based on the given Memory */ public static QuantilesSketch heapify(Memory srcMem) { return HeapQuantilesSketch.getInstance(srcMem); } /** * Computes the number of retained entries (samples) in the sketch * @return the number of retained entries (samples) in the sketch */ public int getRetainedEntries() { int k = getK(); long n = getN(); int bbCnt = Util.computeBaseBufferCount(k, n); long bitPattern = Util.computeBitPattern(k, n); int validLevels = Long.bitCount(bitPattern); return bbCnt + validLevels*k; } public int getStorageBytes() { if (isEmpty()) return 8; return 40 + 8*Util.bufferElementCapacity(getK(), getN()); } //restricted /** * Returns the combined buffer reference * @return the commbined buffer reference */ abstract double[] getCombinedBuffer(); /** * Returns the base buffer count * @return the base buffer count */ abstract int getBaseBufferCount(); /** * Returns the bit pattern for valid log levels * @return the bit pattern for valid log levels */ abstract long getBitPattern(); /** * Checks the validity of the given value k * @param k must be greater than or equal to 2. */ static void checkK(int k) { if (k < MIN_BASE_BUF_SIZE/2) { throw new IllegalArgumentException("K must be >= "+(MIN_BASE_BUF_SIZE/2)); } } /** * Check the validity of the given serialization version * @param serVer the given serialization version */ static void checkSerVer(int serVer) { if (serVer != SER_VER) { throw new IllegalArgumentException( "Possible corruption: Invalid Serialization Version: "+serVer); } } /** * Checks the validity of the given family ID * @param familyID the given family ID */ static void checkFamilyID(int familyID) { Family family = Family.idToFamily(familyID); if (!family.equals(Family.QUANTILES)) { throw new IllegalArgumentException( "Possible corruption: Invalid Family: " + family.toString()); } } /** * Checks the validity of the memory buffer allocation and the memory capacity assuming * n and k. * @param k the given value of k * @param n the given value of n * @param memBufAlloc the memory buffer allocation * @param memCapBytes the memory capacity */ static void checkBufAllocAndCap(int k, long n, int memBufAlloc, long memCapBytes) { int computedBufAlloc = bufferElementCapacity(k, n); if (memBufAlloc != computedBufAlloc) { throw new IllegalArgumentException("Possible corruption: Invalid Buffer Allocated Count: " + memBufAlloc +" != " +computedBufAlloc); } int maxPre = Family.QUANTILES.getMaxPreLongs(); int reqBufBytes = (maxPre + memBufAlloc) << 3; if (memCapBytes < reqBufBytes) { throw new IllegalArgumentException("Possible corruption: Memory capacity too small: "+ memCapBytes + " < "+ reqBufBytes); } } /** * Checks the consistency of the flag bits and the state of preambleLong and the memory * capacity and returns the empty state. * @param preambleLongs the size of preamble in longs * @param flags the flags field * @param memCapBytes the memory capacity * @return the value of the empty state */ static boolean checkPreLongsFlagsCap(int preambleLongs, int flags, long memCapBytes) { boolean empty = (flags & EMPTY_FLAG_MASK) > 0; int minPre = Family.QUANTILES.getMinPreLongs(); int maxPre = Family.QUANTILES.getMaxPreLongs(); boolean valid = ((preambleLongs == minPre) && empty) || ((preambleLongs == maxPre) && !empty); if (!valid) { throw new IllegalArgumentException( "Possible corruption: PreambleLongs inconsistent with empty state: " +preambleLongs); } checkFlags(flags); if (!empty && (memCapBytes < (maxPre<<3))) { throw new IllegalArgumentException( "Possible corruption: Insufficient capacity for preamble: " +memCapBytes); } return empty; } /** * Checks just the flags field of the preamble * @param flags the flags field */ static void checkFlags(int flags) { int flagsMask = ORDERED_FLAG_MASK | COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK | BIG_ENDIAN_FLAG_MASK; if ((flags & flagsMask) > 0) { throw new IllegalArgumentException( "Possible corruption: Input srcMem cannot be: big-endian, compact, ordered, or read-only"); } } /** * Checks the validity of the split points. They must be unique, monotonically increasing and * not NaN. * @param splitPoints array */ static final void validateSplitPoints(double[] splitPoints) { for (int j = 0; j < splitPoints.length - 1; j++) { if (splitPoints[j] < splitPoints[j+1]) { continue; } throw new IllegalArgumentException( "SplitPoints must be unique, monotonically increasing and not NaN."); } } }
package com.yandex.money.api.net; import com.yandex.money.api.model.Scope; import com.yandex.money.api.utils.Strings; import java.util.HashSet; import java.util.Set; /** * Builds parameters for OAuth2 authorization using application's web browser. * * @author Slava Yasevich (vyasevich@yamoney.ru) */ public class OAuth2Authorization { private final ApiClient client; /** * Constructor. * * @param client API client * @see com.yandex.money.api.net.ApiClient */ public OAuth2Authorization(ApiClient client) { if (client == null) { throw new NullPointerException("hostsProvider is null"); } this.client = client; } /** * URL to open in web browser. * * @return URL */ public String getAuthorizeUrl() { return client.getHostsProvider().getSpMoney() + "/oauth/authorize"; } /** * POST parameters for URL. Client ID is set by default. * * @return authorize parameters */ public Params getAuthorizeParams() { return new Params() .setClientId(client.getClientId()); } /** * Authorize POST parameters. */ public static final class Params { private String clientId; private String responseType; private String redirectUri; private Set<Scope> scopes; private String rawScope; private String instanceName; /** * @param responseType specific response type */ public Params setResponseType(String responseType) { this.responseType = responseType; return this; } /** * @param redirectUri redirect URI */ public Params setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; return this; } /** * Scopes are added to a set so there are no two identical scopes in params. * * @param scope required scope */ public Params addScope(Scope scope) { if (scope != null) { if (scopes == null) { scopes = new HashSet<>(); } scopes.add(scope); } return this; } /** * Sets raw scopes parameter. Overrides {@link #addScope(com.yandex.money.api.model.Scope)}. * * @param rawScope {@code scope} parameter */ public Params setRawScope(String rawScope) { this.rawScope = rawScope; return this; } /** * Sets unique instance name for application. * * @param instanceName the instance name */ public Params setInstanceName(String instanceName) { this.instanceName = instanceName; return this; } /** * Build provided parameters. * * @return parameters */ public byte[] build() { PostRequestBodyBuffer buffer = new PostRequestBodyBuffer(); final String scopeName = "scope"; if (Strings.isNullOrEmpty(rawScope)) { if (scopes != null) { buffer.addParam(scopeName, Scope.createScopeParameter(scopes.iterator())); } } else { buffer.addParam(scopeName, rawScope); } return buffer .addParamIfNotNull("client_id", clientId) .addParamIfNotNull("response_type", responseType) .addParamIfNotNull("redirect_uri", redirectUri) .addParamIfNotNull("instance_name", instanceName) .toByteArray(); } private Params setClientId(String clientId) { this.clientId = clientId; return this; } } }
package org.lantern; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.apache.commons.io.IOUtils; import com.google.common.base.Charsets; public class HostSpoofingTest { public static void main(final String... args) throws Exception { final SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); sock.connect(new InetSocketAddress("github.global.ssl.fastly.net", 443), 10000); OutputStream os = null; try { os = sock.getOutputStream(); writeHttpRequest(os); readResponse(sock.getInputStream()); } finally { IOUtils.closeQuietly(os); } } private static void readResponse(InputStream inputStream) throws IOException { /* BufferedReader br = null; br = new BufferedReader(new InputStreamReader(inputStream)); String cur = br.readLine(); while (!StringUtils.isEmpty(cur)) { System.err.println(cur); cur = br.readLine(); } */ final byte[] body = new byte[1200]; inputStream.read(body); System.err.println(new String(body, "UTF-8")); } private static void writeHttpRequest(final OutputStream os) throws IOException { os.write("GET / HTTP/1.1\r\n".getBytes(Charsets.UTF_8)); os.write("Host: www.getlantem.org\r\n".getBytes(Charsets.UTF_8)); os.write("\r\n".getBytes(Charsets.UTF_8)); } }
package crazypants.enderio.capability; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nonnull; import javax.annotation.Nullable; import crazypants.util.Prep; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.items.IItemHandler; public class EnderInventory implements IItemHandler { public static enum Type { ALL, INPUT, OUTPUT, INOUT, UPGRADE, INTERNAL, } private final Map<String, InventorySlot> idents = new HashMap<String, InventorySlot>(); private final EnumMap<EnderInventory.Type, List<InventorySlot>> slots = new EnumMap<EnderInventory.Type, List<InventorySlot>>(EnderInventory.Type.class); private final View allSlots = new View(EnderInventory.Type.ALL); private @Nullable TileEntity owner = null; public static final @Nonnull IItemHandler OFF = new IItemHandler() { @Override public int getSlots() { return 0; } @Override public ItemStack getStackInSlot(int slot) { return Prep.getEmpty(); } @Override public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { return stack; } @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { return Prep.getEmpty(); } }; public EnderInventory() { for (EnderInventory.Type type : EnderInventory.Type.values()) { slots.put(type, new ArrayList<InventorySlot>()); } } public void add(EnderInventory.Type type, Enum<?> ident, InventorySlot slot) { add(type, ident.name(), slot); } public void add(EnderInventory.Type type, String ident, InventorySlot slot) { if (idents.containsKey(ident)) { throw new RuntimeException("Duplicate slot '" + ident + "'"); } if (type == EnderInventory.Type.ALL) { throw new RuntimeException("Invalid type '" + type + "'"); } idents.put(ident, slot); slots.get(type).add(slot); slots.get(EnderInventory.Type.ALL).add(slot); if (type == EnderInventory.Type.INPUT || type == EnderInventory.Type.OUTPUT) { slots.get(EnderInventory.Type.INOUT).add(slot); } if (type == EnderInventory.Type.INOUT) { slots.get(EnderInventory.Type.INPUT).add(slot); slots.get(EnderInventory.Type.OUTPUT).add(slot); } slot.setOwner(owner); } public InventorySlot getSlot(Enum<?> ident) { return getSlot(ident.name()); } public InventorySlot getSlot(String ident) { if (!idents.containsKey(ident)) { throw new RuntimeException("Unknown slot '" + ident + "'"); } return idents.get(ident); } @Nonnull public View getView(EnderInventory.Type type) { return new View(type); } public NBTTagCompound writeToNBT() { NBTTagCompound tag = new NBTTagCompound(); writeToNBT(tag); return tag; } public void writeToNBT(NBTTagCompound tag) { for (Entry<String, InventorySlot> entry : idents.entrySet()) { if (entry.getValue() != null) { NBTTagCompound subTag = new NBTTagCompound(); entry.getValue().writeToNBT(subTag); tag.setTag(entry.getKey(), subTag); } } } public void readFromNBT(NBTTagCompound tag, String name) { readFromNBT(tag.getCompoundTag(name)); } public void readFromNBT(NBTTagCompound tag) { for (Entry<String, InventorySlot> entry : idents.entrySet()) { if (entry.getValue() != null) { entry.getValue().readFromNBT(tag.getCompoundTag(entry.getKey())); } } } public void setOwner(TileEntity owner) { this.owner = owner; for (InventorySlot slot : idents.values()) { slot.setOwner(owner); } } @Override public int getSlots() { return allSlots.getSlots(); } @Override public ItemStack getStackInSlot(int slot) { return allSlots.getStackInSlot(slot); } @Override public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (Prep.isInvalid(stack)) { return Prep.getEmpty(); } return allSlots.insertItem(slot, stack, simulate); } @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { return allSlots.extractItem(slot, amount, simulate); } public class View implements IItemHandler, Iterable<InventorySlot> { private final EnderInventory.Type type; private View(Type type) { this.type = type; } public InventorySlot getSlot(int slot) { if (slot >= 0 && slot < getSlots()) { return slots.get(type).get(slot); } return null; } @Override public int getSlots() { return slots.get(type).size(); } @Override public ItemStack getStackInSlot(int slot) { if (slot >= 0 && slot < getSlots()) { InventorySlot inventorySlot = slots.get(type).get(slot); if (inventorySlot != null) { return inventorySlot.getStackInSlot(0); } } return Prep.getEmpty(); } @Override public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (Prep.isInvalid(stack)) { return Prep.getEmpty(); } if (slot >= 0 && slot < getSlots()) { InventorySlot inventorySlot = slots.get(type).get(slot); if (inventorySlot != null) { return inventorySlot.insertItem(0, stack, simulate); } } return stack; } @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { if (slot >= 0 && slot < getSlots()) { InventorySlot inventorySlot = slots.get(type).get(slot); if (inventorySlot != null) { return inventorySlot.extractItem(0, amount, simulate); } } return Prep.getEmpty(); } @Override public Iterator<InventorySlot> iterator() { return new Iterator<InventorySlot>() { int i = 0; @Override public boolean hasNext() { return i < getSlots(); } @Override public InventorySlot next() { return getSlot(i++); } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } } }
package com.xnlogic.pacer.pipes; import java.util.NoSuchElementException; import com.tinkerpop.pipes.AbstractPipe; import com.tinkerpop.pipes.util.FastNoSuchElementException; public class IsEmptyPipe<T> extends AbstractPipe<T, Boolean> { private boolean raise; public IsEmptyPipe() { super(); this.raise = false; } protected Boolean processNextStart() throws NoSuchElementException{ if (this.raise) { throw FastNoSuchElementException.instance(); } try { this.starts.next(); this.raise = true; } catch (NoSuchElementException nsee) { return true; } throw FastNoSuchElementException.instance(); } public void reset() { this.raise = false; super.reset(); } }
package de.prob2.ui.operations; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.effect.ColorAdjust; import javafx.scene.effect.Lighting; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.util.Callback; public class TransitionTransformer implements Callback<ListView<Operation>, ListCell<Operation>> { public class OperationsCell extends ListCell<Operation> { ImageView imEnabled = new ImageView( new Image(getClass().getResourceAsStream("/glyphicons_free/glyphicons/png/glyphicons-174-play.png"))); ImageView imNotEnabled = new ImageView( new Image(getClass().getResourceAsStream("/glyphicons_free/glyphicons/png/glyphicons-192-minus-sign.png"))); public OperationsCell() { Lighting lighting = new Lighting(); lighting.setSpecularConstant(1.5); lighting.setSpecularExponent(0.0); ColorAdjust green = new ColorAdjust(); green.setInput(lighting); green.setHue(0.6); green.setSaturation(1); imEnabled.setEffect(green); imEnabled.setFitWidth(13); imEnabled.setFitHeight(13); ColorAdjust red = new ColorAdjust(); red.setInput(lighting); red.setHue(0.0); red.setSaturation(1); imNotEnabled.setEffect(red); imNotEnabled.setFitWidth(13); imNotEnabled.setFitHeight(13); } @Override protected void updateItem(Operation item, boolean empty) { super.updateItem(item, empty); if(item != null &! empty) { setText(item.toString()); if(item.isEnabled()) { setGraphic(imEnabled); } else { setGraphic(imNotEnabled); } } else { setGraphic(null); setText(null); } } } @Override public ListCell<Operation> call(ListView<Operation> lv) { return new OperationsCell(); } }
package de.slackspace.openkeepass.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; import de.slackspace.openkeepass.filter.Filter; import de.slackspace.openkeepass.filter.ListFilter; /** * A KeePassFile represents the structure of a KeePass database. This is the * central entry point to read data from the KeePass database. */ @XmlRootElement(name = "KeePassFile") @XmlAccessorType(XmlAccessType.FIELD) public class KeePassFile implements KeePassFileElement { @XmlElement(name = "Meta") private Meta meta; @XmlElement(name = "Root") private Group root; @XmlTransient private ProtectedStringCrypto protectedStringCrypto; KeePassFile() { } public KeePassFile(KeePassFileBuilder builder) { this.meta = builder.meta; this.root = builder.root; } /** * Retrieves the meta section of a KeePass database. * * @return the meta section of the database * @see Meta */ public Meta getMeta() { return meta; } /** * Retrieves the root group of a KeePass database. * * @return the root group * @see Group */ public Group getRoot() { return root; } /** * Retrieves all groups at the root level of a KeePass database. * * @return a list of root level groups * @see Group */ public List<Group> getTopGroups() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getGroups(); } return new ArrayList<Group>(); } /** * Retrieves all entries at the root level of a KeePass database. * * @return a list of root level entries * @see Entry */ public List<Entry> getTopEntries() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getEntries(); } return new ArrayList<Entry>(); } /** * Retrieves a single entry with an exactly matching title. * <p> * If there are multiple entries with the same title, the first one found * will be returned. * * @param title * the title which should be searched * @return an entry with a matching title * @see Entry */ public Entry getEntryByTitle(String title) { List<Entry> entries = getEntriesByTitle(title, true); if (!entries.isEmpty()) { return entries.get(0); } return null; } /** * Retrieves a list of entries with matching titles. * <p> * If the <tt>matchExactly</tt> flag is true, only entries which have an * exactly matching title will be returned, otherwise all entries which * contain the given title will be returned. * * @param title * the title which should be searched * @param matchExactly * if true only entries which have an exactly matching title will * be returned * @return a list of entries with matching titles * @see Entry */ public List<Entry> getEntriesByTitle(final String title, final boolean matchExactly) { List<Entry> allEntries = new ArrayList<Entry>(); if (root != null) { getEntries(root, allEntries); } return ListFilter.filter(allEntries, new Filter<Entry>() { @Override public boolean matches(Entry item) { if (matchExactly) { if (item.getTitle() != null && item.getTitle().equalsIgnoreCase(title)) { return true; } } else { if (item.getTitle() != null && item.getTitle().toLowerCase().contains(title.toLowerCase())) { return true; } } return false; } }); } /** * Retrieves a list of group with matching names. * <p> * If the <tt>matchExactly</tt> flag is true, only groups which have an * exactly matching name will be returned, otherwise all groups which * contain the given name will be returned. * * @param name * the name which should be searched * @param matchExactly * if true only groups which have an exactly matching name will * be returned * @return a list of entries with matching names * @see Group */ public List<Group> getGroupsByName(final String name, final boolean matchExactly) { List<Group> allGroups = new ArrayList<Group>(); if (root != null) { getGroups(root, allGroups); } return ListFilter.filter(allGroups, new Filter<Group>() { @Override public boolean matches(Group item) { if (matchExactly) { if (item.getName() != null && item.getName().equalsIgnoreCase(name)) { return true; } } else { if (item.getName() != null && item.getName().toLowerCase().contains(name.toLowerCase())) { return true; } } return false; } }); } /** * Retrieves a list of all entries in the KeePass database. * * @return a list of all entries * @see Entry */ public List<Entry> getEntries() { List<Entry> allEntries = new ArrayList<Entry>(); if (root != null) { getEntries(root, allEntries); } return allEntries; } /** * Retrieves a list of all groups in the KeePass database. * * @return a list of all groups * @see Group */ public List<Group> getGroups() { List<Group> allGroups = new ArrayList<Group>(); if (root != null) { getGroups(root, allGroups); } return allGroups; } /** * Retrieves a single group with an exactly matching name. * <p> * If there are multiple groups with the same name, the first one found will * be returned. * * @param name * the name which should be searched * @return a group with a matching name * @see Group */ public Group getGroupByName(String name) { List<Group> groups = getGroupsByName(name, true); if (!groups.isEmpty()) { return groups.get(0); } return null; } private void getEntries(Group parentGroup, List<Entry> entries) { List<Group> groups = parentGroup.getGroups(); entries.addAll(parentGroup.getEntries()); if (!groups.isEmpty()) { for (Group group : groups) { getEntries(group, entries); } } return; } private void getGroups(Group parentGroup, List<Group> groups) { List<Group> parentGroups = parentGroup.getGroups(); groups.addAll(parentGroups); if (!parentGroups.isEmpty()) { for (Group group : parentGroups) { getGroups(group, groups); } } return; } /** * Retrieves an entry based on its UUID. * * @param UUID * the uuid which should be searched * @return the found entry or null */ public Entry getEntryByUUID(final UUID UUID) { List<Entry> allEntries = getEntries(); List<Entry> entries = ListFilter.filter(allEntries, new Filter<Entry>() { @Override public boolean matches(Entry item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (entries.size() == 1) { return entries.get(0); } else { return null; } } /** * Retrieves a group based on its UUID. * * @param UUID * the uuid which should be searched * @return the found group or null */ public Group getGroupByUUID(final UUID UUID) { List<Group> allGroups = getGroups(); List<Group> groups = ListFilter.filter(allGroups, new Filter<Group>() { @Override public boolean matches(Group item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (groups.size() == 1) { return groups.get(0); } else { return null; } } }
package eu.musesproject.server.rt2ae; import java.math.BigInteger; import java.sql.Time; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.persistence.EntityTransaction; import org.apache.log4j.Logger; import eu.musesproject.server.db.handler.DBManager; import eu.musesproject.server.entity.RiskCommunication; import eu.musesproject.server.entity.RiskPolicy; import eu.musesproject.server.entity.Users; import eu.musesproject.server.eventprocessor.correlator.model.owl.ConnectivityEvent; import eu.musesproject.server.eventprocessor.impl.EventProcessorImpl; import eu.musesproject.server.risktrust.AccessRequest; import eu.musesproject.server.risktrust.Asset; import eu.musesproject.server.risktrust.Clue; import eu.musesproject.server.risktrust.Context; import eu.musesproject.server.risktrust.Decision; import eu.musesproject.server.risktrust.Device; import eu.musesproject.server.risktrust.DeviceSecurityState; import eu.musesproject.server.risktrust.DeviceTrustValue; import eu.musesproject.server.risktrust.OpportunityDescriptor; import eu.musesproject.server.risktrust.Outcome; import eu.musesproject.server.risktrust.PolicyCompliance; import eu.musesproject.server.risktrust.Probability; import eu.musesproject.server.risktrust.RiskTreatment; import eu.musesproject.server.risktrust.Rt2ae; import eu.musesproject.server.risktrust.SecurityIncident; import eu.musesproject.server.risktrust.SolvingRiskTreatment; import eu.musesproject.server.risktrust.Threat; import eu.musesproject.server.risktrust.TrustValue; import eu.musesproject.server.risktrust.User; import eu.musesproject.server.risktrust.UserTrustValue; import eu.musesproject.server.scheduler.ModuleType; public class Rt2aeServerImpl implements Rt2ae { private final int RISK_TREATMENT_SIZE = 20; private Logger logger = Logger.getLogger(Rt2aeServerImpl.class.getName()); private static DBManager dbManager = new DBManager(ModuleType.RT2AE); private RiskPolicy riskPolicy = new RiskPolicy();//Sending e-mail with virus /*private String sendingemail = "Sending e-mail with virus\nYour system is infected with a virus and you want to\n send an attachment via e-mail.\n This may cause critical system failure and puts the\n receiver at risk. Remove the virus first."; private String saveconfidentieldocument = "Saving confidential document\n You want to save a confidential document on your device.\n If you loose your\n device, other people may be able to\n access the document."; private String antivirusnotrunning = "Your Antivirus is not running on your device\nPlease launch your Antivirus\n In order to protect your device";*/ private String opensensitivedocumentinunsecurenetwork = "Opening sensitive document in unsecure network\n You are connected to an unsecure network and try\n to open a sensitive document.\n Information sent over this network is not encrypted\n and might be visible to other people.\n Switch to a secure network."; private String privateloungewifi = "Please go to the private lounge secure Wi-Fi"; private String wifisniffing = "Wi-Fi sniffing"; private String strongdenythreat = "There is too much risk in your context situation, the probability of a threat leading to a security incident is too high "; private String malwarerisktreatment = "Your device seems to have a Malware,please scan you device with an Antivirus or use another device"; /** * DecideBasedOnRiskPolicy is a function whose aim is to compute a Decision based on RiskPolicy. * @param accessRequest the access request * @param context the context */ @Override public Decision decideBasedOnRiskPolicy(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub RiskPolicy rPolicy = new RiskPolicy(); logger.info("RT2AE computes the Decision..."); String decisionId=""; //String accessrequestId=""; String threatId=""; Decision decision = Decision.STRONG_DENY_ACCESS; if(policyCompliance.getResult().equals(policyCompliance.DENY)){ EventProcessorImpl eventProcessorImpl = new EventProcessorImpl(); List<Asset> requestedAssets = new ArrayList<Asset>(); requestedAssets.add(accessRequest.getRequestedCorporateAsset()); List<Clue> clues = new ArrayList<Clue>(); // infer clues from the access request for (Asset asset : requestedAssets) { clues = eventProcessorImpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest .getDevice().getDevicetrustvalue()); Clue userName = new Clue(); userName.setName(accessRequest.getUser().getUsername()); clues.add(userName); Clue assetName = new Clue(); assetName.setName(asset.getTitle()); logger.info("ASSET: "+asset.getTitle()); clues.add(assetName); for (Clue clue : clues) { logger.info("The clue associated with Asset " + asset.getTitle() + " is " + clue.getName() + "\n"); } } List<eu.musesproject.server.entity.Threat> currentThreats = new ArrayList<eu.musesproject.server.entity.Threat>(); String threatName = ""; // combine clues with the asset and the user to generate a single threat for (Clue clue : clues) { threatName = threatName + clue.getName(); } eu.musesproject.server.entity.Threat threat = new eu.musesproject.server.entity.Threat(); threat.setDescription("Threat" + threatName); threat.setProbability(0.5); eu.musesproject.server.entity.Outcome o = new eu.musesproject.server.entity.Outcome(); o.setDescription("Compromised Asset"); o.setCostbenefit(-requestedAssets.iterator().next().getValue()); threat.setOutcomes(new ArrayList<eu.musesproject.server.entity.Outcome>( Arrays.asList(o))); // check if the threat already exists in the database boolean exists = false; List<eu.musesproject.server.entity.Threat> dbThreats = dbManager .getThreats(); eu.musesproject.server.entity.Threat existingThreat = new eu.musesproject.server.entity.Threat(); for (eu.musesproject.server.entity.Threat threat2 : dbThreats) { if (threat2.getDescription().equalsIgnoreCase( threat.getDescription())) { exists = true; existingThreat = threat2; } } // if doesn't exist, insert a new one if (!exists) { int oC = threat.getOccurences() + 1; threat.setOccurences(oC); currentThreats.add(threat); try { threatId = dbManager.setThreat(threat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The newly created Threat from the Clues is: " + threat.getDescription() + " with probability " + threat.getProbability() + " for the following outcome: \"" + threat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + threat.getOutcomes().iterator().next().getCostbenefit() + "\n"); // if already exists, update occurrences and update it in the // database } else { int oC = existingThreat.getOccurences() + 1; existingThreat.setOccurences(oC); currentThreats.add(existingThreat); logger.info("Occurences: " + existingThreat.getOccurences() + " - Bad Count: " + existingThreat.getBadOutcomeCount()); try { threatId = dbManager.setThreat(existingThreat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The inferred Threat from the Clues is: " + existingThreat.getDescription() + " with probability " + existingThreat.getProbability() + " for the following outcome: \"" + existingThreat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + existingThreat.getOutcomes().iterator().next().getCostbenefit() + "\n"); } decision.setInformation(policyCompliance.getInformation()); if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Disable Accessibility")){ decision.setSolving_risktreatment(SolvingRiskTreatment.ACCESSIBILITY); } if (policyCompliance.getReason().equalsIgnoreCase("Antivirus not running")){ decision.setSolving_risktreatment(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Detection open asset type confidential unsecure wifi")){ decision.setSolving_risktreatment(SolvingRiskTreatment.OPEN_CONFIDENTIAL_ASSET_UNSECURE_WIFI); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Detection open asset type internal unsecure wifi")){ decision.setSolving_risktreatment(SolvingRiskTreatment.OPEN_INTERNAL_ASSET_UNSECURE_WIFI); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Detection open asset type strictly confidential unsecure wifi")){ decision.setSolving_risktreatment(SolvingRiskTreatment.OPEN_STRICTLY_CONFIDENTIAL_ASSET_UNSECURE_WIFI); } if (policyCompliance.getReason().equalsIgnoreCase("Blacklist app 00001")){ decision.setSolving_risktreatment(SolvingRiskTreatment.BLACKLIST_APP_0001); } if (policyCompliance.getReason().equalsIgnoreCase("Blacklist app 00002")){ decision.setSolving_risktreatment(SolvingRiskTreatment.BLACKLIST_APP_0002); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Email with Attachments")){ decision.setSolving_risktreatment(SolvingRiskTreatment.EMAIL_WITH_ATTACHEMENT); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Change Security Property-password-protected")){ decision.setSolving_risktreatment(SolvingRiskTreatment.CHANGE_SECURITY_PROPERTY_PASSWORD_PROTECTED); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Change Security Property-screen-timeout")){ decision.setSolving_risktreatment(SolvingRiskTreatment.CHANGE_SECURITY_PROPERTY_SCREEN_TIMEOUT); } if (policyCompliance.getReason().equalsIgnoreCase("Required application list")){ decision.setSolving_risktreatment(SolvingRiskTreatment.REQUIRED_APPLICATION_LIST); } if (policyCompliance.getReason().equalsIgnoreCase("AccessRequest Detection Open File in a monitored folder")){ decision.setSolving_risktreatment(SolvingRiskTreatment.DETECTION_OPEN_FILE_MONITORED_FOLDER); } if (policyCompliance.getReason().equalsIgnoreCase("Rooted device")){ decision.setSolving_risktreatment(SolvingRiskTreatment.ROOTED_DEVICE); } if (policyCompliance.getReason().equalsIgnoreCase("Blacklist generic open")){ decision.setSolving_risktreatment(SolvingRiskTreatment.BLACKLIST_GENERIC_OPEN); } if (policyCompliance.getReason().equalsIgnoreCase("Unsafe Storage")){ decision.setSolving_risktreatment(SolvingRiskTreatment.UNSAFE_STORAGE); } if (policyCompliance.getReason().equalsIgnoreCase("Install not allowed application")){ decision.setSolving_risktreatment(SolvingRiskTreatment.INSTALL_NOT_ALLOWED_APPLICATION); } if (policyCompliance.getReason().equalsIgnoreCase("Zone 1 application restriction")){ decision.setSolving_risktreatment(SolvingRiskTreatment.ZONE_1_APPLICATION_RESTRICTION); } if (policyCompliance.getReason().equalsIgnoreCase("Open asset in restricted zone 1")){ decision.setSolving_risktreatment(SolvingRiskTreatment.OPEN_ASSET_IN_RESTRICTED_ZONE_1); } if (policyCompliance.getReason().equalsIgnoreCase("User entered password")){ decision.setSolving_risktreatment(SolvingRiskTreatment.USER_ENTERED_PASSWORD); } if (policyCompliance.getReason().equalsIgnoreCase("Emas Add Note")){ decision.setSolving_risktreatment(SolvingRiskTreatment.EMAS_ADD_NOTE); } ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(1));//TO DO Adding assetId from EP accessrequest1.setModification(new Date()); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setInformation(decision.getInformation()); decision1.setValue("STRONGDENY"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } else{ logger.info("RT2AE: receives ALLOW policyCompliance from EP"); if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("PUBLIC")){ EventProcessorImpl eventProcessorImpl = new EventProcessorImpl(); List<Asset> requestedAssets = new ArrayList<Asset>( Arrays.asList(accessRequest.getRequestedCorporateAsset())); List<Clue> clues = new ArrayList<Clue>(); // infer clues from the access request for (Asset asset : requestedAssets) { clues = eventProcessorImpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest .getDevice().getDevicetrustvalue()); Clue userName = new Clue(); userName.setName(accessRequest.getUser().getUsername()); clues.add(userName); Clue assetName = new Clue(); assetName.setName(asset.getTitle()); clues.add(assetName); for (Clue clue : clues) { logger.info("The clue associated with Asset " + asset.getTitle() + " is " + clue.getName() + "\n"); } } List<eu.musesproject.server.entity.Threat> currentThreats = new ArrayList<eu.musesproject.server.entity.Threat>(); String threatName = ""; // combine clues with the asset and the user to generate a single threat for (Clue clue : clues) { threatName = threatName + clue.getName(); } eu.musesproject.server.entity.Threat threat = new eu.musesproject.server.entity.Threat(); threat.setDescription("Threat" + threatName); threat.setProbability(0.5); eu.musesproject.server.entity.Outcome o = new eu.musesproject.server.entity.Outcome(); o.setDescription("Compromised Asset"); o.setCostbenefit(-requestedAssets.iterator().next().getValue()); threat.setOutcomes(new ArrayList<eu.musesproject.server.entity.Outcome>( Arrays.asList(o))); // check if the threat already exists in the database boolean exists = false; List<eu.musesproject.server.entity.Threat> dbThreats = dbManager .getThreats(); eu.musesproject.server.entity.Threat existingThreat = new eu.musesproject.server.entity.Threat(); for (eu.musesproject.server.entity.Threat threat2 : dbThreats) { if (threat2.getDescription().equalsIgnoreCase( threat.getDescription())) { exists = true; existingThreat = threat2; } } // if doesn't exist, insert a new one if (!exists) { int oC = threat.getOccurences() + 1; threat.setOccurences(oC); currentThreats.add(threat); try { threatId = dbManager.setThreat(threat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The newly created Threat from the Clues is: " + threat.getDescription() + " with probability " + threat.getProbability() + " for the following outcome: \"" + threat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + threat.getOutcomes().iterator().next().getCostbenefit() + "\n"); // if already exists, update occurrences and update it in the // database } else { int oC = existingThreat.getOccurences() + 1; existingThreat.setOccurences(oC); currentThreats.add(existingThreat); logger.info("Occurences: " + existingThreat.getOccurences() + " - Bad Count: " + existingThreat.getBadOutcomeCount()); try { threatId = dbManager.setThreat(existingThreat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The inferred Threat from the Clues is: " + existingThreat.getDescription() + " with probability " + existingThreat.getProbability() + " for the following outcome: \"" + existingThreat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + existingThreat.getOutcomes().iterator().next().getCostbenefit() + "\n"); } ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { decision = Decision.GRANTED_ACCESS; accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } riskPolicy.setRiskvalue(0.5); return decideBasedOnRiskPolicy_version_7(accessRequest, riskPolicy); } } /** * * This function is the version 7 of the decideBasedOnRiskPolicy. This * version computes the Decision based on the AccessRequest computing the * threats and their probabilities as well as accepting opportunities as * well if needed. It stores certain elements in the DB if needed. It also * compares against a risk policy. * * @param accessRequest * the access request * @return Decision * */ public Decision decideBasedOnRiskPolicy_version_7( AccessRequest accessRequest, RiskPolicy rPolicy) { // function variables and assignments double costOpportunity = 0.0; double combinedProbabilityThreats = 1.0; double combinedProbabilityOpportunities = 1.0; double singleThreatProbabibility = 0.0; double singleOpportunityProbability = 0.0; int opcount = 0; int threatcount = 0; Decision decision = Decision.STRONG_DENY_ACCESS; String decisionId=""; String threatId=""; riskPolicy = rPolicy; EventProcessorImpl eventProcessorImpl = new EventProcessorImpl(); List<Asset> requestedAssets = new ArrayList<Asset>( Arrays.asList(accessRequest.getRequestedCorporateAsset())); List<Clue> clues = new ArrayList<Clue>(); // infer clues from the access request for (Asset asset : requestedAssets) { clues = eventProcessorImpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest .getDevice().getDevicetrustvalue()); Clue userName = new Clue(); userName.setName(accessRequest.getUser().getUsername()); clues.add(userName); Clue assetName = new Clue(); assetName.setName(asset.getTitle()); clues.add(assetName); for (Clue clue : clues) { logger.info("The clue associated with Asset " + asset.getTitle() + " is " + clue.getName() + "\n"); } } List<eu.musesproject.server.entity.Threat> currentThreats = new ArrayList<eu.musesproject.server.entity.Threat>(); String threatName = ""; // combine clues with the asset and the user to generate a single threat for (Clue clue : clues) { threatName = threatName + clue.getName(); } eu.musesproject.server.entity.Threat threat = new eu.musesproject.server.entity.Threat(); threat.setDescription("Threat" + threatName); threat.setProbability(0.5); eu.musesproject.server.entity.Outcome o = new eu.musesproject.server.entity.Outcome(); o.setDescription("Compromised Asset"); o.setCostbenefit(-requestedAssets.iterator().next().getValue()); System.out.println("value of asset "+o.getCostbenefit()); threat.setOutcomes(new ArrayList<eu.musesproject.server.entity.Outcome>( Arrays.asList(o))); logger.info("Asset value: "+requestedAssets.iterator().next().getValue()); // check if the threat already exists in the database boolean exists = false; List<eu.musesproject.server.entity.Threat> dbThreats = dbManager .getThreats(); eu.musesproject.server.entity.Threat existingThreat = new eu.musesproject.server.entity.Threat(); for (eu.musesproject.server.entity.Threat threat2 : dbThreats) { if (threat2.getDescription().equalsIgnoreCase( threat.getDescription())) { exists = true; existingThreat = threat2; } } // if doesn't exist, insert a new one if (!exists) { int oC = threat.getOccurences() + 1; threat.setOccurences(oC); currentThreats.add(threat); try { threatId = dbManager.setThreat(threat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The newly created Threat from the Clues is: " + threat.getDescription() + " with probability " + threat.getProbability() + " for the following outcome: \"" + threat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + threat.getOutcomes().iterator().next().getCostbenefit() + "\n"); // if already exists, update occurrences and update it in the // database } else { int oC = existingThreat.getOccurences() + 1; existingThreat.setOccurences(oC); currentThreats.add(existingThreat); logger.info("Occurences: " + existingThreat.getOccurences() + " - Bad Count: " + existingThreat.getBadOutcomeCount()); try { dbManager.setThreat(existingThreat); threatId = existingThreat.getThreatId(); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The inferred Threat from the Clues is: " + existingThreat.getDescription() + " with probability " + existingThreat.getProbability() + " for the following outcome: \"" + "\n"); } OpportunityDescriptor opportunityDescriptor = accessRequest .getOpportunityDescriptor(); if (opportunityDescriptor != null) { for (Iterator<Outcome> iterator = opportunityDescriptor.getOutcomes().iterator(); iterator.hasNext();) { Outcome outcome = iterator.next(); costOpportunity = costOpportunity + outcome.getCostBenefit(); logger.info("Cost: "+outcome.getCostBenefit()); logger.info("Total: "+costOpportunity); } opportunityDescriptor.computeOpportunityOutcomeProbability(accessRequest.getUser()); System.out .println("There is an oportunity descriptor associated with this action: \"" + opportunityDescriptor.getDescription() + "\" with the following possible outcome: " + " which can yield the following benefit (in kEUR): " + costOpportunity + "\n"); combinedProbabilityOpportunities = combinedProbabilityOpportunities * opportunityDescriptor.getProbability(); singleOpportunityProbability = singleOpportunityProbability + opportunityDescriptor.getProbability(); opcount++; } // infer some probabilities from the threats and opportunities (if // present) for (eu.musesproject.server.entity.Threat t : currentThreats) { if(t.getOutcomes().size()!=0){ costOpportunity = costOpportunity + t.getOutcomes().iterator().next() .getCostbenefit(); if (t.getOutcomes().iterator().next().getCostbenefit() < 0) { combinedProbabilityThreats = combinedProbabilityThreats * t.getProbability(); singleThreatProbabibility = singleThreatProbabibility + t.getProbability(); threatcount++; } }else{ combinedProbabilityThreats = combinedProbabilityThreats * t.getProbability(); singleThreatProbabibility = singleThreatProbabibility + t.getProbability(); threatcount++; } } if (threatcount > 1) singleThreatProbabibility = singleThreatProbabibility - combinedProbabilityThreats; if (opcount > 1) singleOpportunityProbability = singleOpportunityProbability - combinedProbabilityOpportunities; // log some useful info logger.info("Decission data is: "); logger.info("- Risk Policy threshold: " + riskPolicy.getRiskvalue()); logger.info("- Cost Oportunity: " + costOpportunity); logger.info("- Combined Probability of the all possible Threats happening together: " + combinedProbabilityThreats); //logger.info("- Combined Probability of the all the possible Opportunities happening together: " // + combinedProbabilityOpportunities); logger.info("- Combined Probability of only one of the possible Threats happening: " + singleThreatProbabibility); //logger.info("- Combined Probability of only one of the possible Opportunities happening: " // + singleOpportunityProbability); logger.info("Making a decision..."); logger.info("."); logger.info(".."); logger.info("..."); // compute the decision based on the risk policy, the threat // probabilities, the user trust level and the cost benefit Double trustvalue = (accessRequest .getUser().getUsertrustvalue().getValue()+accessRequest.getDevice().getDevicetrustvalue().getValue())/2; if (riskPolicy.getRiskvalue() == 0.0) { return Decision.GRANTED_ACCESS; } if (riskPolicy.getRiskvalue() == 1.0) { return Decision.STRONG_DENY_ACCESS; } System.out.println("trust value: "+trustvalue); System.out.println("value: "+(combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2); System.out.println("Asset value : "+accessRequest.getRequestedCorporateAsset().getValue()); if(((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 >= riskPolicy .getRiskvalue()) && ((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 < 0.6) ){ if (clues.get(0).getName().contains("NOT-AVAILABLE-CLUES") && accessRequest.getOpportunityDescriptor() == null ){ logger.info("Without OPPORTUNITY DESCRIPTOR"); eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(SolvingRiskTreatment.OPPORTUNITY); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:You may use an Opportunity in your situation. If oyur Oppportunity is higher that the risk of lossing the value of the asset, you will have access to the asset. Please your Opportunity"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Opportunity with no clues"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(1); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Antivirus is not running")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(4); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your Antivirus is not running on your device,please launch your Antivirus in order to protect your device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("UnsecureWifi:Encryption without WPA2 protocol might be unsecure") && (accessRequest.getOpportunityDescriptor() == null) && accessRequest.getRequestedCorporateAsset().getValue()>5000){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.setSolving_risktreatment(2); decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS: You are connected to an unsecure network, please connect to a secure network"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Unsecure network"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().equalsIgnoreCase("Attempt to save a file in a monitored folder") && accessRequest.getRequestedCorporateAsset().getValue()<5000 ) { eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ logger.info("RISKTREATMENTS:"+dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ logger.info("RISKTREATMENTS:"+dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getSpanish()); riskTreatments[0] = riskTreatment; } decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(1)); logger.info("Asset Id:"+accessRequest.getRequestedCorporateAsset().getId()); logger.info("Event Id:"+accessRequest.getEventId()); logger.info("ThreatId:"+threatId); logger.info("UserId:"+accessRequest.getUser().getUserId()); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Saving file"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); logger.info("DecisionId: "+decisionId); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.updateAccessRequest:"+e.getMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (costOpportunity > 0){ logger.info(" With OPPORTUNITY DESCRIPTOR "); logger.info("Cost Opportunity: "+costOpportunity); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { decision = Decision.GRANTED_ACCESS; accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } logger.info("Decision: GRANTED"); return decision; }else { logger.info("The Opportunity was not higher that the risk to lose the asset Decision: DENY"); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setModification(new Date()); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision = Decision.STRONG_DENY_ACCESS; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ decision.setInformation(dbManager.getRisktreatments(6).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ decision.setInformation(dbManager.getRisktreatments(6).getSpanish()); } decision1.setInformation(decision.getInformation()); decision1.setValue("STRONGDENY"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } logger.info("Decision: DENY"); return decision; } } else { System.out.println("trust value: "+trustvalue); System.out.println("value: "+(combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2); if ((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 < riskPolicy .getRiskvalue()) { if (clues.get(0).getName().contains("NOT-AVAILABLE-CLUES") && accessRequest.getOpportunityDescriptor() == null ){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(SolvingRiskTreatment.OPPORTUNITY); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:You may use an Opportunity in your situation. If oyur Oppportunity is higher that the risk of lossing the value of the asset, you will have access to the asset. Please your Opportunity"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Opportunity"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(1)); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Antivirus is not running")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS:Your Antivirus is not running on your device,please launch your Antivirus in order to protect your device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(1)); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Antivirus not running"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("UnsecureWifi:Encryption without WPA2 protocol might be unsecure") && accessRequest.getOpportunityDescriptor() == null){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS:You may use an Opportunity in your situation. If oyur Oppportunity is higher that the risk of lossing the value of the asset, you will have access to the asset. Please your Opportunity"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Unsecure network"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.OPPORTUNITY).getSpanish()); } risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().equalsIgnoreCase("Attempt to save a file in a monitored folder")) { eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getSpanish()); riskTreatments[0] = riskTreatment; } decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Saving file"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (costOpportunity > 0){ logger.info(" With OPPORTUNITY "); logger.info("Cost Opportunity: "+costOpportunity); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { decision = Decision.GRANTED_ACCESS; accessrequest1.setAssetId(BigInteger.valueOf(1)); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } logger.info("Decision: GRANTED"); return decision; }else { logger.info("Decision: DENY"); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(1));//TO DO Adding assetId from EP accessrequest1.setModification(new Date()); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision = Decision.STRONG_DENY_ACCESS; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ decision.setInformation(dbManager.getRisktreatments(6).getDescription()); } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ decision.setInformation(dbManager.getRisktreatments(6).getSpanish()); } decision1.setInformation(decision.getInformation()); decision1.setValue("STRONGDENY"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } logger.info("Decision: DENY"); return decision; } } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setThreatId(Integer.valueOf(threatId)); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); //Update access request with decision ID accessrequest1.setDecisionId(new BigInteger(decisionId)); dbManager.updateAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } /** * * This function is the version 6 of the decideBasedOnRiskPolicy. This * version computes the Decision based on the AccessRequest computing the * threats and their probabilities as well as accepting opportunities as * well if needed. It stores certain elements in the DB if needed. It also * compares against a risk policy. * * @param accessRequest * the access request * @return Decision * */ public Decision decideBasedOnRiskPolicy_version_6( AccessRequest accessRequest, RiskPolicy rPolicy) { // function variables and assignments double costOpportunity = 0.0; double combinedProbabilityThreats = 1.0; double combinedProbabilityOpportunities = 1.0; double singleThreatProbabibility = 0.0; double singleOpportunityProbability = 0.0; int opcount = 0; int threatcount = 0; Decision decision = Decision.STRONG_DENY_ACCESS; String decisionId=""; riskPolicy = rPolicy; EventProcessorImpl eventProcessorImpl = new EventProcessorImpl(); List<Asset> requestedAssets = new ArrayList<Asset>( Arrays.asList(accessRequest.getRequestedCorporateAsset())); List<Clue> clues = new ArrayList<Clue>(); // infer clues from the access request for (Asset asset : requestedAssets) { clues = eventProcessorImpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest .getDevice().getDevicetrustvalue()); Clue userName = new Clue(); userName.setName(accessRequest.getUser().getUsername()); clues.add(userName); Clue assetName = new Clue(); assetName.setName(asset.getTitle()); clues.add(assetName); for (Clue clue : clues) { logger.info("The clue associated with Asset " + asset.getTitle() + " is " + clue.getName() + "\n"); } } List<eu.musesproject.server.entity.Threat> currentThreats = new ArrayList<eu.musesproject.server.entity.Threat>(); String threatName = ""; // combine clues with the asset and the user to generate a single threat for (Clue clue : clues) { threatName = threatName + clue.getName(); } eu.musesproject.server.entity.Threat threat = new eu.musesproject.server.entity.Threat(); threat.setDescription("Threat" + threatName); threat.setProbability(0.5); eu.musesproject.server.entity.Outcome o = new eu.musesproject.server.entity.Outcome(); o.setDescription("Compromised Asset"); o.setCostbenefit(-requestedAssets.iterator().next().getValue()); threat.setOutcomes(new ArrayList<eu.musesproject.server.entity.Outcome>( Arrays.asList(o))); // check if the threat already exists in the database boolean exists = false; List<eu.musesproject.server.entity.Threat> dbThreats = dbManager .getThreats(); eu.musesproject.server.entity.Threat existingThreat = new eu.musesproject.server.entity.Threat(); for (eu.musesproject.server.entity.Threat threat2 : dbThreats) { if (threat2.getDescription().equalsIgnoreCase( threat.getDescription())) { exists = true; existingThreat = threat2; } } // if doesn't exist, insert a new one if (!exists) { int oC = threat.getOccurences() + 1; threat.setOccurences(oC); currentThreats.add(threat); try { dbManager.setThreat(threat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The newly created Threat from the Clues is: " + threat.getDescription() + " with probability " + threat.getProbability() + " for the following outcome: \"" + threat.getOutcomes().iterator().next().getDescription() + "\" with the following potential cost (in kEUR): " + threat.getOutcomes().iterator().next().getCostbenefit() + "\n"); // if already exists, update occurrences and update it in the // database } else { int oC = existingThreat.getOccurences() + 1; existingThreat.setOccurences(oC); currentThreats.add(existingThreat); logger.info("Occurences: " + existingThreat.getOccurences() + " - Bad Count: " + existingThreat.getBadOutcomeCount()); try { dbManager.setThreat(existingThreat); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setThreat:"+e.getLocalizedMessage()); } logger.info("The inferred Threat from the Clues is: " + existingThreat.getDescription() + " with probability " + existingThreat.getProbability() + " for the following outcome: \"" + "\n"); } // infer some probabilities from the threats and opportunities (if // present) for (eu.musesproject.server.entity.Threat t : currentThreats) { costOpportunity += t.getOutcomes().iterator().next() .getCostbenefit(); if (t.getOutcomes().iterator().next().getCostbenefit() < 0) { combinedProbabilityThreats = combinedProbabilityThreats * t.getProbability(); singleThreatProbabibility = singleThreatProbabibility + t.getProbability(); threatcount++; } else { combinedProbabilityOpportunities = combinedProbabilityOpportunities * t.getProbability(); singleOpportunityProbability = singleOpportunityProbability + t.getProbability(); opcount++; } } if (threatcount > 1) singleThreatProbabibility = singleThreatProbabibility - combinedProbabilityThreats; if (opcount > 1) singleOpportunityProbability = singleOpportunityProbability - combinedProbabilityOpportunities; // log some useful info logger.info("Decission data is: "); //logger.info("- Risk Policy threshold: " + riskPolicy.getRiskvalue()); logger.info("- Cost Oportunity: " + costOpportunity); logger.info("- Combined Probability of the all possible Threats happening together: " + combinedProbabilityThreats); //logger.info("- Combined Probability of the all the possible Opportunities happening together: " // + combinedProbabilityOpportunities); logger.info("- Combined Probability of only one of the possible Threats happening: " + singleThreatProbabibility); //logger.info("- Combined Probability of only one of the possible Opportunities happening: " // + singleOpportunityProbability); logger.info("Making a decision..."); logger.info("."); logger.info(".."); logger.info("..."); // compute the decision based on the risk policy, the threat // probabilities, the user trust level and the cost benefit Double trustvalue = (accessRequest .getUser().getUsertrustvalue().getValue()+accessRequest.getDevice().getDevicetrustvalue().getValue())/2; if(((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 > riskPolicy .getRiskvalue()) && ((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 < 0.7) ){ if (clues.get(0).getName().contains("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(1); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Antivirus is not running")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setSolving_risktreatment(4); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your Antivirus is not running on your device,please launch your Antivirus in order to protect your device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("UnsecureWifi:Encryption without WPA2 protocol might be unsecure")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.setSolving_risktreatment(2); decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS: You are connected to an unsecure network, please connect to a secure network"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("MAYBE"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Unsecure network"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().equalsIgnoreCase("Attempt to save a file in a monitored folder")) { eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getFrench()); riskTreatments[0] = riskTreatment; } decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Saving file"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } else { if ((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 <= riskPolicy .getRiskvalue()) { if (clues.get(0).getName().contains("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Virus detection"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.VIRUS_FOUND).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("Antivirus is not running")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS:Your Antivirus is not running on your device,please launch your Antivirus in order to protect your device"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Antivirus not running"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ANTIVIRUS_IS_NOT_RUNNING).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().contains("UnsecureWifi:Encryption without WPA2 protocol might be unsecure")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getFrench()); riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU"); logger.info("RISKTREATMENTS: You are connected to an unsecure network, please connect to a secure network"); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Unsecure network"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.UNSECURE_WIFI_ENCRYPTION_WITHOUT_WPA2).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } if (clues.get(0).getName().equalsIgnoreCase("Attempt to save a file in a monitored folder")) { eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("en")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("es")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getSpanish()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("de")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getGerman()); riskTreatments[0] = riskTreatment; } if(dbManager.getUserByUsername(accessRequest.getUser().getUsername()).getLanguage().equalsIgnoreCase("fr")){ RiskTreatment riskTreatment = new RiskTreatment(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getFrench()); riskTreatments[0] = riskTreatment; } decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION"); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); try { dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } decision1.setAccessRequest(accessrequest1); decision1.setValue("UPTOYOU"); decision1.setTime(new java.util.Date()); RiskCommunication riskcommunication1 = new RiskCommunication(); riskcommunication1.setDescription("Saving file"); try { dbManager.setRiskCommunications(riskcommunication1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskCommunications:"+e.getLocalizedMessage()); } List<eu.musesproject.server.entity.RiskTreatment> risktreatments1 = new ArrayList<eu.musesproject.server.entity.RiskTreatment>(); eu.musesproject.server.entity.RiskTreatment risktreatment1 = new eu.musesproject.server.entity.RiskTreatment(); risktreatment1.setDescription(dbManager.getRisktreatments(SolvingRiskTreatment.ATTEMPT_TO_SAVE_A_FILE_IN_A_MONITORED_FOLDER).getDescription()); risktreatment1.setRiskCommunication(riskcommunication1); risktreatments1.add(risktreatment1); try { dbManager.setRiskTreatments(risktreatments1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setRiskTreatments:"+e.getLocalizedMessage()); } decision1.setRiskCommunication(riskcommunication1); List<eu.musesproject.server.entity.Decision> list = new ArrayList<eu.musesproject.server.entity.Decision>(); list.add(decision1); try { decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId())); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequests(accessRequests); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisions:"+e.getLocalizedMessage()); } ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); try { dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } } if ((combinedProbabilityThreats + ((Double) 1.0-trustvalue) )/2 > 0.7) { ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { accessrequest1.setAssetId(BigInteger.valueOf(accessRequest.getRequestedCorporateAsset().getId()));//TO DO Adding assetId from EP accessrequest1.setModification(new Date()); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setThreatId(Integer.valueOf(existingThreat.getThreatId())); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision = Decision.STRONG_DENY_ACCESS; decision.setInformation(strongdenythreat); decision1.setInformation(decision.getInformation()); decision1.setValue("STRONGDENY"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } ArrayList<eu.musesproject.server.entity.Decision> listDecisions = new ArrayList<eu.musesproject.server.entity.Decision>(); eu.musesproject.server.entity.Decision decision1 = new eu.musesproject.server.entity.Decision(); eu.musesproject.server.entity.AccessRequest accessrequest1 = new eu.musesproject.server.entity.AccessRequest(); try { decision = Decision.GRANTED_ACCESS; accessrequest1.setAssetId(BigInteger.valueOf(1)); accessrequest1.setEventId(BigInteger.valueOf(accessRequest.getEventId())); accessrequest1.setAction(accessRequest.getAction()); accessrequest1.setModification(new Date()); accessrequest1.setThreatId(Integer.valueOf(existingThreat.getThreatId())); accessrequest1.setUserId(new BigInteger(accessRequest.getUser().getUserId())); ArrayList<eu.musesproject.server.entity.AccessRequest> accessRequests = new ArrayList<eu.musesproject.server.entity.AccessRequest>() ; accessRequests.add(accessrequest1); dbManager.setAccessRequest(accessrequest1); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setAccessRequests:"+e.getLocalizedMessage()); } try { decision1.setAccessRequest(accessrequest1); decision1.setValue("GRANTED"); decision1.setTime(new java.util.Date()); decisionId = dbManager.setDecision(decision1); decision.setId(decisionId); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecision:"+e.getLocalizedMessage()); } try { ArrayList<eu.musesproject.server.entity.DecisionTrustvalues> decisiontrustvalues = new ArrayList<eu.musesproject.server.entity.DecisionTrustvalues>(); eu.musesproject.server.entity.DecisionTrustvalues decisiontrustvalue = new eu.musesproject.server.entity.DecisionTrustvalues(); decisiontrustvalue.setDevicetrustvalue(accessRequest.getDevice().getDevicetrustvalue().getValue()); decisiontrustvalue.setUsertrustvalue(accessRequest.getUser().getUsertrustvalue().getValue()); decisiontrustvalue.setDecisionId(Integer.parseInt(decisionId)); decisiontrustvalues.add(decisiontrustvalue); dbManager.setDecisionTrustvalues(decisiontrustvalues); } catch (Exception e) { logger.error("Please, check database persistence:An error has produced while calling dbManager.setDecisionTrustvalues:"+e.getLocalizedMessage()); } return decision; } /** * This function is the version 1 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the AccessRequest * * @param accessRequest * @param context * @return */ @SuppressWarnings("static-access") public Decision decideBasedOnRiskPolicy_version_1(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; if (accessRequest.getRequestedCorporateAsset().getValue() <= 1000000 ) { Random r = new Random(); int valeur = 0 + r.nextInt(100 - 0); accessRequest.getUser().getUsertrustvalue().setValue(valeur); accessRequest.getDevice().getDevicetrustvalue().setValue(valeur); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; return decision; }else{ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } } else { decision = Decision.STRONG_DENY_ACCESS; return decision; } } /** * This function is the version 2 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats * * @param accessRequest * @param context * @return */ @SuppressWarnings("static-access") public Decision decideBasedOnRiskPolicy_version_2(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment1 = new RiskTreatment(malwarerisktreatment); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 3 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats and the Outcome * * @param accessRequest * @param context * @return */ @SuppressWarnings({ "unused", "static-access" }) public Decision decideBasedOnRiskPolicy_version_3(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("TThere is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 4 of the decideBasedOnRiskPolicy. This version computes the Decision based on the Context and the list of Threats and the Outcome and the trust value * * @param accessRequest * @param context * @return */ @SuppressWarnings({ "unused", "static-access" }) public Decision decideBasedOnRiskPolicy_version_4(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; Random r = new Random(); int valeur = 0 + r.nextInt(100 - 0); accessRequest.getUser().getUsertrustvalue().setValue(valeur); accessRequest.getDevice().getDevicetrustvalue().setValue(valeur); EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS;; return decision; }else{ for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.5){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()>0.5){ decision = Decision.STRONG_DENY_ACCESS; return decision; } decision = Decision.GRANTED_ACCESS;; return decision; } } } decision = Decision.GRANTED_ACCESS;; return decision; } /** * This function is the version 5 of the decideBasedOnRiskPolicy. This version computes the Decision based on the value of the Asset,the Context and the list of Threats and the Outcome and the trust value * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_version_5(AccessRequest accessRequest,Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("public")){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("internal")){ if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionInternalAsset( accessRequest, context); } } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("confidential")){ if (!threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionConfidentialAsset(accessRequest, context); } } if(accessRequest.getRequestedCorporateAsset().getConfidential_level().equalsIgnoreCase("strictlyconfidential")){ if (threats.isEmpty()){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ return computeDecisionStrictlyConfidentialAsset( accessRequest, context); } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionInternalAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<=0.5){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ logger.info("Decision: STRONG_DENY_ACCESS"); decision = Decision.STRONG_DENY_ACCESS; return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is less that 50% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; logger.info("Decision: MAYBE_ACCESS"); decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is more than 50% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<=0.5){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 50% of chances that the asset that you wan to access will lose around 33% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; logger.info("Decision: UPTOYOU_ACCESS"); decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()<0.5 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/5); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 50% of chances that the asset that you wan to access will lose 20% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()>0){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()>0){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionConfidentialAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you want to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.7 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.7){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 0.5% of chances that the asset that you wan to access will lose 0.5% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<0.3){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()<0.2){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()<0.3 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/5); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.3){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 20% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.7 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.7){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 30% of chances that the asset that you wan to access will lose 20% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()<0.3){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType()=="Device under attack" && threats.get(i).getProbability()<0.3){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } public Decision computeDecisionStrictlyConfidentialAsset(AccessRequest accessRequest,Context context){ Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); List<Threat> threats = new ArrayList<Threat>(); //TODO Change threats by clues for (int i = 0; i < threats.size(); i++) { if(threats.get(i).getAssetId() == accessRequest.getRequestedCorporateAsset().getId()){ if(threats.get(i).getType().equalsIgnoreCase(wifisniffing) && threats.get(i).getProbability()<0.1){ Outcome requestPotentialOutcome = new Outcome(wifisniffing, -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.5 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.5){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Malware") && threats.get(i).getProbability()<0.1){ Outcome requestPotentialOutcome = new Outcome("Malware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(malwarerisktreatment); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Spyware") && threats.get(i).getProbability()>0.1){ Outcome requestPotentialOutcome = new Outcome("Spyware", -accessRequest.getRequestedCorporateAsset().getValue()/2); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Spyware,please scan you device with an Antivirus or use another device"); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } if(threats.get(i).getType().equalsIgnoreCase("Unsecure Connexion") && threats.get(i).getProbability()>0.1 ){ Outcome requestPotentialOutcome = new Outcome("Unsecure Connexion", -accessRequest.getRequestedCorporateAsset().getValue()/3); Probability probability = eventprocessorimpl.computeOutcomeProbability(requestPotentialOutcome, accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if(probability == null){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; }else{ if(probability.getValue()<=0.1){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with this device,please scan you device with an Antivirus or use another device"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); return decision; }else{ if(accessRequest.getUser().getUsertrustvalue().getValue() >0.9 && accessRequest.getDevice().getDevicetrustvalue().getValue()>0.9){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[RISK_TREATMENT_SIZE]; RiskTreatment riskTreatment = new RiskTreatment(privateloungewifi); RiskTreatment riskTreatment1 = new RiskTreatment("There is around 10% of chances that the asset that you wan to access will lose 50% of this value if you access it with by using this Wi-Fi connection,please try to connect to a secure Wi-Fi connection"); if (riskTreatments.length > 0){ riskTreatments[0] = riskTreatment; riskTreatments[1] = riskTreatment1; } riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION; decision.UPTOYOU_ACCESS_WITH_RISKCOMMUNICATION.setRiskCommunication(riskCommunication); logger.info("Decision: UPTOYOU_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } } } if(threats.get(i).getType().equalsIgnoreCase("Jailbroken") && threats.get(i).getProbability()<0.1){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } if(threats.get(i).getType().equalsIgnoreCase("Device under attack") && threats.get(i).getProbability()<0.1){ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } /** * This function is the version of the decideBasedOnRiskPolicy for the demo Demo_Hambourg. * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_version_Demo_Hambourg(AccessRequest accessRequest, ConnectivityEvent connEvent) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; if (!connEvent.getWifiEncryption().equals("WPA2")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("Action not allowed. Please, change WIFI encryption to WPA2"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); logger.info("Decision: MAYBE_ACCESS"); logger.info("RiskTreatment: Action not allowed. Please, change WIFI encryption to WPA2"); return decision; }else{ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; } } /** * This function is the version of the decideBasedOnRiskPolicy for the demo Demo_Hambourg. * * @param accessRequest * @param context * @return */ public Decision decideBasedOnRiskPolicy_testing_version(AccessRequest accessRequest, PolicyCompliance policyCompliance, Context context) { // TODO Auto-generated method stub Decision decision = Decision.STRONG_DENY_ACCESS; EventProcessorImpl eventprocessorimpl = new EventProcessorImpl(); if(!policyCompliance.getResult().equals(policyCompliance.DENY)){ List<Clue> listclues = eventprocessorimpl.getCurrentClues(accessRequest, accessRequest.getUser().getUsertrustvalue(), accessRequest.getDevice().getDevicetrustvalue()); if (accessRequest.getRequestedCorporateAsset().getConfidential_level()=="PUBLIC"){ decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); logger.info("The confidential level of the asset is PUBLIC"); return decision; } for (int i = 0; i < listclues.size(); i++) { if (listclues.get(i).getName().equalsIgnoreCase("Virus")){ eu.musesproject.server.risktrust.RiskCommunication riskCommunication = new eu.musesproject.server.risktrust.RiskCommunication(); RiskTreatment [] riskTreatments = new RiskTreatment[1]; RiskTreatment riskTreatment = new RiskTreatment("Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); riskTreatments[0] = riskTreatment; riskCommunication.setRiskTreatment(riskTreatments); decision = Decision.MAYBE_ACCESS_WITH_RISKTREATMENTS; decision.MAYBE_ACCESS_WITH_RISKTREATMENTS.setRiskCommunication(riskCommunication); decision.setCondition("<noAttachments>1</noAttachments>");//TODO Manage this programmatically logger.info("Decision: MAYBE_ACCESS"); logger.info("RISKTREATMENTS:Your device seems to have a Virus,please scan you device with an Antivirus or use another device"); return decision; } } decision = Decision.GRANTED_ACCESS; logger.info("Decision: GRANTED_ACCESS"); return decision; }else{ decision = Decision.STRONG_DENY_ACCESS; logger.info("Decision: STRONG_DENY_ACCESS"); return decision; } } /** * WarnDeviceSecurityStateChange is a function whose aim is to update the device trust value based on the new DeviceSecurityState. * @param deviceSecurityState the device security state */ @Override public void warnDeviceSecurityStateChange(DeviceSecurityState deviceSecurityState) { /*if(dbManager.findDeviceById(Integer.toString(deviceSecurityState.getDevice_id())).size()!=0){ logger.info("RT2AE.......: "+deviceSecurityState.getDevice_id()); if(dbManager.getDeviceByIMEI(new String(deviceSecurityState.getDevice_id().toByteArray()))!=null){ //eu.musesproject.server.entity.Devices device = dbManager.findDeviceById(Integer.toString(deviceSecurityState.getDevice_id())).get(0); eu.musesproject.server.entity.Devices device = dbManager.getDeviceByIMEI(new String(deviceSecurityState.getDevice_id().toByteArray())); double countadditionalprotection = device.getAdditionalProtections().size(); double countclues = deviceSecurityState.getClues().size(); deviceSecurityState.getDevice_id(); List<Clue> listclues = deviceSecurityState.getClues(); if(listclues.size()<=5){ device.setTrustValue(countadditionalprotection/(countadditionalprotection+countclues+1)); }else{ device.setTrustValue(countadditionalprotection/(countadditionalprotection+countclues)); } try { dbManager.setDevice(device); } catch (Exception e) { // TODO: handle exception } }else{ logger.info("The device is not stored in the database, make sure that your device is registred,please contact the CSO"); }*/ } /** * WarnUserSeemsInvolvedInSecurityIncident is a function whose aim is to check that if the user seems involved in security incident. * @param user the user * @param probability the probability * @param securityIncident the security incident */ @Override public void warnUserSeemsInvolvedInSecurityIncident(User user,Probability probability, SecurityIncident securityIncident) { // TODO Auto-generated method stub eu.musesproject.server.entity.Decision decision = dbManager.findDecisionById(String.valueOf(securityIncident.getDecisionid())).get(0); eu.musesproject.server.entity.Threat threat = dbManager.findThreatById(String.valueOf(decision.getAccessRequest().getThreatId())).get(0); System.out.println("bad 11 "+threat.getBadOutcomeCount()); threat.setBadOutcomeCount(threat.getBadOutcomeCount()+1); System.out.println("bad "+threat.getBadOutcomeCount()); System.out.println("occ "+threat.getOccurences()); System.out.println("prob "+(double)threat.getBadOutcomeCount()/(double)threat.getOccurences()); threat.setProbability(((double)threat.getBadOutcomeCount()/(double)threat.getOccurences())); dbManager.setThreat(threat); eu.musesproject.server.entity.Users musesUser = dbManager.getUserByUsername(securityIncident.getUser().getUsername()); eu.musesproject.server.entity.Devices musesDevice = dbManager.findDeviceById(String.valueOf(securityIncident.getDeviceid())).get(0); List<eu.musesproject.server.entity.Devices> musesDevices = new ArrayList<eu.musesproject.server.entity.Devices>(); List<eu.musesproject.server.entity.Users> users = new ArrayList<eu.musesproject.server.entity.Users>(); System.out.println("opp "+threat.getProbability()); musesDevice.setTrustValue(1-threat.getProbability()); musesDevices.add(musesDevice); dbManager.updateorSaveDevice(musesDevice); musesUser.setTrustValue(1-threat.getProbability()); users.add(musesUser); dbManager.setUsers(users); } public void storingUserBehavior(eu.musesproject.server.entity.UserBehaviour userbehaviour) { if(userbehaviour!=null){ logger.info("RT2AE receives the user behaviour...."); try { logger.info("RT2AE storing the user behaviour...."); dbManager.setUserBehaviour(userbehaviour); } catch (Exception e) { logger.error("Something happens storing the user behaviour"); } }else{ logger.info("The user behaviour is null, make sure that the user behaviour is not null"); } } /** * Updates trust in user given positive outcome. * * @param user1 * the user1 * @param opportunityDescriptor * the opportunity descriptor public void updatesTrustInUserGivenPositiveOutcome(User user1, OpportunityDescriptor opportunityDescriptor) { //System.out.println("Former users trust value is: " + user1.getUsertrustvalue().getValue()); eu.musesproject.server.entity.Users musesUser = dbManager.getUserByUsername(user1.getUsername()); List<eu.musesproject.server.entity.Users> users = new ArrayList<eu.musesproject.server.entity.Users>(); UserTrustValue usertrustvalue = new UserTrustValue(); usertrustvalue.setValue(1.0); if(user1.getUsertrustvalue().getValue() >= 1) user1.setUsertrustvalue(usertrustvalue); else{ UserTrustValue t = new UserTrustValue();//TrustValue t = new TrustValue((user1.getTrustValue().getValue() + 0.1)); t.setValue(user1.getUsertrustvalue().getValue()+0.1); user1.setUsertrustvalue(t); } System.out.println("New users trust value is: " + user1.getUsertrustvalue().getValue()); //GuiMain.getPersistenceManager().setSimUsers(new ArrayList<SimUser>(Arrays.asList(user1))); musesUser.setTrustValue(user1.getUsertrustvalue().getValue()); users.add(musesUser); dbManager.setUsers(users); } */ }
package io.liveoak.pgsql; import java.io.IOException; import java.net.URI; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.liveoak.common.util.PagingLinksBuilder; import io.liveoak.pgsql.data.QueryResults; import io.liveoak.pgsql.meta.Catalog; import io.liveoak.pgsql.meta.Column; import io.liveoak.pgsql.meta.QueryBuilder; import io.liveoak.pgsql.meta.Table; import io.liveoak.spi.LiveOak; import io.liveoak.spi.RequestContext; import io.liveoak.spi.Sorting; import io.liveoak.spi.resource.MapResource; import io.liveoak.spi.resource.SynchronousResource; import io.liveoak.spi.resource.async.Resource; import io.liveoak.spi.resource.async.Responder; import io.liveoak.spi.state.ResourceState; /** * @author <a href="mailto:marko.strukelj@gmail.com">Marko Strukelj</a> */ public class PgSqlTableResource implements SynchronousResource { private static final String SCHEMA_ENDPOINT = ";schema"; private PgSqlRootResource parent; private String id; private QueryResults results; private QueryBuilder queryBuilder; public PgSqlTableResource(PgSqlRootResource root, String table) { this.parent = root; this.id = table; this.queryBuilder = parent.queryBuilder(); } @Override public PgSqlRootResource parent() { return parent; } @Override public String id() { return id; } @Override public Map<String, ?> properties(RequestContext ctx) throws Exception { // perform select and store it for readMembers if (results != null) { return null; } results = queryTable(id, null, ctx); List<Resource> links = new LinkedList<>(); MapResource link = new MapResource(); link.put("rel", "schema"); link.put(LiveOak.HREF, uri() + SCHEMA_ENDPOINT); links.add(link); PagingLinksBuilder linksBuilder = new PagingLinksBuilder(ctx) .uri(uri()) .count(results.count()); int totalCount = -1; if (parent.configuration().configuration().includeTotalCount()) { totalCount = queryTableCount(id, ctx); linksBuilder.totalCount(totalCount); } links.addAll(linksBuilder.build()); // keep predictable ordering by using LinkedHashMap Map<String, Object> result = new LinkedHashMap<>(); result.put("links", links); if (totalCount != -1 || results.count() < ctx.pagination().limit()) { result.put("count", totalCount != -1 ? totalCount : results.count()); } result.put("type", "collection"); return result; } @Override public Collection<Resource> members(RequestContext ctx) throws Exception { return results.rows() .stream() .map(row -> new PgSqlRowResource(this, row)) .collect(Collectors.toList()); } @Override public Resource member(RequestContext ctx, String childId) throws Exception { QueryResults results = queryTable(id, childId, ctx); if (results.count() != 0) { return new PgSqlRowResource(this, results.rows().get(0)); } return null; } @Override public void createMember(RequestContext ctx, ResourceState state, Responder responder) throws Exception { // insert a new record into a table String itemId = state.id(); if (itemId == null || itemId.length() == 0) { responder.invalidRequest("No id"); return; } state.uri(new URI(uri().toString() + "/" + itemId)); Catalog cat = parent.catalog(); Table table = cat.tableById(id()); try (Connection c = parent.connection()) { itemId = queryBuilder.executeCreate(ctx, c, table, state); // TODO: also handle expanded many-to-one / one-to-many } //readMember(ctx, itemId, responder); QueryResults results = queryTable(id, itemId, ctx); responder.resourceCreated(new PgSqlRowResource(this, results.rows().get(0))); } @Override public void updateProperties(RequestContext ctx, ResourceState state, Responder responder) throws Exception { System.out.println("Table updateProperties"); SynchronousResource.super.updateProperties(ctx, state, responder); } @Override public void delete(RequestContext ctx, Responder responder) throws Exception { Catalog cat = parent.catalog(); Table t = cat.tableById(id); try (Connection c = parent.connection()) { queryBuilder.executeDeleteTable(c, t); } // trigger schema reload parent.reloadSchema(); // TODO - does it make sense to return a body here at all? Container fails to set Content-Length if resourceDeleted(null) // only return id and uri in response - no members results = new QueryResults(); responder.resourceDeleted(this); } public QueryResults queryResults() { return results; } public QueryResults queryTable(String table, String id, RequestContext ctx) throws SQLException, IOException { Catalog cat = parent.catalog(); Table t = cat.tableById(table); try (Connection con = parent.connection()) { String q = ctx.resourceParams().value("q"); if (id == null) { if (q != null) { return queryBuilder.querySelectFromTable(con, t, replaceIdsWithColumnNames(ctx.sorting()), ctx.pagination(), q); } else { return queryBuilder.querySelectFromTable(con, t, replaceIdsWithColumnNames(ctx.sorting()), ctx.pagination()); } } else { return queryBuilder.querySelectFromTableWhereId(con, t, id); } } } public int queryTableCount(String table, RequestContext ctx) throws SQLException, IOException { Catalog cat = parent.catalog(); Table t = cat.tableById(table); try (Connection con = parent.connection()) { String q = ctx.resourceParams().value("q"); if (q != null) { return queryBuilder.querySelectCountFromTable(con, t, q); } else { return queryBuilder.querySelectCountFromTable(con, t); } } } private Sorting replaceIdsWithColumnNames(Sorting sorting) { if (sorting == null) { return null; } Catalog cat = parent.catalog(); Sorting.Builder builder = new Sorting.Builder(); for (Sorting.Spec f: sorting) { if (f.name().equals("id")) { Table table = cat.tableById(id); for (Column col: table.pk().columns()) { builder.addSpec(col.name(), f.ascending()); } } else { builder.addSpec(f.name(), f.ascending()); } } return builder.build(); } }
package org.jpos.qi.system; import com.vaadin.data.Binder; import org.jpos.ee.BLException; import org.jpos.ee.DB; import org.jpos.ee.SysLog; import org.jpos.ee.SysLogManager; import org.jpos.qi.QIHelper; import java.util.*; import java.util.stream.Stream; public class AuditLogHelper extends QIHelper { protected AuditLogHelper() { super(SysLog.class); } @Override public Stream getAll(int offset, int limit, Map<String, Boolean> orders) throws Exception { List<SysLog> list = DB.exec(db -> { SysLogManager mgr = new SysLogManager(db); return mgr.getAll(offset,limit,orders); }); return list.stream(); } @Override public int getItemCount() throws Exception { return DB.exec(db -> { SysLogManager mgr = new SysLogManager(db); return mgr.getItemCount(); }); } @Override public String getItemId(Object item) { return String.valueOf(((SysLog)item).getId()); } @Override public boolean updateEntity(Binder binder) throws BLException { return false; } }
package foodtruck.server.resources; import java.io.IOException; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import com.google.appengine.api.capabilities.CapabilitiesService; import com.google.appengine.api.capabilities.CapabilitiesServiceFactory; import com.google.appengine.api.capabilities.Capability; import com.google.appengine.api.capabilities.CapabilityServicePb; import com.google.appengine.api.capabilities.CapabilityStatus; import com.google.appengine.api.users.UserServiceFactory; import com.google.inject.Inject; import org.joda.time.DateTime; import foodtruck.model.TruckStop; import foodtruck.model.TruckStopWithCounts; import foodtruck.server.security.SecurityChecker; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * @author aviolette * @since 3/30/15 */ @Path("/v2/stops") @Produces("application/json") public class TruckStopResource { private static final Logger log = Logger.getLogger(TruckStopResource.class.getName()); private final FoodTruckStopService foodTruckService; private final Clock clock; private final SecurityChecker checker; @Inject public TruckStopResource(FoodTruckStopService service, Clock clock, SecurityChecker checker) { this.foodTruckService = service; this.clock = clock; this.checker = checker; } @DELETE @Path("{stopId: \\d+}") public void delete(@PathParam("stopId") final long stopId) throws ServletException, IOException { if (!checker.isAdmin()) { TruckStop stop = foodTruckService.findById(stopId); if (stop == null) { return; } checker.requiresLoggedInAs(stop.getTruck().getId()); } foodTruckService.delete(stopId); } @PUT public void save(TruckStop truckStop) throws ServletException, IOException { checker.requiresLoggedInAs(truckStop.getTruck().getId()); log.log(Level.INFO, "Saving stop: {0}", truckStop); CapabilitiesService service = CapabilitiesServiceFactory.getCapabilitiesService(); CapabilityStatus status = service.getStatus(Capability.DATASTORE_WRITE).getStatus(); log.log(Level.INFO, "Data store: {0}", status); foodTruckService.update(truckStop, UserServiceFactory.getUserService().getCurrentUser().getEmail()); } @GET public Collection<TruckStopWithCounts> getStops(@QueryParam("truck") String truckId, @Context DateTime startTime) { startTime = (startTime == null) ? clock.currentDay().toDateMidnight().toDateTime() : startTime; return foodTruckService.findStopsForTruckAfter(truckId, startTime); } }
package hudson.plugins.checkstyle; import hudson.maven.MavenBuild; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenModule; import hudson.maven.MavenReporterDescriptor; import hudson.maven.MojoInfo; import hudson.model.Action; import hudson.plugins.checkstyle.parser.CheckStyleParser; import hudson.plugins.checkstyle.util.FilesParser; import hudson.plugins.checkstyle.util.HealthAwareMavenReporter; import hudson.plugins.checkstyle.util.HealthReportBuilder; import hudson.plugins.checkstyle.util.model.JavaProject; import java.io.IOException; import java.io.PrintStream; import org.apache.maven.project.MavenProject; import org.kohsuke.stapler.DataBoundConstructor; /** * Publishes the results of the Checkstyle analysis (maven 2 project type). * * @author Ulli Hafner */ public class CheckStyleReporter extends HealthAwareMavenReporter { /** Unique identifier of this class. */ private static final long serialVersionUID = 2272875032054063496L; /** Descriptor of this publisher. */ public static final CheckStyleReporterDescriptor CHECKSTYLE_SCANNER_DESCRIPTOR = new CheckStyleReporterDescriptor(CheckStylePublisher.CHECKSTYLE_DESCRIPTOR); /** Default Checkstyle pattern. */ private static final String CHECKSTYLE_XML_FILE = "checkstyle-result.xml"; /** * Creates a new instance of <code>CheckStyleReporter</code>. * * @param threshold * Bug threshold to be reached if a build should be considered as * unstable. * @param healthy * Report health as 100% when the number of warnings is less than * this value * @param unHealthy * Report health as 0% when the number of warnings is greater * than this value * @param height * the height of the trend graph */ @DataBoundConstructor public CheckStyleReporter(final String threshold, final String healthy, final String unHealthy, final String height) { super(threshold, healthy, unHealthy, height, "CHECKSTYLE"); } /** {@inheritDoc} */ @Override protected boolean acceptGoal(final String goal) { return "checkstyle".equals(goal) || "site".equals(goal); } /** {@inheritDoc} */ @Override public JavaProject perform(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo, final PrintStream logger) throws InterruptedException, IOException { FilesParser checkstyleCollector = new FilesParser(logger, CHECKSTYLE_XML_FILE, new CheckStyleParser()); return getTargetPath(pom).act(checkstyleCollector); } /** {@inheritDoc} */ @Override protected void persistResult(final JavaProject project, final MavenBuild build) { CheckStyleResult result = new CheckStyleResultBuilder().build(build, project); HealthReportBuilder healthReportBuilder = createHealthBuilder( Messages.Checkstyle_ResultAction_HealthReportSingleItem(), Messages.Checkstyle_ResultAction_HealthReportMultipleItem("%d")); build.getActions().add(new MavenCheckStyleResultAction(build, healthReportBuilder, getHeight(), result)); build.registerAsProjectAction(CheckStyleReporter.this); } /** {@inheritDoc} */ @Override public Action getProjectAction(final MavenModule module) { return new CheckStyleProjectAction(module, getTrendHeight()); } /** {@inheritDoc} */ @Override protected Class<? extends Action> getResultActionClass() { return MavenCheckStyleResultAction.class; } /** {@inheritDoc} */ @Override public MavenReporterDescriptor getDescriptor() { return CHECKSTYLE_SCANNER_DESCRIPTOR; } }
package net.xmeter.samplers; import java.text.MessageFormat; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.jmeter.JMeter; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.Interruptible; import org.apache.jmeter.samplers.SampleEvent; import org.apache.jmeter.samplers.SampleListener; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.TestStateListener; import org.apache.jmeter.testelement.ThreadListener; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import org.apache.log.Priority; import org.fusesource.mqtt.client.Future; import org.fusesource.mqtt.client.FutureConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; import net.xmeter.Util; public class ConnectionSampler extends AbstractMQTTSampler implements TestStateListener, ThreadListener, Interruptible, SampleListener { private transient static Logger logger = LoggingManager.getLoggerForClass(); private transient MQTT mqtt = new MQTT(); private transient FutureConnection connection = null; private boolean interrupt = false; //Declare it as static, for the instance variable will be set to initial value 0 in testEnded method. //The static value will not be reset. private static int keepTime = 0; private static AtomicBoolean sleepFlag = new AtomicBoolean(false); private static final long serialVersionUID = 1859006013465470528L; @Override public boolean isKeepTimeShow() { return true; } @Override public SampleResult sample(Entry entry) { SampleResult result = new SampleResult(); result.setSampleLabel(getName()); try { if (!DEFAULT_PROTOCOL.equals(getProtocol())) { mqtt.setSslContext(Util.getContext(this)); } mqtt.setHost(getProtocol().toLowerCase() + "://" + getServer() + ":" + getPort()); mqtt.setKeepAlive((short) Integer.parseInt(getConnKeepAlive())); String clientId = null; if(isClientIdSuffix()) { clientId = Util.generateClientId(getConnPrefix()); } else { clientId = getConnPrefix(); } mqtt.setClientId(clientId); mqtt.setConnectAttemptsMax(Integer.parseInt(getConnAttamptMax())); mqtt.setReconnectAttemptsMax(Integer.parseInt(getConnReconnAttamptMax())); if (!"".equals(getUserNameAuth().trim())) { mqtt.setUserName(getUserNameAuth()); } if (!"".equals(getPasswordAuth().trim())) { mqtt.setPassword(getPasswordAuth()); } result.sampleStart(); connection = mqtt.futureConnection(); Future<Void> f1 = connection.connect(); f1.await(Integer.parseInt(getConnTimeout()), TimeUnit.SECONDS); Topic[] topics = { new Topic("topic_" + clientId, QoS.AT_LEAST_ONCE) }; connection.subscribe(topics); result.sampleEnd(); result.setSuccessful(true); result.setResponseData("Successful.".getBytes()); result.setResponseMessage(MessageFormat.format("Connection {0} connected successfully.", connection)); result.setResponseCodeOK(); } catch (Exception e) { logger.log(Priority.ERROR, e.getMessage(), e); result.sampleEnd(); result.setSuccessful(false); result.setResponseMessage(MessageFormat.format("Connection {0} connected failed.", connection)); result.setResponseData("Failed.".getBytes()); result.setResponseCode("500"); } return result; } @Override public void testEnded() { this.testEnded("local"); } @Override public void testEnded(String arg0) { logger.info("in testEnded, isNonGUI=" + JMeter.isNonGUI() + ", sleepFlag=" + sleepFlag.get()); this.interrupt = true; try { if (JMeter.isNonGUI()) { if(!sleepFlag.get()) { //The keepTime is saved as static variable, because keepTime variable in testEnded() //returns with initial value. logger.info("The work has been done, will keep connection for " + keepTime + " sceconds."); TimeUnit.SECONDS.sleep(keepTime); sleepFlag.set(true); } //The following code does not make sense, because the connection variable was already reset. //But it makes sense in threadFinished method. //The reason for not sleeping and then disconnecting in threadFinished is to avoid maintain too much of threads. //Otherwise each thread (for a thread-group) will be kept open before sleeping. /*if(this.connection != null) { this.connection.disconnect(); logger.info(MessageFormat.format("The connection {0} disconneted successfully.", connection)); }*/ } } catch(Exception ex) { logger.error(ex.getMessage(), ex); } } @Override public void testStarted() { this.testStarted("local"); } @Override public void testStarted(String arg0) { sleepFlag.set(false); keepTime = Integer.parseInt(getConnKeepTime()); logger.info("*** Keeptime is: " + keepTime); } @Override public void threadFinished() { } private void sleepCurrentThreadAndDisconnect() { try { //If the connection is null or does not connect successfully, then not necessary to keep the connection. if(connection == null || (!connection.isConnected())) { if(connection == null) { logger.info("Connection is null."); } else if(!connection.isConnected()) { logger.info("Connection is created, but is not connected."); } return; } long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= TimeUnit.SECONDS.toMillis(keepTime)) { if (this.interrupt) { logger.info("interrupted flag is true, and stop the sleep."); break; } TimeUnit.SECONDS.sleep(1); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); logger.log(Priority.INFO, MessageFormat.format("The connection {0} disconneted successfully.", connection)); } } } @Override public void threadStarted() { } @Override public boolean interrupt() { this.interrupt = true; if (!JMeter.isNonGUI()) { logger.info("In GUI mode, received the interrupt request from user."); } return true; } // Note: JMeter.isNonGUI() only valid when you specify "-n" option from command line, // other cases (such as JMeter GUI, remote engine) all treat isNonGUI() as "false" // So, if you use remote engine, it's actually follow isNonGUI()=false path in this sampler code, // and you can control the test and stop it in JMeter GUI via say "Remote Stop All" button. // You can also start remote agent with say "jmeter-server -DJMeter.NonGui=true", // in order to fool JMeter to treat isNonGUI() as "true". // However, the interrupt mechanism may not work well with remote engine when stop the remote test from JMeter GUI, // you may need to manually kill remote jmeter process to clean it up. /** * In this listener, it can receive the interrupt event trigger by user. */ @Override public void sampleOccurred(SampleEvent event) { if (!JMeter.isNonGUI() && "MQTT Connection Sampler".equals(event.getResult().getSampleLabel() )) { logger.info("Created the sampler results, will sleep current thread for " + getConnKeepTime() + " sceconds"); sleepCurrentThreadAndDisconnect(); } } @Override public void sampleStarted(SampleEvent arg0) { } @Override public void sampleStopped(SampleEvent arg0) { } }
package hudson.plugins.warnings.parser; import java.util.regex.Matcher; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.jvnet.localizer.Localizable; import hudson.Extension; import hudson.plugins.analysis.util.model.Priority; /** * A parser for the MSBuild/PcLint compiler warnings. * * @author Ulli Hafner */ @Extension public class MsBuildParser extends RegexpLineParser { private static final long serialVersionUID = -2141974437420906595L; static final String WARNING_TYPE = "MSBuild"; private static final String MS_BUILD_WARNING_PATTERN = "(?:^(?:.*)Command line warning ([A-Za-z0-9]+):\\s*(.*)\\s*\\[(.*)\\])|" + ANT_TASK + "(?:(?:\\s*\\d+>)?(?:(?:(?:(.*)\\((\\d*)(?:,(\\d+))?.*\\)|.*LINK)\\s*:|(.*):)\\s*([A-z-_]*\\s?(?:[Nn]ote|[Ii]nfo|[Ww]arning|(?:fatal\\s*)?[Ee]rror))\\s*:?\\s*([A-Za-z0-9]+)\\s*:\\s(?:\\s*([A-Za-z0-9.]+)\\s*:)?\\s*(.*?)(?: \\[([^\\]]*)[/\\\\][^\\]\\\\]+\\])?" + "|(.*)\\s*:.*error\\s*(LNK[0-9]+):\\s*(.*)))$"; /** * Creates a new instance of {@link MsBuildParser}. */ public MsBuildParser() { this(Messages._Warnings_MSBuild_ParserName(), Messages._Warnings_MSBuild_LinkName(), Messages._Warnings_MSBuild_TrendName()); } /** * Creates a new instance of {@link MsBuildParser}. * * @param parserName * name of the parser * @param linkName * name of the project action link * @param trendName * name of the trend graph */ public MsBuildParser(final Localizable parserName, final Localizable linkName, final Localizable trendName) { super(parserName, linkName, trendName, MS_BUILD_WARNING_PATTERN); } @Override protected Warning createWarning(final Matcher matcher) { String fileName = determineFileName(matcher); if (StringUtils.isNotBlank(matcher.group(2))) { return createWarning(fileName, 0, matcher.group(1), matcher.group(2), Priority.NORMAL); } else if (StringUtils.isNotBlank(matcher.group(13))) { return createWarning(fileName, 0, matcher.group(14), matcher.group(15), Priority.HIGH); } else { Warning warning; if (StringUtils.isNotEmpty(matcher.group(10))) { warning = createWarning(fileName, getLineNumber(matcher.group(5)), matcher.group(10), matcher.group(9), matcher.group(11), determinePriority(matcher)); } else { String category = matcher.group(9); if ("Expected".matches(category)) { return FALSE_POSITIVE; } warning = createWarning(fileName, getLineNumber(matcher.group(5)), category, matcher.group(11), determinePriority(matcher)); } warning.setColumnPosition(getLineNumber(matcher.group(6))); return warning; } } /** * Determines the name of the file that is cause of the warning. * * @param matcher * the matcher to get the matches from * @return the name of the file with a warning */ private String determineFileName(final Matcher matcher) { String fileName; if (StringUtils.isNotBlank(matcher.group(3))) { fileName = matcher.group(3); } else if (StringUtils.isNotBlank(matcher.group(7))) { fileName = matcher.group(7); } else if (StringUtils.isNotBlank(matcher.group(13))) { fileName = matcher.group(13); } else { fileName = matcher.group(4); } if (StringUtils.isBlank(fileName)) { fileName = StringUtils.substringBetween(matcher.group(11), "'"); } if (StringUtils.isBlank(fileName)) { fileName = "unknown.file"; } final String projectDir = matcher.group(12); if (StringUtils.isNotBlank(projectDir) && FilenameUtils.getPrefixLength(fileName) == 0 && !fileName.trim().equals("MSBUILD")) { // resolve fileName relative to projectDir fileName = FilenameUtils.concat(projectDir, fileName); } return fileName; } /** * Determines the priority of the warning. * * @param matcher * the matcher to get the matches from * @return the priority of the warning */ private Priority determinePriority(final Matcher matcher) { if (isOfType(matcher, "note") || isOfType(matcher, "info")) { return Priority.LOW; } else if (isOfType(matcher, "warning")) { return Priority.NORMAL; } return Priority.HIGH; } /** * Returns whether the warning type is of the specified type. * * @param matcher * the matcher * @param type * the type to match with * @return <code>true</code> if the warning type is of the specified type */ private boolean isOfType(final Matcher matcher, final String type) { return StringUtils.containsIgnoreCase(matcher.group(8), type); } }
package io.github.mzmine.gui.colorpicker; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.util.color.SimpleColorPalette; import java.util.List; import java.util.function.Consumer; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; /** * Grid of buttons for selecting color. */ public class ColorSwatch extends GridPane { private static final double MIN_TILE_SIZE = 18; private static final double PREF_TILE_SIZE = 24; private static final List<Color> BASIC_COLORS = List.of( Color.CYAN, Color.TEAL, Color.BLUE, Color.NAVY, Color.MAGENTA, Color.PURPLE, Color.RED, Color.MAROON, Color.YELLOW, Color.OLIVE, Color.GREEN, Color.LIME); private final int nColumns; private final int nRows; Consumer<Color> onColorSelected = (clr) -> { }; /** * No arguments constructor. Needed for FXML usage. */ public ColorSwatch() { this(new Color[]{}); } public ColorSwatch(Color... extraColors) { getStylesheets().add(getClass().getResource("ColorSwatch.css").toExternalForm()); getStyleClass().add("color-grid"); SimpleColorPalette palette = MZmineCore.getConfiguration().getDefaultColorPalette(); List<Color> colors = palette != null ? palette : BASIC_COLORS; nColumns = colors.size(); nRows = (colors.size() + extraColors.length) / nColumns; // create button controls for color selection. for (int i = 0; i < colors.size(); i++) { addColorButton(colors.get(i), 0, i); } for (int i = 0; i < extraColors.length; i++) { addColorButton(extraColors[i], (i / nColumns) + 1, i % nColumns); } } private void addColorButton(Color color, int row, int column) { final Button colorChoice = new Button(); colorChoice.setUserData(color); colorChoice.setMinSize(MIN_TILE_SIZE, MIN_TILE_SIZE); colorChoice.setPrefSize(PREF_TILE_SIZE, PREF_TILE_SIZE); colorChoice.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); var colorHex = String.format( "#%02x%02x%02x", (int) Math.round(color.getRed() * 255), (int) Math.round(color.getGreen() * 255), (int) Math.round(color.getBlue() * 255)); final String backgroundStyle = "-fx-background-color: " + colorHex + ";"; colorChoice.setStyle(backgroundStyle); colorChoice.getStyleClass().add("color-choice"); // choose the color when the button is clicked. colorChoice.setOnAction(actionEvent -> { onColorSelected.accept((Color) colorChoice.getUserData()); }); add(colorChoice, column, row); } @Override protected void layoutChildren() { final double tileSize = Math.min(getWidth() / nColumns, getHeight() / nRows); for (var child : getChildren()) { if (child instanceof Button btn) { btn.setPrefSize(tileSize, tileSize); } } setPrefWidth(nColumns * tileSize); setMaxWidth(nColumns * tileSize); setPrefHeight(nRows * tileSize); setMaxHeight(nRows * tileSize); super.layoutChildren(); } }
package io.github.mzmine.modules.batchmode; import io.github.mzmine.datamodel.MZmineProject; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.features.FeatureList; import io.github.mzmine.main.GoogleAnalyticsTracker; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.MZmineModuleCategory; import io.github.mzmine.modules.MZmineProcessingModule; import io.github.mzmine.modules.MZmineProcessingStep; import io.github.mzmine.modules.MZmineRunnableModule; import io.github.mzmine.modules.io.import_rawdata_all.AllSpectralDataImportParameters; import io.github.mzmine.parameters.Parameter; import io.github.mzmine.parameters.ParameterSet; import io.github.mzmine.parameters.parametertypes.EmbeddedParameterSet; import io.github.mzmine.parameters.parametertypes.filenames.FileNameParameter; import io.github.mzmine.parameters.parametertypes.filenames.FileNamesParameter; import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsParameter; import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsSelection; import io.github.mzmine.parameters.parametertypes.selectors.RawDataFilesParameter; import io.github.mzmine.parameters.parametertypes.selectors.RawDataFilesSelection; import io.github.mzmine.taskcontrol.AbstractTask; import io.github.mzmine.taskcontrol.Task; import io.github.mzmine.taskcontrol.TaskPriority; import io.github.mzmine.taskcontrol.TaskStatus; import io.github.mzmine.taskcontrol.impl.WrappedTask; import io.github.mzmine.util.ExitCode; import io.github.mzmine.util.files.FileAndPathUtil; import java.io.File; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import org.jetbrains.annotations.NotNull; /** * Batch mode task */ public class BatchTask extends AbstractTask { private final BatchQueue queue; // advanced parameters private final int stepsPerDataset; private final Logger logger = Logger.getLogger(this.getClass().getName()); private final int totalSteps; private final MZmineProject project; private int processedSteps; private final boolean useAdvanced; private final int datasets; private List<File> subDirectories; private List<RawDataFile> createdDataFiles; private List<RawDataFile> previousCreatedDataFiles; private List<FeatureList> createdFeatureLists; private List<FeatureList> previousCreatedFeatureLists; private Boolean skipOnError; private Boolean searchSubdirs; private Boolean createResultsDir; private File parentDir; private int currentDataset; BatchTask(MZmineProject project, ParameterSet parameters, @NotNull Instant moduleCallDate) { this(project, parameters, moduleCallDate, null); // we don't create any new data here, date is irrelevant, too. } public BatchTask(final MZmineProject project, final ParameterSet parameters, final Instant moduleCallDate, final List<File> subDirectories) { super(null, moduleCallDate); this.project = project; this.queue = parameters.getParameter(BatchModeParameters.batchQueue).getValue(); // advanced parameters useAdvanced = parameters.getParameter(BatchModeParameters.advanced).getValue(); if (useAdvanced) { // if sub directories is set - the input and output files are changed to each sub directory // each sub dir is processed sequentially as a different dataset AdvancedBatchModeParameters advanced = parameters.getParameter(BatchModeParameters.advanced) .getEmbeddedParameters(); skipOnError = advanced.getValue(AdvancedBatchModeParameters.skipOnError); searchSubdirs = advanced.getValue(AdvancedBatchModeParameters.includeSubdirectories); createResultsDir = advanced.getValue(AdvancedBatchModeParameters.createResultsDirectory); parentDir = advanced.getValue(AdvancedBatchModeParameters.processingParentDir); this.subDirectories = subDirectories; datasets = subDirectories == null || subDirectories.isEmpty() ? 1 : subDirectories.size(); } else { datasets = 1; } stepsPerDataset = queue.size(); totalSteps = stepsPerDataset * datasets; createdDataFiles = new ArrayList<>(); createdFeatureLists = new ArrayList<>(); previousCreatedDataFiles = new ArrayList<>(); previousCreatedFeatureLists = new ArrayList<>(); } @Override public void run() { setStatus(TaskStatus.PROCESSING); logger.info("Starting a batch of " + totalSteps + " steps"); int errorDataset = 0; currentDataset = -1; String datasetName = ""; // Process individual batch steps for (int i = 0; i < totalSteps; i++) { // at the end of one dataset, clear the project and start over again if (useAdvanced && processedSteps % stepsPerDataset == 0) { // clear the old project MZmineCore.getProjectManager().clearProject(); currentDataset++; // change files File datasetDir = subDirectories.get(currentDataset); datasetName = datasetDir.getName(); File[] allFiles = FileAndPathUtil.findFilesInDirFlat(datasetDir, AllSpectralDataImportParameters.ALL_MS_DATA_FILTER, searchSubdirs); logger.info( String.format("Processing batch dataset %s (%d/%d)", datasetName, currentDataset + 1, datasets)); if (allFiles.length != 0) { // set files to import setImportFiles(allFiles); // set files to output setOutputFiles(parentDir, createResultsDir, datasetName); } else { errorDataset++; logger.info("No data files found in directory: " + datasetName); // no data files if (skipOnError) { processedSteps += stepsPerDataset; continue; } else { setStatus(TaskStatus.ERROR); setErrorMessage("No data files found in directory: " + datasetName); return; } } } // run step processQueueStep(i % stepsPerDataset); processedSteps++; // If we are canceled or ran into error, stop here if (isCanceled()) { return; } else if (getStatus() == TaskStatus.ERROR) { errorDataset++; if (skipOnError && datasets - currentDataset > 0) { // skip to next dataset logger.info("Error in dataset: " + datasetName + " total error datasets:" + errorDataset); processedSteps = (processedSteps / stepsPerDataset + 1) * stepsPerDataset; continue; } else { return; } } } logger.info("Finished a batch of " + totalSteps + " steps"); setStatus(TaskStatus.FINISHED); } private void setOutputFiles(final File parentDir, final boolean createResultsDir, final String datasetName) { int changedOutputSteps = 0; for (MZmineProcessingStep<?> currentStep : queue) { // only change for export modules if (currentStep.getModule() instanceof MZmineRunnableModule mod && ( mod.getModuleCategory() == MZmineModuleCategory.FEATURELISTEXPORT || mod.getModuleCategory() == MZmineModuleCategory.RAWDATAEXPORT)) { ParameterSet params = currentStep.getParameterSet(); for (final Parameter<?> p : params.getParameters()) { if (p instanceof FileNameParameter fnp) { File old = fnp.getValue(); String oldName = FileAndPathUtil.eraseFormat(old).getName(); fnp.setValue( createDatasetExportPath(parentDir, createResultsDir, datasetName, oldName)); changedOutputSteps++; } } } } if (changedOutputSteps == 0) { logger.info( "No output steps were changes... Make sure to include steps that include filename parameters for export"); throw new IllegalStateException( "No output steps were changes... Make sure to include steps that include filename parameters for export"); } else { logger.info("Changed output for n steps=" + changedOutputSteps); } } private File createDatasetExportPath(final File parentDir, final boolean createResultsDir, final String datasetName, final String oldName) { if (createResultsDir) { return Paths.get(parentDir.getPath(), "results", datasetName, oldName + datasetName).toFile(); } else { return Paths.get(parentDir.getPath(), datasetName, oldName + datasetName).toFile(); } } private void setImportFiles(final File[] allFiles) { MZmineProcessingStep<?> currentStep = queue.get(0); ParameterSet importParameters = currentStep.getParameterSet(); FileNamesParameter importParam = importParameters.getParameter( AllSpectralDataImportParameters.fileNames); if (importParam == null) { logger.warning( "When running advanced batch, the first step in the batch needs to be the all spectral data import module."); throw new IllegalStateException( "When running advanced batch, the first step in the batch needs to be the all spectral data import module"); } importParam.setValue(allFiles); } private void processQueueStep(int stepNumber) { logger.info("Starting step # " + (stepNumber + 1)); // Run next step of the batch MZmineProcessingStep<?> currentStep = queue.get(stepNumber); MZmineProcessingModule method = (MZmineProcessingModule) currentStep.getModule(); ParameterSet batchStepParameters = currentStep.getParameterSet(); final List<FeatureList> beforeFeatureLists = project.getCurrentFeatureLists(); final List<RawDataFile> beforeDataFiles = project.getCurrentRawDataFiles(); // If the last step did not produce any data files or feature lists, use // the ones from the previous step if (createdDataFiles.isEmpty()) { createdDataFiles = previousCreatedDataFiles; } if (createdFeatureLists.isEmpty()) { createdFeatureLists = previousCreatedFeatureLists; } // Update the RawDataFilesParameter parameters to reflect the current // state of the batch for (Parameter<?> p : batchStepParameters.getParameters()) { if (p instanceof RawDataFilesParameter rdp) { RawDataFile[] createdFiles = createdDataFiles.toArray(new RawDataFile[0]); final RawDataFilesSelection selectedFiles = rdp.getValue(); if (selectedFiles == null) { setStatus(TaskStatus.ERROR); setErrorMessage("Invalid parameter settings for module " + method.getName() + ": " + "Missing parameter value for " + p.getName()); return; } selectedFiles.setBatchLastFiles(createdFiles); } } if (!setBatchlastFeatureListsToParamSet(method, batchStepParameters)) { return; } // Check if the parameter settings are valid ArrayList<String> messages = new ArrayList<String>(); boolean paramsCheck = batchStepParameters.checkParameterValues(messages); if (!paramsCheck) { setStatus(TaskStatus.ERROR); setErrorMessage( "Invalid parameter settings for module " + method.getName() + ": " + Arrays.toString( messages.toArray())); } List<Task> currentStepTasks = new ArrayList<>(); Instant moduleCallDate = Instant.now(); logger.finest(() -> "Module " + method.getName() + " called at " + moduleCallDate.toString()); ExitCode exitCode = method.runModule(project, batchStepParameters, currentStepTasks, moduleCallDate); if (exitCode != ExitCode.OK) { setStatus(TaskStatus.ERROR); setErrorMessage("Could not start batch step " + method.getName()); return; } else { // track step by module GoogleAnalyticsTracker.trackModule(method); } // If current step didn't produce any tasks, continue with next step if (currentStepTasks.isEmpty()) { return; } boolean allTasksFinished = false; // Submit the tasks to the task controller for processing WrappedTask[] currentStepWrappedTasks = MZmineCore.getTaskController() .addTasks(currentStepTasks.toArray(new Task[0])); currentStepTasks = null; while (!allTasksFinished) { // If we canceled the batch, cancel all running tasks if (isCanceled()) { for (WrappedTask stepTask : currentStepWrappedTasks) { stepTask.getActualTask().cancel(); } return; } // First set to true, then check all tasks allTasksFinished = true; for (WrappedTask stepTask : currentStepWrappedTasks) { TaskStatus stepStatus = stepTask.getActualTask().getStatus(); // If any of them is not finished, keep checking if (stepStatus != TaskStatus.FINISHED) { allTasksFinished = false; } // If there was an error, we have to stop the whole batch if (stepStatus == TaskStatus.ERROR) { setStatus(TaskStatus.ERROR); setErrorMessage( stepTask.getActualTask().getTaskDescription() + ": " + stepTask.getActualTask() .getErrorMessage()); return; } // If user canceled any of the tasks, we have to cancel the // whole batch if (stepStatus == TaskStatus.CANCELED) { setStatus(TaskStatus.CANCELED); for (WrappedTask t : currentStepWrappedTasks) { t.getActualTask().cancel(); } return; } } // Wait 1s before checking the tasks again if (!allTasksFinished) { synchronized (this) { try { this.wait(1000); } catch (InterruptedException e) { // ignore } } } } createdDataFiles = new ArrayList<>(project.getCurrentRawDataFiles()); createdFeatureLists = new ArrayList<>(project.getCurrentFeatureLists()); createdDataFiles.removeAll(beforeDataFiles); createdFeatureLists.removeAll(beforeFeatureLists); // Clear the saved data files and feature lists. Save them to the // "previous" lists, in case the next step does not produce any new data if (!createdDataFiles.isEmpty()) { previousCreatedDataFiles = createdDataFiles; } if (!createdFeatureLists.isEmpty()) { previousCreatedFeatureLists = createdFeatureLists; } } /** * Recursively sets the last feature lists to the parameters since there might be embedded * parameters. * * @return false on error */ private boolean setBatchlastFeatureListsToParamSet(MZmineProcessingModule method, ParameterSet batchStepParameters) { // Update the FeatureListsParameter parameters to reflect the current // state of the batch for (Parameter<?> p : batchStepParameters.getParameters()) { if (p instanceof FeatureListsParameter featureListsParameter) { FeatureList[] createdFlists = createdFeatureLists.toArray(new FeatureList[0]); final FeatureListsSelection selectedFeatureLists = featureListsParameter.getValue(); if (selectedFeatureLists == null) { setStatus(TaskStatus.ERROR); setErrorMessage("Invalid parameter settings for module " + method.getName() + ": " + "Missing parameter value for " + p.getName()); return false; } selectedFeatureLists.setBatchLastFeatureLists(createdFlists); } else if (p instanceof EmbeddedParameterSet embedded) { if (!setBatchlastFeatureListsToParamSet(method, embedded.getEmbeddedParameters())) { return false; } } } return true; } @Override public TaskPriority getTaskPriority() { // to not block mzmine when run with single thread return TaskPriority.HIGH; } @Override public double getFinishedPercentage() { if (totalSteps == 0) { return 0; } return (double) processedSteps / totalSteps; } @Override public String getTaskDescription() { if (datasets > 1) { if (stepsPerDataset == 0) { return "Batch mode"; } else { return String.format("Batch step %d/%d of dataset %d/%d", processedSteps % stepsPerDataset + 1, stepsPerDataset, currentDataset + 1, datasets); } } else { return String.format("Batch step %d/%d", processedSteps + 1, totalSteps); } } }
package kr.rvs.ksecurity.initializer; import kr.rvs.ksecurity.blacklist.CompoundChecker; import kr.rvs.ksecurity.blacklist.Parser; import kr.rvs.ksecurity.util.Config; import kr.rvs.ksecurity.util.Lang; import kr.rvs.ksecurity.util.Static; import kr.rvs.ksecurity.util.URLs; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; public class MainInitializer implements Initializer { @Override public Result check(JavaPlugin plugin, Config config) { return Result.ofDefault(); } @Override public void init(JavaPlugin plugin) { // Send intro Bukkit.getScheduler().runTask(plugin, () -> Static.log(Lang.INTRO.withoutPrefix())); // Main listener Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { CompoundChecker checkers = new CompoundChecker(Parser.parseBlackList(URLs.BLACKLIST.openReader())); Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (checkers.check(event.getPlayer())) { player.kickPlayer(Lang.BLACKLIST.withSpacingPrefix()); } else { Bukkit.getScheduler().runTaskLater(plugin, () -> player.sendMessage( ChatColor.WHITE + " " + ChatColor.YELLOW + "KSecurity " + ChatColor.WHITE + " ."), 20); } } }, plugin); }); } }
package main.java.com.bag.server; import bftsmart.tom.MessageContext; import bftsmart.tom.ServiceReplica; import bftsmart.tom.server.defaultservices.DefaultRecoverable; import bftsmart.tom.server.defaultservices.DefaultReplier; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import com.github.benmanes.caffeine.cache.*; import main.java.com.bag.exceptions.OutDatedDataException; import main.java.com.bag.operations.CreateOperation; import main.java.com.bag.operations.DeleteOperation; import main.java.com.bag.operations.IOperation; import main.java.com.bag.operations.UpdateOperation; import main.java.com.bag.server.database.Neo4jDatabaseAccess; import main.java.com.bag.server.database.OrientDBDatabaseAccess; import main.java.com.bag.server.database.SparkseeDatabaseAccess; import main.java.com.bag.server.database.TitanDatabaseAccess; import main.java.com.bag.server.database.interfaces.IDatabaseAccess; import main.java.com.bag.util.Constants; import main.java.com.bag.util.Log; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import main.java.com.bag.util.storage.TransactionStorage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; /** * Super class of local or global cluster. * Used for common communication methods. */ public abstract class AbstractRecoverable extends DefaultRecoverable { /** * Keep the last x transaction in a separate list. */ public static final int KEEP_LAST_X = 500; /** * Contains the local server replica. */ private ServiceReplica replica = null; /** * Global snapshot id, increases with every committed transaction. */ private long globalSnapshotId = 0; /** * Unique Id of the server. */ private int id; /** * Write set of the nodes contains updates and deletes. */ private ConcurrentSkipListMap<Long, List<IOperation>> globalWriteSet; /** * Write set cache of the nodes contains updates and deletes but only of the last x transactions. */ private Cache<Long, List<IOperation>> latestWritesSet = Caffeine.newBuilder() .maximumSize(KEEP_LAST_X) .writer(new CacheWriter<Long, List<IOperation>>() { @Override public void write(@NotNull final Long key, @NotNull final List<IOperation> value) { globalWriteSet.put(key, value); } @Override public void delete(@NotNull final Long key, @Nullable final List<IOperation> value, @NotNull final RemovalCause cause) { //Nothing to do. } }).build(); /** * Object to lock on commits. */ private final Object commitLock = new Object(); /** * The wrapper class instance. Used to access the global cluster if possible. */ private final ServerWrapper wrapper; private final ServerInstrumentation instrumentation; private KryoFactory factory = () -> { Kryo kryo = new Kryo(); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); // configure kryo instance, customize settings return kryo; }; protected AbstractRecoverable(int id, final String configDirectory, final ServerWrapper wrapper, final ServerInstrumentation instrumentation) { this.id = id; this.wrapper = wrapper; this.instrumentation = instrumentation; globalSnapshotId = 1; KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); //the default verifier is instantiated with null in the ServerReplica. this.replica = new ServiceReplica(id, configDirectory, this, this, null, new DefaultReplier()); Log.getLogger().warn("Instantiated abstract recoverable of id: " + id); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); pool.release(kryo); globalWriteSet = new ConcurrentSkipListMap<>(); Log.getLogger().warn("Instantiating fileWriter."); try (final FileWriter file = new FileWriter(System.getProperty("user.home") + "/results" + id + ".txt", true); final BufferedWriter bw = new BufferedWriter(file); final PrintWriter out = new PrintWriter(bw)) { out.println(); out.println("Starting new experiment: "); out.println(); out.print("time;"); out.print("aborts;"); out.print("commits;"); out.print("reads;"); out.print("writes;"); out.print("throughput"); out.println(); } catch (IOException e) { Log.getLogger().info("Problem while writing to file!", e); } Log.getLogger().warn("Finished file writer instantiation."); } public void updateCounts(int writes, int reads, int commits, int aborts) { instrumentation.updateCounts(writes, reads, commits, aborts); } @Override public void installSnapshot(final byte[] bytes) { Log.getLogger().warn("Install snapshot!"); if (bytes == null) { return; } KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); Input input = new Input(bytes); globalSnapshotId = kryo.readObject(input, Long.class); Log.getLogger().error("Install snapshot with old values!!!!: " + globalSnapshotId); if (input.canReadInt()) { int writeSetSize = kryo.readObject(input, Integer.class); for (int i = 0; i < writeSetSize; i++) { long snapshotId = kryo.readObject(input, Long.class); Object object = kryo.readClassAndObject(input); if (object instanceof List && !((List) object).isEmpty() && ((List) object).get(0) instanceof IOperation) { globalWriteSet.put(snapshotId, (List<IOperation>) object); } } } if (input.canReadInt()) { int writeSetSize = kryo.readObject(input, Integer.class); for (int i = 0; i < writeSetSize; i++) { long snapshotId = kryo.readObject(input, Long.class); Object object = kryo.readClassAndObject(input); if (object instanceof List && !((List) object).isEmpty() && ((List) object).get(0) instanceof IOperation) { latestWritesSet.put(snapshotId, (List<IOperation>) object); } } } this.id = kryo.readObject(input, Integer.class); String instance = kryo.readObject(input, String.class); wrapper.setDataBaseAccess(ServerWrapper.instantiateDBAccess(instance, wrapper.getGlobalServerId())); readSpecificData(input, kryo); this.replica = new ServiceReplica(id, this, this); this.replica.setReplyController(new DefaultReplier()); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); input.close(); pool.release(kryo); } /** * Read the specific data of a local or global cluster. * * @param input object to read from. * @param kryo kryo object. */ abstract void readSpecificData(final Input input, final Kryo kryo); /** * Write the specific data of a local or global cluster. * * @param output object to write to. * @param kryo kryo object. * @param needToLock check if need to lock anything or server is currently starting. */ abstract Output writeSpecificData(final Output output, final Kryo kryo, boolean needToLock); @Override public byte[] getSnapshot() { Log.getLogger().warn("Get snapshot!!: " + globalWriteSet.size() + " + " + latestWritesSet.estimatedSize()); final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Output output = new Output(0, 200240); kryo.writeObject(output, getGlobalSnapshotId()); boolean needToLock = false; if (globalWriteSet != null && !globalWriteSet.isEmpty()) { kryo.writeObject(output, globalWriteSet.size()); for (final Map.Entry<Long, List<IOperation>> writeSet : globalWriteSet.entrySet()) { kryo.writeObject(output, writeSet.getKey()); kryo.writeObject(output, writeSet.getValue()); } } final Map<Long, List<IOperation>> latest = latestWritesSet.asMap(); kryo.writeObject(output, latest.size()); for (final Map.Entry<Long, List<IOperation>> writeSet : latest.entrySet()) { kryo.writeObject(output, writeSet.getKey()); kryo.writeObject(output, writeSet.getValue()); } kryo.writeObject(output, id); IDatabaseAccess databaseAccess = wrapper.getDataBaseAccess(); if (databaseAccess instanceof Neo4jDatabaseAccess) { kryo.writeObject(output, Constants.NEO4J); } else if (databaseAccess instanceof TitanDatabaseAccess) { kryo.writeObject(output, Constants.TITAN); } else if (databaseAccess instanceof OrientDBDatabaseAccess) { kryo.writeObject(output, Constants.ORIENTDB); } else if (databaseAccess instanceof SparkseeDatabaseAccess) { kryo.writeObject(output, Constants.SPARKSEE); } else { kryo.writeObject(output, "none"); } output = writeSpecificData(output, kryo, needToLock); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Handles the node read message and requests it to the database. * * @param input get info from. * @param messageContext additional context. * @param kryo kryo object. * @param output write info to. * @return output object to return to client. */ public Output handleNodeRead(Input input, MessageContext messageContext, Kryo kryo, Output output) { long localSnapshotId = kryo.readObject(input, Long.class); NodeStorage identifier = kryo.readObject(input, NodeStorage.class); input.close(); updateCounts(0, 1, 0, 0); Log.getLogger().info("With snapShot id: " + localSnapshotId); if (localSnapshotId == -1) { TransactionStorage transaction = new TransactionStorage(); transaction.addReadSetNodes(identifier); //localTransactionList.put(messageContext.getSender(), transaction); localSnapshotId = getGlobalSnapshotId(); } ArrayList<Object> returnList = null; Log.getLogger().info("Get info from databaseAccess to snapShotId " + localSnapshotId); try { returnList = new ArrayList<>(wrapper.getDataBaseAccess().readObject(identifier, localSnapshotId)); } catch (OutDatedDataException e) { kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, localSnapshotId); Log.getLogger().warn("Transaction found conflict"); kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); return output; } kryo.writeObject(output, Constants.CONTINUE); kryo.writeObject(output, localSnapshotId); if (returnList != null) { Log.getLogger().info("Got info from databaseAccess: " + returnList.size()); } if (returnList == null || returnList.isEmpty()) { kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); return output; } ArrayList<NodeStorage> nodeStorage = new ArrayList<>(); ArrayList<RelationshipStorage> relationshipStorage = new ArrayList<>(); for (Object obj : returnList) { if (obj instanceof NodeStorage) { nodeStorage.add((NodeStorage) obj); } else if (obj instanceof RelationshipStorage) { relationshipStorage.add((RelationshipStorage) obj); } } kryo.writeObject(output, nodeStorage); kryo.writeObject(output, relationshipStorage); return output; } /** * Handles the relationship read message and requests it to the database. * * @param input get info from. * @param kryo kryo object. * @param output write info to. * @return output object to return to client. */ public Output handleRelationshipRead(final Input input, final Kryo kryo, final Output output) { long localSnapshotId = kryo.readObject(input, Long.class); RelationshipStorage identifier = kryo.readObject(input, RelationshipStorage.class); input.close(); updateCounts(0, 1, 0, 0); Log.getLogger().info("With snapShot id: " + localSnapshotId); if (localSnapshotId == -1) { TransactionStorage transaction = new TransactionStorage(); transaction.addReadSetRelationship(identifier); //localTransactionList.put(messageContext.getSender(), transaction); localSnapshotId = getGlobalSnapshotId(); } ArrayList<Object> returnList = null; Log.getLogger().info("Get info from databaseAccess"); try { returnList = new ArrayList<>((wrapper.getDataBaseAccess()).readObject(identifier, localSnapshotId)); } catch (OutDatedDataException e) { kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, localSnapshotId); Log.getLogger().warn("Transaction found conflict"); kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); } kryo.writeObject(output, Constants.CONTINUE); kryo.writeObject(output, localSnapshotId); if (returnList == null || returnList.isEmpty()) { kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); return output; } Log.getLogger().info("Got info from databaseAccess: " + returnList.size()); final ArrayList<NodeStorage> nodeStorage = new ArrayList<>(); final ArrayList<RelationshipStorage> relationshipStorage = new ArrayList<>(); for (Object obj : returnList) { if (obj instanceof NodeStorage) { nodeStorage.add((NodeStorage) obj); } else if (obj instanceof RelationshipStorage) { relationshipStorage.add((RelationshipStorage) obj); } } //todo problem returning the relationship here! kryo.writeObject(output, nodeStorage); kryo.writeObject(output, relationshipStorage); return output; } /** * Execute the commit on the replica. * * @param localWriteSet the write set to execute. */ public void executeCommit(final List<IOperation> localWriteSet) { synchronized (commitLock) { final long currentSnapshot = ++globalSnapshotId; //Execute the transaction. for (IOperation op : localWriteSet) { op.apply(wrapper.getDataBaseAccess(), globalSnapshotId); updateCounts(1, 0, 0, 0); } this.putIntoWriteSet(currentSnapshot, localWriteSet); putIntoWriteSet(currentSnapshot, localWriteSet); } updateCounts(0, 0, 1, 0); } private void putIntoWriteSet(final long currentSnapshot, final List<IOperation> localWriteSet) { latestWritesSet.put(currentSnapshot, localWriteSet); } /** * Getter for the service replica. * * @return instance of the service replica */ public ServiceReplica getReplica() { return replica; } /** * Getter for the global snapshotId. * * @return the snapshot id. */ public long getGlobalSnapshotId() { return globalSnapshotId; } /** * Get a copy of the global writeSet. * * @return a hashmap of all the operations with their snapshotId. */ public Map<Long, List<IOperation>> getGlobalWriteSet() { return new LinkedHashMap<>(globalWriteSet); } /** * Get a copy of the global writeSet. * * @return a hashmap of all the operations with their snapshotId. */ public Map<Long, List<IOperation>> getLatestWritesSet() { return latestWritesSet.asMap(); } /** * Shuts down the Server. */ public void terminate() { this.replica.kill(); } /** * Get the kryoFactory of this recoverable. * * @return the factory. */ public KryoFactory getFactory() { return factory; } }
package me.wayne.leetcodetop100.dp; import java.util.Arrays; /** * * <p> * : [10,9,2,5,3,7,101,18] * : 4 * : [2,3,7,101] 4 */ class LC300_LengthOfLIS { /** * Longest Increasing Subsequence */ public int lengthOfLIS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } //dp[i] num[i] int[] dp = new int[nums.length]; Arrays.fill(dp, 1); for (int i = 0; i < dp.length; i++) { //j >= 0 < idp[i][0, i} //nums[i]>nums[j]LISdp[j] + 1 //nums[i]<=nums[j] for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) { dp[i] = Math.max(dp[j] + 1, dp[i]); } } } int max = 0; for (int value : dp) { max = Math.max(max, value); } return max; } }
package mytown.protection; import mytown.MyTown; import mytown.entities.Town; import mytown.entities.flag.FlagType; import mytown.util.BlockPos; import mytown.util.Utils; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class ThermalExpansionProtection extends Protection { public static Class<? extends TileEntity> clsTileActivator; public static Class<? extends TileEntity> clsTileBreaker; @SuppressWarnings("unchecked") public ThermalExpansionProtection() { try { clsTileActivator = (Class<? extends TileEntity>) Class.forName("thermalexpansion.block.device.TileActivator"); clsTileBreaker = (Class<? extends TileEntity>) Class.forName("thermalexpansion.block.device.TileBreaker"); trackedTileEntities.add(clsTileActivator); trackedTileEntities.add(clsTileBreaker); } catch (ClassNotFoundException e) { e.printStackTrace(); MyTown.instance.log.error("Failed to load Thermal Expansion classes!"); } } @SuppressWarnings("unchecked") @Override public boolean checkTileEntity(TileEntity te) { if (clsTileActivator.isAssignableFrom(te.getClass())) { //Get the position at which is pointing at int x = te.xCoord; int y = te.yCoord; int z = te.zCoord; switch (getFacing(te)) { case 0: y break; case 1: y++; break; case 2: z break; case 3: z++; break; case 4: x break; case 5: x++; break; } IInventory inv = (IInventory) te; for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if (stack != null) { if (stack.getItem() instanceof ItemBlock) { Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); if (town != null) { boolean placeFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.modifyBlocks); if (!placeFlag) { town.notifyEveryone(FlagType.modifyBlocks.getLocalizedTownNotification()); return true; } } } else if (!Utils.isBlockWhitelisted(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.useItems) && ProtectionUtils.checkItemUsage(stack, null, new BlockPos(te.xCoord, te.yCoord, te.zCoord, te.getWorldObj().provider.dimensionId))) { return true; } } } // The break flag Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); if (town != null) { boolean breakFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.modifyBlocks); if (!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.modifyBlocks)) { town.notifyEveryone(FlagType.modifyBlocks.getLocalizedTownNotification()); return true; } else { // The activate flag boolean activateFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.activateBlocks); if (!activateFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.activateBlocks)) { town.notifyEveryone(FlagType.activateBlocks.getLocalizedTownNotification()); return true; } } } } else if (clsTileBreaker.isAssignableFrom(te.getClass())) { int x = te.xCoord; int y = te.yCoord; int z = te.zCoord; switch (getFacing(te)) { case 0: y break; case 1: y++; break; case 2: z break; case 3: z++; break; case 4: x break; case 5: x++; break; } Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); if (town != null) { boolean breakFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.modifyBlocks); if (!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.modifyBlocks)) { town.notifyEveryone(FlagType.modifyBlocks.getLocalizedTownNotification()); return true; } } } return false; } @Override public List<FlagType> getFlagTypeForTile(Class<? extends TileEntity> te) { List<FlagType> list = new ArrayList<FlagType>(); if (clsTileActivator.isAssignableFrom(te)) { list.add(FlagType.useItems); list.add(FlagType.activateBlocks); list.add(FlagType.modifyBlocks); list.add(FlagType.modifyBlocks); } else if (clsTileBreaker.isAssignableFrom(te)) { list.add(FlagType.modifyBlocks); } return list; } public static int getFacing(TileEntity te) { try { Method method = clsTileActivator.getMethod("getFacing"); return (Integer) method.invoke(te); } catch (Exception e) { e.printStackTrace(); MyTown.instance.log.error("Failed to get facing for " + te + ", maybe it's a mistake?"); } return -1; } }
package net.amigocraft.pore.impl.entity; import net.amigocraft.pore.impl.block.PoreBlockState; import net.amigocraft.pore.util.converter.MaterialConverter; import net.amigocraft.pore.util.converter.TypeConverter; import org.apache.commons.lang.NotImplementedException; import org.bukkit.entity.Enderman; import org.bukkit.entity.EntityType; import org.bukkit.material.MaterialData; import org.spongepowered.api.item.ItemBlock; public class PoreEnderman extends PoreMonster implements Enderman { private static TypeConverter<org.spongepowered.api.entity.living.monster.Enderman, PoreEnderman> converter; @SuppressWarnings("unchecked") static TypeConverter<org.spongepowered.api.entity.living.monster.Enderman, PoreEnderman> getEndermanConverter() { if (converter == null) { converter = new TypeConverter<org.spongepowered.api.entity.living.monster.Enderman, PoreEnderman>() { @Override protected PoreEnderman convert( org.spongepowered.api.entity.living.monster.Enderman handle) { return new PoreEnderman(handle); } }; } return converter; } protected PoreEnderman(org.spongepowered.api.entity.living.monster.Enderman handle) { super(handle); } @Override public org.spongepowered.api.entity.living.monster.Enderman getHandle() { return (org.spongepowered.api.entity.living.monster.Enderman) super.getHandle(); } /** * Returns a Pore wrapper for the given handle. * If one exists, it will be retrieved; otherwise, a new wrapper instance will be created. * * @param handle The Sponge object to wrap. * @return A Pore wrapper for the given Sponge object. */ public static PoreEnderman of(org.spongepowered.api.entity.living.monster.Enderman handle) { return converter.apply(handle); } //TODO: bridge @Override public EntityType getType() { return EntityType.ENDERMAN; } @Override public MaterialData getCarriedMaterial() { return getHandle().getCarriedBlock().isPresent() ? PoreBlockState.of(getHandle().getCarriedBlock().get()).getData() : null; } @Override public void setCarriedMaterial(MaterialData material) { ItemBlock type = (ItemBlock) MaterialConverter.toItemType(material.getItemType()); if (type != null) { //getHandle().setCarriedBlock(type); //TODO: not sure of how to create the block state throw new NotImplementedException(); } else { throw new UnsupportedOperationException(); } } }
package net.bootsfaces.component.image; import java.io.IOException; import java.util.logging.Logger; import javax.faces.application.ProjectStage; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import net.bootsfaces.component.ajax.AJAXRenderer; import net.bootsfaces.render.CoreRenderer; import net.bootsfaces.render.Responsive; import net.bootsfaces.render.Tooltip; import net.bootsfaces.utils.FacesMessages; @FacesRenderer(componentFamily = "net.bootsfaces.component", rendererType = "net.bootsfaces.component.image.Image") public class ImageRenderer extends CoreRenderer { private static final Logger LOGGER = Logger.getLogger("net.bootsfaces.component.image.ImageRenderer"); @Override public void decode(FacesContext context, UIComponent component) { Image image = (Image) component; if (componentIsDisabledOrReadonly(image)) { return; } decodeBehaviors(context, image); // moved to AJAXRenderer new AJAXRenderer().decode(context, component); } /** * This methods generates the HTML code of the current b:image. * * @param context * the FacesContext. * @param component * the current b:image. * @throws IOException * thrown if something goes wrong when writing the HTML code. */ @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } Image image = (Image) component; ResponseWriter rw = context.getResponseWriter(); String clientId = image.getClientId(); rw.startElement("img", image); Tooltip.generateTooltip(context, image, rw); rw.writeAttribute("id", clientId, "id"); rw.writeURIAttribute("src", getImageSource(context, component), "value"); renderPassThruAttributes(context, image, new String[] { "alt", "height", "lang", "style", "title", "width" }); String styleClass = image.getStyleClass(); if (null == styleClass) styleClass = Responsive.getResponsiveStyleClass(image, false); else styleClass += Responsive.getResponsiveStyleClass(image, false); if (styleClass != null && styleClass.trim().length() > 0) { writeAttribute(rw, "class", styleClass, "styleClass"); } AJAXRenderer.generateBootsFacesAJAXAndJavaScript(FacesContext.getCurrentInstance(), image, rw, false); rw.endElement("img"); Tooltip.activateTooltips(context, image); } /** * <p> * Determine the path value of an image value. * </p> * * @param context * the {@link FacesContext} for the current request. * @param component * the component to obtain the image information from * @return the encoded path to the image source */ public static String getImageSource(FacesContext context, UIComponent component) { Image image = (Image) component; ResourceHandler handler = context.getApplication().getResourceHandler(); String resourceName = image.getName(); String value = image.getValue(); if (value != null && value.length() > 0) { if (resourceName != null && image.getLibrary() != null) { if (FacesContext.getCurrentInstance().isProjectStage(ProjectStage.Development)) { LOGGER.warning( "Please use either the 'value' attribute of b:image, or the 'name' and 'library' attribute pair. If all three attributes are provided, BootsFaces uses the 'value' attributes, ignoring both 'name' and 'library'."); } } if (handler.isResourceURL(value)) { return value; } else { value = context.getApplication().getViewHandler().getResourceURL(context, value); return (context.getExternalContext().encodeResourceURL(value)); } } String library = image.getLibrary(); Resource res = handler.createResource(resourceName, library); if (res == null) { if (context.isProjectStage(ProjectStage.Development)) { String msg = "Unable to find resource " + resourceName; FacesMessages.error(component.getClientId(context), msg, msg); } return "RES_NOT_FOUND"; } else { return (context.getExternalContext().encodeResourceURL(res.getRequestPath())); } } }
package net.bramp.ffmpeg.builder; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import net.bramp.ffmpeg.modelmapper.Mapper; import net.bramp.ffmpeg.options.AudioEncodingOptions; import net.bramp.ffmpeg.options.EncodingOptions; import net.bramp.ffmpeg.options.MainEncodingOptions; import net.bramp.ffmpeg.options.VideoEncodingOptions; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.math.Fraction; import org.apache.commons.lang3.tuple.ImmutablePair; import java.net.URI; import java.util.List; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static net.bramp.ffmpeg.FFmpegUtils.millisecondsToString; import static com.google.common.base.Preconditions.checkNotNull; /** * Builds a representation of a single output/encoding setting */ public class FFmpegOutputBuilder implements Cloneable { final private static String DEVNULL = SystemUtils.IS_OS_WINDOWS ? "NUL" : "/dev/null"; final private static List<String> rtps = ImmutableList.of("rtsp", "rtp", "rtmp"); final private static List<String> udpTcp = ImmutableList.of("udp", "tcp"); FFmpegBuilder parent; /** * Output filename or uri. Only one may be set */ public String filename; public URI uri; public String format; public Long startOffset; // in millis public Long duration; // in millis public final List<String> meta_tags = new ArrayList<>(); public boolean audio_enabled = true; public String audio_codec; public int audio_channels; public int audio_sample_rate; public String audio_bit_depth; public long audio_bit_rate; public int audio_quality; public String audio_bit_stream_filter; public boolean video_enabled = true; public String video_codec; public boolean video_copyinkf = false; public Fraction video_frame_rate; public int video_width; public int video_height; public String video_movflags; public long video_bit_rate; public Integer video_frames; public String video_preset; public String video_filter; public String video_filter_complex; public String video_bit_stream_filter; public boolean subtitle_enabled = true; public final List<String> extra_args = new ArrayList<>(); public FFmpegBuilder.Strict strict = FFmpegBuilder.Strict.NORMAL; public long targetSize = 0; // in bytes public long pass_padding_bitrate = 1024; // in bits per second public boolean throwWarnings = true; // TODO Either delete this, or apply it consistently /** * Checks if the URI is valid for streaming to * * @param uri * @return */ public static URI checkValidStream(URI uri) { String scheme = checkNotNull(uri).getScheme(); scheme = checkNotNull(scheme, "URI is missing a scheme").toLowerCase(); if (rtps.contains(scheme)) { return uri; } if (udpTcp.contains(scheme)) { if (uri.getPort() == -1) { throw new IllegalArgumentException("must set port when using udp or tcp scheme"); } return uri; } throw new IllegalArgumentException("not a valid output URL, must use rtp/tcp/udp scheme"); } public FFmpegOutputBuilder() {} protected FFmpegOutputBuilder(FFmpegBuilder parent, String filename) { this.parent = checkNotNull(parent); this.filename = checkNotNull(filename); } protected FFmpegOutputBuilder(FFmpegBuilder parent, URI uri) { this.parent = checkNotNull(parent); this.uri = checkValidStream(uri); } public FFmpegOutputBuilder useOptions(EncodingOptions opts) { Mapper.map(opts, this); return this; } public FFmpegOutputBuilder useOptions(MainEncodingOptions opts) { Mapper.map(opts, this); return this; } public FFmpegOutputBuilder useOptions(AudioEncodingOptions opts) { Mapper.map(opts, this); return this; } public FFmpegOutputBuilder useOptions(VideoEncodingOptions opts) { Mapper.map(opts, this); return this; } public FFmpegOutputBuilder disableVideo() { this.video_enabled = false; return this; } public FFmpegOutputBuilder disableAudio() { this.audio_enabled = false; return this; } public FFmpegOutputBuilder disableSubtitle() { this.subtitle_enabled = false; return this; } public FFmpegOutputBuilder setFilename(String filename) { this.filename = checkNotNull(filename); return this; } public String getFilename() { return filename; } public FFmpegOutputBuilder setUri(URI uri) { this.uri = checkValidStream(uri); return this; } public URI getUri() { return uri; } public FFmpegOutputBuilder setFormat(String format) { this.format = checkNotNull(format); return this; } public FFmpegOutputBuilder setVideoBitRate(long bit_rate) { Preconditions.checkArgument(bit_rate > 0, "bitrate must be positive"); this.video_enabled = true; this.video_bit_rate = bit_rate; return this; } public FFmpegOutputBuilder setVideoCodec(String codec) { this.video_enabled = true; this.video_codec = checkNotNull(codec); return this; } public FFmpegOutputBuilder setVideoCopyInkf(boolean copyinkf) { this.video_enabled = true; this.video_copyinkf = copyinkf; return this; } public FFmpegOutputBuilder setVideoMovFlags(String movflags) { this.video_enabled = true; this.video_movflags = checkNotNull(movflags); return this; } public FFmpegOutputBuilder setVideoFrameRate(Fraction frame_rate) { this.video_enabled = true; this.video_frame_rate = checkNotNull(frame_rate); return this; } public FFmpegOutputBuilder setVideoBitStreamFilter(String filter) { Preconditions .checkArgument(!Strings.isNullOrEmpty(filter), "filter should be declared by name"); this.video_bit_stream_filter = filter; return this; } /** * Set the video frame rate in terms of frames per interval. For example 24fps would be 24/1, * however NTSC TV at 23.976fps would be 24000 per 1001 * * @param frames Number of frames * @param per Number of seconds * @return */ public FFmpegOutputBuilder setVideoFrameRate(int frames, int per) { return setVideoFrameRate(Fraction.getFraction(frames, per)); } public FFmpegOutputBuilder setVideoFrameRate(double frame_rate) { return setVideoFrameRate(Fraction.getFraction(frame_rate)); } /** * Set the number of video frames to record. * * @param frames * @return this */ public FFmpegOutputBuilder setFrames(int frames) { this.video_enabled = true; this.video_frames = frames; return this; } public FFmpegOutputBuilder setVideoPreset(String preset) { this.video_enabled = true; this.video_preset = checkNotNull(preset); return this; } protected static boolean isValidSize(int widthOrHeight) { return widthOrHeight > 0 || widthOrHeight == -1; } public FFmpegOutputBuilder setVideoWidth(int width) { Preconditions.checkArgument(isValidSize(width), "Width must be -1 or greater than zero"); this.video_enabled = true; this.video_width = width; return this; } public FFmpegOutputBuilder setVideoHeight(int height) { Preconditions.checkArgument(isValidSize(height), "Height must be -1 or greater than zero"); this.video_enabled = true; this.video_height = height; return this; } public FFmpegOutputBuilder setVideoResolution(int width, int height) { Preconditions.checkArgument(isValidSize(width) && isValidSize(height), "Both width and height must be -1 or greater than zero"); this.video_enabled = true; this.video_width = width; this.video_height = height; return this; } /** * Sets Video Filter TODO Build a fluent Filter builder * * @param filter * @return this */ public FFmpegOutputBuilder setVideoFilter(String filter) { this.video_enabled = true; this.video_filter = checkNotNull(filter); return this; } public FFmpegOutputBuilder setComplexVideoFilter(String filter) { this.video_enabled = true; this.video_filter_complex = checkNotNull(filter); return this; } /** * Add metadata on output streams. Which keys are possible depends on the used codec. * * @param key Metadata key, e.g. "comment" * @param value Value to set for key * @return this */ public FFmpegOutputBuilder addMetaTag(String key, String value) { checkNotNull(key, "Key may not be null"); checkNotNull(value, "Value may not be null"); meta_tags.add(key + "=" + value.replace("\"", "")); return this; } public FFmpegOutputBuilder setAudioCodec(String codec) { this.audio_enabled = true; this.audio_codec = checkNotNull(codec); return this; } public FFmpegOutputBuilder setAudioChannels(int channels) { Preconditions.checkArgument(channels > 0, "channels must be positive"); this.audio_enabled = true; this.audio_channels = channels; return this; } /** * Sets the Audio Sample Rate, for example 44_000 * * @param sample_rate * @return this */ public FFmpegOutputBuilder setAudioSampleRate(int sample_rate) { Preconditions.checkArgument(sample_rate > 0, "sample rate must be positive"); this.audio_enabled = true; this.audio_sample_rate = sample_rate; return this; } /** * Sets the Audio Bit Depth. Samples given in the FFmpeg.AUDIO_DEPTH_* constants. * * @param bit_depth * @return this */ public FFmpegOutputBuilder setAudioBitDepth(String bit_depth) { Preconditions.checkNotNull(bit_depth); this.audio_enabled = true; this.audio_bit_depth = bit_depth; return this; } /** * Sets the Audio bitrate * * @param bit_rate * @return this */ public FFmpegOutputBuilder setAudioBitRate(long bit_rate) { Preconditions.checkArgument(bit_rate > 0, "bitrate must be positive"); this.audio_enabled = true; this.audio_bit_rate = bit_rate; return this; } public FFmpegOutputBuilder setAudioQuality(int quality) { Preconditions.checkArgument(quality >= 1 && quality <= 5, "quality must be in the range 1..5"); this.audio_enabled = true; this.audio_quality = quality; return this; } public FFmpegOutputBuilder setAudioBitStreamFilter(String filter) { Preconditions .checkArgument(!Strings.isNullOrEmpty(filter), "filter should be declared by name"); this.audio_bit_stream_filter = filter; return this; } /** * Target output file size (in bytes) * * @param targetSize * @return this */ public FFmpegOutputBuilder setTargetSize(long targetSize) { Preconditions.checkArgument(targetSize > 0, "target size must be positive"); this.targetSize = targetSize; return this; } /** * Decodes but discards input until the duration * * @param duration * @param units * @return this */ public FFmpegOutputBuilder setStartOffset(long duration, TimeUnit units) { checkNotNull(duration); checkNotNull(units); this.startOffset = units.toMillis(duration); return this; } /** * Stop writing the output after its duration reaches duration * * @param duration * @param units * @return this */ public FFmpegOutputBuilder setDuration(long duration, TimeUnit units) { checkNotNull(duration); checkNotNull(units); this.duration = units.toMillis(duration); return this; } public FFmpegOutputBuilder setStrict(FFmpegBuilder.Strict strict) { this.strict = checkNotNull(strict); return this; } /** * When doing multi-pass we add a little extra padding, to ensure we reach our target * * @param bitrate * @return this */ public FFmpegOutputBuilder setPassPaddingBitrate(long bitrate) { Preconditions.checkArgument(bitrate > 0, "bitrate must be positive"); this.pass_padding_bitrate = bitrate; return this; } /** * Add additional ouput arguments (for flags which aren't currently supported). * * @param values */ public FFmpegOutputBuilder addExtraArgs(String... values) { checkArgument(values.length > 0, "One or more values must be supplied"); for (String value : values) { extra_args.add(checkNotNull(value)); } return this; } /** * Finished with this output * * @return the parent FFmpegBuilder */ public FFmpegBuilder done() { Preconditions.checkState(parent != null, "Can not call done without parent being set"); return parent; } public EncodingOptions buildOptions() { // TODO When/if modelmapper supports @ConstructorProperties, we map this // object, instead of doing new XXX(...) return new EncodingOptions(new MainEncodingOptions(format, startOffset, duration), new AudioEncodingOptions(audio_enabled, audio_codec, audio_channels, audio_sample_rate, audio_bit_depth, audio_bit_rate, audio_quality), new VideoEncodingOptions( video_enabled, video_codec, video_frame_rate, video_width, video_height, video_bit_rate, video_frames, video_filter, video_preset)); } protected List<String> build(int pass) { Preconditions.checkState(parent != null, "Can not build without parent being set"); ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); if (targetSize > 0) { checkState(parent.inputs.size() == 1, "Target size does not support multiple inputs"); String firstInput = parent.inputs.get(0); FFmpegProbeResult input = parent.inputProbes.get(firstInput); checkState(input != null, "Target size must be used with setInput(FFmpegProbeResult)"); // TODO factor in start time and/or number of frames double durationInSeconds = input.format.duration; long totalBitRate = (long) Math.floor((targetSize * 8) / durationInSeconds) - pass_padding_bitrate; // TODO Calculate audioBitRate if (video_enabled && video_bit_rate == 0) { // Video (and possibly audio) long audioBitRate = audio_enabled ? audio_bit_rate : 0; video_bit_rate = totalBitRate - audioBitRate; } else if (audio_enabled && audio_bit_rate == 0) { // Just Audio audio_bit_rate = totalBitRate; } } if (strict != FFmpegBuilder.Strict.NORMAL) { args.add("-strict").add(strict.toString()); } if (!Strings.isNullOrEmpty(format)) { args.add("-f").add(format); } if (startOffset != null) { args.add("-ss").add(millisecondsToString(startOffset)); } if (duration != null) { args.add("-t").add(millisecondsToString(duration)); } for (String meta : meta_tags) { args.add("-metadata").add("\"" + meta + "\""); } if (video_enabled) { if (video_frames != null) { args.add("-vframes").add(String.format("%d", video_frames)); } if (!Strings.isNullOrEmpty(video_codec)) { args.add("-vcodec").add(video_codec); } if (video_copyinkf) { args.add("-copyinkf"); } if (!Strings.isNullOrEmpty(video_movflags)) { args.add("-movflags").add(video_movflags); } if (video_width != 0 && video_height != 0) { args.add("-s").add(String.format("%dx%d", video_width, video_height)); } if (video_frame_rate != null) { // args.add("-r").add(String.format("%2f", video_frame_rate)); args.add("-r").add(video_frame_rate.toString()); } if (video_bit_rate > 0) { args.add("-b:v").add(String.format("%d", video_bit_rate)); } if (!Strings.isNullOrEmpty(video_preset)) { args.add("-vpre").add(video_preset); } if (!Strings.isNullOrEmpty(video_filter)) { checkState(parent.inputs.size() == 1, "Video filter only works with one input, instead use setVideoFilterComplex(..)"); args.add("-vf").add(video_filter); } if (!Strings.isNullOrEmpty(video_filter_complex)) { args.add("-filter_complex").add(video_filter_complex); } if (!Strings.isNullOrEmpty(video_bit_stream_filter)) { args.add("-bsf:v", video_bit_stream_filter); } } else { args.add("-vn"); } if (audio_enabled && pass != 1) { if (!Strings.isNullOrEmpty(audio_codec)) { args.add("-acodec").add(audio_codec); } if (audio_channels > 0) { args.add("-ac").add(String.format("%d", audio_channels)); } if (audio_sample_rate > 0) { args.add("-ar").add(String.format("%d", audio_sample_rate)); } if (!Strings.isNullOrEmpty(audio_bit_depth)) { args.add("-sample_fmt").add(audio_bit_depth); } if (audio_bit_rate > 0 && audio_quality > 0 && throwWarnings) { // I'm not sure, but it seems audio_quality overrides // audio_bit_rate, so don't allow both throw new IllegalStateException("Only one of audio_bit_rate and audio_quality can be set"); } if (audio_bit_rate > 0) { args.add("-b:a").add(String.format("%d", audio_bit_rate)); } if (audio_quality > 0) { args.add("-aq").add(String.format("%d", audio_quality)); } if (!Strings.isNullOrEmpty(audio_bit_stream_filter)) { args.add("-bsf:a", audio_bit_stream_filter); } } else { args.add("-an"); } if (!subtitle_enabled) args.add("-sn"); args.addAll(extra_args); if (filename != null && uri != null) { throw new IllegalStateException("Only one of filename and uri can be set"); } // Output if (pass == 1) { args.add(DEVNULL); } else if (filename != null) { args.add(filename); } else if (uri != null) { args.add(uri.toString()); } else { assert (false); } return args.build(); } }
package net.davidlauzon.logshaper.event; import net.davidlauzon.logshaper.EventJournal; import net.davidlauzon.logshaper.event.attribute.Attribute; import net.davidlauzon.logshaper.event.attribute.CounterAttribute; import net.davidlauzon.logshaper.event.attribute.TextAttribute; import java.util.LinkedHashMap; import java.util.Map; public class DefaultEvent implements Event { private EventJournal journal; private Event parent; private String eventName; private int depth; private long eventStartedAtMS; private long eventEndedAtMS; private EventState state; private Map<String,Attribute> attributes; /** * (Constructor reserved for internal use). See @EventJournal for how to initialize the root event * * @param parent The parent event that triggered this new event. * @param depth The level of depth from the root event (0 if no parent) * @param name The name of the Event */ public DefaultEvent(EventJournal journal, String name, int depth, Event parent) { this.journal = journal; this.eventName = name; this.depth = depth; this.parent = parent; this.attributes = new LinkedHashMap<>(); eventStartedAtMS = System.currentTimeMillis(); state = EventState.NEW; } /** * Starts a new child event of the current event * * @param name The name of the event * @return the event newly created */ @Override public Event createChild(String name) { return new DefaultEvent( journal, name, depth + 1, this ); } /** * Creates or updates a counter with the given name and adds it the specified value. * * The Counter is automatically propagated recursively to all the parents. * * To decrement the counter, just send a negative value. * * Exemples: "DB.Duration", "Alfresco.Duration", "BIRT.Duration", "JSON.Parsing.Duration", "ComputingBudget.Duration" * * @param name The name of the counter. * @param value The value to add to the counter. * @return Event The current counter. */ @Override public Event count(String name, long value) { CounterAttribute attr = ((CounterAttribute) attributes.get(name)); if (attr == null) attributes.put( name, new CounterAttribute(value) ); else attr.increment(value); // propagate the counter to the parents recursively if (parent != null) parent.count(name, value); return this; } /** * Sets an attribute of this event. * * The scope is always local to the event (e.g. is it NOT propagated to the parents like the counters are). * * Exemples: User, SessionId, IP, UserAction, URL, Method, UserAgent * * @param name The attribute name * @param value The attribute value * @return Event this event */ @Override public Event attr(String name, String value) { this.attributes.put( name, new TextAttribute(value) ); return this; } @Override public Event publishTrace() { if (state == EventState.NEW) start(); journal.publishTrace(this); return this; } @Override public Event publishDebug() { if (state == EventState.NEW) start(); journal.publishDebug(this); return this; } @Override public Event publishInfo() { if (state == EventState.NEW) start(); journal.publishInfo(this); return this; } @Override public Event publishWarn() { if (state == EventState.NEW) start(); journal.publishWarn(this); return this; } @Override public Event publishError() { if (state == EventState.NEW) start(); journal.publishError(this); return this; } /** * Records the timestamp where this event occurred. * * No need to handle this manually, unless you don't want to broadcast the start event. * * @return Event this event */ @Override public Event start() { state = EventState.STARTED; eventStartedAtMS = System.currentTimeMillis(); return this; } /** * Records the timestamp where this event occurred AND returns the parent of this event. * * @return Event the parent of this event */ @Override public Event stop() { eventEndedAtMS = System.currentTimeMillis(); state = EventState.ENDED; // Accumulating this event's duration into the parent's scope if (parent != null) parent.count(getDurationCounterName(), durationInMS()); return this; } protected String getDurationCounterName() { return this.eventName.replace(' ', '.') + ".MS"; } /** * Getter of attributes * * @return the list of attributes */ @Override public Map<String,Attribute> attributes() { return attributes; } /** * @return duration of the event in milliseconds, or 0 if non-started/non-stopped. */ @Override public long durationInMS() { if (eventStartedAtMS > 0 && eventEndedAtMS > 0) return (eventEndedAtMS - eventStartedAtMS); else return 0; } @Override public Event parent() { return parent; } @Override public String eventName() { return eventName; } @Override public EventState state() { return state; } @Override public int depth() { return depth; } }
package net.liquidpineapple.pang.objects; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Array; import java.util.ArrayList; public class ScoreSystem { private static int score; @Getter private static ArrayList<ScoreToken> Places; public ScoreSystem() { score = 0; //These are from right to left. Places = new ArrayList<>(9); Places.add(new ScoreToken(261,5)); Places.add(new ScoreToken(229,5)); Places.add(new ScoreToken(197,5)); Places.add(new ScoreToken(165,5)); Places.add(new ScoreToken(133,5)); Places.add(new ScoreToken(101,5)); Places.add(new ScoreToken(69,5)); Places.add(new ScoreToken(37,5)); Places.add(new ScoreToken(5,5)); displayscore(); } public static void AddScore(int scoreIn) { if(score != 999999999){ score += scoreIn; if(score > 999999999){score = 999999999;} } } public void displayscore() { int calcscore = score; int i = 0; while(calcscore>0){ Places.get(i).SetScoreToken(calcscore % 10); calcscore /= 10; i++; } } public int getScore(){ return score; } }
package net.nordu.mdx.index.neo4j; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.utils.MetadataUtils; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import org.neo4j.index.IndexService; import org.oasis.saml.metadata.EntityDescriptorType; import org.springframework.beans.factory.annotation.Autowired; public class Neo4JMetadataIndex implements MetadataIndex { private static final String ENTITY_ID = "entity.id"; private static final String ATTRIBUTE_VALUE = "attribute.value"; private static final String ATTRIBUTE_NAME = "attribute.name"; private static final String ATTRIBUTE_NAME_FORMAT = "attribute.nameFormat"; private static final String NF_UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"; private static final String NF_NONE = ""; private static final String NF_INTERNAL = "internal"; private static final String ENTITY_LM = "entity.lastModified"; private static final Log log = LogFactory.getLog(Neo4JMetadataIndex.class); @Autowired private GraphDatabaseService neoService; @Autowired private IndexService indexService; public GraphDatabaseService getNeoService() { return neoService; } @Override public Iterable<String> find(String[] tags) throws Exception { ArrayList<String> ids = new ArrayList<String>(); for (Node n: indexService.getNodes(ENTITY_ID, tags[0])) { if (hasAttributes(n,NF_NONE,"tags",tags,1)) ids.add((String)n.getProperty(ENTITY_ID)); } if (ids.size() > 0) return ids; for (Node n: getNodesByAttribute(NF_NONE, "tags", tags[0])) { if (hasAttributes(n,NF_NONE,"tags",tags,0)) ids.add((String)n.getProperty(ENTITY_ID)); } return ids; } private void _set(Node n, String key, Object value) { n.setProperty(key, value); indexService.index(n,key,value); } private boolean hasAttributes(Node entityNode, String nameFormat, String name, String[] values, int offset) { for (int i = offset; i < values.length; i++) { if (!hasAttribute(entityNode,nameFormat,name,values[i])) return false; } return true; } private boolean hasAttribute(Node entityNode, String nameFormat, String name,String value) { for (Relationship r : entityNode.getRelationships(MetadataRelationshipTypes.HAS_ATTRIBUTE,Direction.OUTGOING)) { Node vn = r.getEndNode(); if (isAttribute(r,nameFormat,name) && vn.getProperty(ATTRIBUTE_VALUE).equals(value)) return true; } return false; } private boolean isAttribute(Relationship r, String nameFormat, String name) { return r.getProperty(ATTRIBUTE_NAME_FORMAT).equals(nameFormat) && r.getProperty(ATTRIBUTE_NAME).equals(name); } @Override public void update(String id,EntityDescriptorType entity) throws Exception { assert(id != null && id.length() > 0); System.err.println(id); System.err.println(entity.getEntityID()); Transaction tx = neoService.beginTx(); try { Node entityNode = indexService.getSingleNode(ENTITY_ID, id); if (entityNode == null) { entityNode = neoService.createNode(); _set(entityNode,ENTITY_ID,id); } System.err.println(entityNode); Date now = new Date(); entityNode.setProperty(ENTITY_LM, new Long(now.getTime())); /* * TODO: make this a bit more effective perhaps - not sure if it is worth it though... */ for (Relationship r : entityNode.getRelationships(MetadataRelationshipTypes.HAS_ATTRIBUTE,Direction.OUTGOING)) { r.delete(); } String entityID = entity.getEntityID(); addAttribute(entityNode,NF_INTERNAL,"entityID",entityID); addAttribute(entityNode,NF_INTERNAL,"entityIDHash","{sha1}"+DigestUtils.shaHex(entityID)); final Node n = entityNode; MetadataUtils.withAttributes(entity, new MetadataUtils.AttributeCallback() { @Override public void attribute(String nameFormat, String name, String value) { addAttribute(n,nameFormat,name,value); } }); addAttribute(entityNode,NF_NONE, "tags", "all"); tx.success(); } finally { tx.finish(); } } @Override public void remove(String id) { assert(id != null && id.length() > 0); Transaction tx = neoService.beginTx(); try { Node entityNode = indexService.getSingleNode(ENTITY_ID, id); if (entityNode != null) { for (Relationship r : entityNode.getRelationships()) { r.delete(); } entityNode.delete(); } //TODO: do reference counting on the value nodes and remove non-used ones. tx.success(); } finally { tx.finish(); } } @Override public Iterable<String> listIDs() { ArrayList<String> ids = new ArrayList<String>(); for (Node n : getNodesByAttribute(NF_NONE, "tags", "all")) { String id = (String)n.getProperty(ENTITY_ID); assert(id != null && id.length() > 0); ids.add(id); } return ids; } private Relationship getAttributeValueRelationship(Node entityNode, String nameFormat, String name, Node valueNode) { for (Relationship r : entityNode.getRelationships(MetadataRelationshipTypes.HAS_ATTRIBUTE,Direction.OUTGOING)) { if (r.getEndNode().equals(valueNode) && isAttribute(r,nameFormat,name)) return r; } return null; } private void addAttribute(Node entityNode, String nameFormat, String name, String value) { log.debug(entityNode+": "+nameFormat+"["+name+"]="+value); Node valueNode = indexService.getSingleNode(ATTRIBUTE_VALUE, value); if (valueNode == null) { valueNode = neoService.createNode(); _set(valueNode,ATTRIBUTE_VALUE, value); } if (getAttributeValueRelationship(entityNode, nameFormat, name, valueNode) == null) { Relationship r = entityNode.createRelationshipTo(valueNode, MetadataRelationshipTypes.HAS_ATTRIBUTE); r.setProperty(ATTRIBUTE_NAME_FORMAT, nameFormat); r.setProperty(ATTRIBUTE_NAME, name); } } /* * This is not a directory server. The attribute lookup is optimized for a sparse attribute-value set */ //@Cacheable(cacheName = "getNodesByAttributeCache") public Collection<Node> getNodesByAttribute(String nameFormat, String name, String value) { ArrayList<Node> nodes = new ArrayList<Node>(); for (Node n : indexService.getNodes(ATTRIBUTE_VALUE, value)) { for (Relationship r: n.getRelationships(MetadataRelationshipTypes.HAS_ATTRIBUTE, Direction.INCOMING)) { if (r.getProperty(ATTRIBUTE_NAME_FORMAT).equals(nameFormat) && r.getProperty(ATTRIBUTE_NAME).equals(name)) nodes.add(r.getStartNode()); } } return nodes; } @Override public Calendar lastModified(String id) { Calendar t = Calendar.getInstance(); long ts = 0; Node entityNode = indexService.getSingleNode(ENTITY_ID, id); if (entityNode == null) throw new IllegalArgumentException("No such entity in index: "+id); if (entityNode.hasProperty(ENTITY_LM)) { ts = ((Long)entityNode.getProperty(ENTITY_LM, new Long(0))).longValue(); } t.setTimeInMillis(ts); return t; } @Override public boolean exists(String id) { Node entityNode = indexService.getSingleNode(ENTITY_ID, id); return entityNode != null; } }
package net.sf.jabref.model.entry; import java.util.Arrays; import java.util.List; public class IEEETranEntryTypes { /** * Electronic entry type for internet references * <p> * Required fields: * Optional fields: author, month, year, title, language, howpublished, organization, address, note, url */ public static final EntryType ELECTRONIC = new BibtexEntryType() { { addAllOptional("author", "month", "year", "title", "language", "howpublished", "organization", "address", "note", "url"); } @Override public String getName() { return "Electronic"; } }; /** * Special entry type that can be used to externally control some aspects of the bibliography style. */ public static final EntryType IEEETRANBSTCTL = new BibtexEntryType() { { addAllOptional("ctluse_article_number", "ctluse_paper", "ctluse_forced_etal", "ctluse_url", "ctlmax_names_forced_etal", "ctlnames_show_etal", "ctluse_alt_spacing", "ctlalt_stretch_factor", "ctldash_repeated_names", "ctlname_format_string", "ctlname_latex_cmd", "ctlname_url_prefix"); } @Override public String getName() { return "IEEEtranBSTCTL"; } }; public static final String[] IEEETRANBSTCTL_YES_NO_FIELDS = {"ctluse_article_number", "ctluse_paper", "ctluse_url", "ctluse_forced_etal", "ctluse_alt_spacing", "ctldash_repeated_names"}; public static final String[] IEEETRANBSTCTL_NUMERIC_FIELDS = {"ctlmax_names_forced_etal", "ctlnames_show_etal", "ctlalt_stretch_factor"}; /** * The periodical entry type is used for journals and magazines. * <p> * Required fields: title, year * Optional fields: editor, language, series, volume, number, organization, month, note, url */ public static final EntryType PERIODICAL = new BibtexEntryType() { { addAllRequired("title", "year"); addAllOptional("editor", "language", "series", "volume", "number", "organization", "month", "note", "url"); } @Override public String getName() { return "Periodical"; } }; /** * Entry type for patents. * <p> * Required fields: nationality, number, year or yearfiled * Optional fields: author, title, language, assignee, address, type, number, day, dayfiled, month, monthfiled, note, url */ public static final EntryType PATENT = new BibtexEntryType() { { addAllRequired("nationality", "number", "year/yearfiled"); addAllOptional("author", "title", "language", "assignee", "address", "type", "number", "day", "dayfiled", "month", "monthfiled", "note", "url"); } @Override public String getName() { return "Patent"; } }; /** * The standard entry type is used for proposed or formally published standards. * <p> * Required fields: title, organization or institution * Optional fields: author, language, howpublished, type, number, revision, address, month, year, note, url */ public static final EntryType STANDARD = new BibtexEntryType() { { addAllRequired("title", "organization/institution"); addAllOptional("author", "language", "howpublished", "type", "number", "revision", "address", "month", "year", "note", "url"); } @Override public String getName() { return "Standard"; } }; public static final List<EntryType> ALL = Arrays.asList(ELECTRONIC, IEEETRANBSTCTL, PERIODICAL, PATENT, STANDARD); }
package net.winroad.wrdoclet.builder; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import net.winroad.wrdoclet.AbstractConfiguration; import net.winroad.wrdoclet.data.APIParameter; import net.winroad.wrdoclet.data.ParameterOccurs; import net.winroad.wrdoclet.data.ParameterType; import net.winroad.wrdoclet.data.RequestMapping; import net.winroad.wrdoclet.data.WRDoc; import net.winroad.wrdoclet.utils.LoggerFactory; import net.winroad.wrdoclet.utils.UniversalNamespaceCache; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.Parameter; import com.sun.javadoc.Tag; import com.sun.tools.doclets.internal.toolkit.Configuration; public class DubboDocBuilder extends AbstractServiceDocBuilder { protected LinkedList<String> dubboInterfaces = null; public DubboDocBuilder(WRDoc wrDoc) { super(wrDoc); this.logger = LoggerFactory.getLogger(this.getClass()); dubboInterfaces = this.getDubboInterfaces(); } @Override protected void processOpenAPIClasses(ClassDoc[] classes, Configuration configuration) { LinkedList<String> annotationDubboInterfaces = getAnnotationDubboInterfaces(classes); dubboInterfaces.addAll(annotationDubboInterfaces); super.processOpenAPIClasses(classes, configuration); } protected LinkedList<String> getAnnotationDubboInterfaces(ClassDoc[] classes) { LinkedList<String> result = new LinkedList<String>(); for (int i = 0; i < classes.length; i++) { // implementation class which used com.alibaba.dubbo.config.annotation.Service if(isClassDocAnnotatedWith(classes[i],"Service")) { for(ClassDoc classDoc : classes[i].interfaces()) { result.add(classDoc.qualifiedName()); } } } return result; } protected LinkedList<String> getDubboInterfaces() { LinkedList<String> result = new LinkedList<String>(); try { Document dubboConfig = readXMLConfig(((AbstractConfiguration) this.wrDoc .getConfiguration()).dubboconfigpath); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new UniversalNamespaceCache(dubboConfig, false)); NodeList serviceNodes = (NodeList) xPath.evaluate( "//:beans/dubbo:service", dubboConfig, XPathConstants.NODESET); for (int i = 0; i < serviceNodes.getLength(); i++) { Node node = serviceNodes.item(i); String ifc = getAttributeValue(node, "interface"); if (ifc != null) result.add(ifc); } } catch (Exception e) { this.logger.error(e); } this.logger.debug("dubbo interface list:"); for (String s : result) { this.logger.debug("interface: " + s); } return result; } @Override protected RequestMapping parseRequestMapping(MethodDoc methodDoc) { RequestMapping mapping = new RequestMapping(); mapping.setUrl(methodDoc.toString().replaceFirst( methodDoc.containingClass().qualifiedName() + ".", "")); mapping.setTooltip(methodDoc.containingClass().simpleTypeName()); mapping.setContainerName(methodDoc.containingClass().simpleTypeName()); return mapping; } @Override protected APIParameter getOutputParam(MethodDoc methodDoc) { APIParameter apiParameter = null; if (methodDoc.returnType() != null) { apiParameter = new APIParameter(); apiParameter.setParameterOccurs(ParameterOccurs.REQUIRED); apiParameter.setType(this.getTypeName(methodDoc.returnType(), false)); for (Tag tag : methodDoc.tags("return")) { apiParameter.setDescription(tag.text()); } HashSet<String> processingClasses = new HashSet<String>(); apiParameter.setFields(this.getFields(methodDoc.returnType(), ParameterType.Response, processingClasses)); apiParameter.setHistory(this.getModificationHistory(methodDoc .returnType())); } return apiParameter; } @Override protected List<APIParameter> getInputParams(MethodDoc methodDoc) { List<APIParameter> paramList = new LinkedList<APIParameter>(); Parameter[] methodParameters = methodDoc.parameters(); if (methodParameters.length != 0) { for (int i = 0; i < methodParameters.length; i++) { APIParameter p = new APIParameter(); p.setName(methodParameters[i].name()); p.setType(this.getTypeName(methodParameters[i].type(), false)); p.setDescription(this.getParamComment(methodDoc, methodParameters[i].name())); HashSet<String> processingClasses = new HashSet<String>(); p.setFields(this.getFields(methodParameters[i].type(), ParameterType.Request, processingClasses)); paramList.add(p); } } return paramList; } @Override protected boolean isServiceInterface(ClassDoc classDoc) { return classDoc.isInterface() && dubboInterfaces.contains(classDoc.qualifiedName()); } @Override protected int isAPIAuthNeeded(String url) { //no authentication return -1; } }
package online.pizzacrust.lukkitplus.api; import org.luaj.vm2.LuaNumber; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import org.luaj.vm2.lib.jse.CoerceJavaToLua; import org.luaj.vm2.lib.jse.CoerceLuaToJava; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import online.pizzacrust.lukkitplus.environment.FunctionController; import online.pizzacrust.lukkitplus.environment.LuaLibrary; import static org.luaj.vm2.lib.jse.CoerceLuaToJava.coerce; public class LuaAccessor extends LuaLibrary { private final Object object; public Object getObject() { return this.object; } public static LuaValue convertType(Object object) { return CoerceJavaToLua.coerce(object); } public LuaAccessor(Object object) { this.object = object; newFunction(new SetPrimitiveField(object)); newFunction(new InvokeVoidMethod(object)); newFunction(new AccessPrimitiveField(object)); newFunction(new AccessJavaTypeField(object)); newFunction(new AccessJavaTypeMethod(object)); newFunction(new AccessPrimitiveMethod(object)); } public static class SetPrimitiveField implements FunctionController { private final Object object; public SetPrimitiveField(Object object) { this.object = object; } @Override public String getName() { return "setPrimitiveField"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); Object value = fromType(parameters.arg(2)); for (Field field : object.getClass().getFields()) { if (field.getName().equals(name)) { field.setAccessible(true); try { field.set(object, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return LuaValue.NIL; } } public static Object fromType(LuaValue luaValue) { if (luaValue.isboolean()) { return coerce(luaValue, Boolean.class); } if (luaValue.isint()) { return coerce(luaValue, Integer.class); } if (luaValue.isnumber()) { return coerce(luaValue, Double.class); } if (luaValue.isstring()) { return LuaLogger.colorString(luaValue.tojstring()); } return null; } public static List<Class<?>> convertObjectsToTypes(List<Object> object) { List<Class<?>> classes = new ArrayList<>(); for (Object aObject : object) { classes.add(aObject.getClass()); } return classes; } public static Class[] toArray(List<Class<?>> classes) { return classes.toArray(new Class[classes.size()]); } public static class InvokeVoidMethod implements FunctionController { private final Object object; public InvokeVoidMethod(Object object) { this.object = object; } @Override public String getName() { return "invokeVoidMethod"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); List<Object> objParameters = new ArrayList<Object>(); if (parameters.narg() != 1) { int index = 1; while (index != parameters.narg()) { objParameters.add(fromType(parameters.arg(index + 1))); index++; } } for (Method method : object.getClass().getMethods()) { method.setAccessible(true); if (Arrays.equals(toArray(convertObjectsToTypes(objParameters)), method .getParameterTypes())) { if (method.getName().equals(name)) { try { method.invoke(object, objParameters.toArray(new Object[objParameters.size ()])); return LuaValue.NIL; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } return LuaValue.NIL; } } public static class AccessPrimitiveMethod implements FunctionController { private final Object object; public AccessPrimitiveMethod(Object object) { this.object = object; } @Override public String getName() { return "accessPrimitiveMethod"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); List<Object> objParameters = new ArrayList<Object>(); if (parameters.narg() != 1) { int index = 1; while (index != parameters.narg()) { objParameters.add(fromType(parameters.arg(index + 1))); index++; } } for (Method method : object.getClass().getMethods()) { method.setAccessible(true); if (Arrays.equals(toArray(convertObjectsToTypes(objParameters)), method .getParameterTypes())) { if (method.getName().equals(name)) { try { return convertType(method.invoke(object, objParameters.toArray(new Object[objParameters.size ()]))); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } return LuaValue.NIL; } } public static class AccessPrimitiveField implements FunctionController { private final Object object; public AccessPrimitiveField(Object object) { this.object = object; } @Override public String getName() { return "accessPrimitiveField"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); for (Field field : object.getClass().getFields()) { field.setAccessible(true); if (field.getName().equals(name)) { try { return convertType(field.get(object)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return LuaValue.NIL; } } public static class AccessJavaTypeMethod implements FunctionController { private final Object object; public AccessJavaTypeMethod(Object object) { this.object = object; } @Override public String getName() { return "accessJavaTypeMethod"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); List<Object> objParameters = new ArrayList<Object>(); if (parameters.narg() != 1) { int index = 1; while (index != parameters.narg()) { objParameters.add(fromType(parameters.arg(index + 1))); index++; } } for (Method method : object.getClass().getMethods()) { method.setAccessible(true); if (Arrays.equals(toArray(convertObjectsToTypes(objParameters)), method .getParameterTypes())) { if (method.getName().equals(name)) { try { return new LuaAccessor(method.invoke(object, objParameters.toArray(new Object[objParameters.size ()]))); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } return LuaValue.NIL; } } public static class AccessJavaTypeField implements FunctionController { private final Object object; public AccessJavaTypeField(Object object) { this.object = object; } @Override public String getName() { return "accessJavaTypeField"; } @Override public LuaValue onCalled(Varargs parameters) { String name = parameters.arg(1).tojstring(); for (Field field : object.getClass().getFields()) { field.setAccessible(true); if (field.getName().equals(name)) { try { return new LuaAccessor(field.get(this.object)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return LuaValue.NIL; } } }
package org.animotron.graph; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Stack; import org.apache.log4j.Logger; import org.neo4j.graphdb.Node; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class ReverseAnimoGraphBuilder { private static final Logger LOG = Logger.getLogger(ReverseAnimoGraphBuilder.class); private static final String HASH_ALGOTHIM = "SHA-256"; private int level = 0; private Stack<MessageDigest> hashStack = new Stack<MessageDigest>(); public void startElement(String ns, String name) { level++; MessageDigest md; try { md = MessageDigest.getInstance(HASH_ALGOTHIM); } catch (NoSuchAlgorithmException e) { //can't be, but throw runtime error throw new RuntimeException(e); } //hash-function depend on namespace & name md.update(ns.getBytes()); md.update(name.getBytes()); hashStack.push(md); } public void endElement(String ns, String name) { MessageDigest md = hashStack.pop(); //current element hash-function value byte[] elementDigest = md.digest(); if (level != 1) //update parent's hashStack.peek().update(elementDigest); level } public void attribute(String ns, String name, String value) { MessageDigest md = hashStack.peek(); //hash-function depend on namespace, name & value md.update(ns.getBytes()); md.update(name.getBytes()); md.update(value.getBytes()); } public void characters(String text) { MessageDigest md = hashStack.peek(); //hash-function depend on characters md.update(text.getBytes()); } }
package org.apdplat.superword.rule; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apdplat.superword.model.CharMap; import org.apdplat.superword.model.Word; import org.apdplat.superword.tools.WordLinker; import org.apdplat.superword.tools.WordSources; /** * : * * * a e i o u) * () * (phf) * * VUMN * * @author */ public class CharTransformRule { private CharTransformRule(){} private static final List<CharMap> CHAR_MAP_REGULAR = new ArrayList<>(); static { CHAR_MAP_REGULAR.add(new CharMap("b", "p")); CHAR_MAP_REGULAR.add(new CharMap("b", "m")); CHAR_MAP_REGULAR.add(new CharMap("b", "f")); CHAR_MAP_REGULAR.add(new CharMap("b", "v")); CHAR_MAP_REGULAR.add(new CharMap("p", "m")); CHAR_MAP_REGULAR.add(new CharMap("p", "f")); CHAR_MAP_REGULAR.add(new CharMap("p", "v")); CHAR_MAP_REGULAR.add(new CharMap("m", "f")); CHAR_MAP_REGULAR.add(new CharMap("m", "v")); CHAR_MAP_REGULAR.add(new CharMap("f", "v")); CHAR_MAP_REGULAR.add(new CharMap("d", "t")); CHAR_MAP_REGULAR.add(new CharMap("d", "s")); CHAR_MAP_REGULAR.add(new CharMap("d", "c")); CHAR_MAP_REGULAR.add(new CharMap("d", "z")); CHAR_MAP_REGULAR.add(new CharMap("d", "th")); CHAR_MAP_REGULAR.add(new CharMap("t", "s")); CHAR_MAP_REGULAR.add(new CharMap("t", "c")); CHAR_MAP_REGULAR.add(new CharMap("t", "z")); CHAR_MAP_REGULAR.add(new CharMap("t", "th")); CHAR_MAP_REGULAR.add(new CharMap("s", "c")); CHAR_MAP_REGULAR.add(new CharMap("s", "z")); CHAR_MAP_REGULAR.add(new CharMap("s", "th")); CHAR_MAP_REGULAR.add(new CharMap("c", "z")); CHAR_MAP_REGULAR.add(new CharMap("c", "th")); CHAR_MAP_REGULAR.add(new CharMap("ch", "k")); CHAR_MAP_REGULAR.add(new CharMap("z", "th")); CHAR_MAP_REGULAR.add(new CharMap("g", "k")); CHAR_MAP_REGULAR.add(new CharMap("g", "c")); CHAR_MAP_REGULAR.add(new CharMap("g", "h")); CHAR_MAP_REGULAR.add(new CharMap("k", "c")); CHAR_MAP_REGULAR.add(new CharMap("k", "h")); CHAR_MAP_REGULAR.add(new CharMap("c", "h")); CHAR_MAP_REGULAR.add(new CharMap("r", "l")); CHAR_MAP_REGULAR.add(new CharMap("r", "n")); CHAR_MAP_REGULAR.add(new CharMap("l", "n")); CHAR_MAP_REGULAR.add(new CharMap("m", "n")); CHAR_MAP_REGULAR.add(new CharMap("a", "e")); CHAR_MAP_REGULAR.add(new CharMap("a", "i")); CHAR_MAP_REGULAR.add(new CharMap("a", "o")); CHAR_MAP_REGULAR.add(new CharMap("a", "u")); CHAR_MAP_REGULAR.add(new CharMap("e", "i")); CHAR_MAP_REGULAR.add(new CharMap("e", "o")); CHAR_MAP_REGULAR.add(new CharMap("e", "u")); CHAR_MAP_REGULAR.add(new CharMap("i", "o")); CHAR_MAP_REGULAR.add(new CharMap("i", "u")); CHAR_MAP_REGULAR.add(new CharMap("o", "u")); CHAR_MAP_REGULAR.add(new CharMap("ph", "f")); CHAR_MAP_REGULAR.add(new CharMap("v", "u")); CHAR_MAP_REGULAR.add(new CharMap("v", "w")); CHAR_MAP_REGULAR.add(new CharMap("u", "w")); CHAR_MAP_REGULAR.add(new CharMap("i", "l")); CHAR_MAP_REGULAR.add(new CharMap("i", "j")); CHAR_MAP_REGULAR.add(new CharMap("f", "t")); CHAR_MAP_REGULAR.add(new CharMap("m", "w")); } public static String toHtmlFragmentForWord(Map<Word, Map<CharMap, List<Word>>> data){ StringBuilder result = new StringBuilder(); AtomicInteger i = new AtomicInteger(); data.keySet().forEach(target -> { if(data.size() > 1) { result.append(i.incrementAndGet()) .append(". ") .append(target.getWord()) .append("</br>\n"); } AtomicInteger j = new AtomicInteger(); data.get(target).keySet().forEach(charMap -> { result.append("\t") .append(j.incrementAndGet()) .append(". ") .append(charMap.getFrom()) .append(" - ") .append(charMap.getTo()) .append("\n"); String from = charMap.getFrom(); String to = charMap.getTo(); result.append("<ol>\n"); data.get(target).get(charMap).forEach(word -> { result.append("\t\t") .append("<li>") .append(WordLinker.toLink(word.getWord(), from)) .append(" -> ") .append(WordLinker.toLink(word.getWord().replaceAll(from, to), to)) .append("</li>\n"); }); result.append("</ol>\n"); }); }); return result.toString(); } public static Map<Word, Map<CharMap, List<Word>>> transforms(Set<Word> words, Word target){ return transforms(words, new HashSet<Word>(Arrays.asList(target))); } public static Map<Word, Map<CharMap, List<Word>>> transforms(Set<Word> words, Set<Word> targets){ Map<CharMap, List<Word>> data = transforms(words); Map<Word, Map<CharMap, List<Word>>> result = new ConcurrentHashMap<>(); targets.parallelStream().forEach(target -> { Map<CharMap, List<Word>> t = new HashMap<>(); data.entrySet().parallelStream().forEach(entry -> { List<Word> w = new ArrayList<>(); String from = entry.getKey().getFrom(); String to = entry.getKey().getTo(); entry.getValue().parallelStream().forEach(word -> { String old = word.getWord(); if (target.getWord().equals((old))) { w.add(word); } else if (target.getWord().equals(old.replaceAll(from, to))) { w.add(word); } }); if (!w.isEmpty()) { t.put(entry.getKey(), w); } }); if(!t.isEmpty()){ result.put(target, t); } }); return result; } public static Map<CharMap, List<Word>> transforms(Set<Word> words) { Map<CharMap, List<Word>> result = new ConcurrentHashMap<>(); CHAR_MAP_REGULAR.parallelStream().forEach(charMap -> result.putAll(transform(words, charMap))); return result; } /** * * @param words * @param charMap */ public static Map<CharMap, List<Word>> transform(Set<Word> words, CharMap charMap) { String from = charMap.getFrom(); String to = charMap.getTo(); List<Word> list = words.parallelStream() .filter(word -> word.getWord().contains(from) && words.contains( new Word( word.getWord().replaceAll(from, to), null))) .sorted() .collect(Collectors.toList()); Map<CharMap, List<Word>> result = new HashMap<>(); if(!list.isEmpty()) { result.put(new CharMap(from, to), list); } return result; } public static String toHtmlFragmentForRule(Map<CharMap, List<Word>> data){ StringBuilder html = new StringBuilder(); AtomicInteger i = new AtomicInteger(); List<CharMap> sortedList = new ArrayList<>(data.keySet()); Collections.sort(sortedList); sortedList.forEach(charMap -> { String from = charMap.getFrom(); String to = charMap.getTo(); List<Word> list = data.get(charMap); html.append("<h2>") .append(i.incrementAndGet()) .append("") .append(from) .append(" - ") .append(to) .append(" rule total number: ") .append(list.size()) .append("</h2></br>\n"); AtomicInteger j = new AtomicInteger(); list.stream() .forEach(word -> html.append("\t") .append(j.incrementAndGet()) .append("") .append(WordLinker.toLink(word.getWord())) .append(" -> ") .append(WordLinker.toLink(word.getWord().replaceAll(from, to))) .append("</br>\n")); }); return html.toString(); } public static void main(String[] args) throws Exception { //WordLinker.serverRedirect = null; //WordLinker.jsDefinition = false; Set<Word> words = WordSources.getSyllabusVocabulary(); //Map<CharMap, List<Word>> data = CharTransformRule.transforms(words); //String html = CharTransformRule.toHtmlFragmentForRule(data); Map<Word, Map<CharMap, List<Word>>> data2 = CharTransformRule.transforms(words, new Word("back", "")); String html2 = CharTransformRule.toHtmlFragmentForWord(data2); //System.out.println(html); System.out.println(html2); //Files.write(Paths.get("target/char_transform_rule.txt"), Arrays.asList(html, html2)); Files.write(Paths.get("target/char_transform_rule.txt"), Arrays.asList(html2)); } }
package org.arrah.framework.ndtable; /* This files is used for creating Report Table model. * We are using swing class but no UI. * This can have non editiable/editable values. * */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Vector; import java.util.stream.Collectors; import javax.swing.table.DefaultTableModel; import org.arrah.framework.rdbms.SqlType; import com.opencsv.CSVWriter; public class ReportTableModel implements Serializable, Cloneable { private static final long serialVersionUID = 1L; private Vector<Vector<?>> rowVector = new Vector<>(); private Vector<Object> column_v = new Vector<Object>(); private int col_size = 0; private DefaultTableModel tabModel; private boolean _isEditable = false; private boolean showClass = false; private int[] classType = null; public ReportTableModel(String[] col) { addColumns(col); createTable(false); } public ReportTableModel(Object[] col) { addColumns(col); createTable(false); } public ReportTableModel(Object[] col, boolean isEditable) { addColumns(col); createTable(isEditable); } public ReportTableModel(String[] col, boolean isEditable) { addColumns(col); createTable(isEditable); } public ReportTableModel(String[] col, boolean isEditable, boolean colClass) { addColumns(col); createTable(isEditable); showClass = colClass; } public ReportTableModel(String[] col, int[] sqlType, boolean isEditable, boolean colClass) { addColumns(col); createTable(isEditable); showClass = colClass; classType = sqlType; } public ReportTableModel(Object[] col, boolean isEditable, boolean colClass) { addColumns(col); createTable(isEditable); showClass = colClass; } public ReportTableModel(String less, String more, String b_less1, String b_more1, String b_less2, String b_more2) { String[] columnNames = { "<html><b><i>Values</i></b></html>", "<html><b>Aggregate</i></b></html>", "<html><b> &lt; <i>" + less + "</i></b></html>", "<html><b> &gt; <i>" + more + "</i></b></html>", "<html><b><i>" + b_less1 + "</i>&lt;&gt;<i>" + b_more1 + "</i></b></html>", "<html><b><i>" + b_less2 + "</i>&lt;&gt;<i>" + b_more2 + "</i></b></html>" }; String[][] data = { { "<html><b>COUNT</b></html>", "", "", "", "", "" }, { "<html><b>AVG</b></html>", "", "", "", "", "" }, { "<html><b>MAX</b></html>", "", "", "", "", "" }, { "<html><b>MIN</b></html>", "", "", "", "", "" }, { "<html><b>SUM</b></html>", "", "", "", "", "" }, { "<html><b>DUPLICATE</b></html>", "", "", "", "", "" }, }; addColumns(columnNames); addRows(data); createTable(false); }; private void createTable(final boolean isEditable) { _isEditable = isEditable; tabModel = new DefaultTableModel() { private static final long serialVersionUID = 1L; public boolean isCellEditable(int row, int col) { String colN = this.getColumnName(col); int[] colIndex = new int[1]; colIndex[0] = col; if (isEditable == true) { return true; } else { // isEditable False if (colN.endsWith("Editable") == true ) { return true; } else { // colN.endsWith("Editable") not true return false; } } } // end of isCellEditable public Class<?> getColumnClass(int col) { if (showClass == true) if (classType != null) { return SqlType.getClass(classType[col]); } else { // class type is null for (int i = 0; i < this.getRowCount(); i++) try{ if (getValueAt(i, col) != null) return getValueAt(i, col).getClass(); } catch(Exception e) { return (new Object()).getClass(); } return (new Object()).getClass(); } return (new Object()).getClass(); } }; tabModel.setDataVector(rowVector, column_v); } public void setValueAt(String s, int row, int col) { if (row < 0 || col < 0) return; tabModel.setValueAt(s, row, col); } public void setValueAt(Object s, int row, int col) { if (row < 0 || col < 0) return; tabModel.setValueAt(s, row, col); } private void addColumns(String[] colName) { int i; for (i = 0; i < colName.length; i++) column_v.addElement((String) colName[i]); col_size = i; } private void addColumns(Object[] colName) { int i; for (i = 0; i < colName.length; i++) column_v.addElement((String) colName[i].toString()); col_size = i; } private void addRows(String[][] rowData) { for (int i = 0; i < rowData.length; i++) { Vector<String> newRow = new Vector<String>(); for (int j = 0; j < rowData[i].length; j++) newRow.addElement((String) rowData[i][j]); rowVector.addElement(newRow); } } public void addFillRow(String[] rowset) { Vector<String> newRow = new Vector<String>(); for (int j = 0; j < rowset.length; j++) newRow.addElement((String) rowset[j]); rowVector.addElement(newRow); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } /* Add row from one object sequence*/ public void addFillRow(Object[] rowset) { Vector<Object> newRow = new Vector<Object>(); for (int j = 0; j < rowset.length; j++) newRow.addElement(rowset[j]); rowVector.addElement(newRow); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } public void addFillRow(Object[] rowset, Object[] rowset1) { Vector<Object> newRow = new Vector<Object>(); for (int j = 0; j < rowset.length; j++) newRow.addElement(rowset[j]); for (int j = 0; j < rowset1.length; j++) // append in the last newRow.addElement(rowset1[j]); rowVector.addElement(newRow); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } public void addFillRow(Vector<Object> rowset) { rowVector.addElement(rowset); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } public void addRow() { Vector<String> newRow = new Vector<>(); for (int j = 0; j < col_size; j++) newRow.addElement((String) ""); rowVector.addElement(newRow); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } public void addNullRow() { Vector<String> newRow = new Vector<String>(); for (int j = 0; j < col_size; j++) newRow.addElement(null); rowVector.addElement(newRow); tabModel.fireTableRowsInserted(tabModel.getRowCount(),1); } // Add Column and Remove Column public void addColumn(final String name) { tabModel.addColumn(name); tabModel.fireTableStructureChanged(); col_size = tabModel.getColumnCount();// Increase the col size } public void addRows(int startRow, int noOfRows) { int col_c = tabModel.getColumnCount(); Object[] row = new Object[col_c]; for (int i = 0; i < noOfRows; i++) tabModel.insertRow(startRow, row); tabModel.fireTableRowsInserted(startRow, noOfRows); } public void removeRows(int startRow, int noOfRows) { for (int i = 0; i < noOfRows; i++) tabModel.removeRow(startRow); tabModel.fireTableRowsDeleted(startRow, noOfRows); } public void removeMarkedRows(Vector<Integer> marked) { Integer[] a = new Integer[marked.size()]; a = marked.toArray(a); Arrays.sort(a); int len = a.length; for (int i = 0; i < len; i++) { tabModel.removeRow(a[len - 1 - i]); tabModel.fireTableRowsDeleted(a[len - 1 - i], 1); } } public Object[] copyRow(int startRow) { int col_c = tabModel.getColumnCount(); Object[] row = new Object[col_c]; for (int i = 0; i < col_c; i++) row[i] = tabModel.getValueAt(startRow, i); return row; } public void pasteRow(int startRow, Vector<Object[]> row) { int row_c = tabModel.getRowCount(); int col_c = tabModel.getColumnCount(); int vci = 0; int saveR = row_c - (startRow + row.size()); if (saveR < 0) { System.out.println("Not Enough Rows left to paste " + row.size() + " Rows \n Use \'Insert Clip\' instead"); return; } for (int i = row.size() - 1; i >= 0; i Object[] a = row.elementAt(vci++); col_c = (col_c > a.length) ? a.length : col_c; for (int j = 0; j < col_c; j++) tabModel.setValueAt(a[j], startRow + i, j); } } public void pasteRow(int startRow, Object[] row) { int row_c = tabModel.getRowCount(); int col_c = tabModel.getColumnCount(); int saveR = row_c - (startRow + 1); if (saveR < 0) { System.out.println("Not Enough Rows left to paste " + 1 + " Row \n Use \'Insert Clip\' instead"); return; } Object[] a = row; col_c = (col_c > a.length) ? a.length : col_c; for (int j = 0; j < col_c; j++) tabModel.setValueAt(a[j], startRow, j); } public DefaultTableModel getModel() { return tabModel; } public boolean isRTMEditable() { return _isEditable; } public boolean isRTMShowClass() { return showClass; } public static ReportTableModel copyTable(ReportTableModel rpt, boolean editable, boolean showClass) { if (rpt == null) return null; int colC = rpt.tabModel.getColumnCount(); int rowC = rpt.tabModel.getRowCount(); String[] colName = new String[colC]; for (int i = 0; i < colC; i++) colName[i] = rpt.tabModel.getColumnName(i); ReportTableModel newRT = new ReportTableModel(colName, editable, showClass); for (int i = 0; i < rowC; i++) { newRT.addRow(); for (int j = 0; j < colC; j++) newRT.tabModel.setValueAt(rpt.tabModel.getValueAt(i, j), i, j); } return newRT; } public Object[] getRow(int rowIndex) { int colC = tabModel.getColumnCount(); Object[] obj = new Object[colC]; if (rowIndex < 0 || rowIndex >= tabModel.getRowCount()) return obj; for (int i = 0; i < colC; i++) { obj[i] = tabModel.getValueAt(rowIndex, i); } return obj; } // To get only indexed or selected cols public Object[] getSelectedColRow(int rowIndex,int[] colI) { int colC = colI.length; Object[] obj = new Object[colC]; if (rowIndex < 0 || rowIndex >= tabModel.getRowCount()) return obj; for (int i = 0; i < colC; i++) { try { obj[i] = tabModel.getValueAt(rowIndex, colI[i]); } catch (Exception e) { // in case array out-of-bound obj[i] = null; continue; } } return obj; } // To get only indexed or selected cols public Object[] getSelectedColRow(int rowIndex,Integer[] colI) { int[] leftI = Arrays.stream(colI).mapToInt(Integer::intValue).toArray(); return getSelectedColRow( rowIndex, leftI); } public void cleanallRow() { int i = tabModel.getRowCount(); removeRows(0, i); } public boolean isEmptyRow (int rowid) { Object[] rowObj = this.getRow(rowid); for (int i=0 ; i < rowObj.length ; i++) { if (!(rowObj[i] == null || "".equals(rowObj[i].toString()))) { return false; } } return true; } public boolean isEmptyExceptCols (int rowid, int[] colIndex) { boolean isColMatch = false; Object[] rowObj = this.getRow(rowid); for (int i=0 ; i < rowObj.length ; i++) { isColMatch = false; for (int j=0; j < colIndex.length; j++){ if ( i == colIndex[j]) isColMatch = true; } if (isColMatch == false && (!(rowObj[i] == null || "".equals(rowObj[i].toString())))) { return false; } } return true; } // Static utility method public static int getColumnIndex(ReportTableModel rpt, String colName) { int row_c = rpt.getModel().getColumnCount(); for (int i = 0; i < row_c; i++) { if (colName.equals(rpt.getModel().getColumnName(i))) return i; } return -1; } // public util methods public int getColumnIndex(String colName) { int row_c = this.getModel().getColumnCount(); for (int i = 0; i < row_c; i++) { if (colName.equals(this.getModel().getColumnName(i))) return i; } return -1; } public Object[] getAllColName() { int colC = this.getModel().getColumnCount(); Object[] colN = new Object[colC]; for (int i = 0; i < colC; i++) colN[i] = this.getModel().getColumnName(i); return colN; } public String[] getAllColNameStr() { int colC = this.getModel().getColumnCount(); String[] colN = new String[colC]; for (int i = 0; i < colC; i++) colN[i] = this.getModel().getColumnName(i); return colN; } public Object[] getColData(int index) { int row_c = this.getModel().getRowCount(); Object[] colN = new Object[row_c]; for (int i = 0; i < row_c; i++) colN[i] = this.getModel().getValueAt(i, index); return colN; } public Object[] getColDataRandom(int index,int count) { Object[] colN = new Object[count]; Vector<Object> vc = new Vector<Object>(); int row_c = this.getModel().getRowCount(); int rowcount=0; while(rowcount < count) { int newc = new Random().nextInt(row_c); Object o = this.getModel().getValueAt(newc, index); // if (vc.indexOf(o) != -1) continue; // it may create loop vc.add(o); rowcount++; } return vc.toArray(colN); } public Object[] getColDataRandom(String colName,int count) { int index = getColumnIndex( colName); if ( index < 0 ) return null; return getColDataRandom( index,count); } public Vector<Object> getColDataV(int index) { int row_c = this.getModel().getRowCount(); Vector<Object> vc = new Vector<Object>(); for (int i = 0; i < row_c; i++) vc.add(this.getModel().getValueAt(i, index)); return vc; } public Vector<Double> getColDataVD(int index) { int row_c = this.getModel().getRowCount(); Vector<Double> vc = new Vector<Double>(); for (int i = 0; i < row_c; i++) { Object colv = this.getModel().getValueAt(i, index); if (colv == null || "".equals(colv.toString())) continue; // Null, empty skipped if (colv instanceof Number) //vc.add(((Double) colv).doubleValue()); vc.add(((Number)colv).doubleValue()); else if (colv instanceof String) { try { double newv = Double.parseDouble(colv.toString()); vc.add(newv); } catch (Exception e) { // Do nothing } } } return vc; } public Object[] getColData(String colName) { int colI = getColumnIndex( colName); if ( colI < 0 ) return null; return getColData(colI); } public int[] getClassType() { return classType; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public List<List<Object>> toNativeObjectListList() { return rowVector .stream() .map(vector -> { List<Object> list = new ArrayList<>(vector); return list; }) .collect(Collectors.toList()); } public void toPrint() { String[] colN = this.getAllColNameStr(); for(String s: colN) if (s != null) System.out.print(s+" "); else System.out.print("EMPTYCOLNAME"+" "); System.out.println(); for (int i=0 ; i <this.getModel().getRowCount(); i++) { for (int j=0 ; j <this.getModel().getColumnCount(); j++) { Object o = this.getModel().getValueAt(i, j); if (o != null) System.out.print(o.toString()+" "); else System.out.print("null"+" "); } System.out.println(); } } /** * save the table as comma separated values (OpenCSV format) */ public void saveAsOpenCSV(String fileLoc) { File fileN = null; if (fileLoc.toLowerCase().endsWith(".csv") == false) { fileN = new File(fileLoc + ".csv"); } else fileN = new File(fileLoc); // Get Row and Column count int rowCount = this.getModel().getRowCount(); int columnCount = this.getModel().getColumnCount(); String[] colD = new String[columnCount]; try { CSVWriter writer = new CSVWriter(new FileWriter(fileN)); // Get Column header for (int j = 0; j < columnCount; j++) colD[j] = this.getModel().getColumnName(j); writer.writeNext(colD,true); // Get Column data for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { Object o = this.getModel().getValueAt(i, j); if (o == null) colD[j] = "null"; else colD[j] = o.toString(); } writer.writeNext(colD,true); } writer.close(); } catch (IOException exp) { System.out.println( exp.getMessage()); } } } // End of ReportTableModel class
package org.ftcTeam.opmodes.production; import com.qualcomm.robotcore.hardware.Servo; import org.ftcTeam.configurations.production.Team8702ProdAuto; public class ElmoOperation { private enum ElmoState { START_POSITION(0.0), SPIN_FIRST(0.5), REACH_MOVING_FORWARD(0.3), SPIN_TO_HIT_BALL(0.6), SPIN_RECOIL(0.5), REACH_MOVING_BACKWARD(0.95), SPIN_RESET(0.0), END_POSITION(0.0); private final double position; private ElmoState(double position) { this.position = position; } public double position() { return this.position; } } private static ElmoState elmoState = ElmoState.START_POSITION; private static final double REACH_DELTA = 0.005, SPIN_DELTA = 0.005, HIT_BALL_DELTA = 0.02; private enum SPIN_DIRECTION { POSITIVE(1.0), NEGATIVE(-1.0); private final double direction; private SPIN_DIRECTION(double direction) { this.direction = direction; } public double getDirection() { return direction; } } final AbstractAutoMode abstractAutoMode; final Team8702ProdAuto robot; public ElmoOperation(AbstractAutoMode abstractAutoMode){ this.abstractAutoMode = abstractAutoMode; this.robot = this.abstractAutoMode.getRobot(); resetServoPositions(); elmoState = ElmoState.START_POSITION; } private void resetServoPositions() { try { robot.elmoReach.setPosition(0.95); Thread.sleep(500); robot.elmoSpin.setPosition(0.0); } catch(InterruptedException ignored) {} } public boolean elmoDown() throws InterruptedException { // elmoDown called in incorrect elmo state // Just return true so that operation is not stuck. if (elmoState != ElmoState.START_POSITION) { return true; } boolean done = false; do { this.abstractAutoMode.getTelemetryUtil().addData("elmoDown() Beginning of do-while loop: ", this.abstractAutoMode.getCurrentState().name()); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); switch (elmoState) { case START_POSITION: elmoState = ElmoState.SPIN_FIRST; break; case SPIN_FIRST: rotateServo(robot.elmoSpin, ElmoState.SPIN_FIRST.position(), SPIN_DELTA); Thread.sleep(500); elmoState = ElmoState.REACH_MOVING_FORWARD; break; case REACH_MOVING_FORWARD: rotateServo(robot.elmoReach, ElmoState.REACH_MOVING_FORWARD.position(), REACH_DELTA); Thread.sleep(500); elmoState = ElmoState.SPIN_TO_HIT_BALL; done = true; break; } } while (done == false); return done; } public boolean elmoUp() throws InterruptedException { // elmoUp called in incorrect elmo state // Just return true so that operation is not stuck. if (elmoState != ElmoState.REACH_MOVING_BACKWARD) { return true; } boolean done = false; do { this.abstractAutoMode.getTelemetryUtil().addData("elmoUp() Beginning of do-while loop: ", this.abstractAutoMode.getCurrentState().name()); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); switch (elmoState) { case REACH_MOVING_BACKWARD: rotateServo(robot.elmoReach, ElmoState.REACH_MOVING_BACKWARD.position(), REACH_DELTA); Thread.sleep(500); elmoState = ElmoState.SPIN_RESET; break; case SPIN_RESET: rotateServo(robot.elmoSpin, ElmoState.SPIN_RESET.position(), SPIN_DELTA); Thread.sleep(500); elmoState = ElmoState.END_POSITION; done = true; break; } } while (done == false); return done; } public boolean knockOffJewel() throws InterruptedException { // knockOffJewel called in incorrect elmo state. // Just return true so that operation is not stuck. if (elmoState != ElmoState.SPIN_TO_HIT_BALL) { return true; } final double beginHitPosition = this.robot.elmoSpin.getPosition(); boolean done = false; do { this.abstractAutoMode.getTelemetryUtil().addData("knockOffJewel() Beginning of do-while loop: ", this.abstractAutoMode.getCurrentState().name()); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); switch (elmoState) { case SPIN_TO_HIT_BALL: double endHitposition = ElmoState.SPIN_TO_HIT_BALL.position(); SPIN_DIRECTION spinDirection = getSpinDirection(); // For example, if currentPosition = 0.5 and final spin position is 0.7 // and spin direction is negative, then final spin position should be 0.3 if (spinDirection == SPIN_DIRECTION.NEGATIVE) { endHitposition = beginHitPosition - (ElmoState.SPIN_TO_HIT_BALL.position() - beginHitPosition); } this.abstractAutoMode.getTelemetryUtil().addData("knockOffJewel() Moving Spin position to: ", new String("" + endHitposition)); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); rotateServo(robot.elmoSpin, endHitposition, HIT_BALL_DELTA); printPositions(); Thread.sleep(500); elmoState = ElmoState.SPIN_RECOIL; break; case SPIN_RECOIL: this.abstractAutoMode.getTelemetryUtil().addData("knockOffJewel() Moving Spin position to: ", new String(""+ beginHitPosition)); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); rotateServo(robot.elmoSpin, beginHitPosition, HIT_BALL_DELTA); Thread.sleep(500); elmoState = ElmoState.REACH_MOVING_BACKWARD; done = true; break; } } while (done == false); return done; } /** * Move a {@link Servo} a given {@code #finalPosition} at the speed decided by {@code #delta} * <p> * The {@code servoDelta} shall be adjusted based on the required speed at which the arm needs to move. * * @param servo * @param finalPosition * @param delta */ private double rotateServo(Servo servo, double finalPosition, double delta) throws InterruptedException { double servoPosition = servo.getPosition(), startPosition = servo.getPosition(), prevPosition = servo.getPosition(); Servo.Direction direction = (finalPosition > servoPosition) ? Servo.Direction.FORWARD : Servo.Direction.REVERSE; String msg = String.format("[start:%.3f][final:%.3f]", servoPosition, finalPosition); this.abstractAutoMode.getTelemetryUtil().addData("rotateServo : ", msg); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); // while comparing floating point numbers, never use "equals" due to problems with precision while (Math.abs(finalPosition - servoPosition) > 0.001) { prevPosition = servoPosition; if (direction == Servo.Direction.FORWARD) { servoPosition += delta; } else { servoPosition -= delta; } servo.setPosition(servoPosition); msg = String.format("[old:%.3f][new:%.3f]", prevPosition, servoPosition); this.abstractAutoMode.getTelemetryUtil().addData("rotateServo : ", msg); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); //Thread.sleep(2000); } return servoPosition; } private SPIN_DIRECTION getSpinDirection() { SPIN_DIRECTION direction = SPIN_DIRECTION.POSITIVE; printColors(); if (this.abstractAutoMode.getPanelColor() != this.abstractAutoMode.getElmoColor()) { direction = SPIN_DIRECTION.NEGATIVE; } this.abstractAutoMode.getTelemetryUtil().addData("knockOffJewel() Sping direction: ", direction.name()); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); return direction; } private void printPositions() { this.abstractAutoMode.getTelemetryUtil().addData("Current State: ", this.abstractAutoMode.getCurrentState().name()); String msg = String.format("[Spin=%f][Reach=%f]", this.robot.elmoSpin.getPosition(), this.robot.elmoReach.getPosition()); this.abstractAutoMode.getTelemetryUtil().addData("Current Positions: ", msg); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); } private void printColors() { this.abstractAutoMode.getTelemetryUtil().addData("Panel Color: ", this.abstractAutoMode.getPanelColor().name()); this.abstractAutoMode.getTelemetryUtil().addData("Sensor Color: ", this.abstractAutoMode.getElmoColor().name()); this.abstractAutoMode.getTelemetryUtil().sendTelemetry(); } }
package org.jboss.util.loading; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandlerFactory; /** * A URL classloader that delegates to its parent, avoiding * synchronization. * * A standard flag is provided so it can be used as a parent class, * but later subclassed and to revert to standard class loading * if the subclass wants to load classes. * * @author <a href="mailto:adrian@jboss.org">Adrian Brock</a> * @version $Revision$ */ public class DelegatingClassLoader extends URLClassLoader { /** The value returned by {@link getURLs}. */ public static final URL[] EMPTY_URL_ARRAY = {}; /** Whether to use standard loading */ protected boolean standard = false; /** * Constructor * * @param parent the parent classloader, cannot be null. */ public DelegatingClassLoader(ClassLoader parent) { super(EMPTY_URL_ARRAY, parent); if (parent == null) throw new IllegalArgumentException("No parent"); } /** * Constructor * * @param parent, the parent classloader, cannot be null. * @param factory the url stream factory. */ public DelegatingClassLoader(ClassLoader parent, URLStreamHandlerFactory factory) { super(EMPTY_URL_ARRAY, parent, factory); if (parent == null) throw new IllegalArgumentException("No parent"); } /** * Load a class, by asking the parent * * @param className the class name to load * @param resolve whether to link the class * @return the loaded class * @throws ClassNotFoundException when the class could not be found */ protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException { // Revert to standard rules if (standard) return super.loadClass(className, resolve); // Ask the parent Class clazz = null; try { clazz = getParent().loadClass(className); } catch (ClassNotFoundException e) { // Not found in parent, // maybe it is a proxy registered against this classloader? clazz = findLoadedClass(className); if (clazz == null) throw e; } // Link the class if (resolve) resolveClass(clazz); return clazz; } }
package org.jenkinsci.plugins.koji.xmlrpc; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Singleton used for XML-RPC communication with Koji. */ public class KojiClient { private XmlRpcClient koji; private static KojiClient instance; private String kojiInstanceURL; public String getKojiInstanceURL() { return kojiInstanceURL; } private KojiClient(String kojiInstanceURL) { this.kojiInstanceURL = kojiInstanceURL; this.koji = connect(kojiInstanceURL); } /** * Get the KojiClient Singleton instance. * @param kojiInstanceURL URL of remote Koji instance. */ public static KojiClient getKojiClient(String kojiInstanceURL) { if (instance == null) instance = new KojiClient(kojiInstanceURL); else { if (instance.getKojiInstanceURL() != kojiInstanceURL) { instance = new KojiClient(kojiInstanceURL); // TODO: won't it be more efficient to only call setServerURL? } } return instance; } /** * Gets latest builds. * @param tag Koji tag * @param pkg Koji package * @return Array of properties for latest build. */ public Object[] getLatestBuilds(String tag, String pkg) throws XmlRpcException { // Koji XML-RPC API // getLatestBuilds(tag, event=None, package=None, type=None) // description: List latest builds for tag (inheritance enabled) List<Object> params = new ArrayList<Object>(); params.add(tag); // Event is of no interest to us. params.add(null); params.add(pkg); Object[] latestBuilds = null; try { latestBuilds = (Object[]) koji.execute("getLatestBuilds", params); } catch (XmlRpcException e) { throw e; } if (latestBuilds == null) { throw new XmlRpcException("empty"); } return latestBuilds; } /** * Retrieves information about a given build. * @param buildId BuildId can be Name-Version-Release (NVR) or numeric buildId. * @return A map containing all information about given build. */ public Map<String, String> getBuildInfo(String buildId) throws XmlRpcException { /* XML-RPC method information getBuild(buildInfo, strict=False) description: Return information about a build. buildID may be either a int ID, a string NVR, or a map containing 'name', 'version' and 'release. A map will be returned containing the following keys: id: build ID package_id: ID of the package built package_name: name of the package built version release epoch nvr state task_id: ID of the task that kicked off the build owner_id: ID of the user who kicked off the build owner_name: name of the user who kicked off the build volume_id: ID of the storage volume volume_name: name of the storage volume creation_event_id: id of the create_event creation_time: time the build was created (text) creation_ts: time the build was created (epoch) completion_time: time the build was completed (may be null) completion_ts: time the build was completed (epoch, may be null) If there is no build matching the buildInfo given, and strict is specified, raise an error. Otherwise return None. */ List<Object> params = new ArrayList<Object>(); params.add(buildId); Map<String, String> buildInfo; try { buildInfo = (Map<String, String>) koji.execute("getBuild", params); } catch (XmlRpcException e) { throw e; } if (buildInfo == null) { throw new XmlRpcException("empty"); } return buildInfo; } /** * Gets information about logged user. * @return Session identification. */ public String getSession() { String result = null; try { result = (String) koji.execute("showSession", new Object[] {}); } catch (XmlRpcException e) { e.printStackTrace(); } return result; } public void listTaggedBuilds(BuildParams buildParams) { // Koji XML-RPC API // listTagged(tag, event=None, inherit=False, prefix=None, latest=False, package=None, owner=None, type=None) // description: List builds tagged with tag List<Object> params = new ArrayList<Object>(); params.add(buildParams.getTag()); // Event is of no interest to us. params.add(null); params.add(false); params.add(null); params.add(buildParams.isLatest()); params.add(buildParams.getPkg()); params.add(buildParams.getOwner()); params.add(buildParams.getType()); try { Object[] objects = (Object[]) koji.execute("listTagged", params); for (Object o : objects) { Map<String, String> map = (Map<String, String>) o; for (Map.Entry<String, String> m : map.entrySet()) { String key = m.getKey(); Object value = m.getValue(); System.out.println(key + ": " + value); } } // return buildInfo; } catch (XmlRpcException e) { e.printStackTrace(); } // return null; } /** * Holds Koji Build parameters. Use BuildParamsBuilder for initialization. */ static class BuildParams { private final String id; private final String tag; private final boolean latest; private final String pkg; private final String owner; private final String type; BuildParams(String id, String tag, boolean latest, String pkg, String owner, String type) { this.id = id; this.tag = tag; this.latest = latest; this.pkg = pkg; this.owner = owner; this.type = type; } public String getId() { return id; } public String getTag() { return tag; } public boolean isLatest() { return latest; } public String getPkg() { return pkg; } public String getOwner() { return owner; } public String getType() { return type; } } /** * Builder instance for BuildParams providing default values. */ static class BuildParamsBuilder { private String id = null; private String tag = null; private boolean latest = false; private String pkg = null; private String owner = null; private String type = null; BuildParamsBuilder setId(String id) { this.id = id; return this; } BuildParamsBuilder setTag(String tag) { this.tag = tag; return this; } BuildParamsBuilder setLatest(boolean latest) { this.latest = latest; return this; } BuildParamsBuilder setPackage(String pkg) { this.pkg = pkg; return this; } BuildParamsBuilder setOwner(String owner) { this.owner = owner; return this; } BuildParamsBuilder setType(String type) { this.type = type; return this; } BuildParams build() { return new BuildParams(id, tag, latest, pkg, owner, type); } } /** * Greet the remote Koji instance and test the communication. * @return */ public String sayHello() { StringBuilder sb = new StringBuilder(); try { Object result = koji.execute("hello", new Object[] {"Hello"}); sb.append("Jenkins-Koji Plugin: Hello Koji server running at " + kojiInstanceURL); sb.append("\nKoji: " + result); return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Connect to remote Koji instance. Uses custom Transport factory adding a None / null support for XML-RPC. * @param kojiInstanceURL Address of the remote Koji server. * @return XMLRPC client instance. */ private XmlRpcClient connect(String kojiInstanceURL) { XmlRpcClient koji = new XmlRpcClient(); koji.setTransportFactory(new XmlRpcCommonsTransportFactory(koji)); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); koji.setTransportFactory(new XmlRpcCommonsTransportFactory(koji)); koji.setTypeFactory(new MyTypeFactory(koji)); config.setEnabledForExtensions(true); config.setEnabledForExceptions(true); try { config.setServerURL(new URL(kojiInstanceURL)); } catch (MalformedURLException e) { e.printStackTrace(); } koji.setConfig(config); return koji; } public void setDebug(boolean debug) { if (debug) koji.setTransportFactory(new MyXmlRpcCommonsTransportFactory(koji)); else koji.setTransportFactory(new XmlRpcCommonsTransportFactory(koji)); } }
package org.jenkinsci.plugins.p4.client; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.p4.changes.P4Revision; import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials; import org.jenkinsci.plugins.p4.populate.AutoCleanImpl; import org.jenkinsci.plugins.p4.populate.CheckOnlyImpl; import org.jenkinsci.plugins.p4.populate.ForceCleanImpl; import org.jenkinsci.plugins.p4.populate.Populate; import org.jenkinsci.plugins.p4.publish.Publish; import org.jenkinsci.plugins.p4.publish.ShelveImpl; import org.jenkinsci.plugins.p4.publish.SubmitImpl; import org.jenkinsci.plugins.p4.tasks.TimeTask; import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl; import org.jenkinsci.plugins.p4.workspace.Workspace; import com.perforce.p4java.client.IClient; import com.perforce.p4java.client.IClientSummary.IClientOptions; import com.perforce.p4java.core.IChangelist; import com.perforce.p4java.core.IChangelistSummary; import com.perforce.p4java.core.file.FileAction; import com.perforce.p4java.core.file.FileSpecBuilder; import com.perforce.p4java.core.file.FileSpecOpStatus; import com.perforce.p4java.core.file.IFileSpec; import com.perforce.p4java.impl.generic.client.ClientView; import com.perforce.p4java.impl.generic.core.Changelist; import com.perforce.p4java.impl.generic.core.file.FileSpec; import com.perforce.p4java.option.changelist.SubmitOptions; import com.perforce.p4java.option.client.ReconcileFilesOptions; import com.perforce.p4java.option.client.ReopenFilesOptions; import com.perforce.p4java.option.client.ResolveFilesAutoOptions; import com.perforce.p4java.option.client.ResolvedFilesOptions; import com.perforce.p4java.option.client.RevertFilesOptions; import com.perforce.p4java.option.client.SyncOptions; import com.perforce.p4java.option.server.GetChangelistsOptions; import com.perforce.p4java.option.server.GetFileContentsOptions; import com.perforce.p4java.option.server.OpenedFilesOptions; import hudson.AbortException; import hudson.model.TaskListener; public class ClientHelper extends ConnectionHelper { private static Logger logger = Logger.getLogger(ClientHelper.class.getName()); private IClient iclient; public ClientHelper(String credential, TaskListener listener, String client) { super(credential, listener); clientLogin(client); } public ClientHelper(P4BaseCredentials credential, TaskListener listener, String client) { super(credential, listener); clientLogin(client); } private void clientLogin(String client) { // Exit early if no connection if (connection == null) { return; } // Find workspace and set as current try { iclient = connection.getClient(client); connection.setCurrentClient(iclient); } catch (Exception e) { String err = "P4: Unable to use Workspace: " + e; logger.severe(err); log(err); e.printStackTrace(); } } public void setClient(Workspace workspace) throws Exception { if (isUnicode()) { String charset = workspace.getCharset(); connection.setCharsetName(charset); } // Setup/Create workspace based on type iclient = workspace.setClient(connection, authorisationConfig.getUsername()); // Exit early if client is not defined if (!isClientValid(workspace)) { String err = "P4: Undefined workspace: " + workspace.getFullName(); throw new AbortException(err); } // Exit early if client is Static if (workspace instanceof StaticWorkspaceImpl) { connection.setCurrentClient(iclient); return; } // Ensure root and host fields are not null if (workspace.getRootPath() != null) { iclient.setRoot(workspace.getRootPath()); } if (workspace.getHostName() != null) { iclient.setHostName(workspace.getHostName()); } // Set clobber on to ensure workspace is always good IClientOptions options = iclient.getOptions(); options.setClobber(true); iclient.setOptions(options); // Save client spec iclient.update(); // Set active client for this connection connection.setCurrentClient(iclient); return; } /** * Sync files to workspace at the specified change/label. * * @param buildChange * Change to sync from * @param populate * Populate strategy * @throws Exception */ public void syncFiles(P4Revision buildChange, Populate populate) throws Exception { TimeTask timer = new TimeTask(); // test label is valid if (buildChange.isLabel()) { String label = buildChange.toString(); try { int change = Integer.parseInt(label); log("P4 Task: label is a number! syncing files at change: " + change); } catch (NumberFormatException e) { if (!isLabel(label) && !isClient(label)) { String msg = "P4: Unable to find client/label: " + label; log(msg); logger.warning(msg); throw new AbortException(msg); } else { log("P4 Task: syncing files at client/label: " + label); } } } else { log("P4 Task: syncing files at change: " + buildChange); } // build file revision spec List<IFileSpec> files; String path = iclient.getRoot() + "/..."; String revisions = path + "@" + buildChange; // Sync files files = FileSpecBuilder.makeFileSpecList(revisions); if (populate instanceof CheckOnlyImpl) { syncHaveList(files, populate); } else { syncFiles(files, populate); } log("duration: " + timer.toString() + "\n"); } /** * Test to see if workspace is at the latest revision. * * @throws Exception */ private boolean syncHaveList(List<IFileSpec> files, Populate populate) throws Exception { // Preview (sync -k) SyncOptions syncOpts = new SyncOptions(); syncOpts.setClientBypass(true); syncOpts.setQuiet(populate.isQuiet()); List<IFileSpec> syncMsg = iclient.sync(files, syncOpts); validateFileSpecs(syncMsg, "file(s) up-to-date.", "file does not exist", "no file(s) as of that date"); for (IFileSpec fileSpec : syncMsg) { if (fileSpec.getOpStatus() != FileSpecOpStatus.VALID) { String msg = fileSpec.getStatusMessage(); if (msg.contains("file(s) up-to-date.")) { return true; } } } return false; } private void syncFiles(List<IFileSpec> files, Populate populate) throws Exception { // set MODTIME if populate options is used only required before 15.1 if (populate.isModtime() && !checkVersion(20151)) { IClientOptions options = iclient.getOptions(); if (!options.isModtime()) { options.setModtime(true); iclient.setOptions(options); iclient.update(); // Save client spec } } // sync options SyncOptions syncOpts = new SyncOptions(); // setServerBypass (-p no have list) syncOpts.setServerBypass(!populate.isHave()); // setForceUpdate (-f only if no -p is set) syncOpts.setForceUpdate(populate.isForce() && populate.isHave()); syncOpts.setQuiet(populate.isQuiet()); List<IFileSpec> syncMsg = iclient.sync(files, syncOpts); validateFileSpecs(syncMsg, "file(s) up-to-date.", "file does not exist", "no file(s) as of that date"); } /** * Cleans up the Perforce workspace after a previous build. Removes all * pending and abandoned files (equivalent to 'p4 revert -w'). * * @throws Exception */ public void tidyWorkspace(Populate populate) throws Exception { // relies on workspace view for scope. log(""); List<IFileSpec> files; String path = iclient.getRoot() + "/..."; files = FileSpecBuilder.makeFileSpecList(path); if (populate instanceof AutoCleanImpl) { tidyAutoCleanImpl(populate, files); } if (populate instanceof ForceCleanImpl) { tidyForceSyncImpl(populate, files); } } private void tidyForceSyncImpl(Populate populate, List<IFileSpec> files) throws Exception { // remove all pending files within workspace tidyPending(files); // remove all versioned files (clean have list) String revisions = iclient.getRoot() + "/... files = FileSpecBuilder.makeFileSpecList(revisions); // Only use quiet populate option to insure a clean sync boolean quiet = populate.isQuiet(); Populate clean = new AutoCleanImpl(false, false, false, quiet, null); syncFiles(files, clean); // remove all files from workspace String root = iclient.getRoot(); log("... rm -rf " + root); silentlyForceDelete(root); } private void silentlyForceDelete(String root) throws IOException { try { FileUtils.forceDelete(new File(root)); } catch (FileNotFoundException ignored) { } } private void tidyAutoCleanImpl(Populate populate, List<IFileSpec> files) throws Exception { // remove all pending files within workspace tidyPending(files); // clean files within workspace tidyClean(files, populate); } private void tidyPending(List<IFileSpec> files) throws Exception { TimeTask timer = new TimeTask(); log("P4 Task: reverting all pending and shelved revisions."); // revert all pending and shelved revisions RevertFilesOptions rOpts = new RevertFilesOptions(); List<IFileSpec> list = iclient.revertFiles(files, rOpts); validateFileSpecs(list, "not opened on this client"); // check for added files and remove... log("... rm [abandoned files]"); for (IFileSpec file : list) { if (file.getAction() == FileAction.ABANDONED) { // first check if we have the local path String path = file.getLocalPathString(); if (path == null) { path = depotToLocal(file); } if (path != null) { File unlink = new File(path); unlink.delete(); } } } log("duration: " + timer.toString() + "\n"); } private void tidyClean(List<IFileSpec> files, Populate populate) throws Exception { // Use old method if 'p4 clean' is not supported if (!checkVersion(20141)) { tidyRevisions(files, populate); return; } // Set options boolean delete = ((AutoCleanImpl) populate).isDelete(); boolean replace = ((AutoCleanImpl) populate).isReplace(); String[] base = { "-w", "-f" }; List<String> list = new ArrayList<String>(); list.addAll(Arrays.asList(base)); if (delete && !replace) { list.add("-a"); } if (replace && !delete) { list.add("-e"); list.add("-d"); } if (!replace && !delete) { log("P4 Task: skipping clean, no options set."); return; } // set MODTIME if populate options is used and server supports flag if (populate.isModtime()) { if (checkVersion(20141)) { list.add("-m"); } else { log("P4: Resolving files by MODTIME not supported (requires 2014.1 or above)"); } } TimeTask timer = new TimeTask(); log("P4 Task: cleaning workspace to match have list."); String[] args = list.toArray(new String[list.size()]); ReconcileFilesOptions cleanOpts = new ReconcileFilesOptions(args); List<IFileSpec> status = iclient.reconcileFiles(files, cleanOpts); validateFileSpecs(status, "also opened by", "no file(s) to reconcile", "must sync/resolve", "exclusive file already opened", "cannot submit from stream", "instead of", "empty, assuming text"); log("duration: " + timer.toString() + "\n"); } private void tidyRevisions(List<IFileSpec> files, Populate populate) throws Exception { TimeTask timer = new TimeTask(); log("P4 Task: tidying workspace to match have list."); boolean delete = ((AutoCleanImpl) populate).isDelete(); boolean replace = ((AutoCleanImpl) populate).isReplace(); // check status - find all missing, changed or added files String[] base = { "-n", "-a", "-e", "-d", "-l", "-f" }; List<String> list = new ArrayList<String>(); list.addAll(Arrays.asList(base)); String[] args = list.toArray(new String[list.size()]); ReconcileFilesOptions statusOpts = new ReconcileFilesOptions(args); List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts); validateFileSpecs(status, "also opened by", "no file(s) to reconcile", "must sync/resolve", "exclusive file already opened", "cannot submit from stream", "instead of", "empty, assuming text"); // Add missing, modified or locked files to a list, and delete the // unversioned files. List<IFileSpec> update = new ArrayList<IFileSpec>(); for (IFileSpec s : status) { if (s.getOpStatus() == FileSpecOpStatus.VALID) { String path = s.getLocalPathString(); if (path == null) { path = depotToLocal(s); } switch (s.getAction()) { case ADD: if (path != null && delete) { File unlink = new File(path); unlink.delete(); } break; default: update.add(s); break; } } else { String msg = s.getStatusMessage(); if (msg.contains("exclusive file already opened")) { String rev = msg.substring(0, msg.indexOf(" - can't ")); IFileSpec spec = new FileSpec(rev); update.add(spec); } } } // Force sync missing and modified files if (!update.isEmpty() && replace) { SyncOptions syncOpts = new SyncOptions(); syncOpts.setForceUpdate(true); syncOpts.setQuiet(populate.isQuiet()); List<IFileSpec> syncMsg = iclient.sync(update, syncOpts); validateFileSpecs(syncMsg, "file(s) up-to-date.", "file does not exist"); } log("duration: " + timer.toString() + "\n"); } public boolean buildChange() throws Exception { TimeTask timer = new TimeTask(); log("P4 Task: reconcile files to changelist."); // build file revision spec String ws = "//" + iclient.getName() + "/..."; List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws); // cleanup pending changes (revert -k) RevertFilesOptions revertOpts = new RevertFilesOptions(); revertOpts.setNoClientRefresh(true); List<IFileSpec> revertStat = iclient.revertFiles(files, revertOpts); validateFileSpecs(revertStat, ""); // flush client to populate have (sync -k) SyncOptions syncOpts = new SyncOptions(); syncOpts.setClientBypass(true); List<IFileSpec> syncStat = iclient.sync(files, syncOpts); validateFileSpecs(syncStat, "file(s) up-to-date."); // check status - find all changes to files ReconcileFilesOptions statusOpts = new ReconcileFilesOptions(); statusOpts.setUseWildcards(true); List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts); validateFileSpecs(status, "- no file(s) to reconcile", "instead of", "empty, assuming text", "also opened by"); // Check if file is open boolean open = isOpened(files); log("duration: " + timer.toString() + "\n"); return open; } public void publishChange(Publish publish) throws Exception { TimeTask timer = new TimeTask(); log("P4 Task: publish files to Perforce."); // build file revision spec String ws = "//" + iclient.getName() + "/..."; List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws); // create new pending change and add description IChangelist change = new Changelist(); change.setDescription(publish.getExpandedDesc()); change = iclient.createChangelist(change); log("... pending change: " + change.getId()); // move files from default change ReopenFilesOptions reopenOpts = new ReopenFilesOptions(); reopenOpts.setChangelistId(change.getId()); iclient.reopenFiles(files, reopenOpts); // logging OpenedFilesOptions openOps = new OpenedFilesOptions(); List<IFileSpec> open = iclient.openedFiles(files, openOps); for (IFileSpec f : open) { FileAction action = f.getAction(); String path = f.getDepotPathString(); log("... ... " + action + " " + path); } // if SUBMIT if (publish instanceof SubmitImpl) { SubmitImpl submit = (SubmitImpl) publish; SubmitOptions submitOpts = new SubmitOptions(); submitOpts.setReOpen(submit.isReopen()); log("... submitting files"); List<IFileSpec> submitted = change.submit(submitOpts); validateFileSpecs(submitted, "Submitted as change"); long cngNumber = findSubmittedChange(submitted); if (cngNumber > 0) { log("... submitted in change: " + cngNumber); } } // if SHELVE if (publish instanceof ShelveImpl) { ShelveImpl shelve = (ShelveImpl) publish; log("... shelving files"); List<IFileSpec> shelved = iclient.shelveChangelist(change); validateFileSpecs(shelved, ""); // post shelf cleanup RevertFilesOptions revertOpts = new RevertFilesOptions(); revertOpts.setChangelistId(change.getId()); revertOpts.setNoClientRefresh(!shelve.isRevert()); String r = (shelve.isRevert()) ? "(revert)" : "(revert -k)"; log("... reverting open files " + r); iclient.revertFiles(files, revertOpts); } log("duration: " + timer.toString() + "\n"); } private long findSubmittedChange(List<IFileSpec> submitted) { long change = 0; for (IFileSpec spec : submitted) { if (spec.getOpStatus() != FileSpecOpStatus.VALID) { String msg = spec.getStatusMessage(); String cng = "Submitted as change "; if (msg.startsWith(cng)) { try { String id = msg.substring(cng.length()); change = Long.parseLong(id); } catch (NumberFormatException e) { change = -1; } } } } return change; } private boolean isOpened(List<IFileSpec> files) throws Exception { OpenedFilesOptions openOps = new OpenedFilesOptions(); List<IFileSpec> open = iclient.openedFiles(files, openOps); for (IFileSpec file : open) { if (file != null && file.getAction() != null) { return true; } } return false; } /** * Workaround for p4java bug. The 'setLocalSyntax(true)' option does not * provide local syntax, so I have to use 'p4 where' to translate through * the client view. * * @param fileSpec * @return * @throws Exception */ private String depotToLocal(IFileSpec fileSpec) throws Exception { String depotPath = fileSpec.getDepotPathString(); if (depotPath == null) { depotPath = fileSpec.getOriginalPathString(); } if (depotPath == null) { return null; } List<IFileSpec> dSpec = FileSpecBuilder.makeFileSpecList(depotPath); List<IFileSpec> lSpec = iclient.where(dSpec); String path = lSpec.get(0).getLocalPathString(); return path; } private void printFile(String rev) throws Exception { byte[] buf = new byte[1024 * 64]; List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(rev); GetFileContentsOptions printOpts = new GetFileContentsOptions(); printOpts.setNoHeaderLine(true); InputStream ins = connection.getFileContents(file, printOpts); String localPath = depotToLocal(file.get(0)); File target = new File(localPath); if (target.exists()) { target.setWritable(true); } FileOutputStream outs = new FileOutputStream(target); BufferedOutputStream bouts = new BufferedOutputStream(outs); int len; while ((len = ins.read(buf)) > 0) { bouts.write(buf, 0, len); } ins.close(); bouts.close(); } /** * Unshelve review into workspace. Workspace is sync'ed to head first then * review unshelved. * * @param review * @throws Exception */ public void unshelveFiles(int review) throws Exception { // skip if review is 0 or less if(review < 1) { log("P4 Task: skipping review: " + review); return; } TimeTask timer = new TimeTask(); log("P4 Task: unshelve review: " + review); // build file revision spec List<IFileSpec> files; String path = iclient.getRoot() + "/..."; files = FileSpecBuilder.makeFileSpecList(path); // Unshelve change for review List<IFileSpec> shelveMsg; shelveMsg = iclient.unshelveChangelist(review, null, 0, true, false); validateFileSpecs(shelveMsg, false, "also opened by", "no such file(s)", "exclusive file already opened"); // force sync any files missed due to INFO messages e.g. exclusive files for (IFileSpec spec : shelveMsg) { if (spec.getOpStatus() != FileSpecOpStatus.VALID) { String msg = spec.getStatusMessage(); if (msg.contains("exclusive file already opened")) { String rev = msg.substring(0, msg.indexOf(" - can't ")); printFile(rev); } } else { log(spec.getDepotPathString()); } } // Remove opened files from have list. RevertFilesOptions rOpts = new RevertFilesOptions(); rOpts.setNoClientRefresh(true); List<IFileSpec> rvtMsg = iclient.revertFiles(files, rOpts); validateFileSpecs(rvtMsg, "file(s) not opened on this client"); log("... duration: " + timer.toString()); } /** * Resolve files in workspace with the specified option. * * @param mode * @throws Exception */ public void resolveFiles(String mode) throws Exception { if ("none".equals(mode)) { return; } TimeTask timer = new TimeTask(); log("P4 Task: resolve: -" + mode); // build file revision spec List<IFileSpec> files; String path = iclient.getRoot() + "/..."; files = FileSpecBuilder.makeFileSpecList(path); // Unshelve change for review ResolveFilesAutoOptions rsvOpts = new ResolveFilesAutoOptions(); rsvOpts.setAcceptTheirs("at".equals(mode)); rsvOpts.setAcceptYours("ay".equals(mode)); rsvOpts.setSafeMerge("as".equals(mode)); rsvOpts.setForceResolve("af".equals(mode)); List<IFileSpec> rsvMsg = iclient.resolveFilesAuto(files, rsvOpts); validateFileSpecs(rsvMsg, "no file(s) to resolve"); log("... duration: " + timer.toString()); } /** * Get the change number for the last change within the scope of the * workspace view. * * @return * @throws Exception */ public int getClientHead() throws Exception { // get last change in server String latestChange = connection.getCounter("change"); int change = Integer.parseInt(latestChange); // build file revision spec String ws = "//" + iclient.getName() + "/..."; List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws); GetChangelistsOptions opts = new GetChangelistsOptions(); opts.setMaxMostRecent(1); List<IChangelistSummary> list = connection.getChangelists(files, opts); if (!list.isEmpty() && list.get(0) != null) { change = list.get(0).getId(); } else { log("P4: no revisions under " + ws + " using latest change: " + change); } return change; } /** * Show all changes within the scope of the client, between the 'from' and * 'to' change limits. * * @param from * @return * @throws Exception */ public List<Integer> listChanges(P4Revision from, P4Revision to) throws Exception { // return empty array, if from and to are equal, or Perforce will report // a change if (from.equals(to)) { return new ArrayList<Integer>(); } String ws = "//" + iclient.getName() + "/...@" + from + "," + to; List<Integer> list = listChanges(ws); if (!from.isLabel()) { Object obj = from.getChange(); list.remove(obj); } return list; } /** * Show all changes within the scope of the client, from the 'from' change * limits. * * @param from * @return * @throws Exception */ public List<Integer> listChanges(P4Revision from) throws Exception { String ws = "//" + iclient.getName() + "/...@" + from + ",now"; List<Integer> list = listChanges(ws); if (!from.isLabel()) { Object obj = from.getChange(); list.remove(obj); } return list; } /** * Show all changes within the scope of the client. * * @return * @throws Exception */ public List<Integer> listChanges() throws Exception { String ws = "//" + iclient.getName() + "/..."; return listChanges(ws); } private List<Integer> listChanges(String ws) throws Exception { List<Integer> list = new ArrayList<Integer>(); List<IFileSpec> spec = FileSpecBuilder.makeFileSpecList(ws); GetChangelistsOptions opts = new GetChangelistsOptions(); opts.setMaxMostRecent(100); List<IChangelistSummary> cngs = connection.getChangelists(spec, opts); if (cngs != null) { for (IChangelistSummary c : cngs) { // don't try to add null or -1 changes if (c != null && c.getId() != -1) { // don't add change entries already in the list if (!(list.contains(c.getId()))) { list.add(c.getId()); } } } } return list; } /** * Fetches a list of changes needed to update the workspace to head. * * @return * @throws Exception */ public List<Integer> listHaveChanges() throws Exception { String path = "//" + iclient.getName() + "/..."; return listHaveChanges(path); } /** * Fetches a list of changes needed to update the workspace to the specified * limit. The limit could be a Perforce change number or label. * * @param changeLimit * @return * @throws Exception */ public List<Integer> listHaveChanges(P4Revision changeLimit) throws Exception { String path = "//" + iclient.getName() + "/..."; String fileSpec = path + "@" + changeLimit; return listHaveChanges(fileSpec); } private List<Integer> listHaveChanges(String fileSpec) throws Exception { List<Integer> haveChanges = new ArrayList<Integer>(); Map<String, Object>[] map; map = connection.execMapCmd("cstat", new String[] { fileSpec }, null); for (Map<String, Object> entry : map) { String status = (String) entry.get("status"); if (status != null) { if (status.startsWith("have")) { String value = (String) entry.get("change"); int change = Integer.parseInt(value); haveChanges.add(change); } } } return haveChanges; } public ClientView getClientView() { return iclient.getClientView(); } public boolean isClientValid(Workspace workspace) { if (iclient == null) { String msg; if (workspace instanceof TemplateWorkspaceImpl) { TemplateWorkspaceImpl template = ((TemplateWorkspaceImpl) workspace); String name = template.getTemplateName(); msg = "P4: Template workspace not found: " + name; } else { String name = workspace.getFullName(); msg = "P4: Unable to use workspace: " + name; } logger.severe(msg); if (listener != null) { log(msg); } return false; } return true; } public IClient getClient() { return iclient; } }
package org.jenkinsci.plugins.p4.groovy; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.p4.client.ClientHelper; import org.jenkinsci.plugins.p4.tasks.AbstractTask; import org.jenkinsci.remoting.RoleChecker; import org.jenkinsci.remoting.RoleSensitive; import hudson.FilePath.FileCallable; import hudson.remoting.VirtualChannel; import jenkins.security.Roles; public class P4GroovyTask extends AbstractTask implements FileCallable<Map<String,Object>[]>, Serializable { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(P4GroovyTask.class.getName()); private final String cmd; private final String[] args; private final Map<String,Object> spec; public P4GroovyTask(String cmd, String[] args, Map<String,Object> spec) { this.cmd = cmd; this.args = Arrays.copyOf(args, args.length); this.spec = spec; } public P4GroovyTask(String cmd, String... args) { this(cmd, args, null); } @Override public Map<String,Object>[] invoke(File workspace, VirtualChannel channel) throws IOException { return (Map<String,Object>[]) tryTask(); } @Override public Object task(ClientHelper p4) throws Exception { try { if (!checkConnection(p4)) { return null; } return p4.getConnection().execMapCmd(cmd, args, spec); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("P4: Unable to execute p4 groovy task: "); sb.append(cmd==null? "[null]": cmd).append(" "); sb.append(args==null? "[null]": Arrays.toString(args)).append(": "); sb.append(e.toString()); String err = sb.toString(); logger.severe(err); p4.log(err); throw e; } finally { p4.disconnect(); } } @Override public void checkRoles(RoleChecker checker) throws SecurityException { checker.check((RoleSensitive) this, Roles.SLAVE); } }
package org.jenkinsci.plugins.rpmmock; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Map; public class RpmMockBuilder extends Builder { private final String specFile; private final Boolean downloadSources; private final Boolean verbose; private final String configName; @DataBoundConstructor public RpmMockBuilder(String specFile, Boolean downloadSources, Boolean verbose, String configName) { this.specFile = specFile; this.downloadSources = downloadSources; this.verbose = verbose; this.configName = configName; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { PrintStream logger = listener.getLogger(); FilePath workspace = build.getWorkspace(); CommandRunner commandRunner = getCommandRunner(build, launcher, listener); int result = 1; String sourceDir = workspace+"/SOURCES", specFile = workspace+"/"+getSpecFile(); if( getDownloadSources() ){ try { String verboseParam = ""; if( getVerbose() ){ verboseParam = "-D"; } result = commandRunner.runCommand("spectool -g {0} -R -C {0} "+verboseParam, specFile, sourceDir ); if( CommandRunner.isError( result ) ){ logger.println( "Spectool doesn't finish properly, exit code: "+result ); return false; } } catch (Exception e) { logger.println("Downloading sources fail due to: " + e.getMessage()); return false; } } String command, resultSRPMDir = workspace+"/SRPMS", resultRPMDir = workspace+"/RPMS"; try { command = buildMockCmd()+" --resultdir={0} --buildsrpm --spec {1} --sources {2}"; result = commandRunner.runCommand(command, resultSRPMDir, specFile, sourceDir ); if( CommandRunner.isError(result) ){ logger.println( "Source rpm using mock creation doesn't finish properly, exit code:"+result ); return false; } }catch (Exception e) { logger.println("Building source RPM fail due to: " + e.getMessage()); return false; } try { command = buildMockCmd()+" --resultdir={0} --rebuild {1}"; * See <tt>src/main/resources/hudson/plugins/hello_world/RpmMockBuilder/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { protected String mockCmd; /** * In order to load the persisted global configuration, you have to * call load() in the constructor. */ public DescriptorImpl() { load(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable specFile is used in the configuration screen. */ public String getDisplayName() { return "Build RPM using mock"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { setMockCmd(formData.getString("mockCmd")); save(); return super.configure(req,formData); } public FormValidation doCheckMockCmd( @QueryParameter String mockCmd ){ File mockExe = new File( mockCmd ); if( mockExe.canExecute() ){ return FormValidation.error( "Mock command '"+mockCmd+"' must be executable" ); } return FormValidation.ok(); } public String defaultMockCmd(){ return "/usr/bin/mock"; } public String getMockCmd() { return mockCmd; } public void setMockCmd( String mockCmd ) { this.mockCmd = mockCmd; } } }
package org.jfrog.hudson.util; import hudson.FilePath; import hudson.model.AbstractBuild; import hudson.model.Computer; import hudson.model.Hudson; import hudson.slaves.SlaveComputer; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.IOException; /** * @author Noam Y. Tenne */ public class PluginDependencyHelper { public static FilePath getActualDependencyDirectory(AbstractBuild build, File localDependencyFile) throws IOException, InterruptedException { File localDependencyDir = localDependencyFile.getParentFile(); // if (!(Computer.currentComputer() instanceof SlaveComputer)) { // return new FilePath(localDependencyDir); String pluginVersion = Hudson.getInstance().getPluginManager().getPlugin("artifactory").getVersion(); if (pluginVersion.contains(" ")) { pluginVersion = StringUtils.split(pluginVersion, " ")[0]; } FilePath remoteDependencyDir = new FilePath(build.getBuiltOn().getRootPath(),"cache/artifactory-plugin/" + pluginVersion); if (!remoteDependencyDir.exists()) { remoteDependencyDir.mkdirs(); } //Check if the dependencies have already been transferred successfully FilePath remoteDependencyMark = new FilePath(remoteDependencyDir, "ok"); if (!remoteDependencyMark.exists()) { File[] localDependencies = localDependencyDir.listFiles(); for (File localDependency : localDependencies) { if (localDependency.getName().equals("classes.jar")) // skip classes in this plugin source tree. // TODO: for a proper long term fix, see my comment in JENKINS-18401 continue; FilePath remoteDependencyFilePath = new FilePath(remoteDependencyDir, localDependency.getName()); if (!remoteDependencyFilePath.exists()) { FilePath localDependencyFilePath = new FilePath(localDependency); localDependencyFilePath.copyTo(remoteDependencyFilePath); } } //Mark that all the dependencies have been transferred successfully for future references remoteDependencyMark.touch(System.currentTimeMillis()); } return remoteDependencyDir; } }
package org.jtrfp.trcl.game; import java.awt.Frame; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.WeakReference; import org.jtrfp.trcl.core.Feature; import org.jtrfp.trcl.core.FeatureFactory; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.gui.LevelSkipWindow; import org.jtrfp.trcl.gui.MenuSystem; import org.jtrfp.trcl.gui.RootWindowFactory.RootWindow; import org.jtrfp.trcl.shell.GameShellFactory.GameShell; import org.springframework.stereotype.Component; @Component public class LevelSkipMenuItemFactory implements FeatureFactory<TVF3Game> { private LevelSkipWindow levelSkipWindow; protected static final String [] MENU_ITEM_PATH = new String [] {"Game","Skip To Level"}; @Override public Feature<TVF3Game> newInstance(TVF3Game target) { final LevelSkipMenuItem result = new LevelSkipMenuItem(); final Frame frame = (target).getTr().getRootWindow(); result.setMenuSystem(Features.get(frame, MenuSystem.class)); return result; } @Override public Class<TVF3Game> getTargetClass() { return TVF3Game.class; } @Override public Class<? extends Feature> getFeatureClass() { return LevelSkipMenuItem.class; } class LevelSkipMenuItem implements Feature<TVF3Game>{ private final MenuItemListener menuItemListener = new MenuItemListener(); private final RunStateListener runStateListener = new RunStateListener(); private final VoxListener voxListener = new VoxListener(); private WeakReference<Game> target; private MenuSystem menuSystem; @Override public void apply(TVF3Game target) { this.target = new WeakReference<Game>(target); final MenuSystem menuSystem = getMenuSystem(); menuSystem.addMenuItem(MenuSystem.MIDDLE, MENU_ITEM_PATH); menuSystem.addMenuItemListener(menuItemListener, MENU_ITEM_PATH); final TR tr = target.getTr(); tr.addPropertyChangeListener (TRFactory.RUN_STATE, runStateListener); target.addPropertyChangeListener(TVF3Game.VOX , voxListener); this.getLevelSkipWindow();//This make sure the cache is set so that display() doesn't get stuck } @Override public void destruct(TVF3Game target) { target.getTr().removePropertyChangeListener(TRFactory.RUN_STATE,runStateListener); final MenuSystem menuSystem = getMenuSystem(); menuSystem.removeMenuItemListener(menuItemListener, MENU_ITEM_PATH); menuSystem.removeMenuItem(MENU_ITEM_PATH); target.removePropertyChangeListener(TVF3Game.VOX, voxListener); } private class MenuItemListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //TODO: Use non-display() thread. getLevelSkipWindow().setVisible(true); } }//end MenuItemListener private class RunStateListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { final MenuSystem menuSystem = getMenuSystem(); menuSystem.setMenuItemEnabled( evt.getNewValue() instanceof Game.GameLoadedMode, MENU_ITEM_PATH); }//end propertyChange(...) }//end RunStateListener private class VoxListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { getLevelSkipWindow().setGame(target.get()); } }//end VoxListener public MenuSystem getMenuSystem() { return menuSystem; } private LevelSkipWindow getLevelSkipWindow(){ if(levelSkipWindow==null){ final TVF3Game game = ((TVF3Game)(target.get())); final TR tr = game.getTr(); final LevelSkipWindow levelSkipWindow = new LevelSkipWindow(game.getTr()); final Point screenXY = Features.get(game.getTr(), RootWindow.class).getLocationOnScreen(); levelSkipWindow.setLocation(screenXY); final GameShell gameShell = Features.get(tr,GameShell.class); assert gameShell != null; levelSkipWindow.setGameShell(gameShell); LevelSkipMenuItemFactory.this.levelSkipWindow = levelSkipWindow; } return levelSkipWindow; }//end getLevelSkipWindow() public void setMenuSystem(MenuSystem menuSystem) { this.menuSystem = menuSystem; } }//end LevelSkipMenuItem }//end LevelSkipMenuItemFactory
package org.pfaa.chemica.fluid; import java.util.Collection; import java.util.Collections; import java.util.List; import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemPotion; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import com.google.common.base.CaseFormat; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /* Alternative design: * Use a brewing API to define a custom potion for every fluid. Then, the FluidContainerRegistry * maps from fluid to potion (damage on the itemstack), and vice versa. * Otherwise, this class may behave strangely in a brewing stand. */ public class FilledGlassBottleItem extends ItemPotion { public FilledGlassBottleItem() { this.setTextureName("potion"); this.setMaxStackSize(64); this.setHasSubtypes(true); } private Fluid getFluidForItemStack(ItemStack itemStack) { FluidStack fluidStack = FluidContainerRegistry.getFluidForFilledItem(itemStack); return fluidStack.getFluid(); } @Override @SideOnly(Side.CLIENT) public int getColorFromItemStack(ItemStack itemStack, int renderPass) { if (renderPass > 0) { return super.getColorFromItemStack(itemStack, renderPass); } else { return this.getFluidForItemStack(itemStack).getBlock().colorMultiplier(null, 0, 0, 0); } } @Override @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack p_77636_1_) { return false; } @Override public List<PotionEffect> getEffects(ItemStack itemStack) { Fluid fluid = this.getFluidForItemStack(itemStack); if (fluid instanceof IndustrialFluid) { return ((IndustrialFluid)fluid).getProperties().hazard.getIngestionEffects(); } return Collections.EMPTY_LIST; } @Override public List<PotionEffect> getEffects(int damage) { return this.getEffects(new ItemStack(this, 1, damage)); } @Override public String getUnlocalizedName(ItemStack itemStack) { String fluidToken = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, this.getFluidForItemStack(itemStack).getName()); return "item." + fluidToken + "Bottle"; } @Override public String getItemStackDisplayName(ItemStack p_77653_1_) { return StatCollector.translateToLocal(this.getUnlocalizedName(p_77653_1_) + ".name").trim(); } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs tabs, List itemStacks) { Collection<Fluid> fluids = FluidRegistry.getRegisteredFluids().values(); for (Fluid fluid : fluids) { FluidStack fluidStack = new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME); ItemStack filledContainer = FluidContainerRegistry.fillFluidContainer(fluidStack, FluidContainerRegistry.EMPTY_BOTTLE); if (filledContainer != null && filledContainer.getItem() instanceof FilledGlassBottleItem) { itemStacks.add(filledContainer); } } } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemStack, EntityPlayer player, List lines, boolean p_77624_4_) { Fluid fluid = this.getFluidForItemStack(itemStack); if (fluid instanceof IndustrialFluid) { IndustrialFluid industrialFluid = (IndustrialFluid)fluid; lines.add(EnumChatFormatting.BLUE + I18n.format("label.hazard.health") + ": " + industrialFluid.getProperties().hazard.health); } } }
package org.spacehq.mc.protocol.data.message; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.List; public abstract class Message implements Cloneable { private MessageStyle style = new MessageStyle(); private List<Message> extra = new ArrayList<Message>(); public abstract String getText(); public String getFullText() { StringBuilder build = new StringBuilder(this.getText()); for(Message msg : this.extra) { build.append(msg.getFullText()); } return build.toString(); } public MessageStyle getStyle() { return this.style; } public List<Message> getExtra() { return new ArrayList<Message>(this.extra); } public Message setStyle(MessageStyle style) { this.style = style; return this; } public Message setExtra(List<Message> extra) { this.extra = new ArrayList<Message>(extra); for(Message msg : this.extra) { msg.getStyle().setParent(this.style); } return this; } public Message addExtra(Message message) { this.extra.add(message); message.getStyle().setParent(this.style); return this; } public Message removeExtra(Message message) { this.extra.remove(message); message.getStyle().setParent(null); return this; } public Message clearExtra() { for(Message msg : this.extra) { msg.getStyle().setParent(null); } this.extra.clear(); return this; } @Override public String toString() { return this.getFullText(); } @Override public abstract Message clone(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Message message = (Message) o; if (!extra.equals(message.extra)) return false; if (!style.equals(message.style)) return false; return true; } @Override public int hashCode() { int result = style.hashCode(); result = 31 * result + extra.hashCode(); return result; } public String toJsonString() { return this.toJson().toString(); } public JsonElement toJson() { JsonObject json = new JsonObject(); json.addProperty("color", this.style.getColor().toString()); for(ChatFormat format : this.style.getFormats()) { json.addProperty(format.toString(), true); } if(this.style.getClickEvent() != null) { JsonObject click = new JsonObject(); click.addProperty("action", this.style.getClickEvent().getAction().toString()); click.addProperty("value", this.style.getClickEvent().getValue()); json.add("clickEvent", click); } if(this.style.getHoverEvent() != null) { JsonObject hover = new JsonObject(); hover.addProperty("action", this.style.getHoverEvent().getAction().toString()); hover.add("value", this.style.getHoverEvent().getValue().toJson()); json.add("hoverEvent", hover); } if(this.style.getInsertion() != null) { json.addProperty("insertion", this.style.getInsertion()); } if(this.extra.size() > 0) { JsonArray extra = new JsonArray(); for(Message msg : this.extra) { extra.add(msg.toJson()); } json.add("extra", extra); } return json; } public static Message fromString(String str) { try { return fromJson(new JsonParser().parse(str)); } catch(Exception e) { return new TextMessage(str); } } public static Message fromJson(JsonElement e) { if(e.isJsonPrimitive()) { return new TextMessage(e.getAsString()); } else if(e.isJsonObject()) { JsonObject json = e.getAsJsonObject(); Message msg = null; if(json.has("text")) { msg = new TextMessage(json.get("text").getAsString()); } else if(json.has("translate")) { Message with[] = new Message[0]; if(json.has("with")) { JsonArray withJson = json.get("with").getAsJsonArray(); with = new Message[withJson.size()]; for(int index = 0; index < withJson.size(); index++) { JsonElement el = withJson.get(index); if(el.isJsonPrimitive()) { with[index] = new TextMessage(el.getAsString()); } else { with[index] = Message.fromJson(el.getAsJsonObject()); } } } msg = new TranslationMessage(json.get("translate").getAsString(), with); } else { throw new IllegalArgumentException("Unknown message type in json: " + json.toString()); } MessageStyle style = new MessageStyle(); if(json.has("color")) { style.setColor(ChatColor.byName(json.get("color").getAsString())); } for(ChatFormat format : ChatFormat.values()) { if(json.has(format.toString()) && json.get(format.toString()).getAsBoolean()) { style.addFormat(format); } } if(json.has("clickEvent")) { JsonObject click = json.get("clickEvent").getAsJsonObject(); style.setClickEvent(new ClickEvent(ClickAction.byName(click.get("action").getAsString()), click.get("value").getAsString())); } if(json.has("hoverEvent")) { JsonObject hover = json.get("hoverEvent").getAsJsonObject(); style.setHoverEvent(new HoverEvent(HoverAction.byName(hover.get("action").getAsString()), Message.fromJson(hover.get("value")))); } if(json.has("insertion")) { style.setInsertion(json.get("insertion").getAsString()); } msg.setStyle(style); if(json.has("extra")) { JsonArray extraJson = json.get("extra").getAsJsonArray(); List<Message> extra = new ArrayList<Message>(); for(int index = 0; index < extraJson.size(); index++) { JsonElement el = extraJson.get(index); if(el.isJsonPrimitive()) { extra.add(new TextMessage(el.getAsString())); } else { extra.add(Message.fromJson(el.getAsJsonObject())); } } msg.setExtra(extra); } return msg; } else { throw new IllegalArgumentException("Cannot convert " + e.getClass().getSimpleName() + " to a message."); } } }
package org.spongepowered.api.item.potion; import org.spongepowered.api.CatalogType; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.text.translation.Translatable; import org.spongepowered.api.text.translation.Translation; import org.spongepowered.api.util.annotation.CatalogedBy; import java.util.List; /** * Represents a type of potion with specific {@link PotionEffect}s. */ @CatalogedBy(PotionTypes.class) public interface PotionType extends CatalogType { List<PotionEffect> getEffects(); }
package org.tuberlin.de.district_trips; import com.google.gson.Gson; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.util.Collector; import org.tuberlin.de.geodata.MapCoordToDistrict; import org.tuberlin.de.read_data.Pickup; import org.tuberlin.de.read_data.Taxidrive; @SuppressWarnings("serial") public class DistrictTrips { public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); String inputFilepath = "hdfs:///TaxiData/sorted_data.csv"; //local: "data/testData.csv"; String districtsCsvFilepath = "hdfs:///data/ny_districts.csv"; //local: "data/geodata/ny_districts.csv"; String dataWithDistrictsFilepath = "hdfs:///data/sorted_data_with_districts"; //local: "data/testDataWithDistricts"; if (args != null) { if (args.length > 2) { dataWithDistrictsFilepath = args[2]; } if (args.length > 1) { districtsCsvFilepath = args[1]; } if (args.length > 0) { districtsCsvFilepath = args[0]; } } MapCoordToDistrict.main(new String[]{inputFilepath, districtsCsvFilepath}); DataSet<String> textInput = env.readTextFile(dataWithDistrictsFilepath); DataSet<Pickup> pickupDataset = textInput.flatMap(new FlatMapFunction<String, Pickup>() { @Override public void flatMap(String value, Collector<Pickup> collector) throws Exception { Taxidrive taxidrive = new Gson().fromJson(value, Taxidrive.class); if (taxidrive.getPickupNeighborhood() != null && taxidrive.getPickupBorough() != null) { Pickup pickup = new Pickup.Builder() .setNeighborhood(taxidrive.getPickupNeighborhood()) .setBorough(taxidrive.getPickupBorough()) .build(); collector.collect(pickup); } } }); DataSet<Pickup> dsGroupedByNeighborhood = pickupDataset.groupBy("neighborhood").reduce((t1, t2) -> { int sum = t1.getCount() + t2.getCount(); return new Pickup.Builder() .setNeighborhood(t1.getNeighborhood()) .setBorough(t1.getBorough()) .setCount(sum) .build(); }); dsGroupedByNeighborhood.print(); DataSet<Pickup> dsGroupedByBorough = pickupDataset.groupBy("borough").reduce((t1, t2) -> { int sum = t1.getCount() + t2.getCount(); return new Pickup.Builder() .setNeighborhood(t1.getNeighborhood()) .setBorough(t1.getBorough()) .setCount(sum) .build(); }); dsGroupedByBorough.print(); } }
package ratul.myexperiments.cluster; import ratul.myexperiments.cluster.ClusterMsgs.*; import akka.actor.*; import scala.concurrent.duration.Duration; import java.util.concurrent.TimeUnit; public class VideoStorageClient extends UntypedActor { ActorRef p = getContext().actorSelection("/user/video-storage-coordinator-proxy").resolveOne(); Cancellable cancellable = getContext().system().scheduler().schedule(Duration.Zero(), Duration.create(1000, TimeUnit.MILLISECONDS), p, new Hello(), getContext().system().dispatcher(), null); @Override public void onReceive(Object message) { if (message instanceof Hello) { Hello job = (Hello) message; getSender().tell(new HelloResult(), getSelf()); //getContext().actorSelection("/user/video-storage-coordinator-proxy").tell(new HelloResult(), getSelf()); } else { unhandled(message); } } }
package uk.ac.ebi.ena.taxonomy.client; import uk.ac.ebi.ena.taxonomy.taxon.Taxon; import uk.ac.ebi.ena.taxonomy.taxon.TaxonomyException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; enum TaxonomyUrl { scientificName("scientific-name"), taxid("tax-id"), anyName("any-name"), commonName("common-name"), suggestForSubmission("suggest-for-submission"); private final String url = "http: private String searchName; private TaxonomyUrl(String searchName) { this.searchName = searchName; } public String get(String searchId) { return String.format(url, searchName, searchId); } public boolean isValid(String searchId) throws IOException { URL url = new URL(get(searchId).replaceAll(" ", "%20")); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.connect(); return con.getResponseCode() >= 400; } } public interface TaxonomyClient { List<Taxon> suggestTaxa(String partialName) throws TaxonomyException; List<Taxon> suggestTaxa(String partialName, boolean metagenome) throws TaxonomyException; List<Taxon> suggestTaxa(String partialName, boolean metagenome, int limit) throws TaxonomyException; List<Taxon> suggestTaxa(String partialName, int limit) throws TaxonomyException; List<Taxon> getTaxonByScientificName(String scientificName) throws TaxonomyException; List<Taxon> getTaxonByCommonName(String commonName) throws TaxonomyException; List<Taxon> getTaxonByAnyName(String commonName) throws TaxonomyException; Taxon getTaxonByTaxid(Long taxId) throws TaxonomyException; Taxon getSubmittableTaxonByTaxId(Long taxId) throws TaxonomyException; Taxon getSubmittableTaxonByScientificName(String scientificName) throws TaxonomyException; Taxon getSubmittableTaxonByAnyName(String anyName) throws TaxonomyException; Taxon getSubmittableTaxonByCommonName(String commonName) throws TaxonomyException; }
package uk.co.skyem.projects.emuZ80.cpu; import uk.co.skyem.projects.emuZ80.util.buffer.IByteHandler; public class MemoryRouter { private IByteHandler memoryBus; public MemoryRouter(IByteHandler targetBus) { memoryBus = targetBus; } public void putByte(short address, Byte data) { memoryBus.putByte(safeShortToInt(address), data); } public void putWord(short address, Short data) { memoryBus.putByte(Short.toUnsignedInt(address), (byte)(data & 0x00FF)); memoryBus.putByte(Short.toUnsignedInt(++address), (byte)((data & 0xFF00)>>8)); } public byte getByte(short address) { return memoryBus.getByte(Short.toUnsignedInt(address)); } public short getWord(short address) { byte l = memoryBus.getByte(Short.toUnsignedInt(address)); byte h = memoryBus.getByte(Short.toUnsignedInt(++address)); int lh = ((h << 8) & 0xFF00) | (l & 0xFF); return (short) (lh); } }
package zmaster587.advancedRocketry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import zmaster587.advancedRocketry.api.*; import zmaster587.advancedRocketry.api.atmosphere.AtmosphereRegister; import zmaster587.advancedRocketry.api.fuel.FuelRegistry; import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType; import zmaster587.advancedRocketry.api.satellite.SatelliteProperties; import zmaster587.advancedRocketry.armor.ItemSpaceArmor; import zmaster587.advancedRocketry.atmosphere.AtmosphereVacuum; import zmaster587.advancedRocketry.block.BlockCharcoalLog; import zmaster587.advancedRocketry.block.BlockCrystal; import zmaster587.advancedRocketry.block.BlockDoor2; import zmaster587.advancedRocketry.block.BlockElectricMushroom; import zmaster587.advancedRocketry.block.BlockFluid; import zmaster587.advancedRocketry.block.BlockGeneric; import zmaster587.advancedRocketry.block.BlockIntake; import zmaster587.advancedRocketry.block.BlockLandingPad; import zmaster587.advancedRocketry.block.BlockLaser; import zmaster587.advancedRocketry.block.BlockLightSource; import zmaster587.advancedRocketry.block.BlockLinkedHorizontalTexture; import zmaster587.advancedRocketry.block.BlockMiningDrill; import zmaster587.advancedRocketry.block.BlockPlanetSoil; import zmaster587.advancedRocketry.block.BlockPress; import zmaster587.advancedRocketry.block.BlockPressurizedFluidTank; import zmaster587.advancedRocketry.block.BlockQuartzCrucible; import zmaster587.advancedRocketry.block.BlockRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockRocketMotor; import zmaster587.advancedRocketry.block.BlockRotatableModel; import zmaster587.advancedRocketry.block.BlockSeat; import zmaster587.advancedRocketry.block.BlockFuelTank; import zmaster587.advancedRocketry.block.BlockSolarPanel; import zmaster587.advancedRocketry.block.BlockTileNeighborUpdate; import zmaster587.advancedRocketry.block.BlockTileRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockWarpCore; import zmaster587.advancedRocketry.block.BlockWarpShipMonitor; import zmaster587.advancedRocketry.block.cable.BlockDataCable; import zmaster587.advancedRocketry.block.multiblock.BlockARHatch; import zmaster587.advancedRocketry.block.plant.BlockAlienLeaves; import zmaster587.advancedRocketry.block.plant.BlockAlienSapling; import zmaster587.advancedRocketry.block.plant.BlockAlienWood; import zmaster587.advancedRocketry.block.BlockTorchUnlit; import zmaster587.advancedRocketry.command.WorldCommand; import zmaster587.advancedRocketry.common.CommonProxy; import zmaster587.advancedRocketry.dimension.DimensionManager; import zmaster587.advancedRocketry.dimension.DimensionProperties; import zmaster587.advancedRocketry.entity.EntityDummy; import zmaster587.advancedRocketry.entity.EntityLaserNode; import zmaster587.advancedRocketry.entity.EntityRocket; import zmaster587.advancedRocketry.entity.EntityStationDeployedRocket; import zmaster587.advancedRocketry.event.BucketHandler; import zmaster587.advancedRocketry.event.CableTickHandler; import zmaster587.advancedRocketry.event.PlanetEventHandler; import zmaster587.advancedRocketry.event.WorldEvents; import zmaster587.advancedRocketry.integration.CompatibilityMgr; import zmaster587.advancedRocketry.integration.GalacticCraftHandler; import zmaster587.libVulpes.inventory.GuiHandler; import zmaster587.libVulpes.items.ItemBlockMeta; import zmaster587.libVulpes.items.ItemIngredient; import zmaster587.libVulpes.items.ItemProjector; import zmaster587.advancedRocketry.item.*; import zmaster587.advancedRocketry.item.components.ItemJetpack; import zmaster587.advancedRocketry.item.components.ItemPressureTank; import zmaster587.advancedRocketry.item.components.ItemUpgrade; import zmaster587.advancedRocketry.mission.MissionGasCollection; import zmaster587.advancedRocketry.mission.MissionOreMining; import zmaster587.advancedRocketry.network.PacketAtmSync; import zmaster587.advancedRocketry.network.PacketBiomeIDChange; import zmaster587.advancedRocketry.network.PacketDimInfo; import zmaster587.advancedRocketry.network.PacketOxygenState; import zmaster587.advancedRocketry.network.PacketSatellite; import zmaster587.advancedRocketry.network.PacketSpaceStationInfo; import zmaster587.advancedRocketry.network.PacketStationUpdate; import zmaster587.advancedRocketry.network.PacketStellarInfo; import zmaster587.advancedRocketry.network.PacketStorageTileUpdate; import zmaster587.advancedRocketry.satellite.SatelliteBiomeChanger; import zmaster587.advancedRocketry.satellite.SatelliteComposition; import zmaster587.advancedRocketry.satellite.SatelliteDensity; import zmaster587.advancedRocketry.satellite.SatelliteEnergy; import zmaster587.advancedRocketry.satellite.SatelliteMassScanner; import zmaster587.advancedRocketry.satellite.SatelliteOptical; import zmaster587.advancedRocketry.satellite.SatelliteOreMapping; import zmaster587.advancedRocketry.stations.SpaceObject; import zmaster587.advancedRocketry.stations.SpaceObjectManager; import zmaster587.advancedRocketry.tile.Satellite.TileEntitySatelliteControlCenter; import zmaster587.advancedRocketry.tile.Satellite.TileSatelliteBuilder; import zmaster587.advancedRocketry.tile.*; import zmaster587.advancedRocketry.tile.cables.TileDataPipe; import zmaster587.advancedRocketry.tile.cables.TileLiquidPipe; import zmaster587.advancedRocketry.tile.hatch.TileDataBus; import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityFuelingStation; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityMoniteringStation; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidUnloader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketUnloader; import zmaster587.advancedRocketry.tile.multiblock.*; import zmaster587.advancedRocketry.tile.multiblock.energy.TileMicrowaveReciever; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; import zmaster587.advancedRocketry.tile.oxygen.TileCO2Scrubber; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenCharger; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenVent; import zmaster587.advancedRocketry.tile.station.TileLandingPad; import zmaster587.advancedRocketry.tile.station.TileStationGravityController; import zmaster587.advancedRocketry.tile.station.TileStationOrientationControl; import zmaster587.advancedRocketry.tile.station.TileWarpShipMonitor; import zmaster587.advancedRocketry.util.FluidColored; import zmaster587.advancedRocketry.util.SealableBlockHandler; import zmaster587.advancedRocketry.util.XMLPlanetLoader; import zmaster587.advancedRocketry.world.biome.BiomeGenAlienForest; import zmaster587.advancedRocketry.world.biome.BiomeGenCrystal; import zmaster587.advancedRocketry.world.biome.BiomeGenDeepSwamp; import zmaster587.advancedRocketry.world.biome.BiomeGenHotDryRock; import zmaster587.advancedRocketry.world.biome.BiomeGenMoon; import zmaster587.advancedRocketry.world.biome.BiomeGenMarsh; import zmaster587.advancedRocketry.world.biome.BiomeGenOceanSpires; import zmaster587.advancedRocketry.world.biome.BiomeGenSpace; import zmaster587.advancedRocketry.world.biome.BiomeGenStormland; import zmaster587.advancedRocketry.world.ore.OreGenerator; import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet; import zmaster587.advancedRocketry.world.provider.WorldProviderSpace; import zmaster587.advancedRocketry.world.type.WorldTypePlanetGen; import zmaster587.advancedRocketry.world.type.WorldTypeSpace; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.LibVulpesBlocks; import zmaster587.libVulpes.api.LibVulpesItems; import zmaster587.libVulpes.api.material.AllowedProducts; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.api.material.MixedMaterial; import zmaster587.libVulpes.block.BlockAlphaTexture; import zmaster587.libVulpes.block.BlockMeta; import zmaster587.libVulpes.block.BlockTile; import zmaster587.libVulpes.block.multiblock.BlockMultiBlockComponentVisible; import zmaster587.libVulpes.block.multiblock.BlockMultiblockMachine; import zmaster587.libVulpes.network.PacketHandler; import zmaster587.libVulpes.network.PacketItemModifcation; import zmaster587.libVulpes.recipe.NumberedOreDictStack; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.TileMaterial; import zmaster587.libVulpes.tile.multiblock.TileMultiBlock; import zmaster587.libVulpes.util.InputSyncHandler; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.logging.Logger; @Mod(modid="advancedRocketry", name="Advanced Rocketry", version="%VERSION%", dependencies="required-after:libVulpes@[%LIBVULPESVERSION%,)") public class AdvancedRocketry { @SidedProxy(clientSide="zmaster587.advancedRocketry.client.ClientProxy", serverSide="zmaster587.advancedRocketry.common.CommonProxy") public static CommonProxy proxy; @Instance(value = Constants.modId) public static AdvancedRocketry instance; public static WorldType planetWorldType; public static WorldType spaceWorldType; public static CompatibilityMgr compat = new CompatibilityMgr(); public static Logger logger = Logger.getLogger(Constants.modId); private static Configuration config; private static final String BIOMECATETORY = "Biomes"; String[] sealableBlockWhileList; public MaterialRegistry materialRegistry = new MaterialRegistry(); private HashMap<AllowedProducts, HashSet<String>> modProducts = new HashMap<AllowedProducts, HashSet<String>>(); private static CreativeTabs tabAdvRocketry = new CreativeTabs("advancedRocketry") { @Override public Item getTabIconItem() { return AdvancedRocketryItems.itemSatelliteIdChip; } }; @EventHandler public void preInit(FMLPreInitializationEvent event) { //Init API DimensionManager.planetWorldProvider = WorldProviderPlanet.class; AdvancedRocketryAPI.atomsphereSealHandler = SealableBlockHandler.INSTANCE; ((SealableBlockHandler)AdvancedRocketryAPI.atomsphereSealHandler).loadDefaultData(); config = new Configuration(new File(event.getModConfigurationDirectory(), "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/advancedRocketry.cfg")); config.load(); final String oreGen = "Ore Generation"; final String ROCKET = "Rockets"; final String MOD_INTERACTION = "Mod Interaction"; final String PLANET = "Planet"; final String ASTEROID = "Asteroid"; final String GAS_MINING = "GasMining"; final String PERFORMANCE = "Performance"; AtmosphereVacuum.damageValue = (int) config.get(Configuration.CATEGORY_GENERAL, "vacuumDamage", 1, "Amount of damage taken every second in a vacuum").getInt(); zmaster587.advancedRocketry.api.Configuration.buildSpeedMultiplier = (float) config.get(Configuration.CATEGORY_GENERAL, "buildSpeedMultiplier", 1f, "Multiplier for the build speed of the Rocket Builder (0.5 is twice as fast 2 is half as fast").getDouble(); zmaster587.advancedRocketry.api.Configuration.spaceDimId = config.get(Configuration.CATEGORY_GENERAL,"spaceStationId" , -2,"Dimension ID to use for space stations").getInt(); zmaster587.advancedRocketry.api.Configuration.enableOxygen = config.get(Configuration.CATEGORY_GENERAL, "EnableAtmosphericEffects", true, "If true, allows players being hurt due to lack of oxygen and allows effects from non-standard atmosphere types").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods = config.get(Configuration.CATEGORY_GENERAL, "makeMaterialsForOtherMods", true, "If true the machines from AdvancedRocketry will produce things like plates/rods for other mods even if Advanced Rocketry itself does not use the material (This can increase load time)").getBoolean(); zmaster587.advancedRocketry.api.Configuration.scrubberRequiresCartrige = config.get(Configuration.CATEGORY_GENERAL, "scrubberRequiresCartrige", true, "If true the Oxygen scrubbers require a consumable carbon collection cartridge").getBoolean(); zmaster587.advancedRocketry.api.Configuration.enableLaserDrill = config.get(Configuration.CATEGORY_GENERAL, "EnableLaserDrill", true, "Enables the laser drill machine").getBoolean(); zmaster587.advancedRocketry.api.Configuration.enableTerraforming = config.get(Configuration.CATEGORY_GENERAL, "EnableTerraforming", true,"Enables terraforming items and blocks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceSuitOxygenTime = config.get(Configuration.CATEGORY_GENERAL, "spaceSuitO2Buffer", 30, "Maximum time in minutes that the spacesuit's internal buffer can store O2 for").getInt(); zmaster587.advancedRocketry.api.Configuration.travelTimeMultiplier = (float)config.get(Configuration.CATEGORY_GENERAL, "warpTravelTime", 1f, "Multiplier for warp travel time").getDouble(); zmaster587.advancedRocketry.api.Configuration.maxBiomesPerPlanet = config.get(Configuration.CATEGORY_GENERAL, "maxBiomesPerPlanet", 5, "Maximum unique biomes per planet, -1 to disable").getInt(); zmaster587.advancedRocketry.api.Configuration.allowTerraforming = config.get(Configuration.CATEGORY_GENERAL, "allowTerraforming", false, "EXPERIMENTAL: If set to true allows contruction and usage of the terraformer. This is known to cause strange world generation after successful terraform").getBoolean(); zmaster587.advancedRocketry.api.Configuration.terraformingBlockSpeed = config.get(Configuration.CATEGORY_GENERAL, "biomeUpdateSpeed", 1, "How many blocks have the biome changed per tick. Large numbers can slow the server down", Integer.MAX_VALUE, 1).getInt(); zmaster587.advancedRocketry.api.Configuration.terraformSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformMult", 1f, "Multplier for terraforming speed").getDouble(); zmaster587.advancedRocketry.api.Configuration.terraformRequiresFluid = config.get(Configuration.CATEGORY_GENERAL, "TerraformerRequiresFluids", true).getBoolean(); DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 127, "Dimensions including and after this number are allowed to be made into planets"); zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes = config.getBoolean("blackListVanillaBiomes", PLANET, false, "Prevents any vanilla biomes from spawning on planets"); zmaster587.advancedRocketry.api.Configuration.overrideGCAir = config.get(MOD_INTERACTION, "OverrideGCAir", true, "If true Galaciticcraft's air will be disabled entirely requiring use of Advanced Rocketry's Oxygen system on GC planets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.fuelPointsPerDilithium = config.get(Configuration.CATEGORY_GENERAL, "pointsPerDilithium", 500, "How many units of fuel should each Dilithium Crystal give to warp ships", 1, 1000).getInt(); zmaster587.advancedRocketry.api.Configuration.electricPlantsSpawnLightning = config.get(Configuration.CATEGORY_GENERAL, "electricPlantsSpawnLightning", true, "Should Electric Mushrooms be able to spawn lightning").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood = config.get(Configuration.CATEGORY_GENERAL, "sawMillCutVanillaWood", true, "Should the cutting machine be able to cut vanilla wood into planks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.automaticRetroRockets = config.get(ROCKET, "autoRetroRockets", true, "Setting to false will disable the retrorockets that fire automatically on reentry on both player and automated rockets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.atmosphereHandleBitMask = config.get(PERFORMANCE, "atmosphereCalculationMethod", 0, "BitMask: 0: no threading, radius based; 1: threading, radius based (EXP); 2: no threading volume based; 3: threading volume based (EXP)").getInt(); zmaster587.advancedRocketry.api.Configuration.advancedVFX = config.get(PERFORMANCE, "advancedVFX", true, "Advanced visual effects").getBoolean(); zmaster587.advancedRocketry.api.Configuration.gasCollectionMult = config.get(GAS_MINING, "gasMissionMultiplier", 1.0, "Multiplier for the amount of time gas collection missions take").getDouble(); zmaster587.advancedRocketry.api.Configuration.asteroidMiningMult = config.get(ASTEROID, "miningMissionMultiplier", 1.0, "Multiplier changing how much total material is brought back from a mining mission").getDouble(); zmaster587.advancedRocketry.api.Configuration.standardAsteroidOres = config.get(ASTEROID, "standardOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in asteriods").getStringList(); //Client zmaster587.advancedRocketry.api.Configuration.rocketRequireFuel = config.get(ROCKET, "rocketsRequireFuel", true, "Set to false if rockets should not require fuel to fly").getBoolean(); zmaster587.advancedRocketry.api.Configuration.rocketThrustMultiplier = config.get(ROCKET, "thrustMultiplier", 1f, "Multiplier for per-engine thrust").getDouble(); zmaster587.advancedRocketry.api.Configuration.fuelCapacityMultiplier = config.get(ROCKET, "fuelCapacityMultiplier", 1f, "Multiplier for per-tank capacity").getDouble(); //Copper Config zmaster587.advancedRocketry.api.Configuration.generateCopper = config.get(oreGen, "GenerateCopper", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.copperClumpSize = config.get(oreGen, "CopperPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.copperPerChunk = config.get(oreGen, "CopperPerChunk", 10).getInt(); //Tin Config zmaster587.advancedRocketry.api.Configuration.generateTin = config.get(oreGen, "GenerateTin", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.tinClumpSize = config.get(oreGen, "TinPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.tinPerChunk = config.get(oreGen, "TinPerChunk", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateDilithium = config.get(oreGen, "generateDilithium", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.dilithiumClumpSize = config.get(oreGen, "DilithiumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunk = config.get(oreGen, "DilithiumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunkMoon = config.get(oreGen, "DilithiumPerChunkLuna", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateAluminum = config.get(oreGen, "generateAluminum", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.aluminumClumpSize = config.get(oreGen, "AluminumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.aluminumPerChunk = config.get(oreGen, "AluminumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.generateRutile = config.get(oreGen, "GenerateRutile", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.rutileClumpSize = config.get(oreGen, "RutilePerClump", 3).getInt(); zmaster587.advancedRocketry.api.Configuration.rutilePerChunk = config.get(oreGen, "RutilePerChunk", 6).getInt(); sealableBlockWhileList = config.getStringList(Configuration.CATEGORY_GENERAL, "sealableBlockWhiteList", new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); //Satellite config zmaster587.advancedRocketry.api.Configuration.microwaveRecieverMulitplier = (float)config.get(Configuration.CATEGORY_GENERAL, "MicrowaveRecieverMulitplier", 1f, "Multiplier for the amount of energy produced by the microwave reciever").getDouble(); config.save(); //Register Packets PacketHandler.addDiscriminator(PacketDimInfo.class); PacketHandler.addDiscriminator(PacketSatellite.class); PacketHandler.addDiscriminator(PacketStellarInfo.class); PacketHandler.addDiscriminator(PacketItemModifcation.class); PacketHandler.addDiscriminator(PacketOxygenState.class); PacketHandler.addDiscriminator(PacketStationUpdate.class); PacketHandler.addDiscriminator(PacketSpaceStationInfo.class); PacketHandler.addDiscriminator(PacketAtmSync.class); PacketHandler.addDiscriminator(PacketBiomeIDChange.class); PacketHandler.addDiscriminator(PacketStorageTileUpdate.class); //if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) MinecraftForge.EVENT_BUS.register(this); SatelliteRegistry.registerSatellite("optical", SatelliteOptical.class); SatelliteRegistry.registerSatellite("solar", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("density", SatelliteDensity.class); SatelliteRegistry.registerSatellite("composition", SatelliteComposition.class); SatelliteRegistry.registerSatellite("mass", SatelliteMassScanner.class); SatelliteRegistry.registerSatellite("asteroidMiner", MissionOreMining.class); SatelliteRegistry.registerSatellite("gasMining", MissionGasCollection.class); SatelliteRegistry.registerSatellite("solarEnergy", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("oreScanner", SatelliteOreMapping.class); SatelliteRegistry.registerSatellite("biomeChanger", SatelliteBiomeChanger.class); AdvancedRocketryBlocks.blocksGeode = new BlockGeneric(MaterialGeode.geode).setBlockName("geode").setCreativeTab(LibVulpes.tabLibVulpesOres).setBlockTextureName("advancedrocketry:geode").setHardness(6f).setResistance(2000F); AdvancedRocketryBlocks.blocksGeode.setHarvestLevel("jackhammer", 2); AdvancedRocketryBlocks.blockLaunchpad = new BlockLinkedHorizontalTexture(Material.rock).setBlockName("pad").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:rocketPad").setHardness(2f).setResistance(10f); AdvancedRocketryBlocks.blockStructureTower = new BlockAlphaTexture(Material.rock).setBlockName("structuretower").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:structuretower").setHardness(2f); AdvancedRocketryBlocks.blockGenericSeat = new BlockSeat(Material.cloth).setBlockName("seat").setCreativeTab(tabAdvRocketry).setBlockTextureName("minecraft:wool_colored_silver").setHardness(0.5f); AdvancedRocketryBlocks.blockEngine = new BlockRocketMotor(Material.rock).setBlockName("rocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockFuelTank = new BlockFuelTank(Material.rock).setBlockName("fuelTank").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockSawBlade = new BlockRotatableModel(Material.rock, TileModelRender.models.SAWBLADE.ordinal()).setCreativeTab(tabAdvRocketry).setBlockName("sawBlade").setHardness(2f); AdvancedRocketryBlocks.blockMotor = new BlockRotatableModel(Material.rock, TileModelRender.models.MOTOR.ordinal()).setCreativeTab(tabAdvRocketry).setBlockName("motor").setHardness(2f); AdvancedRocketryBlocks.blockConcrete = new BlockGeneric(Material.rock).setBlockName("concrete").setBlockTextureName("advancedRocketry:rocketPad_noEdge").setCreativeTab(tabAdvRocketry).setHardness(3f).setResistance(16f); AdvancedRocketryBlocks.blockPlatePress = new BlockPress().setBlockName("blockHandPress").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAirLock = new BlockDoor2(Material.rock).setBlockName("smallAirlockDoor").setBlockTextureName("advancedRocketry:smallAirlockDoor").setHardness(3f).setResistance(8f); AdvancedRocketryBlocks.blockLandingPad = new BlockLandingPad(Material.rock).setBlockName("dockingPad").setBlockTextureName("advancedRocketry:rocketPad_").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenDetection = new BlockRedstoneEmitter(Material.rock,"advancedrocketry:atmosphereDetector_active").setBlockName("atmosphereDetector").setBlockTextureName("advancedRocketry:atmosphereDetector").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenScrubber = new BlockTile(TileCO2Scrubber.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber","advancedrocketry:machineScrubberActive").setCreativeTab(tabAdvRocketry).setBlockName("scrubber").setHardness(3f); AdvancedRocketryBlocks.blockUnlitTorch = new BlockTorchUnlit().setHardness(0.0F).setBlockName("unlittorch").setBlockTextureName("minecraft:torch_on"); AdvancedRocketryBlocks.blockVitrifiedSand = new BlockGeneric(Material.sand).setBlockName("vitrifiedSand").setCreativeTab(CreativeTabs.tabBlock).setBlockTextureName("advancedrocketry:vitrifiedSand").setHardness(0.5F).setStepSound(Block.soundTypeSand); AdvancedRocketryBlocks.blockCharcoalLog = new BlockCharcoalLog().setBlockName("charcoallog").setCreativeTab(CreativeTabs.tabBlock); AdvancedRocketryBlocks.blockElectricMushroom = new BlockElectricMushroom().setBlockName("electricMushroom").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:mushroom_electric").setHardness(0.0F).setStepSound(Block.soundTypeGrass); AdvancedRocketryBlocks.blockCrystal = new BlockCrystal().setBlockName("crystal").setCreativeTab(LibVulpes.tabLibVulpesOres).setBlockTextureName("advancedrocketry:crystal").setHardness(2f); AdvancedRocketryBlocks.blockOrientationController = new BlockTile(TileStationOrientationControl.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber").setCreativeTab(tabAdvRocketry).setBlockName("orientationControl").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setSideTexture("advancedrocketry:machineOrientationControl"); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setFrontTexture("advancedrocketry:machineOrientationControl"); AdvancedRocketryBlocks.blockGravityController = new BlockTile(TileStationGravityController.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber").setCreativeTab(tabAdvRocketry).setBlockName("gravityControl").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setSideTexture("advancedrocketry:machineOrientationControl"); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setFrontTexture("advancedrocketry:machineOrientationControl"); AdvancedRocketryBlocks.blockOxygenCharger = new BlockTile(TileOxygenCharger.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("oxygenCharger").setCreativeTab(tabAdvRocketry).setBlockTextureName("libvulpes:machineGeneric").setHardness(3f); AdvancedRocketryBlocks.blockOxygenCharger.setBlockBounds(0, 0, 0, 1, 0.5f, 1); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setSideTexture("advancedrocketry:panelSide"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setTopTexture("advancedrocketry:gasChargerTop"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setFrontTexture("advancedrocketry:panelSide"); AdvancedRocketryBlocks.blockOxygenVent = new BlockTile(TileOxygenVent.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("oxygenVent").setCreativeTab(tabAdvRocketry).setBlockTextureName("libvulpes:machineGeneric").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setSideTexture("advancedrocketry:machineVent"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setTopTexture("advancedrocketry:machineVent"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setFrontTexture("advancedrocketry:machineVent"); AdvancedRocketryBlocks.blockRocketBuilder = new BlockTile(TileRocketBuilder.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("rocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockDeployableRocketBuilder = new BlockTile(TileStationDeployedAssembler.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("deployableRocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockStationBuilder = new BlockTile(TileStationBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("stationAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockFuelingStation = new BlockTileRedstoneEmitter(TileEntityFuelingStation.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("fuelStation").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setSideTexture("Advancedrocketry:FuelingMachine"); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setFrontTexture("Advancedrocketry:FuelingMachine"); AdvancedRocketryBlocks.blockMonitoringStation = new BlockTileNeighborUpdate(TileEntityMoniteringStation.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setFrontTexture("Advancedrocketry:MonitorRocket"); AdvancedRocketryBlocks.blockMonitoringStation.setBlockName("monitoringstation"); AdvancedRocketryBlocks.blockWarpShipMonitor = new BlockWarpShipMonitor(TileWarpShipMonitor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setFrontTexture("Advancedrocketry:starshipcontrolPanel"); AdvancedRocketryBlocks.blockWarpShipMonitor.setBlockName("stationmonitor"); AdvancedRocketryBlocks.blockSatelliteBuilder = new BlockMultiblockMachine(TileSatelliteBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setFrontTexture("Advancedrocketry:satelliteAssembler"); AdvancedRocketryBlocks.blockSatelliteBuilder.setBlockName("satelliteBuilder"); AdvancedRocketryBlocks.blockSatelliteControlCenter = new BlockTile(TileEntitySatelliteControlCenter.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setFrontTexture("Advancedrocketry:MonitorSatellite"); AdvancedRocketryBlocks.blockSatelliteControlCenter.setBlockName("satelliteMonitor"); AdvancedRocketryBlocks.blockMicrowaveReciever = new BlockMultiblockMachine(TileMicrowaveReciever.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setTopTexture("Advancedrocketry:solar"); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setFrontTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockMicrowaveReciever.setBlockName("microwaveReciever"); //Arcfurnace AdvancedRocketryBlocks.blockArcFurnace = new BlockMultiblockMachine(TileElectricArcFurnace.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("electricArcFurnace").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockArcFurnace).setSideTexture("Advancedrocketry:BlastBrick"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockArcFurnace).setFrontTexture("Advancedrocketry:BlastBrickFront", "Advancedrocketry:BlastBrickFrontActive"); AdvancedRocketryBlocks.blockMoonTurf = new BlockPlanetSoil().setMapColor(MapColor.snowColor).setHardness(0.5F).setStepSound(Block.soundTypeGravel).setBlockName("turf").setBlockTextureName("advancedrocketry:moon_turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockHotTurf = new BlockPlanetSoil().setMapColor(MapColor.netherrackColor).setHardness(0.5F).setStepSound(Block.soundTypeGravel).setBlockName("hotDryturf").setBlockTextureName("advancedrocketry:hotdry_turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockLoader = new BlockARHatch(Material.rock).setBlockName("loader").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienWood = new BlockAlienWood().setBlockName("log").setBlockTextureName("advancedrocketry:log").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienLeaves = new BlockAlienLeaves().setBlockName("leaves2").setBlockTextureName("leaves").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienSapling = new BlockAlienSapling().setBlockName("sapling").setBlockTextureName("advancedrocketry:sapling").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLightSource = new BlockLightSource(); AdvancedRocketryBlocks.blockBlastBrick = new BlockMultiBlockComponentVisible(Material.rock).setCreativeTab(tabAdvRocketry).setBlockName("blastBrick").setBlockTextureName("advancedRocketry:BlastBrick").setHardness(3F).setResistance(15F); AdvancedRocketryBlocks.blockQuartzCrucible = new BlockQuartzCrucible(); AdvancedRocketryBlocks.blockPrecisionAssembler = new BlockMultiblockMachine(TilePrecisionAssembler.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("precisionAssemblingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPrecisionAssembler).setFrontTexture("advancedrocketry:PrecisionAssemblerFront", "advancedrocketry:PrecisionAssemblerFront_Active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPrecisionAssembler).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockCuttingMachine = new BlockMultiblockMachine(TileCuttingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("cuttingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCuttingMachine).setFrontTexture("advancedrocketry:CuttingMachine", "advancedrocketry:CuttingMachine_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCuttingMachine).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockCrystallizer = new BlockMultiblockMachine(TileCrystallizer.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("Crystallizer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCrystallizer).setSideTexture("Advancedrocketry:Crystallizer", "Advancedrocketry:Crystallizer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCrystallizer).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockWarpCore = new BlockWarpCore(TileWarpCore.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("warpCore").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockWarpCore).setSideTexture("Advancedrocketry:warpcore"); AdvancedRocketryBlocks.blockChemicalReactor = new BlockMultiblockMachine(TileChemicalReactor.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("chemreactor").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setFrontTexture("Advancedrocketry:Crystallizer", "Advancedrocketry:Crystallizer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockLathe = new BlockMultiblockMachine(TileLathe.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("lathe").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setFrontTexture("Advancedrocketry:controlPanel"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockRollingMachine = new BlockMultiblockMachine(TileRollingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("rollingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setFrontTexture("Advancedrocketry:controlPanel"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockElectrolyser = new BlockMultiblockMachine(TileElectrolyser.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("electrolyser").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setFrontTexture("Advancedrocketry:machineElectrolzyer", "Advancedrocketry:machineElectrolzyer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockAtmosphereTerraformer = new BlockMultiblockMachine(TileAtmosphereTerraformer.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("atmosphereTerraformer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setFrontTexture("Advancedrocketry:machineElectrolzyer", "Advancedrocketry:machineElectrolzyer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockPlanetAnalyser = new BlockMultiblockMachine(TilePlanetAnalyser.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("planetanalyser").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setFrontTexture("advancedrocketry:MonitorPlanet","advancedrocketry:MonitorPlanet_active"); AdvancedRocketryBlocks.blockObservatory = (BlockMultiblockMachine) new BlockMultiblockMachine(TileObservatory.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("observatory").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setFrontTexture("advancedrocketry:MonitorFrontMid","advancedrocketry:MonitorFrontMid"); AdvancedRocketryBlocks.blockGuidanceComputer = new BlockTile(TileGuidanceComputer.class,GuiHandler.guiId.MODULAR.ordinal()).setBlockName("guidanceComputer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockPlanetSelector = new BlockTile(TilePlanetSelector.class,GuiHandler.guiId.MODULARFULLSCREEN.ordinal()).setBlockName("planetSelector").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockBiomeScanner = new BlockMultiblockMachine(TileBiomeScanner.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("biomeScanner").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockDrill = new BlockMiningDrill().setBlockName("drill").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setTopTexture("Advancedrocketry:laserBottom", "Advancedrocketry:laserBottom"); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setSideTexture("Advancedrocketry:machineWarning"); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setFrontTexture("Advancedrocketry:machineWarning"); AdvancedRocketryBlocks.blockSuitWorkStation = new BlockTile(TileSuitWorkStation.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("suitWorkStation").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setTopTexture("Advancedrocketry:suitWorkStation"); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setSideTexture("Advancedrocketry:panelSideWorkStation"); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setFrontTexture("Advancedrocketry:panelSideWorkStation"); AdvancedRocketryBlocks.blockIntake = new BlockIntake(Material.iron).setBlockTextureName("advancedrocketry:intake").setBlockName("gasIntake").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPressureTank = new BlockPressurizedFluidTank(Material.iron).setBlockName("pressurizedTank").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarPanel = new BlockSolarPanel(Material.iron).setBlockName("solarPanel").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCircularLight = new BlockGeneric(Material.iron).setBlockName("circleLight").setCreativeTab(tabAdvRocketry).setHardness(2f).setBlockTextureName("advancedrocketry:stationLight").setLightLevel(1f); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { AdvancedRocketryBlocks.blockSpaceLaser = new BlockLaser(); AdvancedRocketryBlocks.blockSpaceLaser.setCreativeTab(tabAdvRocketry); } //Fluid Registration AdvancedRocketryFluids.fluidOxygen = new FluidColored("oxygen",0x8f94b9).setUnlocalizedName("oxygen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidOxygen)) { AdvancedRocketryFluids.fluidOxygen = FluidRegistry.getFluid("oxygen"); } AdvancedRocketryFluids.fluidHydrogen = new FluidColored("hydrogen",0xdbc1c1).setUnlocalizedName("hydrogen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidHydrogen)) { AdvancedRocketryFluids.fluidHydrogen = FluidRegistry.getFluid("hydrogen"); } AdvancedRocketryFluids.fluidRocketFuel = new FluidColored("rocketFuel", 0xe5d884).setUnlocalizedName("rocketFuel").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidRocketFuel)) { AdvancedRocketryFluids.fluidRocketFuel = FluidRegistry.getFluid("rocketFuel"); } AdvancedRocketryFluids.fluidNitrogen = new FluidColored("nitrogen", 0x97a7e7); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidNitrogen)) { AdvancedRocketryFluids.fluidNitrogen = FluidRegistry.getFluid("nitrogen"); } AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidNitrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidHydrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidOxygen); AdvancedRocketryBlocks.blockOxygenFluid = new BlockFluid(AdvancedRocketryFluids.fluidOxygen, Material.water).setBlockName("oxygenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockHydrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidHydrogen, Material.water).setBlockName("hydrogenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockFuelFluid = new BlockFluid(AdvancedRocketryFluids.fluidRocketFuel, Material.water).setBlockName("rocketFuelBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockNitrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidNitrogen, Material.water).setBlockName("nitrogenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); //Cables //AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.iron).setBlockName("liquidPipe").setCreativeTab(CreativeTabs.tabTransport); AdvancedRocketryBlocks.blockDataPipe = new BlockDataCable(Material.iron).setBlockName("dataPipe").setCreativeTab(tabAdvRocketry).setBlockTextureName("AdvancedRocketry:pipeData"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDataPipe , AdvancedRocketryBlocks.blockDataPipe .getUnlocalizedName()); //GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFluidPipe , AdvancedRocketryBlocks.blockFluidPipe .getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLaunchpad, "launchpad"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockRocketBuilder, "rocketBuilder"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockStructureTower, "structureTower"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGenericSeat, "seat"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockEngine, "rocketmotor"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelTank, "fuelTank"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelingStation, "fuelingStation"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMonitoringStation, "blockMonitoringStation"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSatelliteBuilder, "blockSatelliteBuilder"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMoonTurf, "moonTurf"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockHotTurf, "blockHotTurf"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLoader, ItemBlockMeta.class, AdvancedRocketryBlocks.blockLoader.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPrecisionAssembler, "precisionassemblingmachine"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockBlastBrick, "utilBlock"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockQuartzCrucible, "quartzcrucible"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCrystallizer, "crystallizer"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCuttingMachine, "cuttingMachine"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienWood, "alienWood"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienLeaves, "alienLeaves"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienSapling, "alienSapling"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockObservatory, "observatory"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockConcrete, AdvancedRocketryBlocks.blockConcrete.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlanetSelector, AdvancedRocketryBlocks.blockPlanetSelector.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSatelliteControlCenter, AdvancedRocketryBlocks.blockSatelliteControlCenter.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlanetAnalyser, AdvancedRocketryBlocks.blockPlanetAnalyser.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGuidanceComputer, AdvancedRocketryBlocks.blockGuidanceComputer.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockArcFurnace, AdvancedRocketryBlocks.blockArcFurnace.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSawBlade, AdvancedRocketryBlocks.blockSawBlade.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMotor, AdvancedRocketryBlocks.blockMotor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLathe, AdvancedRocketryBlocks.blockLathe.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockRollingMachine, AdvancedRocketryBlocks.blockRollingMachine.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlatePress, AdvancedRocketryBlocks.blockPlatePress .getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockStationBuilder, AdvancedRocketryBlocks.blockStationBuilder.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockElectrolyser, AdvancedRocketryBlocks.blockElectrolyser.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockChemicalReactor, AdvancedRocketryBlocks.blockChemicalReactor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenScrubber, AdvancedRocketryBlocks.blockOxygenScrubber.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenVent, AdvancedRocketryBlocks.blockOxygenVent.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenCharger, AdvancedRocketryBlocks.blockOxygenCharger.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAirLock, AdvancedRocketryBlocks.blockAirLock.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLandingPad, AdvancedRocketryBlocks.blockLandingPad.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockWarpCore, AdvancedRocketryBlocks.blockWarpCore.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockWarpShipMonitor, AdvancedRocketryBlocks.blockWarpShipMonitor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenDetection, AdvancedRocketryBlocks.blockOxygenDetection.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockUnlitTorch, AdvancedRocketryBlocks.blockUnlitTorch.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blocksGeode,AdvancedRocketryBlocks.blocksGeode.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenFluid,ItemFluid.class, AdvancedRocketryBlocks.blockOxygenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockHydrogenFluid,ItemFluid.class, AdvancedRocketryBlocks.blockHydrogenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelFluid, ItemFluid.class, AdvancedRocketryBlocks.blockFuelFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockNitrogenFluid, ItemFluid.class, AdvancedRocketryBlocks.blockNitrogenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockVitrifiedSand, AdvancedRocketryBlocks.blockVitrifiedSand.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCharcoalLog, AdvancedRocketryBlocks.blockCharcoalLog.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockElectricMushroom, AdvancedRocketryBlocks.blockElectricMushroom.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCrystal, ItemCrystalBlock.class, AdvancedRocketryBlocks.blockCrystal.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOrientationController, AdvancedRocketryBlocks.blockOrientationController.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGravityController, AdvancedRocketryBlocks.blockGravityController.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDrill, AdvancedRocketryBlocks.blockDrill.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMicrowaveReciever, AdvancedRocketryBlocks.blockMicrowaveReciever.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLightSource, AdvancedRocketryBlocks.blockLightSource.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSolarPanel, AdvancedRocketryBlocks.blockSolarPanel.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSuitWorkStation, AdvancedRocketryBlocks.blockSuitWorkStation.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockBiomeScanner, AdvancedRocketryBlocks.blockBiomeScanner.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAtmosphereTerraformer, AdvancedRocketryBlocks.blockAtmosphereTerraformer.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDeployableRocketBuilder, AdvancedRocketryBlocks.blockDeployableRocketBuilder.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPressureTank, AdvancedRocketryBlocks.blockPressureTank.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockIntake, AdvancedRocketryBlocks.blockIntake.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCircularLight, AdvancedRocketryBlocks.blockCircularLight.getUnlocalizedName()); //TODO, use different mechanism to enable/disable drill if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSpaceLaser, "laserController"); AdvancedRocketryItems.itemWafer = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:wafer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCircuitPlate = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:circuitplate").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemIC = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:circuitIC").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemMisc = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:miscpart").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSawBlade = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:sawBlade").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStationChip = new ItemStationChip().setUnlocalizedName("stationChip").setTextureName("advancedRocketry:stationIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemAsteroidChip = new ItemAsteroidChip().setUnlocalizedName("asteroidChip").setTextureName("advancedRocketry:stationIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStation = new ItemPackedStructure().setUnlocalizedName("station").setTextureName("advancedRocketry:SpaceStation"); AdvancedRocketryItems.itemSmallAirlockDoor = new ItemDoor2(Material.rock).setUnlocalizedName("smallAirlock").setTextureName("advancedRocketry:smallAirlock").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCarbonScrubberCartridge = new Item().setMaxDamage(172800).setUnlocalizedName("carbonScrubberCartridge").setTextureName("advancedRocketry:carbonCartridge").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemLens = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:lens").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePowerSource = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:satellitePowerSource").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePrimaryFunction = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:satellitePrimaryFunction").setCreativeTab(tabAdvRocketry); //TODO: move registration in the case we have more than one chip type AdvancedRocketryItems.itemDataUnit = new ItemData().setUnlocalizedName("advancedrocketry:dataUnit").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemOreScanner = new ItemOreScanner().setUnlocalizedName("OreScanner").setTextureName("advancedRocketry:oreScanner").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemQuartzCrucible = (new ItemBlockWithIcon(AdvancedRocketryBlocks.blockQuartzCrucible)).setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry).setTextureName("advancedRocketry:qcrucible"); AdvancedRocketryItems.itemSatellite = new ItemSatellite().setUnlocalizedName("satellite").setTextureName("advancedRocketry:satellite"); AdvancedRocketryItems.itemSatelliteIdChip = new ItemSatelliteIdentificationChip().setUnlocalizedName("satelliteIdChip").setTextureName("advancedRocketry:satelliteIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemPlanetIdChip = new ItemPlanetIdentificationChip().setUnlocalizedName("planetIdChip").setTextureName("advancedRocketry:planetIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBiomeChanger = new ItemBiomeChanger().setUnlocalizedName("biomeChanger").setTextureName("advancedrocketry:biomeChanger").setCreativeTab(tabAdvRocketry); //Fluids AdvancedRocketryItems.itemBucketRocketFuel = new ItemBucket(AdvancedRocketryBlocks.blockFuelFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketRocketFuel").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketNitrogen = new ItemBucket(AdvancedRocketryBlocks.blockNitrogenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketNitrogen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketHydrogen = new ItemBucket(AdvancedRocketryBlocks.blockHydrogenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketHydrogen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketOxygen = new ItemBucket(AdvancedRocketryBlocks.blockOxygenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketOxygen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); //Suit Component Registration AdvancedRocketryItems.itemJetpack = new ItemJetpack().setCreativeTab(tabAdvRocketry).setUnlocalizedName("jetPack").setTextureName("advancedRocketry:jetpack"); AdvancedRocketryItems.itemPressureTank = new ItemPressureTank(4, 1000).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:pressureTank").setTextureName("advancedRocketry:pressureTank"); AdvancedRocketryItems.itemUpgrade = new ItemUpgrade(5).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:itemUpgrade").setTextureName("advancedRocketry:itemUpgrade"); AdvancedRocketryItems.itemAtmAnalyser = new ItemAtmosphereAnalzer().setCreativeTab(tabAdvRocketry).setUnlocalizedName("atmAnalyser").setTextureName("advancedRocketry:atmosphereAnalyzer"); //Armor registration AdvancedRocketryItems.itemSpaceSuit_Helmet = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 0).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceHelmet").setTextureName("advancedRocketry:space_helmet"); AdvancedRocketryItems.itemSpaceSuit_Chest = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceChest").setTextureName("advancedRocketry:space_chestplate"); AdvancedRocketryItems.itemSpaceSuit_Leggings = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 2).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceLeggings").setTextureName("advancedRocketry:space_leggings"); AdvancedRocketryItems.itemSpaceSuit_Boots = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 3).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceBoots").setTextureName("advancedRocketry:space_boots"); AdvancedRocketryItems.itemSealDetector = new ItemSealDetector().setMaxStackSize(1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sealDetector").setTextureName("advancedRocketry:seal_detector"); //Tools AdvancedRocketryItems.itemJackhammer = new ItemJackHammer(ToolMaterial.EMERALD).setTextureName("advancedRocketry:jackHammer").setUnlocalizedName("jackhammer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("jackhammer", 3); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("pickaxe", 3); //Register Satellite Properties SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOptical.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteComposition.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteMassScanner.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteEnergy.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOreMapping.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteBiomeChanger.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), new SatelliteProperties().setPowerGeneration(1)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1), new SatelliteProperties().setPowerGeneration(10)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 0), new SatelliteProperties().setPowerStorage(100)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 1), new SatelliteProperties().setPowerStorage(400)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), new SatelliteProperties().setMaxData(1000)); //Item Registration GameRegistry.registerItem(AdvancedRocketryItems.itemQuartzCrucible, "iquartzcrucible"); GameRegistry.registerItem(AdvancedRocketryItems.itemOreScanner, "oreScanner"); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellitePowerSource, AdvancedRocketryItems.itemSatellitePowerSource.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellitePrimaryFunction, AdvancedRocketryItems.itemSatellitePrimaryFunction.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemCircuitPlate, AdvancedRocketryItems.itemCircuitPlate.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemIC, AdvancedRocketryItems.itemIC.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemWafer, AdvancedRocketryItems.itemWafer.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemDataUnit, AdvancedRocketryItems.itemDataUnit.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellite, AdvancedRocketryItems.itemSatellite.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatelliteIdChip, AdvancedRocketryItems.itemSatelliteIdChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemPlanetIdChip,AdvancedRocketryItems.itemPlanetIdChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemMisc, AdvancedRocketryItems.itemMisc.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSawBlade, AdvancedRocketryItems.itemSawBlade.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceStationChip, AdvancedRocketryItems.itemSpaceStationChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceStation, AdvancedRocketryItems.itemSpaceStation.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Helmet, AdvancedRocketryItems.itemSpaceSuit_Helmet.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Boots, AdvancedRocketryItems.itemSpaceSuit_Boots.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Chest, AdvancedRocketryItems.itemSpaceSuit_Chest.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Leggings, AdvancedRocketryItems.itemSpaceSuit_Leggings.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketRocketFuel, AdvancedRocketryItems.itemBucketRocketFuel.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketNitrogen, AdvancedRocketryItems.itemBucketNitrogen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketHydrogen, AdvancedRocketryItems.itemBucketHydrogen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketOxygen, AdvancedRocketryItems.itemBucketOxygen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSmallAirlockDoor, AdvancedRocketryItems.itemSmallAirlockDoor.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemCarbonScrubberCartridge, AdvancedRocketryItems.itemCarbonScrubberCartridge.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSealDetector, AdvancedRocketryItems.itemSealDetector.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemJackhammer, AdvancedRocketryItems.itemJackhammer.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemAsteroidChip, AdvancedRocketryItems.itemAsteroidChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemLens, AdvancedRocketryItems.itemLens.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemJetpack, AdvancedRocketryItems.itemJetpack.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemPressureTank, AdvancedRocketryItems.itemPressureTank.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemUpgrade, AdvancedRocketryItems.itemUpgrade.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemAtmAnalyser, AdvancedRocketryItems.itemAtmAnalyser.getUnlocalizedName()); if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming) GameRegistry.registerItem(AdvancedRocketryItems.itemBiomeChanger, AdvancedRocketryItems.itemBiomeChanger.getUnlocalizedName()); //Register multiblock items with the projector ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCuttingMachine(), (BlockTile)AdvancedRocketryBlocks.blockCuttingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileLathe(), (BlockTile)AdvancedRocketryBlocks.blockLathe); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCrystallizer(), (BlockTile)AdvancedRocketryBlocks.blockCrystallizer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePrecisionAssembler(), (BlockTile)AdvancedRocketryBlocks.blockPrecisionAssembler); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileObservatory(), (BlockTile)AdvancedRocketryBlocks.blockObservatory); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePlanetAnalyser(), (BlockTile)AdvancedRocketryBlocks.blockPlanetAnalyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRollingMachine(), (BlockTile)AdvancedRocketryBlocks.blockRollingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectricArcFurnace(), (BlockTile)AdvancedRocketryBlocks.blockArcFurnace); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectrolyser(), (BlockTile)AdvancedRocketryBlocks.blockElectrolyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileChemicalReactor(), (BlockTile)AdvancedRocketryBlocks.blockChemicalReactor); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileWarpCore(), (BlockTile)AdvancedRocketryBlocks.blockWarpCore); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileMicrowaveReciever(), (BlockTile)AdvancedRocketryBlocks.blockMicrowaveReciever); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBiomeScanner(), (BlockTile)AdvancedRocketryBlocks.blockBiomeScanner); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAtmosphereTerraformer(), (BlockTile)AdvancedRocketryBlocks.blockAtmosphereTerraformer); //End Items EntityRegistry.registerModEntity(EntityDummy.class, "mountDummy", 0, this, 16, 20, false); EntityRegistry.registerModEntity(EntityRocket.class, "rocket", 1, this, 64, 3, true); EntityRegistry.registerModEntity(EntityLaserNode.class, "laserNode", 2, instance, 256, 20, false); EntityRegistry.registerModEntity(EntityStationDeployedRocket.class, "deployedRocket", 3, this, 256, 600, true); GameRegistry.registerTileEntity(TileRocketBuilder.class, "ARrocketBuilder"); GameRegistry.registerTileEntity(TileWarpCore.class, "ARwarpCore"); GameRegistry.registerTileEntity(TileModelRender.class, "ARmodelRenderer"); GameRegistry.registerTileEntity(TileEntityFuelingStation.class, "ARfuelingStation"); GameRegistry.registerTileEntity(TileEntityMoniteringStation.class, "ARmonitoringStation"); GameRegistry.registerTileEntity(TileMissionController.class, "ARmissionControlComp"); GameRegistry.registerTileEntity(TileSpaceLaser.class, "ARspaceLaser"); GameRegistry.registerTileEntity(TilePrecisionAssembler.class, "ARprecisionAssembler"); GameRegistry.registerTileEntity(TileObservatory.class, "ARobservatory"); GameRegistry.registerTileEntity(TileCrystallizer.class, "ARcrystallizer"); GameRegistry.registerTileEntity(TileCuttingMachine.class, "ARcuttingmachine"); GameRegistry.registerTileEntity(TileDataBus.class, "ARdataBus"); GameRegistry.registerTileEntity(TileSatelliteHatch.class, "ARsatelliteHatch"); GameRegistry.registerTileEntity(TileSatelliteBuilder.class, "ARsatelliteBuilder"); GameRegistry.registerTileEntity(TileEntitySatelliteControlCenter.class, "ARTileEntitySatelliteControlCenter"); GameRegistry.registerTileEntity(TilePlanetAnalyser.class, "ARplanetAnalyser"); GameRegistry.registerTileEntity(TileGuidanceComputer.class, "ARguidanceComputer"); GameRegistry.registerTileEntity(TileElectricArcFurnace.class, "ARelectricArcFurnace"); GameRegistry.registerTileEntity(TilePlanetSelector.class, "ARTilePlanetSelector"); GameRegistry.registerTileEntity(TileModelRenderRotatable.class, "ARTileModelRenderRotatable"); GameRegistry.registerTileEntity(TileMaterial.class, "ARTileMaterial"); GameRegistry.registerTileEntity(TileLathe.class, "ARTileLathe"); GameRegistry.registerTileEntity(TileRollingMachine.class, "ARTileMetalBender"); GameRegistry.registerTileEntity(TileStationBuilder.class, "ARStationBuilder"); GameRegistry.registerTileEntity(TileElectrolyser.class, "ARElectrolyser"); GameRegistry.registerTileEntity(TileChemicalReactor.class, "ARChemicalReactor"); GameRegistry.registerTileEntity(TileOxygenVent.class, "AROxygenVent"); GameRegistry.registerTileEntity(TileOxygenCharger.class, "AROxygenCharger"); GameRegistry.registerTileEntity(TileCO2Scrubber.class, "ARCO2Scrubber"); GameRegistry.registerTileEntity(TileWarpShipMonitor.class, "ARStationMonitor"); GameRegistry.registerTileEntity(TileAtmosphereDetector.class, "AROxygenDetector"); GameRegistry.registerTileEntity(TileStationOrientationControl.class, "AROrientationControl"); GameRegistry.registerTileEntity(TileStationGravityController.class, "ARGravityControl"); GameRegistry.registerTileEntity(TileLiquidPipe.class, "ARLiquidPipe"); GameRegistry.registerTileEntity(TileDataPipe.class, "ARDataPipe"); GameRegistry.registerTileEntity(TileDrill.class, "ARDrill"); GameRegistry.registerTileEntity(TileMicrowaveReciever.class, "ARMicrowaveReciever"); GameRegistry.registerTileEntity(TileSuitWorkStation.class, "ARSuitWorkStation"); GameRegistry.registerTileEntity(TileRocketLoader.class, "ARRocketLoader"); GameRegistry.registerTileEntity(TileRocketUnloader.class, "ARRocketUnloader"); GameRegistry.registerTileEntity(TileBiomeScanner.class, "ARBiomeScanner"); GameRegistry.registerTileEntity(TileAtmosphereTerraformer.class, "ARAttTerraformer"); GameRegistry.registerTileEntity(TileLandingPad.class, "ARLandingPad"); GameRegistry.registerTileEntity(TileStationDeployedAssembler.class, "ARStationDeployableRocketAssembler"); GameRegistry.registerTileEntity(TileFluidTank.class, "ARFluidTank"); GameRegistry.registerTileEntity(TileRocketFluidUnloader.class, "ARFluidUnloader"); GameRegistry.registerTileEntity(TileRocketFluidLoader.class, "ARFluidLoader"); //OreDict stuff OreDictionary.registerOre("waferSilicon", new ItemStack(AdvancedRocketryItems.itemWafer,1,0)); OreDictionary.registerOre("ingotCarbon", new ItemStack(AdvancedRocketryItems.itemMisc, 1, 1)); OreDictionary.registerOre("concrete", new ItemStack(AdvancedRocketryBlocks.blockConcrete)); //Register Space Objects SpaceObjectManager.getSpaceManager().registerSpaceObjectType("genericObject", SpaceObject.class); //Register Allowed Products materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumAluminide", "pickaxe", 1, 0xaec2de, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerOres(LibVulpes.tabLibVulpesOres, "advancedRocketry"); } @EventHandler public void load(FMLInitializationEvent event) { zmaster587.advancedRocketry.cable.NetworkRegistry.registerFluidNetwork(); ItemStack userInterface = new ItemStack(AdvancedRocketryItems.itemMisc, 1,0); ItemStack basicCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,0); ItemStack advancedCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,2); ItemStack controlCircuitBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,3); ItemStack itemIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,4); ItemStack liquidIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,5); ItemStack trackingCircuit = new ItemStack(AdvancedRocketryItems.itemIC,1,1); ItemStack opticalSensor = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0); ItemStack biomeChanger = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5); ItemStack smallSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0); ItemStack largeSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1); ItemStack smallBattery = new ItemStack(LibVulpesItems.itemBattery,1,0); ItemStack battery2x = new ItemStack(LibVulpesItems.itemBattery,1,1); ItemStack superHighPressureTime = new ItemStack(AdvancedRocketryItems.itemPressureTank,1,3); //Register Alloys MaterialRegistry.registerMixedMaterial(new MixedMaterial(TileElectricArcFurnace.class, "oreRutile", new ItemStack[] {MaterialRegistry.getMaterialFromName("Titanium").getProduct(AllowedProducts.getProductByName("INGOT"))})); proxy.registerRenderers(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockBlastBrick,16), new ItemStack(Items.potionitem,1,8195), new ItemStack(Items.potionitem,1,8201), Blocks.brick_block, Blocks.brick_block, Blocks.brick_block, Blocks.brick_block); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockArcFurnace), "aga","ice", "aba", 'a', Items.netherbrick, 'g', userInterface, 'i', itemIOBoard, 'e',controlCircuitBoard, 'c', AdvancedRocketryBlocks.blockBlastBrick, 'b', "ingotCopper")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemQuartzCrucible), " a ", "aba", " a ", Character.valueOf('a'), Items.quartz, Character.valueOf('b'), Items.cauldron); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockPlatePress, " ", " a ", "iii", 'a', Blocks.piston, 'i', Items.iron_ingot)); GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotIron")); GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Steel", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotSteel")); GameRegistry.addSmelting(MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("ORE")), MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("DUST")), 0); //Supporting Materials GameRegistry.addRecipe(new ShapedOreRecipe(userInterface, "lrl", "fgf", 'l', "dyeLime", 'r', Items.redstone, 'g', Blocks.glass_pane, 'f', Items.glowstone_dust)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockGenericSeat), "xxx", 'x', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockConcrete), Blocks.sand, Blocks.gravel, Items.water_bucket); GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockLaunchpad, "concrete", "dyeBlack", "dyeYellow")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockStructureTower, "ooo", " o ", "ooo", 'o', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockEngine, "sss", " t ","t t", 's', "ingotSteel", 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockFuelTank, "s s", "p p", "s s", 'p', "plateSteel", 's', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(smallBattery, " c ","prp", "prp", 'c', "stickIron", 'r', Items.redstone, 'p', "plateTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemBattery,1,1), "bpb", "bpb", 'b', smallBattery, 'p', "plateCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), "ppp", " g ", " l ", 'p', Blocks.glass_pane, 'g', Items.glowstone_dust, 'l', "plateGold")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockObservatory), "gug", "pbp", "rrr", 'g', Blocks.glass_pane, 'u', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'r', MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK"))); //Hatches GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,0), "c", "m"," ", 'c', Blocks.chest, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,1), "m", "c"," ", 'c', Blocks.chest, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,2), "c", "m", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,3), "m", "c", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,0), "m", "c"," ", 'c', AdvancedRocketryItems.itemDataUnit, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,1), " x ", "xmx"," x ", 'x', "stickTitanium", 'm', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,2), new ItemStack(LibVulpesBlocks.blockHatch,1,1), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,3), new ItemStack(LibVulpesBlocks.blockHatch,1,0), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,4), new ItemStack(LibVulpesBlocks.blockHatch,1,3), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,5), new ItemStack(LibVulpesBlocks.blockHatch,1,2), trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMotor), " cp", "rrp"," cp", 'c', "coilCopper", 'p', "plateSteel", 'r', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), "rrr", "ggg","ppp", 'r', Items.redstone, 'g', Items.glowstone_dust, 'p', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemHoloProjector), "oro", "rpr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'r', Items.redstone, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', "crystalDilithium")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemLens, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0), " x ","xox", " x ", 'x', "plateIron", 'o', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSawBlade,1,0), "r r","xox", "x x", 'r', "stickIron", 'x', "plateIron", 'o', new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0))); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSpaceStationChip), LibVulpesItems.itemLinker , basicCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge), "xix", "xix", "xix", 'x', "sheetIron", 'i', Blocks.iron_bars)); //Plugs GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockRFBattery), " x ", "xmx"," x ", 'x', LibVulpesItems.itemBattery, 'm', LibVulpesBlocks.blockStructureBlock); //O2 Support GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenVent), "bfb", "bmb", "btb", 'b', Blocks.iron_bars, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenScrubber), "bfb", "bmb", "btb", 'b', Blocks.iron_bars, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', "ingotCarbon")); //MACHINES GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPrecisionAssembler), "abc", "def", "ghi", 'a', Items.repeater, 'b', userInterface, 'c', Items.diamond, 'd', itemIOBoard, 'e', LibVulpesBlocks.blockStructureBlock, 'f', controlCircuitBoard, 'g', Blocks.furnace, 'h', "gearSteel", 'i', Blocks.dropper)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCrystallizer), "ada", "ecf","bgb", 'a', Items.quartz, 'b', Items.repeater, 'c', LibVulpesBlocks.blockStructureBlock, 'd', userInterface, 'e', itemIOBoard, 'f', controlCircuitBoard, 'g', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCuttingMachine), "aba", "cde", "opo", 'a', "gearSteel", 'b', userInterface, 'c', itemIOBoard, 'e', controlCircuitBoard, 'p', "plateSteel", 'o', Blocks.obsidian, 'd', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLathe), "rsr", "abc", "pgp", 'r', "stickIron",'a', itemIOBoard, 'c', controlCircuitBoard, 'g', "gearSteel", 'p', "plateSteel", 'b', LibVulpesBlocks.blockStructureBlock, 's', userInterface)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRollingMachine), "psp", "abc", "iti", 'a', itemIOBoard, 'c', controlCircuitBoard, 'p', "gearSteel", 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'i', "blockIron",'t', liquidIOBoard)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMonitoringStation), "coc", "cbc", "cpc", 'c', "stickCopper", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'b', LibVulpesBlocks.blockStructureBlock, 'p', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFuelingStation), "bgb", "lbf", "ppp", 'p', "plateTin", 'f', "fanSteel", 'l', liquidIOBoard, 'g', AdvancedRocketryItems.itemMisc, 'x', AdvancedRocketryBlocks.blockFuelTank, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteControlCenter), "oso", "cbc", "rtr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 's', userInterface, 'c', "stickCopper", 'b', LibVulpesBlocks.blockStructureBlock, 'r', Items.repeater, 't', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteBuilder), "dht", "cbc", "mas", 'd', AdvancedRocketryItems.itemDataUnit, 'h', Blocks.hopper, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'm', AdvancedRocketryBlocks.blockMotor, 'a', Blocks.anvil, 's', AdvancedRocketryBlocks.blockSawBlade, 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetAnalyser), "tst", "pbp", "cpc", 't', trackingCircuit, 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateTin", 'c', AdvancedRocketryItems.itemPlanetIdChip)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockGuidanceComputer), "ctc", "rbr", "crc", 'c', trackingCircuit, 't', "plateTitanium", 'r', Items.redstone, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetSelector), "cpc", "lbl", "coc", 'c', trackingCircuit, 'o',new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'l', Blocks.lever, 'b', AdvancedRocketryBlocks.blockGuidanceComputer, 'p', Blocks.stone_button)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder), "sgs", "cbc", "tdt", 's', "stickTitanium", 'g', AdvancedRocketryItems.itemMisc, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 't', "gearTitanium", 'd', AdvancedRocketryBlocks.blockConcrete)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockStationBuilder), "gdg", "dsd", "ada", 'g', "gearTitanium", 'a', advancedCircuit, 'd', "dustDilithium", 's', new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockElectrolyser), "pip", "abc", "ded", 'd', basicCircuit, 'p', "plateSteel", 'i', userInterface, 'a', liquidIOBoard, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'e', Blocks.redstone_torch)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenCharger), "fif", "tbt", "pcp", 'p', "plateSteel", 'f', "fanSteel", 'c', Blocks.heavy_weighted_pressure_plate, 'i', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockChemicalReactor), "pip", "abd", "rcr", 'a', itemIOBoard, 'd', controlCircuitBoard, 'r', basicCircuit, 'p', "plateGold", 'i', userInterface, 'c', liquidIOBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'g', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpCore), "gcg", "pbp", "gcg", 'p', "plateSteel", 'c', advancedCircuit, 'b', "coilCopper", 'g', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenDetection), "pip", "gbf", "pcp", 'p', "plateSteel",'f', "fanSteel", 'i', userInterface, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'g', Blocks.iron_bars)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpShipMonitor), "pip", "obo", "pcp", 'o', controlCircuitBoard, 'p', "plateSteel", 'i', userInterface, 'c', advancedCircuit, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockBiomeScanner), "plp", "bsb","ppp", 'p', "plateTin", 'l', biomeChanger, 'b', smallBattery, 's', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockDeployableRocketBuilder), "gdg", "dad", "rdr", 'g', "gearTitaniumAluminide", 'd', "dustDilithium", 'r', "stickTitaniumAluminide", 'a', AdvancedRocketryBlocks.blockRocketBuilder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPressureTank), "tgt","tgt","tgt", 't', superHighPressureTime, 'g', Blocks.glass_pane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockIntake), "rhr", "hbh", "rhr", 'r', "stickTitanium", 'h', Blocks.hopper, 'b', LibVulpesBlocks.blockStructureBlock)); //Armor recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Boots, " r ", "w w", "p p", 'r', "stickIron", 'w', Blocks.wool, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Leggings, "wrw", "w w", "w w", 'w', Blocks.wool, 'r', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Chest, "wrw", "wtw", "wfw", 'w', Blocks.wool, 'r', "stickIron", 't', AdvancedRocketryBlocks.blockFuelTank, 'f', "fanSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Helmet, "prp", "rgr", "www", 'w', Blocks.wool, 'r', "stickIron", 'p', "plateIron", 'g', Blocks.glass_pane)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJetpack, "cpc", "lsl", "f f", 'c', AdvancedRocketryItems.itemPressureTank, 'f', Items.fire_charge, 's', Items.string, 'l', Blocks.lever, 'p', "plateSteel")); //Tool Recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJackhammer, " pt","imp","di ",'d', Items.diamond, 'm', AdvancedRocketryBlocks.blockMotor, 'p', "plateBronze", 't', "stickTitanium", 'i', "stickIron")); //Other blocks GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSmallAirlockDoor, "pp", "pp","pp", 'p', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCircularLight), "p ", " l ", " ", 'p', "sheetIron", 'l', Blocks.glowstone)); //TEMP RECIPES GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemPlanetIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemMisc,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1) ,new ItemStack(Items.coal,1,1) ,new ItemStack(Items.coal,1,1)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLandingPad), new ItemStack(AdvancedRocketryBlocks.blockConcrete), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemAsteroidChip), trackingCircuit.copy(), AdvancedRocketryItems.itemDataUnit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockDataPipe, 8), "ggg", " d ", "ggg", 'g', Blocks.glass_pane, 'd', AdvancedRocketryItems.itemDataUnit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDrill), LibVulpesBlocks.blockStructureBlock, Items.iron_pickaxe); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockOrientationController), LibVulpesBlocks.blockStructureBlock, Items.compass, userInterface); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockGravityController), LibVulpesBlocks.blockStructureBlock, Blocks.piston, Blocks.redstone_block); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemLens), " g ", "g g", 'g', Blocks.glass_pane); GameRegistry.addShapelessRecipe(new ItemStack(LibVulpesBlocks.blockRFBattery), new ItemStack(LibVulpesBlocks.blockRFOutput)); GameRegistry.addShapelessRecipe(new ItemStack(LibVulpesBlocks.blockRFOutput), new ItemStack(LibVulpesBlocks.blockRFBattery)); GameRegistry.addShapelessRecipe(largeSolarPanel.copy(), smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMicrowaveReciever), "ggg", "tbc", "aoa", 'g', "plateGold", 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'c', controlCircuitBoard, 'a', advancedCircuit, 'o', opticalSensor)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSolarPanel, "rrr", "gbg", "ppp", 'r' , Items.redstone, 'g', Items.glowstone_dust, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemOreScanner, "lwl", "bgb", " ", 'l', Blocks.lever, 'g', userInterface, 'b', "battery", 'w', advancedCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), " c ","sss", "tot", 'c', "stickCopper", 's', "sheetIron", 'o', AdvancedRocketryItems.itemOreScanner, 't', trackingCircuit)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockSuitWorkStation), "c","b", 'c', Blocks.crafting_table, 'b', LibVulpesBlocks.blockStructureBlock); RecipesMachine.getInstance().addRecipe(TileElectrolyser.class, new Object[] {new FluidStack(AdvancedRocketryFluids.fluidOxygen, 100), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 100)}, 100, 20, new FluidStack(FluidRegistry.WATER, 10)); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new FluidStack(AdvancedRocketryFluids.fluidRocketFuel, 20), 100, 10, new FluidStack(AdvancedRocketryFluids.fluidOxygen, 10), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 10)); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSpaceLaser, "ata", "bec", "gpg", 'a', advancedCircuit, 't', trackingCircuit, 'b', LibVulpesItems.itemBattery, 'e', Items.emerald, 'c', controlCircuitBoard, 'g', "gearTitanium", 'p', LibVulpesBlocks.blockStructureBlock)); } if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockAtmosphereTerraformer), "gdg", "lac", "gbg", 'g', "gearTitaniumAluminide", 'd', "crystalDilithium", 'l', liquidIOBoard, 'a', LibVulpesBlocks.blockAdvStructureBlock, 'c', controlCircuitBoard, 'b', battery2x)); } //Control boards GameRegistry.addRecipe(new ShapedOreRecipe(itemIOBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', "dustGold", 'w', Blocks.wooden_slab, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(controlCircuitBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', "dustCopper", 'w', Blocks.wooden_slab, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(liquidIOBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', new ItemStack(Items.dye, 1, 4), 'w', Blocks.wooden_slab, 'p', "plateIron")); //Cutting Machine RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 0), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 2), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemWafer, 4, 0), 300, 100, "bouleSilicon"); //Lathe RecipesMachine.getInstance().addRecipe(TileLathe.class, MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), 300, 100, "ingotIron"); //Precision Assembler recipes RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), 900, 100, Items.gold_ingot, Items.redstone, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1), 900, 100, Items.gold_ingot, Blocks.redstone_block, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), 500, 60, Items.emerald, basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, trackingCircuit, 900, 50, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), Items.ender_eye, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, itemIOBoard, 200, 10, "plateSilicon", "plateGold", basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, controlCircuitBoard, 200, 10, "plateSilicon", "plateCopper", basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, liquidIOBoard, 200, 10, "plateSilicon", new ItemStack(Items.dye, 1, 4), basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,0), 400, 1, Items.redstone, Blocks.redstone_torch, basicCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,1), 400, 1, Items.fire_charge, Items.diamond, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,2), 400, 1, AdvancedRocketryBlocks.blockMotor, "rodTitanium", advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,3), 400, 1, Items.leather_boots, Items.feather, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemAtmAnalyser), 1000, 1, smallBattery, advancedCircuit, "plateTin", AdvancedRocketryItems.itemLens, userInterface); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemBiomeChanger), 1000, 1, smallBattery, advancedCircuit, "plateTin", trackingCircuit, userInterface); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, biomeChanger, 1000, 1, new NumberedOreDictStack("stickCopper", 2), "stickTitanium", new NumberedOreDictStack("waferSilicon", 2), advancedCircuit); //BlastFurnace RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Silicon").getProduct(AllowedProducts.getProductByName("INGOT")), 12000, 1, Blocks.sand); RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Steel").getProduct(AllowedProducts.getProductByName("INGOT")), 6000, 1, "ingotIron", Items.coal); //TODO add 2Al2O3 as output RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("TitaniumAluminide").getProduct(AllowedProducts.getProductByName("INGOT"), 3), 9000, 20, new NumberedOreDictStack("ingotAluminum", 7), new NumberedOreDictStack("ingotTitanium", 3)); //TODO titanium dioxide //Chemical Reactor RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new Object[] {new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge,1, 0), new ItemStack(Items.coal, 1, 1)}, 40, 20, new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge, 1, AdvancedRocketryItems.itemCarbonScrubberCartridge.getMaxDamage())); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new ItemStack(Items.dye,5,0xF), 100, 1, Items.bone, new FluidStack(AdvancedRocketryFluids.fluidNitrogen, 10)); //Rolling Machine RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 0), 100, 1, "sheetIron", "sheetIron"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 1), 200, 2, "sheetSteel", "sheetSteel"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 2), 100, 1, "sheetAluminum", "sheetAluminum"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 3), 1000, 8, "sheetTitanium", "sheetTitanium"); NetworkRegistry.INSTANCE.registerGuiHandler(this, new zmaster587.advancedRocketry.inventory.GuiHandler()); planetWorldType = new WorldTypePlanetGen("PlanetCold"); spaceWorldType = new WorldTypeSpace("Space"); AdvancedRocketryBiomes.moonBiome = new BiomeGenMoon(config.get(BIOMECATETORY, "moonBiomeId", 90).getInt(), true); AdvancedRocketryBiomes.alienForest = new BiomeGenAlienForest(config.get(BIOMECATETORY, "alienForestBiomeId", 91).getInt(), true); AdvancedRocketryBiomes.hotDryBiome = new BiomeGenHotDryRock(config.get(BIOMECATETORY, "hotDryBiome", 92).getInt(), true); AdvancedRocketryBiomes.spaceBiome = new BiomeGenSpace(config.get(BIOMECATETORY, "spaceBiomeId", 93).getInt(), true); AdvancedRocketryBiomes.stormLandsBiome = new BiomeGenStormland(config.get(BIOMECATETORY, "stormLandsBiomeId", 94).getInt(), true); AdvancedRocketryBiomes.crystalChasms = new BiomeGenCrystal(config.get(BIOMECATETORY, "crystalChasmsBiomeId", 95).getInt(), true); AdvancedRocketryBiomes.swampDeepBiome = new BiomeGenDeepSwamp(config.get(BIOMECATETORY, "deepSwampBiomeId", 96).getInt(), true); AdvancedRocketryBiomes.marsh = new BiomeGenMarsh(config.get(BIOMECATETORY, "marsh", 97).getInt(), true); AdvancedRocketryBiomes.oceanSpires = new BiomeGenOceanSpires(config.get(BIOMECATETORY, "oceanSpires", 98).getInt(), true); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.alienForest); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.spaceBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.stormLandsBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.crystalChasms); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.swampDeepBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.marsh); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.oceanSpires); String[] biomeBlackList = config.getStringList("BlacklistedBiomes", "Planet", new String[] {"7", "8", "9", "127", String.valueOf(AdvancedRocketryBiomes.alienForest.biomeID)}, "List of Biomes to be blacklisted from spawning as BiomeIds, default is: river, sky, hell, void, alienForest"); String[] biomeHighPressure = config.getStringList("HighPressureBiomes", "Planet", new String[] { String.valueOf(AdvancedRocketryBiomes.swampDeepBiome.biomeID), String.valueOf(AdvancedRocketryBiomes.stormLandsBiome.biomeID) }, "Biomes that only spawn on worlds with pressures over 125, will override blacklist. Defaults: StormLands, DeepSwamp"); String[] biomeSingle = config.getStringList("SingleBiomes", "Planet", new String[] { String.valueOf(AdvancedRocketryBiomes.swampDeepBiome.biomeID), String.valueOf(AdvancedRocketryBiomes.crystalChasms.biomeID), String.valueOf(AdvancedRocketryBiomes.alienForest.biomeID), String.valueOf(BiomeGenBase.desertHills.biomeID), String.valueOf(BiomeGenBase.mushroomIsland.biomeID), String.valueOf(BiomeGenBase.extremeHills.biomeID), String.valueOf(BiomeGenBase.icePlains.biomeID) }, "Some worlds have a chance of spawning single biomes contained in this list. Defaults: deepSwamp, crystalChasms, alienForest, desert hills, mushroom island, extreme hills, ice plains"); config.save(); //Prevent these biomes from spawning normally AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.spaceBiome); //Read BlackList from config and register Blacklisted biomes for(String string : biomeBlackList) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome.biomeID == 0 && id != 0) logger.warning(String.format("Error blackListing biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerBlackListBiome(biome); } catch (NumberFormatException e) { logger.warning("Error blackListing \"" + string + "\". It is not a valid number"); } } if(zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes) { AdvancedRocketryBiomes.instance.blackListVanillaBiomes(); } //Read and Register High Pressure biomes from config for(String string : biomeHighPressure) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome.biomeID == 0 && id != 0) logger.warning(String.format("Error registering high pressure biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerHighPressureBiome(biome); } catch (NumberFormatException e) { logger.warning("Error registering high pressure biome \"" + string + "\". It is not a valid number"); } } //Read and Register Single biomes from config for(String string : biomeSingle) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome.biomeID == 0 && id != 0) logger.warning(String.format("Error registering single biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerSingleBiome(biome); } catch (NumberFormatException e) { logger.warning("Error registering single biome \"" + string + "\". It is not a valid number"); } } } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.registerEventHandlers(); proxy.registerKeyBindings(); //TODO: debug //ClientCommandHandler.instance.registerCommand(new Debugger()); PlanetEventHandler handle = new PlanetEventHandler(); FMLCommonHandler.instance().bus().register(handle); MinecraftForge.EVENT_BUS.register(handle); MinecraftForge.EVENT_BUS.register(new BucketHandler()); CableTickHandler cable = new CableTickHandler(); FMLCommonHandler.instance().bus().register(cable); MinecraftForge.EVENT_BUS.register(cable); InputSyncHandler inputSync = new InputSyncHandler(); FMLCommonHandler.instance().bus().register(inputSync); MinecraftForge.EVENT_BUS.register(inputSync); if(Loader.isModLoaded("GalacticraftCore") && zmaster587.advancedRocketry.api.Configuration.overrideGCAir) { GalacticCraftHandler eventHandler = new GalacticCraftHandler(); MinecraftForge.EVENT_BUS.register(eventHandler); if(event.getSide().isClient()) FMLCommonHandler.instance().bus().register(eventHandler); } FMLCommonHandler.instance().bus().register(SpaceObjectManager.getSpaceManager()); PacketHandler.init(); FuelRegistry.instance.registerFuel(FuelType.LIQUID, AdvancedRocketryFluids.fluidRocketFuel, 1); GameRegistry.registerWorldGenerator(new OreGenerator(), 100); ForgeChunkManager.setForcedChunkLoadingCallback(instance, new WorldEvents()); //AutoGenned Recipes for(zmaster587.libVulpes.api.material.Material ore : MaterialRegistry.getAllMaterials()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("ORE")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); if(AllowedProducts.getProductByName("NUGGET").isOfType(ore.getAllowedProducts())) { ItemStack nugget = ore.getProduct(AllowedProducts.getProductByName("NUGGET")); nugget.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(nugget, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("INGOT")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("CRYSTAL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("CRYSTAL")), 300, 20, AllowedProducts.getProductByName("DUST").name().toLowerCase() + str); } if(AllowedProducts.getProductByName("BOULE").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("BOULE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str, AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str); } if(AllowedProducts.getProductByName("STICK").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) { for(String name : ore.getOreDictNames()) if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name)) RecipesMachine.getInstance().addRecipe(TileLathe.class, ore.getProduct(AllowedProducts.getProductByName("STICK")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name); //ore.getProduct(AllowedProducts.getProductByName("INGOT"))); } if(AllowedProducts.getProductByName("PLATE").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames)) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("PLATE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames); if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("PLATE"),3), 0, 0, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + oreDictNames); } } } if(AllowedProducts.getProductByName("SHEET").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("SHEET")), 300, 200, AllowedProducts.getProductByName("PLATE").name().toLowerCase() + oreDictNames); } } if(AllowedProducts.getProductByName("COIL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("COIL")), "ooo", "o o", "ooo",'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } if(AllowedProducts.getProductByName("FAN").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("FAN")), "p p", " r ", "p p", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("GEAR").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("GEAR")), "sps", " r ", "sps", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 's', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts())) { ItemStack ingot = ore.getProduct(AllowedProducts.getProductByName("INGOT")); ingot.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(ingot, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("BLOCK")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("DUST").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("DUST")), 0, 0, AllowedProducts.getProductByName("ORE").name().toLowerCase() + str); } } } //Handle vanilla integration if(zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood) { for(int i = 0; i < 4; i++) { RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.planks, 6, i), 80, 10, new ItemStack(Blocks.log,1, i)); } RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.planks, 6, 4), 80, 10, new ItemStack(Blocks.log2,1, 0)); } //Handle items from other mods if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) { for(Entry<AllowedProducts, HashSet<String>> entry : modProducts.entrySet()) { if(entry.getKey() == AllowedProducts.getProductByName("PLATE")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("PLATE").isOfType(material.getAllowedProducts())) ) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, OreDictionary.getOres("plate" + str).get(0), 300, 20, "ingot" + str); } } } else if(entry.getKey() == AllowedProducts.getProductByName("STICK")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("STICK").isOfType(material.getAllowedProducts())) ) { //GT registers rods as sticks if(OreDictionary.doesOreNameExist("rod" + str) && OreDictionary.getOres("rod" + str).size() > 0) RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("rod" + str).get(0), 300, 20, "ingot" + str); else if(OreDictionary.doesOreNameExist("stick" + str) && OreDictionary.getOres("stick" + str).size() > 0) { RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("stick" + str).get(0), 300, 20, "ingot" + str); } } } } } } //Register buckets BucketHandler.INSTANCE.registerBucket(AdvancedRocketryBlocks.blockFuelFluid, AdvancedRocketryItems.itemBucketRocketFuel); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidRocketFuel, new ItemStack(AdvancedRocketryItems.itemBucketRocketFuel), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidNitrogen, new ItemStack(AdvancedRocketryItems.itemBucketNitrogen), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidHydrogen, new ItemStack(AdvancedRocketryItems.itemBucketHydrogen), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidOxygen, new ItemStack(AdvancedRocketryItems.itemBucketOxygen), new ItemStack(Items.bucket)); //Register mixed material's recipes for(MixedMaterial material : MaterialRegistry.getMixedMaterialList()) { RecipesMachine.getInstance().addRecipe(material.getMachine(), material.getProducts(), 100, 10, material.getInput()); } //Register space dimension net.minecraftforge.common.DimensionManager.registerProviderType(zmaster587.advancedRocketry.api.Configuration.spaceDimId, WorldProviderSpace.class, true); net.minecraftforge.common.DimensionManager.registerDimension(zmaster587.advancedRocketry.api.Configuration.spaceDimId,zmaster587.advancedRocketry.api.Configuration.spaceDimId); //Register Whitelisted Sealable Blocks logger.fine("Start registering sealable blocks"); for(String str : sealableBlockWhileList) { Block block = Block.getBlockFromName(str); if(block == null) logger.warning("'" + str + "' is not a valid Block"); else SealableBlockHandler.INSTANCE.addSealableBlock(block); } logger.fine("End registering sealable blocks"); sealableBlockWhileList = null; //Add mappings for multiblockmachines //Data mapping 'D' List<BlockMeta> list = new LinkedList<BlockMeta>(); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 0)); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 8)); TileMultiBlock.addMapping('D', list); } @EventHandler public void serverStarted(FMLServerStartedEvent event) { for (int dimId : DimensionManager.getInstance().getLoadedDimensions()) { DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(dimId); if(!properties.isNativeDimension) { if(properties.getId() != zmaster587.advancedRocketry.api.Configuration.MoonId) DimensionManager.getInstance().deleteDimension(properties.getId()); else if (!Loader.isModLoaded("GalacticraftCore")) properties.isNativeDimension = true; } } } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new WorldCommand()); if(Loader.isModLoaded("GalacticraftCore") ) zmaster587.advancedRocketry.api.Configuration.MoonId = ConfigManagerCore.idDimensionMoon; //Register hard coded dimensions if(!zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().loadDimensions(zmaster587.advancedRocketry.dimension.DimensionManager.filePath)) { int numRandomGeneratedPlanets = 9; int numRandomGeneratedGasGiants = 1; File file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/planetDefs.xml"); logger.info("Checking for config at " + file.getAbsolutePath()); if(file.exists()) { logger.info("File found!"); XMLPlanetLoader loader = new XMLPlanetLoader(); try { loader.loadFile(file); List<DimensionProperties> list = loader.readAllPlanets(); for(DimensionProperties properties : list) DimensionManager.getInstance().registerDim(properties, true); numRandomGeneratedPlanets = loader.getMaxNumPlanets(); numRandomGeneratedGasGiants = loader.getMaxNumGasGiants(); } catch(IOException e) { logger.severe("XML planet config exists but cannot be loaded! Defaulting to random gen."); } } if(zmaster587.advancedRocketry.api.Configuration.MoonId == -1) zmaster587.advancedRocketry.api.Configuration.MoonId = DimensionManager.getInstance().getNextFreeDim(); DimensionProperties dimensionProperties = new DimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId); dimensionProperties.setAtmosphereDensityDirect(0); dimensionProperties.averageTemperature = 20; dimensionProperties.gravitationalMultiplier = .166f; //Actual moon value dimensionProperties.setName("Luna"); dimensionProperties.orbitalDist = 150; dimensionProperties.addBiome(AdvancedRocketryBiomes.moonBiome); dimensionProperties.setParentPlanet(DimensionManager.overworldProperties); dimensionProperties.setStar(DimensionManager.getSol()); dimensionProperties.isNativeDimension = !Loader.isModLoaded("GalacticraftCore"); DimensionManager.getInstance().registerDimNoUpdate(dimensionProperties, !Loader.isModLoaded("GalacticraftCore")); Random random = new Random(System.currentTimeMillis()); for(int i = 0; i < numRandomGeneratedGasGiants; i++) { int baseAtm = 180; int baseDistance = 100; DimensionProperties properties = DimensionManager.getInstance().generateRandomGasGiant("",baseDistance + 50,baseAtm,125,100,100,75); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(8); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); moonProperties.setParentPlanet(properties); } } } for(int i = 0; i < numRandomGeneratedPlanets; i++) { int baseAtm = 75; int baseDistance = 100; if(i % 4 == 0) { baseAtm = 0; } else if(i != 6 && (i+2) % 4 == 0) baseAtm = 120; if(i % 3 == 0) { baseDistance = 170; } else if((i + 1) % 3 == 0) { baseDistance = 30; } DimensionProperties properties = DimensionManager.getInstance().generateRandom(baseDistance,baseAtm,125,100,100,75); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(4); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); moonProperties.setParentPlanet(properties); } } } } else if(Loader.isModLoaded("GalacticraftCore") ) { DimensionManager.getInstance().getDimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId).isNativeDimension = false; } } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); } @SubscribeEvent public void registerOre(OreRegisterEvent event) { if(!zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) return; for(AllowedProducts product : AllowedProducts.getAllAllowedProducts() ) { if(event.Name.startsWith(product.name().toLowerCase())) { HashSet<String> list = modProducts.get(product); if(list == null) { list = new HashSet<String>(); modProducts.put(product, list); } list.add(event.Name.substring(product.name().length())); } } //GT uses stick instead of Rod if(event.Name.startsWith("stick")) { HashSet<String> list = modProducts.get(AllowedProducts.getProductByName("STICK")); if(list == null) { list = new HashSet<String>(); modProducts.put(AllowedProducts.getProductByName("STICK"), list); } list.add(event.Name.substring("stick".length())); } } //Patch missing mappings @Mod.EventHandler public void missingMappingEvent(FMLMissingMappingsEvent event) { Iterator<MissingMapping> itr = event.getAll().iterator(); while(itr.hasNext()) { MissingMapping mapping = itr.next(); if(mapping.name.equalsIgnoreCase("advancedrocketry:" + LibVulpesItems.itemBattery.getUnlocalizedName())) mapping.remap(LibVulpesItems.itemBattery); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.satellitePowerSource")) mapping.remap(AdvancedRocketryItems.itemSatellitePowerSource); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.circuitplate")) mapping.remap(AdvancedRocketryItems.itemCircuitPlate); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.wafer")) mapping.remap(AdvancedRocketryItems.itemWafer); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.itemUpgrade")) mapping.remap(AdvancedRocketryItems.itemUpgrade); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.dataUnit")) mapping.remap(AdvancedRocketryItems.itemDataUnit); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.satellitePrimaryFunction")) mapping.remap(AdvancedRocketryItems.itemSatellitePrimaryFunction); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.pressureTank")) mapping.remap(AdvancedRocketryItems.itemPressureTank); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.pressureTank")) mapping.remap(AdvancedRocketryItems.itemPressureTank); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.lens")) mapping.remap(AdvancedRocketryItems.itemLens); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.miscpart")) mapping.remap(AdvancedRocketryItems.itemMisc); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.circuitIC")) mapping.remap(AdvancedRocketryItems.itemIC); } } }
import java.io.*; import java.util.*; /* Though it's one of the most fun I've had solving a challenge, it's difficult to describe how the solution works, a telltale sign I don't fully understand how I did it myself. The best analogy I can think of, the one I used throughout to solve the problem, is to think of the input as a mountain range; the index being the x coordinate and the value being the y coordinate. Then follow along with the comments provided and visualize the processes described. Hope it helps! */ public class Solution{ public static void main(String[] args) throws IOException{ //Get input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] A = new int[N]; N = 0; for(String a : br.readLine().split(" ")){ A[N++] = Integer.parseInt(a); } br.close(); br = null; //Solve long count = solve(A, N); //Print System.out.print(count); } private static long solve(int[] A, int N){ if (N < 2){ return N; } long count = N; //Initialize int numTops = 1; int minStart = 0; int numStarts = 1; int[] startIs = new int[N]; int[] startVs = new int[N]; int[] topIs = new int[(N >> 1) + 1]; int[] topVs = new int[(N >> 1) + 1]; topIs[0] = -1; topVs[0] = N + 1; startIs[0] = 0; startVs[0] = A[0]; //For every value in A for (int i = 1; i < N; ++i){ int val = A[i]; //If upslope if (val > A[i-1]){ //If we are above highest mountain previously visible behind us if (val > topVs[numTops-1]){ //Look for highest mountaintop now visible behind us while (--numTops > 0 && val > topVs[numTops-1]){ } //Look for first start possible after found mountaintop minStart = ~Arrays.binarySearch(startIs, 0, numStarts, topIs[numTops-1]); } //Add the number of starts that can reach this point count += numStarts - minStart; //If downslope } else { //Save mountaintop topIs[numTops] = i-1; topVs[numTops++] = A[i-1]; //Ride slope to bottom while (++i < N && A[i] < A[i-1]){ } //Get the valley's bottom val = A[--i]; //Ignore unstartable starts (Slices tops off mountains before us down to this point) minStart = numStarts = ~Arrays.binarySearch(startVs, 0, numStarts, val); } //Add start point to list startIs[numStarts] = i; startVs[numStarts++] = val; /* System.out.println("i: " + i + ", val: " + val); System.out.println("Tops(" + numTops + "): " + Arrays.toString(topIs) + ", " + Arrays.toString(topVs)); System.out.println("Starts(" + numStarts + "): " + Arrays.toString(startIs) + ", " + Arrays.toString(startVs)); System.out.println("Count: " + count + ", minStart: " + minStart); System.out.println(""); */ } return count; } }
package com.fourlastor.dante.html; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ImageSpan; import com.fourlastor.dante.parser.Block; import com.fourlastor.dante.parser.BlockListener; class ImgListener implements BlockListener { private static final String UNICODE_REPLACE = "\uFFFC"; private static final String IMG = "img"; private final ImgLoader imgLoader; ImgListener(ImgLoader imgLoader) { this.imgLoader = imgLoader; } @Override public void start(Block block, SpannableStringBuilder text) { String src = ((HtmlBlock) block).getAttributes().get("src"); if (src == null) { return; } int len = text.length(); text.append(UNICODE_REPLACE); Drawable image = imgLoader.loadImage(src); text.setSpan( new ImageSpan(image, src), len, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } @Override public void end(Block block, SpannableStringBuilder text) { // nothing to do here } @Override public boolean match(Block block) { return block instanceof HtmlBlock && IMG.equalsIgnoreCase(((HtmlBlock) block).getName()); } }
package io.jasonsparc.chemistry; import android.support.annotation.AnyRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.View; import android.view.ViewGroup; import io.jasonsparc.chemistry.util.InflateUtils; public abstract class Chemistry<Item> implements IdSelector<Item>, TypeSelector<Item> { public long getItemId(Item item) { return NO_ID; } @ViewType @AnyRes public abstract int getItemViewType(Item item); public abstract VhFactory<?> getVhFactory(Item item); public abstract ItemBinder<? super Item, ?> getItemBinder(Item item); // Utilities public static View inflate(@NonNull ViewGroup parent, @LayoutRes int layoutRes) { return InflateUtils.inflate(parent, layoutRes); } // Factories public static <Item> BasicChemistry.Preperator<Item> make() { return new BasicChemistry.Preperator<>(); } public static <Item> BasicChemistry.Preperator<Item> make(@ViewType @AnyRes int viewType) { return new BasicChemistry.Preperator<Item>().useViewType(viewType); } public static <Item, VH extends ViewHolder> BasicChemistry.Boiler<Item, VH> make(@NonNull BasicChemistry<? super Item, VH> base) { return new BasicChemistry.Boiler<>(base); } public static <Item, VH extends ViewHolder> BasicChemistry.Boiler<Item, VH> make(@ViewType @AnyRes int viewType, @NonNull BasicChemistry<? super Item, VH> base) { return new BasicChemistry.Boiler<>(base).useViewType(viewType); } public static <Item, VH extends ViewHolder> BasicChemistry.Boiler<Item, VH> make(@NonNull BasicChemistry.Transformer<? super Item, ? super VH> transformer) { return new BasicChemistry.Boiler<Item, VH>().compose(transformer); } }
package com.dglogik.mobile; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.hardware.display.DisplayManager; import android.location.Location; import android.location.LocationManager; import android.media.AudioManager; import android.net.Uri; import android.os.BatteryManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.speech.tts.TextToSpeech; import android.support.annotation.NonNull; import android.util.Log; import android.view.Display; import android.widget.Toast; import com.dglogik.api.BasicMetaData; import com.dglogik.api.DGMetaData; import com.dglogik.api.DGNode; import com.dglogik.api.server.AbstractTunnelClient; import com.dglogik.dslink.Application; import com.dglogik.dslink.client.Client; import com.dglogik.dslink.client.command.base.ArgValue; import com.dglogik.dslink.client.command.base.ArgValueMetadata; import com.dglogik.dslink.client.command.base.Options; import com.dglogik.dslink.node.Poller; import com.dglogik.dslink.node.ValuePoint; import com.dglogik.dslink.node.base.BaseAction; import com.dglogik.dslink.node.base.BaseNode; import com.dglogik.dslink.plugin.Plugin; import com.dglogik.dslink.tunnel.TunnelClientFactory; import com.dglogik.mobile.link.DataValueNode; import com.dglogik.mobile.link.DeviceNode; import com.dglogik.mobile.link.MusicNode; import com.dglogik.mobile.link.RootNode; import com.dglogik.mobile.link.AudioSystemNode; import com.dglogik.mobile.ui.ControllerActivity; import com.dglogik.mobile.wear.WearableSupport; import com.dglogik.table.Table; import com.dglogik.table.Tables; import com.dglogik.value.DGValue; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Scope; import com.google.android.gms.fitness.Fitness; import com.google.android.gms.fitness.FitnessStatusCodes; import com.google.android.gms.location.*; import android.app.*; import com.google.android.gms.wearable.Wearable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import ext.javax.servlet.ServletContext; public class DGMobileContext { public static final String TAG = "DGMobile"; public static DGMobileContext CONTEXT; public AndroidTunnelClient tunnelClient; @NonNull public final LinkService service; @NonNull public final WearableSupport wearable; public final GoogleApiClient googleClient; @NonNull public final Application link; public boolean linkStarted = false; @NonNull public final SensorManager sensorManager; @NonNull public final LocationManager locationManager; @NonNull public final PowerManager powerManager; @NonNull public final Client client; public final SharedPreferences preferences; public static final RootNode<DeviceNode> devicesNode = new RootNode<>("Devices"); public DeviceNode currentDeviceNode; public FitnessSupport fitness; public boolean mResolvingError; public DGMobileContext(@NonNull final LinkService service) { CONTEXT = this; this.service = service; this.handler = new Handler(getApplicationContext().getMainLooper()); this.wearable = new WearableSupport(this); this.fitness = new FitnessSupport(this); this.preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); GoogleApiClient.Builder apiClientBuilder = new GoogleApiClient.Builder(getApplicationContext()) .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { Log.i(TAG, "Google API Client Connected"); initialize(); } @Override public void onConnectionSuspended(int i) { } }) .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS) { try { connectionResult.startResolutionForResult( ControllerActivity.INSTANCE, 50); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } return; } Log.e(TAG, "Google API Client Connection Failed! Code = " + connectionResult.getErrorCode()); ControllerActivity.DID_FAIL = true; ControllerActivity.ERROR_MESSAGE = "Google API Client Failed to Connect: Code = " + connectionResult.getErrorCode(); } }); apiClientBuilder.addApi(LocationServices.API); apiClientBuilder.addApi(ActivityRecognition.API); apiClientBuilder.setHandler(handler); if (preferences.getBoolean("feature.wear", false)) { apiClientBuilder.addApi(Wearable.API); } if (preferences.getBoolean("feature.fitness", false)) { apiClientBuilder.addApi(Fitness.API); apiClientBuilder .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ)) .addScope(new Scope(Scopes.FITNESS_BODY_READ)); apiClientBuilder.setAccountName(preferences.getString("account.name", null)); } this.googleClient = apiClientBuilder.build(); this.sensorManager = (SensorManager) service.getSystemService(LinkService.SENSOR_SERVICE); this.locationManager = (LocationManager) service.getSystemService(LinkService.LOCATION_SERVICE); this.link = Application.get(); this.client = new Client(false) { @Override public void run() { stop = false; try { Thread.sleep(2000); } catch (Exception ignored) { } log("Running Client"); while (!stop) { try { Thread.sleep(100); } catch (Exception ignored) { } } log("Client Complete"); } @Override protected void onStop() { stop = true; } }; link.setClient(client); link.setTunnelClientFactory(new TunnelClientFactory() { @Override public AbstractTunnelClient create(ServletContext servletContext, String uri) { tunnelClient = new AndroidTunnelClient(servletContext, uri); return tunnelClient; } }); powerManager = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE); } private boolean stop = false; public void playSearchArtist(final String artist) { execute(new Action() { @Override public void run() { Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH); intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE); intent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist); intent.putExtra(SearchManager.QUERY, artist); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } }); } public void playSearchSong(final String song) { execute(new Action() { @Override public void run() { Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH); intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE); intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song); intent.putExtra(SearchManager.QUERY, song); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } }); } public static boolean initializedLink = false; public void initialize() { if (preferences.getBoolean("feature.wear", false)) { wearable.initialize(); } if (preferences.getBoolean("feature.fitness", false)) { fitness.initialize(); } if (!initializedLink) { link.register(new Plugin() { @Override public void preInit(Client client) { } @Override public void init(Options options) { } @Override public DGNode[] getRootNodes() { return new DGNode[]{ devicesNode }; } }); final String name = preferences.getString("link.name", "Android") .replaceAll("\\+", " ") .replaceAll(" ", ""); final String brokerUrl = preferences.getString("broker.url", ""); link.init(new String[0], new Options(new HashMap<String, ArgValue>() {{ put("url", new ArgValue(new ArgValueMetadata().setType(ArgValueMetadata.Type.STRING)).set(brokerUrl)); put("name", new ArgValue(new ArgValueMetadata().setType(ArgValueMetadata.Type.STRING)).set(name)); }}, false)); initializedLink = true; } currentDeviceNode = new DeviceNode(Build.MODEL); setupCurrentDevice(currentDeviceNode); devicesNode.addChild(currentDeviceNode); startLink(); } public PackageManager getPackageManager() { return getApplicationContext().getPackageManager(); } public void sendMusicCommand(final String command) { execute(new Action() { @Override public void run() { Intent intent = new Intent("com.android.music.musicservicecommand"); intent.putExtra("command", command); getApplicationContext().sendBroadcast(intent); } }); } public boolean enableNode(String id) { NodeDescriptor desc = null; for (NodeDescriptor descriptor : DGConstants.NODES) { if (descriptor.getId().equals(id)) { desc = descriptor; } } if (desc == null) { log("No Descriptor found for node: " + id); log("Defaulting to Disabled"); return false; } return preferences.getBoolean("providers." + id, desc.isDefaultEnabled()); } public void startActivity(Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(intent); } public double lastLatitude; public double lastLongitude; public final List<Action> cleanups = new ArrayList<>(); public final List<SensorEventListener> sensorListeners = new ArrayList<>(); public void onCleanup(Action action) { cleanups.add(action); } public SensorEventListener sensorEventListener(SensorEventListener eventListener) { sensorListeners.add(eventListener); return eventListener; } public void setupCurrentDevice(@NonNull DeviceNode node) { if (preferences.getBoolean("providers.location", false)) { final DataValueNode latitudeNode = new DataValueNode("Location_Latitude", BasicMetaData.SIMPLE_INT); final DataValueNode longitudeNode = new DataValueNode("Location_Longitude", BasicMetaData.SIMPLE_INT); ValuePoint.DisplayFormatter formatter = new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + "°"; } }; latitudeNode.setFormatter(formatter); longitudeNode.setFormatter(formatter); latitudeNode.initializeValue = new Action() { @Override public void run() { latitudeNode.update(LocationServices.FusedLocationApi.getLastLocation(googleClient).getLatitude()); } }; longitudeNode.initializeValue = new Action() { @Override public void run() { longitudeNode.update(LocationServices.FusedLocationApi.getLastLocation(googleClient).getLongitude()); } }; LocationRequest request = new LocationRequest(); request.setFastestInterval(500); request.setInterval(3000); request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); final LocationListener listener = new LocationListener() { @Override public void onLocationChanged(@NonNull Location location) { if (lastLatitude != location.getLatitude()) { latitudeNode.update(location.getLatitude()); lastLatitude = location.getLatitude(); } if (lastLongitude != location.getLongitude()) { longitudeNode.update(location.getLongitude()); lastLongitude = location.getLatitude(); } } }; LocationServices.FusedLocationApi.requestLocationUpdates(googleClient, request, listener); onCleanup(new Action() { @Override public void run() { LocationServices.FusedLocationApi.removeLocationUpdates(googleClient, listener); } }); node.addChild(latitudeNode); node.addChild(longitudeNode); } if (enableNode("battery")) { final DataValueNode batteryLevelNode = new DataValueNode("Battery_Level", BasicMetaData.SIMPLE_INT); final DataValueNode chargerConnectedNode = new DataValueNode("Charger_Connected", BasicMetaData.SIMPLE_BOOL); final DataValueNode batteryFullNode = new DataValueNode("Battery_Full", BasicMetaData.SIMPLE_BOOL); batteryLevelNode.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { try { return "" + dgValue.toDouble() + "%"; } catch (Exception e) { try { return "" + dgValue.toInteger() + "%"; } catch (Exception e2) { return "null"; } } } }); batteryLevelNode.setGetValueCallback(new DataValueNode.GetValueCallback() { @Override public DGValue handle(DGValue old) { final Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); assert batteryStatus != null; int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); double percent = (level / (float) scale) * 100; return DGValue.make(percent); } }); batteryLevelNode.setGetValueCallback(new DataValueNode.GetValueCallback() { @Override public DGValue handle(DGValue old) { final Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); assert batteryStatus != null; int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL; return DGValue.make(isFull); } }); chargerConnectedNode.setGetValueCallback(new DataValueNode.GetValueCallback() { @Override public DGValue handle(DGValue old) { final Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); assert batteryStatus != null; int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isChargerConnected = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; return DGValue.make(isChargerConnected); } }); poller(new Action() { @Override public void run() { if (isBatteryLevelInitialized && !batteryLevelNode.hasSubscriptions() && !chargerConnectedNode.hasSubscriptions() && !batteryFullNode.hasSubscriptions()) return; isBatteryLevelInitialized = true; final Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); assert batteryStatus != null; int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isChargerConnected = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL; double percent = (level / (float) scale) * 100; batteryLevelNode.update(percent); chargerConnectedNode.update(isChargerConnected); batteryFullNode.update(isFull); } }).poll(TimeUnit.SECONDS, 2, false); node.addChild(batteryLevelNode); node.addChild(batteryFullNode); node.addChild(chargerConnectedNode); } if (Build.VERSION.SDK_INT >= 20 && preferences.getBoolean("providers.screen", false)) { setupScreenProvider(node); } if (enableNode("activity")) { activityNode = new DataValueNode("Activity", BasicMetaData.SIMPLE_STRING); final PendingIntent intent = PendingIntent.getService(getApplicationContext(), 40, new Intent(getApplicationContext(), ActivityRecognitionIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT); ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleClient, 1000, intent); onCleanup(new Action() { @Override public void run() { ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleClient, intent); } }); node.addChild(activityNode); } if (preferences.getBoolean("actions.notifications", true)) { final NotificationManager notificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE); final BaseAction createNotificationAction = new BaseAction("CreateNotification") { @NonNull @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { Notification.Builder builder = new Notification.Builder(getApplicationContext()); builder.setContentTitle(args.get("title").toString()); builder.setContentText(args.get("content").toString()); builder.setSmallIcon(R.drawable.ic_launcher); Notification notification = builder.build(); currentNotificationId++; notificationManager.notify(currentNotificationId, notification); return Tables.makeTable(new HashMap<String, DGMetaData>() {{ put("id", BasicMetaData.SIMPLE_INT); }}, new HashMap<String, DGValue>() {{ put("id", DGValue.make(currentNotificationId)); }}); } }; createNotificationAction.addParam("title", BasicMetaData.SIMPLE_STRING); createNotificationAction.addParam("content", BasicMetaData.SIMPLE_STRING); final BaseAction destroyNotificationAction = new BaseAction("DestroyNotification") { @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { int id = args.get("id").toInt(); notificationManager.cancel(id); return null; } }; destroyNotificationAction.addParam("id", BasicMetaData.SIMPLE_INT); onCleanup(new Action() { @Override public void run() { notificationManager.cancelAll(); } }); node.addAction(createNotificationAction); node.addAction(destroyNotificationAction); } if (enableSensor("steps", 19)) { final DataValueNode stepsNode = new DataValueNode("Steps", BasicMetaData.SIMPLE_INT); Sensor sensor = sensorManager.getDefaultSensor(19); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { stepsNode.update((double) event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); node.addChild(stepsNode); } // if (enableSensor("heart_rate", 21)) { // setupHeartRateMonitor(node); if (enableSensor("temperature", Sensor.TYPE_AMBIENT_TEMPERATURE)) { final DataValueNode tempCNode = new DataValueNode("Ambient_Temperature_Celsius", BasicMetaData.SIMPLE_INT); final DataValueNode tempFNode = new DataValueNode("Ambient_Temperature_Fahrenheit", BasicMetaData.SIMPLE_INT); tempCNode.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " °C"; } }); tempFNode.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " °F"; } }); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { double celsius = (double) event.values[0]; double fahrenheit = 32 + (celsius * 9 / 5); tempCNode.update(celsius); tempFNode.update(fahrenheit); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); node.addChild(tempCNode); node.addChild(tempFNode); } if (enableSensor("light_level", Sensor.TYPE_LIGHT)) { final DataValueNode lux = new DataValueNode("Light_Level", BasicMetaData.SIMPLE_INT); lux.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " lux"; } }); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { lux.update((double) event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, 6000); node.addChild(lux); } if (enableSensor("pressure", Sensor.TYPE_PRESSURE)) { final DataValueNode pressure = new DataValueNode("Air_Pressure", BasicMetaData.SIMPLE_INT); pressure.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " mbar"; } }); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { pressure.update((double) event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); node.addChild(pressure); } if (enableSensor("humidity", Sensor.TYPE_RELATIVE_HUMIDITY)) { final DataValueNode humidity = new DataValueNode("Humidity", BasicMetaData.SIMPLE_INT); humidity.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + "%"; } }); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { humidity.update((double) event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); node.addChild(humidity); } if (enableSensor("proximity", Sensor.TYPE_PROXIMITY)) { final DataValueNode proximity = new DataValueNode("Proximity", BasicMetaData.SIMPLE_INT); proximity.setFormatter(new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " cm"; } }); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { proximity.update((double) event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); node.addChild(proximity); } if (enableSensor("gyroscope", Sensor.TYPE_GYROSCOPE)) { final DataValueNode x = new DataValueNode("Gyroscope_X", BasicMetaData.SIMPLE_INT); final DataValueNode y = new DataValueNode("Gyroscope_Y", BasicMetaData.SIMPLE_INT); final DataValueNode z = new DataValueNode("Gyroscope_Z", BasicMetaData.SIMPLE_INT); ValuePoint.DisplayFormatter formatter = new ValuePoint.DisplayFormatter() { @Override public String handle(DGValue dgValue) { return "" + dgValue.toDouble() + " rad/s"; } }; x.setFormatter(formatter); y.setFormatter(formatter); z.setFormatter(formatter); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); sensorManager.registerListener(sensorEventListener(new SensorEventListener() { @Override public void onSensorChanged(@NonNull SensorEvent event) { x.update((double) event.values[0]); y.update((double) event.values[1]); z.update((double) event.values[2]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }), sensor, SensorManager.SENSOR_DELAY_NORMAL); currentDeviceNode.addChild(x); currentDeviceNode.addChild(y); currentDeviceNode.addChild(z); } if (preferences.getBoolean("actions.speak", true)) { final TextToSpeech speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { } }); final BaseAction speakAction = new BaseAction("Speak") { @SuppressWarnings("deprecation") @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { speech.speak(args.get("text").toString(), TextToSpeech.QUEUE_ADD, new HashMap<String, String>()); return null; } }; speakAction.addParam("text", BasicMetaData.SIMPLE_STRING); onCleanup(new Action() { @Override public void run() { speech.stop(); } }); node.addAction(speakAction); } if (preferences.getBoolean("actions.open_url", true)) { final BaseAction openUrlAction = new BaseAction("OpenUrl") { @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { final Uri url = Uri.parse(args.get("url").toString()); execute(new Action() { @Override public void run() { Intent intent = new Intent(Intent.ACTION_VIEW, url); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (intent.resolveActivity(getPackageManager()) != null) { getApplicationContext().startActivity(intent); } } }); return null; } }; openUrlAction.addParam("url", BasicMetaData.SIMPLE_STRING); node.addAction(openUrlAction); } if (enableNode("audio")) { final AudioSystemNode audioSystemNode = new AudioSystemNode(); final AudioManager manager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); audioSystemNode.addVolumeStream(manager, "Notification", AudioManager.STREAM_NOTIFICATION); audioSystemNode.addVolumeStream(manager, "System", AudioManager.STREAM_SYSTEM); audioSystemNode.addVolumeStream(manager, "Music", AudioManager.STREAM_MUSIC); audioSystemNode.addVolumeStream(manager, "Call", AudioManager.STREAM_VOICE_CALL); audioSystemNode.addVolumeStream(manager, "Ringer", AudioManager.STREAM_RING); audioSystemNode.addVolumeStream(manager, "Alarm", AudioManager.STREAM_ALARM); audioSystemNode.setupInformationNodes(manager); node.addChild(audioSystemNode); } if (preferences.getBoolean("actions.search", true)) { final BaseAction searchWebAction = new BaseAction("SearchWeb") { @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { final String query = args.get("query").toString(); execute(new Action() { @Override public void run() { Intent intent = new Intent(Intent.ACTION_SEARCH); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(SearchManager.QUERY, query); if (intent.resolveActivity(service.getPackageManager()) != null) { service.startActivity(intent); } } }); return null; } }; searchWebAction.addParam("query", BasicMetaData.SIMPLE_STRING); node.addAction(searchWebAction); } if (enableNode("music")) { MusicNode musicNode = new MusicNode(); musicNode.init(); node.addChild(musicNode); } if (preferences.getBoolean("providers.speech", true)) { recognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext()); final DataValueNode lastSpeechNode = new DataValueNode("Recognized_Speech", BasicMetaData.SIMPLE_STRING); final BaseAction startSpeechRecognitionAction = new BaseAction("StartSpeechRecognition") { @SuppressWarnings("deprecation") @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { handler.post(new Runnable() { @Override public void run() { recognizer.startListening(new Intent()); } }); return null; } }; final BaseAction stopSpeechRecognitionAction = new BaseAction("StopSpeechRecognition") { @SuppressWarnings("deprecation") @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { handler.post(new Runnable() { @Override public void run() { recognizer.stopListening(); } }); return null; } }; recognizer.setRecognitionListener(new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { log("Ready for Speech"); } @Override public void onBeginningOfSpeech() { log("Beginning of Speech"); } @Override public void onRmsChanged(float rmsdB) { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { log("End of Speech"); } @Override public void onError(int error) { log("Speech Error"); } @Override public void onResults(Bundle results) { log("Speech Results"); List<Float> scores = new ArrayList<>(); List<String> possibles = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); { float[] sc = results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES); for (float score : sc) { scores.add(score); } } int highestScore = 0; for (String possible : possibles) { int index = possibles.indexOf(possible); float lastHighest = scores.get(highestScore); if (scores.get(index) > lastHighest) { highestScore = index; } } String value = possibles.get(highestScore); Toast.makeText(getApplicationContext(), "You Said: " + value, Toast.LENGTH_LONG).show(); lastSpeechNode.update(value); } @Override public void onPartialResults(Bundle partialResults) { log("Partial Results"); } @Override public void onEvent(int eventType, Bundle params) { } }); node.addChild(lastSpeechNode); node.addAction(startSpeechRecognitionAction); node.addAction(stopSpeechRecognitionAction); } if (enableNode("power")) { log("Power Management Features Enabled"); setupPowerProvider(node); } } private boolean isBatteryLevelInitialized = false; // @TargetApi(20) // private void setupHeartRateMonitor(DeviceNode node) { // final DataValueNode rateNode = new DataValueNode("Heart_Rate", BasicMetaData.SIMPLE_INT); // Sensor sensor = sensorManager.getDefaultSensor(21); // sensorManager.registerListener(sensorEventListener(new SensorEventListener() { // @Override // public void onSensorChanged(@NonNull SensorEvent event) { // rateNode.update((double) event.values[0]); // @Override // public void onAccuracyChanged(Sensor sensor, int accuracy) { // }), sensor, SensorManager.SENSOR_DELAY_NORMAL); // node.addChild(rateNode); protected DataValueNode activityNode; private void setupPowerProvider(DeviceNode node) { BaseAction wakeUpAction = new BaseAction("WakeUp") { @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { long time = args.get("time").toLong(); powerManager.wakeUp(time); return null; } }; BaseAction sleepAction = new BaseAction("Sleep") { @Override public Table invoke(BaseNode baseNode, @NonNull Map<String, DGValue> args) { long time = args.get("time").toLong(); powerManager.goToSleep(time); return null; } }; wakeUpAction.addParam("time", BasicMetaData.SIMPLE_INT); sleepAction.addParam("time", BasicMetaData.SIMPLE_INT); node.addAction(wakeUpAction); node.addAction(sleepAction); } @TargetApi(20) private void setupScreenProvider(DeviceNode node) { final DisplayManager displayManager = (DisplayManager) service.getSystemService(Context.DISPLAY_SERVICE); final DataValueNode screenOn = new DataValueNode("Screen_On", BasicMetaData.SIMPLE_BOOL); final DisplayManager.DisplayListener listener = new DisplayManager.DisplayListener() { @Override public void onDisplayAdded(int i) { } @Override public void onDisplayRemoved(int i) { } @Override public void onDisplayChanged(int i) { Display display = displayManager.getDisplay(i); try { Method method = display.getClass().getMethod("getState"); boolean on = ((Integer) method.invoke(display)) == 2; screenOn.update(on); } catch (NoSuchMethodException ignored) { } catch (InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } }; displayManager.registerDisplayListener(listener, new Handler()); onCleanup(new Action() { @Override public void run() { displayManager.unregisterDisplayListener(listener); } }); screenOn.update(powerManager.isScreenOn()); node.addChild(screenOn); } public boolean enableSensor(String id, int type) { return enableNode(id) && !sensorManager.getSensorList(type).isEmpty(); } public int currentNotificationId = 0; @SuppressWarnings("FieldCanBeLocal") private Thread linkThread; public void startLink() { linkThread = new Thread(new Runnable() { @Override public void run() { log("Starting Link"); linkStarted = true; link.run(); log("Link Stopped"); linkStarted = false; } }); linkThread.start(); } public void execute(Action action) { handler.post(action); } public Context getApplicationContext() { return service.getApplicationContext(); } public final Handler handler; public void start() { googleClient.connect(); } public void destroy() { log("Running Destruction Actions"); for (Action action : cleanups) { action.run(); } log("Un-registering Sensor Event Listeners"); for (SensorEventListener eventListener : sensorListeners) { sensorManager.unregisterListener(eventListener); } if (recognizer != null) { log("Destroying Speech Recognizer"); recognizer.destroy(); } if (linkStarted) { log("Stopping Link"); new Thread(new Runnable() { @Override public void run() { link.stop(); log("Link Stopped"); log("Clearing Device Nodes"); devicesNode.clearChildren(); } }).start(); } log("Disconnecting Google API Client"); googleClient.disconnect(); } public SpeechRecognizer recognizer; public Poller poller(Action action) { final Poller poller = new Poller(action); onCleanup(new Action() { @Override public void run() { if (poller.running()) { poller.cancel(); } } }); return poller; } public static void log(String message) { Log.i(TAG, message); } }
package ru.nsu; import com.softmotions.commons.cont.Pair; import com.softmotions.ncms.asm.Asm; import com.softmotions.ncms.asm.AsmDAO; import com.softmotions.ncms.asm.render.AsmController; import com.softmotions.ncms.asm.render.AsmRendererContext; import com.softmotions.ncms.mhttl.SelectNode; import com.google.inject.Inject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * @author Tyutyunkov Vyacheslav (tve@softmotions.com) * @version $Id$ */ public class SearchNewsController implements AsmController { private static final Logger log = LoggerFactory.getLogger(SearchNewsController.class); private static final int DEFAULT_MAX_RESULTS = 20; private static final Map<String, Callable<Pair<Date, Date>>> TIME_SCOPES; private static final String DEFAULT_TIME_SCOPE = "all"; private final AsmDAO adao; private final SolrServer solr; static { TIME_SCOPES = new HashMap<>(); TIME_SCOPES.put(DEFAULT_TIME_SCOPE, new Callable<Pair<Date, Date>>() { public Pair<Date, Date> call() throws Exception { return null; } }); // TODO: configure? TIME_SCOPES.put("year", new Callable<Pair<Date, Date>>() { public Pair<Date, Date> call() throws Exception { Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -1); return new Pair<>(cal.getTime(), null); } }); TIME_SCOPES.put("half-year", new Callable<Pair<Date, Date>>() { public Pair<Date, Date> call() throws Exception { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -6); return new Pair<>(cal.getTime(), null); } }); TIME_SCOPES.put("month", new Callable<Pair<Date, Date>>() { public Pair<Date, Date> call() throws Exception { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); return new Pair<>(cal.getTime(), null); } }); } @Inject public SearchNewsController(AsmDAO adao, SolrServer solr) { this.adao = adao; this.solr = solr; } public boolean execute(AsmRendererContext ctx) throws Exception { prepare(ctx); HttpServletRequest req = ctx.getServletRequest(); String action = req.getParameter("spc.action"); if ("search".equals(action)) { ctx.put("results_only", true); } doSearch(ctx); return false; } private void prepare(AsmRendererContext ctx) { HttpServletRequest req = ctx.getServletRequest(); int offset = 0; int limit = DEFAULT_MAX_RESULTS; String offsetStr = req.getParameter("spc.start"); try { offset = !StringUtils.isBlank(offsetStr) ? Integer.parseInt(offsetStr) : offset; } catch (NumberFormatException ignored) { } ctx.put("search_start", offset); String limitStr = req.getParameter("spc.limit"); try { limit = !StringUtils.isBlank(limitStr) ? Integer.parseInt(limitStr) : limit; } catch (NumberFormatException ignored) { } ctx.put("search_limit", limit); String text = req.getParameter("spc.text"); ctx.put("search_query", text); String timeScope = req.getParameter("spc.scope"); timeScope = StringUtils.isBlank(timeScope) || !TIME_SCOPES.containsKey(timeScope) ? DEFAULT_TIME_SCOPE : timeScope; ctx.put("search_scope", timeScope); Collection<Pair<String, Boolean>> categories = new ArrayList<>(); Collection<String> selectedCategories = new ArrayList<>(); Object cObj = ctx.getRenderer().renderAsmAttribute(ctx, "categories", Collections.EMPTY_MAP); if (cObj instanceof Collection) { String[] categoryNames = req.getParameterValues("spc.category"); for (SelectNode category : (Iterable<SelectNode>) cObj) { boolean selected = false; if (categoryNames != null) { for (String categoryName : categoryNames) { if (category.getValue().equals(categoryName)) { selected = true; break; } } } categories.add(new Pair<>(category.getValue(), selected)); if (selected) { selectedCategories.add(category.getValue()); } } } ctx.put("search_categories", categories); ctx.put("search_categories_selected", selectedCategories); } private void doSearch(AsmRendererContext ctx) throws Exception { ModifiableSolrParams params = new ModifiableSolrParams(); String text = (String) ctx.get("search_query"); text = StringUtils.isBlank(text) ? "*" : QueryParser.escape(text); params.add(CommonParams.Q, text); String timeScopeFQ = ""; String timeScopeName = (String) ctx.get("search_scope"); if (!StringUtils.isBlank(timeScopeName) && TIME_SCOPES.containsKey(timeScopeName)) { Callable<Pair<Date, Date>> tsc = TIME_SCOPES.get(timeScopeName); Pair<Date, Date> timeScope = tsc != null ? tsc.call() : null; if (timeScope != null && (timeScope.getOne() != null || timeScope.getTwo() != null)) { timeScopeFQ = " +cdate:" + "[" + (timeScope.getOne() == null ? "*" : String.valueOf(timeScope.getOne().getTime())) + " TO " + (timeScope.getTwo() == null ? "*" : String.valueOf(timeScope.getTwo().getTime())) + "]"; } } String categoriesFQ = ""; Collection<String> selectedCategories = (Collection<String>) ctx.get("search_categories_selected"); if (selectedCategories != null && !selectedCategories.isEmpty()) { CollectionUtils.transform(selectedCategories, new Transformer() { public Object transform(Object input) { return "asm_attr_s_subcategory:" + QueryParser.escape(String.valueOf(input)); } }); categoriesFQ = " +(" + StringUtils.join(selectedCategories, " ") + ")"; } params.add(CommonParams.FQ, "+type:news* +published:true" + categoriesFQ + timeScopeFQ); int offset = ctx.get("search_start") != null ? (int) ctx.get("search_start") : 0; params.add(CommonParams.START, String.valueOf(offset)); int limit = ctx.get("search_limit") != null ? (int) ctx.get("search_limit") : DEFAULT_MAX_RESULTS; params.add(CommonParams.ROWS, String.valueOf(limit)); params.add(CommonParams.FL, "id,score,cdate"); params.add(CommonParams.SORT, "score desc, cdate desc"); QueryResponse queryResponse = solr.query(params); SolrDocumentList results = queryResponse.getResults(); Collection<Asm> asms = new ArrayList<>(results.size()); for (SolrDocument document : results) { asms.add(adao.asmSelectById(Long.valueOf(String.valueOf(document.getFieldValue("id"))))); } ctx.put("search_result", asms); } }
package com.orgecc.calltimer; import java.lang.reflect.Array; import java.util.Collection; import java.util.Date; import java.util.Map; import org.slf4j.Logger; class BaseCallTimer implements CallTimer { static final String HEADER = "YYYY-MM-DD HH:mm:ss.sss\tlevel\tTBID\tms\tinsize\toutsize\touttype\tmethod\tclass"; private static final String MSG_FORMAT = "%s\t%s\t%s\t%s\t%s\t%s"; private static final String TO_STRING_FORMAT = "%s:%s [%s %s.%s inputSize=%s, outputSize=%s, output=%s, callEnded=%s]"; private static final String TYPE_PREFIX_TO_OMIT = "java.lang."; static Logger saveHeader( final Logger logger ) { logger.warn( HEADER ); return logger; } static String normalizeOutMessage( final String s ) { return ( s.startsWith( TYPE_PREFIX_TO_OMIT ) ? s.substring( TYPE_PREFIX_TO_OMIT.length() ) : s ).replace( '\t', ' ' ); } @SuppressWarnings( "rawtypes" ) private static Integer getSize( final Object output ) { if ( output instanceof String ) { return ( (String) output ).length(); } if ( output instanceof Collection ) { return ( (Collection) output ).size(); } if ( output instanceof Map ) { return ( (Map) output ).size(); } if ( output.getClass().isArray() ) { return Array.getLength( output ); } return null; } long startNanos; long startMillis; String className; String methodName; long inputSize; private String outputSize; private String output; boolean callEnded; final transient Ticker ticker; final transient Logger logger; BaseCallTimer( final Ticker ticker, final Logger logger ) { this.ticker = ticker; this.logger = logger; } void saveEvent( final Throwable t, final String msg ) { if ( t == null ) { this.logger.info( msg ); return; } this.logger.error( msg ); } public final CallTimer callStart() { return callStart( 0 ); } public final CallTimer callStart( final byte[] b ) { return callStart( b == null ? 0 : b.length ); } public final CallTimer callStart( final long inputSize ) { this.startNanos = this.ticker.read(); this.startMillis = System.currentTimeMillis(); this.inputSize = inputSize; this.outputSize = null; this.output = null; this.callEnded = false; return setCallName( null, null ); } public final CallTimer setCallName( final String className, final String methodName, final int paramCount ) { return setCallName( className, methodName + "#" + paramCount ); } public final CallTimer setCallName( final String className, final String methodName ) { this.className = className == null ? "-" : className.replace( ' ', '-' ); this.methodName = methodName == null ? "-" : methodName.replace( ' ', '-' ); return this; } public final CallTimer setInputSize( final long inputSize ) { this.inputSize = inputSize; return this; } public final CallTimer setOutputSize( final long outputSize ) { this.outputSize = Long.toString( outputSize ); return this; } private CallTimer setOutput( final Object output ) { this.output = output == null ? null : output.getClass().getName(); return this; } private String normalizeOutputAndSize() { if ( this.output == null ) { if ( this.outputSize == null ) { this.outputSize = "-"; return "NULL"; } assert this.outputSize != null; // = method returned a serialized representation of the result class return "SER"; } assert this.output != null; final String result = normalizeOutMessage( this.output ); final Integer size = getSize( result ); this.outputSize = size == null ? "?" : size.toString(); return result; } final long durationInMillis() { return ( this.ticker.read() - this.startNanos ) / 1000000; } public void callEnd( final Throwable t ) { final long durationInMillis = durationInMillis(); if ( this.callEnded ) { return; } final String outputInfo; if ( t == null ) { outputInfo = normalizeOutputAndSize(); } else { outputInfo = "** " + normalizeOutMessage( t.toString() ) + " **"; this.outputSize = "E"; } this.output = null; final String msg = String.format( MSG_FORMAT, durationInMillis, this.inputSize, this.outputSize, outputInfo, this.methodName, this.className ); saveEvent( t, msg ); this.callEnded = true; } public final void callEnd() { callEnd( (Throwable) null ); } public final void callEnd( final byte[] output ) { callEnd( output == null ? 0 : output.length ); } public final void callEnd( final long outputSize ) { setOutputSize( outputSize ).callEnd(); } public final void callEnd( final Object output ) { setOutput( output ).callEnd(); } @Override public String toString() { return String.format( TO_STRING_FORMAT, this.getClass().getSimpleName(), this.ticker, new Date( this.startMillis ), this.className, this.methodName, this.inputSize, this.outputSize, this.output, this.callEnded ); } @Override protected final void finalize() throws Throwable { if ( !this.callEnded ) { callEnd( new Throwable( "CALL NOT ENDED" ) ); } super.finalize(); } }
package org.mustangproject; import org.mustangproject.ZUGFeRD.IZUGFeRDTradeSettlementPayment; /** * provides e.g. the IBAN to transfer money to :-) */ public class BankDetails implements IZUGFeRDTradeSettlementPayment { protected String IBAN, BIC, accountName=null; public BankDetails(String IBAN, String BIC) { this.IBAN = IBAN; this.BIC = BIC; } public String getIBAN() { return IBAN; } /** * Sets the IBAN "ID", which means that it only needs to be a way to uniquely * identify the IBAN. Of course you will specify your own IBAN in full length but * if you deduct from a customer's account you may e.g. leave out the first or last * digits so that nobody spying on the invoice gets to know the complete number * @param IBAN the "IBAN ID", i.e. the IBAN or parts of it * @return fluent setter */ public BankDetails setIBAN(String IBAN) { this.IBAN = IBAN; return this; } public String getBIC() { return BIC; } /*** * The bank identifier. Bank name is no longer neccessary in SEPA. * @param BIC the bic code * @return fluent setter */ public BankDetails setBIC(String BIC) { this.BIC = BIC; return this; } /*** * getOwn... methods will be removed in the future in favor of Tradeparty (e.g. Sender) class * */ @Override @Deprecated public String getOwnBIC() { return getBIC(); } @Override @Deprecated public String getOwnIBAN() { return getIBAN(); } /** * set Holder * @param name account name (usually account holder if != sender) * @return fluent setter */ public BankDetails setAccountName(String name) { accountName=name; return this; } @Override public String getAccountName() { return accountName; } }
package com.shuffle.protocol; import com.shuffle.bitcoin.Address; import com.shuffle.bitcoin.CoinNetworkError; import com.shuffle.bitcoin.Transaction; import com.shuffle.bitcoin.VerificationKey; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; public class MockCoin implements Simulator.MockCoin { public static class Output { final Address address; final long amountHeld; public Output(Address address, long amount) { this.address = address; this.amountHeld = amount; } @Override public String toString() { return "output[" + address.toString() + ", " + amountHeld + "]"; } @Override public boolean equals(Object o) { if (!(o instanceof Output)) { return false; } Output out = (Output)o; return address.equals(out.address) && amountHeld == out.amountHeld; } @Override public int hashCode() { return address.hashCode() + (int)amountHeld; } } public class MockTransaction implements Transaction { final List<Output> inputs = new LinkedList<>(); final List<Output> outputs = new LinkedList<>(); // A number used to represented slight variations in a transaction which would // result in different signatures being produced. int z = 1; public MockTransaction(List<Output> inputs, List<Output> outputs) { for (Output output : inputs) { if (output == null) throw new NullPointerException(); } for (Output output : outputs) { if (output == null) throw new NullPointerException(); } this.inputs.addAll(inputs); this.outputs.addAll(outputs); } public MockTransaction(List<Output> inputs, List<Output> outputs, int z) { this(inputs, outputs); this.z = z; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof MockTransaction)) { return false; } MockTransaction mock = (MockTransaction)o; if (this == mock) { return true; } if (z != mock.z) { return false; } if (inputs.size() != mock.inputs.size()) { return false; } if (outputs.size() != mock.outputs.size()) { return true; } Iterator<Output> i1 = inputs.iterator(); Iterator<Output> i2 = mock.inputs.iterator(); while(i1.hasNext()) { Output c1 = i1.next(); Output c2 = i2.next(); if (c2 == null) { return false; } if (!c1.equals(c2)) { return false; } } return true; } @Override public String toString() { return "{" + inputs.toString() + " ==> " + outputs.toString() + "}"; } @Override public void send() throws CoinNetworkError { MockCoin.this.send(this); } public MockTransaction copy() { return new MockTransaction(inputs, outputs); } } final ConcurrentHashMap<Address, Output> blockchain = new ConcurrentHashMap<>(); // The transaction that spends an output. final ConcurrentHashMap<Output, Transaction> spend = new ConcurrentHashMap<>(); // The transaction that sends to an input. final ConcurrentHashMap<Output, Transaction> sent = new ConcurrentHashMap<>(); // A number used to represented slight variations in a transaction which would // result in different signatures being produced. int z = 1; public MockCoin(Map<Address, Output> blockchain) { this.blockchain.putAll(blockchain); }; public MockCoin() { } public MockCoin setZ(int z) { this.z = z; return this; } @Override public synchronized void put(Address addr, long value) { Output entry = new Output(addr, value); blockchain.put(addr, entry); } @Override public synchronized Transaction spend(Address from, Address to, long amount) { Output output = blockchain.get(from); if (output == null) { return null; } if (amount > valueHeld(from)) { return null; } List<Output> in = new LinkedList<>(); List<Output> out = new LinkedList<>(); in.add(output); out.add(new Output(to, amount)); return new MockTransaction(in, out); } public synchronized void send(Transaction t) { if (t == null) throw new NullPointerException(); if (!(t instanceof MockTransaction)) { throw new InvalidImplementationError(); } MockTransaction mt = (MockTransaction) t; // First check that the transaction doesn't send more than it spends. long available = 0; for (Output input : mt.inputs) { available += input.amountHeld; } for (Output output : mt.outputs) { available -= output.amountHeld; } if (available < 0) { throw new CoinNetworkError(); } // Does the transaction spend from valid outputs? for (Output input : mt.inputs) { if (!blockchain.get(input.address).equals(input)) { throw new CoinNetworkError(); } } for (Output input : mt.inputs) { Transaction nt = spend.get(input); if (nt == null) { continue; } if (mt.equals(nt)) { return; } else { throw new CoinNetworkError(); } } // Register the transaction. for (Output input : mt.inputs) { spend.put(input, t); } for (Output output : mt.outputs) { blockchain.put(output.address, output); sent.put(output, t); } } @Override public synchronized long valueHeld(Address addr) { Output entry = blockchain.get(addr); if (entry == null) { return 0; } if (spend.get(entry) != null) { return 0; } return entry.amountHeld; } @Override // TODO transaction fees. public Transaction shuffleTransaction(final long amount, List<VerificationKey> from, Queue<Address> to, Map<VerificationKey, Address> changeAddresses) { if (amount == 0) { throw new IllegalArgumentException(); } List<Output> inputs = new LinkedList<>(); List<Output> outputs = new LinkedList<>(); // Are there inputs big enough blockchain make this transaction? for (VerificationKey key : from) { final Address address = key.address(); final long value = valueHeld(address); if (value < amount) { throw new CoinNetworkError(); } Output input = blockchain.get(address); if (input == null) { throw new CoinNetworkError(); } inputs.add(input); // If a change address has been provided, add that. Address change = changeAddresses.get(key); if (change != null) { outputs.add(new Output(change, value - amount)); } } for(Address address : to) { outputs.add(new Output(address, amount)); } return new MockTransaction(inputs, outputs, z); } @Override public Transaction getConflictingTransaction(Address addr, long amount) { if (valueHeld(addr) >= amount) { return null; } Output output = blockchain.get(addr); if (output == null) { return null; } Transaction t = spend.get(output); if (t != null) { return t; } return sent.get(output); } @Override public boolean spendsFrom(Address addr, long amount, Transaction t) { Transaction conflict = getConflictingTransaction(addr, amount); return conflict != null && t.equals(conflict); } @Override public String toString() { return "{" + blockchain.values().toString() + ", " + spend.toString() + "}"; } }
package weave.servlets; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.zip.DeflaterOutputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import weave.beans.JsonRpcErrorModel; import weave.beans.JsonRpcRequestModel; import weave.beans.JsonRpcResponseModel; import weave.utils.CSVParser; import weave.utils.ListUtils; import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import com.heatonresearch.httprecipes.html.PeekableInputStream; import com.thoughtworks.paranamer.BytecodeReadingParanamer; import com.thoughtworks.paranamer.Paranamer; import flex.messaging.MessageException; import flex.messaging.io.SerializationContext; import flex.messaging.io.amf.ASObject; import flex.messaging.io.amf.Amf3Input; import flex.messaging.io.amf.Amf3Output; import flex.messaging.messages.ErrorMessage; /** * This class provides a servlet interface to a set of functions. * The functions may be invoked using URL parameters via HTTP GET or AMF3-serialized objects via HTTP POST. * Currently, the result of calling a function is given as an AMF3-serialized object. * * TODO: Provide optional JSON output. * * Not all objects will be supported automatically. * GenericServlet supports basic AMF3-serialized objects such as String,Object,Array. * * The following mappings work (ActionScript -> Java): * Array -> Object[], Object[][], String[], String[][], double[], double[][], List * Object -> Map<String,Object> * String -> String, int, Integer, boolean, Boolean * Boolean -> boolean, Boolean * Number -> double * Raw byte stream -> Java InputStream * * The following Java parameter types are supported: * boolean, Boolean * int, Integer * float, Float * double, Double * String, String[], String[][] * Object, Object[], Object[][] * double[], double[][] * Map<String,Object> * List * InputStream * * TODO: Add support for more common parameter types. * * @author skota * @author adufilie * @author skolman */ public class GenericServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static long debugThreshold = 1000; /** * This is the name of the URL parameter corresponding to the method name. */ protected final String METHOD = "method"; protected final String PARAMS = "params"; protected final String STREAM_PARAMETER_INDEX = "streamParameterIndex"; private Map<String, ExposedMethod> methodMap = new HashMap<String, ExposedMethod>(); //Key: methodName private Paranamer paranamer = new BytecodeReadingParanamer(); // this gets parameter names from Methods /** * This class contains a Method with its parameter names and class instance. */ private class ExposedMethod { public ExposedMethod(Object instance, Method method, String[] paramNames) { this.instance = instance; this.method = method; this.paramNames = paramNames; } public Object instance; public Method method; public String[] paramNames; } /** * Default constructor. * This initializes all public methods defined in a class extending GenericServlet. */ protected GenericServlet() { super(); initLocalMethods(); } /** * @param serviceObjects The objects to invoke methods on. */ protected GenericServlet(Object ...serviceObjects) { super(); initLocalMethods(); for (Object serviceObject : serviceObjects) initAllMethods(serviceObject); } /** * This function will expose all the public methods of a class as servlet methods. * @param serviceObject The object containing public methods to be exposed by the servlet. */ protected void initLocalMethods() { initAllMethods(this); } /** * This function will expose all the declared public methods of a class as servlet methods, * except methods that match those declared by GenericServlet or a superclass of GenericServlet. * @param serviceObject The object containing public methods to be exposed by the servlet. */ protected void initAllMethods(Object serviceObject) { Method[] genericServletMethods = GenericServlet.class.getMethods(); Method[] declaredMethods = serviceObject.getClass().getDeclaredMethods(); for (int i = declaredMethods.length - 1; i >= 0; i { Method declaredMethod = declaredMethods[i]; boolean shouldIgnore = false; for (Method genericServletMethod : genericServletMethods) { if (declaredMethod.getName().equals(genericServletMethod.getName()) && Arrays.equals(declaredMethod.getParameterTypes(), genericServletMethod.getParameterTypes()) ) { shouldIgnore = true; break; } } if (!shouldIgnore) initMethod(serviceObject, declaredMethod); } // for debugging printExposedMethods(); } /** * @param serviceObject The instance of an object to use in the servlet. * @param methodName The method to expose on serviceObject. */ synchronized protected void initMethod(Object serviceObject, Method method) { // only expose public methods if (!Modifier.isPublic(method.getModifiers())) return; String methodName = method.getName(); if (methodMap.containsKey(methodName)) { methodMap.put(methodName, null); System.err.println(String.format( "Method %s.%s will not be supported because there are multiple definitions.", this.getClass().getName(), methodName )); } else { String[] paramNames = null; paramNames = paranamer.lookupParameterNames(method, false); // returns null if not found methodMap.put(methodName, new ExposedMethod(serviceObject, method, paramNames)); } } protected void printExposedMethods() { String output = ""; List<String> methodNames = new Vector<String>(methodMap.keySet()); Collections.sort(methodNames); for (String methodName : methodNames) { ExposedMethod m = methodMap.get(methodName); if (m != null) output += String.format( "Exposed servlet method: %s.%s\n", m.instance.getClass().getName(), formatFunctionSignature( m.method.getName(), m.method.getParameterTypes(), m.paramNames ) ); else output += "Not exposed: "+methodName; } System.out.print(output); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } protected class ServletRequestInfo { public ServletRequestInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { this.request = request; this.response = response; this.inputStream = new PeekableInputStream(request.getInputStream()); } HttpServletRequest request; HttpServletResponse response; JsonRpcRequestModel currentJsonRequest; List<JsonRpcResponseModel> jsonResponses = new Vector<JsonRpcResponseModel>(); Number streamParameterIndex = null; PeekableInputStream inputStream; Boolean isBatchRequest = false; } /** * This maps a thread to the corresponding RequestInfo for the doGet() or doPost() call that thread is handling. */ private Map<Thread,ServletRequestInfo> servletRequestInfo = new HashMap<Thread,ServletRequestInfo>(); /** * This function retrieves the HttpServletResponse associated with the current thread's doGet() or doPost() call. * In a public function with a void return type, you can use the ServletOutputStream for full control over the output. */ protected ServletRequestInfo getServletRequestInfo() { synchronized (servletRequestInfo) { return servletRequestInfo.get(Thread.currentThread()); } } private void setServletRequestInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { synchronized (servletRequestInfo) { servletRequestInfo.put(Thread.currentThread(), new ServletRequestInfo(request, response)); } } @SuppressWarnings("unchecked") private void handleServletRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { setServletRequestInfo(request, response); /* if (request.getMethod().equals("GET")) { @SuppressWarnings("unchecked") List<String> urlParamNames = Collections.list(request.getParameterNames()); // Read Method Name from URL String methodName = request.getParameter(METHOD); @SuppressWarnings({ "unchecked", "rawtypes" }) HashMap<String, String> params = new HashMap(); for (String paramName : urlParamNames) params.put(paramName, request.getParameter(paramName)); invokeMethod(methodName, params); }*/ if (request.getMethod().equals("GET")) { List<String> urlParamNames = Collections.list(request.getParameterNames()); HashMap<String, String> params = new HashMap<String,String>(); for (String paramName : urlParamNames) params.put(paramName, request.getParameter(paramName)); JsonRpcRequestModel json = new JsonRpcRequestModel(); json.id = params.containsKey("id") ? params.remove("id") : null; json.method = params.remove(METHOD); json.params = params; getServletRequestInfo().currentJsonRequest = json; invokeMethod(json.method, params); } else // post { try { String methodName; Object methodParams; ServletRequestInfo info = getServletRequestInfo(); if (info.inputStream.peek() == '[' || info.inputStream.peek() == '{') // json { handleArrayOfJsonRequests(info.inputStream,response); } else // AMF3 { ASObject obj = (ASObject)deseriaizeAmf3(info.inputStream); methodName = (String) obj.get(METHOD); methodParams = obj.get(PARAMS); getServletRequestInfo().streamParameterIndex = (Number) obj.get(STREAM_PARAMETER_INDEX); invokeMethod(methodName, methodParams); } } catch (IOException e) { sendError(e, null); } catch (Exception e) { sendError(e, null); } } handleJsonResponses(); } finally { synchronized (servletRequestInfo) { servletRequestInfo.remove(Thread.currentThread()); } } } private void handleArrayOfJsonRequests(PeekableInputStream inputStream,HttpServletResponse response) throws IOException { try { JsonRpcRequestModel[] jsonRequests; String streamString = IOUtils.toString(inputStream, "UTF-8"); ServletRequestInfo info = getServletRequestInfo(); /*If first character is { then it is a single request. We add it to the array jsonRequests and continue*/ if(streamString.charAt(0) == '{') { //TODO:CHeck parse error for this JsonRpcRequestModel req = (new Gson()).fromJson(streamString, JsonRpcRequestModel.class); jsonRequests = new JsonRpcRequestModel[1]; jsonRequests[0] = req; info.isBatchRequest = false; } else { jsonRequests = (new Gson()).fromJson(streamString, JsonRpcRequestModel[].class); info.isBatchRequest = true; } /* we loop through each request, get results or check error and add repsonses to an array*/ for (int i =0; i< jsonRequests.length; i++) { info.currentJsonRequest = jsonRequests[i]; /* Check to see if JSON-RPC protocol is 2.0*/ if(info.currentJsonRequest.jsonrpc == null || !info.currentJsonRequest.jsonrpc.equals("2.0")) { sendError(null,JSON_RPC_PROTOCOL_ERROR_MESSAGE); continue; } /*Check if ID is a number and if so it has not fractional numbers*/ else if(info.currentJsonRequest.id instanceof Number) { Double tempNum = (Double)info.currentJsonRequest.id; if(!(tempNum == Math.ceil(tempNum))) { sendError(null,JSON_RPC_ID_ERROR_MESSAGE); continue; } info.currentJsonRequest.id = tempNum.intValue(); } /*Check if Method exists*/ String methodName = info.currentJsonRequest.method; if (!methodMap.containsKey(methodName)) { sendError(null,JSON_RPC_METHOD_ERROR_MESSAGE); continue; } invokeMethod(methodName, info.currentJsonRequest.params); } } catch (IOException e) { // TODO: handle IOException } catch (JsonParseException e) { sendError(e, JSON_RPC_PARSE_ERROR_MESSAGE); } } private void handleJsonResponses() { ServletRequestInfo info = getServletRequestInfo(); if(info.currentJsonRequest == null) return; info.response.setContentType("application/json"); info.response.setCharacterEncoding("UTF-8"); String result; try { if (info.jsonResponses.size() == 0) { ServletOutputStream out = info.response.getOutputStream(); out.close(); out.flush(); return; } if(!info.isBatchRequest) { result = (new Gson()).toJson(info.jsonResponses.get(0)); } else { result = (new Gson()).toJson(info.jsonResponses); } PrintWriter writer = info.response.getWriter(); writer.print(result); writer.close(); writer.flush(); }catch (Exception e) { e.printStackTrace(); } } private static String JSON_RPC_PROTOCOL_ERROR_MESSAGE = "JSON-RPC protocol must be 2.0"; private static String JSON_RPC_ID_ERROR_MESSAGE = "ID cannot contain fractional parts"; private static String JSON_RPC_METHOD_ERROR_MESSAGE = "The method does not exist or is not available."; private static String JSON_RPC_PARSE_ERROR_MESSAGE = "Parse Error"; private void handleJsonError(JsonRpcRequestModel request,String errorMessage, Throwable e) { JsonRpcResponseModel result = null; Object id = request.id; /* If ID is empty then it is a notification, we send nothing back */ if (id != null) { result = new JsonRpcResponseModel(); result.id = id; result.jsonrpc = "2.0"; JsonRpcErrorModel jsonErrorObject = new JsonRpcErrorModel(); if(errorMessage.equals(JSON_RPC_PROTOCOL_ERROR_MESSAGE)) { jsonErrorObject.code = "-32600"; jsonErrorObject.message = "Invalid Request"; jsonErrorObject.data = JSON_RPC_PROTOCOL_ERROR_MESSAGE; } else if(errorMessage.equals(JSON_RPC_ID_ERROR_MESSAGE)) { jsonErrorObject.code = "-32600"; jsonErrorObject.message = "Invalid Request"; jsonErrorObject.data = JSON_RPC_ID_ERROR_MESSAGE ; } else if(errorMessage.equals(JSON_RPC_METHOD_ERROR_MESSAGE)) { jsonErrorObject.code = "-32601"; jsonErrorObject.message = "Method not found"; jsonErrorObject.data = JSON_RPC_METHOD_ERROR_MESSAGE ; } else if(errorMessage.equals(JSON_RPC_PARSE_ERROR_MESSAGE)) { jsonErrorObject.code = "-32700"; jsonErrorObject.message = "Parse error"; jsonErrorObject.data = "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."; } else { jsonErrorObject.code = "-32000"; jsonErrorObject.message = "Server error"; jsonErrorObject.data = errorMessage; } if(e !=null) { jsonErrorObject.data = (String)jsonErrorObject.data + "\n" + e.getMessage(); } result.error = jsonErrorObject; getServletRequestInfo().jsonResponses.add(result); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private Object[] getParamsFromMap(String methodName, Map params) { ExposedMethod exposedMethod = methodMap.get(methodName); String[] argNames = exposedMethod.paramNames; Class[] argTypes = exposedMethod.method.getParameterTypes(); Object[] argValues = new Object[argTypes.length]; Map extraParameters = null; // parameters that weren't mapped directly to method arguments // For each method parameter, get the corresponding url parameter value. if (argNames != null && params != null) { //TODO: check why params is null for (Object parameterName : params.keySet()) { Object parameterValue = params.get(parameterName); int index = ListUtils.findString((String)parameterName, argNames); if (index >= 0) { argValues[index] = parameterValue; } else if (!parameterName.equals(METHOD)) { if (extraParameters == null) extraParameters = new HashMap(); extraParameters.put(parameterName, parameterValue); } } } // support for a function having a single Map<String,String> parameter // see if we can find a Map arg. If so, set it to extraParameters if (argTypes != null) { for (int i = 0; i < argTypes.length; i++) { if (argTypes[i] == Map.class) { // avoid passing a null Map to the function if (extraParameters == null) extraParameters = new HashMap<String,String>(); argValues[i] = extraParameters; extraParameters = null; break; } } } if (extraParameters != null) { System.out.println("Received servlet request: " + methodName + Arrays.deepToString(argValues)); System.out.println("Unused parameters: "+extraParameters.entrySet()); } return argValues; } /** * @param methodName The name of the function to invoke. * @param methodParameters A list of input parameters for the method. Values will be cast to the appropriate types if necessary. */ /** * @param methodName * @param methodParams * @throws IOException */ @SuppressWarnings("rawtypes") private void invokeMethod(String methodName, Object methodParams) throws IOException { ServletRequestInfo info = getServletRequestInfo(); if(!methodMap.containsKey(methodName) || methodMap.get(methodName) == null) { sendError(new IllegalArgumentException(String.format("Method \"%s\" not supported.", methodName)),null); return; } if (methodParams instanceof List<?>) methodParams = ((List<?>)methodParams).toArray(); if(methodParams instanceof Map) { methodParams = getParamsFromMap(methodName, (Map)methodParams); } if (info.streamParameterIndex != null) { int index = info.streamParameterIndex.intValue(); if (index >= 0) ((Object[])methodParams)[index] = info.inputStream; } Object[] params = (Object[])methodParams; // get method by name ExposedMethod exposedMethod = methodMap.get(methodName); if (exposedMethod == null) { sendError(new IllegalArgumentException("Unknown method: "+methodName),null); return; } // cast input values to appropriate types if necessary Class[] expectedArgTypes = exposedMethod.method.getParameterTypes(); if (expectedArgTypes.length == params.length) { for (int index = 0; index < params.length; index++) { params[index] = cast(params[index], expectedArgTypes[index]); } } // prepare to output the result of the method call long startTime = System.currentTimeMillis(); // Invoke the method on the object with the arguments try { Object result = exposedMethod.method.invoke(exposedMethod.instance, params); if(info.currentJsonRequest ==null) { if (exposedMethod.method.getReturnType() != void.class) { ServletOutputStream servletOutputStream = getServletRequestInfo().response.getOutputStream(); seriaizeCompressedAmf3(result, servletOutputStream); } } else { Object id = info.currentJsonRequest.id; /* If ID is empty then it is a notification, we send nothing back */ if (id != null) { Gson gson = new Gson(); JsonRpcResponseModel responseObj = new JsonRpcResponseModel(); responseObj.jsonrpc = "2.0"; responseObj.result = result; responseObj.id = id; info.jsonResponses.add(responseObj); } } } catch (InvocationTargetException e) { System.err.println(methodName + Arrays.deepToString(params)); sendError(e,null); } catch (IllegalArgumentException e) { String moreInfo = "Expected: " + formatFunctionSignature(methodName, expectedArgTypes, exposedMethod.paramNames) + "\n" + "Received: " + formatFunctionSignature(methodName, params, null); sendError(e, moreInfo); } catch (Exception e) { System.err.println(methodName + Arrays.deepToString(params)); sendError(e, null); } long endTime = System.currentTimeMillis(); // debug if (endTime - startTime >= debugThreshold) System.out.println(String.format("[%sms] %s", endTime - startTime, methodName + Arrays.deepToString(params))); } @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object cast(Object value, Class<?> type) { // if given value is a String, check if the function is expecting a different type if (value instanceof String) { try { if (type == int.class || type == Integer.class) { value = Integer.parseInt((String)value); } else if (type == float.class || type == Float.class) { value = Float.parseFloat((String)value); } else if (type == double.class || type == Double.class) { value = Double.parseDouble((String)value); } else if (type == boolean.class || type == Boolean.class) { value = ((String)(value)).equalsIgnoreCase("true"); } else if (type == String[].class || type == List.class) { String[][] table = CSVParser.defaultParser.parseCSV((String)value, true); if (table.length == 0) value = new String[0]; // empty else value = table[0]; // first row if (type == List.class) value = Arrays.asList((String[])value); } else if(type == InputStream.class) { try { String temp = (String) value; value = (InputStream)new ByteArrayInputStream(temp.getBytes("UTF-8")); }catch (Exception e) { return null; } } } catch (NumberFormatException e) { // if number parsing fails, leave the original value untouched } } else if (value == null) { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; } else if (value instanceof Boolean && type == boolean.class) { value = (boolean)(Boolean)value; } else if(value.getClass() == ArrayList.class) { value = cast(((ArrayList)value).toArray(), type); } else if (value.getClass() == Object[].class) { Object[] valueArray = (Object[])value; if (type == List.class) { value = ListUtils.copyArrayToList(valueArray, new Vector()); } else if (type == Object[][].class) { Object[][] valueMatrix = new Object[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { valueMatrix[i] = (Object[])valueArray[i]; } value = valueMatrix; } else if (type == String[][].class) { String[][] valueMatrix = new String[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { // cast Objects to Strings Object[] objectArray = (Object[])valueArray[i]; valueMatrix[i] = ListUtils.copyStringArray(objectArray, new String[objectArray.length]); } value = valueMatrix; } else if (type == String[].class) { value = ListUtils.copyStringArray(valueArray, new String[valueArray.length]); } else if (type == double[][].class) { double[][] valueMatrix = new double[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { // cast Objects to doubles Object[] objectArray = (Object[])valueArray[i]; valueMatrix[i] = ListUtils.copyDoubleArray(objectArray, new double[objectArray.length]); } value = valueMatrix; } else if (type == double[].class) { value = ListUtils.copyDoubleArray(valueArray, new double[valueArray.length]); } else if (type == int[][].class) { int[][] valueMatrix = new int[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { // cast Objects to doubles Object[] objectArray = (Object[])valueArray[i]; valueMatrix[i] = ListUtils.copyIntegerArray(objectArray, new int[objectArray.length]); } value = valueMatrix; } else if (type == int[].class) { value = ListUtils.copyIntegerArray(valueArray, new int[valueArray.length]); } } else if ((type == int.class || type == Integer.class) && value instanceof Number) { value = ((Number)value).intValue(); } else if ((type == Double.class || type == double.class) && value instanceof Number) { value = ((Number)value).doubleValue(); } else if ((type == float.class || type== Float.class) && value instanceof Number) { value = ((Number)value).floatValue(); } return value; } /** * This function formats a Java function signature as a String. * @param methodName The name of the method. * @param paramValuesOrTypes A list of Class objects or arbitrary Objects to get the class names from. * @param paramNames The names of the parameters, may be null. * @return A readable Java function signature. */ private String formatFunctionSignature(String methodName, Object[] paramValuesOrTypes, String[] paramNames) { // don't use paramNames if the length doesn't match the paramValuesOrTypes length. if (paramNames != null && paramNames.length != paramValuesOrTypes.length) paramNames = null; List<String> names = new Vector<String>(paramValuesOrTypes.length); for (int i = 0; i < paramValuesOrTypes.length; i++) { Object valueOrType = paramValuesOrTypes[i]; String name = "null"; if (valueOrType instanceof Class) name = ((Class<?>)valueOrType).getName(); else if (valueOrType != null) name = valueOrType.getClass().getName(); // decode output of Class.getName() while (name.charAt(0) == '[') // array type { name = name.substring(1) + "[]"; // decode element type encoding String type = ""; switch (name.charAt(0)) { case 'Z': type = "boolean"; break; case 'B': type = "byte"; break; case 'C': type = "char"; break; case 'D': type = "double"; break; case 'F': type = "float"; break; case 'I': type = "int"; break; case 'J': type = "long"; break; case 'S': type = "short"; break; case 'L': // remove ';' name = name.replace(";", ""); break; default: continue; } // remove first char encoding name = type + name.substring(1); } // hide package names if (name.indexOf('.') >= 0) name = name.substring(name.lastIndexOf('.') + 1); if (paramNames != null) name += " " + paramNames[i]; names.add(name); } String result = names.toString(); return String.format("%s(%s)", methodName, result.substring(1, result.length() - 1)); } private void sendError(Throwable exception, String moreInfo) throws IOException { JsonRpcRequestModel jsonRequest = getServletRequestInfo().currentJsonRequest; if(jsonRequest == null) { String message; if (exception instanceof RuntimeException) message = exception.toString(); else if(exception instanceof InvocationTargetException) { message = exception.getCause().getMessage(); } else message = exception.getMessage(); if (moreInfo != null) message += "\n" + moreInfo; // log errors exception.printStackTrace(); System.err.println("Serializing ErrorMessage: "+message); ServletOutputStream servletOutputStream = getServletRequestInfo().response.getOutputStream(); ErrorMessage errorMessage = new ErrorMessage(new MessageException(message)); errorMessage.faultCode = exception.getClass().getSimpleName(); seriaizeCompressedAmf3(errorMessage, servletOutputStream); } else { handleJsonError(jsonRequest, moreInfo, exception); } } protected static SerializationContext getSerializationContext() { SerializationContext context = SerializationContext.getSerializationContext(); // set serialization context properties context.enableSmallMessages = true; context.instantiateTypes = true; context.supportRemoteClass = true; context.legacyCollection = false; context.legacyMap = false; context.legacyXMLDocument = false; context.legacyXMLNamespaces = false; context.legacyThrowable = false; context.legacyBigNumbers = false; context.restoreReferences = false; context.logPropertyErrors = false; context.ignorePropertyErrors = true; return context; } // Serialize a Java Object to AMF3 ByteArray protected void seriaizeCompressedAmf3(Object objToSerialize, ServletOutputStream servletOutputStream) { try { SerializationContext context = getSerializationContext(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(servletOutputStream); Amf3Output amf3Output = new Amf3Output(context); amf3Output.setOutputStream(deflaterOutputStream); // compress amf3Output.writeObject(objToSerialize); amf3Output.flush(); deflaterOutputStream.close(); // this is necessary to finish the compression } catch (Exception e) { e.printStackTrace(); } } // De-serialize a ByteArray/AMF3/Flex object to a Java object protected ASObject deseriaizeAmf3(InputStream inputStream) throws ClassNotFoundException, IOException { ASObject deSerializedObj = null; SerializationContext context = getSerializationContext(); Amf3Input amf3Input = new Amf3Input(context); amf3Input.setInputStream(inputStream); // uncompress deSerializedObj = (ASObject) amf3Input.readObject(); //amf3Input.close(); return deSerializedObj; } }