answer
stringlengths 17
10.2M
|
|---|
package nuclibook.server;
import nuclibook.constants.C;
import nuclibook.constants.RequestType;
import nuclibook.entity_utils.SecurityUtils;
import nuclibook.models.Staff;
import nuclibook.routes.*;
import org.apache.commons.configuration.ConfigurationException;
import spark.Session;
import spark.Spark;
import java.awt.*;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* This class creates and manages the server for the entire system.
* Its main jobs are to set up the server, route pages, and handle top-level security.
*/
public class LocalServer {
/**
* Create the server and perform initial configuration.
* @param args Any command line arguments; ignored in this application.
*/
public static void main(String... args) {
/*
SERVER SETTINGS
*/
//initialise constants
try {
C.initConstants();
} catch (ConfigurationException e) {
e.printStackTrace();
}
// static files folder
Spark.staticFileLocation("/static");
// page security
Spark.before((request, response) -> {
// get path
String path = request.pathInfo();
// get current session and user
Session session = request.session();
if (request.queryParams("token") != null) {
session = SecurityUtils.checkOneOffSession(request.queryParams("token"));
}
Staff user = SecurityUtils.getCurrentUser(session);
// require all POST requests to be authenticated with a CSRF token
if (request.requestMethod().toLowerCase().equals("post") && !SecurityUtils.checkCsrfToken(session, request.queryParams("csrf-token"))) {
Spark.halt(403, "Security token invalid.");
}
// check if they are accessing non-page
if (path.startsWith("/css")
|| path.startsWith("/images")
|| path.startsWith("/js")
|| path.startsWith("/font-awesome")) {
// nothing more to do - everything is fine
return;
}
// check for a password force-change
if (SecurityUtils.checkLoggedIn(session)
&& user != null
&& user.getDaysRemainingToPasswordChange() < 1
&& !path.startsWith("/profile")
&& !(path.equals("/entity-update") && request.queryParams("entity-type").equals("staff-password-change"))) {
response.redirect("/profile?changepw=1&force=1");
Spark.halt("Redirecting.");
}
// check if they are accessing a non-secure page
if (path.startsWith("/login")) {
// nothing more to do - everything is fine
return;
}
// not authenticated?
if (!SecurityUtils.checkLoggedIn(session)) {
// send them back to the login page
response.redirect("/login");
Spark.halt("Redirecting.");
}
// CSV page
if (path.endsWith(".goto-csv")) {
if (Desktop.isDesktopSupported()) {
// generate token
SecureRandom random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
SecurityUtils.setOneOffToken(token, session);
// redirect
String toOpen = "http://localhost:4567" + path.replace("goto-csv", "csv") + "?token=" + token;
Spark.halt("<!--OPEN:" + toOpen + "-->Your file will download now. Please wait...<script type=\"text/javascript\">window.history.back();</script>");
}
}
});
// prevent viewing pages after logout
Spark.after((request, response) -> {
// get path
String path = request.pathInfo();
// don't apply this for resources
if (path.startsWith("/css")
|| path.startsWith("/images")
|| path.startsWith("/js")
|| path.startsWith("/font-awesome")) {
// nothing more to do - everything is fine
return;
}
response.header("Cache-Control", "no-cache, no-store, must-revalidate");
response.header("Pragma", "no-cache");
response.header("Expires", "0");
});
/*
ROUTES
*/
// basic pages
Spark.get("/", new DashboardRoute());
// day summary
Spark.get("/day-summary", new DaySummaryRoute());
// security
Spark.get("/access-denied", new AccessDeniedRoute());
Spark.get("/login", new LoginRoute(RequestType.GET));
Spark.post("/login", new LoginRoute(RequestType.POST));
Spark.get("/logout", new LogoutRoute());
Spark.get("/profile", new ProfileRoute());
Spark.get("/renew-session", new RenewSessionRoute());
// action logs
Spark.get("/action-log", new ActionLogRoute());
// entity CRUD action routes
Spark.post("/entity-update", new CrudCreateUpdateRoute());
Spark.post("/entity-delete", new CrudDeleteRoute());
// basic CRUD pages
Spark.get("/cameras", new CamerasRoute());
Spark.get("/camera-types", new CameraTypesRoute());
Spark.get("/patients", new PatientsRoute());
Spark.get("/staff", new StaffRoute());
Spark.get("/staff-roles", new StaffRolesRoute());
Spark.get("/therapies", new TherapiesRoute());
Spark.get("/tracers", new TracersRoute());
Spark.get("/generic-events", new GenericEventsRoute());
// staff absences and availabilities
Spark.get("/select-staff/:target:", new SelectStaffRoute());
Spark.get("/staff-absences/:staffid:", new StaffAbsencesRoute());
Spark.get("/staff-availabilities/:staffid:", new StaffAvailabilitiesRoute());
// bookings
Spark.get("/new-booking-1", new NewBookingRouteStage1());
Spark.post("/new-booking-2", new NewBookingRouteStage2());
Spark.post("/new-booking-3", new NewBookingRouteStage3());
Spark.get("/bookings", new BookingsRoute());
Spark.post("/booking-edit", new BookingEditRoute());
Spark.post("/booking-details/:bookingid:", new BookingDetailsRoute());
Spark.get("/booking-details/:bookingid:", new BookingDetailsRoute());
Spark.get("/booking-details/:bookingid:/:newstatus:", new BookingDetailsRoute());
// AJAX routes
Spark.get("/ajax/calendar-data", new AjaxCalendarDataRoute());
Spark.get("/ajax/patient-data/0", new AjaxPatientDataRoute(0));
Spark.get("/ajax/patient-data/1", new AjaxPatientDataRoute(1));
Spark.get("/ajax/action-log-data", new AjaxActionLogDataRoute());
// tracer orders
Spark.get("/tracer-orders", new TracerOrdersRoute());
Spark.get("/tracer-order-details/:tracerorderid:", new TracerOrderDetailsRoute());
Spark.get("/tracer-order-details/:tracerorderid:/:newstatus:", new TracerOrderDetailsRoute());
// patients
Spark.get("/patient-details/:patientid:", new PatientDetailsRoute());
// export
Spark.get("/export/:file:", new ExportRoute());
// import
Spark.post("/import", new ImportRoute());
}
/**
* This will stop the server and effectively kill the application in the event of a fatal error
* @param message The message to be delivered to the user
*/
public static void fatalError(String message) {
Spark.halt(500, "<html>" +
"<head>" +
"</head>" +
"<body>" +
"<p>A fatal error occurred: <em>" + message + "</em>.</p>" +
"<p>Please restart the server and try again.</p>" +
"</body>" +
"</html>");
Spark.stop();
}
}
|
package net.minecraftforge.client.model.obj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.client.model.IModelCustom;
import net.minecraftforge.client.model.ModelFormatException;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class WavefrontObject implements IModelCustom
{
private static Pattern vertexPattern = Pattern.compile("(v( (\\-){0,1}\\d+\\.\\d+){3,4} *\\n)|(v( (\\-){0,1}\\d+\\.\\d+){3,4} *$)");
private static Pattern vertexNormalPattern = Pattern.compile("(vn( (\\-){0,1}\\d+\\.\\d+){3,4} *\\n)|(vn( (\\-){0,1}\\d+\\.\\d+){3,4} *$)");
private static Pattern textureCoordinatePattern = Pattern.compile("(vt( (\\-){0,1}\\d+\\.\\d+){2,3} *\\n)|(vt( (\\-){0,1}\\d+\\.\\d+){2,3} *$)");
private static Pattern face_V_VT_VN_Pattern = Pattern.compile("(f( \\d+/\\d+/\\d+){3,4} *\\n)|(f( \\d+/\\d+/\\d+){3,4} *$)");
private static Pattern face_V_VT_Pattern = Pattern.compile("(f( \\d+/\\d+){3,4} *\\n)|(f( \\d+/\\d+){3,4} *$)");
private static Pattern face_V_VN_Pattern = Pattern.compile("(f( \\d+//\\d+){3,4} *\\n)|(f( \\d+//\\d+){3,4} *$)");
private static Pattern face_V_Pattern = Pattern.compile("(f( \\d+){3,4} *\\n)|(f( \\d+){3,4} *$)");
private static Pattern groupObjectPattern = Pattern.compile("([go]( [\\w\\d]+) *\\n)|([go]( [\\w\\d]+) *$)");
private static Matcher vertexMatcher, vertexNormalMatcher, textureCoordinateMatcher;
private static Matcher face_V_VT_VN_Matcher, face_V_VT_Matcher, face_V_VN_Matcher, face_V_Matcher;
private static Matcher groupObjectMatcher;
public ArrayList<Vertex> vertices = new ArrayList<Vertex>();
public ArrayList<Vertex> vertexNormals = new ArrayList<Vertex>();
public ArrayList<TextureCoordinate> textureCoordinates = new ArrayList<TextureCoordinate>();
public ArrayList<GroupObject> groupObjects = new ArrayList<GroupObject>();
private GroupObject currentGroupObject;
private String fileName;
public WavefrontObject(String fileName, URL resource) throws ModelFormatException
{
this.fileName = fileName;
try
{
loadObjModel(resource.openStream());
}
catch (IOException e)
{
throw new ModelFormatException("IO Exception reading model format", e);
}
}
public WavefrontObject(String filename, InputStream inputStream) throws ModelFormatException
{
this.fileName = filename;
loadObjModel(inputStream);
}
private void loadObjModel(InputStream inputStream) throws ModelFormatException
{
BufferedReader reader = null;
String currentLine = null;
int lineCount = 0;
try
{
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((currentLine = reader.readLine()) != null)
{
lineCount++;
currentLine = currentLine.replaceAll("\\s+", " ").trim();
if (currentLine.startsWith("#") || currentLine.length() == 0)
{
continue;
}
else if (currentLine.startsWith("v "))
{
Vertex vertex = parseVertex(currentLine, lineCount);
if (vertex != null)
{
vertices.add(vertex);
}
}
else if (currentLine.startsWith("vn "))
{
Vertex vertex = parseVertexNormal(currentLine, lineCount);
if (vertex != null)
{
vertexNormals.add(vertex);
}
}
else if (currentLine.startsWith("vt "))
{
TextureCoordinate textureCoordinate = parseTextureCoordinate(currentLine, lineCount);
if (textureCoordinate != null)
{
textureCoordinates.add(textureCoordinate);
}
}
else if (currentLine.startsWith("f "))
{
if (currentGroupObject == null)
{
currentGroupObject = new GroupObject("Default");
}
Face face = parseFace(currentLine, lineCount);
if (face != null)
{
currentGroupObject.faces.add(face);
}
}
else if (currentLine.startsWith("g ") | currentLine.startsWith("o "))
{
GroupObject group = parseGroupObject(currentLine, lineCount);
if (group != null)
{
if (currentGroupObject != null)
{
groupObjects.add(currentGroupObject);
}
}
currentGroupObject = group;
}
}
groupObjects.add(currentGroupObject);
}
catch (IOException e)
{
throw new ModelFormatException("IO Exception reading model format", e);
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
// hush
}
try
{
inputStream.close();
}
catch (IOException e)
{
// hush
}
}
}
public void renderAll()
{
Tessellator tessellator = Tessellator.instance;
if (currentGroupObject != null)
{
tessellator.startDrawing(currentGroupObject.glDrawingMode);
}
else
{
tessellator.startDrawing(GL11.GL_TRIANGLES);
}
for (GroupObject groupObject : groupObjects)
{
groupObject.render(tessellator);
}
tessellator.draw();
}
public void renderOnly(String... groupNames)
{
for (GroupObject groupObject : groupObjects)
{
for (String groupName : groupNames)
{
if (groupName.equalsIgnoreCase(groupObject.name))
{
groupObject.render();
}
}
}
}
public void renderPart(String partName)
{
for (GroupObject groupObject : groupObjects)
{
if (partName.equalsIgnoreCase(groupObject.name))
{
groupObject.render();
}
}
}
public void renderAllExcept(String... excludedGroupNames)
{
for (GroupObject groupObject : groupObjects)
{
for (String excludedGroupName : excludedGroupNames)
{
if (!excludedGroupName.equalsIgnoreCase(groupObject.name))
{
groupObject.render();
}
}
}
}
private Vertex parseVertex(String line, int lineCount) throws ModelFormatException
{
Vertex vertex = null;
if (isValidVertexLine(line))
{
line = line.substring(line.indexOf(" ") + 1);
String[] tokens = line.split(" ");
try
{
if (tokens.length == 2)
{
return new Vertex(Float.parseFloat(tokens[0]), Float.parseFloat(tokens[1]));
}
else if (tokens.length == 3)
{
return new Vertex(Float.parseFloat(tokens[0]), Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]));
}
}
catch (NumberFormatException e)
{
throw new ModelFormatException(String.format("Number formatting error at line %d",lineCount), e);
}
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
return vertex;
}
private Vertex parseVertexNormal(String line, int lineCount) throws ModelFormatException
{
Vertex vertexNormal = null;
if (isValidVertexNormalLine(line))
{
line = line.substring(line.indexOf(" ") + 1);
String[] tokens = line.split(" ");
try
{
if (tokens.length == 3)
return new Vertex(Float.parseFloat(tokens[0]), Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]));
}
catch (NumberFormatException e)
{
throw new ModelFormatException(String.format("Number formatting error at line %d",lineCount), e);
}
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
return vertexNormal;
}
private TextureCoordinate parseTextureCoordinate(String line, int lineCount) throws ModelFormatException
{
TextureCoordinate textureCoordinate = null;
if (isValidTextureCoordinateLine(line))
{
line = line.substring(line.indexOf(" ") + 1);
String[] tokens = line.split(" ");
try
{
if (tokens.length == 2)
return new TextureCoordinate(Float.parseFloat(tokens[0]), 1 - Float.parseFloat(tokens[1]));
else if (tokens.length == 3)
return new TextureCoordinate(Float.parseFloat(tokens[0]), 1 - Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]));
}
catch (NumberFormatException e)
{
throw new ModelFormatException(String.format("Number formatting error at line %d",lineCount), e);
}
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
return textureCoordinate;
}
private Face parseFace(String line, int lineCount) throws ModelFormatException
{
Face face = null;
if (isValidFaceLine(line))
{
face = new Face();
String trimmedLine = line.substring(line.indexOf(" ") + 1);
String[] tokens = trimmedLine.split(" ");
String[] subTokens = null;
if (tokens.length == 3)
{
if (currentGroupObject.glDrawingMode == -1)
{
currentGroupObject.glDrawingMode = GL11.GL_TRIANGLES;
}
else if (currentGroupObject.glDrawingMode != GL11.GL_TRIANGLES)
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Invalid number of points for face (expected 4, found " + tokens.length + ")");
}
}
else if (tokens.length == 4)
{
if (currentGroupObject.glDrawingMode == -1)
{
currentGroupObject.glDrawingMode = GL11.GL_QUADS;
}
else if (currentGroupObject.glDrawingMode != GL11.GL_QUADS)
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Invalid number of points for face (expected 3, found " + tokens.length + ")");
}
}
// f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ...
if (isValidFace_V_VT_VN_Line(line))
{
face.vertices = new Vertex[tokens.length];
face.textureCoordinates = new TextureCoordinate[tokens.length];
face.vertexNormals = new Vertex[tokens.length];
for (int i = 0; i < tokens.length; ++i)
{
subTokens = tokens[i].split("/");
face.vertices[i] = vertices.get(Integer.parseInt(subTokens[0]) - 1);
face.textureCoordinates[i] = textureCoordinates.get(Integer.parseInt(subTokens[1]) - 1);
face.vertexNormals[i] = vertexNormals.get(Integer.parseInt(subTokens[2]) - 1);
}
face.faceNormal = face.calculateFaceNormal();
}
// f v1/vt1 v2/vt2 v3/vt3 ...
else if (isValidFace_V_VT_Line(line))
{
face.vertices = new Vertex[tokens.length];
face.textureCoordinates = new TextureCoordinate[tokens.length];
for (int i = 0; i < tokens.length; ++i)
{
subTokens = tokens[i].split("/");
face.vertices[i] = vertices.get(Integer.parseInt(subTokens[0]) - 1);
face.textureCoordinates[i] = textureCoordinates.get(Integer.parseInt(subTokens[1]) - 1);
}
face.faceNormal = face.calculateFaceNormal();
}
// f v1//vn1 v2//vn2 v3//vn3 ...
else if (isValidFace_V_VN_Line(line))
{
face.vertices = new Vertex[tokens.length];
face.vertexNormals = new Vertex[tokens.length];
for (int i = 0; i < tokens.length; ++i)
{
subTokens = tokens[i].split("
face.vertices[i] = vertices.get(Integer.parseInt(subTokens[0]) - 1);
face.vertexNormals[i] = vertexNormals.get(Integer.parseInt(subTokens[1]) - 1);
}
face.faceNormal = face.calculateFaceNormal();
}
// f v1 v2 v3 ...
else if (isValidFace_V_Line(line))
{
face.vertices = new Vertex[tokens.length];
for (int i = 0; i < tokens.length; ++i)
{
face.vertices[i] = vertices.get(Integer.parseInt(tokens[i]) - 1);
}
face.faceNormal = face.calculateFaceNormal();
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
return face;
}
private GroupObject parseGroupObject(String line, int lineCount) throws ModelFormatException
{
GroupObject group = null;
if (isValidGroupObjectLine(line))
{
String trimmedLine = line.substring(line.indexOf(" ") + 1);
if (trimmedLine.length() > 0)
{
group = new GroupObject(trimmedLine);
}
}
else
{
throw new ModelFormatException("Error parsing entry ('" + line + "'" + ", line " + lineCount + ") in file '" + fileName + "' - Incorrect format");
}
return group;
}
/***
* Verifies that the given line from the model file is a valid vertex
* @param line the line being validated
* @return true if the line is a valid vertex, false otherwise
*/
private static boolean isValidVertexLine(String line)
{
if (vertexMatcher != null)
{
vertexMatcher.reset();
}
vertexMatcher = vertexPattern.matcher(line);
return vertexMatcher.matches();
}
/***
* Verifies that the given line from the model file is a valid vertex normal
* @param line the line being validated
* @return true if the line is a valid vertex normal, false otherwise
*/
private static boolean isValidVertexNormalLine(String line)
{
if (vertexNormalMatcher != null)
{
vertexNormalMatcher.reset();
}
vertexNormalMatcher = vertexNormalPattern.matcher(line);
return vertexNormalMatcher.matches();
}
/***
* Verifies that the given line from the model file is a valid texture coordinate
* @param line the line being validated
* @return true if the line is a valid texture coordinate, false otherwise
*/
private static boolean isValidTextureCoordinateLine(String line)
{
if (textureCoordinateMatcher != null)
{
textureCoordinateMatcher.reset();
}
textureCoordinateMatcher = textureCoordinatePattern.matcher(line);
return textureCoordinateMatcher.matches();
}
/***
* Verifies that the given line from the model file is a valid face that is described by vertices, texture coordinates, and vertex normals
* @param line the line being validated
* @return true if the line is a valid face that matches the format "f v1/vt1/vn1 ..." (with a minimum of 3 points in the face, and a maximum of 4), false otherwise
*/
private static boolean isValidFace_V_VT_VN_Line(String line)
{
if (face_V_VT_VN_Matcher != null)
{
face_V_VT_VN_Matcher.reset();
}
face_V_VT_VN_Matcher = face_V_VT_VN_Pattern.matcher(line);
return face_V_VT_VN_Matcher.matches();
}
/***
* Verifies that the given line from the model file is a valid face that is described by vertices and texture coordinates
* @param line the line being validated
* @return true if the line is a valid face that matches the format "f v1/vt1 ..." (with a minimum of 3 points in the face, and a maximum of 4), false otherwise
*/
private static boolean isValidFace_V_VT_Line(String line)
{
if (face_V_VT_Matcher != null)
{
face_V_VT_Matcher.reset();
}
face_V_VT_Matcher = face_V_VT_Pattern.matcher(line);
return face_V_VT_Matcher.matches();
}
/***
* Verifies that the given line from the model file is a valid face that is described by vertices and vertex normals
* @param line the line being validated
* @return true if the line is a valid face that matches the format "f v1//vn1 ..." (with a minimum of 3 points in the face, and a maximum of 4), false otherwise
*/
private static boolean isValidFace_V_VN_Line(String line)
{
if (face_V_VN_Matcher != null)
{
face_V_VN_Matcher.reset();
}
face_V_VN_Matcher = face_V_VN_Pattern.matcher(line);
return face_V_VN_Matcher.matches();
}
/***
* Verifies that the given line from the model file is a valid face that is described by only vertices
* @param line the line being validated
* @return true if the line is a valid face that matches the format "f v1 ..." (with a minimum of 3 points in the face, and a maximum of 4), false otherwise
*/
private static boolean isValidFace_V_Line(String line)
{
if (face_V_Matcher != null)
{
face_V_Matcher.reset();
}
face_V_Matcher = face_V_Pattern.matcher(line);
return face_V_Matcher.matches();
}
/***
* Verifies that the given line from the model file is a valid face of any of the possible face formats
* @param line the line being validated
* @return true if the line is a valid face that matches any of the valid face formats, false otherwise
*/
private static boolean isValidFaceLine(String line)
{
return isValidFace_V_VT_VN_Line(line) || isValidFace_V_VT_Line(line) || isValidFace_V_VN_Line(line) || isValidFace_V_Line(line);
}
/***
* Verifies that the given line from the model file is a valid group (or object)
* @param line the line being validated
* @return true if the line is a valid group (or object), false otherwise
*/
private static boolean isValidGroupObjectLine(String line)
{
if (groupObjectMatcher != null)
{
groupObjectMatcher.reset();
}
groupObjectMatcher = groupObjectPattern.matcher(line);
return groupObjectMatcher.matches();
}
@Override
public String getType()
{
return "obj";
}
}
|
package com.sdoward.rxgooglemaps;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import com.sdoward.rxgooglemap.MapObservableProvider;
import rx.functions.Action1;
import rx.subscriptions.*;
public class MapsActivity extends FragmentActivity {
private SupportMapFragment mapFragment;
private MapObservableProvider mapObservableProvider;
private CompositeSubscription subscriptions = Subscriptions.from();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapObservableProvider = new MapObservableProvider(mapFragment);
subscriptions.add(mapObservableProvider.getMapReadyObservable()
.subscribe(new Action1<GoogleMap>() {
@Override
public void call(GoogleMap googleMap) {
Log.d(MapsActivity.class.getName(), "map ready");
}
}));
subscriptions.add(mapObservableProvider.getMapLongClickObservable()
.subscribe(new Action1<LatLng>() {
@Override
public void call(LatLng latLng) {
Log.d(MapsActivity.class.getName(), "map long click");
}
}));
subscriptions.add(mapObservableProvider.getMapClickObservable()
.subscribe(new Action1<LatLng>() {
@Override
public void call(LatLng latLng) {
Log.d(MapsActivity.class.getName(), "map click");
}
}));
subscriptions.add(mapObservableProvider.getCameraChangeObservable().subscribe(new Action1<CameraPosition>() {
@Override
public void call(CameraPosition cameraPosition) {
Log.d(MapsActivity.class.getName(), "camera position changed");
}
}));
}
@Override
protected void onDestroy() {
super.onDestroy();
subscriptions.unsubscribe();
}
}
|
package org.jetel.connection;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.Defaults;
import org.jetel.database.IConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.graph.GraphElement;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ComponentXMLAttributes;
import org.jetel.util.Enigma;
import org.jetel.util.PropertyRefResolver;
import org.jetel.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class DBConnection extends GraphElement implements IConnection {
private static Log logger = LogFactory.getLog(DBConnection.class);
Driver dbDriver;
Connection dbConnection;
Properties config;
boolean threadSafeConnections;
boolean isPasswordEncrypted;
private Map openedConnections;
public final static String JDBC_DRIVER_LIBRARY_NAME = "driverLibrary";
public final static String TRANSACTION_ISOLATION_PROPERTY_NAME="transactionIsolation";
public static final String XML_DBURL_ATTRIBUTE = "dbURL";
public static final String XML_DBDRIVER_ATTRIBUTE = "dbDriver";
public static final String XML_DBCONFIG_ATTRIBUTE = "dbConfig";
public static final String XML_PASSWORD_ATTRIBUTE = "password";
public static final String XML_USER_ATTRIBUTE = "user";
public static final String XML_THREAD_SAFE_CONNECTIONS="threadSafeConnection";
public static final String XML_IS_PASSWORD_ENCRYPTED = "passwordEncrypted";
// not yet used by component
public static final String XML_NAME_ATTRIBUTE = "name";
/**
* Constructor for the DBConnection object
*
* @param dbDriver Description of the Parameter
* @param dbURL Description of the Parameter
* @param user Description of the Parameter
* @param password Description of the Parameter
*/
public DBConnection(String id, String dbDriver, String dbURL, String user, String password) {
super(id);
this.openedConnections=new HashMap();
this.config = new Properties();
try{
config.setProperty(XML_USER_ATTRIBUTE, user);
config.setProperty(XML_PASSWORD_ATTRIBUTE, password);
config.setProperty(XML_DBDRIVER_ATTRIBUTE, dbDriver);
config.setProperty(XML_DBURL_ATTRIBUTE, dbURL);
}catch(NullPointerException ex){
// do nothing in constructor - will probably fail later
}
this.threadSafeConnections=true;
this.isPasswordEncrypted=false;
}
/**
* Constructor for the DBConnection object (not used in engine yet)
*
* @param configFilename properties filename containing definition of driver, dbURL, username, password
*/
public DBConnection(String id, String configFilename) {
super(id);
this.openedConnections=new HashMap();
this.config = new Properties();
try {
InputStream stream = null;
if (!new File(configFilename).exists()) {
// config file not found on file system - try classpath
stream = getClass().getClassLoader().getResourceAsStream(configFilename);
if(stream == null) {
throw new FileNotFoundException("Config file for db connection " + id + " not found (" + configFilename +")");
}
stream = new BufferedInputStream(stream);
} else {
stream = new BufferedInputStream(new FileInputStream(configFilename));
}
this.config.load(stream);
stream.close();
this.threadSafeConnections=parseBoolean(config.getProperty(XML_THREAD_SAFE_CONNECTIONS,"true"));
this.isPasswordEncrypted=parseBoolean(config.getProperty(XML_IS_PASSWORD_ENCRYPTED,"false"));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public DBConnection(String id, Properties configProperties) {
super(id);
this.openedConnections=new HashMap();
this.config = configProperties;
this.threadSafeConnections=parseBoolean(configProperties.getProperty(XML_THREAD_SAFE_CONNECTIONS,"true"));
this.isPasswordEncrypted=parseBoolean(config.getProperty(XML_IS_PASSWORD_ENCRYPTED,"false"));
}
/**
* Method which connects to database and if successful, sets various
* connection parameters. If as a property "transactionIsolation" is defined, then
* following options are allowed:<br>
* <ul>
* <li>READ_UNCOMMITTED</li>
* <li>READ_COMMITTED</li>
* <li>REPEATABLE_READ</li>
* <li>SERIALIZABLE</li>
* </ul>
*
* @see java.sql.Connection#setTransactionIsolation(int)
*/
public void connect() {
String dbDriverName;
if (dbDriver==null){
dbDriverName=config.getProperty(XML_DBDRIVER_ATTRIBUTE);
try {
dbDriver = (Driver) Class.forName(dbDriverName).newInstance();
} catch (ClassNotFoundException ex) {
// let's try to load in any additional .jar library (if specified) (one or more)
// separator of individual libraries depends on platform - UNIX - ":" Win - ";"
String jdbcDriverLibrary = config
.getProperty(JDBC_DRIVER_LIBRARY_NAME);
if (jdbcDriverLibrary != null) {
String[] libraryPaths=jdbcDriverLibrary.split(Defaults.DEFAULT_JDBC_LIBRARY_SEPARATOR);
URL[] myURLs= new URL[libraryPaths.length];
// try to create URL directly, if failed probably the protocol is missing, so use File.toURL
for(int i=0;i<libraryPaths.length;i++){
try {
// valid url
myURLs[i]=new URL(libraryPaths[i]);
} catch (MalformedURLException ex1) {
try {
// probably missing protocol prefix, try to load it as a file
myURLs[i] = new File(libraryPaths[i]).toURI().toURL();
} catch (MalformedURLException ex2) {
throw new RuntimeException("Malformed URL: " + ex1.getMessage());
}
}
}
try {
URLClassLoader classLoader = new URLClassLoader(myURLs,Thread.currentThread().getContextClassLoader());
dbDriver = (Driver) Class.forName(dbDriverName,true,classLoader).newInstance();
} catch (ClassNotFoundException ex1) {
throw new RuntimeException("Can not find class: " + ex1);
} catch (Exception ex1) {
throw new RuntimeException("General exception: "
+ ex1.getMessage());
}
} else {
throw new RuntimeException("Can't load DB driver :"
+ ex.getMessage());
}
} catch (Exception ex) {
throw new RuntimeException("Can't load DB driver :"
+ ex.getMessage());
}
}
try {
// handle encrypted password
if (isPasswordEncrypted){
decryptPassword(this.config);
isPasswordEncrypted=false;
}
dbConnection = dbDriver.connect(config.getProperty(XML_DBURL_ATTRIBUTE), this.config);
} catch (SQLException ex) {
throw new RuntimeException("Can't connect to DB :"
+ ex.getMessage());
}
if (dbConnection == null) {
throw new RuntimeException(
"Not suitable driver for specified DB URL : " + dbDriver
+ " ; " + config.getProperty(XML_DBURL_ATTRIBUTE));
}
// try to set Transaction isolation level, it it was specified
if (config.containsKey(TRANSACTION_ISOLATION_PROPERTY_NAME)) {
int trLevel;
String isolationLevel = config
.getProperty(TRANSACTION_ISOLATION_PROPERTY_NAME);
if (isolationLevel.equalsIgnoreCase("READ_UNCOMMITTED")) {
trLevel = Connection.TRANSACTION_READ_UNCOMMITTED;
} else if (isolationLevel.equalsIgnoreCase("READ_COMMITTED")) {
trLevel = Connection.TRANSACTION_READ_COMMITTED;
} else if (isolationLevel.equalsIgnoreCase("REPEATABLE_READ")) {
trLevel = Connection.TRANSACTION_REPEATABLE_READ;
} else if (isolationLevel.equalsIgnoreCase("SERIALIZABLE")) {
trLevel = Connection.TRANSACTION_SERIALIZABLE;
} else {
trLevel = Connection.TRANSACTION_NONE;
}
try {
dbConnection.setTransactionIsolation(trLevel);
} catch (SQLException ex) {
// we do nothing, if anything goes wrong, we just
// leave whatever was the default
}
}
}
/**
* Description of the Method
*
* @exception SQLException Description of the Exception
*/
public void free() {
if(threadSafeConnections) {
for(Iterator i = openedConnections.values().iterator(); i.hasNext();) {
try {
Connection c = ((Connection)i.next());
if(!c.getAutoCommit()) {
c.commit();
}
c.close();
} catch (SQLException e) {
logger.warn(getId() + " - close operation failed.");
}
}
} else {
try {
if (!dbConnection.isClosed()) {
if (!dbConnection.getAutoCommit()) {
dbConnection.commit();
}
dbConnection.close();
}
} catch (SQLException e) {
logger.warn(getId() + " - close operation failed.");
}
}
}
/**
* Gets the connection attribute of the DBConnection object. If threadSafe option
* is set, then each call will result in new connection being created.
*
* @return The database connection (JDBC)
*/
public synchronized Connection getConnection() {
Connection con=null;
if (threadSafeConnections){
con=(Connection)openedConnections.get(Thread.currentThread());
if(con==null){
connect();
con=dbConnection;
openedConnections.put(Thread.currentThread(),con);
}
}else{
try{
if (dbConnection.isClosed()){
connect();
}
}catch(SQLException ex){
throw new RuntimeException(
"Can't establish or reuse existing connection : " + dbDriver
+ " ; " + config.getProperty(XML_DBURL_ATTRIBUTE));
}
con=dbConnection;
}
return con;
}
/**
* Creates new statement with default parameters and returns it
*
* @return The new statement
* @exception SQLException Description of the Exception
*/
public Statement getStatement() throws SQLException {
return getConnection().createStatement();
}
/**
* Creates new statement with specified parameters
*
* @param type one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY,
* ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
* @param concurrency one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or
* ResultSet.CONCUR_UPDATABLE
* @param holdability one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT
* or ResultSet.CLOSE_CURSORS_AT_COMMIT
* @return The new statement
* @throws SQLException
*/
public Statement getStatement(int type,int concurrency,int holdability) throws SQLException {
return getConnection().createStatement(type,concurrency,holdability);
}
/**
* Creates new prepared statement with default parameters
*
* @param sql SQL/DML query
* @return Description of the Return Value
* @exception SQLException Description of the Exception
*/
public PreparedStatement prepareStatement(String sql) throws SQLException {
return getConnection().prepareStatement(sql);
}
/**
* Creates new prepared statement with specified parameters
*
* @param sql SQL/DML query
* @param resultSetType
* @param resultSetConcurrency
* @param resultSetHoldability
* @return
* @throws SQLException
*/
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return getConnection().prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
}
/**
* Sets the property attribute of the DBConnection object
*
* @param name The new property value
* @param value The new property value
*/
public void setProperty(String name, String value) {
config.setProperty(name, value);
}
/**
* Sets the property attribute of the DBConnection object
*
* @param properties The new property value
*/
public void setProperty(Properties properties) {
config.putAll(properties);
this.decryptPassword(this.config);
}
/**
* Gets the property attribute of the DBConnection object
*
* @param name Description of the Parameter
* @return The property value
*/
public String getProperty(String name) {
return config.getProperty(name);
}
/**
* Description of the Method
*
* @param nodeXML Description of the Parameter
* @return Description of the Return Value
*/
public static DBConnection fromXML(TransformationGraph graph, Element nodeXML) {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
NamedNodeMap attributes = nodeXML.getAttributes();
DBConnection con;
// for resolving reference in additional parameters
// this should be changed in the future when ComponentXMLAttributes
// is enhanced to support iterating through attributes
PropertyRefResolver refResolver=new PropertyRefResolver(graph);
try {
String id = xattribs.getString(XML_ID_ATTRIBUTE);
// do we have dbConfig parameter specified ??
if (xattribs.exists(XML_DBCONFIG_ATTRIBUTE)) {
return new DBConnection(id, xattribs.getString(XML_DBCONFIG_ATTRIBUTE));
} else {
String dbDriver = xattribs.getString(XML_DBDRIVER_ATTRIBUTE);
String dbURL = xattribs.getString(XML_DBURL_ATTRIBUTE);
String user = "";
String password = "";
con = new DBConnection(id, dbDriver, dbURL, user, password);
//check thread safe option
if (xattribs.exists(XML_THREAD_SAFE_CONNECTIONS)){
con.setThreadSafeConnections(xattribs.getBoolean(XML_THREAD_SAFE_CONNECTIONS));
}
//check passwordEncrypted option
if (xattribs.exists(XML_IS_PASSWORD_ENCRYPTED)){
con.setPasswordEncrypted(xattribs.getBoolean(XML_IS_PASSWORD_ENCRYPTED));
}
// assign rest of attributes/parameters to connection properties so
// it can be retrieved by DB JDBC driver
for (int i = 0; i < attributes.getLength(); i++) {
con.setProperty(attributes.item(i).getNodeName(), refResolver.resolveRef(attributes.item(i).getNodeValue()));
}
con.decryptPassword(con.config);
return con;
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
return null;
}
}
public void saveConfiguration(OutputStream outStream) throws IOException {
Properties propsToStore = new Properties();
propsToStore.putAll(config);
propsToStore.put(XML_THREAD_SAFE_CONNECTIONS,Boolean.toString(this.threadSafeConnections));
propsToStore.put(XML_IS_PASSWORD_ENCRYPTED,Boolean.toString(this.isPasswordEncrypted));
propsToStore.store(outStream,null);
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public String toString() {
StringBuffer strBuf=new StringBuffer(255);
strBuf.append("DBConnection driver[").append(config.getProperty(XML_DBDRIVER_ATTRIBUTE));
strBuf.append("]:url[").append(config.getProperty(XML_DBURL_ATTRIBUTE));
strBuf.append("]:user[").append(config.getProperty(XML_NAME_ATTRIBUTE)).append("]");
return strBuf.toString();
}
/**
* @return Returns the threadSafeConnections.
*/
public boolean isThreadSafeConnections() {
return threadSafeConnections;
}
/**
* @param threadSafeConnections The threadSafeConnections to set.
*/
public void setThreadSafeConnections(boolean threadSafeConnections) {
this.threadSafeConnections = threadSafeConnections;
}
private boolean parseBoolean(String s) {
return s != null && s.equalsIgnoreCase("true");
}
/** Decrypt the password entry in the configuration properties if the
* isPasswordEncrypted property is set to "y" or "yes". If any error occurs
* and decryption fails, the original password entry will be used.
*
* @param configProperties
* configuration properties
*/
private void decryptPassword(Properties configProperties) {
if (isPasswordEncrypted){
Enigma enigma = Enigma.getInstance();
String decryptedPassword = null;
try {
decryptedPassword = enigma.decrypt(configProperties.getProperty(XML_PASSWORD_ATTRIBUTE));
} catch (JetelException e) {
logger.error("Can't decrypt password on DBConnection (id=" + this.getId() + "). Please set the password as engine parameter -pass.");
}
// If password decryption returns failure, try with the password
// as it is.
if (decryptedPassword != null) {
configProperties.setProperty(XML_PASSWORD_ATTRIBUTE, decryptedPassword);
}
}
}
/**
* @return Returns the isPasswordEncrypted.
*/
public boolean isPasswordEncrypted() {
return isPasswordEncrypted;
}
/**
* @param isPasswordEncrypted The isPasswordEncrypted to set.
*/
public void setPasswordEncrypted(boolean isPasswordEncrypted) {
this.isPasswordEncrypted = isPasswordEncrypted;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig()
*/
public boolean checkConfig() {
return true;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
public void init() throws ComponentNotReadyException {
connect();
}
/* (non-Javadoc)
* @see org.jetel.database.IConnection#createMetadata(java.util.Properties)
*/
public DataRecordMetadata createMetadata(Properties parameters) throws SQLException {
Statement statement;
ResultSet resultSet;
String sqlQuery = parameters.getProperty("sqlQuery");
if(StringUtils.isEmpty(sqlQuery)) {
throw new IllegalArgumentException("JDBC stub for clover metadata can't find sqlQuery parameter.");
}
statement = getStatement();
resultSet = statement.executeQuery(sqlQuery);
return SQLUtil.dbMetadata2jetel(resultSet.getMetaData());
}
}
|
package org.basex.io;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import org.basex.data.MetaData;
import org.basex.util.Array;
import org.basex.util.BitArray;
import org.basex.util.Util;
public final class TableDiskAccess extends TableAccess {
/** Max entries per block. */
static final int ENTRIES = IO.BLOCKSIZE >>> IO.NODEPOWER;
/** Buffer manager. */
private final Buffers bm = new Buffers();
/** Current buffer. */
private Buffer bf;
/** File storing all blocks. */
private final RandomAccessFile data;
/** FirstPre values (sorted ascending; length={@link #allBlocks}). */
private int[] fpres;
/** Index array storing BlockNumbers (length={@link #allBlocks}). */
private int[] pages;
/** Bit map storing free (=0) and occupied (=1) pages. */
private BitArray pagemap;
/** Pre value of the first entry in the current block. */
private int fpre = -1;
/** First pre value of the next block. */
private int npre = -1;
/** Number of blocks in the data file (including unused). */
private int allBlocks;
/** Number of entries in the index (used blocks). */
private int blocks;
/** Index of the current block number in the {@link #pages} array. */
private int index = -1;
/**
* Constructor.
* @param md meta data
* @param pf file prefix
* @throws IOException I/O exception
*/
public TableDiskAccess(final MetaData md, final String pf)
throws IOException {
super(md, pf);
// read meta and index data
final DataInput in = new DataInput(meta.file(pf + 'i'));
allBlocks = in.readNum();
blocks = in.readNum();
fpres = in.readNums();
pages = in.readNums();
final int psize = in.readNum();
// check if the page map has been stored:
if(psize == 0) {
// init the map with empty pages:
pagemap = new BitArray(allBlocks);
for(final int p : pages) pagemap.set(p);
dirty = true;
} else {
pagemap = new BitArray(in.readLongs(psize), allBlocks);
}
in.close();
// initialize data file
data = new RandomAccessFile(meta.file(pf), "rw");
readBlock(0, 0, blocks > 1 ? fpres[1] : md.size);
}
@Override
public synchronized void flush() throws IOException {
for(final Buffer b : bm.all()) if(b.dirty) writeBlock(b);
if(!dirty) return;
final DataOutput out = new DataOutput(meta.file(pref + 'i'));
out.writeNum(allBlocks);
out.writeNum(blocks);
out.writeNums(fpres);
out.writeNums(pages);
out.writeLongs(pagemap.toArray());
out.close();
dirty = false;
}
@Override
public synchronized void close() throws IOException {
flush();
data.close();
}
@Override
public synchronized int read1(final int pre, final int off) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
return b[o] & 0xFF;
}
@Override
public synchronized int read2(final int pre, final int off) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
return ((b[o] & 0xFF) << 8) + (b[o + 1] & 0xFF);
}
@Override
public synchronized int read4(final int pre, final int off) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
return ((b[o] & 0xFF) << 24) + ((b[o + 1] & 0xFF) << 16) +
((b[o + 2] & 0xFF) << 8) + (b[o + 3] & 0xFF);
}
@Override
public synchronized long read5(final int pre, final int off) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
return ((long) (b[o] & 0xFF) << 32) + ((long) (b[o + 1] & 0xFF) << 24) +
((b[o + 2] & 0xFF) << 16) + ((b[o + 3] & 0xFF) << 8) + (b[o + 4] & 0xFF);
}
@Override
public void write1(final int pre, final int off, final int v) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
b[o] = (byte) v;
bf.dirty = true;
}
@Override
public void write2(final int pre, final int off, final int v) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
b[o] = (byte) (v >>> 8);
b[o + 1] = (byte) v;
bf.dirty = true;
}
@Override
public void write4(final int pre, final int off, final int v) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
b[o] = (byte) (v >>> 24);
b[o + 1] = (byte) (v >>> 16);
b[o + 2] = (byte) (v >>> 8);
b[o + 3] = (byte) v;
bf.dirty = true;
}
@Override
public void write5(final int pre, final int off, final long v) {
final int o = off + cursor(pre);
final byte[] b = bf.data;
b[o] = (byte) (v >>> 32);
b[o + 1] = (byte) (v >>> 24);
b[o + 2] = (byte) (v >>> 16);
b[o + 3] = (byte) (v >>> 8);
b[o + 4] = (byte) v;
bf.dirty = true;
}
/* Note to delete method: Freed blocks are currently ignored. */
@Override
public void delete(final int first, final int nr) {
// mark index as dirty and get first block
dirty = true;
cursor(first);
// some useful variables to make code more readable
int from = first - fpre;
final int last = first + nr;
// check if all entries are in current block => handle and return
if(last - 1 < npre) {
copy(bf.data, from + nr, bf.data, from, npre - last);
updatePre(nr);
// if whole block was deleted, remove it from the index
if(npre == fpre) {
// mark the block as empty:
pagemap.clear(pages[index]);
Array.move(fpres, index + 1, -1, blocks - index - 1);
Array.move(pages, index + 1, -1, blocks - index - 1);
readBlock(index, fpre, index + 2 > --blocks ? meta.size :
fpres[index + 1]);
}
return;
}
// handle blocks whose entries are to be deleted entirely
// first count them
int unused = 0;
while(npre < last) {
if(from == 0) {
++unused;
// mark the blocks as empty; range clear cannot be used because the
// block may not be consecutive:
pagemap.clear(pages[index]);
}
nextBlock();
from = 0;
}
// now remove them from the index
if(unused > 0) {
Array.move(fpres, index, -unused, blocks - index);
Array.move(pages, index, -unused, blocks - index);
blocks -= unused;
index -= unused;
}
// delete entries at beginning of current (last) block
copy(bf.data, last - fpre, bf.data, 0, npre - last);
// update index entry for this block
fpres[index] = first;
fpre = first;
updatePre(nr);
}
@Override
public void insert(final int pre, final byte[] entries) {
if(entries.length <= 0) return;
// number of records to be inserted:
final int nr = entries.length >>> IO.NODEPOWER;
meta.size += nr;
dirty = true;
// go to the block and find the offset within the block where the new
// records will be inserted:
final int split = cursor(pre - 1) + (1 << IO.NODEPOWER);
// number of bytes occupied by old records in the current block:
final int nold = npre - fpre << IO.NODEPOWER;
// number of bytes occupied by old records which will be after the new ones:
final int nlast = nold - split;
// special case: all entries fit in the current block:
if(nold + entries.length <= IO.BLOCKSIZE) {
System.arraycopy(bf.data, split, bf.data, split + entries.length, nlast);
System.arraycopy(entries, 0, bf.data, split, entries.length);
bf.dirty = true;
// increment first pre-values of blocks after the last modified block:
for(int i = index + 1; i < blocks; ++i) fpres[i] += nr;
// update cached variables (fpre is not changed):
npre += nr;
return;
}
// append old entries at the end of the new entries:
// [DP] the following can be optimized to avoid copying arrays:
final byte[] all = new byte[entries.length + nlast];
System.arraycopy(entries, 0, all, 0, entries.length);
System.arraycopy(bf.data, split, all, entries.length, nlast);
// fill in the current block with new entries:
// number of bytes which can fit in the first block:
int n = bf.data.length - split;
System.arraycopy(all, 0, bf.data, split, n);
bf.dirty = true;
// resize fpres and pages:
// number of blocks needed to store the remaining entries:
final int neededBlocks = (all.length - n + IO.BLOCKSIZE - 1) / IO.BLOCKSIZE;
// number of new blocks (number of needed block - number of empty blocks):
final int newBlocks = neededBlocks - (allBlocks - blocks);
// extend fpres and pages, if new blocks will be allocated:
if(newBlocks > 0) {
fpres = Arrays.copyOf(fpres, fpres.length + newBlocks);
pages = Arrays.copyOf(pages, pages.length + newBlocks);
}
// make place for the blocks where the new entries will be written:
Array.move(fpres, index + 1, neededBlocks, blocks - index - 1);
Array.move(pages, index + 1, neededBlocks, blocks - index - 1);
// write the all remaining entries:
while(n < all.length) {
getFreeBlock();
n += write(all, n);
fpres[index + 1] = fpres[index] + ENTRIES;
pages[++index] = (int) bf.pos;
}
// increment first pre-values of blocks after the last modified block:
for(int i = index + 1; i < blocks; ++i) fpres[i] += nr;
// update cached variables:
fpre = fpres[index];
npre = index + 1 >= blocks ? meta.size : fpres[index + 1];
}
@Override
public void set(final int pre, final byte[] entries) {
dirty = true;
final int nr = entries.length >>> IO.NODEPOWER;
for(int l = 0, i = pre; i < pre + nr; ++i, l += 1 << IO.NODEPOWER) {
final int o = cursor(pre);
System.arraycopy(entries, l, bf.data, o, 1 << IO.NODEPOWER);
}
}
/**
* Searches for the block containing the entry for that pre. then it
* reads the block and returns it's offset inside the block.
* @param pre pre of the entry to search for
* @return offset of the entry in currentBlock
*/
private int cursor(final int pre) {
int fp = fpre;
int np = npre;
if(pre < fp || pre >= np) {
final int last = blocks - 1;
int l = 0;
int h = last;
int m = index;
while(l <= h) {
if(pre < fp) h = m - 1;
else if(pre >= np) l = m + 1;
else break;
m = h + l >>> 1;
fp = fpres[m];
np = m == last ? fp + ENTRIES : fpres[m + 1];
}
if(l > h) Util.notexpected("Data Access out of bounds [pre:" + pre +
", indexSize:" + blocks + ", access:" + l + " > " + h + "]");
readBlock(m, fp, np);
}
return pre - fpre << IO.NODEPOWER;
}
/**
* Fetches the requested block and update pointers.
* @param i index number of the block to fetch
* @param f first entry in that block
* @param n first entry in the next block
*/
private void readBlock(final int i, final int f, final int n) {
index = i;
fpre = f;
npre = n;
final int b = pages[i];
final boolean ch = bm.cursor(b);
bf = bm.current();
if(ch) {
try {
if(bf.dirty) writeBlock(bf);
bf.pos = b;
data.seek(bf.pos * IO.BLOCKSIZE);
data.readFully(bf.data);
} catch(final IOException ex) {
Util.stack(ex);
}
}
}
/**
* Checks whether the current block needs to be written and write it.
* @param buf buffer to write
* @throws IOException I/O exception
*/
private void writeBlock(final Buffer buf) throws IOException {
data.seek(buf.pos * IO.BLOCKSIZE);
data.write(buf.data);
buf.dirty = false;
}
/**
* Fetches next block.
*/
private void nextBlock() {
readBlock(index + 1, npre, index + 2 >= blocks ? meta.size :
fpres[index + 2]);
}
/**
* Updates the firstPre index entries.
* @param nr number of entries to move
*/
private void updatePre(final int nr) {
// update index entries for all following blocks and reduce counter
for(int i = index + 1; i < blocks; ++i) fpres[i] -= nr;
meta.size -= nr;
npre = index + 1 >= blocks ? meta.size : fpres[index + 1];
}
/**
* Convenience method for copying blocks.
* @param s source array
* @param sp source position
* @param d destination array
* @param dp destination position
* @param l source length
*/
private void copy(final byte[] s, final int sp, final byte[] d,
final int dp, final int l) {
System.arraycopy(s, sp << IO.NODEPOWER, d, dp << IO.NODEPOWER,
l << IO.NODEPOWER);
bf.dirty = true;
}
/**
* Fill the current buffer with bytes from the specified array from the
* specified offset.
* @param s source array
* @param o offset from the beginning of the array
* @return number of written bytes
*/
private int write(final byte[] s, final int o) {
final int len = Math.min(bf.data.length, s.length - o);
System.arraycopy(s, o, bf.data, 0, len);
bf.dirty = true;
return len;
}
/** Free the current buffer. */
private void flushCurrentBuffer() {
try {
if(bf.dirty) {
writeBlock(bf);
bf.dirty = false;
}
} catch(final IOException ex) {
Util.stack(ex);
}
}
/** Move the cursor to a free block (either new or existing empty one). */
private void getFreeBlock() {
flushCurrentBuffer();
// find an empty block:
bf.pos = pagemap.nextClearBit(0);
// if the block number is bigger than the total number of block, it's a new:
if(bf.pos >= allBlocks) allBlocks = (int) bf.pos + 1;
bf.dirty = true;
pagemap.set(bf.pos);
blocks++;
}
/**
* Returns the number of entries; needed for JUnit tests.
* @return number of entries
*/
public int size() {
return meta.size;
}
/**
* Returns the number of used blocks; needed for JUnit tests.
* @return number of used blocks
*/
public int blocks() {
return blocks;
}
}
|
package org.basex.query.flwor;
import static org.basex.query.QueryText.*;
import java.util.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.path.*;
import org.basex.query.util.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.list.*;
public class GFLWOR extends ParseExpr {
/** Return expression. */
Expr ret;
/** For/Let expression. */
ForLet[] fl;
/** Where clause. */
Expr where;
/** Order clause. */
private Order order;
/** Group by clause. */
private final Group group;
/**
* GFLWOR constructor.
* @param f variable inputs
* @param w where clause
* @param o order expression
* @param g group by expression
* @param r return expression
* @param ii input info
*/
GFLWOR(final ForLet[] f, final Expr w, final Order o, final Group g, final Expr r,
final InputInfo ii) {
super(ii);
ret = r;
fl = f;
where = w;
group = g;
order = o;
}
/**
* Returns a GFLWOR instance.
* @param fl variable inputs
* @param whr where clause
* @param ord order expression
* @param grp group-by expression
* @param ret return expression
* @param ii input info
* @return GFLWOR instance
*/
public static GFLWOR get(final ForLet[] fl, final Expr whr, final Order ord,
final Group grp, final Expr ret, final InputInfo ii) {
return ord == null && grp == null ? new FLWR(fl, whr, ret, ii) :
new GFLWOR(fl, whr, ord, grp, ret, ii);
}
@Override
public void checkUp() throws QueryException {
for(final ForLet f : fl) f.checkUp();
checkNoneUp(where, group, order);
ret.checkUp();
}
@Override
public Expr compile(final QueryContext ctx) throws QueryException {
compHoist(ctx);
compWhere(ctx);
final boolean grp = ctx.grouping;
ctx.grouping = group != null;
// optimize for/let clauses
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) {
final ForLet flt = fl[f].compile(ctx);
// bind variable if it contains a value or will only be evaluated once
boolean let = true;
for(int g = f + 1; g < fl.length; g++) let &= fl[g] instanceof Let;
if(flt.expr.isValue() || let && count(flt.var, f) == 1) flt.bind(ctx);
}
// optimize where clause
boolean empty = false;
if(where != null) {
where = where.compile(ctx).compEbv(ctx);
if(where.isValue()) {
// test is always false: no results
empty = !where.ebv(ctx, info).bool(info);
if(!empty) {
// always true: test can be skipped
ctx.compInfo(OPTREMOVE, description(), where);
where = null;
}
}
}
if(group != null) group.compile(ctx);
if(order != null) order.compile(ctx);
ret = ret.compile(ctx);
ctx.vars.size(vs);
ctx.grouping = grp;
// remove FLWOR expression if WHERE clause always returns false
if(empty) {
ctx.compInfo(OPTREMOVE, description(), where);
return Empty.SEQ;
}
// check if return always yields an empty sequence
if(ret == Empty.SEQ) {
ctx.compInfo(OPTFLWOR);
return Empty.SEQ;
}
// remove declarations of statically bound or unused variables
for(int f = 0; f < fl.length; ++f) {
final ForLet l = fl[f];
// do not optimize non-deterministic expressions. example:
// let $a := file:write('file', 'content') return ...
if(l.var.expr() != null || l.simple(true) && count(l.var, f) == 0 &&
!l.expr.uses(Use.NDT)) {
ctx.compInfo(OPTVAR, l.var);
fl = Array.delete(fl, f
}
}
// no clauses left: simplify expression
// an optional order clause can be safely ignored
if(fl.length == 0) {
// if where clause exists: where A return B -> if A then B else ()
// otherwise: return B -> B
ctx.compInfo(OPTFLWOR);
return where != null ? new If(info, where, ret, Empty.SEQ) : ret;
}
// remove FLWOR expression if a FOR clause yields an empty sequence
for(final ForLet f : fl) {
if(f instanceof For && f.size() == 0 && !f.expr.uses(Use.NDT)) {
ctx.compInfo(OPTFLWOR);
return Empty.SEQ;
}
}
// compute number of results to speed up count() operations
if(where == null && group == null) {
size = ret.size();
if(size != -1) {
// multiply loop runs
for(final ForLet f : fl) {
final long s = f.size();
if(s == -1) {
size = s;
break;
}
size *= s;
}
}
}
type = SeqType.get(ret.type().type, size);
compHoist(ctx);
return this;
}
/**
* Hoists loop-invariant code. Avoids repeated evaluation of independent
* variables that return a single value. This method is called twice
* (before and after all other optimizations).
* @param ctx query context
*/
private void compHoist(final QueryContext ctx) {
// modification counter
int m = 0;
for(int i = 1; i < fl.length; i++) {
final ForLet in = fl[i];
/* move clauses upwards that contain a single value.
non-deterministic expressions or fragment constructors creating
unique nodes are ignored. example:
for $a in 1 to 2 let $b := random:double() return $b
*/
if(in.size() != 1 || in.uses(Use.NDT) || in.uses(Use.CNS)) continue;
/* - find most outer clause that declares no variables used in the inner clause.
* example: let $x := <a/> for $i in 1 to 2 let $a := $x return $a
* - code will not be moved if all clauses are let clauses.
* example: let $x := <a/> let $i := <b/> let $a := $x return ($a, $i)
*/
int p = -1;
boolean f = false;
for(int o = i; o-- != 0 && in.count(fl[o]) == 0; p = o, f |= fl[o] instanceof For);
if(p == -1 || !f) continue;
// move clause
Array.move(fl, p, 1, i - p);
fl[p] = in;
if(m++ == 0) ctx.compInfo(OPTFORLET);
}
}
/**
* Rewrites a where clause to one or more predicates.
* @param ctx query context
*/
private void compWhere(final QueryContext ctx) {
// no where clause specified
if(where == null) return;
// check if all clauses are simple, and if variables are removable
for(final ForLet f : fl) {
if(f instanceof For && (!f.simple(false) || !where.removable(f.var))) return;
}
// create array with tests
final Expr[] tests = where instanceof And ? ((And) where).expr : new Expr[] { where };
// find which tests access which variables. if a test will not use any of
// the variables defined in the local context, they will be added to the
// first binding
final int[] tar = new int[tests.length];
for(int t = 0; t < tests.length; ++t) {
int fr = -1;
for(int f = fl.length - 1; f >= 0; --f) {
// remember index of most inner FOR clause
if(fl[f] instanceof For) fr = f;
// predicate is found that uses the current variable
if(tests[t].count(fl[f].var) != 0) {
// stop rewriting if no most inner FOR clause is defined
if(fr == -1) return;
// attach predicate to the corresponding FOR clause, and stop
tar[t] = fr;
break;
}
}
}
// convert where clause to predicate(s)
ctx.compInfo(OPTWHERE);
for(int f = 0; f < fl.length; ++f) {
final ForLet c = fl[f];
final ExprList el = new ExprList();
// find all tests that will be bound to the current clause
for(int t = 0; t < tests.length; ++t) {
if(tar[t] == f) el.add(tests[t].remove(c.var));
}
// none found: continue
if(el.isEmpty()) continue;
// attach predicates to axis path or filter, or create a new filter
final Expr a;
if(el.size() == 1) {
// one found: wrap with boolean function if value may be numeric
final Expr e = el.get(0);
a = e.type().mayBeNumber() ? Function.BOOLEAN.get(info, e) : e;
} else {
// more found: wrap with and expression
a = new And(info, el.finish());
}
// add to clause expression
if(c.expr instanceof AxisPath) {
c.expr = ((AxisPath) c.expr).addPreds(a);
} else if(c.expr instanceof Filter) {
c.expr = ((Filter) c.expr).addPred(a);
} else {
c.expr = new Filter(info, c.expr, a);
}
}
// eliminate where clause
where = null;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
final Iter[] iter = new Iter[fl.length];
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) iter[f] = ctx.iter(fl[f]);
// evaluate pre grouping tuples
ArrayList<Item[]> keys = null;
ValueList vals = null;
if(order != null) {
keys = new ArrayList<Item[]>();
vals = new ValueList();
}
if(group != null) group.init(order);
iter(ctx, iter, 0, keys, vals);
ctx.vars.size(vs);
for(final ForLet f : fl) ctx.vars.add(f.var);
// order != null, otherwise it would have been handled in group
final Iter ir = group != null ?
group.gp.ret(ctx, ret, keys, vals) : ctx.iter(order.set(keys, vals));
ctx.vars.size(vs);
return ir;
}
/**
* Performs a recursive iteration on the specified variable position.
* @param ctx query context
* @param it iterator
* @param p variable position
* @param ks sort keys
* @param vs values to sort
* @throws QueryException query exception
*/
private void iter(final QueryContext ctx, final Iter[] it, final int p,
final ArrayList<Item[]> ks, final ValueList vs) throws QueryException {
final boolean more = p + 1 != fl.length;
while(it[p].next() != null) {
if(more) {
iter(ctx, it, p + 1, ks, vs);
} else if(where == null || where.ebv(ctx, info).bool(info)) {
if(group != null) {
group.gp.add(ctx);
} else if(order != null) {
// order by will be handled in group by otherwise
order.add(ctx, ret, ks, vs);
}
}
}
}
@Override
public final boolean uses(final Use u) {
for(final ForLet f : fl) if(f.uses(u)) return true;
return where != null && where.uses(u) ||
order != null && order.uses(u) ||
group != null && group.uses(u) || ret.uses(u);
}
@Override
public final int count(final Var v) {
return count(v, 0);
}
/**
* Counts how often the specified variable is used, starting from the
* specified for/let index.
* @param v variable to be checked
* @param i index
* @return number of occurrences
*/
final int count(final Var v, final int i) {
int c = 0;
for(int f = i; f < fl.length; f++) c += fl[f].count(v);
if(where != null) c += where.count(v);
if(order != null) c += order.count(v);
if(group != null) c += group.count(v);
return c + ret.count(v);
}
@Override
public final boolean removable(final Var v) {
for(final ForLet f : fl) if(!f.removable(v)) return false;
return (where == null || where.removable(v)) &&
(order == null || order.removable(v)) &&
(group == null || group.removable(v)) && ret.removable(v);
}
@Override
public final Expr remove(final Var v) {
for(final ForLet f : fl) f.remove(v);
if(where != null) where = where.remove(v);
if(order != null) order = order.remove(v);
ret = ret.remove(v);
return this;
}
@Override
public boolean databases(final StringList db) {
for(final ForLet f : fl) if(!f.databases(db)) return false;
return (where == null || where.databases(db)) &&
(order == null || order.databases(db)) &&
(group == null || group.databases(db)) && ret.databases(db);
}
@Override
public boolean isVacuous() {
return ret.isVacuous();
}
@Override
public final void plan(final FElem plan) {
final FElem el = planElem();
addPlan(plan, el, fl);
if(where != null) addPlan(el, new FElem(WHR), where);
if(group != null) group.plan(el);
if(order != null) order.plan(el);
addPlan(el, new FElem(RET), ret);
}
@Override
public final String toString() {
final StringBuilder sb = new StringBuilder();
for(int i = 0; i != fl.length; ++i) sb.append(i != 0 ? " " : "").append(fl[i]);
if(where != null) sb.append(' ' + WHERE + ' ' + where);
if(group != null) sb.append(group);
if(order != null) sb.append(order);
return sb.append(' ' + RETURN + ' ' + ret).toString();
}
}
|
package org.jetel.util;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.graph.TransformationGraph;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.apache.commons.logging.Log;
/**
* Helper class (wrapper) around NamedNodeMap with possibility to parse string
* values into integers, booleans, doubles..<br>
* Used in conjunction with org.jetel.Component.*<br>
* MAX_INT,MIN_INT,MAX_DOUBLE, MIN_DOUBLE constants are defined and are
* translated to appropriate int or double values when getInteger(), getDouble()
* methods are called.<br>
* Converts any child nodes of form <code><attr name="xyz">abcd</attr></code> into
* attribute of the current node with name="xyz" and value="abcd".<br>
* Example:<br>
* <code><pre>
* <Node id="mynode" name="xyz" append="yes">
* <attr name="query">
* select * from my_table;
* </attr>
* <attr name="code">
* a=b*10-20%50;
* </attr>
* </Node>
* </pre></code>
*
* There will be following attribute/value pairs available for getXXX() calls:
* <ul>
* <li>id - "mynode"</li>
* <li>name - "xyz"</li>
* <li>append - "yes"</li>
* <li>query - "select * from my_table;"</li>
* <li>code - "a=b*10-20%50;"</li>
* </ul>
* @author dpavlis
* @since July 25, 2002
* @revision $Revision$
* @created 26. March 2003
*/
public class ComponentXMLAttributes {
private static final String STR_MAX_INT="MAX_INT";
private static final String STR_MIN_INT="MIN_INT";
private static final String STR_MAX_DOUBLE="MAX_DOUBLE";
private static final String STR_MIN_DOUBLE="MIN_DOUBLE";
protected NamedNodeMap attributes;
protected Element nodeXML;
protected PropertyRefResolver refResolver;
public static final String XML_ATTRIBUTE_NODE_NAME = "attr";
public static final String XML_ATTRIBUTE_NODE_NAME_ATTRIBUTE = "name";
//private Map childNodes;
/**
* Constructor for the ComponentXMLAttributes object
*
* @param nodeXML Description of the Parameter
*/
public ComponentXMLAttributes(Element nodeXML) {
this(nodeXML, (Properties) null);
}
/**
* Constructor for the ComponentXMLAttributes object
*
* @param nodeXML Description of the Parameter
*/
public ComponentXMLAttributes(Element nodeXML, TransformationGraph graph) {
this(nodeXML, graph.getGraphProperties());
}
/**
*Constructor for the ComponentXMLAttributes object
*
* @param nodeXML Description of the Parameter
* @param properties Description of the Parameter
*/
public ComponentXMLAttributes(Element nodeXML, Properties properties) {
this.nodeXML = nodeXML;
refResolver= new PropertyRefResolver(properties);
instantiateInlinedNodeAttributes(nodeXML);
this.attributes = nodeXML.getAttributes();
}
private void instantiateInlinedNodeAttributes(Element _nodeXML){
org.w3c.dom.Node childNode;
org.w3c.dom.NodeList list;
String newAttributeName;
String newAttributeValue;
// add all "inlined" attributes in form of "attr" node as normal attributes
if (_nodeXML!=null && _nodeXML.hasChildNodes()) {
list = _nodeXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
childNode = list.item(i);
if (childNode.getNodeName().equalsIgnoreCase(XML_ATTRIBUTE_NODE_NAME)) {
newAttributeName=childNode.getAttributes().getNamedItem(XML_ATTRIBUTE_NODE_NAME_ATTRIBUTE).getNodeValue();
// get text value
newAttributeValue=null;
org.w3c.dom.NodeList childList = childNode.getChildNodes();
for (int j = 0; j < childList.getLength(); j++) {
org.w3c.dom.Node child2Node = childList.item(j);
if (child2Node.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
newAttributeValue=child2Node.getNodeValue();
break;
}
}
// add value of child node as attribute, also create new attribute node
if (newAttributeName!=null && newAttributeValue!=null){
org.w3c.dom.Attr newAttribute = _nodeXML.getOwnerDocument().createAttribute(newAttributeName);
newAttribute.setNodeValue(newAttributeValue);
_nodeXML.getAttributes().setNamedItem(newAttribute);
// remove child node as it is now included as an attribute - in attribute
_nodeXML.removeChild(childNode);
}
}
}
}
}
/**
* Returns the String value of specified XML attribute
*
* @param key name of the attribute
* @return The string value
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public String getString(String key) throws AttributeNotFoundException {
return getString(key,true);
}
/**
* Returns the String value of specified XML attribute
*
* @param key name of the attribute
* @param strictlyResolve if true, any unresolvable reference to global parameter/property causes AttributeNotFoundException be
* thrown
* @return The string value
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public String getString(String key,boolean strictlyResolve) throws AttributeNotFoundException {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
throw new AttributeNotFoundException(key);
}
return refResolver.resolveRef(value,strictlyResolve);
}
/**
* Returns the String value of specified XML attribute
*
* @param key name of the attribute
* @param defaultValue default value to be returned when attribute can't be found
* @return The string value
*/
public String getString(String key, String defaultValue) {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
return defaultValue;
}
return refResolver.resolveRef(value);
}
/**
* Sets value of specified attribute
*
* @param key attribute name
* @param value attribute value
*/
public void setString(String key,String value) throws AttributeNotFoundException {
nodeXML.setAttribute(key,String.valueOf(value));
}
/**
* Returns the int value of specified XML attribute
*
* @param key name of the attribute
* @return The integer value
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public int getInteger(String key) throws AttributeNotFoundException {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
throw new AttributeNotFoundException(key);
}
value = refResolver.resolveRef(value);
if (value.equalsIgnoreCase(STR_MIN_INT)){
return Integer.MIN_VALUE;
}else if (value.equalsIgnoreCase(STR_MAX_INT)){
return Integer.MAX_VALUE;
}
return Integer.parseInt(value);
}
/**
* Returns the int value of specified XML attribute
*
* @param key name of the attribute
* @param defaultValue default value to be returned when attribute can't be found
* @return The integer value
*/
public int getInteger(String key, int defaultValue) {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
return defaultValue;
}
try{
value = refResolver.resolveRef(value);
if (value.equalsIgnoreCase(STR_MIN_INT)){
return Integer.MIN_VALUE;
}else if (value.equalsIgnoreCase(STR_MAX_INT)){
return Integer.MAX_VALUE;
}
return Integer.parseInt(value);
} catch (NumberFormatException ex) {
return defaultValue;
}
}
/**
* Sets value of specified attribute
*
* @param key attribute name
* @param value value to be set
*/
public void setInteger(String key,int value) throws AttributeNotFoundException{
nodeXML.setAttribute(key,String.valueOf(value));
}
/**
* Returns the boolean value of specified XML attribute
*
* @param key name of the attribute
* @return The boolean value
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public boolean getBoolean(String key) throws AttributeNotFoundException {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
throw new AttributeNotFoundException(key);
}
value = refResolver.resolveRef(value);
return value.matches("^[tTyY].*");
}
/**
* Returns the boolean value of specified XML attribute
*
* @param key name of the attribute
* @param defaultValue default value to be returned when attribute can't be found
* @return The boolean value
*/
public boolean getBoolean(String key, boolean defaultValue) {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
return defaultValue;
}
try {
value = refResolver.resolveRef(nodeXML.getAttribute(key));
return value.matches("^[tTyY].*");
} catch (Exception ex) {
return defaultValue;
}
}
/**
* Sets value of specified attribute
*
* @param key attribute name
* @param value value to be set
*/
public void setBoolean(String key,boolean value) throws AttributeNotFoundException {
nodeXML.setAttribute(key,String.valueOf(value));
}
/**
* Returns the double value of specified XML attribute
*
* @param key name of the attribute
* @return The double value
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public double getDouble(String key) throws AttributeNotFoundException {
String value=nodeXML.getAttribute(key);
if (value.length()==0){
throw new AttributeNotFoundException(key);
}
value = refResolver.resolveRef(value);
if (value.equalsIgnoreCase(STR_MIN_DOUBLE)){
return Double.MIN_VALUE;
}else if (value.equalsIgnoreCase(STR_MAX_DOUBLE)){
return Double.MAX_VALUE;
}
return Double.parseDouble(value);
}
/**
* Returns the double value of specified XML attribute
*
* @param key name of the attribute
* @param defaultValue default value to be returned when attribute can't be found
* @return The double value
*/
public double getDouble(String key, double defaultValue){
String value=nodeXML.getAttribute(key);
if (value.length()==0){
return defaultValue;
}
try {
value = refResolver.resolveRef(value);
if (value.equalsIgnoreCase(STR_MIN_DOUBLE)){
return Double.MIN_VALUE;
}else if (value.equalsIgnoreCase(STR_MAX_DOUBLE)){
return Double.MAX_VALUE;
}
return Double.parseDouble(value);
} catch (NumberFormatException ex) {
return defaultValue;
}
}
/**
* Sets value of specified attribute
*
* @param key attribute name
* @param value value to be set
*/
public void setDouble(String key, double value) {
nodeXML.setAttribute(key,String.valueOf(value));
}
/**
* Checks whether specified attribute exists (XML node has such attribute
* defined)
*
* @param key
* name of the attribute
* @return true if exists, otherwise false
*/
public boolean exists(String key) {
if (attributes.getNamedItem(key) != null) {
return true;
}
return false;
}
/**
* Returns first TEXT_NODE child under specified XML Node
*
* @param nodeXML XML node from which to start searching
* @param strictlyResolve if true, any unresolvable reference to global parameter/property causes AttributeNotFoundException be
* thrown
* @return The TEXT_NODE value (String) if any exist or null
* @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public String getText(org.w3c.dom.Node nodeXML,boolean strictlyResolve) throws AttributeNotFoundException{
org.w3c.dom.Node childNode;
org.w3c.dom.NodeList list;
if (nodeXML.hasChildNodes()) {
list = nodeXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
childNode = list.item(i);
if (childNode.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
return refResolver.resolveRef(childNode.getNodeValue(),strictlyResolve);
}
}
}
throw new AttributeNotFoundException("TEXT_NODE not found within node \""+nodeXML.getNodeName()+"\"");
}
/**
* Returns first TEXT_NODE child under specified XML Node
*
* @param nodeXML XML node from which to start searching
* @return The TEXT_NODE value (String) if any exist or null
* * @throws AttributeNotFoundException if attribute does not exist or if can not resolve
* reference to global parameter/property included in atribute's textual/string value
*/
public String getText(org.w3c.dom.Node nodeXML) throws AttributeNotFoundException{
return getText(nodeXML,true);
}
/**
* Searches for specific child node name under specified XML Node
*
* @param nodeXML XML node from which to start searching
* @param childNodeName name of the child node to be searched for
* @return childNode if exist under specified name or null
*/
public org.w3c.dom.Node getChildNode(org.w3c.dom.Node nodeXML, String childNodeName) {
org.w3c.dom.Node childNode;
org.w3c.dom.NodeList list;
if (nodeXML.hasChildNodes()) {
list = nodeXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
childNode = list.item(i);
if (childNodeName.equals(childNode.getNodeName())) {
return childNode;
} else {
childNode = getChildNode(childNode, childNodeName);
if (childNode != null) {
return childNode;
}
}
}
}
return null;
}
/**
* Gets the childNodes attribute of the ComponentXMLAttributes object
*
* @param nodeXML Description of the Parameter
* @param childNodeName Description of the Parameter
* @return The childNodes value
*/
public org.w3c.dom.Node[] getChildNodes(org.w3c.dom.Node nodeXML, String childNodeName) {
org.w3c.dom.Node childNode;
org.w3c.dom.NodeList list;
List<Node> childNodesList = new LinkedList<Node>();
if (nodeXML.hasChildNodes()) {
list = nodeXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
childNode = list.item(i);
if (childNodeName.equals(childNode.getNodeName())) {
childNodesList.add(childNode);
}
}
}
return (org.w3c.dom.Node[]) childNodesList.toArray(new org.w3c.dom.Node[0]);
}
/**
* Converts XML Node's attributes to Properties object - hash of key-value pairs.
* Can omit/exclude certain attributes based on specified array of Strings - attribute
* names.
* @param exclude array of Strings - names of attributes to be excluded (can be null)
* @return Properties object with pairs [attribute name]-[attribute value]
*/
public Properties attributes2Properties(String[] exclude) {
Properties properties=new Properties();
Set<String> exception=new HashSet<String>();
String name;
if(exclude != null) Collections.addAll(exception,exclude);
for (int i=0; i<attributes.getLength();i++){
name=attributes.item(i).getNodeName();
if (!exception.contains(name)){
properties.setProperty(name,
refResolver.resolveRef(attributes.item(i).getNodeValue()));
}
}
return properties;
}
public void Properties2Attributes(Properties properties){
org.w3c.dom.Node node;
for (Iterator iter=properties.entrySet().iterator();iter.hasNext();){
Map.Entry entry=(Map.Entry)iter.next();
// check whether attribute of certain name already exists
if ((node=attributes.getNamedItem((String)entry.getKey())) != null){
node.setNodeValue((String)entry.getValue()); // just set the value
}else{
// create new attribute
org.w3c.dom.Attr attr=node.getOwnerDocument().createAttribute((String)entry.getKey());
attr.setValue((String)entry.getValue());
node.appendChild(attr);
}
}
}
/**
* Replaces references to parameters in string with parameters' values.
*
* @param input string in which references to parameters should be resolved
* (substituted with parameters' values)
* @return String with references resolved.
*/
public String resloveReferences(String input) throws AttributeNotFoundException{
return refResolver.resolveRef(input);
}
/**
* Determines whether resolving references is enabled/disabled.
*
* @return true if resolving references is enables.
*/
public boolean isResolveReferences(){
return this.refResolver.isResolve();
}
/**
* Enables/disables resolving references within string values to Properties.<br>
* Default behaviour is to resolve.
*
* @param resolve true to resolve references
*/
public void setResolveReferences(boolean resolve){
this.refResolver.setResolve(resolve);
}
}
/*
* End class StringUtils
*/
|
package org.cactoos.iterable;
/**
* Skipped iterable.
*
* <p>There is no thread-safety guarantee.</p>
*
* @param <T> Element type
* @since 0.34
*/
public final class Skipped<T> extends IterableEnvelope<T> {
/**
* Ctor.
* @param skip How many to skip
* @param src The underlying iterable
*/
@SafeVarargs
public Skipped(final int skip, final T... src) {
this(skip, new IterableOf<>(src));
}
/**
* Ctor.
* @param skip Count skip elements
* @param iterable Decorated iterable
*/
public Skipped(final int skip, final Iterable<? extends T> iterable) {
super(
new IterableOf<>(
() -> new org.cactoos.iterator.Skipped<>(
skip,
iterable.iterator()
)
)
);
}
}
|
package org.chocosolver.solver;
import gnu.trove.map.hash.TIntObjectHashMap;
import org.chocosolver.memory.EnvironmentBuilder;
import org.chocosolver.memory.IEnvironment;
import org.chocosolver.memory.trailing.EnvironmentTrailing;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.nary.cnf.PropFalse;
import org.chocosolver.solver.constraints.nary.cnf.PropTrue;
import org.chocosolver.solver.constraints.nary.cnf.SatConstraint;
import org.chocosolver.solver.constraints.nary.nogood.NogoodConstraint;
import org.chocosolver.solver.constraints.real.Ibex;
import org.chocosolver.solver.constraints.reification.ConDisConstraint;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.exception.SolverException;
import org.chocosolver.solver.objective.ObjectiveManager;
import org.chocosolver.solver.propagation.IPropagationEngine;
import org.chocosolver.solver.propagation.NoPropagationEngine;
import org.chocosolver.solver.propagation.PropagationTrigger;
import org.chocosolver.solver.variables.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* The <code>Model</code> is the header component of Constraint Programming.
* It embeds the list of <code>Variable</code> (and their <code>Domain</code>), the <code>Constraint</code>'s network,
* and a <code>IPropagationEngine</code> to pilot the propagation.<br/>
* <code>Model</code> includes a <code>AbstractSearchLoop</code> to guide the search loop: applying decisions and propagating,
* running backups and rollbacks and storing solutions.
*
* @author Xavier Lorca
* @author Charles Prud'homme
* @author Jean-Guillaume Fages
* @version 0.01, june 2010
* @see org.chocosolver.solver.variables.Variable
* @see org.chocosolver.solver.constraints.Constraint
* @since 0.01
*/
public class Model implements IModel {
/////////////////////////////////////// PRIVATE FIELDS /////////////////////////////////////////////////////////////
/** Settings to use with this solver */
private Settings settings = new Settings() {};
/** A map to cache constants (considered as fixed variables) */
private TIntObjectHashMap<IntVar> cachedConstants;
/** Variables of the model */
private Variable[] vars;
/** Index of the last added variable */
private int vIdx;
/** Constraints of the model */
private Constraint[] cstrs;
/** Index of the last added constraint */
private int cIdx;
/** Environment, based of the search tree (trailing or copying) */
private final IEnvironment environment;
/** Resolver of the model, controls propagation and search */
private final Solver solver;
/** Variable to optimize, possibly null. */
private Variable objective;
/** Precision to consider when optimizing a RealVariable */
private double precision = 0.0001D;
/** Model name */
private String name;
/** Stores this model's creation time */
private long creationTime;
/** Counter used to set ids to variables and propagators */
private int id = 1;
/** A MiniSat instance, useful to deal with clauses*/
protected SatConstraint minisat;
/** A MiniSat instance adapted to nogood management */
protected NogoodConstraint nogoods;
/** A CondisConstraint instance adapted to constructive disjunction management */
protected ConDisConstraint condis;
/** An Ibex (continuous constraint model) instance */
private Ibex ibex;
/** Enable attaching hooks to a model. */
private Map<String,Object> hooks;
/** Resolution policy (sat/min/max) */
private ResolutionPolicy policy = ResolutionPolicy.SATISFACTION;
/////////////////////////////////////// CONSTRUCTORS ///////////////////////////////////////////////////////////////
/**
* Creates a Model object to formulate a decision problem by declaring variables and posting constraints.
* The model is named <code>name</code> and it uses a specific backtracking <code>environment</code>.
*
* @param environment a backtracking environment to allow search
* @param name The name of the model (for logging purpose)
*/
public Model(IEnvironment environment, String name) {
this.name = name;
this.vars = new Variable[32];
this.vIdx = 0;
this.cstrs = new Constraint[32];
this.cIdx = 0;
this.environment = environment;
this.creationTime = System.currentTimeMillis();
this.cachedConstants = new TIntObjectHashMap<>(16, 1.5f, Integer.MAX_VALUE);
this.objective = null;
this.hooks = new HashMap<>();
this.solver = new Solver(this);
}
/**
* Creates a Model object to formulate a decision problem by declaring variables and posting constraints.
* The model is named <code>name</code> and uses the default (trailing) backtracking environment.
*
* @param name The name of the model (for logging purpose)
* @see Model#Model(org.chocosolver.memory.IEnvironment, String)
*/
public Model(String name) {
this(EnvironmentBuilder.buildFlatEnvironment(), name);
}
/**
* Creates a Model object to formulate a decision problem by declaring variables and posting constraints.
* The model uses the default (trailing) backtracking environment.
*
* @see Model#Model(org.chocosolver.memory.IEnvironment, String)
*/
public Model() {
this("Model-" + nextModelNum());
}
/** For autonumbering anonymous models. */
private static int modelInitNumber;
/** @return next model's number, for anonymous models. */
private static synchronized int nextModelNum() {
return modelInitNumber++;
}
/////////////////////////////////////// GETTERS ////////////////////////////////////////////////////////////////////
/**
* Get the creation time (in milliseconds) of the model (to estimate modeling duration)
* @return the time (in ms) of the creation of the model
*/
public long getCreationTime(){
return creationTime;
}
/**
* Get the resolution policy of the model
* @return the resolution policy of the model
* @see ResolutionPolicy
*/
public ResolutionPolicy getResolutionPolicy(){
return policy;
}
/**
* Get the map of constant IntVar the have default names to avoid creating multiple identical constants.
* Should not be called by the user.
* @return the map of constant IntVar having default names.
*/
public TIntObjectHashMap<IntVar> getCachedConstants() {
return cachedConstants;
}
/**
* The basic "true" constraint, which is always satisfied
* @return a "true" constraint
*/
public Constraint trueConstraint() {
return new Constraint("TRUE cstr", new PropTrue(boolVar(true)));
}
/**
* The basic "false" constraint, which is always violated
* @return a "false" constraint
*/
public Constraint falseConstraint() {
return new Constraint("FALSE cstr", new PropFalse(boolVar(false)));
}
/**
* Returns the unique and internal propagation and search object to solve this model.
* @return the unique and internal <code>Resolver</code> object.
*/
public Solver getSolver() {
return solver;
}
/**
* Returns the array of <code>Variable</code> objects declared in this <code>Model</code>.
* @return array of all variables in this model
*/
public Variable[] getVars() {
return Arrays.copyOf(vars, vIdx);
}
/**
* Returns the number of variables involved in <code>this</code>.
* @return number of variables in this model
*/
public int getNbVars() {
return vIdx;
}
/**
* Returns the i<sup>th</sup> variable within the array of variables defined in <code>this</code>.
* @param i index of the variable to return.
* @return the i<sup>th</sup> variable of this model
*/
public Variable getVar(int i) {
return vars[i];
}
/**
* Iterate over the variable of <code>this</code> and build an array that contains all the IntVar of the model.
* <b>excludes</b> BoolVar if includeBoolVar=false.
* It also contains FIXED variables and VIEWS, if any.
* @param includeBoolVar indicates whether or not to include BoolVar
* @return array of IntVars in <code>this</code> model
*/
public IntVar[] retrieveIntVars(boolean includeBoolVar) {
IntVar[] ivars = new IntVar[vIdx];
int k = 0;
for (int i = 0; i < vIdx; i++) {
int kind = (vars[i].getTypeAndKind() & Variable.KIND);
if (kind == Variable.INT || (includeBoolVar && kind == Variable.BOOL)) {
ivars[k++] = (IntVar) vars[i];
}
}
return Arrays.copyOf(ivars, k);
}
/**
* Iterate over the variable of <code>this</code> and build an array that contains the BoolVar only.
* It also contains FIXED variables and VIEWS, if any.
* @return array of BoolVars in <code>this</code> model
*/
public BoolVar[] retrieveBoolVars() {
BoolVar[] bvars = new BoolVar[vIdx];
int k = 0;
for (int i = 0; i < vIdx; i++) {
if ((vars[i].getTypeAndKind() & Variable.KIND) == Variable.BOOL) {
bvars[k++] = (BoolVar) vars[i];
}
}
return Arrays.copyOf(bvars, k);
}
/**
* Iterate over the variable of <code>this</code> and build an array that contains the SetVar only.
* It also contains FIXED variables and VIEWS, if any.
* @return array of SetVars in <code>this</code> model
*/
public SetVar[] retrieveSetVars() {
SetVar[] bvars = new SetVar[vIdx];
int k = 0;
for (int i = 0; i < vIdx; i++) {
if ((vars[i].getTypeAndKind() & Variable.KIND) == Variable.SET) {
bvars[k++] = (SetVar) vars[i];
}
}
return Arrays.copyOf(bvars, k);
}
/**
* Iterate over the variable of <code>this</code> and build an array that contains the RealVar only.
* It also contains FIXED variables and VIEWS, if any.
* @return array of RealVars in <code>this</code> model
*/
public RealVar[] retrieveRealVars() {
RealVar[] bvars = new RealVar[vIdx];
int k = 0;
for (int i = 0; i < vIdx; i++) {
if ((vars[i].getTypeAndKind() & Variable.KIND) == Variable.REAL) {
bvars[k++] = (RealVar) vars[i];
}
}
return Arrays.copyOf(bvars, k);
}
/**
* Returns the array of <code>Constraint</code> objects posted in this <code>Model</code>.
* @return array of posted constraints
*/
public Constraint[] getCstrs() {
return Arrays.copyOf(cstrs, cIdx);
}
/**
* Return the number of constraints posted in <code>this</code>.
* @return number of posted constraints.
*/
public int getNbCstrs() {
return cIdx;
}
/**
* Return the name of <code>this</code> model.
* @return this model's name
*/
public String getName() {
return name;
}
/**
* Return the backtracking environment of <code>this</code> model.
* @return the backtracking environment of this model
*/
public IEnvironment getEnvironment() {
return environment;
}
/**
* Return the (possibly null) objective variable
* @return a variable (null for satisfaction problems)
*/
public Variable getObjective() {
return objective;
}
/**
* In case of real variable(s) to optimize, a precision is required.
* @return the precision used
*/
public double getPrecision() {
return precision;
}
/**
* Returns the object associated with the named <code>hookName</code>
* @param hookName the name of the hook to return
* @return the object associated to the name <code>hookName</code>
*/
public Object getHook(String hookName){
return hooks.get(hookName);
}
/**
* Returns the map containing declared hooks.
* This map is mutable.
* @return the map of hooks.
*/
protected Map<String, Object> getHooks(){
return hooks;
}
/**
* Returns the unique constraint embedding a minisat model.
* A call to this method will create and post the constraint if it does not exist already.
* @return the minisat constraint
*/
public SatConstraint getMinisat() {
if (minisat == null) {
minisat = new SatConstraint(this);
minisat.post();
}
return minisat;
}
/**
* Return a constraint embedding a nogood store (based on a sat model).
* A call to this method will create and post the constraint if it does not exist already.
* @return the no good constraint
*/
public NogoodConstraint getNogoodStore() {
if (nogoods == null) {
nogoods = new NogoodConstraint(this);
nogoods.post();
}
return nogoods;
}
/**
* Return a constraint embedding a constructive disjunction store.
* A call to this method will create and post the constraint if it does not exist already.
* @return the constructive disjunction constraint
*/
public ConDisConstraint getConDisStore(){
if (condis == null) {
condis = new ConDisConstraint(this);
condis.post();
}
return condis;
}
/**
* Return the current settings for the solver
* @return a {@link org.chocosolver.solver.Settings}
*/
public Settings getSettings() {
return this.settings;
}
/////////////////////////////////////// SETTERS ////////////////////////////////////////////////////////////////////
/**
* Defines the variable to optimize according to <i>policy</i>.
* By default, each solution forces either :
* <ul>
* <li> for {@link ResolutionPolicy#MAXIMIZE}: to increase by one for {@link IntVar} (or {@link #precision} for {@link RealVar}) the objective lower bound, or</li>
* <li> for {@link ResolutionPolicy#MINIMIZE}: to decrease by one {@link IntVar} (or {@link #precision} for {@link RealVar}) the objective upper bound.</li>
* </ul>
* @see ObjectiveManager#strictIntVarCutComputer(ResolutionPolicy)
* @see ObjectiveManager#strictRealVarCutComputer(ResolutionPolicy, double)
* @see ObjectiveManager#setCutComputer(Function)
* @param policy optimisation policy (minimisation or maximisation)
* @param objective variable to optimize
*/
@SuppressWarnings("unchecked")
public <V extends Variable, N extends Number> void setObjective(ResolutionPolicy policy, V objective) {
if(objective == null){
assert policy == ResolutionPolicy.SATISFACTION;
clearObjective();
}else {
assert policy != ResolutionPolicy.SATISFACTION;
this.objective = objective;
this.policy = policy;
if ((objective.getTypeAndKind() & Variable.KIND) == Variable.REAL) {
getSolver().set(new ObjectiveManager<RealVar, Double>((RealVar) objective, policy, 0.00d,
ObjectiveManager.strictRealVarCutComputer(policy, precision)));
} else {
getSolver().set(new ObjectiveManager<IntVar, Integer>((IntVar) objective, policy,
ObjectiveManager.strictIntVarCutComputer(policy)));
}
}
}
/**
* Removes any objective and set problem to a satisfaction problem
*/
public void clearObjective() {
this.objective = null;
this.policy = ResolutionPolicy.SATISFACTION;
getSolver().set(ObjectiveManager.SAT());
}
/**
* In case of real variable to optimize, a precision is required.
* @param p the precision (default is 0.0001D)
*/
public void setPrecision(double p) {
this.precision = p;
}
/**
* Override the default {@link org.chocosolver.solver.Settings} object.
* @param defaults new settings
*/
public void set(Settings defaults) {
this.settings = defaults;
}
/**
* Adds the <code>hookObject</code> to store in this model, associated with the name <code>hookName</code>.
* A hook is a simple map "hookName" <-> hookObject.
* @param hookName name of the hook
* @param hookObject hook to store
*/
public void addHook(String hookName, Object hookObject){
this.hooks.put(hookName, hookObject);
}
/**
* Removes the hook named <code>hookName</code>
* @param hookName name of the hookObject to remove
*/
public void removeHook(String hookName){
this.hooks.remove(hookName);
}
/**
* Empties the hooks attached to this model.
*/
public void removeAllHooks(){
this.hooks.clear();
}
/**
* Changes the name of this model to be equal to the argument <code>name</code>.
* @param name the new name of this model.
*/
public void setName(String name){
this.name = name;
}
/////////////////////////////////////// RELATED TO VAR ////////////////////////////////////////
/**
* Link a variable to <code>this</code>. This is executed AUTOMATICALLY in variable constructor,
* so no checked are done on multiple occurrences of the very same variable.
* Should not be called by the user.
* @param variable a newly created variable, not already added
*/
public void associates(Variable variable) {
if (vIdx == vars.length) {
Variable[] tmp = vars;
vars = new Variable[tmp.length * 2];
System.arraycopy(tmp, 0, vars, 0, vIdx);
}
vars[vIdx++] = variable;
}
/**
* Unlink the variable from <code>this</code>.
* Should not be called by the user.
* @param variable variable to un-associate
*/
public void unassociates(Variable variable) {
if (variable.getNbProps() > 0) {
throw new SolverException("Try to remove a variable (" + variable.getName() + ")which is still involved in at least one constraint");
}
int idx = 0;
for (; idx < vIdx; idx++) {
if (variable == vars[idx]) break;
}
System.arraycopy(vars, idx + 1, vars, idx + 1 - 1, vIdx - (idx + 1));
vars[--vIdx] = null;
}
/**
* Get a free id to idendity unically a new variable.
* Should not be called by the user.
* @return a free id to use
*/
public int nextId() {
return id++;
}
/////////////////////////////////////// RELATED TO CSTR DECLARATION ////////////////////////////////////////
/**
* Posts constraints <code>cs</code> permanently in the constraints network of <code>this</code>:
* - add them to the data structure,
* - set the fixed idx,
* - checks for restrictions
*
* @param cs Constraints
* @throws SolverException if the constraint is posted twice, posted although reified or reified twice.
*/
public void post(Constraint... cs) throws SolverException{
_post(true, cs);
}
/**
* Add constraints to the model.
*
* @param permanent specify whether the constraints are added permanently (if set to true) or temporary (ie, should be removed on backtrack)
* @param cs list of constraints
* @throws SolverException if a constraint is posted twice, posted although reified or reified twice.
*/
private void _post(boolean permanent, Constraint... cs) throws SolverException{
boolean dynAdd = false;
// check if the resolution already started -> if true, dynamic addition
IPropagationEngine engine = getSolver().getEngine();
if (engine != NoPropagationEngine.SINGLETON && engine.isInitialized()) {
dynAdd = true;
}
// then prepare storage of the constraints
if (cIdx + cs.length >= cstrs.length) {
int nsize = cstrs.length;
while (cIdx + cs.length >= nsize) {
nsize *= 3 / 2 + 1;
}
Constraint[] tmp = cstrs;
cstrs = new Constraint[nsize];
System.arraycopy(tmp, 0, cstrs, 0, cIdx);
}
// specific behavior for dynamic addition and/or reified constraints
for (Constraint c : cs) {
for (Propagator p : c.getPropagators()) {
p.getConstraint().checkNewStatus(Constraint.Status.POSTED);
p.linkVariables();
}
if (dynAdd) {
engine.dynamicAddition(permanent, c.getPropagators());
}
c.declareAs(Constraint.Status.POSTED, cIdx);
cstrs[cIdx++] = c;
}
}
/**
* Posts constraints <code>cs</code> temporary, that is, they will be unposted upon backtrack.
* @param cs a set of constraints to add
* @throws ContradictionException if the addition of constraints <code>cs</code> detects inconsistency.
* @throws SolverException if a constraint is posted twice, posted although reified or reified twice.
*/
public void postTemp(Constraint... cs) throws ContradictionException {
for(Constraint c:cs) {
_post(false, c);
if (getSolver().getEngine() == NoPropagationEngine.SINGLETON || !getSolver().getEngine().isInitialized()) {
throw new SolverException("Try to post a temporary constraint while the resolution has not begun.\n" +
"A call to Model.post(Constraint) is more appropriate.");
}
for (Propagator propagator : c.getPropagators()) {
if (settings.debugPropagation()) {
IPropagationEngine.Trace.printFirstPropagation(propagator, settings.outputWithANSIColors());
}
PropagationTrigger.execute(propagator, getSolver().getEngine());
}
}
}
/**
* Remove permanently the constraint <code>c</code> from the constraint network.
*
* @param constraints the constraints to remove
* @throws SolverException if a constraint is unknown from the model
*/
public void unpost(Constraint... constraints) throws SolverException {
if (constraints != null) {
for (Constraint c : constraints) {
// 1. look for the constraint c
int idx = c.getCidxInModel();
c.declareAs(Constraint.Status.FREE, -1);
// 2. remove it from the network
Constraint cm = cstrs[--cIdx];
if (idx < cIdx) {
cstrs[idx] = cm;
cstrs[idx].declareAs(Constraint.Status.FREE, -1); // needed, to avoid throwing an exception
cstrs[idx].declareAs(Constraint.Status.POSTED, idx);
}
cstrs[cIdx] = null;
// 3. check if the resolution already started -> if true, dynamic deletion
IPropagationEngine engine = getSolver().getEngine();
if (engine != NoPropagationEngine.SINGLETON && engine.isInitialized()) {
engine.dynamicDeletion(c.getPropagators());
}
// 4. remove the propagators of the constraint from its variables
for (Propagator prop : c.getPropagators()) {
for (int v = 0; v < prop.getNbVars(); v++) {
prop.getVar(v).unlink(prop);
}
}
}
}
}
//////////////////////////////////////////// RELATED TO I/O ////////////////////////////////////////////////////////
/**
* Return a string describing the CSP defined in <code>this</code> model.
*/
@Override
public String toString() {
StringBuilder st = new StringBuilder(256);
st.append(String.format("\n Model[%s]\n", name));
st.append(String.format("\n[ %d vars -- %d cstrs ]\n", vIdx, cIdx));
st.append(String.format("Feasability: %s\n", getSolver().isFeasible()));
st.append("== variables ==\n");
for (int v = 0; v < vIdx; v++) {
st.append(vars[v].toString()).append('\n');
}
st.append("== constraints ==\n");
for (int c = 0; c < cIdx; c++) {
st.append(cstrs[c].toString()).append('\n');
}
return st.toString();
}
//////////////////////////////////////////// RELATED TO IBEX ///////////////////////////////////////////////////////
/**
* Get the ibex reference
* Creates one if none
*
* @return the ibex reference
*/
public Ibex getIbex() {
if (ibex == null) {
try {
ibex = new Ibex();
}catch (ExceptionInInitializerError ini){
throw new SolverException("Choco cannot initialize Ibex.\n" +
"The following option should be passed as VM argument: \"-Djava.library.path=/path/to/ibex/dynlib\"");
}
}
return ibex;
}
//////////////////////////////////////////// RELATED TO MODELING FACTORIES /////////////////////////////////////////
@Override
public Model _me(){
return this;
}
}
|
package dynamo.model.music;
import java.nio.file.Path;
import dynamo.manager.MusicManager;
import dynamo.model.Downloadable;
import dynamo.model.DownloadableStatus;
public class MusicAlbum extends Downloadable {
private String searchString;
private MusicQuality quality = MusicQuality.COMPRESSED;
private String allMusicURL;
private String artistName;
private String genre;
private Path folder;
public MusicAlbum( Long id, DownloadableStatus status, Path folder, String aka, String artistName, String albumName, String genre, MusicQuality quality, String allMusicURL) {
super( id, albumName, null, status, aka, -1, null );
this.artistName = artistName;
this.genre = genre;
this.allMusicURL = allMusicURL;
this.quality = quality;
this.folder = folder;
this.searchString = MusicManager.getSearchString( artistName, albumName );
}
public String getSearchString() {
return searchString;
}
public MusicQuality getQuality() {
return quality;
}
public void setQuality(MusicQuality quality) {
this.quality = quality;
}
public String getArtistName() {
return artistName;
}
public String getAllMusicURL() {
return allMusicURL;
}
public void setAllMusicURL(String allMusicURL) {
this.allMusicURL = allMusicURL;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public String toString() {
return String.format("%s - %s", artistName, getName());
}
@Override
public String getRelativeLink() {
return String.format("index.html#/music-album/%d", getId());
}
@Override
public int hashCode() {
return getSearchString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MusicAlbum) {
return ((MusicAlbum)obj).getSearchString().equals( getSearchString() );
}
return false;
}
public Path getFolder() {
return folder;
}
@Override
public Path determineDestinationFolder() {
if ( folder != null ) {
return folder;
} else {
return MusicManager.getInstance().getPath(getArtistName(), getName() );
}
}
}
|
package org.example.seed.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.example.seed.catalog.ChefStatus;
import org.example.seed.constraint.Curp;
import org.example.seed.constraint.Rfc;
import org.example.seed.group.chef.ChefCreateGroup;
import org.example.seed.group.chef.ChefRegisterGroup;
import org.example.seed.group.chef.ChefUpdateGroup;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
import java.util.UUID;
@Data
@EqualsAndHashCode(callSuper = true)
public class Chef extends Dates {
@NotNull(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
@Size(min = 36, max = 36, groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
private String id;
@Null(groups = {ChefCreateGroup.class})
@Rfc(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
@NotNull(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
@Size(min = 13, max = 13, groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
private String rfc;
@Null(groups = {ChefCreateGroup.class})
@Curp(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
@NotNull(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
@Size(min = 18, max = 18, groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
private String curp;
@Null(groups = {ChefCreateGroup.class, ChefRegisterGroup.class})
@Min(value = 0, groups = {ChefCreateGroup.class, ChefRegisterGroup.class, ChefUpdateGroup.class})
@Max(value = 5, groups = {ChefCreateGroup.class, ChefRegisterGroup.class, ChefUpdateGroup.class})
private Float rating;
@NotNull(groups = {ChefRegisterGroup.class, ChefUpdateGroup.class})
private ChefStatus status;
private boolean active;
@Valid
@NotNull(groups = {ChefCreateGroup.class, ChefRegisterGroup.class, ChefUpdateGroup.class})
private Account account;
@Valid
@NotEmpty(groups = {ChefUpdateGroup.class})
@Null(groups = {ChefCreateGroup.class, ChefRegisterGroup.class})
private List<Telephone> telephones;
public Chef() {
this.id = UUID.randomUUID().toString();
}
}
|
package entity;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import tile.Tile;
import util.Animation;
import util.EnumSide;
import util.ImageManipulator;
import util.Resources;
import util.Texture;
import web.Shareable;
import main.GamePanel;
import map.Map;
public class EntityPlayer extends Entity implements Shareable{
public int speedX = 0, speedY = 0;
private final int MAX_SPEEDX = 3, MAX_SPEEDY = 10;
private int jumpCountDown = 0;
private boolean isJumping = false;
private int startx,starty;
private String name;
private Texture stillLeft, stillRight;
private Animation leftAnim, rightAnim, leftJumpAnim, rightJumpAnim;
private EntityShotPortal_Blue shotPortalBlue;
private EntityShotPortal_Red shotPortalRed;
private IEntityPortal_Red redportal;
private IEntityPortal_Blue blueportal;
private boolean willShootBlue = true;
private String username;
public EntityPlayer(int x, int y,String name,String username_){
this(x,y,name);
username = username_;
}
private boolean inPortalVert = false;
private boolean inPortalHoriz = false;
private int tempY = 0;
public EntityPlayer(int x, int y,String name){
setX(x);
setY(y);
startx = x;
starty = y;
this.name = name;
boolean isMel = name.equals("Mel");
//image = ImageManipulator.loadImage("error.png");
//rightImage = Resources.getPlayer("Jeff\\walk_1");
//leftImage = ImageManipulator.horizontalFlip(rightImage);
String[] rightImgNames = {"walk_1","walk_2","walk_3","walk_4","walk_5","walk_6"};
BufferedImage[] rightImages = new BufferedImage[rightImgNames.length];
BufferedImage[] leftImages = new BufferedImage[rightImgNames.length];
for(int i = 0; i < rightImgNames.length; i++){
Texture img = Resources.getPlayer(((isMel)? "Chell" : name)+"\\"+rightImgNames[i]);
if(isMel)img.replaceColors(new Color(255,147,0), new Color(91,170,255)).replaceColors(new Color(0,0,0),new Color(255,226,81)).replaceColors(new Color(255,223,215),new Color(255,206,193));
rightImages[i] = img;
leftImages[i] = ImageManipulator.horizontalFlip(img);
}
leftAnim = new Animation(leftImages,0);
rightAnim = new Animation(rightImages,0);
String[] jumpNames = {"jump_1","jump_2","jump_3","jump_4","jump_5","jump_6","jump_7","jump_8","jump_9","jump_10","jump_11","jump_12"};
rightImages = new BufferedImage[jumpNames.length];
leftImages = new BufferedImage[jumpNames.length];
for(int i = 0; i < jumpNames.length; i++){
Texture img = Resources.getPlayer(((isMel)? "Chell" : name)+"\\"+jumpNames[i]);
if(isMel)img.replaceColors(new Color(255,147,0), new Color(91,170,255)).replaceColors(new Color(0,0,0),new Color(255,226,81)).replaceColors(new Color(255,223,215),new Color(255,206,193));
rightImages[i] = img;
leftImages[i] = ImageManipulator.horizontalFlip(img);
}
leftJumpAnim = new Animation(leftImages,0);
rightJumpAnim = new Animation(rightImages,0);
stillRight = Resources.getPlayer(((isMel)? "Chell" : name)+"\\still");
if(isMel)stillRight.replaceColors(new Color(255,147,0), new Color(91,170,255)).replaceColors(new Color(0,0,0),new Color(255,226,81)).replaceColors(new Color(255,223,215),new Color(255,206,193));
stillLeft = new Texture( ImageManipulator.horizontalFlip(stillRight));
setImage(rightAnim.next());
boundingBox = new Rectangle(x,y,image.getWidth(),image.getHeight());
}
public void update(){
processKeys();
testforportals();
if(inPortalVert)System.out.println("In portal vert!");
if(inPortalHoriz)System.out.println("In portal horiz!");
}
public void testforportals(){
IEntityPortal[] portals = {(IEntityPortal) redportal,(IEntityPortal) blueportal};
for(IEntityPortal portal : portals){
if(portal != null){
if(portal.isHorizontal() && portal.getDir() == EnumSide.TOP){
if(getX() >= portal.getX() && getX() <= portal.getX()+16 && getY() >= portal.getY()-image.getHeight()-1 && getY() <= portal.getY()+16){
inPortalHoriz = true;
}else{
if(inPortalHoriz){
inPortalHoriz = false;
System.out.println("Teleporting");
teleportToOtherPortal(portal);
}
}
}else if(!portal.isHorizontal() && portal.getDir() == EnumSide.LEFT){ //isVertical
if(getX() >= portal.getX()-image.getWidth() && getX() <= portal.getX()+16 && getY() >= portal.getY()-2 && getY() <= portal.getY()+6){
inPortalVert = true;
System.out.println("in left portal");
jumpCountDown = 0;
isJumping = false;
speedY = 0;
tempY = getY();
}else if(inPortalVert){
inPortalVert = false;
System.out.println("Teleporting");
teleportToOtherPortal(portal);
}
}else if(!portal.isHorizontal() && portal.getDir() == EnumSide.RIGHT){
if(getX() >= portal.getX()-16 && getX() <= portal.getX()+image.getWidth()-16 && getY() >= portal.getY() && getY() <= portal.getY()+6){
inPortalVert = true;
System.out.println("in right portal");
jumpCountDown = 0;
isJumping = false;
speedY = 0;
tempY = getY();
}else if(inPortalVert){
inPortalVert = false;
System.out.println("Teleporting");
teleportToOtherPortal(portal);
}
}
}
}
}
public void teleportToOtherPortal(IEntityPortal portal){
IEntityPortal other = portal;
//other = portal.getOtherPortal();
if(other.isHorizontal() && other.getDir() == EnumSide.BOTTOM){
int newx = other.getX();
int newy = other.getY()+4;
setX(newx);
setY(newy);
System.out.println("Teleporting to : "+newx+", "+newy+" with Dir = BOTTOM");
}else if(other.isHorizontal() && other.getDir() == EnumSide.TOP){
int newx = other.getX();
int newy = other.getY()-16;
setX(newx);
setY(newy);
System.out.println("Teleporting to : "+newx+", "+newy+" with Dir = TOP");
}else if (other.getDir() == EnumSide.RIGHT){
int newx = other.getX()+4;
int newy = other.getY();
setX(newx);
setY(newy);
System.out.println("Teleporting to : "+newx+", "+newy+" with Dir = RIGHT");
}else{
int newx = other.getX()-1-image.getWidth();
int newy = other.getY();
setX(newx);
setY(newy);
System.out.println("Teleporting to : "+newx+", "+newy+" with Dir = LEFT");
}
}
public boolean willShootBlue(){return willShootBlue;}
public void mouseClicked(int x, int y){
x=(x/2);
y=(y/2);
int fromX = getX() + 12;
int fromY = getY() + 18;
if (getDirection()[0] < 0)
fromX = getX() + 5;
if(willShootBlue){
//if (blueportal!=null)
//remove last blue portal?
shotPortalBlue = new EntityShotPortal_Blue(x,y,fromX,fromY,this);
shotPortalBlue.setMap(map);
if(shotPortalBlue.go())
willShootBlue = false;
}else{
shotPortalRed = new EntityShotPortal_Red(x,y,fromX,fromY,this);
shotPortalRed.setMap(map);
if(shotPortalRed.go())
willShootBlue = true;
}//*/
}
public void mouseRightClicked()//switch portal to other color; we may want it to be a button but I though mouse would work well.
{
willShootBlue = !willShootBlue;
}
public boolean isJumping(){
return (jumpCountDown != 0);
}
public void processKeys(){
boolean[] keys = GamePanel.instance.keys;
if(keys[KeyEvent.VK_D]){
setImage((isJumping())? rightJumpAnim.next() : rightAnim.next());
if(moveRight()){
setImage((isJumping())? rightJumpAnim.back() : rightAnim.back());
}
}else if(keys[KeyEvent.VK_A]){
setImage((isJumping())? leftJumpAnim.next() : leftAnim.next());
if(moveLeft()){
setImage((isJumping())? leftJumpAnim.back() : leftAnim.back());
}
}else{
//System.out.print("Not moving");
if(speedX < 0){
//speedX+=1;
moveRight();
}
else if(speedX > 0){
//speedX -= 1;
moveLeft();
}
//System.out.println(" speedX = "+speedX);
}
if(keys[KeyEvent.VK_W] && jumpCountDown == 0 && !isJumping){
jumpCountDown = 10;
isJumping = true;
jump();
}else{
if(jumpCountDown != 0){
jumpCountDown
if (GamePanel.debug)
System.out.println("Jump Countdown = "+jumpCountDown);
int newy = getY()+ ((speedY < 0)? speedY++ : speedY);
int x = Map.pixelsToTiles(getX());
int y = Map.pixelsToTiles(newy);
Tile t= map.getTile(y, x);
if((t != null && t.boundingBox(0, 0) != null)){
speedY = 0;
setY(Map.tilesToPixels(y)+16);
fall();
leftJumpAnim.reset();
rightJumpAnim.reset();
}else
setY(newy);
}else{
fall();
leftJumpAnim.reset();
rightJumpAnim.reset();
}
/*if(speedY < 0){
fall();
}else if(speedY > 0){
jump();
}*/
}
if(!keys[KeyEvent.VK_W]&& !keys[KeyEvent.VK_A]&& !keys[KeyEvent.VK_D] && !keys[KeyEvent.VK_S] ){
int[] dir = getDirection();
if(dir[0] == -1){
setImage(stillLeft);
}else{
setImage(stillRight);
}
}
int x = Map.pixelsToTiles(getX());
int y = Map.pixelsToTiles(getY());
Tile t = map.getTile(y, x);
if(!inPortalVert && (t != null && speedX == 0 && speedY == 0)){
setY(getY()-1);
}
if(getX()<0)setX(0);
if(getX()>(map.getPreferredSize().width/2)-16)setX((map.getPreferredSize().width/32)-16);
if(getY()>(map.getPreferredSize().height/2))kill();
}
public int getSpeedX(){ return speedX; }
public void kill(){
System.out.println("player died!");
setX(startx);
setY(starty);
map.reset();
}
@Override
public void draw(Graphics2D g){
super.draw(g);
//System.out.println(name()+" drawing!");
if(redportal != null)
redportal.draw(g);
if(blueportal != null)
blueportal.draw(g);
}
public int getSpeedY(){ return speedY; }
public void jump(){
speedY = -6;
/*for(int i = 0; i < speedY; i++){
y = Map.pixelsToTiles(newy+i);
t = map.getTile(y,x);
if(t == null){
setX(newy+i);
return;
}
}*
return;
}else
setY(newy);
**/
}
public boolean moveLeft(){
int newx = getX()+((speedX == 0)? speedX = -1 : (speedX > 0)? speedX-- : (Math.abs(speedX) < MAX_SPEEDX)? speedX-- : speedX);
int x = Map.pixelsToTiles(newx);
int y = Map.pixelsToTiles(getY());
int y2 = Map.pixelsToTiles(getY()+16);
int x2 = Map.pixelsToTiles(newx+16);
Tile t = map.getTile(y, x);
Tile t2 = map.getTile(y2,x);
if(!inPortalHoriz && ((t != null && t.boundingBox(0, 0) != null) || (t2 != null && t2.boundingBox(0, 0) != null)) ){
setX(Map.tilesToPixels(x)+16);
speedX = 0;
/*for(int i = 0; i < speedX; i++){
x = Map.pixelsToTiles(newx+i);
t = map.getTile(y,x);
if(t == null){
setX(newx+i);
return;
}
}*/
return true;
}else{
setX(newx);
return false;
}
}
public boolean moveRight(){
int newx = getX()+((speedX == 0)? speedX =1 : (speedX < 0)? speedX++ : (Math.abs(speedX) < MAX_SPEEDX)? speedX++ : speedX)+16;
int x = Map.pixelsToTiles(newx);
int y = Map.pixelsToTiles(getY());
int y2 = Map.pixelsToTiles(getY()+16);
Tile t = map.getTile(y, x);
Tile t2 = map.getTile(y2, x);
if(!inPortalHoriz && ((t != null && t.boundingBox(0, 0) != null) || (t2 != null && t2.boundingBox(0, 0) != null)) ){
setX(Map.tilesToPixels(x)-16);
speedX = 0;
/*for(int i = 0; i < speedX; i++){
x = Map.pixelsToTiles(newx-i);
t = map.getTile(y,x);
if(t == null){
setX(newx-i);
return;
}
}*/
return true;
}else{
setX(newx-16);
return false;
}
}
public void fall(){
if(inPortalVert){
setY(tempY);
}
int newy = getY()+((speedY == 0)? speedY = 1 :(speedY < 0)? speedY+=1.5 : (Math.abs(speedY) < MAX_SPEEDY)? speedY+=1.5 : speedY)+32;
int x = Map.pixelsToTiles(getX());
int y = Map.pixelsToTiles(newy);
int x2 = Map.pixelsToTiles(getX()+16);
Tile t = map.getTile(y, x);
Tile t2 =map.getTile(y, x2);
if(!inPortalVert && ((t != null && t.boundingBox(0, 0) != null) || (t2 != null && t2.boundingBox(0, 0) != null))){
setY(Map.tilesToPixels(y)-32);
speedY = 0;
isJumping = false;
/*for(int i = 0; i < speedY; i++){
y = Map.pixelsToTiles(newy-i);
t = map.getTile(y,x);
if(t == null){
setX(newy-i);
return;
}
}*/
return;
}else
setY(newy-32);
}
public void setRedPortal(IEntityPortal_Red portal){
if (GamePanel.debug)
System.out.println("Setting red portal");
redportal =portal;
redportal.setOtherPortal(blueportal);
if(blueportal!=null)
blueportal.setOtherPortal(redportal);
}
public void setBluePortal(IEntityPortal_Blue portal){
if (GamePanel.debug)
System.out.println("Setting blue portal");
blueportal = portal;
blueportal.setOtherPortal(redportal);
if(redportal != null)
redportal.setOtherPortal(blueportal);
}
/** gather any data to share with other player and package it, returning a 2D String array, containing key,value pairs.
* All values will be CSV formatted by Web.java
{{"Key1","Value1"},
{"Key2","Value2"},
{"Key3","Value3"}} */
@Override
public String[][] packData() {
String[] xRow = new String[] {"x",((Integer)getX()).toString()};
String[] yRow = new String[] {"y",((Integer)getY()).toString()};
//TODO: Add other vars as needed, like character image, etc.
return new String[][]{xRow,yRow};
}
/** update all internal variables to new values based on data packed by a different client.
* Should follow exact same pattern for decoding as it does for encoding.
*/
@Override
public void unpackData(String[][] update) {
for(String[] row : update)//loop through each item to use with this frame update
{
switch (row[0]){
case "x":
setX(Integer.decode(row[1]));
break;
case "y":
setY(Integer.decode(row[1]));
break;
}
}
}
@Override//not used in the player class, but is in other entities.
public int getIdentifier() {
return 0;
}
public String getUsername() {
return username;
}
public void setUsername(String username_) {
username = username_;
}
public IEntityPortal_Red getRedPortal(){ return redportal; }
public IEntityPortal_Blue getBluePortal(){ return blueportal;}
}
|
package com.twitter.intellij.pants.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class ExternalProjectUtil {
public static void refresh(@NotNull Project project, ProjectSystemId id) {
// This code needs to run on the dispatch thread, but in some cases
// refreshAllProjects() is called on a non-dispatch thread; we use
// invokeLater() to run in the dispatch thread.
ApplicationManager.getApplication().invokeAndWait(
() -> {
ApplicationManager.getApplication().runWriteAction(() -> FileDocumentManager.getInstance().saveAllDocuments());
final ImportSpecBuilder specBuilder = new ImportSpecBuilder(project, id);
ProgressExecutionMode executionMode = ApplicationManager.getApplication().isUnitTestMode() ||
Objects.equals(System.getenv("PANTS_PLUGIN_SYNC_REFRESH"), "true") ?
ProgressExecutionMode.MODAL_SYNC : ProgressExecutionMode.IN_BACKGROUND_ASYNC;
specBuilder.use(executionMode);
ExternalSystemUtil.refreshProjects(specBuilder);
});
}
public static boolean isExternalProject(@NotNull Project project, ProjectSystemId id) {
return ContainerUtil.exists(
ModuleManager.getInstance(project).getModules(),
module -> isExternalModule(module, id)
);
}
public static boolean isExternalModule(@NotNull Module module, ProjectSystemId id) {
final String systemId = module.getOptionValue(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
return StringUtil.equals(systemId, id.getId());
}
}
|
package com.sics.sicsthsense.core;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Resource {
@JsonProperty
private long id;
@JsonProperty
private String label;
private int version;
public Resource() {
this.id = -1;
this.label = "";
}
public Resource(long id, String label) {
this.id = id;
this.label = label;
}
public long getId() { return id; }
public String getLabel() { return label; }
public String getOwner_id() { return null; }
public String getPolling_period(){ return "-1"; }
public String getLast_polled() { return "-1"; }
public String getPolling_url() { return "null"; }
public String getPolling_authentication_key() { return "null"; }
public String getDescription() { return "null"; }
public String getParent_id() { return "-1"; }
public String getSecret_key() { return "null"; }
public String getVersion() { return "-1"; }
public String getLast_posted() { return "-1"; }
public void setId(long id) { this.id = id; }
public void setOwner_id(String p) {}
public void setLabel(String label) { this.label = label; }
public void setPolling_period(String p) {}
public void setLast_polled(String p) {}
public void setPolling_url(String p) {}
public void setPolling_authentication_key(String p) {}
public void setDescription(String p) {}
public void setParent_id(String p) {}
public void setSecret_key(String p) {}
public void setVersion(String p) {}
public void setLast_posted(String p) {}
}
|
package org.xtreemfs.common.clients;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.xtreemfs.common.ReplicaUpdatePolicies;
import org.xtreemfs.common.clients.internal.OpenFileList;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.uuids.UUIDResolver;
import org.xtreemfs.foundation.pbrpc.client.PBRPCException;
import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication;
import org.xtreemfs.foundation.pbrpc.client.RPCResponse;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Setattrs;
import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.XCap;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntries;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntry;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Stat;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.StatVFS;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.XAttr;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.getattrResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.getxattrResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.listxattrResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.openResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.unlinkResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.xtreemfs_get_suitable_osdsRequest;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.xtreemfs_get_suitable_osdsResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.xtreemfs_replica_addRequest;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.xtreemfs_replica_removeRequest;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.xtreemfs_update_file_sizeRequest;
/**
*
* @author bjko
*/
public class Volume {
private final MRCServiceClient mrcClient;
final UUIDResolver uuidResolver;
private final String volumeName;
private final UserCredentials userCreds;
protected final OSDServiceClient osdClient;
private final OpenFileList ofl;
private final int maxRetries;
private static final VivaldiCoordinates emptyCoordinates;
static {
emptyCoordinates = VivaldiCoordinates.newBuilder().setLocalError(0).setXCoordinate(0).setYCoordinate(0).build();
}
/*
* private final LRUCache<String,CachedXAttr> xattrCache;
*
* private final int mdCacheTimeout_ms;
*/
Volume(OSDServiceClient osdClient, MRCServiceClient client, String volumeName, UUIDResolver uuidResolver,
UserCredentials userCreds) {
this(osdClient, client, volumeName, uuidResolver, userCreds, 0, 5);
}
Volume(OSDServiceClient osdClient, MRCServiceClient client, String volumeName, UUIDResolver uuidResolver,
UserCredentials userCreds, int mdCacheTimeout_ms, int maxRetries) {
this.mrcClient = client;
this.volumeName = volumeName.endsWith("/") ? volumeName : volumeName + "/";
this.uuidResolver = uuidResolver;
this.userCreds = userCreds;
this.osdClient = osdClient;
this.maxRetries = maxRetries;
this.ofl = new OpenFileList(client);
/*
* this.xattrCache = new LRUCache<String, CachedXAttr>(2048);
* this.mdCacheTimeout_ms = mdCacheTimeout_ms;
*/
ofl.start();
}
/**
* same semantics as File.list()
*
* @param path
* @param cred
* @return
* @throws IOException
*/
public String[] list(String path) throws IOException {
return list(path, userCreds);
}
public String[] list(String path, UserCredentials userCreds) throws IOException {
RPCResponse<DirectoryEntries> response = null;
final String fixedVol = fixPath(volumeName);
final String fixedPath = fixPath(path);
try {
response = mrcClient.readdir(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0, 0, true,
0);
DirectoryEntries entries = response.get();
String[] list = new String[entries.getEntriesCount()];
for (int i = 0; i < list.length; i++) {
list[i] = entries.getEntries(i).getName();
}
return list;
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
return null;
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public DirectoryEntry[] listEntries(String path, UserCredentials userCreds) throws IOException {
RPCResponse<DirectoryEntries> response = null;
path = path.replace("
final String fixedVol = fixPath(volumeName);
final String fixedPath = fixPath(path);
try {
response = mrcClient.readdir(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0, 0, false,
0);
DirectoryEntries entries = response.get();
DirectoryEntry[] list = new DirectoryEntry[entries.getEntriesCount()];
for (int i = 0; i < list.length; i++) {
list[i] = entries.getEntries(i);
Stat s = list[i].getStbuf();
OSDWriteResponse r = ofl.getLocalFS(volumeName + s.getIno());
if (r != null && r.hasTruncateEpoch()) {
// update with local file size, if cahced
if ((r.getTruncateEpoch() > s.getTruncateEpoch()) || (r.getTruncateEpoch() == s.getTruncateEpoch())
&& (r.getSizeInBytes() > s.getSize())) {
s = s.toBuilder().setSize(r.getSizeInBytes()).setTruncateEpoch(r.getTruncateEpoch()).build();
list[i] = list[i].toBuilder().setStbuf(s).build();
}
}
}
return list;
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
return null;
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public DirectoryEntry[] listEntries(String path) throws IOException {
return listEntries(path, userCreds);
}
public File getFile(String path, UserCredentials userCreds) {
return new File(this, userCreds, path);
}
public File getFile(String path) {
return new File(this, userCreds, path);
}
public String getName() {
return volumeName;
}
String fixPath(String path) {
path = path.replace("
if (path.endsWith("/"))
path = path.substring(0, path.length() - 1);
if (path.startsWith("/"))
path = path.substring(1);
return path;
}
public long getFreeSpace(UserCredentials userCreds) throws IOException {
RPCResponse<StatVFS> response = null;
try {
response = mrcClient.statvfs(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), 0);
StatVFS fsinfo = response.get();
return fsinfo.getBavail() * fsinfo.getBsize();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public long getFreeSpace() throws IOException {
return getFreeSpace(userCreds);
}
public StatVFS statfs(UserCredentials userCreds) throws IOException {
RPCResponse<StatVFS> response = null;
try {
response = mrcClient.statvfs(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), 0);
StatVFS fsinfo = response.get();
return fsinfo;
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public StatVFS statfs() throws IOException {
return statfs(userCreds);
}
public boolean isReplicateOnClose(UserCredentials userCreds) throws IOException {
String numRepl = getxattr(fixPath(volumeName), "xtreemfs.repl_factor", userCreds);
if (numRepl == null)
return false;
return numRepl.equals("1");
}
public boolean isReplicateOnClose() throws IOException {
return isReplicateOnClose(userCreds);
}
public boolean isSnapshot() {
return volumeName.indexOf('@') != -1;
}
public int getDefaultReplicationFactor(UserCredentials userCreds) throws IOException {
String numRepl = getxattr(fixPath(volumeName), "xtreemfs.repl_factor", userCreds);
try {
return Integer.valueOf(numRepl);
} catch (Exception ex) {
throw new IOException("cannot fetch replication factor", ex);
}
}
public int getDefaultReplicationFactor() throws IOException {
return getDefaultReplicationFactor(userCreds);
}
public long getUsedSpace(UserCredentials userCreds) throws IOException {
RPCResponse<StatVFS> response = null;
try {
response = mrcClient.statvfs(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), 0);
StatVFS fsinfo = response.get();
return (fsinfo.getBlocks() - fsinfo.getBavail()) * fsinfo.getBsize();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public long getUsedSpace() throws IOException {
return getUsedSpace(userCreds);
}
public long getDefaultObjectSize(UserCredentials userCreds) throws IOException {
RPCResponse<StatVFS> response = null;
try {
response = mrcClient.statvfs(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), 0);
StatVFS fsinfo = response.get();
return fsinfo.getBsize();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
public long getDefaultObjectSize() throws IOException {
return getDefaultObjectSize(userCreds);
}
public void enableSnapshots(boolean enable, UserCredentials userCreds) throws IOException {
RPCResponse r = null;
try {
r = mrcClient.setxattr(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), "",
"xtreemfs.snapshots_enabled", enable + "", 0);
r.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (r != null)
r.freeBuffers();
}
}
public void enableSnapshots(boolean enable) throws IOException {
enableSnapshots(enable, userCreds);
}
public void snapshot(String name, boolean recursive, UserCredentials userCreds) throws IOException {
RPCResponse r = null;
try {
r = mrcClient.setxattr(null, RPCAuthentication.authNone, userCreds, volumeName.replace("/", ""), "",
"xtreemfs.snapshots", "c" + (recursive ? "r" : "") + " " + name, 0);
r.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (r != null)
r.freeBuffers();
}
}
public void snapshot(String name, boolean recursive) throws IOException {
snapshot(name, recursive, userCreds);
}
Stat stat(String path, UserCredentials userCreds) throws IOException {
RPCResponse<getattrResponse> response = null;
try {
response = mrcClient.getattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), 0);
Stat s = response.get().getStbuf();
OSDWriteResponse r = ofl.getLocalFS(volumeName + s.getIno());
if (r != null && r.hasTruncateEpoch()) {
// update with local file size, if cahced
if ((r.getTruncateEpoch() > s.getTruncateEpoch()) || (r.getTruncateEpoch() == s.getTruncateEpoch())
&& (r.getSizeInBytes() > s.getSize())) {
s = s.toBuilder().setSize(r.getSizeInBytes()).setTruncateEpoch(r.getTruncateEpoch()).build();
}
}
return s;
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
String getxattr(String path, String name, UserCredentials userCreds) throws IOException {
RPCResponse<getxattrResponse> response = null;
try {
response = mrcClient.getxattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), name);
return response.get().getValue();
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENODATA)
return null;
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
String[] listxattr(String path, UserCredentials userCreds) throws IOException {
RPCResponse<listxattrResponse> response = null;
try {
response = mrcClient.listxattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), true);
listxattrResponse result = response.get();
List<XAttr> attrs = result.getXattrsList();
String[] names = new String[attrs.size()];
for (int i = 0; i < names.length; i++)
names[i] = attrs.get(i).getName();
return names;
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENODATA)
return null;
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void setxattr(String path, String name, String value, UserCredentials userCreds) throws IOException {
RPCResponse response = null;
try {
response = mrcClient.setxattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), name, value, 0);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void mkdir(String path, int permissions, UserCredentials userCreds) throws IOException {
RPCResponse response = null;
try {
response = mrcClient.mkdir(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName), fixPath(path),
permissions);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void touch(String path, UserCredentials userCreds) throws IOException {
RPCResponse response = null;
try {
response = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName), fixPath(path),
GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber(), 0700, 0, emptyCoordinates);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void rename(String src, String dest, UserCredentials userCreds) throws IOException {
RPCResponse response = null;
try {
response = mrcClient.rename(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName), fixPath(src),
fixPath(dest));
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void unlink(String path, UserCredentials userCreds) throws IOException {
RPCResponse<unlinkResponse> response = null;
RPCResponse ulnkResp = null;
try {
response = mrcClient
.unlink(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName), fixPath(path));
unlinkResponse resp = response.get();
final FileCredentials fcs = resp.hasCreds() ? resp.getCreds() : null;
if (fcs != null) {
// delete on OSDs
for (GlobalTypes.Replica r : fcs.getXlocs().getReplicasList()) {
final String headOSDuuid = r.getOsdUuids(0);
final ServiceUUID osdAddr = new ServiceUUID(headOSDuuid, uuidResolver);
osdAddr.resolve();
ulnkResp = osdClient.unlink(osdAddr.getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcs, fcs.getXcap().getFileId());
ulnkResp.get();
ulnkResp.freeBuffers();
ulnkResp = null;
}
}
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
if (ulnkResp != null)
ulnkResp.freeBuffers();
}
}
void storeFileSizeUpdate(String fileId, OSDWriteResponse resp, UserCredentials userCreds) {
ofl.fsUpdate(fileId, resp);
}
void pushFileSizeUpdate(String fileId, UserCredentials userCreds) throws IOException {
OSDWriteResponse owr = ofl.sendFsUpdate(fileId);
if (owr != null) {
XCap cap = ofl.getCapability(fileId);
RPCResponse response = null;
try {
if (!owr.hasSizeInBytes())
return;
long newSize = owr.getSizeInBytes();
int newEpoch = owr.getTruncateEpoch();
OSDWriteResponse.Builder osdResp = OSDWriteResponse.newBuilder().setSizeInBytes(newSize)
.setTruncateEpoch(newEpoch);
xtreemfs_update_file_sizeRequest fsBuf = xtreemfs_update_file_sizeRequest.newBuilder().setXcap(cap)
.setOsdWriteResponse(osdResp).build();
response = mrcClient.xtreemfs_update_file_size(null, RPCAuthentication.authNone, userCreds, fsBuf);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
}
void closeFile(RandomAccessFile file, String fileId, boolean readOnly, UserCredentials userCreds)
throws IOException {
pushFileSizeUpdate(fileId, userCreds);
try {
XCap cap = ofl.getCapability(fileId);
// notify MRC that file has been closed
RPCResponse response = null;
try {
response = mrcClient.xtreemfs_update_file_size(null, RPCAuthentication.authNone, userCreds, cap,
OSDWriteResponse.newBuilder().build(), true, emptyCoordinates);
response.get();
} catch (Exception ex) {
throw new IOException("cannot mark file as read-only for automatic replication", ex);
} finally {
if (response != null)
response.freeBuffers();
}
} finally {
ofl.closeFile(fileId, file);
}
}
RandomAccessFile openFile(File parent, int flags, int mode, UserCredentials userCreds) throws IOException {
RPCResponse<openResponse> response = null;
final String fullPath = fixPath(volumeName + parent.getPath());
final String fixedVol = fixPath(volumeName);
final String fixedPath = fixPath(parent.getPath());
try {
response = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, flags, mode, 0,
emptyCoordinates);
FileCredentials cred = response.get().getCreds();
boolean syncMd = (flags & GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_SYNC.getNumber()) > 0;
boolean rdOnly = cred.getXlocs().getReplicaUpdatePolicy()
.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY);
RandomAccessFile file = new RandomAccessFile(parent, this, osdClient, cred, rdOnly, syncMd, userCreds);
ofl.openFile(cred.getXcap(), file);
return file;
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
throw new FileNotFoundException("file '" + fullPath + "' does not exist");
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
XCap truncateFile(String fileId, UserCredentials userCreds) throws IOException {
RPCResponse<XCap> response = null;
try {
response = mrcClient.ftruncate(null, RPCAuthentication.authNone, userCreds, ofl.getCapability(fileId));
return response.get();
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
throw new FileNotFoundException("file '" + fileId + "' does not exist");
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
List<String> getSuitableOSDs(File file, int numOSDs, UserCredentials userCreds) throws IOException {
String fileId = getxattr(file.getPath(), "xtreemfs.file_id", userCreds);
RPCResponse<xtreemfs_get_suitable_osdsResponse> response = null;
try {
xtreemfs_get_suitable_osdsRequest request = xtreemfs_get_suitable_osdsRequest.newBuilder()
.setFileId(fileId).setNumOsds(numOSDs).build();
response = mrcClient.xtreemfs_get_suitable_osds(null, RPCAuthentication.authNone, userCreds, request);
return response.get().getOsdUuidsList();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void chmod(String path, int mode, UserCredentials userCreds) throws IOException {
Stat stbuf = Stat.newBuilder().setAtimeNs(0).setAttributes(0).setBlksize(0).setCtimeNs(0).setDev(0).setEtag(0)
.setGroupId("").setIno(0).setMode(mode).setMtimeNs(0).setNlink(0).setSize(0).setTruncateEpoch(0)
.setUserId("").build();
int toSet = Setattrs.SETATTR_MODE.getNumber();
RPCResponse response = null;
try {
response = mrcClient.setattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), stbuf, toSet);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void chown(String path, String user, UserCredentials userCreds) throws IOException {
Stat stbuf = Stat.newBuilder().setAtimeNs(0).setAttributes(0).setBlksize(0).setCtimeNs(0).setDev(0).setEtag(0)
.setGroupId("").setIno(0).setMode(0).setMtimeNs(0).setNlink(0).setSize(0).setTruncateEpoch(0)
.setUserId(user).build();
int toSet = Setattrs.SETATTR_UID.getNumber();
RPCResponse response = null;
try {
response = mrcClient.setattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), stbuf, toSet);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void chgrp(String path, String group, UserCredentials userCreds) throws IOException {
Stat stbuf = Stat.newBuilder().setAtimeNs(0).setAttributes(0).setBlksize(0).setCtimeNs(0).setDev(0).setEtag(0)
.setGroupId(group).setIno(0).setMode(0).setMtimeNs(0).setNlink(0).setSize(0).setTruncateEpoch(0)
.setUserId("").build();
int toSet = Setattrs.SETATTR_GID.getNumber();
RPCResponse response = null;
try {
response = mrcClient.setattr(null, RPCAuthentication.authNone, userCreds, fixPath(volumeName),
fixPath(path), stbuf, toSet);
response.get();
} catch (PBRPCException ex) {
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response != null)
response.freeBuffers();
}
}
void setACL(String path, List<String> aclEntries, UserCredentials userCreds) throws IOException {
// remove all existing entries first
List<String> existingACL = getACL(path, userCreds);
for (String entry : existingACL) {
int index = entry.lastIndexOf(':');
if (index == -1)
throw new IOException("existing ACL contains invalid entry: " + entry);
String entity = entry.substring(0, index);
if (!entity.equals("u:") && !entity.equals("g:") && !entity.equals("o:") && !entity.equals("m:"))
setxattr(path, "xtreemfs.acl", "x " + entity, userCreds);
}
// add all entries from the given list
for (String entry : aclEntries)
setxattr(path, "xtreemfs.acl", "m " + entry, userCreds);
}
List<String> getACL(String path, UserCredentials userCreds) throws IOException {
String aclAsCSV = getxattr(path, "xtreemfs.acl", userCreds);
StringTokenizer st = new StringTokenizer(aclAsCSV, ", ");
List<String> list = new LinkedList<String>();
while (st.hasMoreTokens())
list.add(st.nextToken());
return list;
}
static IOException wrapException(PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
return new FileNotFoundException(ex.getErrorMessage());
return new IOException(ex.getPOSIXErrno() + ": " + ex.getErrorMessage(), ex);
}
static IOException wrapException(InterruptedException ex) {
return new IOException("operation was interruped: " + ex, ex);
}
public void finalize() {
ofl.shutdown();
}
void addReplica(File file, int width, List<String> osdSet, int flags, UserCredentials userCreds) throws IOException {
RPCResponse<openResponse> response1 = null;
RPCResponse response3 = null;
final String fullPath = fixPath(volumeName + file.getPath());
final String fixedVol = fixPath(volumeName);
final String fixedPath = fixPath(file.getPath());
try {
org.xtreemfs.common.clients.Replica r = file.getReplica(0);
StripingPolicy sp = StripingPolicy.newBuilder().setStripeSize(r.getStripeSize()).setWidth(width)
.setType(r.getStripingPolicy()).build();
org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica newReplica = org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica
.newBuilder().addAllOsdUuids(osdSet).setReplicationFlags(flags).setStripingPolicy(sp).build();
response1 = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0,
GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), 0, emptyCoordinates);
FileCredentials oldCreds = response1.get().getCreds();
response1.freeBuffers();
response1 = null;
boolean readOnlyRepl = (oldCreds.getXlocs().getReplicaUpdatePolicy()
.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY));
xtreemfs_replica_addRequest request = xtreemfs_replica_addRequest.newBuilder().setNewReplica(newReplica)
.setFileId(oldCreds.getXcap().getFileId()).build();
response3 = mrcClient.xtreemfs_replica_add(null, RPCAuthentication.authNone, userCreds, request);
response3.get();
response3.freeBuffers();
response3 = null;
if (readOnlyRepl) {
if ((flags & GlobalTypes.REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber()) > 0) {
response1 = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0,
GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), 0, emptyCoordinates);
FileCredentials newCreds = response1.get().getCreds();
for (int objNo = 0; objNo < width; objNo++) {
ServiceUUID osd = new ServiceUUID(osdSet.get(objNo), uuidResolver);
response3 = osdClient
.read(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService,
newCreds, newCreds.getXcap().getFileId(), objNo, 0, 0, 1);
response3.get();
response3.freeBuffers();
response3 = null;
}
}
} else {
response1 = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0,
GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), 0, emptyCoordinates);
FileCredentials newCreds = response1.get().getCreds();
ServiceUUID osd = new ServiceUUID(osdSet.get(0), uuidResolver);
response3 = osdClient.xtreemfs_rwr_notify(osd.getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, newCreds);
response3.get();
response3.freeBuffers();
response3 = null;
}
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
throw new FileNotFoundException("file '" + fullPath + "' does not exist");
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response1 != null)
response1.freeBuffers();
if (response3 != null)
response3.freeBuffers();
}
}
void removeReplica(File file, String headOSDuuid, UserCredentials userCreds) throws IOException {
RPCResponse<openResponse> response1 = null;
RPCResponse<FileCredentials> response2 = null;
RPCResponse response3 = null;
final String fullPath = fixPath(volumeName + file.getPath());
final String fixedVol = fixPath(volumeName);
final String fixedPath = fixPath(file.getPath());
try {
response1 = mrcClient.open(null, RPCAuthentication.authNone, userCreds, fixedVol, fixedPath, 0,
GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), 0, emptyCoordinates);
FileCredentials oldCreds = response1.get().getCreds();
xtreemfs_replica_removeRequest request = xtreemfs_replica_removeRequest.newBuilder()
.setOsdUuid(headOSDuuid).setFileId(oldCreds.getXcap().getFileId()).build();
response2 = mrcClient.xtreemfs_replica_remove(null, RPCAuthentication.authNone, userCreds, request);
FileCredentials delCap = response2.get();
ServiceUUID osd = new ServiceUUID(headOSDuuid, uuidResolver);
boolean readOnlyRepl = (oldCreds.getXlocs().getReplicaUpdatePolicy()
.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY));
FileCredentials newCreds = FileCredentials.newBuilder().setXcap(delCap.getXcap())
.setXlocs(oldCreds.getXlocs()).build();
response3 = osdClient.unlink(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService,
newCreds, oldCreds.getXcap().getFileId());
response3.get();
} catch (PBRPCException ex) {
if (ex.getPOSIXErrno() == POSIXErrno.POSIX_ERROR_ENOENT)
throw new FileNotFoundException("file '" + fullPath + "' does not exist");
throw wrapException(ex);
} catch (InterruptedException ex) {
throw wrapException(ex);
} finally {
if (response1 != null)
response1.freeBuffers();
if (response2 != null)
response2.freeBuffers();
if (response3 != null)
response3.freeBuffers();
}
}
void shutdown() {
ofl.shutdown();
}
/**
* @return the maxRetries
*/
public int getMaxRetries() {
return maxRetries;
}
}
|
package net.silentchaos512.gems.compat.jei;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.IJeiHelpers;
import mezz.jei.api.IJeiRuntime;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.JEIPlugin;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import net.silentchaos512.gems.api.lib.EnumMaterialGrade;
import net.silentchaos512.gems.block.ModBlocks;
import net.silentchaos512.gems.item.ItemChaosStorage;
import net.silentchaos512.gems.item.ItemReturnHome;
import net.silentchaos512.gems.item.ModItems;
import net.silentchaos512.gems.lib.Names;
@JEIPlugin
public class SilentGemsPlugin implements IModPlugin {
public static IJeiHelpers jeiHelper;
@Override
public void onRuntimeAvailable(IJeiRuntime runtime) {
}
@Override
public void register(IModRegistry reg) {
jeiHelper = reg.getJeiHelpers();
IGuiHelper guiHelper = jeiHelper.getGuiHelper();
// Hide blocks/items
int any = OreDictionary.WILDCARD_VALUE;
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.gemLampInverted, 1, any));
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.gemLampInvertedDark, 1 , any));
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.gemLampLit, 1, any));
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.gemLampLitDark, 1, any));
// jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.chaosNode));
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModBlocks.fluffyPuffPlant));
jeiHelper.getItemBlacklist().addItemToBlacklist(new ItemStack(ModItems.toolRenderHelper));
// NBT ignores
jeiHelper.getNbtIgnoreList().ignoreNbtTagNames(EnumMaterialGrade.NBT_KEY);
jeiHelper.getNbtIgnoreList().ignoreNbtTagNames(ItemChaosStorage.NBT_CHARGE);
jeiHelper.getNbtIgnoreList().ignoreNbtTagNames(ModItems.returnHomeCharm, ItemReturnHome.NBT_READY);
// Descriptions
String descPrefix = "jei.silentgems.desc.";
reg.addDescription(new ItemStack(ModItems.gem, 1, OreDictionary.WILDCARD_VALUE),
descPrefix + Names.GEM);
}
}
|
package org.jdbdt;
/**
* Exception thrown by JDBDT due to an unexpected internal error.
*
* <p>
* Exceptions of this kind should never happen in principle.
* If they do, there is either likely a bug in JDBDT or something
* abnormal with the environment setup.
* </p>
*
* @since 0.1
*/
final class JDBDTInternalError extends Error {
/**
* Constructs exception with given cause.
* @param cause Cause for the exception.
*/
JDBDTInternalError(Throwable cause) {
super("Unexpected internal error", cause);
}
/**
* Constructs exception using supplied message.
* @param message Error message.
*/
JDBDTInternalError(String message) {
super(message);
}
/**
* Serial version UID.
*/
private static final long serialVersionUID = 1L;
}
|
package co.uk.niadel.napi.gen.structures;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.structure.MapGenStructure;
import co.uk.niadel.napi.annotations.Internal;
/**
* The registry for structures.
*
* @author Niadel
*/
public final class StructureRegistry
{
/**
* Contains the structures that will generate regardless of whether or not
* Map Features is enabled.
*/
public static List<MapGenStructure> nonMapFDependantStructures = new ArrayList<>();
/**
* Contains the structures that will generate only if Map Features is enabled.
*/
public static List<MapGenStructure> mapFDependantStructures = new ArrayList<>();
/**
* A Map containing the information to be added to IO.
*/
public static Map<Class, String> ioStructureInformation = new HashMap<>();
/**
* Adds a structure that will always generate, regardless of whether or not Map Features is enabled or disabled.
* @param structure The structure object to generate.
* @param structureClass The class of structure.
* @param shortStructId The shortened structure id of structureClass, I recommend to do something like "YOU_your_modid:SSid" for compatibility.
*/
public static void addNonMapFDependantStructure(MapGenStructure structure, Class structureClass, String shortStructId)
{
nonMapFDependantStructures.add(structure);
ioStructureInformation.put(structureClass, shortStructId);
}
/**
* Adds a structure that will only generate if Map Features is enabled. Same params as
* @see StructureRegistry#addNonMapFDependantStructure(net.minecraft.world.gen.structure.MapGenStructure, Class, String)
*/
public static void addMapFDependantStructure(MapGenStructure structure, Class structureClass, String shortStructId)
{
mapFDependantStructures.add(structure);
ioStructureInformation.put(structureClass, shortStructId);
}
/**
* Generates all Map Feature dependant structures.
* @param provider The provider to generate the structures in.
* @param worldObj The world object for provider.
* @param chunkCoordX Likely the chunk coord x.
* @param chunkCoordY Likely the chunk coord y.
* @param blocks An array of blocks to generate in.
*/
@Internal
public static void generateAllMapFDependantStructures(IChunkProvider provider, World worldObj, int chunkCoordX, int chunkCoordY, Block[] blocks)
{
for (MapGenStructure mapGenStructure : mapFDependantStructures)
{
mapGenStructure.func_151539_a(provider, worldObj, chunkCoordX, chunkCoordY, blocks);
}
}
/**
* Generates all non-Map Feature dependant structures. Params are the same as
* @see StructureRegistry#generateAllMapFDependantStructures
*/
@Internal
public static void generateAllNonMapFDependantStructures(IChunkProvider provider, World worldObj, int par1, int par2, Block[] blocks)
{
for (MapGenStructure structure : nonMapFDependantStructures)
{
structure.func_151539_a(provider, worldObj, par1, par2, blocks);
}
}
}
|
package rres.ondex.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.queryParser.ParseException;
import net.sourceforge.ondex.InvalidPluginArgumentException;
import net.sourceforge.ondex.core.ONDEXConcept;
import net.sourceforge.ondex.core.ONDEXGraph;
/**
* @author huf
* @date 10-03-2010
*
*/
public class ClientWorker implements Runnable {
static String[] SEARCH_MODES={"genome","qtl","list","network","countdocuments"};
/**
* network socket to listen on
*/
private Socket clientSocket;
/**
* Ondex interface provider
*/
private OndexServiceProvider ondexProvider;
/**
* Set network socket and Ondex interface provider
*
* @param socket
* @param provider
*/
public ClientWorker(Socket socket, OndexServiceProvider provider) {
this.clientSocket = socket;
this.ondexProvider = provider;
}
@Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
String request;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Request
String fromClient = in.readLine();
System.out.println("FromClient: "+fromClient);
request = "";
while(!fromClient.equals("Bye.")) {
try{
request = request+fromClient+"\n";
fromClient = in.readLine();
}
catch (Exception e) {
System.out.println(e.getMessage());
out.println("Bye.");
}
}
// Response
System.out.println("Calling to processRequest()");
out.println(processRequest(request));
out.println("Bye.");
}
catch (IOException e) {
System.out.println(e.getMessage());
out.println("Bye.");
}
}
protected String processRequest(String query) throws UnsupportedEncodingException {
System.out.println("Processing request...");
String keyword = "";
String mode = "";
String listMode = "";
List<QTL> qtls = new ArrayList<QTL>();
List<String> qtlString = new ArrayList<String>();
List<String> list = new ArrayList<String>();
// Split query
for(String param : query.split("&")) {
String pair[] = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
if(key.toLowerCase().startsWith("qtl")){
qtlString.add(value.trim());
}
else if(key.toLowerCase().equals("keyword")){
keyword = value.trim().replace("\n", "");
keyword = URLDecoder.decode(keyword, "UTF-8");
System.out.println("Keyword decoded: "+keyword);
}
else if(key.toLowerCase().equals("mode")){
mode = value.trim().replace("\n", "");
}
else if(key.toLowerCase().equals("list")){
Collections.addAll(list, value.split("\n"));
}
else if(key.toLowerCase().equals("listmode")){
listMode = value.trim();
}
}
boolean validQTL = false;
// QTLs
for(String region : qtlString){
String[] r = region.split(":");
String chrName;
int chrIndex;
long start, end;
String label = "";
try {
if(r.length == 3 || r.length == 4){
chrName = r[0];
start = Long.parseLong(r[1]);
end = Long.parseLong(r[2]);
if(r.length == 4){
label = r[3];
}
if(start < end) {
validQTL = true;
chrIndex = ondexProvider.chromBidiMap.inverseBidiMap().get(chrName);
QTL qtl = new QTL(chrIndex, chrName, Long.toString(start), Long.toString(end), label, "significant");
qtls.add(qtl);
}
}
if(!validQTL){
System.out.println(region+" not valid qtl region");
}
}
catch(Exception e){
System.out.println("Exception: "+region+" not valid qtl region. "+e.getCause());
}
}
// Call Ondex provider
if(keyword != null && keyword.length()>2) {
if(mode.equals("network")) { // applet
try {
return callApplet(keyword, qtls, list);
} catch (InvalidPluginArgumentException e) {
e.printStackTrace();
}
return "OndexWeb";
}
else if(mode.equals("counthits")) { //counts the hits in real-time for the search box
Hits hits = new Hits(keyword, ondexProvider);
//number of Lucene documents
Integer luceneCount = hits.getLuceneConcepts().size();
//number of Lucene documents related to genes
Integer luceneLinkedCount = hits.getLuceneDocumentsLinked();
//count unique genes linked to Lucene documents
Integer geneCount = hits.getNumConnectedGenes();
System.out.println("Number of matches: "+luceneCount.toString());
return (luceneCount+"|"+luceneLinkedCount+"|"+geneCount);
}else if(mode.equals("countloci")) { //counts the genes withina a loci for the Genome or QTL Search box
String[] loci = keyword.split("-");
String chr = loci[0];
Integer start = Integer.parseInt(loci[1]);
Integer end = Integer.parseInt(loci[2]);
return String.valueOf(ondexProvider.getGeneCount(chr, start, end));
}else if(mode.equals("evidencepath")) { //returns the path between an evidence and all connected genes
System.out.println("Creating Evidence Path for ONDEXID: "+keyword);
Integer evidenceOndexID = Integer.parseInt(keyword);
ONDEXGraph subGraph = ondexProvider.evidencePath(evidenceOndexID);
long timestamp = System.currentTimeMillis();
String fileName = timestamp+"evidencePath.oxl";
String exportPath = MultiThreadServer.props.getProperty("DataPath");
String request = "";
// Export graph
try {
boolean fileIsCreated = false;
try {
fileIsCreated = ondexProvider.exportGraph(subGraph, exportPath+fileName);
} catch (InvalidPluginArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(fileIsCreated) {
request = "FileCreated:"+fileName;
}
else {
System.out.println("NoFile");
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return request;
}else if(mode.equals("synonyms")){
// Synonym table file
long timestamp = System.currentTimeMillis();
String fileSynonymTable = timestamp+"SynonymTable.tab";
try {
ondexProvider.writeSynonymTable(keyword, MultiThreadServer.props.getProperty("DataPath") + fileSynonymTable);
System.out.println("Synonym table created");
return "File created:"+fileSynonymTable;
} catch (ParseException e) {
System.out.println("Synonym table could not be created");
e.printStackTrace();
}
return "SynonymTable";
}
else{
return callOndexProvider(keyword, mode, listMode, qtls, list);
}
}
else{
System.out.println("Not valid request.");
return "Not valid request.";
}
}
protected String callApplet(String keyword, List<QTL> qtls, List<String> list) throws UnsupportedEncodingException, InvalidPluginArgumentException {
String request = "";
Set<ONDEXConcept> genes = new HashSet<ONDEXConcept>();
// File name
long timestamp = System.currentTimeMillis();
String fileName = "result_"+timestamp+".oxl";
String exportPath = MultiThreadServer.props.getProperty("DataPath");
System.out.println("Call applet! Search genes "+list.size());
// Search Genes
if(!list.isEmpty()){
Set<ONDEXConcept> genesFromList = ondexProvider.searchGenes(list);
genes.addAll(genesFromList);
}
// Search Regions
if(!qtls.isEmpty()){
Set<ONDEXConcept> genesWithinQTLs = ondexProvider.searchQTLs(qtls);
genes.addAll(genesWithinQTLs);
}
// Find Semantic Motifs
ONDEXGraph subGraph = ondexProvider.findSemanticMotifs(genes, keyword);
// Export graph
try {
boolean fileIsCreated = false;
fileIsCreated = ondexProvider.exportGraph(subGraph, exportPath+fileName);
if(fileIsCreated) {
request = "FileCreated:"+fileName;
}
else {
System.out.println("NoFile");
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return request;
}
protected String callOndexProvider(String keyword, String mode, String listMode, List<QTL> qtl, List<String> list) {
// Setup file names
long timestamp = System.currentTimeMillis();
String fileGViewer = timestamp+"GViewer.xml";
String fileGeneTable = timestamp+"GeneTable.tab";
String fileEvidenceTable = timestamp+"EvidenceTabl.tab";
String request = "";
ArrayList<ONDEXConcept> genes = new ArrayList<ONDEXConcept>();
// Find genes from the user's list
Set<ONDEXConcept> userGenes = null;
if(list != null && list.size() > 0) {
userGenes = ondexProvider.searchGenes(list);
}
//find qtl in knowledgebase that match keywords
List<QTL> qtlDB = ondexProvider.findQTL(keyword);
//some logic to limit QTL size if too many are found
if(qtlDB.size() > 150){
System.out.println("Too many QTL found, remove not significant ones...");
for(QTL q : qtlDB){
if(!q.getSignificance().equalsIgnoreCase("significant")){
qtlDB.remove(q);
}
}
}
//add QTL from knowledgebase to QTL list from user
qtl.addAll(qtlDB);
System.out.println("Total number of QTL to display: "+qtl.size());
try {
// Genome search
if(Arrays.asList(SEARCH_MODES).contains(mode)){
System.out.println("Search mode: "+mode);
Hits qtlnetminerResults = new Hits(keyword, ondexProvider);
if(mode.equals("genome")){
genes = qtlnetminerResults.getSortedCandidates();
// find qtl and add to qtl list!
System.out.println("Number of genes "+genes.size());
}
else if(mode.equals("qtl")){
genes = qtlnetminerResults.getSortedCandidates();
System.out.println("Number of genes "+genes.size());
genes = ondexProvider.filterQTLs(genes, qtl);
System.out.println("Genes after QTL filter: "+genes.size());
}
if(list.size() > 0){
Set<ONDEXConcept> userList = ondexProvider.searchGenes(list);
if(mode.equals("qtl") && listMode.equals("GLrestrict")){
ArrayList<ONDEXConcept> userListArray = new ArrayList<ONDEXConcept>(userList);
userListArray = ondexProvider.filterQTLs(userListArray, qtl);
userList = new HashSet<ONDEXConcept>(userListArray);
}
System.out.println("userlist 1 "+userList.size());
qtlnetminerResults.setUsersGenes(userList);
}
if(genes.size() == 0){
System.out.println("NoFile: no genes found");
request = "NoFile:noGenesFound";
}
else {
// Gviewer Annotation File
if(ondexProvider.getReferenceGenome() == true){
ondexProvider.writeAnnotationXML(
genes, userGenes, qtl, MultiThreadServer.props.getProperty("DataPath")
+ fileGViewer, keyword, 100, qtlnetminerResults, listMode);
System.out.println("1.) Gviewer annotation ");
}else{
System.out.println("1.) No reference genome for Gviewer annotation ");
}
// Gene table file
boolean txtIsCreated = ondexProvider.writeTableOut(
genes, userGenes, qtl,
MultiThreadServer.props.getProperty("DataPath")
+ fileGeneTable);
System.out.println("2.) Gene table ");
// Evidence table file
boolean eviTableIsCreated = ondexProvider.writeEvidenceTable(qtlnetminerResults.getLuceneConcepts(),
userGenes, qtl, MultiThreadServer.props.getProperty("DataPath") + fileEvidenceTable);
System.out.println("3.) Evidence table ");
//Document count (only related with genes)
int docSize = ondexProvider.getMapEvidences2Genes(qtlnetminerResults.getLuceneConcepts()).size();
//Total documents
int totalDocSize = qtlnetminerResults.getLuceneConcepts().size();
// We have annotation and table file
if (txtIsCreated && eviTableIsCreated) {
request = "FileCreated:"+fileGViewer+":"+fileGeneTable+":"+fileEvidenceTable+":"+genes.size()+":"+docSize+":"+totalDocSize;
System.out.println("request is "+request);
}
}
}
}
catch (Exception e) {
System.out.println("exception "+e.getMessage());
e.printStackTrace();
}
System.out.println("request is "+request);
return request;
}
}
|
package org.lightmare.cache;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.utils.CollectionUtils;
/**
* Container class to save bean {@link Field} with annotation
* {@link PersistenceContext} and bean class
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
* @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters)
* @see org.lightmare.ejb.EjbConnector#connectToBean(MetaData)
* @see org.lightmare.ejb.EjbConnector#createRestHandler(MetaData)
* @see org.lightmare.ejb.handlers.BeanHandler
*/
public class MetaData {
// EJB bean class
private Class<?> beanClass;
//EJB bean implementation interfaces
private Class<?>[] interfaceClasses;
private Class<?>[] localInterfaces;
private Class<?>[] remoteInterfaces;
private Field transactionField;
private Collection<ConnectionData> connections;
private ClassLoader loader;
private AtomicBoolean inProgress = new AtomicBoolean();
private boolean transactional;
private TransactionAttributeType transactionAttrType;
private TransactionManagementType transactionManType;
private List<InjectionData> injects;
private Collection<Field> unitFields;
private Queue<InterceptorData> interceptors;
private BeanHandler handler;
public Class<?> getBeanClass() {
return beanClass;
}
public void setBeanClass(Class<?> beanClass) {
this.beanClass = beanClass;
}
public Class<?>[] getInterfaceClasses() {
return interfaceClasses;
}
public void setInterfaceClasses(Class<?>[] interfaceClasses) {
this.interfaceClasses = interfaceClasses;
}
public Class<?>[] getLocalInterfaces() {
return localInterfaces;
}
public void setLocalInterfaces(Class<?>[] localInterfaces) {
this.localInterfaces = localInterfaces;
}
public Class<?>[] getRemoteInterfaces() {
return remoteInterfaces;
}
public void setRemoteInterfaces(Class<?>[] remoteInterfaces) {
this.remoteInterfaces = remoteInterfaces;
}
public Field getTransactionField() {
return transactionField;
}
public void setTransactionField(Field transactionField) {
this.transactionField = transactionField;
}
public Collection<ConnectionData> getConnections() {
return connections;
}
public void setConnections(Collection<ConnectionData> connections) {
this.connections = connections;
}
/**
* Caches passed connection information
*
* @param connection
*/
public void addConnection(ConnectionData connection) {
if (connections == null) {
connections = new ArrayList<ConnectionData>();
}
connections.add(connection);
}
/**
* Caches {@link javax.persistence.PersistenceUnit} annotated field and unit
* name to cache
*
* @param unitName
* @param unitField
*/
private void addUnitField(String unitName, Field unitField) {
for (ConnectionData connection : connections) {
if (unitName.equals(connection.getUnitName())) {
connection.setUnitField(unitField);
}
}
}
/**
* Adds {@link javax.ejb.PersistenceUnit} annotated field to
* {@link MetaData} for cache
*
* @param unitFields
*/
public void addUnitFields(Collection<Field> unitFields) {
if (CollectionUtils.validAll(connections, unitFields)) {
String unitName;
for (Field unitField : unitFields) {
unitName = unitField.getAnnotation(PersistenceUnit.class)
.unitName();
addUnitField(unitName, unitField);
}
this.unitFields = unitFields;
}
}
public ClassLoader getLoader() {
return loader;
}
public void setLoader(ClassLoader loader) {
this.loader = loader;
}
public boolean isInProgress() {
return inProgress.get();
}
public void setInProgress(boolean inProgress) {
this.inProgress.getAndSet(inProgress);
}
public boolean isTransactional() {
return transactional;
}
public void setTransactional(boolean transactional) {
this.transactional = transactional;
}
public TransactionAttributeType getTransactionAttrType() {
return transactionAttrType;
}
public void setTransactionAttrType(
TransactionAttributeType transactionAttrType) {
this.transactionAttrType = transactionAttrType;
}
public TransactionManagementType getTransactionManType() {
return transactionManType;
}
public void setTransactionManType(
TransactionManagementType transactionManType) {
this.transactionManType = transactionManType;
}
public List<InjectionData> getInjects() {
return injects;
}
/**
* Adds passed {@link InjectionData} to cache
*
* @param inject
*/
public void addInject(InjectionData inject) {
if (injects == null) {
injects = new ArrayList<InjectionData>();
}
injects.add(inject);
}
public Collection<Field> getUnitFields() {
return this.unitFields;
}
/**
* Offers {@link InterceptorData} to {@link Stack} to process request by
* order
*
* @param interceptor
*/
public void addInterceptor(InterceptorData interceptor) {
if (interceptors == null) {
interceptors = new LinkedList<InterceptorData>();
}
interceptors.offer(interceptor);
}
public Collection<InterceptorData> getInterceptors() {
return interceptors;
}
public BeanHandler getHandler() {
return handler;
}
public void setHandler(BeanHandler handler) {
this.handler = handler;
}
}
|
package HxCKDMS.HxCWorldGen.libs;
public class Reference {
public static final String MOD_ID = "HxCWorldGen";
public static final String MOD_NAME = "HxC World Gen";
public static final String VERSION = "1.7.10-1.4.1";
public static final String DEPENDENCIES = "required-after:HxCCore@[1.8.1,)";
public static final String CLIENT_PROXY_CLASS = "HxCKDMS.HxCWorldGen.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "HxCKDMS.HxCWorldGen.proxy.ServerProxy";
public static final String RESOURCE_LOCATION = "hxcworldgen:";
public static int ORE_RENDER_ID = 0;
public static String[] ORES = new String[]{"oreCopper", "oreTin", "oreSilver", "oreLead", "oreNickel", "oreChromium", "oreAluminium", "oreTitanium", "orePlatinum", "oreAventurine", "oreRuby", "oreSapphire", "oreRutile"};
public static String[] BLOCKS = new String[]{"blockCopper", "blockTin", "blockSilver", "blockLead", "blockNickel", "blockChromium", "blockAluminum", "blockTitanium", "blockPlatinum", "blockPeridot", "blockRuby", "blockSapphire", "blockZircon"};
public static String[] RESOURCES = new String[]{"ingotCopper", "ingotTin", "ingotSilver", "ingotLead", "ingotNickel", "ingotChromium", "ingotAluminum", "ingotTitanium", "ingotPlatinum", "gemPeridot", "gemRuby", "gemSapphire", "gemZircon", "ingotZirconia"};
public static String[] PIECES = new String[]{"nuggetCopper", "nuggetTin", "nuggetSilver", "nuggetLead", "nuggetNickel", "nuggetChromium", "nuggetAluminum", "nuggetTitanium", "nuggetPlatinum", "nuggetPeridot", "nuggetRuby", "nuggetSapphire", "nuggetZircon", "nuggetZirconia"};
}
|
package com.am05.reddit.library.datasources;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.json.JSONObject;
import com.am05.reddit.library.net.HttpHelper;
import com.am05.reddit.library.net.NetException;
public class LiveDataSource implements JsonDataSource {
private static final String COOKIE_KEY_REDDIT_SESSION = "reddit_session";
private static final String URI_BASE = "http:
private static final String URI_SUBREDDIT_PREFIX = URI_BASE + "/r/";
private static final String URI_SUBREDDITS = URI_BASE + "/reddits.json";
public JSONObject getSubreddits(String sessionId) throws DataSourceException {
Cookie cookie = new BasicClientCookie(COOKIE_KEY_REDDIT_SESSION, sessionId);
List<Cookie> cookies = new ArrayList<Cookie>();
cookies.add(cookie);
try {
return HttpHelper.getInstance().getJsonFromGet(URI_SUBREDDITS, cookies);
} catch (NetException e) {
throw new DataSourceException(
"error trying to parse JSON from GET @ " + URI_SUBREDDITS, e);
}
}
public JSONObject getLinks(String subreddit) throws DataSourceException {
String subredditUrl = URI_SUBREDDIT_PREFIX + subreddit + ".json";
try {
return HttpHelper.getInstance().getJsonFromGet(subredditUrl);
} catch (NetException e) {
throw new DataSourceException("could not get JSON response from: " + subredditUrl, e);
}
}
public JSONObject getComments(String permalink) {
// TODO Auto-generated method stub
return null;
}
public JSONObject getSubreddit(String subreddit) {
// TODO Auto-generated method stub
return null;
}
public JSONObject getDefaultSubreddits() throws DataSourceException {
try {
return HttpHelper.getInstance().getJsonFromGet(URI_SUBREDDITS);
} catch (NetException e) {
throw new DataSourceException("could not get JSON response from: " + URI_SUBREDDITS, e);
}
}
}
|
package nl.mpi.yaas.common.db;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import nl.mpi.flap.kinnate.entityindexer.QueryException;
import nl.mpi.flap.model.DataNodeLink;
import nl.mpi.flap.model.ModelException;
import nl.mpi.flap.model.SerialisableDataNode;
import nl.mpi.flap.plugin.PluginException;
import nl.mpi.yaas.common.data.DataNodeId;
import nl.mpi.yaas.common.data.DatabaseLinks;
import nl.mpi.yaas.common.data.DatabaseStats;
import nl.mpi.yaas.common.data.IconTable;
import nl.mpi.yaas.common.data.IconTableBase64;
import nl.mpi.yaas.common.data.MetadataFileType;
import nl.mpi.yaas.common.data.NodeTypeImage;
import nl.mpi.yaas.common.data.QueryDataStructures.CriterionJoinType;
import nl.mpi.yaas.common.data.QueryDataStructures.SearchNegator;
import nl.mpi.yaas.common.data.QueryDataStructures.SearchOption;
import nl.mpi.yaas.common.data.QueryDataStructures.SearchType;
import nl.mpi.yaas.common.data.SearchParameters;
import org.slf4j.LoggerFactory;
public class DataBaseManager<D, F, M> {
final private Class<D> dClass;
final private Class<F> fClass;
final private Class<M> mClass;
final protected DbAdaptor dbAdaptor;
final private String databaseName;
final private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
/**
* these are two recommended database names, one for testing and the other
* for production
*/
final static public String defaultDataBase = "yaas-data";
final static public String testDataBase = "yaas-test-data";
final static public String facetsCollection = "Facets";
final static public String dbStatsDocument = "DbStats";
final static public String iconTableDocument = "IconTable";
final private String crawledDataCollection = "CrawledData";
// final static public String guestUser = "guestdbuser";
// final static public String guestUserPass = "minfc8u4ng6s";
final static public String guestUser = "admin"; // todo: the user name and password for admin and guest users needs to be determined and set
final static public String guestUserPass = "admin";
/**
*
* @param dClass Concrete class of DataNode that will be used in the jaxb
* deserialising process
* @param fClass Concrete class of DataField that will be used in the jaxb
* deserialising process
* @param mClass Concrete class of MetadataFileType that is used as query
* parameters and in some cases query results via the jaxb deserialising
* process
* @param dbAdaptor an implementation of DbAdaptor which interfaces to
* either the REST DB or local DB via java bindings
* @param databaseName the name of the database that will be connected to
* @throws QueryException
*/
public DataBaseManager(Class<D> dClass, Class<F> fClass, Class<M> mClass, DbAdaptor dbAdaptor, String databaseName) throws QueryException {
this.dbAdaptor = dbAdaptor;
this.dClass = dClass;
this.fClass = fClass;
this.mClass = mClass;
this.databaseName = databaseName;
// dbAdaptor.checkDbExists(databaseName);
}
/**
* Verifies that the database exists and create a new empty database if it
* does not
*
* @throws QueryException
*/
public void checkDbExists() throws QueryException {
dbAdaptor.checkDbExists(databaseName);
}
/**
* Drop the entire database if it exists and create a new empty database
*
* @throws QueryException
*/
public void dropAllRecords() throws QueryException {
dbAdaptor.dropAndRecreateDb(databaseName);
// dbAdaptor.deleteDocument(databaseName, crawledDataCollection);
// dbAdaptor.deleteDocument(databaseName, dbStatsDocument);
// dbAdaptor.deleteDocument(databaseName, iconTableDocument);
// dbAdaptor.deleteDocument(databaseName, facetsCollection);
}
/**
* Remove the database statistics document that is generated after a crawl
* by getDatabaseStats()
*
* @throws QueryException
*/
public void clearDatabaseStats() throws QueryException {
dbAdaptor.deleteDocument(databaseName, dbStatsDocument);
}
/**
* Causes the database to reindex all of its files which is required after
* an add or delete for instance
*
* @throws QueryException
*/
public void createIndexes() throws QueryException {
long startTime = System.currentTimeMillis();
dbAdaptor.createIndexes(databaseName);
// System.out.println("queryResult: " + queryResult);
long queryMils = System.currentTimeMillis() - startTime;
String queryTimeString = "Create indexes time: " + queryMils + "ms";
System.out.println(queryTimeString);
}
private String getCachedVersion(String cachedDocument, String queryString) throws QueryException {
String statsCachedQuery = "for $statsDoc in collection(\"" + databaseName + "\")\n"
+ "where matches(document-uri($statsDoc), '" + cachedDocument + "')\n"
+ "return $statsDoc";
String queryResult;
queryResult = dbAdaptor.executeQuery(databaseName, statsCachedQuery);
if (queryResult.length() < 2) {
// calculate the stats
queryResult = dbAdaptor.executeQuery(databaseName, queryString);
String resultCacheFlagged = queryResult.replaceFirst("<Cached>false</Cached>", "<Cached>true</Cached>");
// insert the stats as a document
dbAdaptor.addDocument(databaseName, cachedDocument, resultCacheFlagged);
}
// System.out.println("queryResult: " + queryResult);
return queryResult;
}
/**
* Gets a list of available databases
*
* @return a list of database names
* @throws QueryException
*/
public String[] getDatabaseList() throws QueryException {
// String queryResult = dbAdaptor.executeQuery(databaseName, "for $databaseName in db:list()\n"
// + "return <String>{$databaseName}</String>");
String queryResult = dbAdaptor.executeQuery(databaseName, "db:list()");
System.out.println("databaseList: " + queryResult);
return queryResult.split(" ");
}
/**
* Creates a document in the database that holds information on the contents
* of the database such as document count and root nodes URLs
*
* @return an object of type DatabaseStats that contains information on the
* contents of the database
* @throws QueryException
*/
public DatabaseStats getDatabaseStats() throws QueryException {
long startTime = System.currentTimeMillis();
String statsQuery = "let $knownIds := collection(\"" + databaseName + "\")/DataNode/@ID\n"
+ "let $duplicateDocumentCount := count($knownIds) - count(distinct-values($knownIds))\n"
+ "let $childIds := collection(\"" + databaseName + "\")/DataNode/ChildLink/@ID\n" // removing the "/text()" here reduced the query from 310ms to 290ms with 55 documents
// + "let $missingIds := distinct-values(for $testId in $childIds where not ($knownIds = $testId) return $testId)\n"
// + "let $rootNodes := distinct-values(for $testId in $knownIds where not ($childIds = $testId) return $testId)\n"
// With 55 documents this change (for loop replaced by "[not(.=") decreased the query from 254ms to 237ms and with zero documents it made no difference, but this was doe with out updating the indexes and running the query only once
+ "let $missingIds := distinct-values($childIds[not(.=$knownIds)])"
+ "let $rootNodes := distinct-values($knownIds[not(.=$childIds)])"
+ "return <DatabaseStats>\n"
+ "<KnownDocuments>{count($knownIds)}</KnownDocuments>\n"
+ "<MissingDocuments>{count($missingIds)}</MissingDocuments>\n"
+ "<DuplicateDocuments>{$duplicateDocumentCount}</DuplicateDocuments>\n"
+ "<RootDocuments>{count($rootNodes)}</RootDocuments>\n"
+ "<Cached>false</Cached>\n"
+ "{for $rootDocId in $rootNodes return <RootDocumentID>{$rootDocId}</RootDocumentID>}\n"
+ "</DatabaseStats>\n";
String queryResult = getCachedVersion(dbStatsDocument, statsQuery);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(DatabaseStats.class, DataNodeId.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
DatabaseStats databaseStats = (DatabaseStats) unmarshaller.unmarshal(new StreamSource(new StringReader(queryResult)), DatabaseStats.class).getValue();
long queryMils = System.currentTimeMillis() - startTime;
// String queryTimeString = "DatabaseStats Query time: " + queryMils + "ms";
databaseStats.setQueryTimeMS(queryMils);
// System.out.println(queryTimeString);
return databaseStats;
} catch (JAXBException exception) {
logger.debug(exception.getMessage());
throw new QueryException("Error getting DatabaseStats");
}
}
/**
* Searches the database for missing child nodes for use when crawling
* missing documents
*
* @return the URLs of the first N missing documents
* @throws PluginException
* @throws QueryException
*/
public String getHandlesOfMissing() throws PluginException, QueryException {
long startTime = System.currentTimeMillis();
String queryString = "let $childIds := collection(\"" + databaseName + "\")/DataNode/ChildLink\n"
+ "let $knownIds := collection(\"" + databaseName + "\")/DataNode/@ID\n"
+ "let $missingIds := distinct-values($childIds[not(@ID=$knownIds)]/@URI)"
+ "return $missingIds[matches(., '\\.[icIC][mM][dD][iI]$')][position() le 1000]\n"; // <DataNodeId> </DataNodeId>
System.out.println("filtering by suffix on cmdi and imdi (this must be removed when a better solution is defined)");
// System.out.println("getHandlesOfMissing: " + queryString);
String queryResult = dbAdaptor.executeQuery(databaseName, queryString);
long queryMils = System.currentTimeMillis() - startTime;
String queryTimeString = "Query time: " + queryMils + "ms";
final String sampleDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());;
String statsQuery = "let $childIds := collection(\"" + databaseName + "\")/DataNode/ChildLink\n"
+ "let $knownIds := collection(\"" + databaseName + "\")/DataNode/@ID\n"
+ "return\n"
+ "<CrawlerStats linkcount='{count($childIds)}' documentcount='{count($knownIds)}' queryms='" + queryMils + "' timestamp='" + sampleDateTime + "'/>";
String statsDoc = dbAdaptor.executeQuery(databaseName, statsQuery);
System.out.println("stats:" + statsDoc);
// insert the stats document
dbAdaptor.addDocument(databaseName, "CrawlerStats/" + sampleDateTime, statsDoc);
System.out.println(queryTimeString);
return queryResult; // the results here need to be split on " ", but the string can be very long so it should not be done by String.split().
}
/**
* Uses the DatabaseLinks document to get the next batch of missing child
* nodes for use when crawling missing documents
*
* @param DatabaseLinks from the crawler with will be merged and updated
* with the DatabaseLinks document in the database
* @return the DataNodeLinks of the first N missing documents
* @throws PluginException
* @throws QueryException
*/
public Set<DataNodeLink> getHandlesOfMissing(DatabaseLinks databaseLinks, int numberToGet) throws PluginException, QueryException {
long startTime = System.currentTimeMillis();
String linksDocument = "DatabaseLinks";
DatabaseLinks updatedDatabaseLinks;
try {
String docTestQueryString = "if(fn:empty(collection(\"" + databaseName + "\")/" + linksDocument + ")) then (0)else(1)";
String docTestResult = dbAdaptor.executeQuery(databaseName, docTestQueryString);
JAXBContext jaxbContext = JAXBContext.newInstance(DatabaseLinks.class, DataNodeLink.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(databaseLinks, stringWriter);
if (docTestResult.equals("1")) {
// update the document
String insertString = "let $updatedLinks := "
+ stringWriter.toString().replaceFirst("^\\<\\?[^\\?]*\\?\\>", "") // remove the xml header that xquery cant have in a variable
+ "\n"
+ "return (insert node $updatedLinks/RootDocumentLinks[not(@ID=collection(\"" + databaseName + "\")/" + linksDocument + "/RootDocumentLinks/@ID)] into collection(\"" + databaseName + "\")/" + linksDocument
+ ",\ninsert node $updatedLinks/MissingDocumentLinks[not(@ID=collection(\"" + databaseName + "\")/" + linksDocument + "/MissingDocumentLinks/@ID)] into collection(\"" + databaseName + "\")/" + linksDocument + ")";
// System.out.println("getHandlesOfMissing: " + queryString);
dbAdaptor.executeQuery(databaseName, insertString);
String deleteQuery = "delete node collection(\"" + databaseName + "\")/" + linksDocument + "/MissingDocumentLinks[@ID = collection(\"" + databaseName + "\")/DataNode/@ID]";
dbAdaptor.executeQuery(databaseName, deleteQuery);
} else if (docTestResult.equals("0")) {
// add the document
dbAdaptor.addDocument(databaseName, linksDocument, stringWriter.toString());
} else {
throw new QueryException("unexpected state for DatabaseLinks document");
}
String queryResult = dbAdaptor.executeQuery(databaseName, "<DatabaseLinks>{collection(\"" + databaseName + "\")/" + linksDocument + "/MissingDocumentLinks[position() le " + numberToGet + "]}</DatabaseLinks>");
// System.out.println("updatedDatabaseLinks: " + queryResult);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
updatedDatabaseLinks = (DatabaseLinks) unmarshaller.unmarshal(new StreamSource(new StringReader(queryResult)), DatabaseLinks.class).getValue();
} catch (JAXBException exception) {
System.err.println("jaxb error:" + exception.getMessage());
throw new PluginException(exception);
}
long queryMils = System.currentTimeMillis() - startTime;
String queryTimeString = "Query time: " + queryMils + "ms";
final String sampleDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());;
String statsQuery = "let $childIds := collection(\"" + databaseName + "\")/DataNode/ChildLink\n"
+ "let $knownIds := collection(\"" + databaseName + "\")/DataNode/@ID\n"
+ "return\n"
+ "<CrawlerStats linkcount='{count($childIds)}' documentcount='{count($knownIds)}' queryms='" + queryMils + "' timestamp='" + sampleDateTime + "'/>";
String statsDoc = dbAdaptor.executeQuery(databaseName, statsQuery);
System.out.println("stats:" + statsDoc);
// insert the stats document
dbAdaptor.addDocument(databaseName, "CrawlerStats/" + sampleDateTime, statsDoc);
System.out.println(queryTimeString);
return updatedDatabaseLinks.getChildLinks(); // the results here need to be split on " ", but the string can be very long so it should not be done by String.split().
}
/**
* Retrieves the document of all the known node types and the icons for each
* type from the database in base 64 format
*
* @return IconTableBase64 a set of node types and their icons in base 64
* format
* @throws PluginException
* @throws QueryException
*/
public IconTableBase64 getNodeIconsBase64() throws PluginException, QueryException {
String iconTableQuery = "for $statsDoc in collection(\"" + databaseName + "\")\n"
+ "where matches(document-uri($statsDoc), '" + iconTableDocument + "')\n"
+ "return $statsDoc";
try {
JAXBContext jaxbContext = JAXBContext.newInstance(IconTableBase64.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
String queryResult;
queryResult = dbAdaptor.executeQuery(databaseName, iconTableQuery);
// System.out.println("queryResult: " + queryResult);
return (IconTableBase64) unmarshaller.unmarshal(new StreamSource(new StringReader(queryResult)), IconTableBase64.class).getValue();
} catch (JAXBException exception) {
throw new PluginException(exception);
}
}
/**
* Retrieves the document of all the known node types and the icons for each
* type from the database
*
* @return IconTable a set of node types and their icons
* @throws PluginException
* @throws QueryException
*/
public IconTable getNodeIcons() throws PluginException, QueryException {
String iconTableQuery = "for $iconTable in collection(\"" + databaseName + "\")\n"
+ "where matches(document-uri($iconTable), '" + iconTableDocument + "')\n"
+ "return $iconTable";
try {
JAXBContext jaxbContext = JAXBContext.newInstance(IconTable.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
String queryResult;
queryResult = dbAdaptor.executeQuery(databaseName, iconTableQuery);
// System.out.println("queryResult: " + queryResult);
return (IconTable) unmarshaller.unmarshal(new StreamSource(new StringReader(queryResult)), IconTable.class).getValue();
} catch (JAXBException exception) {
throw new PluginException(exception);
}
}
/**
* Inserts a document of all the known node types and the icons for each
* type into the database
*
* @param iconTable a set of node types and their icons to be inserted into
* the database
* @throws PluginException
* @throws QueryException
*/
public IconTable insertNodeIconsIntoDatabase(IconTable iconTable) throws PluginException, QueryException {
try {
IconTable databaseIconTable = getNodeIcons();
for (NodeTypeImage nodeTypeImage : databaseIconTable.getNodeTypeImageSet()) {
// add the known types to the new set
iconTable.addTypeIcon(nodeTypeImage);
}
} catch (PluginException exception) {
// if there is not icon document here that can be normal if it is the first run
System.out.println("Error getting existing IconTableDocument (this is normal on the first run).");
}
dbAdaptor.deleteDocument(databaseName, iconTableDocument);
// use JAXB to serialise and insert the IconTable into the database
try {
JAXBContext jaxbContext = JAXBContext.newInstance(IconTable.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(iconTable, stringWriter);
//System.out.println("NodeIcons to be inserted:\n" + stringWriter.toString());
dbAdaptor.addDocument(databaseName, iconTableDocument, stringWriter.toString());
} catch (JAXBException exception) {
System.err.println("jaxb error:" + exception.getMessage());
throw new PluginException(exception);
}
return iconTable;
}
/**
* Inserts a document into the database and optionally checks for existing
* documents that would constitute a duplicate
*
* @param dataNode the data node to be inserted into the database
* @param testForDuplicates if true the database will be searched for the
* document before inserting
* @throws PluginException
* @throws QueryException
*/
public void insertIntoDatabase(SerialisableDataNode dataNode, boolean testForDuplicates) throws PluginException, QueryException, ModelException {
// test for existing documents with the same ID and throw if one is found
if (testForDuplicates) {
String existingDocumentQuery = "let $countValue := count(collection(\"" + databaseName + "\")/DataNode[@ID = \"" + dataNode.getID() + "\"])\nreturn $countValue";
String existingDocumentResult = dbAdaptor.executeQuery(databaseName, existingDocumentQuery);
if (!existingDocumentResult.equals("0")) {
throw new QueryException("Existing document found, count: " + existingDocumentResult);
}
}
// use JAXB to serialise and insert the data node into the database
try {
JAXBContext jaxbContext = JAXBContext.newInstance(dClass, fClass, mClass);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(dataNode, stringWriter);
// System.out.println("Data to be inserted:\n" + stringWriter.toString());
dbAdaptor.addDocument(databaseName, crawledDataCollection + "/" + dataNode.getID(), stringWriter.toString());
} catch (JAXBException exception) {
System.err.println("jaxb error:" + exception.getMessage());
throw new PluginException(exception);
}
}
private String getTypeClause(MetadataFileType metadataFileType) {
String typeClause = "";
if (metadataFileType != null) {
if (metadataFileType.getType() != null) {
typeClause += "[/DataNode/Type/@Name = '" + metadataFileType.getType() + "']";
}
if (metadataFileType.getPath() != null) {
typeClause += "//DataNode/FieldGroup[@Label = '" + metadataFileType.getPath() + "']";
}
}
return typeClause;
}
private String getTypeNodes(MetadataFileType metadataFileType) {
String typeNodes = "";
if (metadataFileType != null) {
if (metadataFileType.getPath() != null) {
typeNodes += "<Path>" + metadataFileType.getPath() + "</Path>";
}
if (metadataFileType.getType() != null) {
typeNodes += "<Type>" + metadataFileType.getType() + "</Type>";
}
}
return typeNodes;
}
private String getDocumentName(MetadataFileType metadataFileType, String queryType) {
if (metadataFileType == null) {
return facetsCollection + "/" + queryType + "/all";
}
final String type = (metadataFileType.getType() == null) ? "all" : metadataFileType.getType();
final String path = (metadataFileType.getPath() == null) ? "all" : metadataFileType.getPath();
return facetsCollection + "/" + queryType + "/" + type + "/" + path;
}
private String getDocumentName(MetadataFileType[] metadataFileTypes, String queryType) {
String documentName = facetsCollection + "/" + queryType;
for (MetadataFileType metadataFileType : metadataFileTypes) {
if (metadataFileType == null) {
documentName += "/all/all";
} else {
final String type = (metadataFileType.getType() == null) ? "all" : metadataFileType.getType();
final String path = (metadataFileType.getPath() == null) ? "all" : metadataFileType.getPath();
documentName += "/" + type + "/" + path;
}
}
System.out.println("documentName: " + documentName);
return documentName;
}
// private String getFieldConstraint(MetadataFileType fieldType) {
// String fieldConstraint = "";
// if (fieldType != null) {
// final String fieldNameString = fieldType.getFieldName();
// if (fieldNameString != null) {
// fieldConstraint = "FieldGroup/@Label = '" + fieldNameString + "' and ";
// return fieldConstraint;
private String getSearchTextConstraint(SearchNegator searchNegator, SearchType searchType, String searchString, String nodeString) {
final String escapedSearchString = escapeBadChars(searchString);
String returnString = "";
switch (searchType) {
case contains:
if (escapedSearchString.isEmpty()) {
// when the user has not entered any string then return all, but allow the negator to still be used
returnString = "1=1";
} else {
returnString = nodeString + "@FieldValue contains text '" + escapedSearchString + "'";
}
break;
case equals:
returnString = nodeString + "@FieldValue = '" + escapedSearchString + "'";
break;
case fuzzy:
returnString = nodeString + "@FieldValue contains text '" + escapedSearchString + "' using fuzzy";
break;
}
switch (searchNegator) {
case is:
// returnString = returnString;
break;
case not:
returnString = "not(" + returnString + ")";
break;
}
return returnString;
}
static String escapeBadChars(String inputString) {
// our queries use double quotes so single quotes are allowed
// todo: could ; cause issues?
return inputString.replace("&", "&").replace("\"", """).replace("'", "'");
}
let $intersectionSet0 := $elementSet1[root()//*:Address = $nameString0]
for $nameString1 in distinct-values($intersectionSet0/text())
return
<TreeNode><DisplayString>Region: {$nameString1}</DisplayString>
</TreeNode>
}
</TreeNode>
}
</TreeNode>
* */
private String getTreeSubQuery(ArrayList<MetadataFileType> treeBranchTypeList, String whereClause, String selectClause, String trailingSelectClause, int levelCount) {
final int maxMetadataFileCount = 100;
if (!treeBranchTypeList.isEmpty()) {
String separatorString = "";
// if (whereClause.length() > 0) {
// separatorString = ",\n";
MetadataFileType treeBranchType = treeBranchTypeList.remove(0);
String currentFieldName = treeBranchType.getPath();
// + "for $imdiType in distinct-values(collection('" + databaseName + "')/*:METATRANSCRIPT/*/name())\n"
/*
* optimised this query 2012-10-17
* the query above takes:
* 5014.03 ms
* the query below takes:
* 11.8 ms (varies per run)
*/
// + "for $profileInfo in index:facets('" + databaseName + "/" + crawledDataCollection + "')/document-node/element[@name='DataNode']/element[@name='Type']/attribute[@name='Format']/entry\n"
// + "return\n"
// + "<MetadataFileType>\n"
// + "<fieldName>{string($profileInfo)}</fieldName>\n"
// + "<RecordCount>{string($profileInfo/@count)}</RecordCount>\n"
// + "</MetadataFileType>"
// + "for $profileInfo in index:facets('" + databaseName + "')/document-node/element[@name='DataNode']/element[@name='Type']/attribute[@name='Name']/entry\n"
// + "return\n"
// + "<MetadataFileType>\n"
// + "<fieldName>{string($profileInfo)}</fieldName>\n"
// + "<RecordCount>{string($profileInfo/@count)}</RecordCount>\n"
// // + "<ValueCount>{count($profileInfo/entry)}</ValueCount>\n"
// + "</MetadataFileType>\n"
+ "let $allNodeTypes := collection('" + databaseName + "/" + crawledDataCollection + "')/DataNode/Type/@Name/string()\n"
+ "for $nodeType in distinct-values($allNodeTypes)\n"
+ "order by $nodeType\n"
+ "return\n"
+ "<MetadataFileType>\n"
+ "<Label>{$nodeType}</Label>\n"
+ "<Type>{$nodeType}</Type>\n"
+ "<Count>{count($allNodeTypes[. = $nodeType])}</Count>\n"
+ "</MetadataFileType>\n"
+ "}</MetadataFileType>";
}
private String getMetadataPathsQuery(MetadataFileType metadataFileType) {
String typeClause = getTypeClause(metadataFileType);
String typeNodes = getTypeNodes(metadataFileType);
return "let $fieldLabels := collection('" + databaseName + "/" + crawledDataCollection + "')" + typeClause + "//FieldGroup[FieldData/@FieldValue != '']/@Label/string()\n"
+ "return <MetadataFileType>\n"
+ "<MetadataFileType><Label>All Paths</Label>"
+ typeNodes
+ "<Count>{count($fieldLabels)}</Count></MetadataFileType>\n"
+ "{\n"
+ "for $label in distinct-values($fieldLabels)\n"
+ "order by $label\n"
+ "return <MetadataFileType>"
+ "<Label>{$label}</Label>\n"
+ typeNodes
+ "<Path>{$label}</Path>\n"
+ "<Count>{count($fieldLabels[. = $label and $label != ''])}</Count></MetadataFileType>\n"
+ "}</MetadataFileType>";
}
/**
* Searches the database
*
* @param criterionJoinType the type of join that the query will perform
* @param searchParametersList the parameters of the search
* @return A data node that the results as child nodes plus some query
* information
* @throws QueryException
*/
public D getSearchResult(CriterionJoinType criterionJoinType, ArrayList<SearchParameters> searchParametersList) throws QueryException {
StringBuilder queryStringBuilder = new StringBuilder();
queryStringBuilder.append("<DataNode ID=\"Search Results\" Label=\"Search Results: ");
if (searchParametersList.size() > 1) {
queryStringBuilder.append(criterionJoinType.name());
queryStringBuilder.append(" ");
}
for (SearchParameters parameters : searchParametersList) {
queryStringBuilder.append("(");
queryStringBuilder.append(parameters.getFileType().getType());
queryStringBuilder.append(" ");
queryStringBuilder.append(parameters.getFieldType().getPath());
queryStringBuilder.append(" ");
for (SearchOption option : SearchOption.values()) {
if (option.getSearchNegator() == parameters.getSearchNegator() && option.getSearchType() == parameters.getSearchType()) {
queryStringBuilder.append(option.toString());
}
}
queryStringBuilder.append(" ");
queryStringBuilder.append(parameters.getSearchString());
queryStringBuilder.append(") ");
}
queryStringBuilder.append("\">");
queryStringBuilder.append("{\n");
int parameterCounter = 0;
for (SearchParameters searchParameters : searchParametersList) {
queryStringBuilder.append("let $documentSet");
queryStringBuilder.append(parameterCounter);
queryStringBuilder.append(" := ");
parameterCounter++;
queryStringBuilder.append(getSearchConstraint(searchParameters));
}
queryStringBuilder.append("let $returnSet := $documentSet0");
for (int setCount = 1; setCount < parameterCounter; setCount++) {
queryStringBuilder.append(" ");
queryStringBuilder.append(criterionJoinType.name());
queryStringBuilder.append(" $documentSet");
queryStringBuilder.append(setCount);
}
queryStringBuilder.append("\n"
+ "for $documentNode in $returnSet\n"
+ "return\n"
/*
* This query currently takes 18348.54 ms
* the loop over the return set takes 15000 ms or so
* With two search values and union it takes 13810.04ms
* With two search values and union and one field name specified it takes 9086.76ms
*
*/
/*
* 15041
* <TreeNode>{
for $fieldNode in collection('" + databaseName + "')//.[(text() contains text 'pu6') or (name() = 'Name' and text() contains text 'pu8')]
let $documentFile := base-uri($fieldNode)
group by $documentFile
return
<MetadataTreeNode>
<FileUri>{$documentFile}</FileUri>
{
for $entityNode in $fieldNode
return <FileUriPath>{path($entityNode)}</FileUriPath>
}
</MetadataTreeNode>
}</TreeNode>
*/
// todo: add back in the set functions
// + "for $entityNode in $documentNode[");
// boolean firstConstraint = true;
// for (SearchParameters searchParameters : searchParametersList) {
// if (firstConstraint) {
// firstConstraint = false;
// } else {
// queryStringBuilder.append(" or ");
// queryStringBuilder.append(getSearchFieldConstraint(searchParameters));
// queryStringBuilder.append("]\n"
// + "return $entityNode\n"
+ "$returnSet"
+ "}</DataNode>\n");
final D metadataTypesString = getDbTreeNode(queryStringBuilder.toString());
return metadataTypesString;
}
// public DbTreeNode getSearchResultX(CriterionJoinType criterionJoinType, ArrayList<SearchParameters> searchParametersList) {
// StringBuilder queryStringBuilder = new StringBuilder();
// StringBuilder joinStringBuilder = new StringBuilder();
// StringBuilder fieldStringBuilder = new StringBuilder();
// int parameterCounter = 0;
// for (SearchParameters searchParameters : searchParametersList) {
// fieldStringBuilder.append(getSearchFieldConstraint(searchParameters));
// if (queryStringBuilder.length() > 0) {
// fieldStringBuilder.append(" or ");
// joinStringBuilder.append(" ");
// joinStringBuilder.append(criterionJoinType.name());
// joinStringBuilder.append(" ");
// } else {
// joinStringBuilder.append("let $returnSet := ");
// joinStringBuilder.append("$set");
// joinStringBuilder.append(parameterCounter);
// queryStringBuilder.append("let $set");
// queryStringBuilder.append(parameterCounter);
// queryStringBuilder.append(" := ");
// parameterCounter++;
// queryStringBuilder.append(getSearchConstraint(searchParameters));
// queryStringBuilder.append(joinStringBuilder);
// queryStringBuilder.append("return <TreeNode>{"
// + "for $documentNode in $returnSet\n"
// + "return\n"
// + "<MetadataTreeNode>\n"
// + "<FileUri>{base-uri($entityNode)}</FileUri>\n"
|
package org.marat.advent.day04;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.marat.advent.common.Util;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
public class Day04 {
public static void main(String[] args) {
Pattern delimiter = Pattern.compile("\\s+");
List<String> keyWords = Arrays.asList("north", "pole");
int sectorId = Util.readElementsWithDelimiter("day04/input.txt", delimiter)
.map(StringUtils::trim)
.filter(StringUtils::isNotEmpty)
.map(Door::new)
.filter(Door::isValid)
.filter(door -> keyWords.stream().allMatch(keyWord -> door.getName().contains(keyWord)))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(
String.format("Could not find root with key words'%s'", keyWords)))
.getSectorId();
System.out.println(sectorId);
}
@Data
static class Door {
private static final Pattern PATTERN = Pattern.compile("([a-z\\-]+)-(\\d+)\\[([a-z]+)]");
private final String encryptedName;
private final int sectorId;
private final String givenChecksum;
private final String checksum;
private final String name;
public Door(String input) {
Matcher matcher = PATTERN.matcher(input);
if (matcher.matches()) {
encryptedName = matcher.group(1);
sectorId = Integer.parseInt(matcher.group(2));
givenChecksum = matcher.group(3);
checksum = computeChecksum(encryptedName, givenChecksum.length());
name = decrypt(encryptedName, sectorId);
} else {
throw new IllegalArgumentException(String.format("Cannot parse input as room: '%s'", input));
}
}
public boolean isValid() {
return checksum.equals(givenChecksum);
}
private static String decrypt(String encryptedName, int sectorId) {
return encryptedName.chars()
.mapToObj(i -> (char) i)
.map(c -> shift(c, sectorId))
.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
}
private static char shift(char c, int sectorId) {
if (c == '-') {
return ' ';
} else {
int shift = sectorId % 26;
return (char) ('a' + ((c - 'a' + shift) % 26));
}
}
private static String computeChecksum(String name, int length) {
Map<Character, AtomicInteger> counts = new TreeMap<>();
name.chars()
.mapToObj(i -> (char) i)
.filter(c -> c != '-')
.forEachOrdered(c -> counts.computeIfAbsent(c, (key) -> new AtomicInteger(0)).getAndIncrement());
return counts.entrySet().stream()
.sorted((o1, o2) -> o2.getValue().get() - o1.getValue().get())
.limit(length)
.map(Map.Entry::getKey)
.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
}
}
}
|
package SW9.controllers;
import SW9.HUPPAAL;
import SW9.abstractions.*;
import SW9.backend.UPPAALDriver;
import SW9.code_analysis.CodeAnalysis;
import SW9.presentations.*;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.Color;
import SW9.utility.helpers.NailHelper;
import SW9.utility.helpers.SelectHelper;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import com.jfoenix.controls.JFXPopup;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Path;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;
import static SW9.presentations.CanvasPresentation.GRID_SIZE;
public class LocationController implements Initializable, SelectHelper.ColorSelectable {
private static final Map<Location, Boolean> invalidNameError = new HashMap<>();
private final ObjectProperty<Location> location = new SimpleObjectProperty<>();
private final ObjectProperty<Component> component = new SimpleObjectProperty<>();
public Group root;
public Path initialIndicator;
public StackPane finalIndicator;
public Group shakeContent;
public Circle circle;
public Circle circleShakeIndicator;
public Group scaleContent;
public TagPresentation nameTag;
public TagPresentation invariantTag;
public Circle hiddenAreaCircle;
public Path locationShape;
public Label idLabel;
public Line nameTagLine;
public Line invariantTagLine;
private TimerTask reachabilityCheckTask;
private double previousX;
private double previousY;
private boolean wasDragged = false;
private DropDownMenu dropDownMenu;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
this.location.addListener((obsLocation, oldLocation, newLocation) -> {
// The radius property on the abstraction must reflect the radius in the view
newLocation.radiusProperty().bind(circle.radiusProperty());
// The scale property on the abstraction must reflect the radius in the view
newLocation.scaleProperty().bind(scaleContent.scaleXProperty());
});
// Scale x and y 1:1 (based on the x-scale)
scaleContent.scaleYProperty().bind(scaleContent.scaleXProperty());
//initializeReachabilityCheck();
}
public void initializeDropDownMenu() {
dropDownMenu = new DropDownMenu(((Pane) root.getParent()), root, 230, true);
dropDownMenu.addListElement("Set Urgency");
final BooleanProperty isUrgent = new SimpleBooleanProperty(false);
isUrgent.bind(getLocation().urgencyProperty().isEqualTo(Location.Urgency.URGENT));
dropDownMenu.addTogglableListElement("Urgent", isUrgent, event -> {
if (isUrgent.get()) {
getLocation().setUrgency(Location.Urgency.NORMAL);
} else {
getLocation().setUrgency(Location.Urgency.URGENT);
}
});
final BooleanProperty isCommitted = new SimpleBooleanProperty(false);
isCommitted.bind(getLocation().urgencyProperty().isEqualTo(Location.Urgency.COMMITTED));
dropDownMenu.addTogglableListElement("Committed", isCommitted, event -> {
if (isCommitted.get()) {
getLocation().setUrgency(Location.Urgency.NORMAL);
} else {
getLocation().setUrgency(Location.Urgency.COMMITTED);
}
});
dropDownMenu.addSpacerElement();
dropDownMenu.addClickableListElement("Is reachable?", event -> {
// Generate the query from the backend
final String reachabilityQuery = UPPAALDriver.getLocationReachableQuery(getLocation(), getComponent());
// Add proper comment
final String reachabilityComment = "Is " + getLocation().getMostDescriptiveIdentifier() + " reachable?";
// Add new query for this location
HUPPAAL.getProject().getQueries().add(new Query(reachabilityQuery, reachabilityComment, QueryState.UNKNOWN));
dropDownMenu.close();
});
}
public void initializeInvalidNameError() {
final Location location = getLocation();
if (invalidNameError.containsKey(location)) return;
invalidNameError.put(location, true);
final CodeAnalysis.Message invalidNickName = new CodeAnalysis.Message("Nicknames for locations must be alpha-numeric", CodeAnalysis.MessageType.ERROR, location);
final Consumer<String> updateNickNameCheck = (nickname) -> {
if (!nickname.matches("[A-Za-z0-9_-]*$")) {
// Invalidate the list (will update the UI with the new name)
invalidNickName.getNearables().remove(location);
invalidNickName.getNearables().add(location);
CodeAnalysis.addMessage(getComponent(), invalidNickName);
} else {
CodeAnalysis.removeMessage(getComponent(), invalidNickName);
}
};
location.nicknameProperty().addListener((obs, oldNickName, newNickName) -> {
updateNickNameCheck.accept(newNickName);
});
updateNickNameCheck.accept(location.getNickname());
}
public void initializeReachabilityCheck() {
final int interval = 5000;
// Could not run query
reachabilityCheckTask = new TimerTask() {
@Override
public void run() {
if (getComponent() == null || getLocation() == null) return;
// The location might have been remove from the component (through ctrl + z)
if (getLocation().getType() == Location.Type.NORMAL && !getComponent().getLocations().contains(getLocation())) return;
final Component mainComponent = HUPPAAL.getProject().getMainComponent();
if (mainComponent == null) {
return; // We cannot generate a UPPAAL file without a main component
}
UPPAALDriver.verify(
"E<> " + getComponent().getName() + "." + getLocation().getId(),
result -> {
final LocationPresentation locationPresentation = (LocationPresentation) LocationController.this.root;
locationPresentation.animateShakeWarning(!result);
},
e -> {
// Could not run query
System.out.println(e);
},
mainComponent
);
}
};
new Timer().schedule(reachabilityCheckTask, 0, interval);
}
public Location getLocation() {
return location.get();
}
public void setLocation(final Location location) {
this.location.set(location);
if (ComponentController.isPlacingLocation()) {
root.layoutXProperty().bind(location.xProperty());
root.layoutYProperty().bind(location.yProperty());
} else {
root.setLayoutX(location.getX());
root.setLayoutY(location.getY());
location.xProperty().bind(root.layoutXProperty());
location.yProperty().bind(root.layoutYProperty());
((LocationPresentation) root).setPlaced(true);
}
}
public ObjectProperty<Location> locationProperty() {
return location;
}
public Component getComponent() {
return component.get();
}
public void setComponent(final Component component) {
this.component.set(component);
}
public ObjectProperty<Component> componentProperty() {
return component;
}
@FXML
private void mouseEntered() {
final LocationPresentation locationPresentation = (LocationPresentation) this.root;
if(!locationPresentation.isInteractable()) return;
circle.setCursor(Cursor.HAND);
locationPresentation.animateHoverEntered();
// Keybind for making location urgent
KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_URGENT, new Keybind(new KeyCodeCombination(KeyCode.U), () -> {
final Location.Urgency previousUrgency = location.get().getUrgency();
if (previousUrgency.equals(Location.Urgency.URGENT)) {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.NORMAL);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
}, "Made location " + getLocation().getNickname() + " urgent", "hourglass-full");
} else {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.URGENT);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
}, "Made location " + getLocation().getNickname() + " normal (back form urgent)", "hourglass-empty");
}
}));
// Keybind for making location committed
KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED, new Keybind(new KeyCodeCombination(KeyCode.C), () -> {
final Location.Urgency previousUrgency = location.get().getUrgency();
if (previousUrgency.equals(Location.Urgency.COMMITTED)) {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.NORMAL);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
}, "Made location " + getLocation().getNickname() + " committed", "hourglass-full");
} else {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.COMMITTED);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
}, "Made location " + getLocation().getNickname() + " normal (back from committed)", "hourglass-empty");
}
}));
hiddenAreaEntered();
}
@FXML
private void mouseExited() {
final LocationPresentation locationPresentation = (LocationPresentation) this.root;
if(!locationPresentation.isInteractable()) return;
circle.setCursor(Cursor.DEFAULT);
locationPresentation.animateHoverExited();
KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_URGENT);
KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED);
hiddenAreaExited();
}
@FXML
private void mousePressed(final MouseEvent event) {
final Component component = getComponent();
if (event.getButton().equals(MouseButton.SECONDARY)) {
dropDownMenu.show(JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT, 380, 160);
return;
}
event.consume();
if (((LocationPresentation) root).isPlaced()) {
final Edge unfinishedEdge = component.getUnfinishedEdge();
if (unfinishedEdge != null) {
unfinishedEdge.setTargetLocation(getLocation());
NailHelper.addMissingNails(unfinishedEdge);
} else {
// If shift is being held down, start drawing a new edge
if (event.isShiftDown()) {
final Edge newEdge = new Edge(getLocation());
KeyboardTracker.registerKeybind(KeyboardTracker.ABANDON_EDGE, new Keybind(new KeyCodeCombination(KeyCode.ESCAPE), () -> {
component.removeEdge(newEdge);
UndoRedoStack.forget();
}));
UndoRedoStack.push(() -> { // Perform
component.addEdge(newEdge);
}, () -> { // Undo
component.removeEdge(newEdge);
}, "Created edge starting from location " + getLocation().getNickname(), "add-circle");
}
// Otherwise, select the location
else {
if(((LocationPresentation) root).isInteractable()) {
SelectHelper.select(this);
}
}
// Update position for undo dragging
previousX = root.getLayoutX();
previousY = root.getLayoutY();
}
} else {
// Unbind presentation root x and y coordinates (bind the view properly to enable dragging)
root.layoutXProperty().unbind();
root.layoutYProperty().unbind();
// Bind the location to the presentation root x and y
getLocation().xProperty().bind(root.layoutXProperty());
getLocation().yProperty().bind(root.layoutYProperty());
// Notify that the location was placed
((LocationPresentation) root).setPlaced(true);
ComponentController.setPlacingLocation(null);
KeyboardTracker.unregisterKeybind(KeyboardTracker.ABANDON_LOCATION);
}
}
@FXML
private void mouseDragged(final MouseEvent event) {
// If the location is not a normal location (not initial/final) make it draggable
if (getLocation().getType() == Location.Type.NORMAL) {
// Calculate the potential new x alongside min and max values
final double newX = CanvasPresentation.mouseTracker.gridXProperty().subtract(getComponent().xProperty()).doubleValue();
final double minX = LocationPresentation.RADIUS + GRID_SIZE;
final double maxX = getComponent().getWidth() - LocationPresentation.RADIUS - GRID_SIZE;
// Drag according to min and max
if (newX < minX) {
root.setLayoutX(minX);
} else if (newX > maxX) {
root.setLayoutX(maxX);
} else {
root.setLayoutX(newX);
}
// Calculate the potential new y alongside min and max values
final double newY = CanvasPresentation.mouseTracker.gridYProperty().subtract(getComponent().yProperty()).doubleValue();
final double minY = LocationPresentation.RADIUS + ComponentPresentation.TOOL_BAR_HEIGHT + GRID_SIZE;
final double maxY = getComponent().getHeight() - LocationPresentation.RADIUS - GRID_SIZE;
// Drag according to min and max
if (newY < minY) {
root.setLayoutY(minY);
} else if (newY > maxY) {
root.setLayoutY(maxY);
} else {
root.setLayoutY(newY);
}
// Tell the mouse release action that we can store an update
wasDragged = true;
}
}
@FXML
private void mouseReleased(final MouseEvent event) {
if (wasDragged) {
// Add to undo redo stack
final double currentX = root.getLayoutX();
final double currentY = root.getLayoutY();
final double storePreviousX = previousX;
final double storePreviousY = previousY;
UndoRedoStack.push(() -> {
root.setLayoutX(currentX);
root.setLayoutY(currentY);
}, () -> {
root.setLayoutX(storePreviousX);
root.setLayoutY(storePreviousY);
}, String.format("Moved location from (%.0f,%.0f) to (%.0f,%.0f)", currentX, currentY, storePreviousX, storePreviousY), "pin-drop");
// Reset the was dragged boolean
wasDragged = false;
}
}
@FXML
private void hiddenAreaEntered() {
invariantTag.setOpacity(1);
nameTag.setOpacity(1);
}
@FXML
private void hiddenAreaExited() {
if (getLocation().getInvariant().equals("")) {
invariantTag.setOpacity(0);
} else {
invariantTag.setOpacity(1);
}
if(getLocation().getNickname().equals("")) {
nameTag.setOpacity(0);
} else {
nameTag.setOpacity(1);
}
}
@Override
public void color(final Color color, final Color.Intensity intensity) {
final Location location = getLocation();
// Set the color of the location
location.setColorIntensity(intensity);
location.setColor(color);
}
@Override
public Color getColor() {
return getLocation().getColor();
}
@Override
public Color.Intensity getColorIntensity() {
return getLocation().getColorIntensity();
}
@Override
public void select() {
((SelectHelper.Selectable) root).select();
}
@Override
public void deselect() {
((SelectHelper.Selectable) root).deselect();
}
}
|
package com.appliedanalog.uav.mav;
import com.appliedanalog.uav.utils.Log;
/**
* This class is used by MavStatusHandler to parse and represent whether or not
* certain sensors are present on the device.
* @author James
*/
public class MavComponentAvailability {
public class MavComponentStatus{
public MavComponentStatus(int index){
component_index = index;
}
public boolean parse(int p, int e, int h){
boolean np = ((p & (1 << component_index)) != 0);
boolean ne = ((e & (1 << component_index)) != 0);
boolean nh = ((h & (1 << component_index)) != 0);
boolean result = (np ^ present) || (ne ^ enabled) || (nh ^ health);
present = np;
enabled = ne;
health = nh;
return result;
}
/**
* Returns whether or not the specified component is present in the system.
*/
public boolean present(){
return present;
}
/**
* Returns whether or not the specified component is enabled.
*/
public boolean enabled(){
return enabled;
}
/**
* Returns false if the component is in "Bad health".
*/
public boolean health(){
return health;
}
private boolean present = false;
private boolean enabled = false;
private boolean health = false;
private int component_index;
}
public MavComponentAvailability(){
comp_status = new MavComponentStatus[32];
for(int x = 0; x < comp_status.length; x++){
comp_status[x] = new MavComponentStatus(x);
}
}
/**
* Process the bitmasks from the MAV system status message and return if the
* availability of any of the components has changed.
* @param presentMask
* @param enabledMask
* @param healthMask
* @return true if any of the statuses has changed.
*/
public boolean parseSensorBitmask(int presentMask, int enabledMask, int healthMask, boolean battRemAvailable, boolean currentAvailable){
boolean changed = false;
changed = (battRemAvailable != battery_remaining_available) || (currentAvailable != current_available);
battery_remaining_available = battRemAvailable;
current_available = currentAvailable;
for(MavComponentStatus status : comp_status){
changed = changed || status.parse(presentMask, healthMask, healthMask);
}
return changed;
}
public MavComponentStatus gyro(){ return comp_status[0]; }
public MavComponentStatus accelerometer(){ return comp_status[1]; }
public MavComponentStatus magnetometer(){ return comp_status[2]; }
public MavComponentStatus absolute_pressure(){ return comp_status[3]; }
public MavComponentStatus diff_pressure(){ return comp_status[4]; }
public MavComponentStatus gps(){ return comp_status[5]; }
public MavComponentStatus optical_flow(){ return comp_status[6]; }
public MavComponentStatus computer_vision(){ return comp_status[7]; }
public MavComponentStatus laser(){ return comp_status[8]; }
public MavComponentStatus ground_truth(){ return comp_status[9]; }
public MavComponentStatus angular_rate_control(){ return comp_status[10]; }
public MavComponentStatus attitude_stabilization(){ return comp_status[11]; }
public MavComponentStatus yaw_position(){ return comp_status[12]; }
public MavComponentStatus altitude_control(){ return comp_status[13]; }
public MavComponentStatus x_y_position_control(){ return comp_status[14]; }
public MavComponentStatus motor_control(){ return comp_status[15]; }
public boolean battery_remaining(){ return battery_remaining_available; }
public boolean current(){ return current_available; }
private MavComponentStatus[] comp_status;
boolean battery_remaining_available = false;
boolean current_available = false;
}
|
package org.mockito;
import org.mockito.internal.matchers.Any;
import org.mockito.internal.matchers.Contains;
import org.mockito.internal.matchers.EndsWith;
import org.mockito.internal.matchers.Equals;
import org.mockito.internal.matchers.InstanceOf;
import org.mockito.internal.matchers.Matches;
import org.mockito.internal.matchers.NotNull;
import org.mockito.internal.matchers.Null;
import org.mockito.internal.matchers.Same;
import org.mockito.internal.matchers.StartsWith;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.internal.util.Primitives;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import static org.mockito.internal.util.Primitives.defaultValue;
/**
* Allow flexible verification or stubbing. See also {@link AdditionalMatchers}.
*
* <p>
* {@link Mockito} extends ArgumentMatchers so to get access to all matchers just import Mockito class statically.
*
* <pre class="code"><code class="java">
* //stubbing using anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //you can also verify using argument matcher
* verify(mockedList).get(anyInt());
* </code></pre>
*
* Scroll down to see all methods - full list of matchers.
*
* <p>
* <b>Warning:</b><br/>
*
* If you are using argument matchers, <b>all arguments</b> have to be provided by matchers.
*
* E.g: (example shows verification but the same applies to stubbing):
* </p>
*
* <pre class="code"><code class="java">
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without argument matcher.
* </code></pre>
*
* <p>
* Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due static type safety imposed by java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
* </p>
*
* <h1>Custom Argument ArgumentMatchers</h1>
* <p>
* It is important to understand the use cases and available options for dealing with non-trivial arguments
* <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
* for given scenario and produce highest quality test (clean and maintainable).
* Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples.
* </p>
*/
@SuppressWarnings("unchecked")
public class ArgumentMatchers {
/**
* Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code>
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>false</code>.
*/
public static boolean anyBoolean() {
reportMatcher(new InstanceOf(Boolean.class));
return false;
}
/**
* Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static byte anyByte() {
reportMatcher(new InstanceOf(Byte.class));
return 0;
}
/**
* Any <code>char</code> or <strong>non-null</strong> <code>Character</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static char anyChar() {
reportMatcher(new InstanceOf(Character.class));
return 0;
}
/**
* Any int or <strong>non-null</strong> Integer.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static int anyInt() {
reportMatcher(new InstanceOf(Integer.class));
return 0;
}
/**
* Any <code>long</code> or <strong>non-null</strong> <code>Long</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static long anyLong() {
reportMatcher(new InstanceOf(Long.class));
return 0;
}
/**
* Any <code>float</code> or <strong>non-null</strong> <code>Float</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static float anyFloat() {
reportMatcher(new InstanceOf(Float.class));
return 0;
}
/**
* Any <code>double</code> or <strong>non-null</strong> <code>Double</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static double anyDouble() {
reportMatcher(new InstanceOf(Double.class));
return 0;
}
/**
* Any <code>short</code> or <strong>non-null</strong> <code>Short</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return <code>0</code>.
*/
public static short anyShort() {
reportMatcher(new InstanceOf(Short.class));
return 0;
}
/**
* Matches anything, including <code>null</code>.
*
* <p>
* This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}.
* See examples in javadoc for {@link ArgumentMatchers} class.
* </p>
*
* @return <code>null</code>.
* @see #any()
* @see #any(Class)
* @see #notNull()
*/
public static <T> T anyObject() {
reportMatcher(Any.ANY);
return null;
}
/**
* Any vararg, meaning any number and values of arguments.
*
* <p>
* Example:
* <pre class="code"><code class="java">
* //verification:
* mock.foo(1, 2);
* mock.foo(1, 2, 3, 4);
*
* verify(mock, times(2)).foo(anyVararg());
*
* //stubbing:
* when(mock.foo(anyVararg()).thenReturn(100);
*
* //prints 100
* System.out.println(mock.foo(1, 2));
* //also prints 100
* System.out.println(mock.foo(1, 2, 3, 4));
* </code></pre>
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class.
* </p>
*
* @return <code>null</code>.
* @see #any()
* @see #any(Class)
* @deprecated as of 2.0 use {@link #any()
*/
@Deprecated
public static <T> T anyVararg() {
any();
return null;
}
/**
* Matches any object of given type, excluding nulls.
*
* <p>
* This matcher will perform a type check with the given type, thus excluding values.
*
* See examples in javadoc for {@link ArgumentMatchers} class.
*
* This is an alias of: {@link #isA(Class)}}
* </p>
*
* <p><strong>Notes : </strong><br/>
* <ul>
* <li>For primitive types use {@link #anyChar()} family.</li>
* <li>Since Mockito 2.0 this method will perform a type check thus <code>null</code> values are not authorized.</li>
* <li>Since mockito 2.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li>
* </ul>
* </p>
*
* @return <code>null</code>.
* @see #any()
* @see #anyObject()
* @see #anyVararg()
* @see #isA(Class)
* @see #notNull()
*/
public static <T> T any(Class<T> clazz) {
reportMatcher(Any.ANY);
return defaultValue(clazz);
}
/**
* Matches <strong>anything</strong>, including nulls and varargs.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)}
* </p>
*
* <p>
* <strong>Notes : </strong><br/>
* <ul>
* <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li>
* <li>Since mockito 2.0 {@link #any(Class)} is not anymore an alias of this method.</li>
* </ul>
* </p>
*
* @return <code>null</code>.
*
* @see #any(Class)
* @see #anyObject()
* @see #anyVararg()
* @see #anyChar()
* @see #anyInt()
* @see #anyBoolean()
* @see #anyCollectionOf(Class)
*/
public static <T> T any() {
return anyObject();
}
/**
* Any <strong>non-null</strong> <code>String</code>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @return empty String ("")
*/
public static String anyString() {
reportMatcher(new InstanceOf(String.class));
return "";
}
/**
* Any <strong>non-null</strong> <code>List</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return empty List.
* @see #anyListOf(Class)
*/
public static List anyList() {
reportMatcher(new InstanceOf(List.class));
return new LinkedList();
}
/**
* Any <strong>non-null</strong> <code>List</code>.
*
* Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to
* <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
*
* <p>
* This method doesn't do type checks of the list content with the given type parameter, it is only there
* to avoid casting in the code.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type owned by the list to avoid casting
* @return empty List.
* @see #anyList()
*/
public static <T> List<T> anyListOf(Class<T> clazz) {
return anyList();
}
/**
* Any <strong>non-null</strong> <code>Set</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return empty Set
* @see #anySetOf(Class)
*/
public static Set anySet() {
reportMatcher(new InstanceOf(Set.class));
return new HashSet();
}
/**
* Any <strong>non-null</strong> <code>Set</code>.
*
* <p>
* Generic friendly alias to {@link ArgumentMatchers#anySet()}.
* It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
* </p>
*
* <p>
* This method doesn't do type checks of the set content with the given type parameter, it is only there
* to avoid casting in the code.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type owned by the Set to avoid casting
* @return empty Set
* @see #anySet()
*/
public static <T> Set<T> anySetOf(Class<T> clazz) {
return anySet();
}
/**
* Any <strong>non-null</strong> <code>Map</code>.
*
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return empty Map.
* @see #anyMapOf(Class, Class)
*/
public static Map anyMap() {
reportMatcher(new InstanceOf(Map.class));
return new HashMap();
}
/**
* Any <strong>non-null</strong> <code>Map</code>.
*
* <p>
* Generic friendly alias to {@link ArgumentMatchers#anyMap()}.
* It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
* </p>
*
* <p>
* This method doesn't do type checks of the map content with the given type parameter, it is only there
* to avoid casting in the code.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param keyClazz Type of the map key to avoid casting
* @param valueClazz Type of the value to avoid casting
* @return empty Map.
* @see #anyMap()
*/
public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {
return anyMap();
}
/**
* Any <strong>non-null</strong> <code>Collection</code>.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @return empty Collection.
* @see #anyCollectionOf(Class)
*/
public static Collection anyCollection() {
reportMatcher(new InstanceOf(Collection.class));
return new LinkedList();
}
/**
* Any <strong>non-null</strong> <code>Collection</code>.
*
* <p>
* Generic friendly alias to {@link ArgumentMatchers#anyCollection()}.
* It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
* </p>
*
* <p>
* This method doesn't do type checks of the collection content with the given type parameter, it is only there
* to avoid casting in the code.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type owned by the collection to avoid casting
* @return empty Collection.
* @see #anyCollection()
*/
public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
return anyCollection();
}
/**
* <code>Object</code> argument that implements the given class.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param <T> the accepted type.
* @param type the class of the accepted type.
* @return <code>null</code>.
*/
public static <T> T isA(Class<T> type) {
reportMatcher(new InstanceOf(type));
return defaultValue(type);
}
/**
* <code>boolean</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static boolean eq(boolean value) {
reportMatcher(new Equals(value));
return false;
}
/**
* <code>byte</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static byte eq(byte value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>char</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static char eq(char value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>double</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static double eq(double value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>float</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static float eq(float value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>int</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static int eq(int value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>long</code> argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>0</code>.
*/
public static long eq(long value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* <code>short</code> argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param value the given value.
* @return <code>0</code>.
*/
public static short eq(short value) {
reportMatcher(new Equals(value));
return 0;
}
/**
* Object argument that is equal to the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @return <code>null</code>.
*/
public static <T> T eq(T value) {
reportMatcher(new Equals(value));
if (value == null)
return null;
return (T) Primitives.defaultValue(value.getClass());
}
/**
* Object argument that is reflection-equal to the given value with support for excluding
* selected fields from a class.
*
* <p>
* This matcher can be used when equals() is not implemented on compared objects.
* Matcher uses java reflection API to compare fields of wanted and actual object.
* </p>
*
* <p>
* Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from
* apache commons library.
* <p>
* <b>Warning</b> The equality check is shallow!
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param value the given value.
* @param excludeFields fields to exclude, if field does not exist it is ignored.
* @return <code>null</code>.
*/
public static <T> T refEq(T value, String... excludeFields) {
reportMatcher(new ReflectionEquals(value, excludeFields));
return null;
}
/**
* Object argument that is the same as the given value.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param <T> the type of the object, it is passed through to prevent casts.
* @param value the given value.
* @return <code>null</code>.
*/
public static <T> T same(T value) {
reportMatcher(new Same(value));
if (value == null)
return null;
return (T) Primitives.defaultValue(value.getClass());
}
/**
* <code>null</code> argument.
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @return <code>null</code>.
* @see #isNull(Class)
* @see #isNotNull()
* @see #isNotNull(Class)
*/
public static Object isNull() {
reportMatcher(Null.NULL);
return null;
}
/**
* <code>null</code> argument.
*
* <p>
* The class argument is provided to avoid casting.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
* @see #isNull()
* @see #isNotNull()
* @see #isNotNull(Class)
*/
public static <T> T isNull(Class<T> clazz) {
reportMatcher(Null.NULL);
return null;
}
/**
* Not <code>null</code> argument.
*
* <p>
* Alias to {@link ArgumentMatchers#isNotNull()}
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @return <code>null</code>.
*/
public static Object notNull() {
reportMatcher(NotNull.NOT_NULL);
return null;
}
/**
* Not <code>null</code> argument, not necessary of the given class.
*
* <p>
* The class argument is provided to avoid casting.
*
* Alias to {@link ArgumentMatchers#isNotNull(Class)}
* <p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
* @see #isNotNull()
* @see #isNull()
* @see #isNull(Class)
*/
public static <T> T notNull(Class<T> clazz) {
reportMatcher(NotNull.NOT_NULL);
return null;
}
/**
* Not <code>null</code> argument.
*
* <p>
* Alias to {@link ArgumentMatchers#notNull()}
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @return <code>null</code>.
* @see #isNotNull(Class)
* @see #isNull()
* @see #isNull(Class)
*/
public static Object isNotNull() {
return notNull();
}
/**
* Not <code>null</code> argument, not necessary of the given class.
*
* <p>
* The class argument is provided to avoid casting.
* Alias to {@link ArgumentMatchers#notNull(Class)}
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
* </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
*/
public static <T> T isNotNull(Class<T> clazz) {
return notNull(clazz);
}
/**
* <code>String</code> argument that contains the given substring.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param substring the substring.
* @return empty String ("").
*/
public static String contains(String substring) {
reportMatcher(new Contains(substring));
return "";
}
/**
* <code>String</code> argument that matches the given regular expression.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param regex the regular expression.
* @return empty String ("").
*/
public static String matches(String regex) {
reportMatcher(new Matches(regex));
return "";
}
/**
* <code>String</code> argument that ends with the given suffix.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param suffix the suffix.
* @return empty String ("").
*/
public static String endsWith(String suffix) {
reportMatcher(new EndsWith(suffix));
return "";
}
/**
* <code>String</code> argument that starts with the given prefix.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param prefix the prefix.
* @return empty String ("").
*/
public static String startsWith(String prefix) {
reportMatcher(new StartsWith(prefix));
return "";
}
/**
* Allows creating custom argument matchers.
*
* <p>
* This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide.
* <b>NullPointerException</b> auto-unboxing caveat is described below.
* </p>
*
* <p>
* It is important to understand the use cases and available options for dealing with non-trivial arguments
* <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
* for given scenario and produce highest quality test (clean and maintainable).
* Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples.
* </p>
*
* <p>
* <b>NullPointerException</b> auto-unboxing caveat.
* In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method.
* This way you will avoid <code>NullPointerException</code> during auto-unboxing.
* Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem.
* Hopefully, the javadoc describes the problem and solution well.
* If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker.
* </p>
*
* <p>
* See examples in javadoc for {@link ArgumentMatcher} class
* </p>
*
* @param matcher decides whether argument matches
* @return <code>null</code>.
*/
public static <T> T argThat(ArgumentMatcher<T> matcher) {
reportMatcher(matcher);
return null;
}
/**
* Allows creating custom <code>char</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static char charThat(ArgumentMatcher<Character> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>boolean</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>false</code>.
*/
public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) {
reportMatcher(matcher);
return false;
}
/**
* Allows creating custom <code>byte</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static byte byteThat(ArgumentMatcher<Byte> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>short</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static short shortThat(ArgumentMatcher<Short> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>int</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static int intThat(ArgumentMatcher<Integer> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>long</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static long longThat(ArgumentMatcher<Long> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>float</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static float floatThat(ArgumentMatcher<Float> matcher) {
reportMatcher(matcher);
return 0;
}
/**
* Allows creating custom <code>double</code> argument matchers.
*
* Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static double doubleThat(ArgumentMatcher<Double> matcher) {
reportMatcher(matcher);
return 0;
}
private static void reportMatcher(ArgumentMatcher<?> matcher) {
mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher);
}
}
|
package com.groupbyinc.api.tags;
import com.groupbyinc.api.model.AbstractRecord;
import com.groupbyinc.api.model.AbstractResults;
import com.groupbyinc.api.model.Navigation;
import com.groupbyinc.api.model.Refinement;
import com.groupbyinc.api.model.refinement.RefinementRange;
import com.groupbyinc.api.model.refinement.RefinementValue;
import org.junit.Test;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FunctionsTest {
@Test
public void testUncamel() throws Exception {
assertEquals(
"Java API Reference", Functions.uncamel("javaApiReference"));
assertEquals(
"Java API Reference", Functions.uncamel("javaAPIReference"));
assertEquals("GSA Configuration", Functions.uncamel("gsaConfiguration"));
assertEquals(
"Pier 1 Load Balancing", Functions.uncamel("Pier1LoadBalancing"));
assertEquals(".NET API", Functions.uncamel(".NetApi"));
assertEquals("Network Settings", Functions.uncamel("NetworkSettings"));
assertEquals("FAQ", Functions.uncamel("faq"));
// assertEquals("FAQs", Functions.uncamel("faqS"));
}
@Test
public void testReverse() throws Exception {
List<String> reverse = Functions.reverse(asList("1", "2", "3"));
assertEquals("[3, 2, 1]", reverse.toString());
}
private static class RecordMock extends AbstractRecord<RecordMock> {
}
private static class ResultsMock extends AbstractResults<RecordMock, ResultsMock> {
}
@Test
public void testRefinementSelected() {
ResultsMock r = new ResultsMock();
r.setSelectedNavigation(
asList(
new Navigation().setName("a").setOr(true).setRefinements(
asList(
new RefinementValue().setValue("1"),
new RefinementValue().setValue("2"))),
new Navigation().setName("b").setRange(true).setRefinements(
singletonList((Refinement) new RefinementRange().setLow("0").setHigh("1"))),
new Navigation().setName("c").setOr(false).setRefinements(
asList(
new RefinementValue().setValue("1"),
new RefinementValue().setValue("2")))
));
assertFalse(Functions.isRefinementSelected(r, null, "1"));
assertFalse(Functions.isRefinementSelected(r, "", "1"));
assertFalse(Functions.isRefinementSelected(r, "a", null));
assertFalse(Functions.isRefinementSelected(r, "a", ""));
assertFalse(Functions.isRefinementSelected(r, "a", "3"));
assertFalse(Functions.isRefinementSelected(r, "b", "1"));
assertFalse(Functions.isRefinementSelected(r, "c", "3"));
assertTrue(Functions.isRefinementSelected(r, "a", "1"));
assertTrue(Functions.isRefinementSelected(r, "a", "2"));
assertTrue(Functions.isRefinementSelected(r, "c", "1"));
assertTrue(Functions.isRefinementSelected(r, "c", "2"));
}
}
|
package amerifrance.guideapi.gui;
import amerifrance.guideapi.GuideMod;
import amerifrance.guideapi.api.impl.Book;
import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract;
import amerifrance.guideapi.api.impl.abstraction.EntryAbstract;
import amerifrance.guideapi.api.util.GuiHelper;
import amerifrance.guideapi.button.ButtonBack;
import amerifrance.guideapi.button.ButtonNext;
import amerifrance.guideapi.button.ButtonPrev;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.config.GuiUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GuiSearch extends GuiBase {
private Book book;
private ResourceLocation outlineTexture;
private ResourceLocation pageTexture;
private ButtonNext buttonNext;
private ButtonPrev buttonPrev;
private GuiTextField searchField;
private GuiScreen parent;
private List<List<Pair<EntryAbstract, CategoryAbstract>>> searchResults;
private int currentPage = 0;
private String lastQuery = "";
public GuiSearch(Book book, EntityPlayer player, ItemStack bookStack, GuiScreen parent) {
super(player, bookStack);
this.book = book;
this.pageTexture = book.getPageTexture();
this.outlineTexture = book.getOutlineTexture();
this.parent = parent;
this.searchResults = getMatches(book, null, player, bookStack);
}
@Override
public void initGui() {
buttonList.clear();
guiLeft = (this.width - this.xSize) / 2;
guiTop = (this.height - this.ySize) / 2;
addButton(new ButtonBack(0, guiLeft + xSize / 6, guiTop, this));
addButton(buttonNext = new ButtonNext(1, guiLeft + 4 * xSize / 6, guiTop + 5 * ySize / 6, this));
addButton(buttonPrev = new ButtonPrev(2, guiLeft + xSize / 5, guiTop + 5 * ySize / 6, this));
searchField = new GuiTextField(3, fontRenderer, guiLeft + 43, guiTop + 12, 100, 10);
searchField.setEnableBackgroundDrawing(false);
searchField.setFocused(true);
searchResults = getMatches(book, null, player, bookStack);
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
mc.getTextureManager().bindTexture(pageTexture);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
mc.getTextureManager().bindTexture(outlineTexture);
drawTexturedModalRectWithColor(guiLeft, guiTop, 0, 0, xSize, ySize, book.getColor());
drawRect(searchField.x - 1, searchField.y - 1, searchField.x + searchField.width + 1, searchField.y + searchField.height + 1, new Color(166, 166, 166, 128).getRGB());
drawRect(searchField.x, searchField.y, searchField.x + searchField.width, searchField.y + searchField.height, new Color(58, 58, 58, 128).getRGB());
searchField.drawTextBox();
int entryX = guiLeft + 37;
int entryY = guiTop + 30;
if (searchResults.size() != 0 && currentPage >= 0 && currentPage < searchResults.size()) {
List<Pair<EntryAbstract, CategoryAbstract>> pageResults = searchResults.get(currentPage);
for (Pair<EntryAbstract, CategoryAbstract> entry : pageResults) {
entry.getLeft().draw(book, entry.getRight(), entryX, entryY, 4 * xSize / 6, 10, mouseX, mouseY, this, fontRenderer);
entry.getLeft().drawExtras(book, entry.getRight(), entryX, entryY, 4 * xSize / 6, 10, mouseX, mouseY, this, fontRenderer);
if (GuiHelper.isMouseBetween(mouseX, mouseY, entryX, entryY, 4 * xSize / 6, 10)) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))
GuiUtils.drawHoveringText(Lists.newArrayList(entry.getRight().getLocalizedName()), mouseX, mouseY, width, height, 300, fontRenderer);
if (Mouse.isButtonDown(0)) {
GuideMod.PROXY.openEntry(book, entry.getRight(), entry.getLeft(), player, bookStack);
return;
}
}
entryY += 13;
}
}
buttonPrev.visible = currentPage != 0;
buttonNext.visible = currentPage != searchResults.size() - 1 && !searchResults.isEmpty();
super.drawScreen(mouseX, mouseY, partialTicks);
}
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
super.mouseClicked(mouseX, mouseY, mouseButton);
if (mouseButton == 1) {
if (GuiHelper.isMouseBetween(mouseX, mouseY, searchField.x, searchField.y, searchField.width, searchField.height)) {
searchField.setText("");
lastQuery = "";
searchResults = getMatches(book, "", player, bookStack);
return;
} else
mc.displayGuiScreen(parent);
}
searchField.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public void handleMouseInput() throws IOException {
super.handleMouseInput();
int movement = Mouse.getEventDWheel();
if (movement < 0 && buttonNext.visible && currentPage <= searchResults.size())
currentPage++;
else if (movement > 0 && buttonPrev.visible && currentPage > 0)
currentPage
}
@Override
public void keyTyped(char typedChar, int keyCode) {
if (!searchField.isFocused())
super.keyTyped(typedChar, keyCode);
if (keyCode == Keyboard.KEY_ESCAPE)
searchField.setFocused(false);
searchField.textboxKeyTyped(typedChar, keyCode);
if (!searchField.getText().equalsIgnoreCase(lastQuery)) {
lastQuery = searchField.getText();
searchResults = getMatches(book, searchField.getText(), player, bookStack);
if (currentPage > searchResults.size())
currentPage = searchResults.size() - 1;
}
}
@Override
public void actionPerformed(GuiButton button) {
switch (button.id) {
case 0: {
mc.displayGuiScreen(parent);
break;
}
case 1: {
if (currentPage <= searchResults.size() - 1)
currentPage++;
break;
}
case 2: {
if (currentPage > 0)
currentPage
break;
}
}
}
@Nonnull
static List<List<Pair<EntryAbstract, CategoryAbstract>>> getMatches(Book book, @Nullable String query, EntityPlayer player, ItemStack bookStack) {
List<Pair<EntryAbstract, CategoryAbstract>> discovered = Lists.newArrayList();
for (CategoryAbstract category : book.getCategoryList()) {
if (!category.canSee(player, bookStack))
continue;
for (EntryAbstract entry : category.entries.values()) {
if (!entry.canSee(player, bookStack))
continue;
if (Strings.isNullOrEmpty(query) || entry.getLocalizedName().toLowerCase(Locale.ENGLISH).contains(query.toLowerCase(Locale.ENGLISH)))
discovered.add(Pair.of(entry, category));
}
}
return Lists.partition(discovered, 10);
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.myrobotlab.codec.CodecJson;
import org.myrobotlab.framework.MrlException;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.ProcessData;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.lang.NameGenerator;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.net.Http;
import org.slf4j.Logger;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
/**
* <pre>
*
* Agent is responsible for managing running instances of myrobotlab. It
* can start, stop and update myrobotlab.
*
*
* FIXME - ws client connectivity and communication !!!
* FIXME - Cli client ws enabled !!
* FIXME - capability to update Agent from child
* FIXME - move CmdLine defintion to Runtime
* FIXME - convert Runtime's cmdline processing to CmdOptions Fixme - remove CmdLine
* FIXME !!! - remove stdin/stdout !!!! use sockets only
*
* FIXME - there are at least 3 different levels of updating
* 1. a global thread which only "checks" for updates
* 2. the possibility of just downloading an update (per instance)
* 3. the possibility of auto-restarting after a download is completed (per instance)
*
* FIXME - auto update log .. sparse log of only updates and their results ...
* FIXME - test changing version prefix .. e.g. 1.2.
* FIXME - testing test - without version test - remote unaccessable
* FIXME - spawn must be synchronized 2 threads (the timer and the user)
* FIXME - test naming an instance FIXME - test starting an old version
* FIXME - make hidden check latest version interval and make default interval check large
* FIXME - change Runtime's cli !!!
* FIXME - check user define services for Agent
*
* </pre>
*/
public class Agent extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Agent.class);
final Map<String, ProcessData> processes = new ConcurrentHashMap<String, ProcessData>();
transient static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmssSSS");
Platform platform = Platform.getLocalInstance();
transient WebGui webgui = null;
int port = 8887;
String address = "127.0.0.1";
String currentBranch;
String currentVersion;
/**
* auto update - automatically checks for updates and WILL update any running
* mrl instance automatically
*/
boolean autoUpdate = false;
/**
* autoCheckForUpdate - checks automatically checks for updates after some
* interval but does not automatically update - it publishes events of new
* availability of updates but does not update
*/
boolean autoCheckForUpdate = false;
Set<String> possibleVersions = new HashSet<String>();
// for more info -
// WARNING Jenkins url api format for multi-branch pipelines is different from
// maven builds !
final static String REMOTE_BUILDS_URL = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/job/%s/api/json?tree=builds[number,status,timestamp,id,result]";
final static String REMOTE_JAR_URL = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/job/%s/%s/artifact/target/myrobotlab.jar";
final static String REMOTE_MULTI_BRANCH_JOBS = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/api/json";
boolean checkRemoteVersions = false;
/**
* command line options for the agent
*/
AgentCmdOptions options;
String versionPrefix = "1.1.";
/**
* singleton for security purposes
*/
transient static Agent agent;
String rootBranchDir = "branches";
/**
* development variable to force version "unknown" to be either greatest or
* smallest version for development
*/
private boolean unknownIsGreatest = false;
public static class WorkflowMultiBranchProject {
String name;
WorkflowJob[] jobs;
}
/**
* Jenkins data structure to describe jobs
*/
public static class WorkflowJob {
String name;
String url;
String color;
WorkflowRun lastSuccessfulBuild;
WorkflowRun[] builds;
}
/**
* Jenkins data structure to describe builds
*/
public static class WorkflowRun {
String id;
Integer number;
String result;
Long timestamp;
}
// FIXME - change this to hour for production ...
// long updateCheckIntervalMs = 60 * 60 * 1000; // every hour
long updateCheckIntervalMs = 60 * 1000; // every minute
List<Status> updateLog = new ArrayList<>();
/**
* Update thread - we cannot use addTask as a long update could pile up a
* large set of updates to process quickly in series. Instead, we have a
* simple single class which is always single threaded to process updates.
*
*/
class Updater implements Runnable {
transient Agent agent = null;
transient Thread thread = null;
ProcessData.stateType state = ProcessData.stateType.stopped;
public Updater(Agent agent) {
this.agent = agent;
}
@Override
public void run() {
state = ProcessData.stateType.running;
updateLog("info", "updater running");
try {
while (true) {
state = ProcessData.stateType.sleeping;
updateLog("info", "updater sleeping");
sleep(updateCheckIntervalMs);
state = ProcessData.stateType.updating;
updateLog("info", "updater updating");
agent.update();
}
} catch (Exception e) {
log.info("updater threw", e);
}
log.info("updater stopping");
updateLog("info", "updater stopping");
state = ProcessData.stateType.stopped;
}
synchronized public void start() {
if (state == ProcessData.stateType.stopped) {
thread = new Thread(this, getName() + ".updater");
thread.start();
updateLog("info", "updater starting");
} else {
log.warn("updater busy state = %s", state);
}
}
synchronized public void stop() {
if (state != ProcessData.stateType.stopped) {
// we'll wait if its in the middle of an update
while (state == ProcessData.stateType.updating) {
log.warn("updater currently updating, waiting for 5 seconds...");
sleep(5000);
}
// most likely the thread is a sleeping state
// so, we wake it up quickly to die ;)
thread.interrupt();
}
}
}
public static String BRANCHES_ROOT = "branches";
Updater updater;
public Agent(String n) throws IOException {
super(n);
updater = new Updater(this);
currentBranch = Platform.getLocalInstance().getBranch();
currentVersion = Platform.getLocalInstance().getVersion();
log.info("Agent {} Pid {} is alive", n, Platform.getLocalInstance().getPid());
// basic setup - minimally we make a directory
// and instance folder of the same branch & version as the
// agent jar
setup();
// user has decided to look for updates ..
if (autoUpdate || checkRemoteVersions) {
invoke("getVersions", currentBranch);
}
}
public String getDir(String branch, String version) {
if (branch == null) {
branch = Platform.getLocalInstance().getBranch();
}
if (version == null) {
try {
version = getLatestVersion(branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
return BRANCHES_ROOT + File.separator + branch + "-" + version;
}
public String getJarName(String branch, String version) {
return getDir(branch, version) + File.separator + "myrobotlab.jar";
}
private void setup() throws IOException {
String agentBranch = Platform.getLocalInstance().getBranch();
String agentVersion = Platform.getLocalInstance().getVersion();
// location of the agent's branch (and version)
String agentVersionPath = getDir(agentBranch, agentVersion);
if (!new File(agentVersionPath).exists()) {
File branchDir = new File(agentVersionPath);
branchDir.mkdirs();
}
String agentMyRobotLabJar = getJarName(agentBranch, agentVersion);
if (!new File(agentMyRobotLabJar).exists()) {
String agentJar = new java.io.File(Agent.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
if (!new File(agentJar).exists() || !agentJar.endsWith(".jar")) {
// not operating in released runtime mode - probably operating in ide
String ideTargetJar = new File(System.getProperty("user.dir") + File.separator + "target" + File.separator + "myrobotlab.jar").getAbsolutePath();
if (!new File(ideTargetJar).exists()) {
error("no source agent jar can be found checked:\n%s\n%s\nare you using ide? please package a build (mvn package -DskipTest)", agentJar, ideTargetJar);
} else {
agentJar = ideTargetJar;
}
}
log.info("on branch {} copying agent's current jar to appropriate location {} -> {}", currentBranch, agentJar, agentMyRobotLabJar);
Files.copy(Paths.get(agentJar), Paths.get(agentMyRobotLabJar), StandardCopyOption.REPLACE_EXISTING);
}
}
public void startWebGui() {
try {
if (webgui == null) {
webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.setPort(port);
webgui.setAddress(address);
webgui.startService();
} else {
log.info("webgui already started");
}
} catch (Exception e) {
log.error("startWebGui threw", e);
}
}
public void autoUpdate(boolean b) {
if (b) {
// addTask("update", 1000 * 60, 0, "update");
updater.start();
} else {
// purgeTask("update");
updater.stop();
}
}
/**
* FIXME !!! - i believe in task for these pipe up !!! NOT GOOD _ must have
* its own thread then !!
*
* called by the autoUpdate task which is scheduled every minute to look for
* updates from the build server
*/
public void update() {
log.info("update");
for (String key : processes.keySet()) {
ProcessData process = processes.get(key);
if (!process.autoUpdate) {
log.info("not autoUpdate");
continue;
}
try {
// getRemoteVersions
log.info("getting version");
String version = getLatestVersion(process.branch, true);
if (version == null || version.equals(process.version)) {
log.info("same version {}", version);
continue;
}
log.info("WOOHOO ! updating to version {}", version);
getLatestJar(process.branch);
process.version = version;
log.info("WOOHOO ! updated !");
if (process.isRunning()) {
log.info("its running - we should restart");
restart(process.id);
log.info("restarted");
}
} catch (Exception e) {
log.error("proccessing updates from scheduled task threw", e);
}
}
}
/**
* gets the latest jar if allowed to check remote ....
*
* @param branch
*/
public void getLatestJar(String branch) {
try {
// check for latest
String version = getLatestVersion(branch, true);
// check if branch and version exist locally
if (!existsLocally(branch, version)) {
log.info("found update - getting new jar {} {}", branch, version);
getJar(branch, version);
// download latest to the appropriate directory
// mkdirs
// download file
if (!verifyJar(branch, version)) {
}
log.info("successfully downloaded {} {}", branch, version);
}
} catch (Exception e) {
error(e);
}
}
// FIXME - implement :)
private boolean verifyJar(String branch, String version) {
return true;
}
synchronized public void getJar(String branch, String version) {
new File(getDir(branch, version)).mkdirs();
String build = getBuildId(version);
// this
Http.getSafePartFile(String.format(REMOTE_JAR_URL, branch, build), getJarName(branch, version));
}
public String getBuildId(String version) {
String[] parts = version.split("\\.");
return parts[2];
}
public String getLatestVersion(String branch, Boolean allowRemote) throws MrlException {
Set<String> versions = getVersions(branch, allowRemote);
return getLatestVersion(versions);
}
public String getLatestVersion(Set<String> versions) throws MrlException {
String latest = null;
for (String version : versions) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* checks to see if a branch / version jar exists on the local filesystem
*
* @param branch
* @param version
* @return
*/
public boolean existsLocally(String branch, String version) {
return new File(getJarName(branch, version)).exists();
}
/**
* if there is a single instance - just restart it ...
*
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public synchronized void restart(String id) throws IOException, URISyntaxException, InterruptedException {
log.info("restarting process {}", id);
kill(id); // FIXME - kill should include prepare to shutdown ...
sleep(2000);
spawn(id);
}
private void spawn(String id) {
try {
if (processes.containsKey(id)) {
spawn(processes.get(id));
} else {
log.error("agent does not know about process id {}", id);
}
} catch (Exception e) {
log.error("spawn({}) threw ", id, e);
}
}
/**
* return a non-running process structure from an existing one with a new id
*
* @param id
* id
* @return process data
*
*/
public ProcessData copy(String id) {
if (!processes.containsKey(id)) {
log.error("cannot copy %s does not exist", id);
return null;
}
ProcessData pd = processes.get(id);
ProcessData pd2 = new ProcessData(pd);
pd2.startTs = null;
pd2.stopTs = null;
String[] parts = id.split("\\.");
if (parts.length == 4) {
try {
int instance = Integer.parseInt(parts[3]);
++instance;
} catch (Exception e) {
}
} else {
pd2.id = id + ".0";
}
processes.put(pd2.id, pd2);
if (agent != null) {
agent.broadcastState();
}
return pd2;
}
public void copyAndStart(String id) throws IOException {
// returns a non running copy with new process id
// on the processes list
ProcessData pd2 = copy(id);
spawn(pd2);
if (agent != null) {
agent.broadcastState();
}
}
/**
* gets id from name
*
* @param name
* name
* @return integer
*
*/
public String getId(String name) {
for (String pid : processes.keySet()) {
if (pid.equals(name)) {
return processes.get(pid).id;
}
}
return null;
}
/**
* get the current branches being built in a Jenkins multi-branch pipeline job
*
* @return
*/
static public Set<String> getBranches() {
Set<String> possibleBranches = new HashSet<String>();
try {
byte[] r = Http.get(REMOTE_MULTI_BRANCH_JOBS);
if (r != null) {
String json = new String(r);
CodecJson decoder = new CodecJson();
WorkflowMultiBranchProject project = (WorkflowMultiBranchProject) decoder.decode(json, WorkflowMultiBranchProject.class);
for (WorkflowJob job : project.jobs) {
possibleBranches.add(job.name);
}
}
} catch (Exception e) {
log.error("getRemoteBranches threw", e);
}
return possibleBranches;
}
boolean isGreaterThan(String version1, String version2) throws MrlException {
if (version1 == null) {
return false;
}
if (version2 == null) {
return true;
}
// special development behavior
if (version1.equals("unknown")) {
return (unknownIsGreatest) ? true : false;
}
if (version2.equals("unknown")) {
return !((unknownIsGreatest) ? true : false);
}
String[] parts1 = version1.split("\\.");
String[] parts2 = version2.split("\\.");
if (parts1.length != 3 || parts2.length != 3) {
throw new MrlException("invalid version isGreaterThan(%s, %s)", version1, version2);
}
for (int i = 0; i < 3; ++i) {
int v1 = Integer.parseInt(parts1[i]);
int v2 = Integer.parseInt(parts2[i]);
if (v1 != v2) {
return v1 > v2;
}
}
throw new MrlException("invalid isGreaterThan(%s, %s)", version1, version2);
}
/**
* This method gets all the version on a particular branch, if allowed remote
* access it will ask the build server what successful builds exist
*
* @param branch
* @param allowRemote
* @return
*/
synchronized public Set<String> getVersions(String branch, Boolean allowRemote) {
Set<String> versions = new HashSet<String>();
versions.addAll(getLocalVersions(branch));
if (allowRemote) {
versions.addAll(getRemoteVersions(branch));
}
if (versions.size() != possibleVersions.size()) {
possibleVersions = versions;
broadcastState();
}
return versions;
}
public Set<String> getRemoteVersions(String branch) {
Set<String> versions = new HashSet<String>();
try {
byte[] data = Http.get(String.format(REMOTE_BUILDS_URL, branch));
if (data != null) {
CodecJson decoder = new CodecJson();
String json = new String(data);
WorkflowJob job = (WorkflowJob) decoder.decode(json, WorkflowJob.class);
if (job.builds != null) {
for (WorkflowRun build : job.builds) {
if ("SUCCESS".equals(build.result)) {
versions.add(versionPrefix + build.id);
}
}
}
}
} catch (Exception e) {
error(e);
}
return versions;
}
public String getLatestLocalVersion(String branch) throws MrlException {
Set<String> allLocal = getLocalVersions(branch);
String latest = null;
for (String version : allLocal) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
public Set<String> getLocalVersions(String branch) {
Set<String> versions = new HashSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
if (file.getName().startsWith(branch)) {
String version = file.getName().substring(branch.length() + 1);// getFileVersion(file.getName());
if (version != null) {
versions.add(version);
}
}
}
}
return versions;
}
static public String getFileVersion(String name) {
if (!name.startsWith("myrobotlab.")) {
return null;
}
String[] parts = name.split("\\.");
if (parts.length != 5) {
return null;
}
String version = String.format("%s.%s.%s", parts[1], parts[2], parts[3]);
return version;
}
/**
* get a list of all the processes currently governed by this Agent
*
* @return hash map, int to process data
*/
public Map<String, ProcessData> getProcesses() {
return processes;
}
// by id (or by pid?)
public String kill(String id) {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
if (processes.containsKey(id)) {
if (agent != null) {
agent.info("terminating %s", id);
}
ProcessData process = processes.get(id);
process.process.destroy();
process.state = ProcessData.stateType.stopped;
if (process.monitor != null) {
process.monitor.interrupt();
process.monitor = null;
}
// remove(processes.get(name));
if (agent != null) {
agent.info("{} haz beeen terminated", id);
agent.broadcastState();
}
return id;
}
error("kill unknown process id {}", id);
return null;
}
/*
* BAD IDEA - data type ambiguity is a drag public Integer kill(String name) {
* return kill(getId(name)); }
*/
public void killAll() {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
for (String id : processes.keySet()) {
kill(id);
}
log.info("no survivors sir...");
if (agent != null) {
agent.broadcastState();
}
}
public void killAndRemove(String id) {
if (processes.containsKey(id)) {
kill(id);
processes.remove(id);
if (agent != null) {
agent.broadcastState();
}
}
}
/**
* list processes
*
* @return lp ?
*/
public String[] lp() {
Object[] objs = processes.keySet().toArray();
String[] pd = new String[objs.length];
for (int i = 0; i < objs.length; ++i) {
Integer id = (Integer) objs[i];
ProcessData p = processes.get(id);
pd[i] = String.format("%s - %s [%s - %s]", id, p.id, p.branch, p.version);
}
return pd;
}
public String publishTerminated(String id) {
log.info("publishTerminated - terminated {} - restarting", id);
if (!processes.containsKey(id)) {
log.error("processes {} not found");
return id;
}
// if you don't fork with Agent allowed to
// exist without instances - then
if (!options.fork) {
// spin through instances - if I'm the only
// thing left - terminate
boolean processesStillRunning = false;
for (ProcessData pd : processes.values()) {
if (pd.isRunning() || pd.isRestarting()) {
processesStillRunning = true;
break;
}
}
if (!processesStillRunning) {
shutdown();
}
}
if (agent != null) {
agent.broadcastState();
}
return id;
}
/**
* Max complexity spawn - with all possible options - this will create a
* ProcessData object and send it to spawn. ProcessData contains all the
* unique data related to starting an instance.
*
* Convert command line parameter options into a ProcessData which can be
* spawned
*
* @param options
* @return
* @throws IOException
* @throws URISyntaxException
* @throws InterruptedException
*/
public Process spawn(AgentCmdOptions options) throws IOException, URISyntaxException, InterruptedException {
if (ProcessData.agent == null) {
ProcessData.agent = this;
}
// create a ProcessData then spawn it !
ProcessData pd = new ProcessData();
pd.id = (options.id != null) ? options.id : NameGenerator.getName();
pd.branch = options.branch;
pd.version = options.version;
pd.jarPath = new File(getJarName(options.branch, options.version)).getAbsolutePath();
// javaExe
String fs = File.separator;
Platform platform = Platform.getLocalInstance();
String exeName = platform.isWindows() ? "javaw" : "java";
pd.javaExe = String.format("%s%sbin%s%s", System.getProperty("java.home"), fs, fs, exeName);
pd.jvm = new String[] { "-Djava.library.path=libraries/native", "-Djna.library.path=libraries/native", "-Dfile.encoding=UTF-8" };
if (options.jvm != null) {
pd.jvm = options.jvm;
}
pd.autoUpdate = options.autoUpdate;
return spawn(pd);
}
public String setBranch(String branch) {
currentBranch = branch;
return currentBranch;
}
static public Map<String, String> setEnv(Map<String, String> env) {
Platform platform = Platform.getLocalInstance();
String platformId = platform.getPlatformId();
if (platform.isLinux()) {
String ldPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${LD_LIBRARY_PATH}", platformId);
env.put("LD_LIBRARY_PATH", ldPath);
} else if (platform.isMac()) {
String dyPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${DYLD_LIBRARY_PATH}", platformId);
env.put("DYLD_LIBRARY_PATH", dyPath);
} else if (platform.isWindows()) {
// this just borks the path in Windows - additionally (unlike Linux)
// - i don't think you need native code on the PATH
// and Windows does not have a LD_LIBRARY_PATH
// String path =
// String.format("PATH=%%CD%%\\libraries\\native;PATH=%%CD%%\\libraries\\native\\%s;%%PATH%%",
// platformId);
// env.put("PATH", path);
// we need to sanitize against a non-ascii username
// work around for Jython bug in 2.7.0...
env.put("APPDATA", "%%CD%%");
} else {
log.error("unkown operating system");
}
return env;
}
/**
* Kills all connected processes, then shuts down itself. FIXME - should send
* shutdown to other processes instead of killing them
*/
public void shutdown() {
log.info("terminating others");
killAll();
log.info("terminating self ... goodbye...");
Runtime.shutdown();
}
/**
* Constructs a comman line from a ProcessData object which can directly be
* run to spawn a new instance of mrl
*
* @param pd
* @return
*/
public String[] buildCmdLine(ProcessData pd) {
// command line to be returned
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(pd.javaExe);
if (pd.jvm != null) {
for (int i = 0; i < pd.jvm.length; ++i) {
cmd.add(pd.jvm[i]);
}
}
cmd.add("-cp");
// step 1 - get current env data
String ps = File.pathSeparator;
// bogus jython.jar added as a hack to support - jython's 'more' fragile
// 2.7.0 interface :(
/**
* max complexity spawn
*
* @param pd
* @return
* @throws IOException
*/
public synchronized Process spawn(ProcessData pd) throws IOException {
log.info("============== spawn begin ==============");
// this needs cmdLine
String[] cmdLine = buildCmdLine(pd);
ProcessBuilder builder = new ProcessBuilder(cmdLine);
// handle stderr as a direct pass through to System.err
builder.redirectErrorStream(true);
// setting working directory to wherever the jar is...
String spawnDir = new File(pd.jarPath).getParent();
builder.directory(new File(spawnDir));
log.info("in {}", spawnDir);
log.info("spawning -> {}", Arrays.toString(cmdLine));
// environment variables setup
setEnv(builder.environment());
Process process = builder.start();
pd.process = process;
pd.startTs = System.currentTimeMillis();
pd.monitor = new ProcessData.Monitor(pd);
pd.monitor.start();
pd.state = ProcessData.stateType.running;
if (pd.id == null) {
log.error("id should not be null!");
}
if (processes.containsKey(pd.id)) {
if (agent != null) {
agent.info("restarting %s", pd.id);
}
} else {
if (agent != null) {
agent.info("starting new %s", pd.id);
}
processes.put(pd.id, pd);
}
log.info("Agent finished spawn {}", formatter.format(new Date()));
if (agent != null) {
Cli cli = Runtime.getCli();
cli.add(pd.id, process.getInputStream(), process.getOutputStream());
cli.attach(pd.id);
agent.broadcastState();
}
return process;
}
/**
* DEPRECATE ? spawn should do this checking ?
*
* @param id
* i
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public void start(String id) throws IOException, URISyntaxException, InterruptedException {
if (!processes.containsKey(id)) {
log.error("start process %s can not start - process does not exist", id);
return;
}
ProcessData p = processes.get(id);
if (p.isRunning()) {
log.warn("process %s already started", id);
return;
}
spawn(p);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Agent.class.getCanonicalName());
meta.addDescription("responsible for spawning a MRL process. Agent can also terminate, respawn and control the spawned process");
meta.addCategory("framework");
meta.setSponsor("GroG");
meta.setLicenseApache();
meta.includeServiceInOneJar(true);
return meta;
}
/**
* First method JVM executes when myrobotlab.jar is in jar form.
*
* -agent "-logLevel DEBUG -service webgui WebGui"
*
* @param args
* args
*/
// FIXME - test when internet is not available
// FIXME - test over multiple running processes
// FIXME - add -help
// TODO - add jvm memory other runtime info
// FIXME - a way to route parameters from command line to Agent vs Runtime -
// the current concept is ok - but it does not work ..
// make it work if necessary prefix everything by -agent-<...>
// FIXME - replace by PicoCli !!!
// FIXME - updateAgent(branch, version) -> updateAgent() 'latest
// FIXME - implement --help -h !!! - handle THROW !
@Command(name = "MyRobotLab"/*
* , mixinStandardHelpOptions = true - cant do it
*/)
static class AgentCmdOptions {
@Option(names = { "-jvm", "--jvm" }, arity = "0..*", description = "jvm parameters for the instance of mrl")
public String jvm[];
@Option(names = { "-id", "--id" }, description = "process identifier to be mdns or network overlay name for this instance - one is created at random if not assigned")
public String id;
// FIXME - how does this work ??? if specified is it "true" ?
@Option(names = { "-nb", "--no-banner" }, description = "prevents banner from showing")
public boolean noBanner = false;
@Option(names = { "-f", "--fork" }, description = "forks the agent, otherwise the agent will terminate self if all processes terminate")
public boolean fork = false;
@Option(names = { "-nc", "--no-cli" }, description = "no command line interface")
public boolean noCli = false;
@Option(names = { "-ll", "--log-level" }, description = "log level - helpful for troubleshooting " + " [debug info warn error]")
public String loglevel = "info";
@Option(names = { "-i",
"--install" }, arity = "0..*", description = "installs all dependencies for all services, --install {ServiceType} installs dependencies for a specific service")
public String install[];
@Option(names = { "-au", "--auto-update" }, description = "log level - helpful for troubleshooting " + " [debug info warn error]")
public boolean autoUpdate = false;
// FIXME - implement
@Option(names = { "-lv", "--list-versions" }, description = "list all possible versions for this branch")
public boolean listVersions = false;
// FIXME - does this get executed by another CommandLine ?
@Option(names = { "-a",
"--agent" }, description = "command line options for the agent must be in quotes e.g. --agent \"--service pyadmin Python --invoke pyadmin execFile myadminfile.py\"")
public String agent;
@Option(names = { "-b", "--branch" }, description = "requested branch")
public String branch;
// FIXME - get version vs force version - perhaps just always print version
// in help
@Option(names = { "-v", "--version" }, description = "requested version")
public String version;
@Option(names = { "-s",
"--services" }, description = "services requested on startup, the services must be {name} {Type} paired, e.g. gui SwingGui webgui WebGui servo Servo ...")
public String[] services;
@Option(names = { "-c",
"--client" }, arity = "0..1", description = "starts a command line interface and optionally connects to a remote instance - default with no host param connects to agent process --client [host]")
public String client[];
// FIXME - when instances connect via ws - default will become true
@Option(names = { "-w", "--webgui" }, description = "starts webgui for the agent - this starts a server on port 127.0.0.1:8887 that accepts websockets from spawned clients")
public boolean webgui = false;
/*
* @Parameters(arity = "1..*", paramLabel = "FILE", description =
* "File(s) to process.") private String[] services;
*/
}
public static void main(String[] args) {
try {
AgentCmdOptions options = new AgentCmdOptions();
// int exitCode = new CommandLine(options).execute(args);
new CommandLine(options).parseArgs(args);
String[] agentArgs = new String[] { "-id", "agent-" + NameGenerator.getName(), "-ll", "WARN", "--no-banner" };
if (options.agent != null) {
agentArgs = options.agent.split(" ");
}
Process p = null;
log.info("user args {}", Arrays.toString(args));
log.info("agent args {}", Arrays.toString(agentArgs));
Runtime.main(agentArgs);
if (agent == null) {
agent = (Agent) Runtime.start("agent", "Agent");
agent.options = options;
}
Platform platform = Platform.getLocalInstance();
if (options.branch == null) {
options.branch = platform.getBranch();
}
if (options.version == null) {
options.version = platform.getVersion();
}
agent.setBranch(options.branch);
agent.setVersion(options.version);
// FIXME - have a list versions ... command line !!!
// FIXME - the most common use case is the version of the spawned instance
// if that is the case its needed to determine what is the "proposed"
// branch & version if no
// special command parameters were given
// FIXME HELP !!!! :D
// if (cmdline.containsKey("-h") || cmdline.containsKey("--help")) {
// // FIXME - add all possible command descriptions ..
// System.out.println(String.format("%s branch %s version %s",
// platform.getBranch(), platform.getPlatformId(),
// platform.getVersion()));
// return;
if (options.webgui) {
agent.startWebGui();
// sub options set port default 8887
// webgui.setAddress("127.0.0.1"); - for security...
}
if (options.autoUpdate) {
// if the agent is going to auto update, its effectively "forked"
// because it will potentially need to restart all instances
// a restart terminates the instance - if the agent terminated an
// instance
// and did "not" fork it would terminate itself
options.fork = true;
// lets check and get the latest jar if there is new one
agent.getLatestJar(agent.getBranch());
// the "latest" should have been downloaded
options.version = agent.getLatestLocalVersion(agent.getBranch());
}
// FIXME - use wsclient for remote access
if (options.client != null) {
Runtime.start("cli", "Cli");
return;
}
// TODO - build command line ...
// FIXME - if another instances is spawned agent should wait for all
// instances to stop
p = agent.spawn(options); // <-- agent's is now in charge of first
// we start a timer to process future updates
if (options.autoUpdate) {
agent.autoUpdate(true);
}
if (options.install != null) {
// wait for mrl instance to finish installing
// then shutdown (addendum: check if supporting other processes)
p.waitFor();
agent.shutdown();
}
} catch (Exception e) {
log.error("unsuccessful spawn", e);
}
}
public String getBranch() {
return currentBranch;
}
public String getVersion() {
return currentVersion;
}
public String setVersion(String version) {
currentVersion = version;
return version;
}
// FIXME - move to enums for status level !
public void updateLog(String level, String msg) {
if (updateLog.size() > 100) {
updateLog.remove(updateLog.size() - 1);
}
if ("info".equals(level)) {
updateLog.add(Status.info((new Date()).toString() + " " + msg));
} else if ("error".equals(level)) {
updateLog.add(Status.error((new Date()).toString() + " " + msg));
}
}
}
|
package checkdep.value.depend;
import static java.util.Collections.*;
import checkdep.util.MyImmutableSet;
import com.google.common.collect.Iterables;
import lombok.Delegate;
import lombok.NonNull;
import lombok.Value;
@Value(staticConstructor = "of")
public class PackageNames implements Iterable<PackageName> {
public static final PackageNames EMPTY = copyOf(emptySet());
public static PackageNames copyOf(Iterable<PackageName> raw) {
return of(MyImmutableSet.copyOf(raw));
}
public static PackageNames of(PackageName raw) {
return of(MyImmutableSet.of(raw));
}
@Delegate
@NonNull
private final MyImmutableSet<PackageName> delegate;
public boolean contains(PackageName target) {
return stream().anyMatch(target::matches);
}
public PackageNames concat(PackageNames adding) {
return copyOf(Iterables.concat(this, adding));
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.myrobotlab.codec.CodecJson;
import org.myrobotlab.framework.MrlException;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.ProcessData;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.lang.NameGenerator;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.net.Http;
import org.slf4j.Logger;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
/**
* <pre>
*
* Agent is responsible for managing running instances of myrobotlab. It
* can start, stop and update myrobotlab.
*
*
* FIXME - ws client connectivity and communication !!!
* FIXME - Cli client ws enabled !!
* FIXME - capability to update Agent from child
* FIXME - move CmdLine defintion to Runtime
* FIXME - convert Runtime's cmdline processing to CmdOptions Fixme - remove CmdLine
* FIXME !!! - remove stdin/stdout !!!! use sockets only
*
* FIXME - there are at least 3 different levels of updating
* 1. a global thread which only "checks" for updates
* 2. the possibility of just downloading an update (per instance)
* 3. the possibility of auto-restarting after a download is completed (per instance)
*
* FIXME - auto update log .. sparse log of only updates and their results ...
* FIXME - test changing version prefix .. e.g. 1.2.
* FIXME - testing test - without version test - remote unaccessable
* FIXME - spawn must be synchronized 2 threads (the timer and the user)
* FIXME - test naming an instance FIXME - test starting an old version
* FIXME - make hidden check latest version interval and make default interval check large
* FIXME - change Runtime's cli !!!
* FIXME - check user define services for Agent
*
* </pre>
*/
public class Agent extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Agent.class);
final Map<String, ProcessData> processes = new ConcurrentHashMap<String, ProcessData>();
transient static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmssSSS");
Platform platform = Platform.getLocalInstance();
transient WebGui webgui = null;
int port = 8887;
String address = "127.0.0.1";
String currentBranch;
String currentVersion;
/**
* auto update - automatically checks for updates and WILL update any running
* mrl instance automatically
*/
boolean autoUpdate = false;
/**
* autoCheckForUpdate - checks automatically checks for updates after some
* interval but does not automatically update - it publishes events of new
* availability of updates but does not update
*/
boolean autoCheckForUpdate = false;
Set<String> possibleVersions = new TreeSet<String>();
// for more info -
// WARNING Jenkins url api format for multi-branch pipelines is different from
// maven builds !
final static String REMOTE_BUILDS_URL = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/job/%s/api/json?tree=builds[number,status,timestamp,id,result]";
final static String REMOTE_JAR_URL = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/job/%s/%s/artifact/target/myrobotlab.jar";
final static String REMOTE_MULTI_BRANCH_JOBS = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/api/json";
boolean checkRemoteVersions = false;
/**
* command line options for the agent
*/
CmdOptions options;
String versionPrefix = "1.1.";
static String banner = " _____ __________ ___. __ .____ ___. \n"
+ " / \\ ___.__.\\______ \\ ____\\_ |__ _____/ |_| | _____ \\_ |__ \n"
+ " / \\ / < | | | _
+ "/ Y \\___ | | | ( <_> ) \\_\\ ( <_> ) | | |___ / __ \\| \\_\\ \\\n" + "\\____|__ / ____| |____|_ /\\____/|___ /\\____/|__| |_______ (____ /___ /\n"
+ " \\/\\/ \\/ \\/ \\/ \\/ \\/ \n resistance is futile, we have cookies and robots ...";
/**
* singleton for security purposes
*/
transient static Agent agent;
String rootBranchDir = "branches";
/**
* development variable to force version "unknown" to be either greatest or
* smallest version for development
*/
private boolean unknownIsGreatest = false;
public static class WorkflowMultiBranchProject {
String name;
WorkflowJob[] jobs;
}
/**
* Jenkins data structure to describe jobs
*/
public static class WorkflowJob {
String name;
String url;
String color;
WorkflowRun lastSuccessfulBuild;
WorkflowRun[] builds;
}
/**
* Jenkins data structure to describe builds
*/
public static class WorkflowRun {
String id;
Integer number;
String result;
Long timestamp;
}
// FIXME - change this to hour for production ...
// long updateCheckIntervalMs = 60 * 60 * 1000; // every hour
long updateCheckIntervalMs = 60 * 1000; // every minute
List<Status> updateLog = new ArrayList<>();
/**
* Update thread - we cannot use addTask as a long update could pile up a
* large set of updates to process quickly in series. Instead, we have a
* simple single class which is always single threaded to process updates.
*
*/
class Updater implements Runnable {
transient Agent agent = null;
transient Thread thread = null;
ProcessData.stateType state = ProcessData.stateType.stopped;
public Updater(Agent agent) {
this.agent = agent;
}
@Override
public void run() {
state = ProcessData.stateType.running;
updateLog("info", "updater running");
try {
while (true) {
state = ProcessData.stateType.sleeping;
updateLog("info", "updater sleeping");
sleep(updateCheckIntervalMs);
state = ProcessData.stateType.updating;
updateLog("info", "updater updating");
agent.update();
}
} catch (Exception e) {
log.info("updater threw", e);
}
log.info("updater stopping");
updateLog("info", "updater stopping");
state = ProcessData.stateType.stopped;
}
synchronized public void start() {
if (state == ProcessData.stateType.stopped) {
thread = new Thread(this, getName() + ".updater");
thread.start();
updateLog("info", "updater starting");
} else {
log.warn("updater busy state = %s", state);
}
}
synchronized public void stop() {
if (state != ProcessData.stateType.stopped) {
// we'll wait if its in the middle of an update
while (state == ProcessData.stateType.updating) {
log.warn("updater currently updating, waiting for 5 seconds...");
sleep(5000);
}
// most likely the thread is a sleeping state
// so, we wake it up quickly to die ;)
thread.interrupt();
}
}
}
public static String BRANCHES_ROOT = "branches";
Updater updater;
public Agent(String n) throws IOException {
super(n);
updater = new Updater(this);
currentBranch = Platform.getLocalInstance().getBranch();
currentVersion = Platform.getLocalInstance().getVersion();
log.info("Agent {} Pid {} is alive", n, Platform.getLocalInstance().getPid());
// basic setup - minimally we make a directory
// and instance folder of the same branch & version as the
// agent jar
setup();
// user has decided to look for updates ..
if (autoUpdate || checkRemoteVersions) {
invoke("getVersions", currentBranch);
}
}
public String getDir(String branch, String version) {
if (branch == null) {
branch = Platform.getLocalInstance().getBranch();
}
if (version == null) {
try {
version = getLatestVersion(branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
return BRANCHES_ROOT + File.separator + branch + "-" + version;
}
public String getJarName(String branch, String version) {
return getDir(branch, version) + File.separator + "myrobotlab.jar";
}
private void setup() throws IOException {
String agentBranch = Platform.getLocalInstance().getBranch();
String agentVersion = Platform.getLocalInstance().getVersion();
// location of the agent's branch (and version)
String agentVersionPath = getDir(agentBranch, agentVersion);
if (!new File(agentVersionPath).exists()) {
File branchDir = new File(agentVersionPath);
branchDir.mkdirs();
}
String agentMyRobotLabJar = getJarName(agentBranch, agentVersion);
if (!new File(agentMyRobotLabJar).exists()) {
String agentJar = new java.io.File(Agent.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
if (!new File(agentJar).exists() || !agentJar.endsWith(".jar")) {
// not operating in released runtime mode - probably operating in ide
String ideTargetJar = new File(System.getProperty("user.dir") + File.separator + "target" + File.separator + "myrobotlab.jar").getAbsolutePath();
if (!new File(ideTargetJar).exists()) {
error("no source agent jar can be found checked:\n%s\n%s\nare you using ide? please package a build (mvn package -DskipTest)", agentJar, ideTargetJar);
} else {
agentJar = ideTargetJar;
}
}
log.info("on branch {} copying agent's current jar to appropriate location {} -> {}", currentBranch, agentJar, agentMyRobotLabJar);
Files.copy(Paths.get(agentJar), Paths.get(agentMyRobotLabJar), StandardCopyOption.REPLACE_EXISTING);
}
}
public void startWebGui() {
try {
if (webgui == null) {
webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.setPort(port);
webgui.setAddress(address);
webgui.startService();
} else {
log.info("webgui already started");
}
} catch (Exception e) {
log.error("startWebGui threw", e);
}
}
public void autoUpdate(boolean b) {
if (b) {
// addTask("update", 1000 * 60, 0, "update");
updater.start();
} else {
// purgeTask("update");
updater.stop();
}
}
/**
* FIXME !!! - i believe in task for these pipe up !!! NOT GOOD _ must have
* its own thread then !!
*
* called by the autoUpdate task which is scheduled every minute to look for
* updates from the build server
*/
public void update() {
log.info("update");
for (String key : processes.keySet()) {
ProcessData process = processes.get(key);
if (!process.autoUpdate) {
log.info("not autoUpdate");
continue;
}
try {
// getRemoteVersions
log.info("getting version");
String version = getLatestVersion(process.branch, true);
if (version == null || version.equals(process.version)) {
log.info("same version {}", version);
continue;
}
// we have a possible update
log.info("WOOHOO ! updating to version {}", version);
process.version = version;
process.jarPath = new File(getJarName(process.branch, process.version)).getAbsolutePath();
getLatestJar(process.branch);
log.info("WOOHOO ! updated !");
if (process.isRunning()) {
log.info("its running - we should restart");
restart(process.id);
log.info("restarted");
}
} catch (Exception e) {
log.error("proccessing updates from scheduled task threw", e);
}
}
}
/**
* gets the latest jar if allowed to check remote ....
*
* @param branch
*/
public void getLatestJar(String branch) {
try {
// check for latest
String version = getLatestVersion(branch, true);
// check if branch and version exist locally
if (!existsLocally(branch, version)) {
log.info("found update - getting new jar {} {}", branch, version);
getJar(branch, version);
// download latest to the appropriate directory
// mkdirs
// download file
if (!verifyJar(branch, version)) {
}
log.info("successfully downloaded {} {}", branch, version);
}
} catch (Exception e) {
error(e);
}
}
// FIXME - implement :)
private boolean verifyJar(String branch, String version) {
return true;
}
synchronized public void getJar(String branch, String version) {
new File(getDir(branch, version)).mkdirs();
String build = getBuildId(version);
// this
Http.getSafePartFile(String.format(REMOTE_JAR_URL, branch, build), getJarName(branch, version));
}
public String getBuildId(String version) {
String[] parts = version.split("\\.");
return parts[2];
}
public String getLatestVersion(String branch, Boolean allowRemote) throws MrlException {
Set<String> versions = getVersions(branch, allowRemote);
return getLatestVersion(versions);
}
public String getLatestVersion(Set<String> versions) throws MrlException {
String latest = null;
for (String version : versions) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* checks to see if a branch / version jar exists on the local filesystem
*
* @param branch
* @param version
* @return
*/
public boolean existsLocally(String branch, String version) {
return new File(getJarName(branch, version)).exists();
}
/**
* if there is a single instance - just restart it ...
*
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public synchronized void restart(String id) throws IOException, URISyntaxException, InterruptedException {
log.info("restarting process {}", id);
kill(id); // FIXME - kill should include prepare to shutdown ...
sleep(2000);
spawn(id);
}
private void spawn(String id) {
try {
if (processes.containsKey(id)) {
spawn(processes.get(id));
} else {
log.error("agent does not know about process id {}", id);
}
} catch (Exception e) {
log.error("spawn({}) threw ", id, e);
}
}
/**
* return a non-running process structure from an existing one with a new id
*
* @param id
* id
* @return process data
*
*/
public ProcessData copy(String id) {
if (!processes.containsKey(id)) {
log.error("cannot copy %s does not exist", id);
return null;
}
ProcessData pd = processes.get(id);
ProcessData pd2 = new ProcessData(pd);
pd2.startTs = null;
pd2.stopTs = null;
String[] parts = id.split("\\.");
if (parts.length == 4) {
try {
int instance = Integer.parseInt(parts[3]);
++instance;
} catch (Exception e) {
}
} else {
pd2.id = id + ".0";
}
processes.put(pd2.id, pd2);
if (agent != null) {
agent.broadcastState();
}
return pd2;
}
public void copyAndStart(String id) throws IOException {
// returns a non running copy with new process id
// on the processes list
ProcessData pd2 = copy(id);
spawn(pd2);
if (agent != null) {
agent.broadcastState();
}
}
/**
* gets id from name
*
* @param name
* name
* @return integer
*
*/
public String getId(String name) {
for (String pid : processes.keySet()) {
if (pid.equals(name)) {
return processes.get(pid).id;
}
}
return null;
}
/**
* get the current branches being built in a Jenkins multi-branch pipeline job
*
* @return
*/
static public Set<String> getBranches() {
Set<String> possibleBranches = new TreeSet<String>();
try {
byte[] r = Http.get(REMOTE_MULTI_BRANCH_JOBS);
if (r != null) {
String json = new String(r);
CodecJson decoder = new CodecJson();
WorkflowMultiBranchProject project = (WorkflowMultiBranchProject) decoder.decode(json, WorkflowMultiBranchProject.class);
for (WorkflowJob job : project.jobs) {
possibleBranches.add(job.name);
}
}
} catch (Exception e) {
log.error("getRemoteBranches threw", e);
}
return possibleBranches;
}
boolean isGreaterThan(String version1, String version2) throws MrlException {
if (version1 == null) {
return false;
}
if (version2 == null) {
return true;
}
// special development behavior
if (version1.equals("unknown")) {
return (unknownIsGreatest) ? true : false;
}
if (version2.equals("unknown")) {
return !((unknownIsGreatest) ? true : false);
}
String[] parts1 = version1.split("\\.");
String[] parts2 = version2.split("\\.");
if (parts1.length != 3 || parts2.length != 3) {
throw new MrlException("invalid version isGreaterThan(%s, %s)", version1, version2);
}
for (int i = 0; i < 3; ++i) {
int v1 = Integer.parseInt(parts1[i]);
int v2 = Integer.parseInt(parts2[i]);
if (v1 != v2) {
return v1 > v2;
}
}
throw new MrlException("invalid isGreaterThan(%s, %s)", version1, version2);
}
/**
* This method gets all the version on a particular branch, if allowed remote
* access it will ask the build server what successful builds exist
*
* @param branch
* @param allowRemote
* @return
*/
synchronized public Set<String> getVersions(String branch, Boolean allowRemote) {
Set<String> versions = new TreeSet<String>();
versions.addAll(getLocalVersions(branch));
if (allowRemote) {
versions.addAll(getRemoteVersions(branch));
}
if (versions.size() != possibleVersions.size()) {
possibleVersions = versions;
broadcastState();
}
return versions;
}
public Set<String> getRemoteVersions(String branch) {
Set<String> versions = new TreeSet<String>();
try {
byte[] data = Http.get(String.format(REMOTE_BUILDS_URL, branch));
if (data != null) {
CodecJson decoder = new CodecJson();
String json = new String(data);
WorkflowJob job = (WorkflowJob) decoder.decode(json, WorkflowJob.class);
if (job.builds != null) {
for (WorkflowRun build : job.builds) {
if ("SUCCESS".equals(build.result)) {
versions.add(versionPrefix + build.id);
}
}
}
}
} catch (Exception e) {
error(e);
}
return versions;
}
public String getLatestLocalVersion(String branch) throws MrlException {
Set<String> allLocal = getLocalVersions(branch);
String latest = null;
for (String version : allLocal) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
public Set<String> getLocalVersions() {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
// if (file.getName().startsWith(branch)) {
// String version = file.getName().substring(branch.length() + 1);// getFileVersion(file.getName());
// if (version != null) {
int pos = file.getName().lastIndexOf("-");
String branchAndVersion = file.getName().substring(0, pos - 1) + " " + file.getName().substring(pos + 1);
versions.add(branchAndVersion);
}
}
return versions;
}
public Set<String> getLocalVersions(String branch) {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
if (file.getName().startsWith(branch)) {
String version = file.getName().substring(branch.length() + 1);// getFileVersion(file.getName());
if (version != null) {
versions.add(version);
}
}
}
}
return versions;
}
static public String getFileVersion(String name) {
if (!name.startsWith("myrobotlab.")) {
return null;
}
String[] parts = name.split("\\.");
if (parts.length != 5) {
return null;
}
String version = String.format("%s.%s.%s", parts[1], parts[2], parts[3]);
return version;
}
/**
* get a list of all the processes currently governed by this Agent
*
* @return hash map, int to process data
*/
public Map<String, ProcessData> getProcesses() {
return processes;
}
// by id (or by pid?)
public String kill(String id) {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
if (processes.containsKey(id)) {
if (agent != null) {
agent.info("terminating %s", id);
}
ProcessData process = processes.get(id);
process.process.destroy();
process.state = ProcessData.stateType.stopped;
if (process.monitor != null) {
process.monitor.interrupt();
process.monitor = null;
}
// remove(processes.get(name));
if (agent != null) {
agent.info("{} haz beeen terminated", id);
agent.broadcastState();
}
return id;
}
error("kill unknown process id {}", id);
return null;
}
/*
* BAD IDEA - data type ambiguity is a drag public Integer kill(String name) {
* return kill(getId(name)); }
*/
public void killAll() {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
for (String id : processes.keySet()) {
kill(id);
}
log.info("no survivors sir...");
if (agent != null) {
agent.broadcastState();
}
}
public void killAndRemove(String id) {
if (processes.containsKey(id)) {
kill(id);
processes.remove(id);
if (agent != null) {
agent.broadcastState();
}
}
}
/**
* list processes
*
* @return lp ?
*/
public String[] lp() {
Object[] objs = processes.keySet().toArray();
String[] pd = new String[objs.length];
for (int i = 0; i < objs.length; ++i) {
Integer id = (Integer) objs[i];
ProcessData p = processes.get(id);
pd[i] = String.format("%s - %s [%s - %s]", id, p.id, p.branch, p.version);
}
return pd;
}
public String publishTerminated(String id) {
log.info("publishTerminated - terminated {} - restarting", id);
if (!processes.containsKey(id)) {
log.error("processes {} not found");
return id;
}
// if you don't fork with Agent allowed to
// exist without instances - then
if (!options.fork) {
// spin through instances - if I'm the only
// thing left - terminate
boolean processesStillRunning = false;
for (ProcessData pd : processes.values()) {
if (pd.isRunning() || pd.isRestarting()) {
processesStillRunning = true;
break;
}
}
if (!processesStillRunning) {
shutdown();
}
}
if (agent != null) {
agent.broadcastState();
}
return id;
}
/**
* Max complexity spawn - with all possible options - this will create a
* ProcessData object and send it to spawn. ProcessData contains all the
* unique data related to starting an instance.
*
* Convert command line parameter options into a ProcessData which can be
* spawned
*
* @param options
* @return
* @throws IOException
* @throws URISyntaxException
* @throws InterruptedException
*/
public Process spawn(CmdOptions options) throws IOException, URISyntaxException, InterruptedException {
if (ProcessData.agent == null) {
ProcessData.agent = this;
}
// create a ProcessData then spawn it !
ProcessData pd = new ProcessData();
pd.id = (options.id != null) ? options.id : NameGenerator.getName();
pd.branch = options.branch;
pd.version = options.version;
pd.jarPath = new File(getJarName(options.branch, options.version)).getAbsolutePath();
// javaExe
String fs = File.separator;
Platform platform = Platform.getLocalInstance();
String exeName = platform.isWindows() ? "javaw" : "java";
pd.javaExe = String.format("%s%sbin%s%s", System.getProperty("java.home"), fs, fs, exeName);
pd.jvm = new String[] { "-Djava.library.path=libraries/native", "-Djna.library.path=libraries/native", "-Dfile.encoding=UTF-8" };
if (options.jvm != null) {
pd.jvm = options.jvm.split(" ");
}
pd.autoUpdate = options.autoUpdate;
return spawn(pd);
}
public String setBranch(String branch) {
currentBranch = branch;
return currentBranch;
}
static public Map<String, String> setEnv(Map<String, String> env) {
Platform platform = Platform.getLocalInstance();
String platformId = platform.getPlatformId();
if (platform.isLinux()) {
String ldPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${LD_LIBRARY_PATH}", platformId);
env.put("LD_LIBRARY_PATH", ldPath);
} else if (platform.isMac()) {
String dyPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${DYLD_LIBRARY_PATH}", platformId);
env.put("DYLD_LIBRARY_PATH", dyPath);
} else if (platform.isWindows()) {
// this just borks the path in Windows - additionally (unlike Linux)
// - i don't think you need native code on the PATH
// and Windows does not have a LD_LIBRARY_PATH
// String path =
// String.format("PATH=%%CD%%\\libraries\\native;PATH=%%CD%%\\libraries\\native\\%s;%%PATH%%",
// platformId);
// env.put("PATH", path);
// we need to sanitize against a non-ascii username
// work around for Jython bug in 2.7.0...
env.put("APPDATA", "%%CD%%");
} else {
log.error("unkown operating system");
}
return env;
}
/**
* Kills all connected processes, then shuts down itself. FIXME - should send
* shutdown to other processes instead of killing them
*/
public void shutdown() {
log.info("terminating others");
killAll();
log.info("terminating self ... goodbye...");
Runtime.shutdown();
}
/**
* Constructs a comman line from a ProcessData object which can directly be
* run to spawn a new instance of mrl
*
* @param pd
* @return
*/
public String[] buildCmdLine(ProcessData pd) {
// command line to be returned
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(pd.javaExe);
if (pd.jvm != null) {
for (int i = 0; i < pd.jvm.length; ++i) {
cmd.add(pd.jvm[i]);
}
}
cmd.add("-cp");
// step 1 - get current env data
String ps = File.pathSeparator;
// bogus jython.jar added as a hack to support - jython's 'more' fragile
// 2.7.0 interface :(
/**
* max complexity spawn
*
* @param pd
* @return
* @throws IOException
*/
public synchronized Process spawn(ProcessData pd) throws IOException {
log.info("============== spawn begin ==============");
// this needs cmdLine
String[] cmdLine = buildCmdLine(pd);
ProcessBuilder builder = new ProcessBuilder(cmdLine);
// handle stderr as a direct pass through to System.err
builder.redirectErrorStream(true);
// setting working directory to wherever the jar is...
String spawnDir = new File(pd.jarPath).getParent();
builder.directory(new File(spawnDir));
log.info("in {}", spawnDir);
log.info("SPAWNING ! -> {}", Arrays.toString(cmdLine));
// environment variables setup
setEnv(builder.environment());
Process process = builder.start();
pd.process = process;
pd.startTs = System.currentTimeMillis();
pd.monitor = new ProcessData.Monitor(pd);
pd.monitor.start();
pd.state = ProcessData.stateType.running;
if (pd.id == null) {
log.error("id should not be null!");
}
if (processes.containsKey(pd.id)) {
if (agent != null) {
agent.info("restarting %s", pd.id);
}
} else {
if (agent != null) {
agent.info("starting new %s", pd.id);
}
processes.put(pd.id, pd);
}
log.info("Agent finished spawn {}", formatter.format(new Date()));
if (agent != null) {
Cli cli = Runtime.getCli();
cli.add(pd.id, process.getInputStream(), process.getOutputStream());
cli.attach(pd.id);
agent.broadcastState();
}
return process;
}
/**
* DEPRECATE ? spawn should do this checking ?
*
* @param id
* i
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public void start(String id) throws IOException, URISyntaxException, InterruptedException {
if (!processes.containsKey(id)) {
log.error("start process %s can not start - process does not exist", id);
return;
}
ProcessData p = processes.get(id);
if (p.isRunning()) {
log.warn("process %s already started", id);
return;
}
spawn(p);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Agent.class.getCanonicalName());
meta.addDescription("responsible for spawning a MRL process. Agent can also terminate, respawn and control the spawned process");
meta.addCategory("framework");
meta.setSponsor("GroG");
meta.setLicenseApache();
meta.includeServiceInOneJar(true);
return meta;
}
/**
* First method JVM executes when myrobotlab.jar is in jar form.
*
* -agent "-logLevel DEBUG -service webgui WebGui"
*
* @param args
* args
*/
// FIXME - test when internet is not available
// FIXME - test over multiple running processes
// FIXME - add -help
// TODO - add jvm memory other runtime info
// FIXME - a way to route parameters from command line to Agent vs Runtime -
// the current concept is ok - but it does not work ..
// make it work if necessary prefix everything by -agent-<...>
// FIXME - replace by PicoCli !!!
// FIXME - updateAgent(branch, version) -> updateAgent() 'latest
// FIXME - implement --help -h !!! - handle THROW !
@Command(name = "MyRobotLab"/*
* , mixinStandardHelpOptions = true - cant do it
*/)
static class CmdOptions {
@Option(names = { "-jvm", "--jvm" }, arity = "0..*", description = "jvm parameters for the instance of mrl")
public String jvm;
@Option(names = { "-id", "--id" }, description = "process identifier to be mdns or network overlay name for this instance - one is created at random if not assigned")
public String id;
// FIXME - how does this work ??? if specified is it "true" ?
@Option(names = { "-nb", "--no-banner" }, description = "prevents banner from showing")
public boolean noBanner = false;
@Option(names = { "-f", "--fork" }, description = "forks the agent, otherwise the agent will terminate self if all processes terminate")
public boolean fork = false;
/**<pre>
@Option(names = { "-nc", "--no-cli" }, description = "no command line interface")
public boolean noCli = false;
</pre>
*/
@Option(names = { "-ll", "--log-level" }, description = "log level - helpful for troubleshooting " + " [debug info warn error]")
public String logLevel = "info";
@Option(names = { "-i",
"--install" }, arity = "0..*", description = "installs all dependencies for all services, --install {ServiceType} installs dependencies for a specific service")
public String install[];
@Option(names = { "-au", "--auto-update" }, description = "auto updating - this feature allows mrl instances to be automatically updated when a new version is available")
public boolean autoUpdate = false;
// FIXME - implement
@Option(names = { "-lv", "--list-versions" }, description = "list all possible versions for this branch")
public boolean listVersions = false;
// FIXME - implement
@Option(names = { "-ua", "--update-agent" }, description = "updates agent with the latest versions of the current branch")
public boolean updateAgent = false;
// FIXME - does this get executed by another CommandLine ?
@Option(names = { "-a",
"--agent" }, description = "command line options for the agent must be in quotes e.g. --agent \"--service pyadmin Python --invoke pyadmin execFile myadminfile.py\"")
public String agent;
@Option(names = { "-b", "--branch" }, description = "requested branch")
public String branch;
// FIXME - get version vs force version - perhaps just always print version
// in help
@Option(names = { "-v", "--version" }, description = "requested version")
public String version;
@Option(names = { "-s",
"--services" }, description = "services requested on startup, the services must be {name} {Type} paired, e.g. gui SwingGui webgui WebGui servo Servo ...")
public String[] services;
@Option(names = { "-c",
"--client" }, arity = "0..1", description = "starts a command line interface and optionally connects to a remote instance - default with no host param connects to agent process --client [host]")
public String client[];
// FIXME - when instances connect via ws - default will become true
@Option(names = { "-w", "--webgui" }, description = "starts webgui for the agent - this starts a server on port 127.0.0.1:8887 that accepts websockets from spawned clients")
public boolean webgui = false;
/*
* @Parameters(arity = "1..*", paramLabel = "FILE", description =
* "File(s) to process.") private String[] services;
*/
}
public static void main(String[] args) {
try {
CmdOptions options = new CmdOptions();
// int exitCode = new CommandLine(options).execute(args);
new CommandLine(options).parseArgs(args);
String[] agentArgs = new String[] { "-id", "agent-" + NameGenerator.getName(), "-ll", "WARN"};
if (options.agent != null) {
agentArgs = options.agent.split(" ");
}
Process p = null;
if (!options.noBanner) {
System.out.println(banner);
}
log.info("user args {}", Arrays.toString(args));
log.info("agent args {}", Arrays.toString(agentArgs));
Runtime.main(agentArgs);
if (agent == null) {
agent = (Agent) Runtime.start("agent", "Agent");
agent.options = options;
}
if (options.listVersions) {
System.out.println("available local versions");
for (String bv : agent.getLocalVersions()) {
System.out.println(bv);
}
agent.shutdown();
}
Platform platform = Platform.getLocalInstance();
if (options.branch == null) {
options.branch = platform.getBranch();
}
if (options.version == null) {
options.version = platform.getVersion();
}
agent.setBranch(options.branch);
agent.setVersion(options.version);
// FIXME - have a list versions ... command line !!!
// FIXME - the most common use case is the version of the spawned instance
// if that is the case its needed to determine what is the "proposed"
// branch & version if no
// special command parameters were given
// FIXME HELP !!!! :D
// if (cmdline.containsKey("-h") || cmdline.containsKey("--help")) {
// // FIXME - add all possible command descriptions ..
// System.out.println(String.format("%s branch %s version %s",
// platform.getBranch(), platform.getPlatformId(),
// platform.getVersion()));
// return;
if (options.webgui) {
agent.startWebGui();
// sub options set port default 8887
// webgui.setAddress("127.0.0.1"); - for security...
}
if (options.autoUpdate) {
// if the agent is going to auto update, its effectively "forked"
// because it will potentially need to restart all instances
// a restart terminates the instance - if the agent terminated an
// instance
// and did "not" fork it would terminate itself
options.fork = true;
// lets check and get the latest jar if there is new one
agent.getLatestJar(agent.getBranch());
// the "latest" should have been downloaded
options.version = agent.getLatestLocalVersion(agent.getBranch());
}
// FIXME - use wsclient for remote access
if (options.client != null) {
Runtime.start("cli", "Cli");
return;
}
// TODO - build command line ...
// FIXME - if another instances is spawned agent should wait for all
// instances to stop
p = agent.spawn(options); // <-- agent's is now in charge of first
// we start a timer to process future updates
if (options.autoUpdate) {
agent.autoUpdate(true);
}
if (options.install != null) {
// wait for mrl instance to finish installing
// then shutdown (addendum: check if supporting other processes)
p.waitFor();
agent.shutdown();
}
} catch (Exception e) {
log.error("unsuccessful spawn", e);
}
}
public String getBranch() {
return currentBranch;
}
public String getVersion() {
return currentVersion;
}
public String setVersion(String version) {
currentVersion = version;
return version;
}
// FIXME - move to enums for status level !
public void updateLog(String level, String msg) {
if (updateLog.size() > 100) {
updateLog.remove(updateLog.size() - 1);
}
if ("info".equals(level)) {
updateLog.add(Status.info((new Date()).toString() + " " + msg));
} else if ("error".equals(level)) {
updateLog.add(Status.error((new Date()).toString() + " " + msg));
}
}
}
|
package com.adaptc.mws.plugins;
public enum JobReportFlag {
NONE,
/**
* This job is the master of a job array.
* @see #ARRAYJOB
*/
ARRAYMASTER,
/**
* This job preempted other jobs to start.
*/
HASPREEMPTED,
/**
* The {@link #IGNPOLICIES} flag was set by an administrator.
*/
ADMINSETIGNPOLICIES,
/**
* The job duration (walltime) was extended at job start.
*/
EXTENDSTARTWALLTIME,
/**
* The job will share its memory across nodes.
*/
SHAREDMEM,
/**
* The job's generic resource requirement caused the job to start later.
*/
BLOCKEDBYGRES,
/**
* The job is requesting only generic resources, no compute resources.
*/
GRESONLY,
/**
* The job has had all applicable templates applied to it.
*/
TEMPLATESAPPLIED,
/**
* META job, just a container around resources.
*/
META,
/**
* This job prefers the wide search algorithm.
*/
WIDERSVSEARCHALGO,
/**
* The job is a VMTracking job for an externally-created VM (via job template).
*/
VMTRACKING,
/**
* A destroy job has already been created from the template for this job.
*/
DESTROYTEMPLATESUBMITTED,
/**
* This array job will only run in one partition.
*/
ARRAYJOBPARLOCK,
/**
* This array job will span partitions (default).
*/
ARRAYJOBPARSPAN,
/**
* The job is using backfill to run.
*/
BACKFILL,
/**
* The job can use resources from multiple resource managers and partitions.
*/
COALLOC,
/**
* The job requires use of a reservation.
*/
ADVRES,
/**
* The job will attempt to execute immediately or fail.
*/
NOQUEUE,
/**
* The job will share reserved resources.
*/
ARRAYJOB,
/**
* The job will succeed if even partial resources are available.
*/
BESTEFFORT,
/**
* The job is restartable.
*/
RESTARTABLE,
/**
* The job is suspendable.
*/
SUSPENDABLE,
/**
* The job is a preemptee and therefore can be preempted by other jobs.
*/
PREEMPTEE,
/**
* The job is a preemptor and therefore can preempt other jobs.
*/
PREEMPTOR,
/**
* The job is based on some reservation.
*/
RSVMAP,
/**
* The job was started with a soft policy violation.
*/
SPVIOLATION,
/**
* The job will ignore node policies.
*/
IGNNODEPOLICIES,
/**
* The job will ignore idle, active, class, partition, and system policies.
*/
IGNPOLICIES,
/**
* The job will ignore node state in order to run.
*/
IGNNODESTATE,
/**
* The job can ignore idle job reservations. The job granted access to all
* idle job reservations.
*/
IGNIDLEJOBRSV,
/**
* The job needs to interactive input from the user to run.
*/
INTERACTIVE,
/**
* The job was started with a fairshare violation.
*/
FSVIOLATION,
/**
* The job is directly submitted without doing any authentication.
*/
GLOBALQUEUE,
/**
* The job is a system job that does not need any resources.
*/
NORESOURCES,
/**
* The job will not query a resource manager to run.
*/
NORMSTART,
/**
* The job is locked into the current cluster and cannot be migrated
* elsewhere. This is for grid mode.
*/
CLUSTERLOCKED,
/**
* The job can be run across multiple nodes in individual chunks.
*/
FRAGMENT,
/**
* The job is a system job which simply runs on the same node that Moab is
* running on. This is usually used for running scripts and other
* executables in workflows.
*/
SYSTEMJOB,
/**
* Job requested processors
*/
PROCSPECIFIED,
/**
* Cancel job array on first array job failure
*/
CANCELONFIRSTFAILURE,
/**
* Cancel job array on first array job success
*/
CANCELONFIRSTSUCCESS,
/**
* Cancel job array on any array job failure
*/
CANCELONANYFAILURE,
/**
* Cancel job array on any array job success
*/
CANCELONANYSUCCESS,
/**
* Cancel job array on a specific exit code
*/
CANCELONEXITCODE,
/**
* VM job cannot be migrated.
*/
NOVMMIGRATE,
/**
* Only purge the job if it completed successfully
*/
PURGEONSUCCESSONLY,
/**
* Each job compute task requests all the procs on its node
*/
ALLPROCS;
/**
* Attempts to parse a string and convert it into a corresponding
* JobReportFlag enum value.
*
* @param string The string to parse into a corresponding JobReportFlag enum value.
* @return The corresponding JobReportFlag value or {@link #NONE} if not found.
*/
static JobReportFlag parse(String string) {
// A job flag can look like "ADVRES:alice.1"
if (string.startsWith("ADVRES:"))
return ADVRES;
for(JobReportFlag flag : values())
if (flag.toString().equalsIgnoreCase(string))
return flag;
return NONE;
}
}
|
package com.atexpose.dispatcher;
import com.atexpose.api.API;
import com.atexpose.api.MethodObject;
import com.atexpose.dispatcher.channels.IChannel;
import com.atexpose.dispatcher.logging.LogEntry;
import com.atexpose.dispatcher.logging.Logger;
import com.atexpose.dispatcher.parser.IParser;
import com.atexpose.dispatcher.parser.Request;
import com.atexpose.dispatcher.wrapper.IWrapper;
import com.atexpose.errors.IExceptionProperties;
import com.atexpose.util.ByteStorage;
import io.schinzel.basicutils.Thrower;
import io.schinzel.basicutils.UTF8;
import io.schinzel.basicutils.collections.namedvalues.INamedValue;
import io.schinzel.basicutils.state.IStateNode;
import io.schinzel.basicutils.state.State;
import lombok.Builder;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The dispatcher is the central cog wheel.
* <p>
* From the assigned channel the dispatcher pulls an incoming messages.
* The parser extracts method name and argument values from the incoming message.
* The incoming request is executed.
* The response is wrapped with the assigned wrapper.
* The wrapped response is sent with the assigned channel.
* <p>
* The log data is sent to the assigned loggers (zero, one or many).
*
* @author Schinzel
*/
@Accessors(prefix = "m")
public class Dispatcher implements Runnable, INamedValue, IStateNode {
/** The name as part of the INamedValue interface. Is the name of the Dispatchers. */
@Getter final String mName;
/** The API that is exposed. */
private final API mAPI;
/** Receives incoming messages and sends wrapped responses. */
private final IChannel mChannel;
/** Parses the incoming messages. */
private final IParser mParser;
/** Wraps the responses to send. */
private final IWrapper mWrapper;
/**
* The access level of this dispatcher. The dispatcher can invoke methods with the same access
* level or lower.
**/
private final int mAccessLevel;
/** Says which thread this object is. Useful for debugging and diagnostics. */
private final int mThreadNumber;
/** The thread that this dispatcher executes in. */
private Thread mThread;
/** The loggers assigned to this dispatcher. */
private List<Logger> mLoggers = new ArrayList<>();
/**
* Contains a reference to the next dispatcher if this dispatcher is
* multi-threaded. Multi-threaded dispatchers are stored as a linked-list.
* This variable is a reference to the next dispatcher in the list. If it is
* null, it is the last in the list or the it is single-threaded.
*/
private Dispatcher mNextDispatcher;
// - CONSTRUCTOR
/**
* Sets up a dispatcher.
*/
@Builder
private Dispatcher(String name, int noOfThreads, int accessLevel, IChannel channel, IParser parser, IWrapper wrapper, API api) {
mName = name;
Thrower.throwIfVarTooSmall(noOfThreads, "noOfThreads", 1);
Thrower.throwIfVarEmpty(name, "name");
Thrower.throwIfVarOutsideRange(accessLevel, "accessLevel", 1, 3);
mThreadNumber = noOfThreads;
mAccessLevel = accessLevel;
mChannel = channel;
mParser = parser;
mWrapper = wrapper;
mAPI = api;
//If more than one dispatcher to set up
if (mThreadNumber > 1) {
//Set up the next dispatcher
mNextDispatcher = Dispatcher.builder()
.name(this.getName())
.accessLevel(mAccessLevel)
.channel(mChannel.getClone())
.parser(mParser.getClone())
.wrapper(mWrapper)
.noOfThreads(mThreadNumber - 1)
.api(mAPI)
.build();
}
}
// - START & STOP
/**
* Starts the messaging and tells the next dispatcher to start its messaging recursively until
* all dispatchers of
* that a siblings to this have been started.
*
* @param isSynchronized If true, the dispatcher is to run in the invoking thread. If false,
* the
* dispatcher
* will start a new thread and execute in this.
*/
public Dispatcher commenceMessaging(boolean isSynchronized) {
//If there is a next dispatcher
if (mNextDispatcher != null) {
//Tell the next dispatcher to start its messaging.
mNextDispatcher.commenceMessaging(isSynchronized);
}
//If this is a synchronized execution
if (isSynchronized) {
//Run in the requesting thread.
this.run();
}//Else, i.e. should run in a new separate thread.
else {
//Start a new thread and let this dispatcher execute in this thread.
mThread = new Thread(this);
mThread.setName(this.getName() + ":" + mThreadNumber);
mThread.start();
}
return this;
}
/**
* Shutdown this and the next dispatcher.
*/
public void shutdown() {
//If there was a next dispatchers
if (this.mNextDispatcher != null) {
//Tell the next dispatcher to shutdown
this.mNextDispatcher.shutdown();
}
//Tell the channel to shut down. Send this thread as it is required for some channels to interrupt listening.
this.mChannel.shutdown(mThread);
}
// - REQUEST HANDLING
@Override
public void run() {
ByteStorage incomingRequest = new ByteStorage();
String decodedIncomingRequest;
Object responseAsObjects;
Object responseAsStrings;
String wrappedResponse = "";
byte[] wrappedResponseAsUtf8ByteArray;
Request request = null;
LogEntry logEntry = new LogEntry(mThreadNumber, mChannel);
while (true) {
try {
if (!mChannel.getRequest(incomingRequest)) {
break;
}
logEntry.setTimeOfIncomingCall();
// Get incoming request as string.
decodedIncomingRequest = incomingRequest.getAsString();
//Send the incoming request to the protocol for extracting method name and arguments
request = mParser.getRequest(decodedIncomingRequest);
//if is a file request
if (request.isFileRequest()) {
wrappedResponse = StringUtils.EMPTY;
wrappedResponseAsUtf8ByteArray = mWrapper.wrapFile(request.getFileName());
} // Else must be a method call
else {
MethodObject methodObject = mAPI.getMethodObject(request.getMethodName());
// is the dispatcher authorized to access this method
checkAccessLevel(methodObject.getAccessLevelRequiredToUseThisMethod());
responseAsObjects = methodObject.invoke(request.getArgumentValues(),
request.getArgumentNames(), mAccessLevel);
//If return type is Json
if (methodObject.getReturnDataType().isJson()) {
//Do json wrapping
wrappedResponse = mWrapper.wrapJSON((JSONObject) responseAsObjects);
} else {
responseAsStrings = methodObject.getReturnDataType().convertFromDataTypeToString(responseAsObjects);
wrappedResponse = mWrapper.wrapResponse((String) responseAsStrings);
}
wrappedResponseAsUtf8ByteArray = UTF8.getBytes(wrappedResponse);
}
} catch (Exception e) {
//If the exception has properties
wrappedResponse = (e instanceof IExceptionProperties)
? mWrapper.wrapError(((IExceptionProperties) e).getProperties())
: mWrapper.wrapError(Collections.singletonMap("error_message", e.getMessage()));
wrappedResponseAsUtf8ByteArray = UTF8.getBytes(wrappedResponse);
logEntry.setIsError();
} finally {
logEntry.setTimeOfIncomingCall();
// Get incoming request as string.
decodedIncomingRequest = incomingRequest.getAsString();
}
mChannel.writeResponse(wrappedResponseAsUtf8ByteArray);
logEntry.setLogData(decodedIncomingRequest, wrappedResponse, request);
this.log(logEntry);
logEntry.cleanUpLogData();
incomingRequest.clear();
}
}
private void checkAccessLevel(int methodAccessLevel) {
if (methodAccessLevel > this.mAccessLevel) {
throw new RuntimeException("Cannot access the requested method through this dispatcher. Method requires access level "
+ methodAccessLevel + " and the used dispatcher only has access level " + this.mAccessLevel + ".");
}
}
// - Logger
/**
* Adds a logger to this dispatcher.
*
* @param logger The logger to add.
* @return This for chaining
*/
public Dispatcher addLogger(Logger logger) {
mLoggers.add(logger);
if (mNextDispatcher != null) {
mNextDispatcher.addLogger(logger);
}
return this;
}
/**
* Removes all loggers from this dispatcher.
*
* @return This for chaining.
*/
public Dispatcher removeLoggers() {
mLoggers = Collections.<Logger>emptyList();
if (mNextDispatcher != null) {
mNextDispatcher.removeLoggers();
}
return this;
}
/**
* Logs the argument log entry all attached (if any) loggers.
*
* @param logEntry The entry to add to logs.
*/
private void log(LogEntry logEntry) {
//Go through all logger attached to this dispatcher
for (Logger logger : mLoggers) {
//Log event
logger.log(logEntry);
}
}
// - State
public State getState() {
return State.getBuilder()
.add("Name", this.getName())
.add("AccessLevel", mAccessLevel)
.add("Threads", this.mThreadNumber)
.addChild("Parser", mParser)
.addChild("Wrapper", mWrapper)
.addChild("Channel", mChannel)
.addChildren("Loggers", mLoggers)
.build();
}
}
|
package org.spiffyui.client;
import java.util.Date;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
/**
* A set of static JavaScript utilities for handling JSON data structures.
*/
public final class JSONUtil
{
/**
* Making sure this class can't be instantiated.
*/
private JSONUtil()
{
}
/**
* Get a string from the JSON object or null if it doesn't exist or
* isn't a string
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or null if it could not be decoded
*/
public static String getStringValue(JSONObject obj, String key)
{
return getStringValue(obj, key, null);
}
/**
* Get a string from the JSON object or defaultValue if it doesn't exist or
* isn't a string
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value to return if the key could not be found
*
* @return the value or the defaultValue if it could not be decoded
*/
public static String getStringValue(JSONObject obj, String key, String defaultValue)
{
if (!obj.containsKey(key)) {
return defaultValue;
}
JSONValue v = obj.get(key);
if (v != null) {
JSONString s = v.isString();
if (s != null) {
return s.stringValue();
}
}
return defaultValue;
}
/**
* Get a string from the JSON object or null if it doesn't exist or
* isn't a string
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or null it could not be decoded
*/
public static String getStringValueIgnoreCase(JSONObject obj, String key)
{
return getStringValueIgnoreCase(obj, key, null);
}
/**
* Get a string from the JSON object or defaultValue if it doesn't exist or
* isn't a string
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value to return if the key could not be found
*
* @return the value or the defaultValue if it could not be decoded
*/
public static String getStringValueIgnoreCase(JSONObject obj, String key, String defaultValue)
{
JSONValue v = obj.get(key);
if (v == null) {
key = key.toLowerCase();
for (String k : obj.keySet()) {
if (key.equals(k.toLowerCase())) {
v = obj.get(k);
break;
}
}
}
if (v != null) {
JSONString s = v.isString();
if (s != null) {
return s.stringValue();
}
}
return defaultValue;
}
/**
* Get a boolean from the JSON object false if it doesn't exist or
* isn't a boolean
*
* @param obj the object with the value
* @param key the key for the object
* @return the value or false if it could not be decoded
*/
public static boolean getBooleanValue(JSONObject obj, String key)
{
return getBooleanValue(obj, key, false);
}
/**
* Get a boolean from the JSON object or defaultValue if it doesn't exist or
* isn't a boolean
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value if the key can not be found
*
* @return the value or false it could not be decoded
*/
public static boolean getBooleanValue(JSONObject obj, String key, boolean defaultValue)
{
if (!obj.containsKey(key)) {
return defaultValue;
}
JSONValue v = obj.get(key);
if (v != null) {
JSONBoolean b = v.isBoolean();
if (b != null) {
return b.booleanValue();
} else {
JSONString s = v.isString();
if (s != null) {
return Boolean.parseBoolean(s.stringValue());
}
}
}
return defaultValue;
}
/**
* Get a JSONArray from the JSON object or null if it doesn't exist or
* isn't a JSONArray
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or null it could not be decoded
*/
public static JSONArray getJSONArray(JSONObject obj, String key)
{
JSONValue v = obj.get(key);
if (v != null) {
JSONArray a = v.isArray();
if (a != null) {
return a;
}
}
return null;
}
/**
* Get an int from the JSON object or -1 if it doesn't exist or
* isn't an int. This will handle JSON numbers like this:
*
* "val": 5
*
* It will also handle numbers in strings like:
*
* "val": "5"
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or -1 if it could not be decoded
*/
public static int getIntValue(JSONObject obj, String key)
{
return getIntValue(obj, key, -1);
}
/**
* Get an int from the JSON object or the defaultValue if it doesn't exist or
* isn't an int. This will handle JSON numbers like this:
*
* "val": 5
*
* It will also handle numbers in strings like:
*
* "val": "5"
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value if the specified key isn't found.
*
* @return the value or the defaultValue if it could not be decoded
*/
public static int getIntValue(JSONObject obj, String key, int defaultValue)
{
if (!obj.containsKey(key)) {
return defaultValue;
}
try {
JSONValue v = obj.get(key);
if (v != null) {
JSONNumber n = v.isNumber();
if (n != null) {
return (int) n.doubleValue();
} else {
/*
* If this isn't a number, then it might be a string
* like "5" so we try to parse it as a number.
*/
return Integer.parseInt(getStringValue(obj, key));
}
}
} catch (Exception e) {
JSUtil.println(e.getMessage());
}
return defaultValue;
}
/**
* Get a double from the JSON object or 0 if it doesn't exist or
* isn't a double. This will handle JSON numbers like this:
*
* "val": 0.5 or "val": -0.5 or "val": +0.5
*
* It will also handle numbers in strings like:
*
* "val": "0.5" or "val": "-0.5" or "val": "+0.5"
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or 0 if it could not be decoded
*/
public static double getDoubleValue(JSONObject obj, String key)
{
return getDoubleValue(obj, key, 0);
}
/**
* Get a double from the JSON object or the defaultValue if it doesn't exist or
* isn't a double. This will handle JSON numbers like this:
*
* "val": 0.5 or "val": -0.5 or "val": +0.5
*
* It will also handle numbers in strings like:
*
* "val": "0.5" or "val": "-0.5" or "val": "+0.5"
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value if the specified key isn't found.
*
* @return the value or the defaultValue if it could not be decoded
*/
public static double getDoubleValue(JSONObject obj, String key, double defaultValue)
{
if (!obj.containsKey(key)) {
return defaultValue;
}
try {
JSONValue v = obj.get(key);
if (v != null) {
JSONNumber n = v.isNumber();
if (n != null) {
return n.doubleValue();
} else {
/*
* If this isn't a number, then it might be a string
* like "5" so we try to parse it as a number.
*/
return Double.parseDouble(getStringValue(obj, key));
}
}
} catch (Exception e) {
JSUtil.println(e.getMessage());
}
return defaultValue;
}
/**
* Get a long from the JSON object or -1 if it doesn't exist or
* isn't a long. This will handle JSON numbers like this:
*
* "val": 5
*
* It will also handle numbers in strings like:
*
* "val": "5"
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or -1 if it could not be decoded
*/
public static long getLongValue(JSONObject obj, String key)
{
return getLongValue(obj, key, -1L);
}
/**
* Get a long from the JSON object or the defaultValue if it doesn't exist or
* isn't a long. This will handle JSON numbers like this:
*
* "val": 5
*
* It will also handle numbers in strings like:
*
* "val": "5"
*
* @param obj the object with the value
* @param key the key for the object
* @param defaultValue the default value if the specified key isn't found.
*
* @return the value or the defaultValue if it could not be decoded
*/
public static long getLongValue(JSONObject obj, String key, long defaultValue)
{
if (!obj.containsKey(key)) {
return defaultValue;
}
try {
JSONValue v = obj.get(key);
if (v != null) {
JSONNumber n = v.isNumber();
if (n != null) {
return (long) n.doubleValue();
} else {
/*
* If this isn't a number, then it might be a string
* like "5" so we try to parse it as a number.
*/
return Long.parseLong(getStringValue(obj, key));
}
}
} catch (Exception e) {
JSUtil.println(e.getMessage());
}
return defaultValue;
}
/**
* Get a JSONObject from the JSON object or null if it doesn't exist or
* isn't a JSONObject
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or null it could not be decoded
*/
public static JSONObject getJSONObject(JSONObject obj, String key)
{
JSONValue v = obj.get(key);
if (v != null) {
JSONObject a = v.isObject();
if (a != null) {
return a;
}
}
return null;
}
/**
* Get a java.util.Date from the JSON object as an epoch time in milliseconds
* or return null if it doesn't exist or
* cannot be converted from epoch to Date
*
* @param obj the object with the value
* @param key the key for the object
*
* @return the value or null it could not be decoded/converted
*/
public static Date getDateValue(JSONObject obj, String key)
{
JSONValue v = obj.get(key);
if (v != null) {
JSONNumber n = v.isNumber();
if (n != null) {
return new Date(Double.valueOf(n.doubleValue()).longValue());
} else {
String s = getStringValue(obj, key);
if (s != null) {
return new Date(Long.parseLong(s));
}
}
}
return null;
}
}
|
package be.ibridge.kettle.trans.step.normaliser;
import java.util.ArrayList;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Normalise de-normalised input data.
*
* @author Matt
* @since 5-apr-2003
*/
public class Normaliser extends BaseStep implements StepInterface
{
private NormaliserMeta meta;
private NormaliserData data;
public Normaliser(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=(NormaliserMeta)smi;
data=(NormaliserData)sdi;
Row r=getRow(); // get row from rowset, wait for our turn, indicate busy!
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
if (first) // INITIALISE
{
first = false;
// Get the list of occurances...
data.type_occ = new ArrayList();
data.maxlen=0;
for (int i=0;i<meta.getFieldValue().length;i++)
{
boolean found=false;
for (int j=0;j<data.type_occ.size();j++)
{
if (((String)data.type_occ.get(j)).equalsIgnoreCase(meta.getFieldValue()[i])) found=true;
}
if (!found) data.type_occ.add(meta.getFieldValue()[i]);
if (meta.getFieldValue()[i].length()>data.maxlen) data.maxlen=meta.getFieldValue()[i].length();
}
// Which fields are not impacted? just copy these, leave them alone.
data.copy_fieldnrs = new ArrayList();
for (int i=0;i<r.size();i++)
{
Value v = r.getValue(i);
boolean found=false;
for (int j=0;j<meta.getFieldName().length && !found;j++)
{
if (v.getName().equalsIgnoreCase(meta.getFieldName()[j]))
{
found = true;
}
}
if (!found)
{
data.copy_fieldnrs.add(new Integer(i));
}
}
// Cache lookup of fields
data.fieldnrs=new int[meta.getFieldName().length];
for (int i=0;i<meta.getFieldName().length;i++)
{
data.fieldnrs[i] = r.searchValueIndex(meta.getFieldName()[i]);
if (data.fieldnrs[i]<0)
{
logError("Couldn't find field ["+meta.getFieldName()[i]+" in row!");
setErrors(1);
stopAll();
return false;
}
}
}
for (int e=0;e<data.type_occ.size();e++)
{
String typevalue = (String)data.type_occ.get(e);
Row newrow = new Row();
// First add the copy fields:
for (int i=0;i<data.copy_fieldnrs.size();i++)
{
int nr = ((Integer)data.copy_fieldnrs.get(i)).intValue();
Value v = r.getValue(nr);
newrow.addValue(new Value(v));
}
// Add the typefield_value
Value typefield_value = new Value(meta.getTypeField(), typevalue);
typefield_value.setLength(data.maxlen);
newrow.addValue(typefield_value);
// Then add the norm fields...
for (int i=0;i<data.fieldnrs.length;i++)
{
Value v = r.getValue(data.fieldnrs[i]);
if (meta.getFieldValue()[i].equalsIgnoreCase(typevalue))
{
v.setName(meta.getFieldNorm()[i]);
newrow.addValue(v);
}
}
// The row is constructed, now give it to the next step...
putRow(newrow);
}
if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesRead);
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(NormaliserMeta)smi;
data=(NormaliserData)sdi;
if (super.init(smi, sdi))
{
// Add init code here.
return true;
}
return false;
}
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error in '"+debug+"' : "+e.toString());
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
|
package com.composum.sling.cpnl;
import com.composum.sling.core.BeanContext;
import com.composum.sling.core.SlingBean;
import com.composum.sling.core.bean.BeanFactory;
import com.composum.sling.core.bean.SlingBeanFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.osgi.framework.InvalidSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* a tag to instantiate a bean or model object
*/
public class ComponentTag extends CpnlBodyTagSupport {
private static final Logger LOG = LoggerFactory.getLogger(ComponentTag.class);
protected String var;
protected String type;
protected Integer varScope;
protected Boolean replace;
protected SlingBean component;
private transient Class<? extends SlingBean> componentType;
private static final Map<Class<? extends SlingBean>, Field[]> fieldCache = new ConcurrentHashMap<>();
protected ArrayList<Map<String, Object>> replacedAttributes;
public static final Map<String, Integer> SCOPES = new HashMap<>();
static {
SCOPES.put("page", PageContext.PAGE_SCOPE);
SCOPES.put("request", PageContext.REQUEST_SCOPE);
SCOPES.put("session", PageContext.SESSION_SCOPE);
}
@Override
protected void clear() {
var = null;
type = null;
varScope = null;
replace = null;
component = null;
replacedAttributes = null;
componentType = null;
super.clear();
}
@Override
public int doStartTag() throws JspException {
super.doStartTag();
if (getVar() != null) {
try {
if (available() == null || getReplace()) {
component = createComponent();
setAttribute(getVar(), component, getVarScope());
}
} catch (ClassNotFoundException ex) {
LOG.error("Class not found: " + this.type, ex);
} catch (IllegalAccessException ex) {
LOG.error("Could not access: " + this.type, ex);
} catch (InstantiationException ex) {
LOG.error("Could not instantiate: " + this.type, ex);
} catch (IllegalArgumentException ex) {
LOG.error("Could not adapt to: " + this.type, ex);
}
}
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException {
restoreAttributes();
clear();
super.doEndTag();
return EVAL_PAGE;
}
/**
* Configure an var / variable name to store the component in the context
*/
@Override
public void setId(String id) {
setVar(id);
}
/**
* Configure an var / variable name to store the component in the context
*/
public void setVar(String id) {
this.var = id;
}
public String getVar() {
return this.var;
}
/**
* Component class to instantiate (full notation as in Class.name)
*/
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
/**
* Determine the varScope (<code>page</code>, <code>request</code> or <code>session</code>)
* for the component instance attribute
*/
public void setScope(String key) {
varScope = key != null ? SCOPES.get(key.toLowerCase()) : null;
}
public void setVarScope(Integer value) {
varScope = value;
}
public Integer getVarScope() {
return varScope != null ? varScope : PageContext.PAGE_SCOPE;
}
/**
* Determine the reuse policy if an appropriate instance is already existing.
*
* @param flag <code>false</code> - (re)use an appropriate available instance;
* <code>true</code> - replace each potentially existing instance
* (default in 'page' context).
*/
public void setReplace(Boolean flag) {
this.replace = flag;
}
public Boolean getReplace() {
return replace != null ? replace : (getVarScope() == PageContext.PAGE_SCOPE);
}
/**
* get the content type class object
*/
@SuppressWarnings("unchecked")
protected Class<? extends SlingBean> getComponentType() throws ClassNotFoundException {
if (componentType == null) {
String type = getType();
if (StringUtils.isNotBlank(type)) {
componentType = (Class<? extends SlingBean>) context.getType(type);
}
}
return componentType;
}
/**
* Check for an existing instance of the same var and assignable type
*/
protected Object available() throws ClassNotFoundException {
Object result = null;
if (getVar() != null) {
Object value = pageContext.getAttribute(getVar(), getVarScope());
if (value instanceof SlingBean) {
Class<?> type = getComponentType();
if (type != null && type.isAssignableFrom(value.getClass())) {
result = value;
}
}
}
return result;
}
/**
* Create the requested component instance
*/
protected SlingBean createComponent() throws ClassNotFoundException, IllegalAccessException,
InstantiationException {
SlingBean component = null;
Class<? extends SlingBean> type = getComponentType();
if (type != null) {
BeanFactory factoryRule = type.getAnnotation(BeanFactory.class);
Resource modelResource = getModelResource(context);
if (factoryRule != null) {
SlingBeanFactory factory = context.getService(factoryRule.serviceClass());
if (factory != null) {
return factory.createBean(context, modelResource, type);
}
}
BeanContext baseContext = context.withResource(modelResource);
component = baseContext.adaptTo(type);
if (component == null) {
throw new IllegalArgumentException("Could not adapt " + modelResource + " to " + type);
}
injectServices(component);
additionalInitialization(component);
}
return component;
}
/**
* Hook that can change the resource used for {@link #createComponent()} if necessary. This implementation just uses
* the resource from the {@link #context} ( {@link BeanContext#getResource()} ).
*/
public Resource getModelResource(BeanContext context) {
return context.getResource();
}
/**
* Hook for perform additional initialization of the component. When called, the fields of the component are already
* initialized with Sling-Models or {@link SlingBean#initialize(BeanContext)} / {@link
* SlingBean#initialize(BeanContext, Resource)}.
*/
protected void additionalInitialization(SlingBean component) {
// empty
}
/**
* Inject OSGI services for attributes marked for injection in a new component instance, if not already
* initialized e.g. by Sling-Models.
*/
protected void injectServices(SlingBean component) throws IllegalAccessException {
final Field[] declaredFields;
if (fieldCache.containsKey(component.getClass())) {
declaredFields = fieldCache.get(component.getClass());
} else {
declaredFields = component.getClass().getDeclaredFields();
fieldCache.put(component.getClass(), declaredFields);
}
for (Field field : declaredFields) {
if (field.isAnnotationPresent(Inject.class)) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (null == field.get(component)) { // if not initialized already by Sling-Models
String filter = null;
if (field.isAnnotationPresent(Named.class)) {
Named name = field.getAnnotation(Named.class);
filter = "(service.pid=" + name.value() + ")";
}
Class<?> typeOfField = field.getType();
Object o = retrieveFirstServiceOfType(typeOfField, filter);
field.set(component, o);
}
}
}
}
protected <T> T retrieveFirstServiceOfType(Class<T> serviceType, String filter) {
T[] services = null;
try {
services = context.getServices(serviceType, filter);
} catch (InvalidSyntaxException ex) {
LOG.error(ex.getMessage(), ex);
}
return services == null ? null : services[0];
}
// attribute replacement registry...
/**
* retrieves the registry for one scope
*/
protected Map<String, Object> getReplacedAttributes(int scope) {
if (replacedAttributes == null) {
replacedAttributes = new ArrayList<>();
}
while (replacedAttributes.size() <= scope) {
replacedAttributes.add(new HashMap<String, Object>());
}
return replacedAttributes.get(scope);
}
/**
* each attribute set by a tag should use this method for attribute declaration;
* an existing value with the same key is registered and restored if the tag rendering ends
*/
protected void setAttribute(String key, Object value, int scope) {
Map<String, Object> replacedInScope = getReplacedAttributes(scope);
if (!replacedInScope.containsKey(key)) {
Object current = pageContext.getAttribute(key, scope);
replacedInScope.put(key, current);
}
pageContext.setAttribute(key, value, scope);
}
/**
* restores all replaced values and removes all attributes declared in this tag
*/
protected void restoreAttributes() {
if (replacedAttributes != null) {
for (int scope = 0; scope < replacedAttributes.size(); scope++) {
Map<String, Object> replaced = replacedAttributes.get(scope);
for (Map.Entry<String, Object> entry : replaced.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value != null) {
pageContext.setAttribute(key, value, scope);
} else {
pageContext.removeAttribute(key, scope);
}
}
}
}
}
}
|
package io.ray.test;
import io.ray.api.ActorHandle;
import io.ray.api.BaseActorHandle;
import io.ray.api.ObjectRef;
import io.ray.api.Ray;
import io.ray.api.options.ActorCreationOptions;
import io.ray.runtime.AbstractRayRuntime;
import io.ray.runtime.functionmanager.FunctionDescriptor;
import io.ray.runtime.functionmanager.JavaFunctionDescriptor;
import java.io.File;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.apache.commons.io.FileUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ClassLoaderTest extends BaseTest {
private final String resourcePath = FileUtils.getTempDirectoryPath()
+ "/ray_test/ClassLoaderTest";
@BeforeClass
public void setUp() {
// The potential issue of multiple `ClassLoader` instances for the same job on multi-threading
// scenario only occurs if the classes are loaded from the job resource path.
System.setProperty("ray.job.resource-path", resourcePath);
}
@AfterClass
public void tearDown() {
System.clearProperty("ray.job.resource-path");
}
@Test(groups = {"cluster"})
public void testClassLoaderInMultiThreading() throws Exception {
final String jobResourcePath = resourcePath + "/" + Ray.getRuntimeContext().getCurrentJobId();
File jobResourceDir = new File(jobResourcePath);
FileUtils.deleteQuietly(jobResourceDir);
jobResourceDir.mkdirs();
jobResourceDir.deleteOnExit();
// In this test case the class is expected to be loaded from the job resource path, so we need
// to put the compiled class file into the job resource path and load it later.
String testJavaFile = ""
+ "import java.lang.management.ManagementFactory;\n"
+ "import java.lang.management.RuntimeMXBean;\n"
+ "\n"
+ "public class ClassLoaderTester {\n"
+ "\n"
+ " static volatile int value;\n"
+ "\n"
+ " public int getPid() {\n"
+ " RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();\n"
+ " String name = runtime.getName();\n"
+ " int index = name.indexOf(\"@\");\n"
+ " if (index != -1) {\n"
+ " return Integer.parseInt(name.substring(0, index));\n"
+ " } else {\n"
+ " throw new RuntimeException(\"parse pid error:\" + name);\n"
+ " }\n"
+ " }\n"
+ "\n"
+ " public int increase() throws InterruptedException {\n"
+ " return increaseInternal();\n"
+ " }\n"
+ "\n"
+ " public static synchronized int increaseInternal() throws InterruptedException {\n"
+ " int oldValue = value;\n"
+ " Thread.sleep(10 * 1000);\n"
+ " value = oldValue + 1;\n"
+ " return value;\n"
+ " }\n"
+ "\n"
+ " public int getClassLoaderHashCode() {\n"
+ " return this.getClass().getClassLoader().hashCode();\n"
+ " }\n"
+ "}";
// Write the demo java file to the job resource path.
String javaFilePath = jobResourcePath + "/ClassLoaderTester.java";
Files.write(Paths.get(javaFilePath), testJavaFile.getBytes());
// Compile the java file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "-d",
jobResourcePath, javaFilePath);
if (result != 0) {
throw new RuntimeException("Couldn't compile ClassLoaderTester.java.");
}
FunctionDescriptor constructor = new JavaFunctionDescriptor(
"ClassLoaderTester", "<init>", "()V");
ActorHandle<?> actor1 = createActor(constructor);
FunctionDescriptor getPid = new JavaFunctionDescriptor(
"ClassLoaderTester", "getPid", "()I");
int pid = this.<Integer>callActorFunction(actor1, getPid, new Object[0],
Optional.of(Integer.class)).get();
ActorHandle<?> actor2;
while (true) {
// Create another actor which share the same process of actor 1.
actor2 = createActor(constructor);
int actor2Pid = this.<Integer>callActorFunction(actor2, getPid, new Object[0],
Optional.of(Integer.class)).get();
if (actor2Pid == pid) {
break;
}
}
FunctionDescriptor getClassLoaderHashCode = new JavaFunctionDescriptor(
"ClassLoaderTester", "getClassLoaderHashCode", "()I");
ObjectRef<Integer> hashCode1 = callActorFunction(actor1, getClassLoaderHashCode, new Object[0],
Optional.of(Integer.class));
ObjectRef<Integer> hashCode2 = callActorFunction(actor2, getClassLoaderHashCode, new Object[0],
Optional.of(Integer.class));
Assert.assertEquals(hashCode1.get(), hashCode2.get());
FunctionDescriptor increase = new JavaFunctionDescriptor(
"ClassLoaderTester", "increase", "()I");
ObjectRef<Integer> value1 = callActorFunction(actor1, increase, new Object[0],
Optional.of(Integer.class));
ObjectRef<Integer> value2 = callActorFunction(actor2, increase, new Object[0],
Optional.of(Integer.class));
Assert.assertNotEquals(value1.get(), value2.get());
}
private ActorHandle<?> createActor(FunctionDescriptor functionDescriptor)
throws Exception {
Method createActorMethod = AbstractRayRuntime.class.getDeclaredMethod("createActorImpl",
FunctionDescriptor.class, Object[].class, ActorCreationOptions.class);
createActorMethod.setAccessible(true);
return (ActorHandle<?>) createActorMethod
.invoke(TestUtils.getUnderlyingRuntime(), functionDescriptor, new Object[0], null);
}
private <T> ObjectRef<T> callActorFunction(
ActorHandle<?> rayActor,
FunctionDescriptor functionDescriptor,
Object[] args,
Optional<Class<?>> returnType)
throws Exception {
Method callActorFunctionMethod = AbstractRayRuntime.class.getDeclaredMethod("callActorFunction",
BaseActorHandle.class, FunctionDescriptor.class, Object[].class, Optional.class);
callActorFunctionMethod.setAccessible(true);
return (ObjectRef<T>) callActorFunctionMethod
.invoke(TestUtils.getUnderlyingRuntime(), rayActor, functionDescriptor, args, returnType);
}
}
|
package loci.formats.in;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.Constants;
import loci.common.DataTools;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
public class SlidebookReader extends FormatReader {
// -- Constants --
public static final int SLD_MAGIC_BYTES_1_0 = 0x006c;
public static final int SLD_MAGIC_BYTES_1_1 = 0x0100;
public static final int SLD_MAGIC_BYTES_2_0 = 0x01f5;
public static final int SLD_MAGIC_BYTES_2_1 = 0x0102;
public static final long SLD_MAGIC_BYTES_3 = 0xf6010101L;
// -- Fields --
private Vector<Long> metadataOffsets;
private Vector<Long> pixelOffsets;
private Vector<Long> pixelLengths;
private Vector<Double> ndFilters;
private Hashtable<Integer, String> imageDescriptions;
private long[][] planeOffset;
private boolean adjust = true;
private boolean isSpool;
private Hashtable<Integer, Integer> metadataInPlanes;
// -- Constructor --
/** Constructs a new Slidebook reader. */
public SlidebookReader() {
super("Olympus Slidebook", new String[] {"sld", "spl"});
domains = new String[] {FormatTools.LM_DOMAIN};
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 8;
stream.seek(4);
boolean littleEndian = stream.readString(2).equals("II");
if (!FormatTools.validStream(stream, blockLen, littleEndian)) return false;
int magicBytes1 = stream.readShort();
int magicBytes2 = stream.readShort();
return ((magicBytes2 & 0xff00) == SLD_MAGIC_BYTES_1_1) &&
(magicBytes1 == SLD_MAGIC_BYTES_1_0 ||
magicBytes1 == SLD_MAGIC_BYTES_2_0);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
long offset = planeOffset[getSeries()][no];
in.seek(offset);
int[] zct = getZCTCoords(no);
// if this is a spool file, there may be an extra metadata block here
if (isSpool) {
long len = pixelLengths.get(getSeries());
long planeSize = FormatTools.getPlaneSize(this);
long diff = len - getImageCount() * planeSize;
in.seek(in.getFilePointer() - diff);
Integer[] keys = metadataInPlanes.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
for (int key : keys) {
if (key < no) {
in.skipBytes(256);
}
}
// check next 8 blocks of 256 bytes, just in case
long beginning = in.getFilePointer();
for (int i=0; i<8; i++) {
if (in.getFilePointer() + 4 >= in.length()) {
in.seek(beginning);
break;
}
in.order(false);
long magicBytes = (long) in.readInt() & 0xffffffffL;
in.order(isLittleEndian());
if (magicBytes == SLD_MAGIC_BYTES_3 && !metadataInPlanes.contains(no)) {
metadataInPlanes.put(no, 0);
in.skipBytes(252);
break;
}
else if (i == 7) {
in.seek(beginning);
}
else {
in.skipBytes(252);
}
}
}
readPlane(in, x, y, w, h, buf);
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
metadataOffsets = pixelOffsets = pixelLengths = null;
ndFilters = null;
isSpool = false;
metadataInPlanes = null;
adjust = true;
planeOffset = null;
imageDescriptions = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core.get(0).littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
imageDescriptions = new Hashtable<Integer, String>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if ((buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0) ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i')))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
else if (((buf[i] == 'j' || buf[i] == 'k' || buf[i] == 'n') &&
buf[i + 1] == 0) || (buf[i] == 0 && (buf[i + 1] == 'j' ||
buf[i + 1] == 'k' || buf[i + 1] == 'n')) ||
(buf[i] == 'o' && buf[i + 1] == 'n'))
{
found = true;
pixelOffsets.remove(pixelOffsets.size() - 1);
in.seek(in.getFilePointer() - n + i - 20);
break;
}
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
if (length >= 1024) {
pixelLengths.add(new Long(length));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
Vector<Long> orderedSeries = new Vector<Long>();
Hashtable<Long, Vector<Integer>> uniqueSeries =
new Hashtable<Long, Vector<Integer>>();
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i
}
else {
Vector<Integer> v = uniqueSeries.get(length);
if (v == null) {
orderedSeries.add(length);
v = new Vector<Integer>();
}
v.add(i);
uniqueSeries.put(length, v);
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
int seriesCount = 0;
for (int i=0; i<uniqueSeries.size(); i++) {
Vector<Integer> pixelIndexes = uniqueSeries.get(orderedSeries.get(i));
int nBlocks = pixelIndexes.size();
if (nBlocks == 0) {
nBlocks++;
}
seriesCount += nBlocks;
}
core.clear();
for (int i=0; i<seriesCount; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
ms.littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Hashtable<Integer, Float> pixelSize = new Hashtable<Integer, Float>();
Hashtable<Integer, String> objectives = new Hashtable<Integer, String>();
Hashtable<Integer, Integer> magnifications =
new Hashtable<Integer, Integer>();
Vector<Double> pixelSizeZ = new Vector<Double>();
Vector<Integer> exposureTimes = new Vector<Integer>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
int[] sizeX = new int[pixelOffsets.size()];
int[] sizeY = new int[pixelOffsets.size()];
int[] sizeZ = new int[pixelOffsets.size()];
int[] sizeC = new int[pixelOffsets.size()];
int[] divValues = new int[pixelOffsets.size()];
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
if (isSpool && off == 0) {
off = 276;
}
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
//if (totalBlocks > 100) totalBlocks = 100;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) {
continue;
}
in.seek(off + (long) q * 128);
char n = (char) in.readShort();
while (n == 0 && in.getFilePointer() < off + (q + 1) * 128) {
n = (char) in.readShort();
}
if (in.getFilePointer() >= in.length() - 2) break;
if (n == 'i') {
iCount++;
in.skipBytes(70);
int expTime = in.readInt();
if (expTime > 0) {
exposureTimes.add(expTime);
}
in.skipBytes(20);
Double size = new Double(in.readFloat());
if (isGreaterThanEpsilon(size)) {
pixelSizeZ.add(size);
}
else {
pixelSizeZ.add(null);
}
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (sizeX[j] == 0) {
int x = in.readShort();
int y = in.readShort();
if (x != 0 && y != 0) {
sizeX[j] = x;
sizeY[j] = y;
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
if (checkX == checkY) {
divValues[j] = div;
sizeX[j] /= (div == 0 ? 1 : div);
div = in.readShort();
sizeY[j] /= (div == 0 ? 1 : div);
}
}
else in.skipBytes(8);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
sizeC[j] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<getSeriesCount(); j++) {
long end = j == getSeriesCount() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
sizeZ[j] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
long pointer = in.getFilePointer();
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
String name = in.readCString().trim();
if (name.length() > 0) {
imageNames[nextName++] = name;
}
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
if (in.readShort() == 0) {
in.skipBytes(4);
}
else {
in.skipBytes(16);
}
long diff = in.getFilePointer() - fp;
if (diff > 123 && (fp % 2) == 0 && diff != 142 && diff != 143 &&
diff != 130)
{
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
if (x > 0x8000 || y > 0x8000) {
in.seek(in.getFilePointer() - 7);
x = in.readInt();
y = in.readInt();
}
else if (x == 0 || y == 0) {
in.seek(in.getFilePointer() - 27);
x = in.readInt();
y = in.readInt();
}
int div = in.readShort();
x /= (div == 0 || div > 0x100 ? 1 : div);
div = in.readShort();
y /= (div == 0 || div > 0x100 ? 1 : div);
if (x > 0x10000 || y > 0x10000) {
in.seek(in.getFilePointer() - 11);
x = in.readInt();
y = in.readInt();
div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 0x10000 || y > 0x10000) {
in.skipBytes(2);
x = in.readInt();
y = in.readInt();
div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
}
}
if (nextName >= 1 && x > 16 && (x < sizeX[nextName - 1] ||
sizeX[nextName - 1] == 0) && y > 16 &&
(y < sizeY[nextName - 1] || sizeY[nextName - 1] == 0))
{
sizeX[nextName - 1] = x;
sizeY[nextName - 1] = y;
adjust = false;
}
in.seek(pointer + 214);
int validBits = in.readShort();
if (nextName >= 1 && core.get(nextName - 1).bitsPerPixel == 0 &&
validBits <= 16)
{
core.get(nextName - 1).bitsPerPixel = validBits;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue() || isSpool)
{
in.skipBytes(14);
String name = in.readCString().trim();
if (name.length() > 1) {
channelNames.add(name);
}
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
while (in.read() == 0);
in.seek(in.getFilePointer() - 1);
long nSkipped = in.getFilePointer() - fp;
if (nSkipped < 8) {
in.skipBytes((int) (8 - nSkipped));
}
String objective = in.readCString().trim();
in.seek(fp + 144);
float pixSize = in.readFloat();
int magnification = in.readShort();
int mult = 1;
if (pixelSize.size() < divValues.length) {
mult = divValues[pixelSize.size()];
}
float v = pixSize * mult;
if (isGreaterThanEpsilon(v)) {
pixelSize.put(nextName - 1, v);
objectives.put(nextName - 1, objective);
magnifications.put(nextName - 1, magnification);
}
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
if (nextName >= 0 && nextName < getSeriesCount()) {
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (n == 'n') {
long fp1 = in.getFilePointer();
in.seek(in.getFilePointer() - 3);
while (in.read() != 0) {
in.seek(in.getFilePointer() - 2);
}
long fp2 = in.getFilePointer();
int len = in.read() - 1;
int currentSeries = 0;
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
currentSeries = j;
break;
}
}
if (len > 0 && fp1 - fp2 != 2) {
if (fp2 < fp1) {
in.seek(in.getFilePointer() - 1);
String descr = in.readCString();
descr = descr.substring(0, descr.length() - 2);
if (!descr.endsWith("Annotatio")) {
imageDescriptions.put(currentSeries, descr.trim());
}
}
else {
imageDescriptions.put(currentSeries, in.readString(len).trim());
}
}
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(14);
int check = in.readShort();
int x = in.readShort();
int y = in.readShort();
if (check == 0 && x > 16 && y > 16) {
sizeX[j] = x;
sizeY[j] = y;
}
adjust = false;
break;
}
}
}
}
}
// TODO: extend the name matching to include "* Timepoint *"
String currentName = imageNames[0];
ArrayList<CoreMetadata> realCore = new ArrayList<CoreMetadata>();
int t = 1;
boolean noFlattening =
currentName != null && currentName.equals("Untitled");
for (int i=1; i<getSeriesCount(); i++) {
if (imageNames[i] == null || !imageNames[i].equals(currentName) ||
noFlattening ||
(i == 1 && (sizeX[i - 1] != sizeX[i] || sizeY[i - 1] != sizeY[i] ||
sizeC[i - 1] != sizeC[i] || sizeZ[i - 1] != sizeZ[i])))
{
currentName = imageNames[i];
CoreMetadata nextCore = core.get(i - 1);
nextCore.sizeT = t;
realCore.add(nextCore);
if (t == 1) {
noFlattening = true;
}
t = 1;
if (i == 1) {
noFlattening = true;
}
}
else {
t++;
}
}
core.get(getSeriesCount() - 1).sizeT = t;
realCore.add(core.get(getSeriesCount() - 1));
boolean flattened = false;
if (core.size() != realCore.size() && !noFlattening) {
flattened = true;
core = realCore;
orderedSeries.clear();
uniqueSeries.clear();
int nextIndex = 0;
for (int i=0; i<core.size(); i++) {
long thisSeries = (long) i;
orderedSeries.add(thisSeries);
Vector<Integer> indexes = new Vector<Integer>();
indexes.add(nextIndex);
uniqueSeries.put(thisSeries, indexes);
long length = pixelLengths.get(nextIndex);
length *= core.get(i).sizeT;
pixelLengths.setElementAt(length, i);
nextIndex += core.get(i).sizeT;
}
}
planeOffset = new long[getSeriesCount()][];
boolean divByTwo = false;
boolean divZByTwo = false;
int nextPixelIndex = 0;
int nextBlock = 0;
int nextOffsetIndex = 0;
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
CoreMetadata ms = core.get(i);
Vector<Integer> pixelIndexes =
uniqueSeries.get(orderedSeries.get(nextPixelIndex));
int nBlocks = pixelIndexes.size();
if (nextBlock >= nBlocks) {
nextPixelIndex++;
nextBlock = 0;
pixelIndexes = uniqueSeries.get(orderedSeries.get(nextPixelIndex));
nBlocks = pixelIndexes.size();
}
else {
nextBlock++;
}
int index =
pixelIndexes.size() == getSeriesCount() ? pixelIndexes.get(0) : i;
long pixels = pixelLengths.get(index).longValue() / 2;
boolean x = true;
ms.sizeX = sizeX[index];
ms.sizeY = sizeY[index];
ms.sizeC = sizeC[index];
ms.sizeZ = sizeZ[index];
if (getSizeC() > 64) {
// dimensions are probably incorrect
ms.sizeC = 1;
ms.sizeZ = 1;
ms.sizeX /= 2;
ms.sizeY /= 2;
}
boolean isMontage = false;
if (i > 1 && ((imageNames[i] != null &&
imageNames[i].startsWith("Montage")) || getSizeC() >= 32))
{
ms.sizeC = core.get(1).sizeC;
ms.sizeZ = core.get(1).sizeZ;
isMontage = true;
}
boolean cGreater = ms.sizeC > ms.sizeZ;
if (isSpool) {
if (ms.sizeC == 0) {
ms.sizeC = channelNames.size();
}
}
if (ms.sizeZ % nBlocks == 0 && nBlocks != getSizeC()) {
int z = ms.sizeZ / nBlocks;
if (z <= nBlocks) {
ms.sizeZ = z;
}
}
if (divByTwo) ms.sizeX /= 2;
if (divZByTwo && ms.sizeC > 1) {
ms.sizeZ = (int) ((pixels / (ms.sizeX * ms.sizeY)) / 2);
ms.sizeC = 2;
}
if (getSizeC() == 0) ms.sizeC = 1;
if (getSizeZ() == 0) ms.sizeZ = 1;
long plane = pixels / (getSizeC() * getSizeZ());
if (getSizeT() > 0) {
plane /= getSizeT();
}
if (getSizeX() * getSizeY() == pixels) {
if (getSizeC() == 2 && (getSizeX() % 2 == 0) && (getSizeY() % 2 == 0)) {
if (getSizeC() != getSizeZ()) {
ms.sizeX /= 2;
divByTwo = true;
}
else {
divZByTwo = true;
ms.sizeC = 1;
}
}
else {
ms.sizeC = 1;
}
ms.sizeZ = 1;
}
else if (getSizeX() * getSizeY() * getSizeZ() == pixels) {
if (getSizeC() == 2 && getSizeC() != getSizeZ() &&
(getSizeX() % 2 == 0) && (getSizeY() % 2 == 0) && (i == 0 ||
core.get(i - 1).sizeC > 1))
{
ms.sizeX /= 2;
divByTwo = true;
}
else {
ms.sizeC = 1;
ms.sizeZ = (int) (pixels / (getSizeX() * getSizeY()));
}
}
else if (getSizeX() * getSizeY() * getSizeC() == pixels) {
ms.sizeC = (int) (pixels / (getSizeX() * getSizeY()));
ms.sizeZ = 1;
}
else if ((getSizeX() / 2) * (getSizeY() / 2) * getSizeZ() == pixels) {
ms.sizeX /= 2;
ms.sizeY /= 2;
}
else if ((getSizeX() / 2) * (getSizeY() / 2) * getSizeC() *
getSizeZ() * getSizeT() == pixels)
{
ms.sizeX /= 2;
ms.sizeY /= 2;
}
else {
boolean validSizes = true;
try {
DataTools.safeMultiply32(getSizeX(), getSizeY());
}
catch (IllegalArgumentException e) {
validSizes = false;
}
if (getSizeX() == 0 || getSizeY() == 0 || !validSizes) {
ms.sizeX = sizeX[index] / 256;
ms.sizeY = sizeY[index] / 256;
}
long p = pixels / (getSizeX() * getSizeY());
if (pixels == p * getSizeX() * getSizeY()) {
if (p != getSizeC() * getSizeZ()) {
if (getSizeC() > 1 && core.get(i).sizeZ >= (p / (getSizeC() - 1)) &&
p >= getSizeC() - 1 && p > 2)
{
core.get(i).sizeC
core.get(i).sizeZ = (int) (p / getSizeC());
}
else if (p % getSizeC() != 0) {
core.get(i).sizeC = 1;
core.get(i).sizeZ = (int) p;
}
else if (ms.sizeZ == p + 1) {
ms.sizeC = 1;
ms.sizeZ = 1;
ms.sizeT = (int) p;
}
else if (getSizeC() > 1 &&
ms.sizeZ == (p / (getSizeC() - 1)) + 1)
{
ms.sizeC
ms.sizeZ = 1;
ms.sizeT = (int) (p / getSizeC());
}
else {
if (p > getSizeZ() && (p / getSizeZ() < getSizeZ() - 1)) {
ms.sizeT = (int) (p / getSizeC());
ms.sizeZ = 1;
}
else if (pixels % getSizeX() == 0 && pixels % getSizeY() == 0) {
while (getSizeX() * getSizeY() > plane) {
ms.sizeX /= 2;
ms.sizeY /= 2;
}
int originalX = getSizeX();
while (getSizeX() * getSizeY() < plane) {
ms.sizeX += originalX;
ms.sizeY = (int) (plane / getSizeX());
}
int newX = getSizeX() + originalX;
if (newX * (plane / newX) == plane && !flattened) {
ms.sizeX = newX;
ms.sizeY = (int) (plane / newX);
}
}
else if (!adjust) {
ms.sizeZ = (int) (p / getSizeC());
}
else if (isMontage) {
pixels /= getSizeC();
while (pixels != getSizeX() * getSizeY() ||
(getSizeY() / getSizeX() > 2))
{
ms.sizeX += 16;
ms.sizeY = (int) (pixels / getSizeX());
}
}
}
}
}
else if (isSpool) {
ms.sizeZ = (int) (p / getSizeC());
}
else if (p == 0) {
adjust = true;
if (getSizeC() > 1) {
if (getSizeC() == 3) {
ms.sizeC = 2;
}
else {
ms.sizeC = 1;
}
}
}
else {
if (ms.sizeC > 1 && p <= ms.sizeC) {
int z = getSizeZ();
ms.sizeZ = 1;
ms.sizeC = (int) p;
ms.sizeT = 1;
if (isMontage && pixels == getSizeX() * (pixels / getSizeX())) {
pixels /= getSizeC();
while (pixels != getSizeX() * getSizeY()) {
ms.sizeX -= 16;
ms.sizeY = (int) (pixels / getSizeX());
}
}
else if (!isMontage) {
ms.sizeZ = z;
adjust = true;
}
}
else if (isMontage) {
pixels /= (getSizeC() * getSizeZ());
int originalX = getSizeX();
int originalY = getSizeY();
boolean xGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() != 0 && (
pixels % (getSizeX() * getSizeY()) != 0 ||
((double) getSizeY() / getSizeX() > 2)))
{
ms.sizeX += originalX;
ms.sizeY = (int) (pixels / getSizeX());
if (!xGreater && getSizeX() >= getSizeY()) {
break;
}
}
if (getSizeX() * getSizeY() == 0) {
if (pixels != getSizeX() * getSizeY()) {
pixels *= getSizeC() * getSizeZ();
ms.sizeX = originalX;
ms.sizeY = originalY;
isMontage = false;
}
}
if (pixels % (originalX - (originalX / 4)) == 0) {
int newX = originalX - (originalX / 4);
int newY = (int) (pixels / newX);
if (newX * newY == pixels) {
ms.sizeX = newX;
ms.sizeY = newY;
isMontage = true;
adjust = false;
}
}
}
else if (p != getSizeZ() * getSizeC()) {
if (pixels % getSizeX() == 0 && pixels % getSizeY() == 0) {
while (getSizeX() * getSizeY() > plane) {
ms.sizeX /= 2;
ms.sizeY /= 2;
}
}
else {
ms.sizeZ = 1;
ms.sizeC = 1;
ms.sizeT = (int) p;
}
}
}
}
if (getSizeC() == 0) {
ms.sizeC = 1;
}
if (getSizeZ() == 0) {
ms.sizeZ = 1;
}
int div = getSizeC() * getSizeZ();
if (getSizeT() > 0) {
div *= getSizeT();
}
if (div > 1) {
plane = pixels / div;
}
long diff = 2 * (pixels - (getSizeX() * getSizeY() * div));
if ((pixelLengths.get(index).longValue() % 2) == 1) {
diff++;
}
if (Math.abs(diff) > plane / 2) {
diff = 0;
}
if (adjust && diff == 0) {
double ratio = (double) getSizeX() / getSizeY();
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) ms.sizeX /= 2;
else ms.sizeY /= 2;
x = !x;
}
if (getSizeX() * getSizeY() != plane) {
while (ratio - ((double) getSizeX() / getSizeY()) >= 0.01) {
boolean first = true;
while (first || getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
if (first) {
first = false;
}
ms.sizeX++;
ms.sizeY = (int) (plane / getSizeX());
}
}
}
}
int nPlanes = getSizeZ() * getSizeC();
ms.sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
ms.sizeT
}
if (getSizeT() == 0) ms.sizeT = 1;
if (cGreater && getSizeC() == 1 && getSizeZ() > 1) {
ms.sizeC = getSizeZ();
ms.sizeZ = 1;
}
ms.imageCount = nPlanes * getSizeT();
ms.pixelType = FormatTools.UINT16;
ms.dimensionOrder = nBlocks > 1 ? "XYZCT" : "XYZTC";
ms.indexed = false;
ms.falseColor = false;
ms.metadataComplete = true;
planeOffset[i] = new long[getImageCount()];
int nextImage = 0;
Integer pixelIndex = i;
long offset = pixelOffsets.get(pixelIndex);
int planeSize = getSizeX() * getSizeY() * 2;
if (diff < planeSize) {
offset += diff;
}
else {
offset += (diff % planeSize);
}
long length = pixelLengths.get(pixelIndex);
int planes = (int) (length / planeSize);
if (planes > ms.imageCount) {
planes = ms.imageCount;
}
for (int p=0; p<planes; p++, nextImage++) {
int[] zct = getZCTCoords(p);
if (flattened && zct[0] == 0 && zct[1] == 0) {
offset = pixelOffsets.get(nextOffsetIndex++);
if (zct[2] > 0 && planeOffset[i][nextImage - 1] % 2 != offset % 2 &&
(offset - planeOffset[i][nextImage - 1] > 3 * getSizeX() * getSizeY()) &&
diff == 0)
{
diff = 31;
}
if (diff < planeSize) {
offset += diff;
}
else {
offset += (diff % planeSize);
}
planeOffset[i][nextImage] = offset;
}
else if (flattened && zct[0] == 0) {
int idx = getIndex(0, 0, zct[2]);
planeOffset[i][nextImage] = planeOffset[i][idx] + zct[1] * planeSize;
}
else if (flattened) {
planeOffset[i][nextImage] = planeOffset[i][nextImage - 1] + planeSize;
}
else if (nextImage < planeOffset[i].length) {
planeOffset[i][nextImage] = offset + p * planeSize;
}
}
}
setSeries(0);
if (pixelSizeZ.size() > 0) {
int seriesIndex = 0;
for (int q=0; q<getSeriesCount(); q++) {
CoreMetadata msq = core.get(q);
int inc = msq.sizeC * msq.sizeT;
if (seriesIndex + inc > pixelSizeZ.size()) {
int z = msq.sizeT;
msq.sizeT = msq.sizeZ;
msq.sizeZ = z;
inc = msq.sizeC * msq.sizeT;
}
seriesIndex += inc;
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
for (int i=0; i<getSeriesCount(); i++) {
if (imageDescriptions.containsKey(i)) {
store.setImageDescription(imageDescriptions.get(i), i);
}
else {
store.setImageDescription("", i);
}
}
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
for (int i=0; i<getSeriesCount(); i++) {
store.setImageInstrumentRef(instrumentID, i);
}
int index = 0;
// populate Objective data
int objectiveIndex = 0;
for (int i=0; i<getSeriesCount(); i++) {
String objective = objectives.get(i);
if (objective != null) {
store.setObjectiveModel(objective, 0, objectiveIndex);
store.setObjectiveCorrection(
getCorrection("Other"), 0, objectiveIndex);
store.setObjectiveImmersion(getImmersion("Other"), 0, objectiveIndex);
if (magnifications != null && magnifications.get(i) > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnifications.get(i)), 0, objectiveIndex);
}
// link Objective to Image
String objectiveID =
MetadataTools.createLSID("Objective", 0, objectiveIndex);
store.setObjectiveID(objectiveID, 0, objectiveIndex);
if (i < getSeriesCount()) {
store.setObjectiveSettingsID(objectiveID, i);
}
objectiveIndex++;
}
}
// populate Dimensions data
int exposureIndex = exposureTimes.size() - channelNames.size();
if (exposureIndex >= 1) {
exposureIndex++;
}
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
if (pixelSize.get(i) != null) {
Double size = new Double(pixelSize.get(i));
if (size > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(size), i);
store.setPixelsPhysicalSizeY(new PositiveFloat(size), i);
}
else {
LOGGER.warn("Expected positive value for PhysicalSize; got {}",
size);
}
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core.get(q).sizeC * core.get(q).sizeT;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
if (isGreaterThanEpsilon(pixelSizeZ.get(idx))) {
store.setPixelsPhysicalSizeZ(
new PositiveFloat(pixelSizeZ.get(idx)), i);
}
else {
LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}",
pixelSizeZ.get(idx));
}
}
for (int plane=0; plane<getImageCount(); plane++) {
int c = getZCTCoords(plane)[1];
if (exposureIndex + c < exposureTimes.size() &&
exposureIndex + c >= 0)
{
store.setPlaneExposureTime(
new Double(exposureTimes.get(exposureIndex + c)), i, plane);
}
}
exposureIndex += getSizeC();
}
setSeries(0);
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
// -- Helper methods --
private boolean withinPixels(long offset) {
for (int i=0; i<pixelOffsets.size(); i++) {
long pixelOffset = pixelOffsets.get(i).longValue();
long pixelLength = pixelLengths.get(i).longValue();
if (offset >= pixelOffset && offset < (pixelOffset + pixelLength)) {
return true;
}
}
return false;
}
private boolean isGreaterThanEpsilon(double v) {
return v - Constants.EPSILON > 0;
}
}
|
package ca.mcgill.mcb.pcingola.bigDataScript;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.Tree;
import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptLexer;
import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptParser;
import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptParser.IncludeFileContext;
import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompileErrorStrategy;
import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompilerMessage.MessageType;
import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompilerMessages;
import ca.mcgill.mcb.pcingola.bigDataScript.compile.TypeCheckedNodes;
import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioner;
import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioners;
import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioners.ExecutionerType;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.BigDataScriptNodeFactory;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.ExpressionTask;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.FunctionDeclaration;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.Literal;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralBool;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralInt;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralListString;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralReal;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralString;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.ProgramUnit;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.Statement;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.StatementInclude;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.Type;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.TypeList;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.VarDeclaration;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.VariableInit;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.nativeFunctions.NativeLibraryFunctions;
import ca.mcgill.mcb.pcingola.bigDataScript.lang.nativeMethods.NativeLibraryString;
import ca.mcgill.mcb.pcingola.bigDataScript.run.BigDataScriptThread;
import ca.mcgill.mcb.pcingola.bigDataScript.run.RunState;
import ca.mcgill.mcb.pcingola.bigDataScript.scope.Scope;
import ca.mcgill.mcb.pcingola.bigDataScript.scope.ScopeSymbol;
import ca.mcgill.mcb.pcingola.bigDataScript.serialize.BigDataScriptSerializer;
import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr;
import ca.mcgill.mcb.pcingola.bigDataScript.util.Timer;
/**
* BigDataScript command line parser
*
* @author pcingola
*/
public class BigDataScript {
enum BigDataScriptAction {
RUN, RUN_CHECKPOINT, INFO_CHECKPOINT, TEST
}
public static final String SOFTWARE_NAME = BigDataScript.class.getSimpleName();
public static final String BUILD = "2014-07-25";
public static final String REVISION = "d";
public static final String VERSION_MAJOR = "0.98";
public static final String VERSION_SHORT = VERSION_MAJOR + REVISION;
public static final String VERSION = SOFTWARE_NAME + " " + VERSION_SHORT + " (build " + BUILD + "), by " + Pcingola.BY;
boolean verbose;
boolean debug;
boolean log;
boolean dryRun;
boolean noRmOnExit;
boolean createReport = true;
int taskFailCount = 0;
String configFile = Config.DEFAULT_CONFIG_FILE; // Config file
String chekcpointRestoreFile; // Restore file
String programFileName; // Program file name
String pidFile; // File to store PIDs
String system; // System type
String queue; // Queue name
BigDataScriptAction bigDataScriptAction;
Config config;
ProgramUnit programUnit; // Program (parsed nodes)
BigDataScriptThread bigDataScriptThread;
ArrayList<String> programArgs; // Command line arguments for BigDataScript program
/**
* Create an AST from a program (using ANTLR lexer & parser)
* Returns null if error
* Use 'alreadyIncluded' to keep track of from 'include' statements
*/
public static ParseTree createAst(File file, boolean debug, Set<File> alreadyIncluded) {
alreadyIncluded.add(Gpr.getCanonicalFile(file));
String fileName = file.toString();
String filePath = fileName;
BigDataScriptLexer lexer = null;
BigDataScriptParser parser = null;
try {
filePath = file.getCanonicalPath();
// Input stream
if (!Gpr.canRead(filePath)) {
CompilerMessages.get().addError("Can't read file '" + filePath + "'");
return null;
}
// Create a CharStream that reads from standard input
ANTLRFileStream input = new ANTLRFileStream(fileName);
// Create a lexer that feeds off of input CharStream
lexer = new BigDataScriptLexer(input) {
@Override
public void recover(LexerNoViableAltException e) {
throw new RuntimeException(e); // Bail out
}
};
CommonTokenStream tokens = new CommonTokenStream(lexer);
parser = new BigDataScriptParser(tokens);
parser.setErrorHandler(new CompileErrorStrategy()); // bail out with exception if errors in parser
ParseTree tree = parser.programUnit(); // Begin parsing at main rule
// Error loading file?
if (tree == null) {
System.err.println("Can't parse file '" + filePath + "'");
return null;
}
// Show main nodes
if (debug) {
Timer.showStdErr("AST:");
for (int childNum = 0; childNum < tree.getChildCount(); childNum++) {
Tree child = tree.getChild(childNum);
System.err.println("\t\tChild " + childNum + ":\t" + child + "\tTree:'" + child.toStringTree() + "'");
}
}
// Included files
boolean resolveIncludePending = true;
while (resolveIncludePending)
resolveIncludePending = resolveIncludes(tree, debug, alreadyIncluded);
return tree;
} catch (Exception e) {
String msg = e.getMessage();
CompilerMessages.get().addError("Could not compile " + filePath
+ (msg != null ? " :" + e.getMessage() : "")
);
return null;
}
}
/**
* Main
*/
public static void main(String[] args) {
// Create BigDataScript object and run it
BigDataScript bigDataScript = new BigDataScript(args);
int exitValue = bigDataScript.run();
System.exit(exitValue);
}
/**
* Resolve include statements
*/
private static boolean resolveIncludes(ParseTree tree, boolean debug, Set<File> alreadyIncluded) {
boolean changed = false;
if (tree instanceof IncludeFileContext) {
// Parent file: The one that is including the other file
File parentFile = new File(((IncludeFileContext) tree).getStart().getInputStream().getSourceName());
// Included file name
String includedFilename = StatementInclude.includedFileName(tree.getChild(1).getText());
// Find file (look into all include paths)
File includedFile = StatementInclude.includedFile(includedFilename, parentFile);
if (includedFile == null) {
CompilerMessages.get().add(tree, parentFile, "\n\tIncluded file not found: '" + includedFilename + "'\n\tSearch path: " + Config.get().getIncludePath(), MessageType.ERROR);
return false;
}
// Already included? don't bother
if (alreadyIncluded.contains(Gpr.getCanonicalFile(includedFile))) return false;
if (!includedFile.canRead()) {
CompilerMessages.get().add(tree, parentFile, "\n\tCannot read included file: '" + includedFilename + "'", MessageType.ERROR);
return false;
}
// Parse
ParseTree treeinc = createAst(includedFile, debug, alreadyIncluded);
if (treeinc == null) {
CompilerMessages.get().add(tree, parentFile, "\n\tFatal error including file '" + includedFilename + "'", MessageType.ERROR);
return false;
}
// Is a child always a RuleContext?
for (int i = 0; i < treeinc.getChildCount(); i++) {
((IncludeFileContext) tree).addChild((RuleContext) treeinc.getChild(i));
}
} else {
for (int i = 0; i < tree.getChildCount(); i++)
changed |= resolveIncludes(tree.getChild(i), debug, alreadyIncluded);
}
return changed;
}
public BigDataScript(String args[]) {
parse(args);
initialize();
}
/**
* Compile program
*/
public boolean compile() {
if (debug) log("Loading file: '" + programFileName + "'");
// Convert to AST
if (debug) log("Creating AST.");
CompilerMessages.reset();
ParseTree tree = null;
try {
tree = createAst();
} catch (Exception e) {
System.err.println("Fatal error cannot continue - " + e.getMessage());
return false;
}
// No tree produced? Fatal error
if (tree == null) {
if (CompilerMessages.get().isEmpty()) {
CompilerMessages.get().addError("Fatal error: Could not compile");
}
return false;
}
// Any error? Do not continue
if (!CompilerMessages.get().isEmpty()) return false;
// Convert to BigDataScriptNodes
if (debug) log("Creating BigDataScript tree.");
CompilerMessages.reset();
programUnit = (ProgramUnit) BigDataScriptNodeFactory.get().factory(null, tree); // Transform AST to BigDataScript tree
if (debug) log("AST:\n" + programUnit.toString());
// Any error messages?
if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get());
if (CompilerMessages.get().hasErrors()) return false;
// Type-checking
if (debug) log("Type checking.");
CompilerMessages.reset();
Scope programScope = new Scope();
programUnit.typeChecking(programScope, CompilerMessages.get());
// Any error messages?
if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get());
if (CompilerMessages.get().hasErrors()) return false;
// Free some memory by reseting structure we won't use any more
TypeCheckedNodes.get().reset();
return true;
}
/**
* Create an AST from a program file
* @return A parsed tree
*/
ParseTree createAst() {
File file = new File(programFileName);
return createAst(file, debug, new HashSet<File>());
}
public BigDataScriptThread getBigDataScriptThread() {
return bigDataScriptThread;
}
public CompilerMessages getCompilerMessages() {
return CompilerMessages.get();
}
public ProgramUnit getProgramUnit() {
return programUnit;
}
/**
* Show information from a checkpoint file
*/
int infoCheckpoint() {
// Load checkpoint file
BigDataScriptSerializer bdsSerializer = new BigDataScriptSerializer(chekcpointRestoreFile, config);
List<BigDataScriptThread> bdsThreads = bdsSerializer.load();
for (BigDataScriptThread bdsThread : bdsThreads)
bdsThread.print();
return 0;
}
/**
* Get default settings
*/
void initDefaults() {
log = true;
dryRun = false;
}
/**
* Initialize before running or type-checking
*/
void initialize() {
Type.reset();
// Reset node factory
BigDataScriptNodeFactory.reset();
// Global scope
initilaizeGlobalScope();
// Libraries
initilaizeLibraries();
}
/**
* Set command line arguments as global variables
*
* How it works: - Program is executes as something like:
*
* java -jar BigDataScript.jar [options] programFile.bds [programOptions]
*
* - Any command line argument AFTER "programFile.bds" is considered a
* command line argument for the BigDataScript program. E.g.
*
* java -jar BigDataScript.jar -v program.bds -file myFile.txt -verbose -num
* 7
*
* So our program "program.bds" has command line options: -file myFile.txt
* -verbose -num 7 (notice that "-v" is a command line option for
* loudScript.jar and not for "program.bds")
*
* - We look for variables in ProgramUnit that match the name of these
* command line arguments
*
* - Then we add those values to the variable initialization. Thus
* overriding any initialization values provided in the program. E.g.
*
* Our program has the following variable declarations: string file =
* "default_file.txt" int num = 3 bool verbose = false
*
* We execute the program: java -jar BigDataScript.jar -v program.bds -file
* myFile.txt -verbose -num 7
*
* The variable declarations are replaced as follows: string file =
* "myFile.txt" int num = 7 bool verbose = true
*
* - Note: Only primitive types are supported (i.e.: string, bool, int &
* real)
*
* - Note: Unmatched variables names will be silently ignored (same for
* variables that match, but are non-primitive)
*
* - Note: If a variable is matched, is primitive, but cannot be converted.
* An error is thrown. E.g.: Program: int num = 1
*
* Command line: java -jar BigDataScript.jar program.bds -num "hello" <-
* This is an error because 'num' is an int
*
* - Note: Unprocessed arguments will be available to the program as an
* 'args' list
*/
void initializeArgs() {
// Set program arguments as global variables
for (int argNum = 0; argNum < programArgs.size(); argNum++) {
String arg = programArgs.get(argNum);
// Parse '-OPT' option
if (arg.startsWith("-")) {
// Get variable name and value
String varName = arg.substring(1);
// Find all variable declarations that match this command line argument
for (Statement s : programUnit.getStatements()) {
// Is it a variable declaration?
if (s instanceof VarDeclaration) {
VarDeclaration varDecl = (VarDeclaration) s;
Type varType = varDecl.getType();
// Is is a primitive variable or a primitive list?
if (varType.isPrimitiveType() || varType.isList()) {
// Find an initialization that matches the command line argument
for (VariableInit varInit : varDecl.getVarInit())
if (varInit.getVarName().equals(varName)) { // Name matches?
int argNumOri = argNum;
boolean useVal = false;
if (varType.isList()) {
// Create a list of arguments and use them to initialize the variable (list)
ArrayList<String> vals = new ArrayList<String>();
for (int i = argNum + 1; i < programArgs.size(); i++)
if (programArgs.get(i).startsWith("-")) break;
else vals.add(programArgs.get(i));
useVal = initializeArgs(varType, varInit, vals); // Found variable, try to replace or add LITERAL to this VarInit
} else if (varType.isBool()) {
String valStr = "true";
// Booleans may not have a value (just '-varName' sets them to 'true')
if (programArgs.size() > (argNum + 1)) {
// Is the next argument 'true' or 'false'? => Set argument
String boolVal = programArgs.get(argNum + 1);
if (valStr.equalsIgnoreCase("true") || valStr.equalsIgnoreCase("false")) valStr = boolVal;
}
initializeArgs(varType, varInit, valStr);
} else {
String val = (argNum < programArgs.size() ? programArgs.get(++argNum) : ""); // Get one argument and use it to initialize the variable
useVal = initializeArgs(varType, varInit, val); // Found variable, try to replace or add LITERAL to this VarInit
}
if (!useVal) argNum = argNumOri; // We did not use the arguments
}
}
}
}
}
}
// Make all unprocessed arguments available for the program (in 'args' list)
Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_ARGS_LIST, TypeList.get(Type.STRING), programArgs));
// Initialize program name
String programPath = programUnit.getFileName();
String progName = Gpr.baseName(programPath);
Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, progName));
Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_PATH, Type.STRING, programPath));
}
/**
* Add or replace initialization statement in this VarInit
*
* Note: We create a Literal node (of the appropriate type) and add it to
* "varInit.expression"
*
* @param varType
* : Variable type
* @param varInit
* : Variable initialization
* @param vals
* : Value to assign
*/
boolean initializeArgs(Type varType, VariableInit varInit, ArrayList<String> vals) {
boolean usedVal = true;
try {
Literal literal = null;
if (varType.isList(Type.STRING)) {
// Create literal
LiteralListString lit = new LiteralListString(varInit, null);
literal = lit;
lit.setValue(vals); // Set literal value
} else throw new RuntimeException("Cannot convert command line argument to variable type '" + varType + "'");
// Set varInit to literal
varInit.setExpression(literal);
} catch (Exception e) {
// Error parsing 'val'?
throw new RuntimeException("Cannot convert argument '" + vals + "' to type " + varType);
}
return usedVal;
}
/**
* Add or replace initialization statement in this VarInit
*
* Note: We create a Literal node (of the appropriate type) and add it to
* "varInit.expression"
*
* @param varType
* : Variable type
* @param varInit
* : Variable initialization
* @param valStr
* : Value to assign
*/
boolean initializeArgs(Type varType, VariableInit varInit, String valStr) {
boolean usedVal = true;
try {
Literal literal = null;
// Create a different literal for each primitive type
if (varType.isBool()) {
// Create literal
LiteralBool lit = new LiteralBool(varInit, null);
literal = lit;
// Set literal value
boolean valBool = true; // Default value is 'true'
if (valStr != null) {
// Parse boolean
valStr = valStr.toLowerCase();
if (valStr.equals("true") || valStr.equals("t") || valStr.equals("1")) valBool = true;
else if (valStr.equals("false") || valStr.equals("f") || valStr.equals("0")) valBool = false;
else usedVal = false; // Not any valid value? => This
// argument is not used
}
lit.setValue(valBool);
} else if (varType.isInt()) {
// Create literal
LiteralInt lit = new LiteralInt(varInit, null);
literal = lit;
// Set literal value
long valInt = Long.parseLong(valStr);
lit.setValue(valInt);
} else if (varType.isReal()) {
// Create literal
LiteralReal lit = new LiteralReal(varInit, null);
literal = lit;
// Set literal value
double valReal = Double.parseDouble(valStr);
lit.setValue(valReal);
} else if (varType.isString()) {
// Create literal
LiteralString lit = new LiteralString(varInit, null);
literal = lit;
// Set literal value
if (valStr == null) valStr = ""; // We should never have 'null' values
lit.setValue(valStr);
} else throw new RuntimeException("Cannot convert command line argument to variable type '" + varType + "'");
// Set varInit to literal
varInit.setExpression(literal);
} catch (Exception e) {
// Error parsing 'val'?
throw new RuntimeException("Cannot convert argument '" + valStr + "' to type " + varType);
}
return usedVal;
}
/**
* Add symbols to global scope
*/
void initilaizeGlobalScope() {
if (debug) log("Initialize global scope.");
// Reset Global scope
Scope.resetGlobalScope();
Scope globalScope = Scope.getGlobalScope();
// Add global symbols
globalScope.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, ""));
globalScope.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_PATH, Type.STRING, ""));
// Command line parameters override defaults
if (system == null) system = ExecutionerType.LOCAL.toString().toLowerCase();
if (queue == null) queue = "";
// Task related variables: Default values
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_SYSTEM, Type.STRING, system)); // System type: "local", "ssh", "cluster", "aws", etc.
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_CPUS, Type.INT, 1L)); // Default number of cpus
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_MEM, Type.INT, -1L)); // Default amount of memory (unrestricted)
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_QUEUE, Type.STRING, queue)); // Default queue: none
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_NODE, Type.STRING, "")); // Default node: none
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_CAN_FAIL, Type.BOOL, false)); // Task fail triggers checkpoint & exit (a task cannot fail)
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_RETRY, Type.INT, (long) taskFailCount)); // Task fail can be re-tried (re-run) N times before considering failed.
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_TIMEOUT, Type.INT, 1L * 24 * 60 * 60)); // Task default timeout(1 day)
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_WALL_TIMEOUT, Type.INT, 1L * 24 * 60 * 60)); // Task default wall-timeout(1 day)
// Number of local CPUs
// Kilo, Mega, Giga, Tera, Peta.
LinkedList<ScopeSymbol> constants = new LinkedList<ScopeSymbol>();
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, "")); // Program name, now is empty, but it is filled later
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_LOCAL_CPUS, Type.INT, (long) Gpr.NUM_CORES));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_K, Type.INT, 1024L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_M, Type.INT, 1024L * 1024L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_G, Type.INT, 1024L * 1024L * 1024L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_T, Type.INT, 1024L * 1024L * 1024L * 1024L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_P, Type.INT, 1024L * 1024L * 1024L * 1024L * 1024L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_MINUTE, Type.INT, 60L));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_HOUR, Type.INT, (long) (60 * 60)));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_DAY, Type.INT, (long) (24 * 60 * 60)));
constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_WEEK, Type.INT, (long) (7 * 24 * 60 * 60)));
// Add all constants
for (ScopeSymbol ss : constants) {
ss.setConstant(true);
globalScope.add(ss);
}
// Set "physical" path
String path;
try {
path = new File(".").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException("Cannot get cannonical path for current dir");
}
globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_PHYSICAL_PATH, Type.STRING, path));
// Set all environment variables
Map<String, String> envMap = System.getenv();
for (String varName : envMap.keySet()) {
String varVal = envMap.get(varName);
globalScope.add(new ScopeSymbol(varName, Type.STRING, varVal));
}
// Command line arguments (default: empty list)
// This is properly set in 'initializeArgs()' method, but
// we have to set something now, otherwise we'll get a "variable
// not found" error at compiler time, if the program attempts
// to use 'args'.
Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_ARGS_LIST, TypeList.get(Type.STRING), new ArrayList<String>()));
}
/**
* Initialize standard libraries
*/
void initilaizeLibraries() {
if (debug) log("Initialize standard libraries.");
// Native functions
NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions();
if (debug) log("Native library:\n" + nativeLibraryFunctions);
// Native library: String
NativeLibraryString nativeLibraryString = new NativeLibraryString();
if (debug) log("Native library:\n" + nativeLibraryString);
}
void log(String msg) {
Timer.showStdErr(getClass().getSimpleName() + ": " + msg);
}
/**
* Parse command line arguments
*
* @param args
*/
public void parse(String[] args) {
// Nothing? Show command line options
if (args.length <= 0) usage(null);
programArgs = new ArrayList<String>();
bigDataScriptAction = BigDataScriptAction.RUN;
for (int i = 0; i < args.length; i++) {
if (programFileName != null) programArgs.add(args[i]); // Everything after 'programFileName' is an command line argument for the BigDataScript program
else if (args[i].equals("-c") || args[i].equalsIgnoreCase("-config")) {
// Checkpoint restore
if ((i + 1) < args.length) configFile = args[++i];
else usage("Option '-c' without restore file argument");
} else if (args[i].equals("-d") || args[i].equalsIgnoreCase("-debug")) debug = verbose = true; // Debug implies verbose
else if (args[i].equals("-l") || args[i].equalsIgnoreCase("-log")) log = true;
else if (args[i].equals("-h") || args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("--help")) usage(null);
else if (args[i].equalsIgnoreCase("-dryRun")) {
dryRun = true;
noRmOnExit = true; // Not running, so don't delete files
createReport = false;
} else if (args[i].equalsIgnoreCase("-noRmOnExit")) noRmOnExit = true;
else if (args[i].equalsIgnoreCase("-noReport")) createReport = false;
else if (args[i].equals("-i") || args[i].equalsIgnoreCase("-info")) {
// Checkpoint info
if ((i + 1) < args.length) chekcpointRestoreFile = args[++i];
else usage("Option '-i' without checkpoint file argument");
bigDataScriptAction = BigDataScriptAction.INFO_CHECKPOINT;
} else if (args[i].equals("-pid")) {
// PID file
if ((i + 1) < args.length) pidFile = args[++i];
else usage("Option '-pid' without file argument");
} else if (args[i].equals("-q") || args[i].equalsIgnoreCase("-queue")) {
// Queue name
if ((i + 1) < args.length) queue = args[++i];
else usage("Option '-queue' without file argument");
} else if (args[i].equals("-r") || args[i].equalsIgnoreCase("-restore")) {
// Checkpoint restore
if ((i + 1) < args.length) chekcpointRestoreFile = args[++i];
else usage("Option '-r' without checkpoint file argument");
bigDataScriptAction = BigDataScriptAction.RUN_CHECKPOINT;
} else if (args[i].equals("-s") || args[i].equalsIgnoreCase("-system")) {
// System type
if ((i + 1) < args.length) system = args[++i];
else usage("Option '-system' without file argument");
} else if (args[i].equals("-t") || args[i].equalsIgnoreCase("-test")) {
bigDataScriptAction = BigDataScriptAction.TEST;
} else if (args[i].equals("-y") || args[i].equalsIgnoreCase("-retry")) {
// Number of retries
if ((i + 1) < args.length) taskFailCount = Gpr.parseIntSafe(args[++i]);
else usage("Option '-t' without number argument");
} else if (args[i].equals("-v") || args[i].equalsIgnoreCase("-verbose")) verbose = true;
else if (programFileName == null) programFileName = args[i]; // Get program file name
}
// Sanity checks
if ((programFileName == null) && (chekcpointRestoreFile == null)) usage("Missing program file name.");
}
/**
* Run script
*/
public int run() {
// Startup message
if (verbose) Timer.showStdErr(VERSION);
// Config
config = new Config(configFile);
config.setVerbose(verbose);
config.setDebug(debug);
config.setLog(log);
config.setDryRun(dryRun);
config.setTaskFailCount(taskFailCount);
config.setNoRmOnExit(noRmOnExit);
config.setCreateReport(createReport);
if (pidFile == null) {
if (programFileName != null) pidFile = programFileName + ".pid";
else pidFile = chekcpointRestoreFile + ".pid";
}
config.setPidFile(pidFile);
Executioners executioners = Executioners.getInstance(config); // Initialize executioners
// Run
int exitValue = 0;
switch (bigDataScriptAction) {
case RUN_CHECKPOINT:
exitValue = runCheckpoint();
break;
case INFO_CHECKPOINT:
exitValue = infoCheckpoint();
break;
case TEST:
exitValue = runTests();
break;
default:
exitValue = runCompile(); // Compile & run
}
if (verbose) Timer.showStdErr("Finished running. Exit code: " + exitValue);
// Kill all executioners
for (Executioner executioner : executioners.getAll())
executioner.kill();
config.kill(); // Kill 'tail' and 'monitor' threads
return exitValue;
}
/**
* Restore from checkpoint and run
*/
int runCheckpoint() {
// Load checkpoint file
BigDataScriptSerializer bdsSerializer = new BigDataScriptSerializer(chekcpointRestoreFile, config);
List<BigDataScriptThread> bdsThreads = bdsSerializer.load();
// Set main thread's programUnit running scope (mostly for debugging and test cases)
// ProgramUnit's scope it the one before 'global'
BigDataScriptThread mainThread = bdsThreads.get(0);
programUnit = mainThread.getProgramUnit();
for (Scope scope = mainThread.getScope(); (scope != null) && (scope.getParent() != Scope.getGlobalScope()); scope = scope.getParent())
programUnit.setRunScope(scope);
// Set state and recover tasks
for (BigDataScriptThread bdsThread : bdsThreads) {
bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery
bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks
}
// All set, run main thread
return runThread(mainThread);
}
/**
* Compile and run
*/
int runCompile() {
// Compile, abort on errors
if (verbose) Timer.showStdErr("Parsing");
if (!compile()) {
// Show errors and warnings, if any
if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get());
return 1;
}
if (verbose) Timer.showStdErr("Initializing");
initializeArgs();
// Run the program
BigDataScriptThread bdsThread = new BigDataScriptThread(programUnit, config);
if (verbose) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId());
if (verbose) Timer.showStdErr("Running");
int exitCode = runThread(bdsThread);
return exitCode;
}
/**
* Compile and run
*/
int runTests() {
// Compile, abort on errors
if (verbose) Timer.showStdErr("Parsing");
if (!compile()) {
// Show errors and warnings, if any
if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get());
return 1;
}
if (verbose) Timer.showStdErr("Initializing");
initializeArgs();
// Run the program
BigDataScriptThread bdsThread = new BigDataScriptThread(programUnit, config);
if (verbose) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId());
if (verbose) Timer.showStdErr("Running tests");
ProgramUnit pu = bdsThread.getProgramUnit();
List<FunctionDeclaration> testFuncs = pu.testsFunctions();
// For each test function, create a thread that executes the function's body
int exitCode = 0;
int testOk = 0, testError = 0;
for (FunctionDeclaration testFunc : testFuncs) {
System.out.println("");
BigDataScriptThread bdsTestThread = new BigDataScriptThread(testFunc.getStatement(), bdsThread); // Note: We execute the function's body (not the function declaration)
int exitValTest = runThread(bdsTestThread);
// Show test result
if (exitValTest == 0) {
Timer.show("Test OK : " + testFunc.getFunctionName());
testOk++;
} else {
Timer.show("Test ERROR : " + testFunc.getFunctionName());
exitCode = 1;
testError++;
}
}
// Show results
System.out.println("");
Timer.show("Totals"
+ "\n OK : " + testOk
+ "\n ERROR : " + testError
);
return exitCode;
}
/**
* Run a thread
*/
int runThread(BigDataScriptThread bdsThread) {
bigDataScriptThread = bdsThread;
bdsThread.start();
try {
bdsThread.join();
} catch (InterruptedException e) {
// Nothing to do?
// May be checkpoint?
return 1;
}
// OK, we are done
return bdsThread.getExitValue();
}
void usage(String err) {
if (err != null) System.err.println("Error: " + err);
System.out.println(VERSION + "\n");
System.err.println("Usage: " + BigDataScript.class.getSimpleName() + " [options] file.bds");
System.err.println("\nAvailable options: ");
System.err.println(" [-c | -config ] bds.config : Config file. Default : " + configFile);
System.err.println(" [-d | -debug ] : Debug mode.");
System.err.println(" -dryRun : Do not run any task, just show what would be run.");
System.err.println(" [-i | -info ] checkpoint.chp : Show state information in checkpoint file.");
System.err.println(" [-l | -log ] : Log all tasks (do not delete tmp files).");
System.err.println(" -noReport : Do not create report.");
System.err.println(" -noRmOnExit : Do not remove files marked for deletion on exit (rmOnExit).");
System.err.println(" [-q | -queue ] queueName : Set default queue name.");
System.err.println(" [-r | -restore] checkpoint.chp : Restore state from checkpoint file.");
System.err.println(" [-s | -system ] type : Set system type.");
System.err.println(" [-t | -test ] : Perform testing (run all test* functions).");
System.err.println(" [-v | -verbose] : Be verbose.");
System.err.println(" [-y | -retry ] num : Number of times to retry a failing tasks.");
System.err.println(" -pid <file> : Write local processes PIDs to 'file'");
if (err != null) System.exit(1);
System.exit(0);
}
}
|
package com.googlecode.jmxtrans.model.output;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.util.BaseOutputWriter;
import com.googlecode.jmxtrans.util.JmxUtils;
import com.googlecode.jmxtrans.util.ValidationException;
import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetricSlope;
import info.ganglia.gmetric4j.gmetric.GMetricType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
public class GangliaWriter extends BaseOutputWriter {
private static final Pattern PATTERN_HOST_IP = Pattern.compile("(.+):([^:]+)$");
/** Logger. */
private static final Logger log = LoggerFactory.getLogger(GangliaWriter.class);
/* Settings configuration keys. */
public static final String ADDRESSING_MODE = "addressingMode";
public static final String TTL = "ttl";
public static final String V31 = "v3.1";
public static final String UNITS = "units";
public static final String SLOPE = "slope";
public static final String TMAX = "tmax";
public static final String DMAX = "dmax";
public static final String GROUP_NAME = "groupName";
public static final String SPOOF_NAME = "spoofedHostName";
/* Settings default values. */
public static final String DEFAULT_HOST = null;
public static final int DEFAULT_PORT = 8649;
public static final UDPAddressingMode DEFAULT_ADDRESSING_MODE = UDPAddressingMode.UNICAST;
public static final int DEFAULT_TTL = 5;
public static final boolean DEFAULT_V31 = true;
public static final String DEFAULT_UNITS = "";
public static final GMetricSlope DEFAULT_SLOPE = GMetricSlope.BOTH;
public static final int DEFAULT_DMAX = 0;
public static final int DEFAULT_TMAX = 60;
public static final String DEFAULT_GROUP_NAME = "JMX";
/* Settings run-time values. */
protected String host = DEFAULT_HOST;
protected int port = DEFAULT_PORT;
protected UDPAddressingMode addressingMode = DEFAULT_ADDRESSING_MODE;
protected int ttl = DEFAULT_TTL;
protected boolean v31 = DEFAULT_V31;
protected String units = DEFAULT_UNITS;
protected GMetricSlope slope = DEFAULT_SLOPE;
protected int tmax = DEFAULT_TMAX;
protected int dmax = DEFAULT_DMAX;
protected String groupName = DEFAULT_GROUP_NAME;
protected String spoofedHostName = null;
/** Parse and validate settings. */
@Override
public void validateSetup(Query query) throws ValidationException {
// Parse and validate host setting
host = getStringSetting(HOST, DEFAULT_HOST);
if (host == null) throw new ValidationException("Host can't be null", query);
// Parse and validate port setting
port = getIntegerSetting(PORT, DEFAULT_PORT);
// Parse and validate addressing mode setting
try {
addressingMode = UDPAddressingMode.valueOf(getStringSetting(ADDRESSING_MODE, ""));
} catch (IllegalArgumentException iae) {
try {
addressingMode = UDPAddressingMode.getModeForAddress(host);
} catch (UnknownHostException uhe) {
addressingMode = DEFAULT_ADDRESSING_MODE;
} catch (IOException ioe) {
addressingMode = DEFAULT_ADDRESSING_MODE;
}
}
// Parse and validate TTL setting
ttl = getIntegerSetting(TTL, DEFAULT_TTL);
// Parse and validate protocol version setting
v31 = getBooleanSetting(V31, DEFAULT_V31);
// Parse and validate unit setting
units = getStringSetting(UNITS, DEFAULT_UNITS);
// Parse and validate slope setting
slope = GMetricSlope.valueOf(getStringSetting(SLOPE, DEFAULT_SLOPE.name()));
// Parse and validate tmax setting
tmax = getIntegerSetting(TMAX, DEFAULT_TMAX);
// Parse and validate dmax setting
dmax = getIntegerSetting(DMAX, DEFAULT_DMAX);
// Parse and validate group name setting
groupName = getStringSetting(GROUP_NAME, DEFAULT_GROUP_NAME);
// Determine the spoofed hostname
spoofedHostName = getSpoofedHostName(query.getServer().getHost(), query.getServer().getAlias());
log.debug("Validated Ganglia metric [" +
HOST + ": " + host + ", " +
PORT + ": " + port + ", " +
ADDRESSING_MODE + ": " + addressingMode + ", " +
TTL + ": " + ttl + ", " +
V31 + ": " + v31 + ", " +
UNITS + ": '" + units + "', " +
SLOPE + ": " + slope + ", " +
TMAX + ": " + tmax + ", " +
DMAX + ": " + dmax + ", " +
SPOOF_NAME + ": " + spoofedHostName + ", " +
GROUP_NAME + ": '" + groupName + "']");
}
/** Send query result values to Ganglia. */
@Override
public void doWrite(Query query) throws Exception {
for (final Result result : query.getResults()) {
if (result.getValues() != null) {
for (final Map.Entry<String, Object> resultValue : result.getValues().entrySet()) {
final String name = JmxUtils.getKeyString2(query, result, resultValue, getTypeNames(), null);
final String value = resultValue.getValue().toString();
GMetricType dataType = getType(resultValue.getValue());
log.debug("Sending Ganglia metric {}={} [type={}]", new Object[]{name, value, dataType});
new GMetric(
host,
port,
addressingMode,
ttl,
v31,
null,
spoofedHostName
).announce(
name,
value,
dataType,
units,
slope,
tmax,
dmax,
groupName
);
}
}
}
}
/**
* Determines the spoofed host name to be used when emitting metrics to a
* gmond process. Spoofed host names are of the form IP:hostname.
*
* @param host
* the host of the gmond (ganglia monitor) to which we are
* connecting, not null
* @param alias
* the custom alias supplied, may be null
* @return the host name to use when emitting metrics, in the form of
* IP:hostname
*/
public static String getSpoofedHostName(String host, String alias) {
// Determine the host name to use as the spoofed host name, this should
// be of the format IP:hostname
String spoofed = host;
if (StringUtils.isNotEmpty(alias)) {
// If the alias was supplied in the appropriate format, use it
// directly
Matcher hostIpMatcher = PATTERN_HOST_IP.matcher(alias);
if (hostIpMatcher.matches())
return alias;
// Otherwise, use the alias as the host
spoofed = alias;
}
// Attempt to find the IP of the given host (this may be an aliased
// host)
try {
return InetAddress.getByName(spoofed).getHostAddress() + ":" + spoofed;
} catch (UnknownHostException e) {
// ignore failure to resolve spoofed host
}
// Attempt to return the local host IP with the spoofed host name
try {
return InetAddress.getLocalHost().getHostAddress() + ":" + spoofed;
} catch (UnknownHostException e) {
// ignore failure to resolve spoofed host
}
// We failed to resolve the spoofed host or our local host, return "x"
// for the IP
return "x:" + spoofed;
}
/**
* Guess the Ganglia gmetric type to use for a given object.
*
* @param obj the object to inspect
* @return an appropriate {@link GMetricType}, {@link GMetricType#STRING} by default
*/
private static GMetricType getType(final Object obj) {
// FIXME This is far from covering all cases.
// FIXME Wasteful use of high capacity types (eg Short => INT32)
// Direct mapping when possible
if (obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short)
return GMetricType.INT32;
if (obj instanceof Float)
return GMetricType.FLOAT;
if (obj instanceof Double)
return GMetricType.DOUBLE;
// Convert to double or int if possible
try {
Double.parseDouble(obj.toString());
return GMetricType.DOUBLE;
} catch (NumberFormatException e) {
// Not a double
}
try {
Integer.parseInt(obj.toString());
return GMetricType.UINT32;
} catch (NumberFormatException e) {
// Not an int
}
return GMetricType.STRING;
}
}
|
package redis.clients.jedis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.exceptions.JedisAskDataException;
import redis.clients.jedis.exceptions.JedisClusterException;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisMovedDataException;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder;
/**
* "Redis"
*/
public final class Protocol {
private static final String ASK_RESPONSE = "ASK";
private static final String MOVED_RESPONSE = "MOVED";
private static final String CLUSTERDOWN_RESPONSE = "CLUSTERDOWN";
/** Redis */
public static final int DEFAULT_PORT = 6379;
/** Sentinel */
public static final int DEFAULT_SENTINEL_PORT = 26379;
public static final int DEFAULT_TIMEOUT = 2000;
public static final int DEFAULT_DATABASE = 0;
public static final String CHARSET = "UTF-8";
public static final byte DOLLAR_BYTE = '$';
public static final byte ASTERISK_BYTE = '*';
public static final byte PLUS_BYTE = '+';
public static final byte MINUS_BYTE = '-';
public static final byte COLON_BYTE = ':';
/*
* (Sentinel)
*/
/** "(Master)" */
public static final String SENTINEL_MASTERS = "masters";
public static final String SENTINEL_GET_MASTER_ADDR_BY_NAME = "get-master-addr-by-name";
public static final String SENTINEL_RESET = "reset";
/** "(Slave)" */
public static final String SENTINEL_SLAVES = "slaves";
public static final String SENTINEL_FAILOVER = "failover";
public static final String SENTINEL_MONITOR = "monitor";
public static final String SENTINEL_REMOVE = "remove";
public static final String SENTINEL_SET = "set";
/*
* (Cluster)
*/
/** Redis */
public static final String CLUSTER_NODES = "nodes";
public static final String CLUSTER_MEET = "meet";
public static final String CLUSTER_RESET = "reset";
public static final String CLUSTER_ADDSLOTS = "addslots";
public static final String CLUSTER_DELSLOTS = "delslots";
public static final String CLUSTER_INFO = "info";
public static final String CLUSTER_GETKEYSINSLOT = "getkeysinslot";
public static final String CLUSTER_SETSLOT = "setslot";
public static final String CLUSTER_SETSLOT_NODE = "node";
public static final String CLUSTER_SETSLOT_MIGRATING = "migrating";
public static final String CLUSTER_SETSLOT_IMPORTING = "importing";
public static final String CLUSTER_SETSLOT_STABLE = "stable";
public static final String CLUSTER_FORGET = "forget";
public static final String CLUSTER_FLUSHSLOT = "flushslots";
public static final String CLUSTER_KEYSLOT = "keyslot";
public static final String CLUSTER_COUNTKEYINSLOT = "countkeysinslot";
public static final String CLUSTER_SAVECONFIG = "saveconfig";
public static final String CLUSTER_REPLICATE = "replicate";
public static final String CLUSTER_SLAVES = "slaves";
public static final String CLUSTER_FAILOVER = "failover";
public static final String CLUSTER_SLOTS = "slots";
public static final String PUBSUB_CHANNELS= "channels";
public static final String PUBSUB_NUMSUB = "numsub";
public static final String PUBSUB_NUM_PAT = "numpat";
private Protocol() {
// this prevent the class from instantiation
}
/**
* Redis
*
* @param os
* @param command Redis
* @param args
*/
public static void sendCommand(final RedisOutputStream os,
final Command command, final byte[]... args) {
sendCommand(os, command.raw, args);
}
private static void sendCommand(final RedisOutputStream os,
final byte[] command, final byte[]... args) {
/*
* "Redis"
*/
try {
os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length);
os.write(command);
os.writeCrLf();
for (final byte[] arg : args) {
os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length);
os.write(arg);
os.writeCrLf();
}
} catch (IOException e) {
// "Redis"
throw new JedisConnectionException(e);
}
}
private static void processError(final RedisInputStream is) {
String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this.
// Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message);
}
throw new JedisDataException(message);
}
private static String[] parseTargetHostAndSlot(
String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":");
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
}
private static Object process(final RedisInputStream is) {
try {
byte b = is.readByte();
if (b == MINUS_BYTE) {
processError(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
return null;
}
private static byte[] processStatusCodeReply(final RedisInputStream is) {
return SafeEncoder.encode(is.readLine());
}
private static byte[] processBulkReply(final RedisInputStream is) {
int len = Integer.parseInt(is.readLine());
if (len == -1) {
return null;
}
byte[] read = new byte[len];
int offset = 0;
try {
while (offset < len) {
int size = is.read(read, offset, (len - offset));
if (size == -1)
throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size;
}
// read 2 more bytes for the command delimiter
is.readByte();
is.readByte();
} catch (IOException e) {
throw new JedisConnectionException(e);
}
return read;
}
private static Long processInteger(final RedisInputStream is) {
String num = is.readLine();
return Long.valueOf(num);
}
private static List<Object> processMultiBulkReply(final RedisInputStream is) {
int num = Integer.parseInt(is.readLine());
if (num == -1) {
return null;
}
List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
}
public static Object read(final RedisInputStream is) {
return process(is);
}
public static final byte[] toByteArray(final boolean value) {
return toByteArray(value ? 1 : 0);
}
public static final byte[] toByteArray(final int value) {
return SafeEncoder.encode(String.valueOf(value));
}
public static final byte[] toByteArray(final long value) {
return SafeEncoder.encode(String.valueOf(value));
}
public static final byte[] toByteArray(final double value) {
return SafeEncoder.encode(String.valueOf(value));
}
public static enum Command {
PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, ZLEXCOUNT, ZRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE;
public final byte[] raw;
Command() {
raw = SafeEncoder.encode(this.name());
}
}
public static enum Keyword {
AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
public final byte[] raw;
Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase());
}
}
}
|
package com.fdflib.example;
import com.fdflib.example.model.Car;
import com.fdflib.example.model.CarMake;
import com.fdflib.example.model.Driver;
import com.fdflib.example.service.CarService;
import com.fdflib.example.service.DriverService;
import com.fdflib.model.entity.FdfEntity;
import com.fdflib.persistence.database.DatabaseUtil;
import com.fdflib.service.FdfServices;
import com.fdflib.util.FdfSettings;
import java.util.ArrayList;
import java.util.List;
public class BlackCarService {
public static void main(String[] args) {
System.out.println("Hello 4DF World!"); // Display the string.
// use the settings within this method to customize the 4DFLib. Note, everything in this method is optional.
setOptionalSettings();
// Create a array that will hold the classes that make up our 4df data model
List<Class> myModel = new ArrayList<>();
// Add our 2 classes
myModel.add(Driver.class);
myModel.add(Car.class);
// call the initialization of library!
FdfServices.initializeFdfDataModel(myModel);
// insert some demo data
try {
insertSomeData();
} catch(InterruptedException e) {
e.printStackTrace();
}
// do a few queries and output the results
}
/**
* Everything set in this method is optional, but useful
*/
private static void setOptionalSettings() {
// get the 4dflib settings singleton
FdfSettings fdfSettings = FdfSettings.getInstance();
// set the database type and name and connection information
// PostgreSQL settings
fdfSettings.PERSISTENCE = DatabaseUtil.DatabaseType.POSTGRES;
fdfSettings.DB_PROTOCOL = DatabaseUtil.DatabaseProtocol.JDBC_POSTGRES;
// postgres default root user
// root user settings are only required for initial database creation. Once the database is created you
// should remove this information
fdfSettings.DB_ROOT_USER = "postgres";
// MySQL settings
//fdfSettings.PERSISTENCE = DatabaseUtil.DatabaseType.MYSQL;
//fdfSettings.DB_PROTOCOL = DatabaseUtil.DatabaseProtocol.JDBC_MYSQL;
// MariaDB settings
//fdfSettings.PERSISTENCE = DatabaseUtil.DatabaseType.MARIADB;
//fdfSettings.DB_PROTOCOL = DatabaseUtil.DatabaseProtocol.JDBC_MARIADB;
// MariaDB and MySQL default
// root user settings are only required for initial database creation. Once the database is created you
// should remove this information
//fdfSettings.DB_ROOT_USER = "root";
// root user password
fdfSettings.DB_ROOT_PASSWORD = "";
// Database encoding
fdfSettings.DB_ENCODING = DatabaseUtil.DatabaseEncoding.UTF8;
// Application Database name
fdfSettings.DB_NAME = "blackcardemo";
// Database host
fdfSettings.DB_HOST = "localhost";
// Port is not required for DB defaults can be changed when needed
// fdfSettings.DB_PORT = 3306;
// Database user information
fdfSettings.DB_USER = "blackcar";
fdfSettings.DB_PASSWORD = "blackcarpass";
// set the default system information
fdfSettings.DEFAULT_SYSTEM_NAME = "Black Car Core API";
fdfSettings.DEFAULT_SYSTEM_DESCRIPTION = "Central API service for the Black Car Application";
// set the default tenant information
fdfSettings.DEFAULT_TENANT_NAME = "BlackCar";
fdfSettings.DEFAULT_TENANT_DESRIPTION = "Main system Tenant";
fdfSettings.DEFAULT_TENANT_IS_PRIMARY = true;
fdfSettings.DEFAULT_TENANT_WEBSITE = "http:
// local dev, no ssl
fdfSettings.USE_SSL = false;
}
private static void insertSomeData() throws InterruptedException {
DriverService ds = new DriverService();
CarService cs = new CarService();
// create a few of drivers
Driver sam = new Driver();
sam.firstName = "Sam";
sam.lastName = "Holden";
sam.phoneNumber = "212-555-1212";
ds.saveDriver(sam);
Driver harry = new Driver();
harry.firstName = "Harry";
harry.lastName = "Smith";
harry.phoneNumber = "212-555-1313";
harry = ds.saveDriver(harry);
Driver jack = new Driver();
jack.firstName = "Jack";
jack.lastName = "Johnson";
jack.phoneNumber = "212-555-1414";
jack = ds.saveDriver(jack);
Driver brian = new Driver();
brian.firstName = "Brian";
brian.lastName = "G";
brian.phoneNumber = "845-555-1114";
brian = ds.saveDriver(brian);
Car mufasa = new Car();
mufasa.name = "Mufasa";
mufasa.color = "Teal";
mufasa.isInNeedOfRepair = false;
mufasa.description = "Total awesomeness";
mufasa.make = CarMake.PONTIAC;
mufasa.model = "Trans Am";
mufasa.year = 1983;
mufasa.currentDriverId = brian.id;
cs.saveCar(mufasa);
Car ss = new Car();
ss.name = "sliver ss";
ss.color = "Sliver";
ss.isInNeedOfRepair = false;
ss.description = "Nice Sleeper";
ss.make = CarMake.CHEVY;
ss.model = "SS";
ss.year = 2014;
cs.saveCar(ss);
Car pbox = new Car();
pbox.name = "Brians project";
pbox.color = "Gray";
pbox.isInNeedOfRepair = false;
pbox.description = "Roadster";
pbox.make = CarMake.PORSCHE;
pbox.model = "Boxster s";
pbox.year = 2001;
cs.saveCar(pbox);
Car pilot = new Car();
pilot.name = "Current Family Hauler";
pilot.color = "Maroon";
pilot.isInNeedOfRepair = false;
pilot.description = "Family Fun!";
pilot.make = CarMake.HONDA;
pilot.model = "Pilot";
pilot.year = 2019;
pilot.currentDriverId = brian.id;
cs.saveCar(pilot);
Car van = new Car();
van.name = "Minivan o death";
van.color = "Red";
van.isInNeedOfRepair = false;
van.description = "POS";
van.make = CarMake.CHRYSLER;
van.model = "Town & Country";
van.year = 2014;
cs.saveCar(van);
Car cv1 = new Car();
cv1.name = "Medallion 1";
cv1.color = "Yellow";
cv1.isInNeedOfRepair = false;
cv1.description = "NYC has the best taxis";
cv1.make = CarMake.FORD;
cv1.model = "LTD Crown Victoria";
cv1.year = 2001;
// assign jack to the this car
cv1.currentDriverId = jack.id;
cs.saveCar(cv1);
/*
Lets do some stuff with the data
*/
Thread.sleep(3000);
// since we did not assign anyone to drive Brians project, lets do that now
pbox = cs.getCarsByName("Brians project");
// output the current driver id
if(pbox != null) {
System.out.println("Car: " + pbox.model + " Driver Id (shoud be empty): " + pbox.currentDriverId);
}
// assign me to drive
pbox.currentDriverId = brian.id;
// Wait a few seconds
Thread.sleep(3000);
cs.saveCar(pbox);
// now try again
pbox = cs.getCarsByName("Brians project");;
System.out.println("Car: " + pbox.model + " Driver Id: "
+ pbox.currentDriverId + " [assigned!]"); // should have an id now!
// lets also find all cars from the year 2001
List<Car> cars01 = cs.getCarsByYear(2001);
for(Car car: cars01) {
// see if there should be a driver and get the driver if so!
if(car.currentDriverId >= 0) {
car.currentDriver = ds.getDriverById(car.currentDriverId);
}
String driver = (car.currentDriver != null) ? car.currentDriver.firstName : "no driver";
System.out.println("2001 car: " + car.name + " which is a " + car.make + " " + car.model + " driven by: "
+ driver + " has a current repair status: " + car.isInNeedOfRepair);
}
// Wait a few seconds
Thread.sleep(6000);
// change all 2014 cars status to needing repair
for(Car car: cars01) {
car.isInNeedOfRepair = true;
cs.saveCar(car);
}
// Wait a few seconds
Thread.sleep(6000);
// get one of the cars and change it back
List<Car> cars01new = cs.getCarsByYear(2001);
cars01new.get(0).isInNeedOfRepair = false;
cs.saveCar(cars01new.get(0));
System.out.println("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
// re-run the query and output the results again, this time with history so we can see the change!
List<FdfEntity<Car>> cars01withHistory = cs.getCarsByYearWithHistory(2001);
for(FdfEntity<Car> carWithHistory: cars01withHistory) {
// first output the cars current status
System.out.println("2001 cars [after updates]: " + carWithHistory.current.name + " which is a "
+ carWithHistory.current.make + " " + carWithHistory.current.model
+ " has a [current] repair status: " + carWithHistory.current.isInNeedOfRepair);
System.out.println("
// Now show the historical records for the car
for(Car carHistory : carWithHistory.history) {
System.out.println("Start time: " + carHistory.arsd + " End time: " + carHistory.ared
+ " repair status: " + carHistory.isInNeedOfRepair + " it was driven by userid "
+ carHistory.currentDriverId);
}
System.out.println("___________________");
}
// for fun lets try a custom query
Car myBoxster = cs.customCarQuery("Brians project").current;
System.out.println("\n^^^^^^^^^^^^^^^^ Custom Query Results ^^^^^^^^^^^^^^^^^^^^^^");
System.out.println("year make and model: " + myBoxster.year + " " + myBoxster.make + " " + myBoxster.model);
System.out.println("name: " + myBoxster.name + " Desc: " + myBoxster.description);
}
}
|
package javaslang.concurrent;
import javaslang.Function2;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.Value;
import javaslang.collection.Iterator;
import javaslang.collection.List;
import javaslang.collection.Seq;
import javaslang.collection.Stream;
import javaslang.control.Option;
import javaslang.control.Try;
import javaslang.control.Try.CheckedFunction;
import javaslang.control.Try.CheckedPredicate;
import javaslang.control.Try.CheckedRunnable;
import javaslang.control.Try.CheckedSupplier;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.*;
/**
* A Future is a computation result that becomes available at some point. All operations provided are non-blocking.
* <p>
* The underlying {@code ExecutorService} is used to execute asynchronous handlers, e.g. via
* {@code onComplete(...)}.
* <p>
* A Future has two states: pending and completed.
* <ul>
* <li>Pending: The computation is ongoing. Only a pending future may be completed or cancelled.</li>
* <li>Completed: The computation finished successfully with a result, failed with an exception or was cancelled.</li>
* </ul>
* Callbacks may be registered on a Future at each point of time. These actions are performed as soon as the Future
* is completed. An action which is registered on a completed Future is immediately performed. The action may run on
* a separate Thread, depending on the underlying ExecutorService. Actions which are registered on a cancelled
* Future are performed with the failed result.
*
* @param <T> Type of the computation result.
* @author Daniel Dietrich
* @since 2.0.0
*/
public interface Future<T> extends Value<T> {
/**
* The default executor service is {@link Executors#newCachedThreadPool()}.
* Please note that it may prevent the VM from shutdown.}
*/
ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
/**
* Creates a failed {@code Future} with the given {@code exception}, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param exception The reason why it failed.
* @param <T> The value type of a successful result.
* @return A failed {@code Future}.
* @throws NullPointerException if exception is null
*/
static <T> Future<T> failed(Throwable exception) {
Objects.requireNonNull(exception, "exception is null");
return failed(DEFAULT_EXECUTOR_SERVICE, exception);
}
/**
* Creates a failed {@code Future} with the given {@code exception}, backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param exception The reason why it failed.
* @param <T> The value type of a successful result.
* @return A failed {@code Future}.
* @throws NullPointerException if executorService or exception is null
*/
static <T> Future<T> failed(ExecutorService executorService, Throwable exception) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(exception, "exception is null");
return Promise.<T> failed(executorService, exception).future();
}
/**
* Returns a {@code Future} that eventually succeeds with the first result of the given {@code Future}s which
* matches the given {@code predicate}. If no result matches, the {@code Future} will contain {@link Option.None}.
* <p>
* The returned {@code Future} is backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param futures An iterable of futures.
* @param predicate A predicate that tests successful future results.
* @param <T> Result type of the futures.
* @return A Future of an {@link Option} of the first result of the given {@code futures} that satisfies the given {@code predicate}.
* @throws NullPointerException if one of the arguments is null
*/
static <T> Future<Option<T>> find(Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) {
return find(DEFAULT_EXECUTOR_SERVICE, futures, predicate);
}
/**
* Returns a {@code Future} that eventually succeeds with the first result of the given {@code Future}s which
* matches the given {@code predicate}. If no result matches, the {@code Future} will contain {@link Option.None}.
* <p>
* The returned {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param futures An iterable of futures.
* @param predicate A predicate that tests successful future results.
* @param <T> Result type of the futures.
* @return A Future of an {@link Option} of the first result of the given {@code futures} that satisfies the given {@code predicate}.
* @throws NullPointerException if one of the arguments is null
*/
static <T> Future<Option<T>> find(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
Objects.requireNonNull(predicate, "predicate is null");
final Promise<Option<T>> promise = Promise.make(executorService);
final List<Future<? extends T>> list = List.ofAll(futures);
if (list.isEmpty()) {
promise.success(Option.none());
} else {
final AtomicInteger count = new AtomicInteger(list.length());
list.forEach(future -> future.onComplete(result -> {
synchronized (count) {
// if the promise is already completed we already found our result and there is nothing more to do.
if (!promise.isCompleted()) {
// when there are no more results we return a None
final boolean wasLast = count.decrementAndGet() == 0;
// when result is a Failure or predicate is false then we check in onFailure for finish
result.filter(predicate)
.onSuccess(value -> promise.trySuccess(Option.some(value)))
.onFailure(ignored -> {
if (wasLast) {
promise.trySuccess(Option.none());
}
});
}
}
}));
}
return promise.future();
}
/**
* Returns a new {@code Future} that will contain the result of the first of the given futures that is completed,
* backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param futures An iterable of futures.
* @param <T> The result type.
* @return A new {@code Future}.
* @throws NullPointerException if futures is null
*/
static <T> Future<T> firstCompletedOf(Iterable<? extends Future<? extends T>> futures) {
return firstCompletedOf(DEFAULT_EXECUTOR_SERVICE, futures);
}
/**
* Returns a new {@code Future} that will contain the result of the first of the given futures that is completed,
* backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param futures An iterable of futures.
* @param <T> The result type.
* @return A new {@code Future}.
* @throws NullPointerException if executorService or futures is null
*/
static <T> Future<T> firstCompletedOf(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
final Promise<T> promise = Promise.make(executorService);
final Consumer<Try<? extends T>> completeFirst = promise::tryComplete;
futures.forEach(future -> future.onComplete(completeFirst));
return promise.future();
}
/**
* Returns a Future which contains the result of the fold of the given future values. If any future or the fold
* fail, the result is a failure.
* <p>
* The resulting {@code Future} is backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param futures An iterable of futures.
* @param zero The zero element of the fold.
* @param f The fold operation.
* @param <T> The result type of the given {@code Futures}.
* @param <U> The fold result type.
* @return A new {@code Future} that will contain the fold result.
* @throws NullPointerException if futures or f is null.
*/
static <T, U> Future<U> fold(Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) {
return fold(DEFAULT_EXECUTOR_SERVICE, futures, zero, f);
}
/**
* Returns a Future which contains the result of the fold of the given future values. If any future or the fold
* fail, the result is a failure.
* <p>
* The resulting {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param futures An iterable of futures.
* @param zero The zero element of the fold.
* @param f The fold operation.
* @param <T> The result type of the given {@code Futures}.
* @param <U> The fold result type.
* @return A new {@code Future} that will contain the fold result.
* @throws NullPointerException if executorService, futures or f is null.
*/
static <T, U> Future<U> fold(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
Objects.requireNonNull(f, "f is null");
if (!futures.iterator().hasNext()) {
return successful(executorService, zero);
} else {
return sequence(executorService, futures).map(seq -> seq.foldLeft(zero, f));
}
}
/**
* Creates a {@code Future} with the given java.util.concurrent.Future, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}
*
* @param future A {@link java.util.concurrent.Future}
* @param <T> Result type of the Future
* @return A new {@code Future} wrapping the result of the Java future
* @throws NullPointerException if future is null
*/
static <T> Future<T> fromJavaFuture(java.util.concurrent.Future<T> future) {
Objects.requireNonNull(future, "future is null");
return Future.of(DEFAULT_EXECUTOR_SERVICE, future::get);
}
/**
* Creates a {@code Future} with the given java.util.concurrent.Future, backed by given {@link ExecutorService}
*
* @param executorService An {@link ExecutorService}
* @param future A {@link java.util.concurrent.Future}
* @param <T> Result type of the Future
* @return A new {@code Future} wrapping the result of the Java future
* @throws NullPointerException if executorService or future is null
*/
static <T> Future<T> fromJavaFuture(ExecutorService executorService, java.util.concurrent.Future<T> future) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(future, "future is null");
return Future.of(executorService, future::get);
}
/**
* Creates a {@code Future} from a {@link Try}, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param result The result.
* @param <T> The value type of a successful result.
* @return A completed {@code Future} which contains either a {@code Success} or a {@code Failure}.
* @throws NullPointerException if result is null
*/
static <T> Future<T> fromTry(Try<? extends T> result) {
return fromTry(DEFAULT_EXECUTOR_SERVICE, result);
}
/**
* Creates a {@code Future} from a {@link Try}, backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param result The result.
* @param <T> The value type of a successful result.
* @return A completed {@code Future} which contains either a {@code Success} or a {@code Failure}.
* @throws NullPointerException if executorService or result is null
*/
static <T> Future<T> fromTry(ExecutorService executorService, Try<? extends T> result) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(result, "result is null");
return Promise.<T> fromTry(executorService, result).future();
}
/**
* Narrows a widened {@code Future<? extends T>} to {@code Future<T>}
* by performing a type-safe cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param future A {@code Future}.
* @param <T> Component type of the {@code Future}.
* @return the given {@code future} instance as narrowed type {@code Future<T>}.
*/
@SuppressWarnings("unchecked")
static <T> Future<T> narrow(Future<? extends T> future) {
return (Future<T>) future;
}
/**
* Starts an asynchronous computation, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param computation A computation.
* @param <T> Type of the computation result.
* @return A new Future instance.
* @throws NullPointerException if computation is null.
*/
static <T> Future<T> of(CheckedSupplier<? extends T> computation) {
return Future.of(DEFAULT_EXECUTOR_SERVICE, computation);
}
/**
* Starts an asynchronous computation, backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param computation A computation.
* @param <T> Type of the computation result.
* @return A new Future instance.
* @throws NullPointerException if one of executorService of computation is null.
*/
static <T> Future<T> of(ExecutorService executorService, CheckedSupplier<? extends T> computation) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(computation, "computation is null");
final FutureImpl<T> future = new FutureImpl<>(executorService);
future.run(computation);
return future;
}
/**
* Returns a Future which contains the reduce result of the given future values. The zero is the result of the
* first future that completes. If any future or the reduce operation fail, the result is a failure.
* <p>
* The resulting {@code Future} is backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param futures An iterable of futures.
* @param f The reduce operation.
* @param <T> The result type of the given {@code Futures}.
* @return A new {@code Future} that will contain the reduce result.
* @throws NullPointerException if executorService, futures or f is null.
*/
static <T> Future<T> reduce(Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) {
return reduce(DEFAULT_EXECUTOR_SERVICE, futures, f);
}
/**
* Returns a Future which contains the reduce result of the given future values. The zero is the result of the
* first future that completes. If any future or the reduce operation fail, the result is a failure.
* <p>
* The resulting {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param futures An iterable of futures.
* @param f The reduce operation.
* @param <T> The result type of the given {@code Futures}.
* @return A new {@code Future} that will contain the reduce result.
* @throws NullPointerException if executorService, futures or f is null.
*/
static <T> Future<T> reduce(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
Objects.requireNonNull(f, "f is null");
if (!futures.iterator().hasNext()) {
throw new NoSuchElementException("Future.reduce on empty futures");
} else {
return Future.<T> sequence(futures).map(seq -> seq.reduceLeft(f));
}
}
/**
* Runs an asynchronous computation, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param unit A unit of work.
* @return A new Future instance which results in nothing.
* @throws NullPointerException if unit is null.
*/
static Future<Void> run(CheckedRunnable unit) {
return run(DEFAULT_EXECUTOR_SERVICE, unit);
}
/**
* Starts an asynchronous computation, backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param unit A unit of work.
* @return A new Future instance which results in nothing.
* @throws NullPointerException if one of executorService of unit is null.
*/
static Future<Void> run(ExecutorService executorService, CheckedRunnable unit) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(unit, "unit is null");
return Future.of(executorService, () -> {
unit.run();
return null;
});
}
/**
* Reduces many {@code Future}s into a single {@code Future} by transforming an
* {@code Iterable<Future<? extends T>>} into a {@code Future<Seq<T>>}.
* <p>
* The resulting {@code Future} is backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* <ul>
* <li>
* If all of the given Futures succeed, sequence() succeeds too:
* <pre><code>// = Future(Success(Seq(1, 2)))
* sequence(
* List.of(
* Future.of(() -> 1),
* Future.of(() -> 2)
* )
* );</code></pre>
* </li>
* <li>
* If a given Future fails, sequence() fails too:
* <pre><code>// = Future(Failure(Error)))
* sequence(
* List.of(
* Future.of(() -> 1),
* Future.of(() -> { throw new Error(); }
* )
* );</code></pre>
* </li>
* </ul>
*
* @param futures An {@code Iterable} of {@code Future}s.
* @param <T> Result type of the futures.
* @return A {@code Future} of a {@link Seq} of results.
* @throws NullPointerException if futures is null.
*/
static <T> Future<Seq<T>> sequence(Iterable<? extends Future<? extends T>> futures) {
return sequence(DEFAULT_EXECUTOR_SERVICE, futures);
}
/**
* Reduces many {@code Future}s into a single {@code Future} by transforming an
* {@code Iterable<Future<? extends T>>} into a {@code Future<Seq<T>>}.
* <p>
* The resulting {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param futures An {@code Iterable} of {@code Future}s.
* @param <T> Result type of the futures.
* @return A {@code Future} of a {@link Seq} of results.
* @throws NullPointerException if executorService or futures is null.
*/
static <T> Future<Seq<T>> sequence(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
final Future<Seq<T>> zero = successful(executorService, Stream.empty());
final BiFunction<Future<Seq<T>>, Future<? extends T>, Future<Seq<T>>> f =
(result, future) -> result.flatMap(seq -> future.map(seq::append));
return Iterator.ofAll(futures).foldLeft(zero, f);
}
/**
* Creates a succeeded {@code Future}, backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param result The result.
* @param <T> The value type of a successful result.
* @return A succeeded {@code Future}.
*/
static <T> Future<T> successful(T result) {
return successful(DEFAULT_EXECUTOR_SERVICE, result);
}
/**
* Creates a succeeded {@code Future}, backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param result The result.
* @param <T> The value type of a successful result.
* @return A succeeded {@code Future}.
* @throws NullPointerException if executorService is null
*/
static <T> Future<T> successful(ExecutorService executorService, T result) {
Objects.requireNonNull(executorService, "executorService is null");
return Promise.successful(executorService, result).future();
}
/**
* Maps the values of an iterable in parallel to a sequence of mapped values into a single {@code Future} by
* transforming an {@code Iterable<? extends T>} into a {@code Future<Seq<U>>}.
* <p>
* The resulting {@code Future} is backed by the {@link #DEFAULT_EXECUTOR_SERVICE}.
*
* @param values An {@code Iterable} of {@code Future}s.
* @param mapper A mapper of values to Futures
* @param <T> The type of the given values.
* @param <U> The mapped value type.
* @return A {@code Future} of a {@link Seq} of results.
* @throws NullPointerException if values or f is null.
*/
static <T, U> Future<Seq<U>> traverse(Iterable<? extends T> values, Function<? super T, ? extends Future<? extends U>> mapper) {
return traverse(DEFAULT_EXECUTOR_SERVICE, values, mapper);
}
/**
* Maps the values of an iterable in parallel to a sequence of mapped values into a single {@code Future} by
* transforming an {@code Iterable<? extends T>} into a {@code Future<Seq<U>>}.
* <p>
* The resulting {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An {@code ExecutorService}.
* @param values An {@code Iterable} of values.
* @param mapper A mapper of values to Futures
* @param <T> The type of the given values.
* @param <U> The mapped value type.
* @return A {@code Future} of a {@link Seq} of results.
* @throws NullPointerException if executorService, values or f is null.
*/
static <T, U> Future<Seq<U>> traverse(ExecutorService executorService, Iterable<? extends T> values, Function<? super T, ? extends Future<? extends U>> mapper) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(values, "values is null");
Objects.requireNonNull(mapper, "mapper is null");
return sequence(Iterator.ofAll(values).map(mapper));
}
// -- non-static Future API
/**
* Support for chaining of callbacks that are guaranteed to be executed in a specific order.
* <p>
* An exception, which occurs when performing the given {@code action}, is not propagated to the outside.
* In other words, subsequent actions are performed based on the value of the original Future.
* <p>
* Example:
* <pre><code>
* // prints Success(1)
* Future.of(() -> 1)
* .andThen(t -> { throw new Error(""); })
* .andThen(System.out::println);
* </code></pre>
*
* @param action A side-effecting action.
* @return A new Future that contains this result and which is completed after the given action was performed.
* @throws NullPointerException if action is null
*/
default Future<T> andThen(Consumer<? super Try<T>> action) {
Objects.requireNonNull(action, "action is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(t -> {
Try.run(() -> action.accept(t));
promise.complete(t);
});
return promise.future();
}
/**
* Blocks the current Thread until this Future completed or returns immediately if this Future is already completed.
*/
void await();
/**
* Cancels the Future. A running thread is interrupted.
* <p>
* If the Future was successfully cancelled, the result is a {@code Failure(CancellationException)}.
*
* @return {@code false}, if this {@code Future} is already completed or could not be cancelled, otherwise {@code true}.
*/
default boolean cancel() {
return cancel(true);
}
/**
* Cancels the Future. A pending Future may be interrupted, depending on the underlying ExecutionService.
* <p>
* If the Future was successfully cancelled, the result is a {@code Failure(CancellationException)}.
*
* @param mayInterruptIfRunning {@code true} if a running thread should be interrupted, otherwise a running thread
* is allowed to complete its computation.
* @return {@code false}, if this {@code Future} is already completed or could not be cancelled, otherwise {@code true}.
* @see java.util.concurrent.Future#cancel(boolean)
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* Returns the {@link ExecutorService} used by this {@code Future}.
*
* @return The underlying {@code ExecutorService}.
*/
ExecutorService executorService();
/**
* A projection that inverses the result of this Future.
* <p>
* If this Future succeeds, the failed projection returns a failure containing a {@code NoSuchElementException}.
* <p>
* If this Future fails, the failed projection returns a success containing the exception.
*
* @return A new Future which contains an exception at a point of time.
*/
default Future<Throwable> failed() {
final Promise<Throwable> promise = Promise.make(executorService());
onComplete(result -> {
if (result.isFailure()) {
promise.success(result.getCause());
} else {
promise.failure(new NoSuchElementException("Future.failed completed without a throwable"));
}
});
return promise.future();
}
/**
* Returns a Future that returns the result of this Future, if it is a success. If the value of this Future is a
* failure, the result of {@code that} Future is returned, if that is a success. If both Futures fail, the failure
* of this Future is returned.
* <p>
* Example:
* <pre><code>
* Future<Integer> future = Future.of(() -> { throw new Error(); });
* Future<Integer> that = Future.of(() -> 1);
* Future<Integer> result = future.fallbackTo(that);
*
* // prints Some(1)
* result.onComplete(System.out::println);
* </code></pre>
*
* @param that A fallback future computation
* @return A new Future
* @throws NullPointerException if that is null
*/
default Future<T> fallbackTo(Future<? extends T> that) {
Objects.requireNonNull(that, "that is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(t -> {
if (t.isSuccess()) {
promise.complete(t);
} else {
that.onComplete(alt -> {
if (alt.isSuccess()) {
promise.complete(alt);
} else {
promise.complete(t);
}
});
}
});
return promise.future();
}
/**
* Shortcut for {@code filterTry(predicate::test}.
*
* @param predicate A predicate
* @return A new {@code Future}
* @throws NullPointerException if {@code predicate} is null
*/
default Future<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return filterTry(predicate::test);
}
/**
* Filters the result of this {@code Future} by calling {@link Try#filterTry(CheckedPredicate)}.
*
* @param predicate A checked predicate
* @return A new {@code Future}
* @throws NullPointerException if {@code predicate} is null
*/
default Future<T> filterTry(CheckedPredicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(result -> promise.complete(result.filterTry(predicate)));
return promise.future();
}
/**
* Returns the underlying exception of this Future, syntactic sugar for {@code future.getValue().map(Try::getCause)}.
*
* @return None if the Future is not completed yet. Returns Some(Throwable) if the Future was completed with a failure.
* @throws UnsupportedOperationException if the Future was successfully completed with a value
*/
default Option<Throwable> getCause() {
return getValue().map(Try::getCause);
}
/**
* Returns the value of the Future.
*
* @return {@code None}, if the Future is not yet completed or was cancelled, otherwise {@code Some(Try)}.
*/
Option<Try<T>> getValue();
/**
* Checks if this Future is completed, i.e. has a value.
*
* @return true, if the computation successfully finished, failed or was cancelled, false otherwise.
*/
boolean isCompleted();
/**
* Checks if this Future completed with a success.
*
* @return true, if this Future completed and is a Success, false otherwise.
*/
default boolean isSuccess() {
return getValue().map(Try::isSuccess).getOrElse(false);
}
/**
* Checks if this Future completed with a failure.
*
* @return true, if this Future completed and is a Failure, false otherwise.
*/
default boolean isFailure() {
return getValue().map(Try::isFailure).getOrElse(false);
}
/**
* Performs the action once the Future is complete.
*
* @param action An action to be performed when this future is complete.
* @return this Future
* @throws NullPointerException if {@code action} is null.
*/
Future<T> onComplete(Consumer<? super Try<T>> action);
/**
* Performs the action once the Future is complete and the result is a {@link Try.Failure}. Please note that the
* future is also a failure when it was cancelled.
*
* @param action An action to be performed when this future failed.
* @return this Future
* @throws NullPointerException if {@code action} is null.
*/
default Future<T> onFailure(Consumer<? super Throwable> action) {
Objects.requireNonNull(action, "action is null");
return onComplete(result -> result.onFailure(action));
}
/**
* Performs the action once the Future is complete and the result is a {@link Try.Success}.
*
* @param action An action to be performed when this future succeeded.
* @return this Future
* @throws NullPointerException if {@code action} is null.
*/
default Future<T> onSuccess(Consumer<? super T> action) {
Objects.requireNonNull(action, "action is null");
return onComplete(result -> result.onSuccess(action));
}
/**
* Handles a failure of this Future by returning another result.
* <p>
* Example:
* <pre><code>
* // = "oh!"
* Future.of(() -> new Error("oh!")).recover(Throwable::getMessage);
* </code></pre>
*
* @param f A function which takes the exception of a failure and returns a new value.
* @return A new Future.
* @throws NullPointerException if {@code f} is null
*/
default Future<T> recover(Function<? super Throwable, ? extends T> f) {
Objects.requireNonNull(f, "f is null");
return transformResult(t -> t.recover(f::apply));
}
/**
* Handles a failure of this Future by returning the result of another Future.
* <p>
* Example:
* <pre><code>
* // = "oh!"
* Future.of(() -> { throw new Error("oh!"); }).recoverWith(x -> Future.of(x::getMessage));
* </code></pre>
*
* @param f A function which takes the exception of a failure and returns a new future.
* @return A new Future.
* @throws NullPointerException if {@code f} is null
*/
default Future<T> recoverWith(Function<? super Throwable, ? extends Future<? extends T>> f) {
Objects.requireNonNull(f, "f is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(t -> {
if (t.isFailure()) {
Try.run(() -> f.apply(t.getCause()).onComplete(promise::complete)).onFailure(promise::failure);
} else {
promise.complete(t);
}
});
return promise.future();
}
/**
* Transforms this {@code Future}.
*
* @param f A transformation
* @param <U> Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
default <U> U transform(Function<? super Future<T>, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
/**
* Transforms the result of this {@code Future}, whether it is a success or a failure.
*
* @param f A transformation
* @param <U> Generic type of transformation {@code Try} result
* @return A {@code Future} of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
default <U> Future<U> transformResult(Function<? super Try<T>, ? extends Try<U>> f) {
Objects.requireNonNull(f, "f is null");
final Promise<U> promise = Promise.make(executorService());
onComplete(t -> {
Try.run(() -> promise.complete(f.apply(t))).onFailure(promise::failure);
});
return promise.future();
}
/**
* Returns a tuple of this and that Future result.
* <p>
* If this Future failed the result contains this failure. Otherwise the result contains that failure or
* a tuple of both successful Future results.
*
* @param that Another Future
* @param <U> Result type of {@code that}
* @return A new Future that returns both Future results.
* @throws NullPointerException if {@code that} is null
*/
default <U> Future<Tuple2<T, U>> zip(Future<? extends U> that) {
Objects.requireNonNull(that, "that is null");
return zipWith(that, Tuple::of);
}
/**
* Returns a this and that Future result combined using a given combinator function.
* <p>
* If this Future failed the result contains this failure. Otherwise the result contains that failure or
* a combination of both successful Future results.
*
* @param that Another Future
* @param combinator The combinator function
* @param <U> Result type of {@code that}
* @param <R> Result type of {@code f}
* @return A new Future that returns both Future results.
* @throws NullPointerException if {@code that} is null
*/
@SuppressWarnings("unchecked")
default <U, R> Future<R> zipWith(Future<? extends U> that, Function2<T, U, R> combinator) {
Objects.requireNonNull(that, "that is null");
Objects.requireNonNull(combinator, "combinator is null");
final Promise<R> promise = Promise.make(executorService());
onComplete(res1 -> {
if (res1.isFailure()) {
promise.complete((Try.Failure<R>) res1);
} else {
that.onComplete(res2 -> {
final Try<R> result = res1.flatMap(t -> res2.map(u -> combinator.apply(t, u)));
promise.complete(result);
});
}
});
return promise.future();
}
// -- Value & Monad implementation
default <U> Future<U> flatMap(Function<? super T, ? extends Future<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return flatMapTry(mapper::apply);
}
default <U> Future<U> flatMapTry(CheckedFunction<? super T, ? extends Future<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
final Promise<U> promise = Promise.make(executorService());
onComplete((Try<T> result) -> result.mapTry(mapper)
.onSuccess(promise::completeWith)
.onFailure(promise::failure)
);
return promise.future();
}
/**
* Performs the given {@code action} asynchronously hence this Future result becomes available.
* The {@code action} is not performed, if the result is a failure.
*
* @param action A {@code Consumer}
*/
@Override
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action, "action is null");
onComplete(result -> result.forEach(action));
}
/**
* Returns the value of the future. Waits for the result if necessary.
*
* @return The value of this future.
* @throws NoSuchElementException if the computation unexpectedly failed or was interrupted.
*/
// DEV-NOTE: A NoSuchElementException is thrown instead of the exception of the underlying Failure in order to
// be conform to Value#get
@Override
default T get() {
// is empty will block until result is available
if (isEmpty()) {
throw new NoSuchElementException("get on failed future");
} else {
return getValue().get().get();
}
}
/**
* Checks, if this future has a value.
*
* @return true, if this future succeeded with a value, false otherwise.
*/
@Override
default boolean isEmpty() {
// does not need to be synchronized, wait() has to check the completed state again
if (!isCompleted()) {
await();
}
return getValue().get().isEmpty();
}
/**
* A {@code Future} is single-valued.
*
* @return {@code true}
*/
@Override
default boolean isSingleValued() {
return true;
}
@Override
default Iterator<T> iterator() {
return isEmpty() ? Iterator.empty() : Iterator.of(get());
}
@Override
default <U> Future<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return transformResult(t -> t.map(mapper::apply));
}
default <U> Future<U> mapTry(CheckedFunction<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return transformResult(t -> t.mapTry(mapper::apply));
}
default Future<T> orElse(Future<? extends T> other) {
Objects.requireNonNull(other, "other is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(result -> {
if (result.isSuccess()) {
promise.complete(result);
} else {
other.onComplete(promise::complete);
}
});
return promise.future();
}
default Future<T> orElse(Supplier<? extends Future<? extends T>> supplier) {
Objects.requireNonNull(supplier, "supplier is null");
final Promise<T> promise = Promise.make(executorService());
onComplete(result -> {
if (result.isSuccess()) {
promise.complete(result);
} else {
supplier.get().onComplete(promise::complete);
}
});
return promise.future();
}
@Override
default Future<T> peek(Consumer<? super T> action) {
Objects.requireNonNull(action, "action is null");
onSuccess(action::accept);
return this;
}
@Override
default String stringPrefix() {
return "Future";
}
}
|
package com.itmill.toolkit.demo.featurebrowser;
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.Property;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.ui.AbstractSelect;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.TextField;
import com.itmill.toolkit.ui.Tree;
/**
* Demonstrates basic Tree -functionality. Actions are used for add/remove item
* functionality, and a ValueChangeListener reacts to both the Tree and the
* TextField.
*/
public class TreeExample extends CustomComponent implements Action.Handler,
Tree.ValueChangeListener {
private static final Action ADD = new Action("Add item");
private static final Action DELETE = new Action("Delete item");
private static final Action[] actions = new Action[] { ADD, DELETE };
// Id for the caption property
private static final Object CAPTION_PROPERTY = "caption";
private static final String desc = "Try both right- and left-click!";
Tree tree;
TextField editor;
public TreeExample() {
final OrderedLayout main = new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL);
main.setMargin(true);
setCompositionRoot(main);
// Panel w/ Tree
Panel p = new Panel("Select item");
p.setStyleName(Panel.STYLE_LIGHT);
p.setWidth(250);
// Description
p.addComponent(new Label(desc));
// Tree with a few items
tree = new Tree();
tree.setImmediate(true);
// we'll use a property for caption instead of the item id ("value"),
// so that multiple items can have the same caption
tree.addContainerProperty(CAPTION_PROPERTY, String.class, "");
tree.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
tree.setItemCaptionPropertyId(CAPTION_PROPERTY);
for (int i = 1; i <= 3; i++) {
final Object id = addCaptionedItem("Section " + i, null);
tree.expandItem(id);
addCaptionedItem("Team A", id);
addCaptionedItem("Team B", id);
}
// listen for selections
tree.addListener(this);
// "context menu"
tree.addActionHandler(this);
p.addComponent(tree);
main.addComponent(p);
// Panel w/ TextField ("editor")
p = new Panel("Edit item caption");
p.setStyleName(Panel.STYLE_LIGHT);
editor = new TextField();
// make immediate, instead of adding an "apply" button
editor.setImmediate(true);
editor.setEnabled(false);
editor.setColumns(15);
p.addComponent(editor);
main.addComponent(p);
}
public Action[] getActions(Object target, Object sender) {
// We can provide different actions for each target (item), but we'll
// use the same actions all the time.
return actions;
}
public void handleAction(Action action, Object sender, Object target) {
if (action == DELETE) {
tree.removeItem(target);
} else {
// Add
final Object id = addCaptionedItem("New Item", target);
tree.expandItem(target);
tree.setValue(id);
editor.focus();
}
}
public void valueChange(ValueChangeEvent event) {
final Object id = tree.getValue(); // selected item id
if (event.getProperty() == tree) {
// a Tree item was (un) selected
if (id == null) {
// no selecteion, disable TextField
editor.removeListener(this);
editor.setValue("");
editor.setEnabled(false);
} else {
// item selected
// first remove previous listener
editor.removeListener(this);
// enable TextField and update value
editor.setEnabled(true);
final Item item = tree.getItem(id);
editor.setValue(item.getItemProperty(CAPTION_PROPERTY)
.getValue());
// listen for TextField changes
editor.addListener(this);
editor.focus();
}
} else {
// TextField
if (id != null) {
final Item item = tree.getItem(id);
final Property p = item.getItemProperty(CAPTION_PROPERTY);
p.setValue(editor.getValue());
tree.requestRepaint();
}
}
}
/**
* Helper to add an item with specified caption and (optional) parent.
*
* @param caption
* The item caption
* @param parent
* The (optional) parent item id
* @return the created item's id
*/
private Object addCaptionedItem(String caption, Object parent) {
// add item, let tree decide id
final Object id = tree.addItem();
// get the created item
final Item item = tree.getItem(id);
// set our "caption" property
final Property p = item.getItemProperty(CAPTION_PROPERTY);
p.setValue(caption);
if (parent != null) {
tree.setChildrenAllowed(parent, true);
tree.setParent(id, parent);
tree.setChildrenAllowed(id, false);
}
return id;
}
}
|
package redis.clients.johm;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import redis.clients.johm.collections.RedisList;
import redis.clients.johm.collections.RedisMap;
import redis.clients.johm.collections.RedisSet;
import redis.clients.johm.collections.RedisSortedSet;
public final class JOhmUtils {
static String getReferenceKeyName(final Field field) {
return field.getName() + "_id";
}
public static Long getId(final Object model) {
return getId(model, true);
}
public static Long getId(final Object model, boolean checkValidity) {
Long id = null;
if (model != null) {
if (checkValidity) {
Validator.checkValidModel(model);
}
id = Validator.checkValidId(model);
}
return id;
}
static String getModelKey(Class<?> clazz) {
Model model = clazz.getAnnotation(Model.class);
return model == null || model.value().equals("") ? clazz.getSimpleName() : model.value();
}
static boolean isNew(final Object model) {
return getId(model) == null;
}
@SuppressWarnings("unchecked")
static void initCollections(final Object model, final Nest<?> nest, String... ignoring) {
if (model == null || nest == null) {
return;
}
List<String> ignoredProperties = Arrays.asList(ignoring);
for (Field field : gatherAllFields(model.getClass())) {
if (ignoredProperties.contains(field.getName()))
continue;
field.setAccessible(true);
try {
if (field.isAnnotationPresent(CollectionList.class)) {
Validator.checkValidCollection(field);
List<Object> list = (List<Object>) field.get(model);
if (list == null) {
CollectionList annotation = field
.getAnnotation(CollectionList.class);
RedisList<Object> redisList = new RedisList<Object>(
annotation.of(), nest, field, model, ignoring);
field.set(model, redisList);
}
}
if (field.isAnnotationPresent(CollectionSet.class)) {
Validator.checkValidCollection(field);
Set<Object> set = (Set<Object>) field.get(model);
if (set == null) {
CollectionSet annotation = field
.getAnnotation(CollectionSet.class);
RedisSet<Object> redisSet = new RedisSet<Object>(
annotation.of(), nest, field, model);
field.set(model, redisSet);
}
}
if (field.isAnnotationPresent(CollectionSortedSet.class)) {
Validator.checkValidCollection(field);
Set<Object> sortedSet = (Set<Object>) field.get(model);
if (sortedSet == null) {
CollectionSortedSet annotation = field
.getAnnotation(CollectionSortedSet.class);
RedisSortedSet<Object> redisSortedSet = new RedisSortedSet<Object>(
annotation.of(), annotation.by(), nest, field,
model);
field.set(model, redisSortedSet);
}
}
if (field.isAnnotationPresent(CollectionMap.class)) {
Validator.checkValidCollection(field);
Map<Object, Object> map = (Map<Object, Object>) field
.get(model);
if (map == null) {
CollectionMap annotation = field
.getAnnotation(CollectionMap.class);
RedisMap<Object, Object> redisMap = new RedisMap<Object, Object>(
annotation.key(), annotation.value(), nest,
field, model);
field.set(model, redisMap);
}
}
} catch (IllegalArgumentException e) {
throw new InvalidFieldException();
} catch (IllegalAccessException e) {
throw new InvalidFieldException();
}
}
}
static void loadId(final Object model, final Long id) {
if (model != null) {
boolean idFieldPresent = false;
for (Field field : gatherAllFields(model.getClass())) {
field.setAccessible(true);
if (field.isAnnotationPresent(Id.class)) {
idFieldPresent = true;
Validator.checkValidIdType(field);
try {
field.set(model, id);
} catch (IllegalArgumentException e) {
throw new JOhmException(e);
} catch (IllegalAccessException e) {
throw new JOhmException(e);
}
break;
}
}
if (!idFieldPresent) {
throw new JOhmException(
"JOhm does not support a Model without an Id");
}
}
}
static boolean detectJOhmCollection(final Field field) {
boolean isJOhmCollection = false;
if (field.isAnnotationPresent(CollectionList.class)
|| field.isAnnotationPresent(CollectionSet.class)
|| field.isAnnotationPresent(CollectionSortedSet.class)
|| field.isAnnotationPresent(CollectionMap.class)) {
isJOhmCollection = true;
}
return isJOhmCollection;
}
public static JOhmCollectionDataType detectJOhmCollectionDataType(
final Class<?> dataClazz) {
JOhmCollectionDataType type = null;
if (Validator.checkSupportedPrimitiveClazz(dataClazz)) {
type = JOhmCollectionDataType.PRIMITIVE;
} else {
try {
Validator.checkValidModelClazz(dataClazz);
type = JOhmCollectionDataType.MODEL;
} catch (JOhmException exception) {
// drop it
}
}
if (type == null) {
throw new JOhmException(dataClazz.getSimpleName()
+ " is not a supported JOhm Collection Data Type");
}
return type;
}
@SuppressWarnings("unchecked")
public static boolean isNullOrEmpty(final Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().equals(Collection.class)) {
return ((Collection) obj).size() == 0;
} else {
if (obj.toString().trim().length() == 0) {
return true;
}
}
return false;
}
static List<Field> gatherAllFields(Class<?> clazz, String... ignoring) {
List<Field> allFields = new ArrayList<Field>();
for (Field field : clazz.getDeclaredFields()) {
allFields.add(field);
}
while ((clazz = clazz.getSuperclass()) != null) {
allFields.addAll(gatherAllFields(clazz));
}
for (String ignore: ignoring) {
if (allFields.contains(ignore)) {
allFields.remove(ignore);
}
}
return Collections.unmodifiableList(allFields);
}
public static enum JOhmCollectionDataType {
PRIMITIVE, MODEL;
}
public final static class Convertor {
static Object convert(final Field field, final String value) {
return convert(field, field.getType(), value);
}
public static Object convert(final Class<?> type, String value) {
return convert(null, type, value);
}
public static Object convert(final Field field, final Class<?> type, final String value) {
if (type.equals(Byte.class) || type.equals(byte.class)) {
return new Byte(value);
}
if (type.equals(Character.class) || type.equals(char.class)) {
if (!isNullOrEmpty(value)) {
if (value.length() > 1) {
throw new IllegalArgumentException(
"Non-character value masquerading as characters in a string");
}
return value.charAt(0);
} else {
// This is the default value
return '\u0000';
}
}
if (type.equals(Short.class) || type.equals(short.class)) {
return new Short(value);
}
if (type.equals(Integer.class) || type.equals(int.class)) {
if (value == null) {
return 0;
}
return new Integer(value);
}
if (type.equals(Float.class) || type.equals(float.class)) {
if (value == null) {
return 0f;
}
return new Float(value);
}
if (type.equals(Double.class) || type.equals(double.class)) {
if (value == null) {
return 0d;
}
return new Double(value);
}
if (type.equals(Long.class) || type.equals(long.class)) {
if (value == null) {
return 0l;
}
return new Long(value);
}
if (type.equals(Boolean.class) || type.equals(boolean.class)) {
if (value == null) {
return false;
}
return new Boolean(value);
}
// Higher precision folks
if (type.equals(BigDecimal.class)) {
return new BigDecimal(value);
}
if (type.equals(BigInteger.class)) {
return new BigInteger(value);
}
if (type.isEnum() || type.equals(Enum.class)) {
return value == null ? null : Enum.valueOf((Class<Enum>)type, value);
}
if (type.equals(Date.class)) {
Attribute attr = field.getAnnotation(Attribute.class);
if (attr != null) {
try {
return new SimpleDateFormat(attr.date()).parse(value);
} catch (ParseException e) {
throw new IllegalArgumentException(
"Could not parse value as date `" + value + "` with pattern `" + attr.date() + "`.");
}
}
}
// Raw Collections are unsupported
if (type.equals(Collection.class)) {
return null;
}
// Raw arrays are unsupported
if (type.isArray()) {
return null;
}
return value;
}
}
static final class Validator {
static void checkValidAttribute(final Field field) {
Class<?> type = field.getType();
if ((type.equals(Byte.class) || type.equals(byte.class))
|| type.equals(Character.class) || type.equals(char.class)
|| type.equals(Short.class) || type.equals(short.class)
|| type.equals(Integer.class) || type.equals(int.class)
|| type.equals(Float.class) || type.equals(float.class)
|| type.equals(Double.class) || type.equals(double.class)
|| type.equals(Long.class) || type.equals(long.class)
|| type.equals(Boolean.class) || type.equals(boolean.class)
|| type.equals(BigDecimal.class)
|| type.equals(BigInteger.class)
|| type.equals(String.class)
|| type.equals(Date.class)
|| (type.isEnum() || type.equals(Enum.class))) {
} else {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a JOhm-supported Attribute");
}
}
static void checkValidReference(final Field field) {
if (!field.getType().getClass().isInstance(Model.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a subclass of Model");
}
}
static Long checkValidId(final Object model) {
Long id = null;
boolean idFieldPresent = false;
for (Field field : gatherAllFields(model.getClass())) {
field.setAccessible(true);
if (field.isAnnotationPresent(Id.class)) {
Validator.checkValidIdType(field);
try {
id = (Long) field.get(model);
idFieldPresent = true;
} catch (IllegalArgumentException e) {
throw new JOhmException(e);
} catch (IllegalAccessException e) {
throw new JOhmException(e);
}
break;
}
}
if (!idFieldPresent) {
throw new JOhmException(
"JOhm does not support a Model without an Id");
}
return id;
}
static void checkValidIdType(final Field field) {
Annotation[] annotations = field.getAnnotations();
if (annotations.length > 1) {
for (Annotation annotation : annotations) {
Class<?> annotationType = annotation.annotationType();
if (annotationType.equals(Id.class)) {
continue;
}
if (JOHM_SUPPORTED_ANNOTATIONS.contains(annotationType)) {
throw new JOhmException(
"Element annotated @Id cannot have any other JOhm annotations");
}
}
}
Class<?> type = field.getType().getClass();
if (!type.isInstance(Long.class) || !type.isInstance(long.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is annotated an Id but is not a long");
}
}
static boolean isIndexable(final String attributeName) {
// Prevent null/empty keys and null/empty values
if (!isNullOrEmpty(attributeName)) {
return true;
} else {
return false;
}
}
static void checkValidModel(final Object model) {
checkValidModelClazz(model.getClass());
}
static void checkValidModelClazz(final Class<?> modelClazz) {
if (!modelClazz.isAnnotationPresent(Model.class)) {
throw new JOhmException(
"Class pretending to be a Model but is not really annotated");
}
if (modelClazz.isInterface()) {
throw new JOhmException(
"An interface cannot be annotated as a Model");
}
}
static void checkValidCollection(final Field field) {
boolean isList = false, isSet = false, isMap = false, isSortedSet = false;
if (field.isAnnotationPresent(CollectionList.class)) {
checkValidCollectionList(field);
isList = true;
}
if (field.isAnnotationPresent(CollectionSet.class)) {
checkValidCollectionSet(field);
isSet = true;
}
if (field.isAnnotationPresent(CollectionSortedSet.class)) {
checkValidCollectionSortedSet(field);
isSortedSet = true;
}
if (field.isAnnotationPresent(CollectionMap.class)) {
checkValidCollectionMap(field);
isMap = true;
}
if (isList && isSet && isMap && isSortedSet) {
throw new JOhmException(
field.getName()
+ " can be declared a List or a Set or a SortedSet or a Map but not more than one type");
}
}
static void checkValidCollectionList(final Field field) {
if (!field.getType().getClass().isInstance(List.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a subclass of List");
}
}
static void checkValidCollectionSet(final Field field) {
if (!field.getType().getClass().isInstance(Set.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a subclass of Set");
}
}
static void checkValidCollectionSortedSet(final Field field) {
if (!field.getType().getClass().isInstance(Set.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a subclass of Set");
}
}
static void checkValidCollectionMap(final Field field) {
if (!field.getType().getClass().isInstance(Map.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is not a subclass of Map");
}
}
static void checkValidArrayBounds(final Field field, int actualLength) {
if (field.getAnnotation(Array.class).length() < actualLength) {
throw new JOhmException(
field.getType().getSimpleName()
+ " has an actual length greater than the expected annotated array bounds");
}
}
static void checkAttributeReferenceIndexRules(final Field field) {
boolean isAttribute = field.isAnnotationPresent(Attribute.class);
boolean isReference = field.isAnnotationPresent(Reference.class);
boolean isIndexed = field.isAnnotationPresent(Indexed.class);
if (isAttribute) {
if (isReference) {
throw new JOhmException(
field.getName()
+ " is both an Attribute and a Reference which is invalid");
}
if (isIndexed) {
if (!isIndexable(field.getName())) {
throw new InvalidFieldException();
}
}
if (field.getType().equals(Model.class)) {
throw new JOhmException(field.getType().getSimpleName()
+ " is an Attribute and a Model which is invalid");
}
checkValidAttribute(field);
}
if (isReference) {
checkValidReference(field);
}
}
public static boolean checkSupportedPrimitiveClazz(
final Class<?> primitiveClazz) {
return JOHM_SUPPORTED_PRIMITIVES.contains(primitiveClazz);
}
}
private static final Set<Class<?>> JOHM_SUPPORTED_PRIMITIVES = new HashSet<Class<?>>();
private static final Set<Class<?>> JOHM_SUPPORTED_ANNOTATIONS = new HashSet<Class<?>>();
static {
JOHM_SUPPORTED_PRIMITIVES.add(String.class);
JOHM_SUPPORTED_PRIMITIVES.add(Byte.class);
JOHM_SUPPORTED_PRIMITIVES.add(byte.class);
JOHM_SUPPORTED_PRIMITIVES.add(Character.class);
JOHM_SUPPORTED_PRIMITIVES.add(char.class);
JOHM_SUPPORTED_PRIMITIVES.add(Short.class);
JOHM_SUPPORTED_PRIMITIVES.add(short.class);
JOHM_SUPPORTED_PRIMITIVES.add(Integer.class);
JOHM_SUPPORTED_PRIMITIVES.add(int.class);
JOHM_SUPPORTED_PRIMITIVES.add(Float.class);
JOHM_SUPPORTED_PRIMITIVES.add(float.class);
JOHM_SUPPORTED_PRIMITIVES.add(Double.class);
JOHM_SUPPORTED_PRIMITIVES.add(double.class);
JOHM_SUPPORTED_PRIMITIVES.add(Long.class);
JOHM_SUPPORTED_PRIMITIVES.add(long.class);
JOHM_SUPPORTED_PRIMITIVES.add(Boolean.class);
JOHM_SUPPORTED_PRIMITIVES.add(boolean.class);
JOHM_SUPPORTED_PRIMITIVES.add(BigDecimal.class);
JOHM_SUPPORTED_PRIMITIVES.add(BigInteger.class);
JOHM_SUPPORTED_PRIMITIVES.add(Date.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Array.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Attribute.class);
JOHM_SUPPORTED_ANNOTATIONS.add(CollectionList.class);
JOHM_SUPPORTED_ANNOTATIONS.add(CollectionMap.class);
JOHM_SUPPORTED_ANNOTATIONS.add(CollectionSet.class);
JOHM_SUPPORTED_ANNOTATIONS.add(CollectionSortedSet.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Id.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Indexed.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Model.class);
JOHM_SUPPORTED_ANNOTATIONS.add(Reference.class);
}
}
|
package io.swagger.api;
import io.swagger.model.GenericError;
import io.swagger.model.InventoryItem;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import io.swagger.annotations.*;
import java.util.List;
@Path("/inventory")
@Api(description = "the inventory API")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2017-03-23T17:39:33.552Z")
public class InventoryApi {
@POST
@Consumes({ "application/json" })
@ApiOperation(value = "Adds a new item to the inventory", notes = "Duplicate SKUs will be rejected", response = void.class, tags={ "Inventory", })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Item created", response = void.class),
@ApiResponse(code = 400, message = "General Error", response = void.class) })
public Response addInventory(InventoryItem inventory) {
return Response.ok().entity("magic!").build();
}
@DELETE
@Path("/{sku}")
@ApiOperation(value = "Deletes an item by its SKU", notes = "", response = void.class, tags={ "Inventory", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Item successfully deleted", response = void.class) })
public Response deleteItemBySKU(@PathParam("sku") String sku) {
return Response.ok().entity("magic!").build();
}
@GET
@Produces({ "application/json" })
@ApiOperation(value = "Returns inventory from the system", notes = "longer description", response = InventoryItem.class, responseContainer = "List", tags={ "Inventory" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Returns the inventory for the query", response = InventoryItem.class, responseContainer = "List") })
public Response getInventory(@QueryParam("skip") Integer skip) {
return Response.ok().entity("magic!").build();
}
}
|
package com.gtracing.registros;
import com.gtracing.conexion.Conexion;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Leonel
*/
public class RegUser {
//Variables Globales
Conexion myConn = new Conexion();
PreparedStatement myPstat;
ResultSet myRs;
public int reguistroUsuario(String pNom, String sNom, String pApel, String sApel, String user, String pass, String dia, String mes, String anyo){
int isReg;
String fecha = formatoFecha(anyo, mes, dia);
try {
//Formateando la fecha para ingresarla a la bd
SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date myDate = formato.parse(fecha);
java.sql.Date sqlDate = new Date(myDate.getTime());
myConn.EstablecerConn();
myPstat = myConn.con.prepareStatement("INSERT INTO usuarioweb(pname, sname, papellido, sapellido, username, userpwd, fechanac) VALUES (?, ?, ?, ?, ?, ?, ?)");
myPstat.setString(1, pNom);
myPstat.setString(2, sNom);
myPstat.setString(3, pApel);
myPstat.setString(4, sApel);
myPstat.setString(5, user);
myPstat.setString(6, pass);
myPstat.setDate(7, sqlDate);
isReg = myPstat.executeUpdate();
myPstat.close();
} catch (SQLException | ParseException ex) {
Logger.getLogger(RegUser.class.getName()).log(Level.SEVERE, null, ex);
isReg = -1;
}
return isReg;
}
public int validacionUsuario(String usuario){
int existe;
try {
myConn.EstablecerConn();
myPstat = myConn.con.prepareStatement("select * from usuarioweb where username=?");
myPstat.setString(1, usuario);
existe = myPstat.executeUpdate();
myPstat.close();
} catch (SQLException ex) {
Logger.getLogger(RegUser.class.getName()).log(Level.SEVERE, null, ex);
existe = -1;
}
return existe;
}
public int ingresoCuenta(int idUser, int card, int secureCod, double cantidad){
int isIn;
try {
myConn.EstablecerConn();
myPstat = myConn.con.prepareStatement("INSERT INTO public.cuentacompras(idwebuser, tarjetabanco, securekey, cantidaddinero) VALUES (?, ?, ?, ?)");
myPstat.setInt(1, idUser);
myPstat.setInt(2, card);
myPstat.setInt(3, secureCod);
myPstat.setDouble(4, cantidad);
isIn = myPstat.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RegUser.class.getName()).log(Level.SEVERE, null, ex);
isIn = -1;
}
return isIn;
}
private String formatoFecha(String anyo, String mes, String dia) {
switch (mes) {
case "Enero":
mes = "01";
break;
case "Febrero":
mes = "02";
break;
case "Marzo":
mes = "03";
break;
case "Abril":
mes = "04";
break;
case "Mayo":
mes = "05";
break;
case "Junio":
mes = "06";
break;
case "Julio":
mes = "07";
break;
case "Agosto":
mes = "08";
break;
case "Septiembre":
mes = "09";
break;
case "Octubre":
mes = "10";
break;
case "Noviembre":
mes = "11";
break;
case "Diciembre":
mes = "12";
break;
}
return anyo + "-" + mes + "-" + dia;
}
public void close(){
myConn.CerrarConn();
}
}
|
package ie.dit;
/*
* This is our game class.
* Our game objects will be created here.
*/
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PVector;
import ddf.minim.AudioPlayer;
import ddf.minim.Minim;
public class Game {
String state = "ready";
PImage ready_img;
PApplet applet; // A reference to the PApplet class.
ArrayList<GameObject> objects;
Map map;
Player player;
int level = 0, lives = 3, score = 0, number_of_enemies = 0;
Minim minim; // Required to use Minim.
AudioPlayer snd_explode;
// We initialize the game by doing Game game = new Game(this)
// the 'this' argument is our PApplet window.
public Game(PApplet applet){
this.applet = applet;
this.applet.size(700, 700);
ready_img = applet.loadImage("data/start.jpg");
minim = new Minim(this.applet); // Required to use Minim.
snd_explode = minim.loadFile("data/explosion.wav");
// Our game objects.
map = new Map(this.applet);
player = new Player(this.applet);
// An ArrayList for our game objects.
objects = new ArrayList<GameObject>();
// Add the game objects to the ArrayList.
objects.add(map);
objects.add(player);
} // End constructor.
public void run(){
// ready.
if ( state == "ready" )
{
readyGame();
} // End ready.
// run.
if ( state == "run" )
{
runGame();
} // End run.
// over.
if ( state == "over" )
{
overGame();
} // End over.
} // End run.
public void keyPressed(){
if ( state == "ready" )
{
if(applet.keyCode == 83){ // Press 's' to start.
state = "run";
}
} // End ready.
if ( state == "run" )
{
player.keyPressed();
} // End run.
if ( state == "over" )
{
if(applet.keyCode == 82){ // Press 'r' to restart.
applet.setup();
}
} // End over.
} // End keyPressed.
public void keyReleased(){
player.keyReleased();
} // End keyPressed.
public void readyGame() {
applet.image(ready_img, 0, 0, applet.width, applet.height);
applet.textAlign(PApplet.CENTER);
applet.textSize( 26 );
applet.fill(0, 0, 0, 255);
applet.text("Instructions", (applet.width/2) + 3, 53);
applet.text("Use the arrow keys to control the player", (applet.width/2) + 3, 103);
applet.text("Press 'E' to fire", (applet.width/2) + 3, 153);
applet.fill(255, 255, 255, 255);
applet.text("Instructions", applet.width/2, 50);
applet.text("Use the arrow keys to control the player", applet.width/2, 100);
applet.text("Press 'E' to fire", applet.width/2, 150);
applet.noFill();
} // End readyGame.
public void runGame() {
set_level();
// Run all the game objects.
for (int i = 0; i < objects.size(); ++i) {
// The current object is an Enemy.
if(objects.get(i) instanceof Enemy){
Enemy enemy = (Enemy) objects.get(i);
// Enemy collides with Player.
if( collide(enemy, player) ){
float tmp = enemy.theta;
enemy.theta = player.theta;
player.theta = tmp;
player.health -= 10;
} // End Enemy collides with Player.
// Loop through the player's objects.
for (GameObject bullet : player.objects) {
// Player's bullet hits enemy.
if(collide(enemy, bullet)){
bullet.alive = false;
enemy.health -= 10;
score += 10;
break;
} // End Player's bullet hits enemy.
} // End Loop through the player's ammunition.
// Enemies bullet hits Player.
for (GameObject bullet : enemy.objects) {
if(collide(player, bullet)){
bullet.alive = false;
player.health -= 10;
break;
}
} // End Player's bullet hits enemy.
if(enemy.health <= 15)
enemy.objects.add(new Smoke(applet, enemy.location.x + (enemy.w/2), enemy.location.y + (enemy.h/2) ));
if (enemy.health <= 0) {
snd_explode.rewind();
snd_explode.play();
enemy.alive = false;
--number_of_enemies;
}
} // End The current object is an Enemy.
if(player.health <= 15)
player.objects.add(new Smoke(applet, player.location.x + (player.w/2), player.location.y + (player.h/2) ));
if (player.health <= 0 && lives > 0) {
--lives;
player.health = 50;
}
if(lives <= 0){
state = "over";
player.alive = false;
}
objects.get(i).run();
if (!objects.get(i).alive)
objects.remove(i);
} // End Run all the game objects.
draw_scores();
} // End runGame.
public void overGame(){ // this how the scores you get
map.run();
draw_scores();
applet.textAlign(PApplet.CENTER);
applet.textSize( 36 );
applet.fill(0, 0, 0, 255);
applet.text("Game Over", (applet.width/2) + 3, 303); // this show when when game is over
applet.text("Press 'R' to Restart", (applet.width/2) + 3, 353);
applet.fill(255, 255, 255, 255);
applet.text("Game Over", applet.width/2, 300);
applet.text("Press 'R' to Restart", applet.width/2, 350); // this pressing R to restart the game play
applet.noFill();
} // End overGame.
public void draw_scores() {
applet.textAlign(PApplet.LEFT);
applet.textSize( 26 );
applet.fill(255, 255, 255, 255);
applet.text("Lives " + lives, 30, 50);
applet.text("Level " + level, 30, 100);
applet.text("Score " + score, 30, 150);
applet.noFill();
} // End draw_scores.
public void set_level() {
if(number_of_enemies == 0){
++level;
createEnemies(level);
}
} // End set_level.
public void createEnemies( int amount ){ // create enemies
for ( int i = 0; i < amount; i++ ) {
Enemy enemy = new Enemy(this.applet);
Random random = new Random();
enemy.fireRate = random.nextFloat(); // the fire rate
enemy.theta = random.nextFloat() * 2 - 1;
enemy.colour = new Color(0, 100, 0, 255); // the color
enemy.location = new PVector(-500, -500);
objects.add(enemy);
++number_of_enemies; // add more enemies
}
} // End createEnemies method.
private boolean collide(GameObject obj1, GameObject obj2) { // the enemies method in which location it came
if(obj1.location.x + obj1.w > obj2.location.x &&
obj1.location.x < obj2.location.x + obj2.w &&
obj1.location.y + obj1.h > obj2.location.y &&
obj1.location.y < obj2.location.y + obj2.h){
return true;
}
return false;
} // End collide.
} // End Game class.
|
package com.legit2.Demigods.Listeners;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.legit2.Demigods.DDivineBlocks;
import com.legit2.Demigods.Demigods;
import com.legit2.Demigods.DTributeValue;
import com.legit2.Demigods.Database.DDatabase;
import com.legit2.Demigods.Utilities.DCharUtil;
import com.legit2.Demigods.Utilities.DConfigUtil;
import com.legit2.Demigods.Utilities.DDataUtil;
import com.legit2.Demigods.Utilities.DObjUtil;
import com.legit2.Demigods.Utilities.DPlayerUtil;
import com.legit2.Demigods.Utilities.DMiscUtil;
public class DDivineBlockListener implements Listener
{
static Demigods plugin;
public static double FAVORMULTIPLIER = DConfigUtil.getSettingDouble("global_favor_multiplier");
public static int RADIUS = 8;
public DDivineBlockListener(Demigods instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGH)
public void shrineBlockInteract(PlayerInteractEvent event)
{
// Return if the player is mortal
if(!DCharUtil.isImmortal(event.getPlayer())) return;
if(event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
// Define variables
Location location = event.getClickedBlock().getLocation();
Player player = event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
String charAlliance = DCharUtil.getAlliance(charID);
String charDeity = DCharUtil.getDeity(charID);
if(event.getClickedBlock().getType().equals(Material.GOLD_BLOCK) && event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK)
{
try
{
// Shrine created!
ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location);
DDivineBlocks.createShrine(charID, locations);
if(player.getItemInHand().getAmount() > 1)
{
ItemStack books = new ItemStack(player.getItemInHand().getType(), player.getInventory().getItemInHand().getAmount() - 1);
player.setItemInHand(books);
}
else player.getInventory().remove(Material.BOOK);
location.getWorld().getBlockAt(location).setType(Material.BEDROCK);
location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL);
location.getWorld().strikeLightningEffect(location);
player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased...");
player.sendMessage(ChatColor.GRAY + "A shrine has been created in the name of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!");
}
catch(Exception e)
{
// Creation of shrine failed...
e.printStackTrace();
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void shrineEntityInteract(PlayerInteractEntityEvent event)
{
// Define variables
Location location = event.getRightClicked().getLocation().subtract(0.5, 1.0, 0.5);
Player player = event.getPlayer();
// First handle admin wand
if(DMiscUtil.hasPermissionOrOP(player, "demigods.admin") && DDataUtil.hasPlayerData(player, "temp_admin_wand") && DDataUtil.getPlayerData(player, "temp_admin_wand").equals(true) && player.getItemInHand().getTypeId() == DConfigUtil.getSettingInt("admin_wand_tool"))
{
if(DDataUtil.hasPlayerData(player, "temp_destroy_shrine") && System.currentTimeMillis() < DObjUtil.toLong(DDataUtil.getPlayerData(player, "temp_destroy_shrine")))
{
// We can destroy the Shrine
event.getRightClicked().remove();
location.getBlock().setType(Material.AIR);
DDivineBlocks.removeShrine(location);
// Drop the block of gold and book
location.getWorld().dropItemNaturally(location, new ItemStack(Material.GOLD_BLOCK, 1));
location.getWorld().dropItemNaturally(location, new ItemStack(Material.BOOK, 1));
// Save Divine Blocks
DDatabase.saveDivineBlocks();
player.sendMessage(ChatColor.RED + "Shrine removed!");
return;
}
else
{
DDataUtil.savePlayerData(player, "temp_destroy_shrine", System.currentTimeMillis() + 5000);
player.sendMessage(ChatColor.RED + "If you want to destroy this shrine, please click it again.");
return;
}
}
// Return if the player is mortal
if(!DCharUtil.isImmortal(event.getPlayer())) event.getPlayer().sendMessage(ChatColor.RED + "Mortals can't do that!");
// More variables
int charID = DPlayerUtil.getCurrentChar(player);
try
{
// Check if block is divine
int shrineOwner = DDivineBlocks.getShrineOwner(location);
String shrineDeity = DDivineBlocks.getShrineDeity(location);
if(shrineDeity == null) return;
if(DDivineBlocks.isDivineBlock(location))
{
// Check if character has deity
if(DCharUtil.hasDeity(charID, shrineDeity))
{
// Open the tribute inventory
Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, "Shrine of " + shrineDeity);
player.openInventory(ii);
DDataUtil.saveCharData(charID, "temp_tributing", shrineOwner);
event.setCancelled(true);
return;
}
player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here.");
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerTribute(InventoryCloseEvent event)
{
try
{
if(!(event.getPlayer() instanceof Player)) return;
Player player = (Player)event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
String charDeity = DCharUtil.getDeity(charID);
if(!DCharUtil.isImmortal(player)) return;
// If it isn't a tribute chest then break the method
if(!event.getInventory().getName().contains("Shrine")) return;
// Get the creator of the shrine
//int shrineCreator = DDivineBlocks.getShrineOwner((Location) DDataUtil.getCharData(charID, "temp_tributing"));
DDataUtil.removeCharData(charID, "temp_tributing");
//calculate value of chest
int tributeValue = 0, items = 0;
for(ItemStack ii : event.getInventory().getContents())
{
if(ii != null)
{
tributeValue += DTributeValue.getTributeValue(ii);
items ++;
}
}
tributeValue *= FAVORMULTIPLIER;
// Process tributes and send messages
int favorBefore = DCharUtil.getMaxFavor(charID);
int devotionBefore = DCharUtil.getDevotion(charID);
DCharUtil.addMaxFavor(charID, tributeValue / 5);
DCharUtil.giveDevotion(charID, tributeValue);
DCharUtil.giveDevotion(charID, tributeValue / 7);
if(devotionBefore < DCharUtil.getDevotion(charID)) player.sendMessage(ChatColor.YELLOW + "Your devotion to " + charDeity + " has increased to " + DCharUtil.getDevotion(charID) + ".");
if(favorBefore < DCharUtil.getMaxFavor(charID)) player.sendMessage(ChatColor.YELLOW + "Your favor cap has increased to " + DCharUtil.getMaxFavor(charID) + ".");
// If they aren't good enough let them know
if((favorBefore == DCharUtil.getMaxFavor(charID)) && (devotionBefore == DCharUtil.getDevotion(charID)) && (items > 0)) player.sendMessage(ChatColor.YELLOW + "Your tributes were insufficient for " + charDeity + "'s blessings.");
// Clear the tribute case
event.getInventory().clear();
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGH)
public void divineBlockAlerts(PlayerMoveEvent event)
{
if(event.getFrom().distance(event.getTo()) < 0.1) return;
// Define variables
for(Location divineBlock : DDivineBlocks.getAllShrines())
{
OfflinePlayer charOwner = DCharUtil.getOwner(DDivineBlocks.getShrineOwner(divineBlock));
// Check for world errors
if(!divineBlock.getWorld().equals(event.getPlayer().getWorld())) return;
if(event.getFrom().getWorld() != divineBlock.getWorld()) return;
/*
* Entering
*/
if(event.getFrom().distance(divineBlock) > RADIUS)
{
if(divineBlock.distance(event.getTo()) <= RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have entered " + charOwner.getName() + "'s shrine to " + ChatColor.YELLOW + DDivineBlocks.getShrineDeity(divineBlock) + ChatColor.GRAY + ".");
return;
}
}
/*
* Leaving
*/
else if(event.getFrom().distance(divineBlock) <= RADIUS)
{
if(divineBlock.distance(event.getTo()) > RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have left a holy area.");
return;
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void stopDestroyEnderCrystal(EntityDamageEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getEntity().getLocation().subtract(0.5, 1.0, 0.5).equals(divineBlock))
{
event.setDamage(0);
event.setCancelled(true);
return;
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void stopDestroyDivineBlock(BlockBreakEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.getPlayer().sendMessage(ChatColor.YELLOW + "Divine blocks cannot be broken by hand.");
event.setCancelled(true);
return;
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockDamage(BlockDamageEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockIgnite(BlockIgniteEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockBurn(BlockBurnEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonExtend(BlockPistonExtendEvent event)
{
List<Block> blocks = event.getBlocks();
CHECKBLOCKS:
for(Block block : blocks)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals(divineBlock))
{
event.setCancelled(true);
break CHECKBLOCKS;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonRetract(BlockPistonRetractEvent event)
{
// Define variables
final Block block = event.getBlock().getRelative(event.getDirection(), 2);
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals((divineBlock)) && event.isSticky())
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void divineBlockExplode(final EntityExplodeEvent event)
{
try
{
// Remove divineBlock blocks from explosions
Iterator<Block> i = event.blockList().iterator();
while(i.hasNext())
{
Block block = i.next();
if(!DMiscUtil.canLocationPVP(block.getLocation())) i.remove();
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals(divineBlock)) i.remove();
}
}
}
catch (Exception er) {}
}
}
|
package redis.clients.util;
/**
* ""
*
* @author huagang.li 2014122 7:37:10
*/
public abstract class ShardInfo<T> {
private static final int DEFAULT_WEIGHT = 40;
private int weight;
/**
* ({@link #DEFAULT_WEIGHT})""
*/
public ShardInfo() {
this.weight = DEFAULT_WEIGHT;
}
/**
* ""
*
* @param weight
*/
public ShardInfo(int weight) {
this.weight = weight;
}
/**
*
*
* @return
*/
public int getWeight() {
return this.weight;
}
/**
*
*
* @return
*/
protected abstract T createResource();
/**
*
*
* @return
*/
public abstract String getName();
}
|
package com.github.davidmoten.geo;
import java.awt.Polygon;
import java.text.DecimalFormat;
import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* Encapsulates latitude, longitude and altitude. Provides great circle
* navigation methods. Immutable.
*
* @author dave
*
*/
public class Position {
/**
* Latitude of the position in degrees.
*/
private final double lat;
/**
* Longitude of the position in degrees.
*/
private final double lon;
/**
* Altitude in metres of the position.
*/
private final double altitudeMetres;
/**
* The radius of the Earth in km.
*/
private static final double radiusEarthKm = 6371.01;
// private static final double circumferenceEarthKm = 2.0 * Math.PI
// * radiusEarthKm;
/**
* @param lat
* in degrees
* @param lon
* in degrees
*/
public Position(double lat, double lon) {
this(lat, lon, 0.0);
}
/**
* @param lat
* in degrees
* @param lon
* in degrees
* @param altitudeMetres
* in metres
*/
public Position(double lat, double lon, double altitudeMetres) {
this.lat = lat;
this.lon = lon;
this.altitudeMetres = altitudeMetres;
}
/**
* Returns the latitude in decimal degrees.
*
* @return
*/
public final double getLat() {
return lat;
}
/**
* Returns the longitude in decimal degrees.
*
* @return
*/
public final double getLon() {
return lon;
}
/**
* Returns the altitue in metres.
*
* @return
*/
public final double getAlt() {
return altitudeMetres;
}
@Override
public final String toString() {
return "[" + lat + "," + lon + "]";
}
public final Position predict(double distanceKm, double courseDegrees) {
Preconditions
.checkArgument(Math.abs(altitudeMetres) < 0.000001,
"Predictions only valid for Earth's surface (position altitude must be zero)");
double dr = distanceKm / radiusEarthKm;
double latR = Math.toRadians(lat);
double lonR = Math.toRadians(lon);
double courseR = Math.toRadians(courseDegrees);
double lat2Radians = Math.asin(Math.sin(latR) * Math.cos(dr)
+ Math.cos(latR) * Math.sin(dr) * Math.cos(courseR));
double lon2Radians = Math.atan2(
Math.sin(courseR) * Math.sin(dr) * Math.cos(latR), Math.cos(dr)
- Math.sin(latR) * Math.sin(lat2Radians));
double lon3Radians = mod(lonR + lon2Radians + Math.PI, 2 * Math.PI)
- Math.PI;
return new Position(Math.toDegrees(lat2Radians),
Math.toDegrees(lon3Radians));
}
/**
* Returns the value in decimal degrees of a DMS (degrees minutes seconds)
* value.
*
* @param degrees
* @param minutes
* @param seconds
* @return
*/
public static double toDegrees(double degrees, double minutes,
double seconds) {
return degrees + minutes / 60.0 + seconds / 3600.0;
}
/**
* Returns the square of d.
*
* @param d
* @return
*/
private double sqr(double d) {
return d * d;
}
// public final Position[] getEarthLimb(int radials) {
// Position[] result = new Position[radials];
// double radialDegrees = 0.0;
// double incDegrees = 360.0 / radials;
// double quarterEarthKm = circumferenceEarthKm / 4.0;
// Position surfacePosition = new Position(this.lat, this.lon, 0.0);
// // Assert( this.alt>0.0, "getEarthLimb() requires Position a positive
// // altitude");
// for (int i = 0; i < radials; i++) {
// // TODO: base the distance on the altitude above the Earth
// result[i] = surfacePosition.predict(quarterEarthKm, radialDegrees);
// radialDegrees += incDegrees;
// return result;
/**
* returns distance between two WGS84 positions according to Vincenty's
* formula from Wikipedia
*
* @param position
* @return
*/
public final double getDistanceToKm(Position position) {
double lat1 = Math.toRadians(lat);
double lat2 = Math.toRadians(position.lat);
double lon1 = Math.toRadians(lon);
double lon2 = Math.toRadians(position.lon);
double deltaLon = lon2 - lon1;
double top = Math.sqrt(sqr(Math.cos(lat2) * Math.sin(deltaLon))
+ sqr(Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(deltaLon)));
double bottom = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1)
* Math.cos(lat2) * Math.cos(deltaLon);
double distance = radiusEarthKm * Math.atan2(top, bottom);
return Math.abs(distance);
}
/**
* Returns the Great Circle bearing to the given position from this.
*
* @param position
* @return
*/
public final double getBearingDegrees(Position position) {
double lat1 = Math.toRadians(lat);
double lat2 = Math.toRadians(position.lat);
double lon1 = Math.toRadians(lon);
double lon2 = Math.toRadians(position.lon);
double dLon = lon2 - lon1;
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double course = Math.toDegrees(Math.atan2(y, x));
if (course < 0)
course += 360;
return course;
}
/**
* Returns difference in degrees in the range -180 to 180
*
* @param bearing1
* degrees between -360 and 360
* @param bearing2
* degrees between -360 and 360
* @return
*/
public static double getBearingDifferenceDegrees(double bearing1,
double bearing2) {
if (bearing1 < 0)
bearing1 += 360;
if (bearing2 > 180)
bearing2 -= 360;
double result = bearing1 - bearing2;
if (result > 180)
result -= 360;
return result;
}
// public final double getDistanceKmToPath(Position p1, Position p2) {
// double d = radiusEarthKm
// * Math.asin(Math.sin(getDistanceToKm(p1) / radiusEarthKm)
// * Math.sin(Math.toRadians(getBearingDegrees(p1)
// - p1.getBearingDegrees(p2))));
// return Math.abs(d);
public static String toDegreesMinutesDecimalMinutesLatitude(double lat) {
long degrees = Math.round(Math.signum(lat) * Math.floor(Math.abs(lat)));
double remaining = Math.abs(lat - degrees);
remaining *= 60;
String result = Math.abs(degrees) + "" + (char) 0x00B0
+ new DecimalFormat("00.00").format(remaining) + "'"
+ (lat < 0 ? "S" : "N");
return result;
}
/**
* Returns a string representation of a longitude value in the format
* 00.00[W|E]. For example -25.3 is 25.30W
*
* @param lon
* @return
*/
public static String toDegreesMinutesDecimalMinutesLongitude(double lon) {
long degrees = Math.round(Math.signum(lon) * Math.floor(Math.abs(lon)));
double remaining = Math.abs(lon - degrees);
remaining *= 60;
String result = Math.abs(degrees) + "" + (char) 0x00B0
+ new DecimalFormat("00.00").format(remaining) + "'"
+ (lon < 0 ? "W" : "E");
return result;
}
/**
* Returns the modulus of y/x. This is like % for integers but is for
* doubles.
*
* @param y
* @param x
* @return
*/
@VisibleForTesting
static double mod(double y, double x) {
x = Math.abs(x);
int n = (int) (y / x);
double mod = y - x * n;
if (mod < 0) {
mod += x;
}
return mod;
}
/**
* Returns a position along a path according to the proportion value
*
* @param position
* @param proportion
* is between 0 and 1 inclusive
* @return
*/
public final Position getPositionAlongPath(Position position,
double proportion) {
if (proportion >= 0 && proportion <= 1) {
// Get bearing degrees for course
double courseDegrees = this.getBearingDegrees(position);
// Get distance from position arg and this objects location
double distanceKm = this.getDistanceToKm(position);
// Predict the position for a proportion of the course
// where this object is the start position and the arg
// is the destination position.
Position retPosition = this.predict(proportion * distanceKm,
courseDegrees);
return retPosition;
} else
throw new RuntimeException(
"Proportion must be between 0 and 1 inclusive");
}
// public final List<Position> getPositionsAlongPath(Position position,
// double maxSegmentLengthKm) {
// // Get distance from this to position
// double distanceKm = this.getDistanceToKm(position);
// List<Position> positions = new ArrayList<Position>();
// long numSegments = Math.round(Math.floor(distanceKm
// / maxSegmentLengthKm)) + 1;
// positions.add(this);
// for (int i = 1; i < numSegments; i++)
// positions.add(getPositionAlongPath(position, i
// / (double) numSegments));
// positions.add(position);
// return positions;
// public final Position to360() {
// double lat = this.lat;
// double lon = this.lon;
// if (lon < 0)
// lon += 360;
// return new Position(lat, lon);
/**
* normalize the lat lon values of this to ensure that no large longitude
* jumps are made from lastPosition (e.g. 179 to -180)
*
* @param lastPosition
*/
public final Position ensureContinuous(Position lastPosition) {
double lon = this.lon;
if (Math.abs(lon - lastPosition.lon) > 180) {
if (lastPosition.lon < 0)
lon -= 360;
else
lon += 360;
return new Position(lat, lon);
} else
return this;
}
public final boolean isWithin(List<Position> positions) {
Polygon polygon = new Polygon();
for (Position p : positions) {
polygon.addPoint(degreesToArbitraryInteger(p.lon),
degreesToArbitraryInteger(p.lat));
}
int x = degreesToArbitraryInteger(this.lon);
int y = degreesToArbitraryInteger(this.lat);
return polygon.contains(x, y);
}
private int degreesToArbitraryInteger(double d) {
return (int) Math.round(d * 3600);
}
@Override
public final boolean equals(Object o) {
if (o == null)
return false;
else if (o instanceof Position) {
Position p = (Position) o;
return p.lat == lat && p.lon == lon;
} else
return false;
}
@Override
public final int hashCode() {
return (int) (lat + lon);
}
public final double getDistanceToPathKm(List<Position> positions) {
if (positions.size() == 0)
throw new RuntimeException("positions must not be empty");
else if (positions.size() == 1)
return this.getDistanceToKm(positions.get(0));
else {
Double distance = null;
for (int i = 0; i < positions.size() - 1; i++) {
double d = getDistanceToSegmentKm(positions.get(i),
positions.get(i + 1));
if (distance == null || d < distance)
distance = d;
}
return distance;
}
}
public final double getDistanceToSegmentKm(Position p1, Position p2) {
return getDistanceToKm(getClosestIntersectionWithSegment(p1, p2));
}
public final Position getClosestIntersectionWithSegment(Position p1,
Position p2) {
if (p1.equals(p2))
return p1;
double d = getDistanceToKm(p1);
double bearing1 = p1.getBearingDegrees(this);
double bearing2 = p1.getBearingDegrees(p2);
double bearingDiff = bearing1 - bearing2;
double proportion = d * Math.cos(Math.toRadians(bearingDiff))
/ p1.getDistanceToKm(p2);
if (proportion < 0 || proportion > 1) {
if (d < getDistanceToKm(p2))
return p1;
else
return p2;
} else
return p1.getPositionAlongPath(p2, proportion);
}
/**
* @param path
* @param minDistanceKm
* @return
*/
public boolean isOutside(List<Position> path, double minDistanceKm) {
if (isWithin(path))
return false;
else {
double distance = getDistanceToPathKm(path);
return distance >= minDistanceKm;
}
}
public static Position create(double lat, double lon) {
return new Position(lat, lon);
}
/**
* Returns the difference between two longitude values. The returned value
* is always >=0.
*
* @param a
* @param b
* @return
*/
public static double longitudeDiff(double a, double b) {
a = to180(a);
b = to180(b);
if (a < b)
return a - b + 360;
else
return a - b;
}
/**
* Converts an angle in degrees to range -180< x <= 180.
*
* @param d
* @return
*/
public static double to180(double d) {
if (d < 0)
return -to180(Math.abs(d));
else {
if (d > 180) {
long n = Math.round(Math.floor((d + 180) / 360.0));
return d - n * 360;
} else
return d;
}
}
}
|
package com.legit2.Demigods.Listeners;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import com.legit2.Demigods.DConfig;
import com.legit2.Demigods.DDivineBlocks;
import com.legit2.Demigods.Demigods;
import com.legit2.Demigods.DTributeValue;
import com.legit2.Demigods.Utilities.DCharUtil;
import com.legit2.Demigods.Utilities.DDataUtil;
import com.legit2.Demigods.Utilities.DPlayerUtil;
import com.legit2.Demigods.Utilities.DMiscUtil;
public class DDivineBlockListener implements Listener
{
static Demigods plugin;
public static double FAVORMULTIPLIER = DConfig.getSettingDouble("globalfavormultiplier");
public static int RADIUS = 8;
public DDivineBlockListener(Demigods instance)
{
plugin = instance;
}
@EventHandler (priority = EventPriority.HIGH)
public void shrineInteract(PlayerInteractEvent event)
{
// Exit method if it isn't a block of gold or if the player is mortal
if(!DCharUtil.isImmortal(event.getPlayer())) return;
if(event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock().getType() != Material.GOLD_BLOCK) return;
// Define variables
Location location = event.getClickedBlock().getLocation();
Player player = event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
String charAlliance = DCharUtil.getAlliance(charID);
String charDeity = DCharUtil.getDeity(charID);
if(event.getAction() == Action.LEFT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.WRITTEN_BOOK)
{
// Define variables
ItemStack book = event.getPlayer().getItemInHand();
BookMeta bookMeta = (BookMeta) book.getItemMeta();
if(bookMeta.getTitle().equalsIgnoreCase(charDeity))
{
try
{
// Shrine created!
DDivineBlocks.createShrine(charID, location);
location.getWorld().strikeLightningEffect(location);
player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased...");
player.sendMessage(ChatColor.GRAY + "A shrine has been created in honor of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!");
}
catch(Exception e)
{
// Creation of shrine failed...
e.printStackTrace();
}
}
}
try
{
// Check if block is divine
String shrineDeity = DDivineBlocks.getDeityAtShrine(location);
if(shrineDeity == null) return;
// Check if character has deity
if(DCharUtil.hasDeity(charID, shrineDeity))
{
// Open the tribute inventory
Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, "Tributes");
player.openInventory(ii);
DDataUtil.saveCharData(charID, "temp_tributing", DDivineBlocks.getOwnerOfShrine(event.getClickedBlock().getLocation()));
event.setCancelled(true);
return;
}
player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here.");
}
catch(Exception e) {}
}
@EventHandler (priority = EventPriority.MONITOR)
public void playerTribute(InventoryCloseEvent event)
{
try
{
if(!(event.getPlayer() instanceof Player)) return;
Player player = (Player)event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
if(!DCharUtil.isImmortal(player)) return;
// If it isn't a tribute chest then break the method
if(!event.getInventory().getName().equals("Tributes")) return;
// Get the creator of the shrine
//int shrineCreator = DDivineBlocks.getOwnerOfShrine((Location) DDataUtil.getCharData(charID, "tributing_temp"));
DDataUtil.removeCharData(charID, "temp_tributing");
//calculate value of chest
int tirbuteValue = 0;
int items = 0;
for(ItemStack ii : event.getInventory().getContents())
{
if(ii != null)
{
tirbuteValue += DTributeValue.getTributeValue(ii);
items ++;
}
}
tirbuteValue *= FAVORMULTIPLIER;
// Give devotion
int devotionBefore = DCharUtil.getDevotion(charID);
DCharUtil.giveDevotion(charID, tirbuteValue);
DCharUtil.giveDevotion(charID, tirbuteValue / 7);
// Give favor
int favorBefore = DCharUtil.getMaxFavor(charID);
//DUtil.setFavorCap(player, DUtil.getFavorCap(username)+value/5); TODO
// Devotion lock TODO
String charName = DCharUtil.getName(charID);
if(devotionBefore < DCharUtil.getDevotion(charID)) player.sendMessage(ChatColor.YELLOW + "Your devotion to " + charName + " has increased to " + DCharUtil.getDevotion(charID) + ".");
if(favorBefore < DCharUtil.getMaxFavor(charID)) player.sendMessage(ChatColor.YELLOW + "Your favor cap has increased to " + DCharUtil.getMaxFavor(charID) + ".");
if((favorBefore == DCharUtil.getMaxFavor(charID)) && (devotionBefore == DCharUtil.getDevotion(charID)) && (items > 0)) player.sendMessage(ChatColor.YELLOW + "Your tributes were insufficient for " + charName + "'s blessings.");
// Clear the tribute case
event.getInventory().clear();
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void destroyDivineBlock(BlockBreakEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.getPlayer().sendMessage(ChatColor.YELLOW + "DivineBlocks cannot be broken by hand.");
event.setCancelled(true);
return;
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockDamage(BlockDamageEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockIgnite(BlockIgniteEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockBurn(BlockBurnEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonExtend(BlockPistonExtendEvent event)
{
List<Block> blocks = event.getBlocks();
DMiscUtil.serverMsg("Weiner 1");
CHECKBLOCKS:
for(Block block : blocks)
{
DMiscUtil.serverMsg("Weiner 2");
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
DMiscUtil.serverMsg("Weiner 3");
if(block.getLocation().equals(divineBlock))
{
DMiscUtil.serverMsg("Weiner 4");
event.setCancelled(true);
break CHECKBLOCKS;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonRetract(BlockPistonRetractEvent event)
{
// Define variables
final Block block = event.getBlock().getRelative(event.getDirection(), 2);
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals((divineBlock)) && event.isSticky())
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void divineBlockExplode(final EntityExplodeEvent event)
{
try
{
// Remove divineBlock blocks from explosions
Iterator<Block> i = event.blockList().iterator();
while(i.hasNext())
{
Block block = i.next();
if(!DMiscUtil.canLocationPVP(block.getLocation())) i.remove();
for(Location center : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals(center)) i.remove();
}
}
}
catch (Exception er) {}
}
@EventHandler(priority = EventPriority.HIGH)
public void divineBlockAlerts(PlayerMoveEvent event)
{
if(event.getFrom().distance(event.getTo()) < 0.1) return;
for(int charID : DMiscUtil.getImmortalList())
{
try
{
if(DDivineBlocks.getShrines(charID) != null)
{
// Define variables
OfflinePlayer charOwner = DCharUtil.getOwner(charID);
for(Location center : DDivineBlocks.getShrines(charID))
{
// Check for world errors
if(!center.getWorld().equals(event.getPlayer().getWorld())) return;
if(event.getFrom().getWorld() != center.getWorld()) return;
/*
* Outside coming in
*/
if(event.getFrom().distance(center) > RADIUS)
{
if(center.distance(event.getTo()) <= RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have entered " + charOwner.getName() + "'s divineBlock to " + ChatColor.YELLOW + DDivineBlocks.getDeityAtShrine(center) + ChatColor.GRAY + ".");
return;
}
}
/*
* Leaving
*/
else if(event.getFrom().distance(center) <= RADIUS)
{
if(center.distance(event.getTo()) > RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have left a divineBlock.");
return;
}
}
}
}
} catch(Exception e){}
}
}
}
|
package refinedstorage.tile;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import refinedstorage.RefinedStorage;
import refinedstorage.network.MessageTileContainerUpdate;
import refinedstorage.network.MessageTileUpdate;
public abstract class TileBase extends TileEntity implements ITickable {
public static final String NBT_DIRECTION = "Direction";
public static final String NBT_ENERGY = "Energy";
public static final int UPDATE_RANGE = 64;
private EnumFacing direction = EnumFacing.NORTH;
protected int ticks;
@Override
public void update() {
ticks++;
if (!worldObj.isRemote) {
if (this instanceof INetworkTile) {
TargetPoint target = new TargetPoint(worldObj.provider.getDimensionType().getId(), pos.getX(), pos.getY(), pos.getZ(), UPDATE_RANGE);
RefinedStorage.NETWORK.sendToAllAround(new MessageTileUpdate(this), target);
for (EntityPlayer player : worldObj.playerEntities) {
if (((INetworkTile) this).getContainer() == player.openContainer.getClass()) {
RefinedStorage.NETWORK.sendTo(new MessageTileContainerUpdate(this), (EntityPlayerMP) player);
}
}
}
}
}
public void setDirection(EnumFacing direction) {
this.direction = direction;
}
public EnumFacing getDirection() {
return direction;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
direction = EnumFacing.getFront(nbt.getInteger(NBT_DIRECTION));
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger(NBT_DIRECTION, direction.ordinal());
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger(NBT_DIRECTION, direction.ordinal());
return new SPacketUpdateTileEntity(pos, 1, nbt);
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
direction = EnumFacing.getFront(packet.getNbtCompound().getInteger(NBT_DIRECTION));
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {
return oldState.getBlock() != newState.getBlock();
}
public IInventory getDroppedInventory() {
return null;
}
}
|
package com.dreamfighter.android.manager;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.dreamfighter.android.enums.ActionMethod;
import com.dreamfighter.android.enums.ContentType;
import com.dreamfighter.android.enums.DownloadInfo;
import com.dreamfighter.android.enums.PayloadType;
import com.dreamfighter.android.enums.RequestInfo;
import com.dreamfighter.android.enums.RequestType;
import com.dreamfighter.android.log.Logger;
import com.dreamfighter.android.manager.RequestManager.RequestListeners;
import com.dreamfighter.android.manager.listeners.ConnectionListener;
/**
* this class used for request to the server and get the response back from @see ConnectionListener class
*
* @author fitra.adinugraha
*
*/
public class ConnectionManager{
private Context context;
private ConnectionListener connectionListener;
private RequestType requestType = RequestType.STRING;
private PayloadType payloadType = PayloadType.FORM;
private ContentType contentType = ContentType.APPLICATION_JSON;
private ActionMethod actionMethod = ActionMethod.GET;
private String rawPayload;
private List<NameValuePair> postParams = new ArrayList<NameValuePair>();
private Map<String,String> listHeader = new HashMap<String, String>();
private String url;
private boolean doUpload;
private File fileUpload;
private String fileNameUpload;
public interface ConnectionListener{
void onRequestBitmapComplete(ConnectionManager connectionManager,int requestCode,Bitmap bitmap);
void onRequestRawComplete(ConnectionManager connectionManager,int requestCode,Object object);
void onRequestComplete(ConnectionManager connectionManager,int requestCode,String resultString);
void onCustomRequest(ConnectionManager connectionManager,int requestCode,InputStream is);
void onRequestFailed(ConnectionManager connectionManager,int requestCode,RequestInfo info);
void onRequestComplete(RequestManager requestManager,
Boolean success, Bitmap bitmap, String resultString,
Object ressultRaw);
void requestOnProgress(ConnectionManager connectionManager,int requestCode, Long currentDownload);
}
public ConnectionManager(Context context) {
this.context = context;
}
public boolean isOnline(){
try {
ConnectivityManager __cm = (ConnectivityManager)context.getSystemService((Context.CONNECTIVITY_SERVICE));
NetworkInfo __ni = __cm.getActiveNetworkInfo();
int __netType = __ni.getType();
if (__ni!=null && __ni.isConnected()){
if (__netType==ConnectivityManager.TYPE_WIFI
|| __netType==ConnectivityManager.TYPE_MOBILE){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean isOnline(Context context){
try {
ConnectivityManager __cm = (ConnectivityManager)context.getSystemService((Context.CONNECTIVITY_SERVICE));
NetworkInfo __ni = __cm.getActiveNetworkInfo();
int __netType = __ni.getType();
if (__ni!=null && __ni.isConnected()){
if (__netType==ConnectivityManager.TYPE_WIFI
|| __netType==ConnectivityManager.TYPE_MOBILE){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* print all post parameter in the request
*
*/
public void printPostParam(){
for(NameValuePair valuePair:postParams){
Logger.log("["+valuePair.getName()+":"+valuePair.getValue()+"]");
}
}
/**
* request to the server with url and request code for get specific response if there is more than one
* request in time
*
* @param <code>url</code> server url that you want to request
* @param <code>requestCode</code> request code for specific request
*/
public void request(String url,final int requestCode){
final RequestManager req = new RequestManager(context);
if(actionMethod.equals(ActionMethod.POST) && !doUpload){
req.setPost(true);
req.setPostType(payloadType.getValue());
if(payloadType.equals(PayloadType.RAW)){
req.setRawStringPost(getRawPayload());
}else{
req.setPostParams(postParams);
}
}
req.setSecure(true);
req.setContentType(contentType.getValue());
req.setRequestType(requestType);
req.addHeadersData(listHeader);
if(doUpload){
req.setFileUploadName(fileNameUpload);
req.setPostParams(postParams);
req.setPost(true);
req.setFileUpload(fileUpload);
req.setUpload(true);
}
req.setRequestListeners(new RequestListeners() {
@Override
public void onRequestProgress(DownloadInfo requestInfo, Long currentDownload) {
if(connectionListener!=null){
Double total = 100.0 * currentDownload / req.getFilesize();
connectionListener.requestOnProgress(ConnectionManager.this,requestCode, total.longValue());
}
}
@Override
public void onRequestComplete(RequestManager requestManager,
Boolean success, Bitmap bitmap, String resultString,
Object ressultRaw) {
RequestType type = requestManager.getRequestType();
if(connectionListener!=null){
if(success){
if(type.equals(RequestType.BITMAP)){
connectionListener.onRequestBitmapComplete(ConnectionManager.this,requestCode,bitmap);
}else if(type.equals(RequestType.STRING)){
connectionListener.onRequestComplete(ConnectionManager.this,requestCode,resultString);
}else if(type.equals(RequestType.RAW)){
connectionListener.onRequestRawComplete(ConnectionManager.this,requestCode,ressultRaw);
}
}else{
connectionListener.onRequestFailed(ConnectionManager.this,requestCode, requestManager.getRequestInfo());
}
connectionListener.onRequestComplete(requestManager, success, bitmap, resultString, ressultRaw);
}
}
});
req.request(url);
}
/**
* request to the server with url
*
*
* @param <code>url</code> server url that you want to request
*/
public void request(String url){
request(url, this.hashCode());
}
public void request(){
if(url!=null){
request(this.url, this.hashCode());
}
}
public void upload(String url,String fileNameUpload,File fileUpload){
if(url!=null){
this.fileNameUpload = fileNameUpload;
this.url = url;
doUpload = true;
this.fileUpload = fileUpload;
request(this.url, this.hashCode());
}
}
public void request(int requestCode){
if(url!=null){
request(this.url, requestCode);
}
}
/**
* add post to request if post is true
* @param key <code>String</code> header key
* @param value <code>long</code> header value
*/
public void addPostData(String key,long value){
addPostData(key,String.valueOf(value));
}
/**
* add post to request if post is true
* @param key <code>String</code> header key
* @param value <code>double</code> header value
*/
public void addPostData(String key,double value){
addPostData(key,String.valueOf(value));
}
/**
* add post to request if post is true
* @param key <code>String</code> header key
* @param value <code>float</code> header value
*/
public void addPostData(String key,float value){
addPostData(key,String.valueOf(value));
}
/**
* add post to request if post is true
* @param key <code>String</code> header key
* @param value <code>int</code> header value
*/
public void addPostData(String key,int value){
addPostData(key,String.valueOf(value));
}
/**
* add post to request if post is true
* @param key <code>String</code> header key
* @param value <code>String</code> header value
*/
public void addPostData(String key,String value){
BasicNameValuePair newParams = new BasicNameValuePair(key, value);
this.postParams.add(newParams);
}
/**
* add header to request
* @param key <code>String</code> header key
* @param value <code>String</code> header value
*/
public void addHeaderData(String key,String value){
this.listHeader.put(key,value);
}
public void setHeadersData(Map<String,String> listHeader){
this.listHeader.putAll(listHeader);
}
public ConnectionListener getConnectionListener() {
return connectionListener;
}
/**
* call this method to get response from server
* @param connectionListener
*/
public void setConnectionListener(ConnectionListener connectionListener) {
this.connectionListener = connectionListener;
}
public RequestType getRequestType() {
return requestType;
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
public PayloadType getPayloadType() {
return payloadType;
}
public void setPayloadType(PayloadType payloadType) {
this.payloadType = payloadType;
}
public ContentType getContentType() {
return contentType;
}
public void setContentType(ContentType contentType) {
this.contentType = contentType;
}
public ActionMethod getActionMethod() {
return actionMethod;
}
/**
* set protocol type
* @see ActionMethod.POST will request with protocol POST
* or @see ActionMethod.GET will request with protocol GET
* @param actionMethod
*/
public void setActionMethod(ActionMethod actionMethod) {
this.actionMethod = actionMethod;
}
public String getRawPayload() {
return rawPayload;
}
/**
* call this method if you set the @see MethodType.POST and @see PayloadType.RAW
*
*
* @param <code>raw</code> the payload content it can be plain text, xml, or json
*/
public void setRawPayload(String raw) {
this.rawPayload = raw;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package ru.job4j.statistics;
import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Analize {
private List<User> previous = new ArrayList<>();
private List<User> current = new ArrayList<>();
/**
* User internal class.
*/
public static class User {
int id;
String name;
/**
* User constructor.
* @param name - String.
* @param id - int.
*/
public User(String name, int id) {
this.name = name;
this.id = id;
}
}
/**
* Info internal class.
*/
public static class Info {
int added = 0;
int changed = 0;
int deleted = 0;
/**
* Info constructor.
* @param added - int.
* @param deleted - int.
* @param changed - int.
*/
public Info(int added, int deleted, int changed) {
this.added = added;
this.changed = changed;
this.deleted = deleted;
}
}
/**
* diff.
* @return Info.
*/
public Info diff() {
int added = 0;
int changed =0;
HashMap<Integer, String> previousMap = new HashMap<>();
for (User shuttle : previous) {
previousMap.put(shuttle.id, shuttle.name);
}
for (User shuttle : current) {
String result = previousMap.remove(shuttle.id);
if (result == null) {
added++;
} else if (!result.equals(shuttle.name)) {
changed++;
}
}
int deleted = previousMap.size();
return new Info(added, deleted, changed);
}
/**
* backup.
*/
public void backup() {
previous.clear();
for (User shuttle : current) {
previous.add(new User(shuttle.name, shuttle.id));
}
}
/**
* findIndexByName.
* @param userName - String.
* @return int.
*/
private int findIndexByName(String userName) {
int result = -1;
for (User shuttle : current) {
result = shuttle.name.equals(userName) ? current.indexOf(shuttle) : -1;
if (result >= 0) {
break;
}
}
return result;
}
/**
* add.
* @param user - User.
* @return boolean.
*/
public boolean add(User user) {
boolean result = false;
if (this.current.size() != 0) {
for (User shuttle : current) {
if (shuttle.id == user.id) {
break;
} else {
result = true;
}
}
} else {
result = true;
}
if (result) {
this.current.add(user);
}
return result;
}
/**
* delete.
* @param userName - String.
* @return boolean.
*/
public boolean delete(String userName) {
boolean result = false;
int index = this.findIndexByName(userName);
if (index >= 0) {
this.current.remove(index);
result = true;
}
return result;
}
/**
* change.
* @param oldName - String.
* @param newName - String.
* @return boolean.
*/
public boolean change(String oldName, String newName) {
boolean result = false;
int index = this.findIndexByName(oldName);
if (index >= 0) {
User modUser = this.current.get(index);
modUser.name = newName;
this.current.set(index, modUser);
result = true;
}
return result;
}
}
|
package com.newrelic.metrics.publish.binding;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Provisional API which is subject to change.
* Represents a component that reported metrics will be associated with for a {@link Request}.
*/
public class ComponentData {
public String name;
public String guid;
private Date lastSuccessfulReportedAt;
/* package */ ComponentData() {
super();
}
/* package */ HashMap<String,Object> serialize(Request request) {
HashMap<String, Object> output = new HashMap<String, Object>();
List<MetricData> metrics = request.getMetrics(this);
if(!metrics.isEmpty()) {
output.put("name", name);
output.put("guid", guid);
output.put("duration", calculateDuration());
HashMap<String, Object> metricsOutput = new HashMap<String, Object>();
output.put("metrics", metricsOutput);
for (MetricData metric : metrics) {
metric.serialize(metricsOutput);
}
}
return output;
}
/**
* Set date timestamp for the last successful report
* @param lastSuccessfulReportedAt the date of the last successful report
*/
/* package */ void setLastSuccessfulReportedAt(Date lastSuccessfulReportedAt) {
this.lastSuccessfulReportedAt = lastSuccessfulReportedAt;
}
/**
* Calculate duration from last successful reported timestamp.
* If last timestamp isn't set, return 60 as default duration.
* Otherwise, return the time difference between now and the last successful reported timestamp.
* @return the duration
*/
private int calculateDuration() {
if (lastSuccessfulReportedAt == null) {
return 60; // default duration
}
long now = new Date().getTime();
// round up duration to whole second
long duration = (long) Math.ceil((now - lastSuccessfulReportedAt.getTime()) / 1000.0);
return (int) duration;
}
public String toString() {
return "ComponentData(" + name + ":" + guid + ")";
}
}
|
package ru.serce.jnrfuse;
import jnr.ffi.Pointer;
import jnr.ffi.Struct;
import jnr.ffi.annotations.Delegate;
import jnr.ffi.types.off_t;
import ru.serce.jnrfuse.struct.FileStat;
import java.nio.ByteBuffer;
/**
* Function to add an entry in a readdir() operation
*/
public interface FuseFillDir {
@Delegate
int apply(Pointer buf, ByteBuffer name, Pointer stbuf, @off_t long off);
/**
* Function to add an entry in a readdir() operation
*
* @param buf the buffer passed to the readdir() operation
* @param name the file name of the directory entry
* @param stbuf file attributes, can be NULL
* @param off offset of the next entry or zero
*
* @return 1 if buffer is full, zero otherwise
*/
default int apply(Pointer buf, String name, FileStat stbuf, @off_t long off) {
return apply(buf, ByteBuffer.wrap(name.getBytes()), stbuf == null ? null : Struct.getMemory(stbuf), off);
}
}
|
package io.branch.referral;
/**
* Define the Applications for the sharing the link with.
*/
public class SharingHelper {
/**
* <p>
* Defines the Application for sharing a deep link with.
* </p>
*/
public enum SHARE_WITH {
FACEBOOK("com.facebook.katana"),
FACEBOOK_MESSENGER("com.facebook.orca"),
TWITTER("com.twitter.android"),
MESSAGE(".mms"),
EMAIL("com.google.android.email"),
FLICKR("com.yahoo.mobile.client.android.flickr"),
GOOGLE_DOC("com.google.android.apps.docs"),
WHATS_APP("com.whatsapp"),
PINTEREST("com.pinterest"),
HANGOUT("com.google.android.talk"),
INSTAGRAM("com.instagram.android"),
WECHAT("jom.tencent.mm"),
GMAIL("com.google.android.gm");
private String name = "";
private SHARE_WITH(String key) {
this.name = key;
}
public String getAppName() {
return name;
}
@Override
public String toString() {
return name;
}
}
}
|
package com.imcode.imcms.config;
import com.imcode.db.Database;
import com.imcode.imcms.api.DocumentLanguages;
import com.imcode.imcms.api.MailService;
import com.imcode.imcms.components.Validator;
import com.imcode.imcms.domain.component.DocumentSearchQueryConverter;
import com.imcode.imcms.domain.dto.DocumentDTO;
import com.imcode.imcms.domain.dto.FileDocumentDTO;
import com.imcode.imcms.domain.dto.TextDocumentDTO;
import com.imcode.imcms.domain.dto.UrlDocumentDTO;
import com.imcode.imcms.domain.service.DocumentFileService;
import com.imcode.imcms.domain.service.DocumentService;
import com.imcode.imcms.domain.service.DocumentUrlService;
import com.imcode.imcms.domain.service.ImageService;
import com.imcode.imcms.domain.service.LanguageService;
import com.imcode.imcms.domain.service.TextDocumentTemplateService;
import com.imcode.imcms.domain.service.TextService;
import com.imcode.imcms.domain.service.api.FileDocumentService;
import com.imcode.imcms.domain.service.api.TextDocumentService;
import com.imcode.imcms.domain.service.api.UrlDocumentService;
import com.imcode.imcms.mapping.DocumentLanguageMapper;
import com.imcode.imcms.mapping.DocumentMapper;
import com.imcode.imcms.mapping.ImageCacheMapper;
import com.imcode.imcms.servlet.ImageCacheManager;
import com.imcode.imcms.util.l10n.CachingLocalizedMessageProvider;
import com.imcode.imcms.util.l10n.ImcmsPrefsLocalizedMessageProvider;
import com.imcode.imcms.util.l10n.LocalizedMessageProvider;
import imcode.server.Config;
import imcode.server.DefaultResolvingQueryIndex;
import imcode.server.LanguageMapper;
import imcode.server.LoggingDocumentIndex;
import imcode.server.PhaseQueryFixingDocumentIndex;
import imcode.server.document.index.DocumentIndex;
import imcode.server.document.index.DocumentIndexFactory;
import imcode.server.document.index.ResolvingQueryIndex;
import imcode.util.io.FileUtility;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.StandardEnvironment;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.util.Properties;
@Configuration
@PropertySource(value = {
"/WEB-INF/conf/server.properties",
"classpath:test.server.properties"},
name = "imcms.properties", ignoreResourceNotFound = true)
@Import({
DBConfig.class,
ApplicationConfig.class,
MappingConfig.class
})
@ComponentScan({
"com.imcode.imcms.domain",
"com.imcode.imcms.mapping",
"imcode.util",
"imcode.server",
"com.imcode.imcms.components",
"com.imcode.imcms.db",
})
class MainConfig {
private static final Logger LOG = Logger.getLogger(MainConfig.class);
// Required to be able to access properties file from environment at other configs
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public Properties imcmsProperties(StandardEnvironment env,
Validator<Properties> propertiesValidator,
@Value("WEB-INF/solr") File defaultSolrFolder) {
final Properties imcmsProperties = (Properties) env.getPropertySources().get("imcms.properties").getSource();
final String solrHome = defaultSolrFolder.getAbsolutePath();
imcmsProperties.setProperty("SolrHome", solrHome);
propertiesValidator.validate(imcmsProperties);
return imcmsProperties;
}
@Bean
public LocalizedMessageProvider createLocalizedMessageProvider() {
return new CachingLocalizedMessageProvider(new ImcmsPrefsLocalizedMessageProvider());
}
@Bean
public DocumentLanguages createDocumentLanguages(DocumentLanguageMapper languageMapper, Properties imcmsProperties) {
return DocumentLanguages.create(languageMapper, imcmsProperties);
}
@Bean //fixme: rewrite!
public Config createConfigFromProperties(Properties imcmsProperties) {
class WebappRelativeFileConverter implements Converter {
@SuppressWarnings("unchecked")
public File convert(Class type, Object value) {
return FileUtility.getFileFromWebappRelativePath((String) value);
}
}
final Config config = new Config();
ConvertUtils.register(new WebappRelativeFileConverter(), File.class);
final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(config);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (null == propertyDescriptor.getWriteMethod()) {
continue;
}
final String uncapitalizedPropertyName = propertyDescriptor.getName();
final String capitalizedPropertyName = StringUtils.capitalize(uncapitalizedPropertyName);
final String propertyValue = imcmsProperties.getProperty(capitalizedPropertyName);
if (null != propertyValue) {
try {
BeanUtils.setProperty(config, uncapitalizedPropertyName, propertyValue);
} catch (Exception e) {
LOG.error("Failed to set property " + capitalizedPropertyName, e.getCause());
continue;
}
}
try {
String setPropertyValue = BeanUtils.getProperty(config, uncapitalizedPropertyName);
if (null != setPropertyValue) {
LOG.info(capitalizedPropertyName + " = " + setPropertyValue);
} else {
LOG.warn(capitalizedPropertyName + " not set.");
}
} catch (Exception e) {
LOG.error(e, e);
}
}
return config;
}
@Bean
public MailService mailService(@Value("${SmtpServer}") String host, @Value("${SmtpPort}") int port) {
return new MailService(host, port);
}
@Bean
public ResolvingQueryIndex documentIndex(Database database, DocumentMapper documentMapper,
DocumentSearchQueryConverter documentSearchQueryConverter,
DocumentIndexFactory documentIndexFactory) {
final DocumentIndex index = documentIndexFactory.create();
final LoggingDocumentIndex documentIndex = new LoggingDocumentIndex(
database,
new PhaseQueryFixingDocumentIndex(index)
);
final DefaultResolvingQueryIndex resolvingQueryIndex = new DefaultResolvingQueryIndex(
documentIndex, documentSearchQueryConverter
);
documentMapper.setDocumentIndex(resolvingQueryIndex);
return resolvingQueryIndex;
}
@Bean
public DocumentService<TextDocumentDTO> textDocumentService(DocumentService<DocumentDTO> documentService,
TextDocumentTemplateService textDocumentTemplateService,
TextService textService,
ImageService imageService) {
return new TextDocumentService(documentService, textDocumentTemplateService, imageService, textService);
}
@Bean
public DocumentService<FileDocumentDTO> fileDocumentService(DocumentService<DocumentDTO> documentService,
DocumentFileService documentFileService,
Config config,
@Value("${FilePath}") File filesRoot) {
return new FileDocumentService(documentService, documentFileService, filesRoot, config);
}
@Bean
public DocumentService<UrlDocumentDTO> urlDocumentService(DocumentService<DocumentDTO> documentService,
DocumentUrlService documentUrlService) {
return new UrlDocumentService(documentService, documentUrlService);
}
@Bean
public LanguageMapper languageMapper(Database createDatabase,
LanguageService languageService,
Config config) {
return new LanguageMapper(createDatabase, config.getDefaultLanguage(), languageService);
}
@Bean
public ImageCacheManager imageCacheManager(ImageCacheMapper imageCacheMapper, Config config) {
return new ImageCacheManager(imageCacheMapper, config);
}
}
|
package com.kasije.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* CLI.
*/
public class KasijeCli
{
private List<KasijeCliUtility> utilities = new LinkedList<>();
private String helpCommand;
public List<KasijeCliUtility> getUtilities()
{
return utilities;
}
private void addUtility(KasijeCliUtility utility)
{
utilities.add(utility);
}
public void parseInput(String input)
{
String[] split = input.split(" ");
if (split.length == 0)
{
System.out.println(" Utility name missing.");
System.out.println(" Type help for help.");
}
else
{
processUtility(split);
}
}
public static void main(String[] args)
{
KasijeCli kasijeCli = new KasijeCli();
/* create */
KasijeCliUtility kuCreate = new KasijeCliUtility("create", "creates a site...");
kuCreate.addOption(new KasijeCliOption("engine", KasijeCliOptionStyle.WITH_ARGUMENT));
kuCreate.addOption(new KasijeCliOption("comp", KasijeCliOptionStyle.WITH_ARGUMENT));
kuCreate.setFirstMandatoryOptionName("siteName");
kuCreate.setKasijeCliExecutor(argumentValueMap ->
{
/* Do what needs to be done with create*/
System.out.println("Creating site " + argumentValueMap.get("siteName"));
System.out.println(" Using engine " + argumentValueMap.get("engine"));
System.out.println(" Component type " + argumentValueMap.get("comp"));
});
/* start */
KasijeCliUtility kuStart = new KasijeCliUtility("start", "start a site...");
kuStart.setKasijeCliExecutor(argumentValueMap ->
{
/* Do what needs to be done with start */
System.out.println(" Starting kasije server...");
});
/* Adding utilities*/
kasijeCli.addUtility(kuCreate);
kasijeCli.addUtility(kuStart);
kasijeCli.setHelpCommand("help");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
try
{
String input = console.readLine();
kasijeCli.parseInput(input);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
private void processUtility(String[] args)
{
/* Utility processing */
for (KasijeCliUtility utility : utilities)
{
if (utility.getName().equals(args[0]))
{
utility.process(Arrays.copyOfRange(args, 1, args.length));
return;
}
}
/* Help processing */
if (getHelpCommand() != null)
{
if (args[0].equals(getHelpCommand()))
{
if (args.length > 1)
{
for (KasijeCliUtility utility : utilities)
{
if (utility.getName().equals(args[1]))
{
System.out.println("NAME");
System.out.println(utility.getName() + " - " + utility.getOutline());
System.out.println(" ");
System.out.println("SYNOPSIS");
StringBuilder synopsisBuilder = new StringBuilder(utility.getName());
synopsisBuilder.append(" ");
if (utility.getFirstMandatoryOptionName() != null)
{
synopsisBuilder.append(String.format("<%s>", utility.getFirstMandatoryOptionName()));
synopsisBuilder.append(" ");
}
for (KasijeCliOption kasijeCliOption : utility.getKasijeCliOptions())
{
synopsisBuilder.append(String.format("[%s=<%s>] ", kasijeCliOption.getName(), kasijeCliOption.getName()));
}
System.out.println(synopsisBuilder.toString());
System.out.println(" ");
System.out.println("DESCRIPTION");
System.out.println(utility.getDescription());
return;
}
}
if (args[1].equals("help"))
{
System.out.println(":/");
return;
}
System.out.println(" No help for non-existent utility: " + args[1]);
System.out.println(" Type in help for more help");
return;
}
else
{
System.out.println("Available utilities are:");
for (KasijeCliUtility kasijeCliUtility : utilities)
{
System.out.println(" " + kasijeCliUtility.getName());
}
System.out.println(" Enter help followed by one of the above for further assistance.");
return;
}
}
}
System.out.println(" Ignoring unknown utility: " + args[0]);
System.out.println(" Type in help for help");
}
public String getHelpCommand()
{
return helpCommand;
}
public void setHelpCommand(String helpCommand)
{
this.helpCommand = helpCommand;
}
public static class KasijeCliUtility
{
private String name;
private String firstMandatoryOptionName;
private List<KasijeCliOption> kasijeCliOptions;
private String outline;
private KasijeCliExecutor kasijeCliExecutor;
private String description;
public KasijeCliUtility(String name, String outline)
{
this.name = name;
this.outline = outline;
kasijeCliOptions = new LinkedList<>();
}
public List<KasijeCliOption> getKasijeCliOptions()
{
return kasijeCliOptions;
}
public void setKasijeCliOptions(List<KasijeCliOption> kasijeCliOptions)
{
this.kasijeCliOptions = kasijeCliOptions;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getFirstMandatoryOptionName()
{
return firstMandatoryOptionName;
}
public void setFirstMandatoryOptionName(String firstMandatoryOptionName)
{
this.firstMandatoryOptionName = firstMandatoryOptionName;
}
public void addOption(KasijeCliOption kasijeCliOption)
{
kasijeCliOptions.add(kasijeCliOption);
}
public void setKasijeCliExecutor(KasijeCliExecutor kasijeCliExecutor)
{
this.kasijeCliExecutor = kasijeCliExecutor;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getOutline()
{
return outline;
}
public void setOutline(String outline)
{
this.outline = outline;
}
/* Receives options array */
public void process(String[] args)
{
Map<String, String> map = new HashMap<>();
/* Check if this utility have no options */
if (kasijeCliOptions.size() == 0)
{
if (kasijeCliExecutor != null)
{
kasijeCliExecutor.execute(map);
}
return;
}
/* Check if arguments does not suffice options */
if (args.length == 0)
{
System.out.format("Missing options for the %s utility", getName());
System.out.println(getOutline());
return;
}
/* Proceed to process options */
String[] arguments = args;
/* Obtaining mandatory option if required */
if (firstMandatoryOptionName != null)
{
/* Mandatory option always the first */
map.put(firstMandatoryOptionName, args[0]);
/* If other options, accommodate and proceed */
if (args.length > 1)
{
arguments = Arrays.copyOfRange(args, 1, args.length);
}
else
{
/* return */
if (kasijeCliExecutor != null)
{
kasijeCliExecutor.execute(map);
}
return;
}
}
int i = 1;
ARGS:
for (String arg : arguments)
{
String[] split = arg.split("=");
if (split.length != 2)
{
System.out.println(String.format(" Bad option at argument %d, assignment expression required.", i));
}
else
{
for (KasijeCliOption option : kasijeCliOptions)
{
if (split[0].equals(option.getName()))
{
map.put(option.getName(), split[1]);
continue ARGS;
}
}
System.out.println("Ignoring unrecognized option: " + split[0]);
}
}
if (kasijeCliExecutor != null)
{
kasijeCliExecutor.execute(map);
}
}
}
public static class KasijeCliOption
{
private String name;
private KasijeCliOptionStyle kasijeCliOptionStyle;
public KasijeCliOption(String name, KasijeCliOptionStyle kasijeCliOptionStyle)
{
this.name = name;
this.kasijeCliOptionStyle = kasijeCliOptionStyle;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
public interface KasijeCliExecutor
{
void execute(Map<String, String> argumentValueMap);
}
enum KasijeCliOptionStyle
{
SIMPLE,
WITH_ARGUMENT,
SPACED
}
}
|
package com.phraseapp.androidstudio.ui;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import com.phraseapp.androidstudio.*;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class ProjectConfigDialog extends DialogWrapper {
private Project project = null;
private PhraseAppConfiguration configuration;
private String clientPath;
private APIResourceListModel projects = new APIResourceListModel();
private APIResourceListModel locales = new APIResourceListModel();
private JPanel rootPanel;
private JTextField accessTokenTextField;
private JComboBox projectsComboBox;
private JComboBox defaultLocaleComboBox;
private JCheckBox uploadLocalesCheckbox;
private InfoPane infoPane;
public ProjectConfigDialog(Project project, String clientPath) {
super(project);
init();
setTitle("Create PhraseApp Configuration");
this.project = project;
this.clientPath = clientPath;
configuration = new PhraseAppConfiguration(project);
createInfoText(configuration);
initializeActions();
accessTokenTextField.setText(configuration.getAccessToken());
}
@Override
protected ValidationInfo doValidate(){
if (getSelectedProject().isEmpty()|| getSelectedLocale().isEmpty()) {
return new ValidationInfo("Please verify that you have entered a valid access token and selected a project and locale.", accessTokenTextField);
}
return null;
}
@Override
protected JComponent createCenterPanel() {
return rootPanel;
}
private void initializeActions() {
accessTokenTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent documentEvent) {
checkToken();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
checkToken();
}
@Override
public void changedUpdate(DocumentEvent documentEvent) {
}
private void checkToken() {
if (getAccessToken().length() == 64) {
updateProjectSelect();
} else {
resetLocaleSelect();
}
}
});
projectsComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
updateLocaleSelect();
}
}
});
infoPane.initializeActions();
accessTokenTextField.requestFocus();
}
private void createInfoText( PhraseAppConfiguration config) {
StringBuilder text = new StringBuilder();
text.append("<p>This dialog should help you generate a basic PhraseApp configuration file suitable for Android Apps.");
text.append(" The generated file can be modified manually to be suitable for more complex situation.</p>");
if (config.configExists()) {
text.append("<p>There already exists a PhraseApp configuration file. It will be <b>overwritten</b>!</p>");
}
infoPane.setContent(text.toString());
}
public void writeConfigFile() {
Map<String, Object> cmap = getConfigMap();
configuration.generateConfig(cmap);
if (uploadLocalesCheckbox.isSelected()) {
final API api = new API(clientPath, getAccessToken(), project);
ProjectLocalesUploader projectLocalesUploader = new ProjectLocalesUploader(project, getSelectedProject(), api);
if (projectLocalesUploader.detectedMissingRemoteLocales()) {
projectLocalesUploader.upload();
}
}
}
private void resetProjectSelect() {
projects = new APIResourceListModel();
projectsComboBox.setModel(projects);
projectsComboBox.setEnabled(false);
}
private void updateProjectSelect() {
API api = new API(clientPath, getAccessToken(), project);
projects = api.getProjects();
if (projects.isValid()) {
if (projects.isEmpty()) {
int choice = JOptionPane.showOptionDialog(null,
"No projects found. Should we create an initial project for you?",
"PhraseApp",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null);
if (choice == JOptionPane.YES_OPTION) {
projects = api.postProjects(project.getName());
if (!projects.isValid()) {
JOptionPane.showMessageDialog(rootPanel, "Could not create new project. Please verify that you have added a valid Access Token. " + projects.getErrors());
}
}
}
if (projects.isEmpty()) {
resetProjectSelect();
resetLocaleSelect();
} else {
projectsComboBox.setModel(projects);
projectsComboBox.setEnabled(true);
projectsComboBox.setSelectedIndex(getProjectIndex());
}
} else {
resetLocaleSelect();
resetProjectSelect();
JOptionPane.showMessageDialog(rootPanel, "Could not fetch projects from PhraseApp. Please verify that you have added a valid Access Token. " + projects.getErrors());
}
}
private void resetLocaleSelect() {
locales = new APIResourceListModel();
defaultLocaleComboBox.setModel(locales);
defaultLocaleComboBox.setEnabled(false);
}
private void updateLocaleSelect() {
API api = new API(clientPath, getAccessToken(), project);
if (!getSelectedProject().isEmpty()) {
locales = api.getLocales(getSelectedProject());
if (locales.isValid()) {
if (locales.isEmpty()) {
String[] localesList = {"en", "de", "fr", "es", "it", "pt", "zh"};
String localeName = (String) JOptionPane.showInputDialog(rootPanel,
"No locales found. What is the name of the locale we should create for you?",
"PhraseApp",
JOptionPane.QUESTION_MESSAGE,
null,
localesList,
localesList[0]);
locales = api.postLocales(getSelectedProject(), localeName);
if (!locales.isValid()) {
JOptionPane.showMessageDialog(rootPanel, "Could not create locale. Please verify that you have added a valid Access Token." + locales.getErrors());
}
}
if (locales.isEmpty()) {
resetLocaleSelect();
} else {
defaultLocaleComboBox.setModel(locales);
defaultLocaleComboBox.setSelectedIndex(getLocaleIndex());
defaultLocaleComboBox.setEnabled(true);
}
} else {
JOptionPane.showMessageDialog(rootPanel, "Could not fetch locales. Please verify that you have added a valid Access Token." + locales.getErrors());
}
}
}
@NotNull
private String getAccessToken() {
return accessTokenTextField.getText().trim();
}
private String getSelectedProject() {
if (projectsComboBox.getSelectedIndex() == -1) {
return "";
}
APIResource project = projects.getModelAt(
projectsComboBox.getSelectedIndex());
return project.getId();
}
private String getSelectedLocale() {
if (defaultLocaleComboBox.getSelectedIndex() == -1) {
return "";
}
APIResource locale = locales.getModelAt(
defaultLocaleComboBox.getSelectedIndex());
return locale.getId();
}
private int getProjectIndex() {
String projectId = configuration.getProjectId();
if (projectId != null) {
for (int i = 0; i < projects.getSize(); i++) {
APIResource model = projects.getModelAt(i);
if (model.getId().equals(projectId)) {
return projects.getIndexOf(model);
}
}
}
return 0;
}
private int getLocaleIndex() {
String localeId = configuration.getLocaleId();
if (localeId != null) {
for (int i = 0; i < locales.getSize(); i++) {
APIResource model = locales.getModelAt(i);
if (model.getId().equals(localeId)) {
return locales.getIndexOf(model);
}
}
}
return 0;
}
private Map<String, Object> getConfigMap() {
Map<String, Object> base = new HashMap<String, Object>();
Map<String, Object> root = new TreeMap<String, Object>();
Map<String, Object> pull = new HashMap<String, Object>();
Map<String, Object> push = new HashMap<String, Object>();
Map<String, Object> pullFile = new HashMap<String, Object>();
Map<String, Object> pushFile = new HashMap<String, Object>();
Map<String, Object> pushParams = new HashMap<String, Object>();
pushParams.put("locale_id", getSelectedLocale());
pushFile.put("params", pushParams);
String defaultLocalePath = "./app/src/main/res/values/strings.xml";
pushFile.put("file", defaultLocalePath);
pullFile.put("file", getPullPath(defaultLocalePath));
push.put("sources", new Map[]{pushFile});
pull.put("targets", new Map[]{pullFile});
root.put("push", push);
root.put("pull", pull);
root.put("project_id", getSelectedProject());
root.put("access_token", getAccessToken());
root.put("file_format", "xml");
base.put("phraseapp", root);
return base;
}
private String getPullPath(String defaultLocalePath) {
return defaultLocalePath.replaceAll("values", "values-<locale_name>");
}
}
|
package seedu.tasklist.ui;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import seedu.tasklist.commons.core.Config;
import seedu.tasklist.commons.core.GuiSettings;
import seedu.tasklist.commons.events.ui.ExitAppRequestEvent;
import seedu.tasklist.commons.util.FxViewUtil;
import seedu.tasklist.logic.Logic;
import seedu.tasklist.model.UserPrefs;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart<Region> {
private static final String ICON = "/images/address_book_32.png";
private static final String FXML = "MainWindow.fxml";
private static final int MIN_HEIGHT = 600;
private static final int MIN_WIDTH = 450;
private Stage primaryStage;
private Logic logic;
// Independent Ui parts residing in this Ui container
private TaskListPanel taskListPanel;
private Config config;
private UpcomingTaskPanel upcomingTaskPanel;
@FXML
private AnchorPane upcomingTaskPlaceholder;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane taskListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
public MainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
super(FXML);
// Set dependencies
this.primaryStage = primaryStage;
this.logic = logic;
this.config = config;
// Configure the UI
setTitle(config.getAppTitle());
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
Scene scene = new Scene(getRoot());
primaryStage.setScene(scene);
setAccelerators();
}
public Stage getPrimaryStage() {
return primaryStage;
}
private void setAccelerators() {
setAccelerator(helpMenuItem, KeyCombination.valueOf("F1"));
}
/**
* Sets the accelerator of a MenuItem.
* @param keyCombination the KeyCombination value of the accelerator
*/
private void setAccelerator(MenuItem menuItem, KeyCombination keyCombination) {
menuItem.setAccelerator(keyCombination);
getRoot().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getTarget() instanceof TextInputControl && keyCombination.match(event)) {
menuItem.getOnAction().handle(new ActionEvent());
event.consume();
}
});
}
void fillInnerParts() {
upcomingTaskPanel = new UpcomingTaskPanel(getUpcomingTaskListPlaceholder(), logic.getTodayTaskList(),
logic.getTomorrowTaskList());
taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
new ResultDisplay(getResultDisplayPlaceholder());
new StatusBarFooter(getStatusbarPlaceholder(), config.getTaskListFilePath());
new CommandBox(getCommandBoxPlaceholder(), logic);
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
private AnchorPane getTaskListPlaceholder() {
return taskListPanelPlaceholder;
}
private AnchorPane getUpcomingTaskListPlaceholder() {
return upcomingTaskPlaceholder;
}
void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the given image as the icon of the main window.
* @param iconSource e.g. {@code "/images/help_icon.png"}
*/
private void setIcon(String iconSource) {
FxViewUtil.setStageIcon(primaryStage, iconSource);
}
/**
* Sets the default size based on user preferences.
*/
private void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = new HelpWindow();
helpWindow.show();
}
void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.taskListPanel;
}
}
|
package com.jaamsim.Graphics;
import java.util.ArrayList;
import java.util.HashMap;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.DisplayModels.ImageModel;
import com.jaamsim.DisplayModels.TextModel;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.basicsim.ObjectType;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.EntityInput;
import com.jaamsim.input.EntityListInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.KeywordIndex;
import com.jaamsim.input.Output;
import com.jaamsim.input.RelativeEntityInput;
import com.jaamsim.input.Vec3dInput;
import com.jaamsim.math.Color4d;
import com.jaamsim.math.Mat4d;
import com.jaamsim.math.Quaternion;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec3d;
import com.jaamsim.render.DisplayModelBinding;
import com.jaamsim.render.HasScreenPoints;
import com.jaamsim.render.RenderUtils;
import com.jaamsim.units.AngleUnit;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.DistanceUnit;
/**
* Encapsulates the methods and data needed to display a simulation object in the 3D environment.
* Extends the basic functionality of entity in order to have access to the basic system
* components like the eventManager.
*/
public class DisplayEntity extends Entity {
@Keyword(description = "The point in the region at which the alignment point of the object is positioned.",
example = "Object1 Position { -3.922 -1.830 0.000 m }")
protected final Vec3dInput positionInput;
@Keyword(description = "The size of the object in { x, y, z } coordinates. If only the x and y coordinates are given " +
"then the z dimension is assumed to be zero.",
example = "Object1 Size { 15 12 0 m }")
private final Vec3dInput sizeInput;
@Keyword(description = "Euler angles defining the rotation of the object.",
example = "Object1 Orientation { 0 0 90 deg }")
private final Vec3dInput orientationInput;
@Keyword(description = "The point within the object about which its Position keyword is defined, " +
"expressed with respect to a unit box centered about { 0 0 0 }.",
example = "Object1 Alignment { -0.5 -0.5 0.0 }")
private final Vec3dInput alignmentInput;
@Keyword(description = "The name of the Region containing the object. Applies an offset " +
"to the Position of the object corresponding to the Region's " +
"Position and Orientation values.",
example ="Object1 Region { Region1 }")
private final EntityInput<Region> regionInput;
private final Vec3d position = new Vec3d();
private final Vec3d size = new Vec3d(1.0d, 1.0d, 1.0d);
private final Vec3d orient = new Vec3d();
private final Vec3d align = new Vec3d();
private final ArrayList<DisplayModel> displayModelList = new ArrayList<>();
private Region currentRegion;
@Keyword(description = "The graphic representation of the object. Accepts a list of objects where the distances defined in " +
"LevelOfDetail dictate which DisplayModel entry is used.",
example = "Object1 DisplayModel { Pixels }")
private final EntityListInput<DisplayModel> displayModelListInput;
@Keyword(description = "The name of an object with respect to which the Position keyword is referenced.",
example ="Object1Label RelativeEntity { Object1 }")
private final RelativeEntityInput relativeEntity;
@Keyword(description = "If TRUE, the object is displayed in the simulation view windows.",
example = "Object1 Show { FALSE }")
private final BooleanInput show;
@Keyword(description = "If TRUE, the object is active and used in simulation runs.",
example = "Object1 Active { FALSE }")
private final BooleanInput active;
@Keyword(description = "If TRUE, the object can be positioned interactively using the GUI.",
example = "Object1 Movable { FALSE }")
private final BooleanInput movable;
private ArrayList<DisplayModelBinding> modelBindings;
private final HashMap<String, Tag> tagMap = new HashMap<>();
{
positionInput = new Vec3dInput("Position", "Basic Graphics", new Vec3d());
positionInput.setUnitType(DistanceUnit.class);
this.addInput(positionInput);
alignmentInput = new Vec3dInput("Alignment", "Basic Graphics", new Vec3d());
this.addInput(alignmentInput);
sizeInput = new Vec3dInput("Size", "Basic Graphics", new Vec3d(1.0d, 1.0d, 1.0d));
sizeInput.setUnitType(DistanceUnit.class);
sizeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(sizeInput);
orientationInput = new Vec3dInput("Orientation", "Basic Graphics", new Vec3d());
orientationInput.setUnitType(AngleUnit.class);
this.addInput(orientationInput);
regionInput = new EntityInput<>(Region.class, "Region", "Basic Graphics", null);
this.addInput(regionInput);
relativeEntity = new RelativeEntityInput("RelativeEntity", "Basic Graphics", null);
relativeEntity.setEntity(this);
this.addInput(relativeEntity);
displayModelListInput = new EntityListInput<>( DisplayModel.class, "DisplayModel", "Basic Graphics", null);
this.addInput(displayModelListInput);
displayModelListInput.setUnique(false);
active = new BooleanInput("Active", "Basic Graphics", true);
this.addInput(active);
show = new BooleanInput("Show", "Basic Graphics", true);
this.addInput(show);
movable = new BooleanInput("Movable", "Basic Graphics", true);
this.addInput(movable);
}
/**
* Constructor: initializing the DisplayEntity's graphics
*/
public DisplayEntity() {
for (ObjectType type : ObjectType.getAll()) {
if (type.getJavaClass() == this.getClass()) {
// Set the default DisplayModel
displayModelListInput.setDefaultValue(type.getDefaultDisplayModel());
this.setDisplayModelList(type.getDefaultDisplayModel());
// Set the default size
sizeInput.setDefaultValue(type.getDefaultSize());
this.setSize(type.getDefaultSize());
// Set the default Alignment
alignmentInput.setDefaultValue(type.getDefaultAlignment());
this.setAlignment(type.getDefaultAlignment());
break;
}
}
}
@Override
public void earlyInit() {
super.earlyInit();
this.resetGraphics();
}
/**
* Restores the initial appearance of this entity.
*/
public void resetGraphics() {
this.setPosition(positionInput.getValue());
this.setSize(sizeInput.getValue());
this.setAlignment(alignmentInput.getValue());
this.setOrientation(orientationInput.getValue());
this.setDisplayModelList(displayModelListInput.getValue());
this.setRegion(regionInput.getValue());
}
@Override
public void validate()
throws InputErrorException {
super.validate();
if (getDisplayModelList() != null) {
for (DisplayModel dm : getDisplayModelList()) {
if (!dm.canDisplayEntity(this)) {
error("Invalid DisplayModel: %s for this DisplayEntity", dm.getName());
}
}
}
}
@Override
public void setInputsForDragAndDrop() {
// Determine whether the entity should sit on top of the x-y plane
boolean alignBottom = true;
ArrayList<DisplayModel> displayModels = displayModelListInput.getValue();
if (displayModels != null && displayModels.size() > 0) {
DisplayModel dm0 = displayModels.get(0);
if (dm0 instanceof DisplayModelCompat || dm0 instanceof ImageModel || dm0 instanceof TextModel )
alignBottom = false;
}
if (this instanceof Graph || this instanceof HasScreenPoints || this instanceof Region) {
alignBottom = false;
}
if (alignBottom) {
ArrayList<String> tokens = new ArrayList<>();
tokens.add("0.0");
tokens.add("0.0");
tokens.add("-0.5");
KeywordIndex kw = new KeywordIndex("Alignment", tokens, null);
InputAgent.apply(this, kw);
}
}
/**
* Destroys the branchGroup hierarchy for the entity
*/
@Override
public void kill() {
super.kill();
currentRegion = null;
}
public Region getCurrentRegion() {
return currentRegion;
}
/**
* Removes the entity from its current region and assigns a new region
* @param newRegion - the region the entity will be assigned to
*/
public void setRegion( Region newRegion ) {
currentRegion = newRegion;
}
/**
* Update any internal stated needed by either renderer. This is a transition method to get away from
* java3D onto the new renderer.
*
* The JaamSim renderer will only call updateGraphics() while the Java3D renderer will call both
* updateGraphics() and render()
*/
public void updateGraphics(double simTime) {
}
private void calculateEulerRotation(Vec3d val, Vec3d euler) {
double sinx = Math.sin(euler.x);
double siny = Math.sin(euler.y);
double sinz = Math.sin(euler.z);
double cosx = Math.cos(euler.x);
double cosy = Math.cos(euler.y);
double cosz = Math.cos(euler.z);
// Calculate a 3x3 rotation matrix
double m00 = cosy * cosz;
double m01 = -(cosx * sinz) + (sinx * siny * cosz);
double m02 = (sinx * sinz) + (cosx * siny * cosz);
double m10 = cosy * sinz;
double m11 = (cosx * cosz) + (sinx * siny * sinz);
double m12 = -(sinx * cosz) + (cosx * siny * sinz);
double m20 = -siny;
double m21 = sinx * cosy;
double m22 = cosx * cosy;
double x = m00 * val.x + m01 * val.y + m02 * val.z;
double y = m10 * val.x + m11 * val.y + m12 * val.z;
double z = m20 * val.x + m21 * val.y + m22 * val.z;
val.set3(x, y, z);
}
public Vec3d getPositionForAlignment(Vec3d alignment) {
Vec3d temp = new Vec3d(alignment);
synchronized (position) {
temp.sub3(align);
temp.mul3(size);
calculateEulerRotation(temp, orient);
temp.add3(position);
}
return temp;
}
public Vec3d getGlobalPositionForAlignment(Vec3d alignment) {
Vec3d temp = new Vec3d(alignment);
synchronized (position) {
temp.sub3(align);
temp.mul3(size);
calculateEulerRotation(temp, orient);
temp.add3(this.getGlobalPosition());
}
return temp;
}
public Vec3d getOrientation() {
synchronized (position) {
return new Vec3d(orient);
}
}
public void setOrientation(Vec3d orientation) {
synchronized (position) {
orient.set3(orientation);
}
}
public void setSize(Vec3d size) {
synchronized (position) {
this.size.set3(size);
}
}
public Vec3d getPosition() {
synchronized (position) {
return new Vec3d(position);
}
}
public DisplayEntity getRelativeEntity() {
return relativeEntity.getValue();
}
/**
* Returns the transform to global space including the region transform
* @return
*/
public Transform getGlobalTrans(double simTime) {
return getGlobalTransForSize(size, simTime);
}
/**
* Returns the equivalent global transform for this entity as if 'sizeIn' where the actual
* size.
* @param sizeIn
* @param simTime
* @return
*/
public Transform getGlobalTransForSize(Vec3d sizeIn, double simTime) {
// Okay, this math may be hard to follow, this is effectively merging two TRS transforms,
// The first is a translation only transform from the alignment parameter
// Then a transform is built up based on position and orientation
// As size is a non-uniform scale it can not be represented by the jaamsim TRS Transform and therefore
// not actually included in this result, except to adjust the alignment
// Alignment and Size transformations
Vec3d temp = new Vec3d(sizeIn);
temp.mul3(align);
temp.scale3(-1.0d);
Transform alignTrans = new Transform(temp);
// Orientation transformation
Quaternion rot = new Quaternion();
rot.setEuler3(orient);
Transform ret = new Transform(null, rot, 1);
// Combine the alignment, size, and orientation tranformations
ret.merge(ret, alignTrans);
// Convert the alignment/size/orientation transformation to the global coordinate system
if (currentRegion != null)
ret.merge(currentRegion.getRegionTransForVectors(), ret);
// Offset the transformation by the entity's global position vector
ret.getTransRef().add3(getGlobalPosition());
return ret;
}
/**
* Returns the global transform with scale factor all rolled into a Matrix4d
* @return
*/
public Mat4d getTransMatrix(double simTime) {
Transform trans = getGlobalTrans(simTime);
Mat4d ret = new Mat4d();
trans.getMat4d(ret);
ret.scaleCols3(getSize());
return ret;
}
/**
* Returns the inverse global transform with scale factor all rolled into a Matrix4d
* @return
*/
public Mat4d getInvTransMatrix(double simTime) {
return RenderUtils.getInverseWithScale(getGlobalTrans(simTime), size);
}
/**
* Return the position in the global coordinate system
* @return
*/
public Vec3d getGlobalPosition() {
Vec3d ret = getPosition();
// Position is relative to another entity
DisplayEntity ent = this.getRelativeEntity();
if (ent != null) {
if (currentRegion != null)
currentRegion.getRegionTransForVectors().multAndTrans(ret, ret);
ret.add3(ent.getGlobalPosition());
return ret;
}
// Position is given in a local coordinate system
if (currentRegion != null)
currentRegion.getRegionTrans().multAndTrans(ret, ret);
return ret;
}
/*
* Returns the center relative to the origin
*/
public Vec3d getAbsoluteCenter() {
Vec3d cent = this.getPositionForAlignment(new Vec3d());
DisplayEntity ent = this.getRelativeEntity();
if (ent != null)
cent.add3(ent.getGlobalPosition());
return cent;
}
/**
* Returns the extent for the DisplayEntity
*/
public Vec3d getSize() {
synchronized (position) {
return new Vec3d(size);
}
}
public Vec3d getAlignment() {
synchronized (position) {
return new Vec3d(align);
}
}
public void setAlignment(Vec3d align) {
synchronized (position) {
this.align.set3(align);
}
}
public void setPosition(Vec3d pos) {
synchronized (position) {
position.set3(pos);
}
}
/**
* Set the global position for this entity, this takes into account the region
* transform and sets the local position accordingly
* @param pos - The new position in the global coordinate system
*/
public void setInputForGlobalPosition(Vec3d pos) {
Vec3d localPos = this.getLocalPosition(pos);
setPosition(localPos);
KeywordIndex kw = InputAgent.formatPointInputs(positionInput.getKeyword(), localPos, "m");
InputAgent.apply(this, kw);
}
public void setGlobalPosition(Vec3d pos) {
setPosition(getLocalPosition(pos));
}
/**
* Returns the local coordinates for this entity corresponding to the
* specified global coordinates.
* @param pos - a position in the global coordinate system
*/
public Vec3d getLocalPosition(Vec3d pos) {
Vec3d localPos = pos;
// Position is relative to another entity
DisplayEntity ent = this.getRelativeEntity();
if (ent != null) {
localPos.sub3(ent.getGlobalPosition());
if (currentRegion != null)
currentRegion.getInverseRegionTransForVectors().multAndTrans(localPos, localPos);
return localPos;
}
// Position is given in a local coordinate system
if (currentRegion != null)
currentRegion.getInverseRegionTrans().multAndTrans(pos, localPos);
return localPos;
}
/*
* move object to argument point based on alignment
*/
public void setPositionForAlignment(Vec3d alignment, Vec3d position) {
// Calculate the difference between the desired point and the current aligned position
Vec3d diff = this.getPositionForAlignment(alignment);
diff.sub3(position);
diff.scale3(-1.0d);
// add the difference to the current position and set the new position
diff.add3(getPosition());
setPosition(diff);
}
public void setGlobalPositionForAlignment(Vec3d alignment, Vec3d position) {
// Calculate the difference between the desired point and the current aligned position
Vec3d diff = this.getGlobalPositionForAlignment(alignment);
diff.sub3(position);
diff.scale3(-1.0d);
// add the difference to the current position and set the new position
diff.add3(getPosition());
setPosition(diff);
}
public ArrayList<DisplayModel> getDisplayModelList() {
return displayModelList;
}
public void setDisplayModelList(ArrayList<DisplayModel> dmList) {
displayModelList.clear();
if (dmList == null)
return;
for (DisplayModel dm : dmList) {
displayModelList.add(dm);
}
clearBindings(); // Clear this on any change, and build it lazily later
}
public final void clearBindings() {
modelBindings = null;
}
public ArrayList<DisplayModelBinding> getDisplayBindings() {
if (modelBindings == null) {
// Populate the model binding list
if (getDisplayModelList() == null) {
modelBindings = new ArrayList<>();
return modelBindings;
}
modelBindings = new ArrayList<>(getDisplayModelList().size());
for (int i = 0; i < getDisplayModelList().size(); ++i) {
DisplayModel dm = getDisplayModelList().get(i);
modelBindings.add(dm.getBinding(this));
}
}
return modelBindings;
}
public void dragged(Vec3d distance) {
Vec3d newPos = this.getPosition();
newPos.add3(distance);
this.setPosition(newPos);
KeywordIndex kw = InputAgent.formatPointInputs(positionInput.getKeyword(), newPos, "m");
InputAgent.apply(this, kw);
}
public boolean isActive() {
return active.getValue();
}
public boolean getShow() {
return show.getValue();
}
public boolean isMovable() {
return movable.getValue();
}
/**
* This method updates the DisplayEntity for changes in the given input
*/
@Override
public void updateForInput( Input<?> in ) {
super.updateForInput( in );
if( in == positionInput ) {
this.setPosition( positionInput.getValue() );
return;
}
if( in == sizeInput ) {
this.setSize( sizeInput.getValue() );
return;
}
if( in == orientationInput ) {
this.setOrientation( orientationInput.getValue() );
return;
}
if( in == alignmentInput ) {
this.setAlignment( alignmentInput.getValue() );
return;
}
if( in == regionInput ) {
this.setRegion(regionInput.getValue());
}
if (in == displayModelListInput) {
this.setDisplayModelList( displayModelListInput.getValue() );
}
}
public final void setTagColour(String tagName, Color4d ca) {
Color4d cas[] = new Color4d[1] ;
cas[0] = ca;
setTagColours(tagName, cas);
}
public final void setTagColours(String tagName, Color4d[] cas) {
Tag t = tagMap.get(tagName);
if (t == null) {
t = new Tag(cas, null, true);
tagMap.put(tagName, t);
return;
}
if (t.colorsMatch(cas))
return;
else
tagMap.put(tagName, new Tag(cas, t.sizes, t.visible));
}
public final void setTagSize(String tagName, double size) {
double s[] = new double[1] ;
s[0] = size;
setTagSizes(tagName, s);
}
public final void setTagSizes(String tagName, double[] sizes) {
Tag t = tagMap.get(tagName);
if (t == null) {
t = new Tag(null, sizes, true);
tagMap.put(tagName, t);
return;
}
if (t.sizesMatch(sizes))
return;
else
tagMap.put(tagName, new Tag(t.colors, sizes, t.visible));
}
public final void setTagVisibility(String tagName, boolean isVisible) {
Tag t = tagMap.get(tagName);
if (t == null) {
t = new Tag(null, null, isVisible);
tagMap.put(tagName, t);
return;
}
if (t.visMatch(isVisible))
return;
else
tagMap.put(tagName, new Tag(t.colors, t.sizes, isVisible));
}
/**
* Get all tags for this entity
* @return
*/
public HashMap<String, Tag> getTagSet() {
return tagMap;
}
// Outputs
@Output(name = "Position",
description = "The DisplayEntity's position in region space.",
unitType = DistanceUnit.class)
public Vec3d getPosOutput(double simTime) {
return getPosition();
}
@Output(name = "Size",
description = "The DisplayEntity's size in meters.",
unitType = DistanceUnit.class)
public Vec3d getSizeOutput(double simTime) {
return getSize();
}
@Output(name = "Orientation",
description = "The XYZ euler angles describing the DisplayEntity's current rotation.",
unitType = AngleUnit.class)
public Vec3d getOrientOutput(double simTime) {
return getOrientation();
}
@Output(name = "Alignment",
description = "The point on the DisplayEntity that aligns direction with the position output.\n" +
"The components should be in the range [-0.5, 0.5]",
unitType = DimensionlessUnit.class)
public Vec3d getAlignOutput(double simTime) {
return getAlignment();
}
}
|
package com.vectrace.MercurialEclipse.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import com.vectrace.MercurialEclipse.MercurialEclipsePlugin;
import com.vectrace.MercurialEclipse.exception.HgException;
import com.vectrace.MercurialEclipse.history.MercurialRevision;
import com.vectrace.MercurialEclipse.team.MercurialStatusCache;
public class HistoryPainter {
private final static int[] colors = new int[] { SWT.COLOR_RED,
SWT.COLOR_DARK_BLUE, SWT.COLOR_MAGENTA, SWT.COLOR_DARK_GREEN,
SWT.COLOR_DARK_YELLOW, SWT.COLOR_CYAN, SWT.COLOR_DARK_MAGENTA,
SWT.COLOR_GREEN, SWT.COLOR_DARK_RED, SWT.COLOR_BLUE,
SWT.COLOR_DARK_CYAN };
private HistoryPainterRevision roof;
private SortedSet<HistoryPainterEdge> edges = new TreeSet<HistoryPainterEdge>();
private SortedSet<HistoryPainterRevision> revisions = new TreeSet<HistoryPainterRevision>();
private SortedSet<HistoryPainterEdge> startedEdges = new TreeSet<HistoryPainterEdge>();
private List<HistoryPainterRevision> searchList;
public HistoryPainter(IResource resource) {
try {
this.roof = new HistoryPainterRevision(resource,
MercurialStatusCache.getInstance().getNewestLocalChangeSet(
resource));
// cleanup
revisions.clear();
edges.clear();
startedEdges.clear();
// gets and sorts all edges
this.edges.addAll(addParentEdges(roof));
// gets and sorts all revisions (313, 312, 311, etc.)
this.revisions.add(roof);
this.revisions.addAll(addParentRevisions(roof));
this.searchList = new ArrayList<HistoryPainterRevision>(revisions);
determineLayout();
} catch (HgException e) {
MercurialEclipsePlugin.logError(e);
}
}
private void determineLayout() {
int lane = 1;
for (HistoryPainterRevision rev : revisions) {
lane = Math.max(1, rev.getLane());
rev.setLane(lane);
rev.setLanes(startedEdges.size());
// update started edges
for (int parCount = 0; parCount < rev.getEdgeStarts().size(); parCount++) {
HistoryPainterEdge edge = rev.getEdgeStarts().get(parCount);
int parentLane = lane + parCount;
edge.setStartLane(lane);
edge.setStopLane(parentLane);
edge.getStop().setLane(parentLane);
// add revision start edges to started, remove them from edges
if (edge.getStart().equals(rev)) {
startedEdges.add(edge);
}
}
// update started edges
for (Iterator<HistoryPainterEdge> iter = rev.getEdgeStops()
.iterator(); iter.hasNext();) {
HistoryPainterEdge edge = iter.next();
// add revision start edges to started, remove them from edges
if (edge.getStop().equals(rev)) {
startedEdges.remove(edge);
}
}
}
}
private SortedSet<HistoryPainterRevision> addParentRevisions(
HistoryPainterRevision hpr) {
SortedSet<HistoryPainterRevision> parentRevisions = new TreeSet<HistoryPainterRevision>();
for (HistoryPainterRevision parent : hpr.getParents()) {
parentRevisions.add(parent);
parentRevisions.addAll(addParentRevisions(parent));
}
return parentRevisions;
}
private SortedSet<HistoryPainterEdge> addParentEdges(
HistoryPainterRevision hpr) {
SortedSet<HistoryPainterEdge> parentEdges = new TreeSet<HistoryPainterEdge>();
for (HistoryPainterRevision parent : hpr.getParents()) {
HistoryPainterEdge edge = new HistoryPainterEdge(hpr, parent, 0);
parentEdges.add(edge);
hpr.getEdgeStarts().add(edge);
parent.getEdgeStops().add(edge);
parentEdges.addAll(addParentEdges(parent));
}
return parentEdges;
}
public void paint(Event e, int columnIndex) {
if (e.type != SWT.PaintItem || e.index != columnIndex || e.item == null
|| e.item.getData() == null
|| !(e.item.getData() instanceof MercurialRevision)) {
return;
}
MercurialRevision mrev = (MercurialRevision) e.item.getData();
// int height = e.height;
int itemHeight = e.height;
int pad = 8;
int x = e.x + pad;
int y = e.y;
GC gc = e.gc;
gc.setAntialias(SWT.ON);
gc.setLineWidth(2);
int branchOffsetY = itemHeight / 3;
int startX = x;
int startY = y;
int endY = startY + itemHeight;
// construct key without building graph
HistoryPainterRevision key = new HistoryPainterRevision();
key.setResource(mrev.getResource());
key.setChangeSet(mrev.getChangeSet());
int index = Collections.binarySearch(searchList, key);
HistoryPainterRevision rev = searchList.get(index);
System.out.println(rev.toString());
// draw lane with revision circles
for (int currLane = 0; currLane < rev.getLanes(); currLane++) {
gc.setForeground(Display.getCurrent().getSystemColor(
colors[currLane % 11]));
startX = getStartX(pad, x, currLane);
gc.drawLine(startX, startY, startX, endY - branchOffsetY);
if (rev.getLane() == currLane + 1) {
drawCircle(pad, gc, startX, startY);
drawBranch(rev, pad, gc, branchOffsetY, startX, endY);
}
// draw rest of vertical line if there are parents
if (rev.getParents().size() > 0) {
gc.drawLine(startX, endY - branchOffsetY, startX, endY);
}
}
e.gc.dispose();
}
/**
* @param pad
* @param x
* @param currLane
* @return
*/
private int getStartX(int pad, int x, int currLane) {
int startX;
startX = x + currLane * pad;
return startX;
}
/**
* @param pad
* @param gc
* @param startX
* @param startY
*/
private void drawCircle(int pad, GC gc, int startX, int startY) {
// circle for revision
gc.drawArc(startX - pad / 2, startY + (pad / 2), pad, pad, 0, 360);
gc.fillArc(startX - pad / 2, startY + (pad / 2), pad, pad, 0, 360);
}
/**
* @param pad
* @param gc
* @param arcOffsetY
* @param startX
* @param endY
*/
private void drawBranch(HistoryPainterRevision rev, int pad, GC gc,
int arcOffsetY, int startX, int endY) {
// arc out to outgoingEdges, if they are in different lanes
for (HistoryPainterEdge edge : rev.getEdgeStarts()) {
if (rev.getLane() != edge.getStop().getLane()) {
int circleWidth = pad
* Math.abs(rev.getLane() - edge.getStop().getLane());
// arc to the right
if (rev.getLane() < edge.getStop().getLane()) {
// gc.drawArc(startX-pad, endY - arcOffsetY,
// circleWidth,
// endY, 0, 90);
gc.drawLine(startX, endY - arcOffsetY,
startX + circleWidth, endY);
// arc to the left
} else if (rev.getLane() > edge.getStop().getLane()) {
// gc.drawArc(startX-pad, endY - arcOffsetY,
// circleWidth, endY, 90, 180);
gc.drawLine(startX - circleWidth, endY, startX, endY
- arcOffsetY);
}
}
}
}
/**
* @return the edges
*/
public SortedSet<HistoryPainterEdge> getEdges() {
return edges;
}
/**
* @param edges
* the edges to set
*/
public void setEdges(SortedSet<HistoryPainterEdge> edges) {
this.edges = edges;
}
/**
* @return the roof
*/
public HistoryPainterRevision getRoof() {
return roof;
}
/**
* @param roof
* the roof to set
*/
public void setRoof(HistoryPainterRevision roof) {
this.roof = roof;
}
public void addEdge(HistoryPainterEdge e) {
if (edges == null) {
edges = new TreeSet<HistoryPainterEdge>();
}
this.edges.add(e);
}
public boolean removeEdge(HistoryPainterEdge e) {
return edges.remove(e);
}
}
|
package si.mazi.rescu;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.*;
/**
* This holds name-value mapping for various types of params used in REST (QueryParam, PathParam, FormParam, HeaderParam).
*
* One RestInvocation instance corresponds to one method invocation.
*
* @author Matija Mazi
*/
public class RestInvocation implements Serializable {
@SuppressWarnings("unchecked")
protected static final List<Class<? extends Annotation>> PARAM_ANNOTATION_CLASSES = Arrays.asList(QueryParam.class, PathParam.class, FormParam.class, HeaderParam.class);
private final ObjectMapper objectMapper = new ObjectMapper();
private final Map<Class<? extends Annotation>, Params> paramsMap;
private final List<Object> unannanotatedParams = new ArrayList<Object>();
private String contentType;
private String methodPath;
private String invocationUrl;
private String queryString;
private String path;
private RestMethodMetadata restMethodMetadata;
RestInvocation(RestMethodMetadata restMethodMetadata, Object[] args) {
this.restMethodMetadata = restMethodMetadata;
paramsMap = new HashMap<Class<? extends Annotation>, Params>();
for (Class<? extends Annotation> annotationClass : PARAM_ANNOTATION_CLASSES) {
paramsMap.put(annotationClass, Params.of());
}
Annotation[][] paramAnnotations = restMethodMetadata.parameterAnnotations;
for (int i = 0; i < paramAnnotations.length; i++) {
Annotation[] paramAnns = paramAnnotations[i];
if (paramAnns.length == 0) {
unannanotatedParams.add(args[i]);
}
for (Annotation paramAnn : paramAnns) {
String paramName = getParamName(paramAnn);
if (paramName != null) {
this.paramsMap.get(paramAnn.annotationType()).add(paramName, args[i]);
}
}
}
Map<Class<? extends Annotation>, Annotation> methodAnnotationMap = restMethodMetadata.methodAnnotationMap;
// Support using method name as a parameter.
for (Class<? extends Annotation> paramAnnotationClass : methodAnnotationMap.keySet()) {
Annotation annotation = methodAnnotationMap.get(paramAnnotationClass);
if (annotation != null) {
String paramName = getParamName(annotation);
this.paramsMap.get(paramAnnotationClass).add(paramName, restMethodMetadata.methodName);
}
}
contentType = restMethodMetadata.contentType;
methodPath = getPath(restMethodMetadata.methodPathTemplate);
path = restMethodMetadata.intfacePath;
path = appendIfNotEmpty(path, methodPath, "/");
queryString = paramsMap.get(QueryParam.class).asQueryString();
invocationUrl = getInvocationUrl(restMethodMetadata.baseUrl, path, queryString);
for (int i = 0; i < unannanotatedParams.size(); i++) {
Object param = unannanotatedParams.get(i);
if (param instanceof ParamsDigest) {
unannanotatedParams.set(i, ((ParamsDigest) param).digestParams(this));
}
}
for (Params params : paramsMap.values()) {
params.digestAll(this);
}
}
// todo: this is needed only for testing
public RestInvocation(Map<Class<? extends Annotation>, Params> paramsMap, String contentType) {
this.contentType = contentType;
this.paramsMap = new LinkedHashMap<Class<? extends Annotation>, Params>(paramsMap);
}
private static String getParamName(Annotation queryParam) {
for (Class<? extends Annotation> annotationClass : PARAM_ANNOTATION_CLASSES) {
String paramName = AnnotationUtils.getValueOrNull(annotationClass, queryParam);
if (paramName != null) {
return paramName;
}
}
// This is not one of the annotations in PARAM_ANNOTATION_CLASSES.
return null;
}
static String getInvocationUrl(String baseUrl, String path, String queryString) {
// TODO make more robust in terms of path separator ('/') handling
// (Use UriBuilder?)
String completeUrl = baseUrl;
completeUrl = appendIfNotEmpty(completeUrl, path, "/");
completeUrl = appendIfNotEmpty(completeUrl, queryString, "?");
return completeUrl;
}
static String appendIfNotEmpty(String url, String next, String separator) {
if (!url.isEmpty() && next != null && !next.isEmpty()) {
if (!url.endsWith(separator) && !next.startsWith(separator)) {
url += separator;
}
url += next;
}
return url;
}
public String getPath(String methodPath) {
return paramsMap.get(PathParam.class).applyToPath(methodPath);
}
public String getRequestBody() {
if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
return paramsMap.get(FormParam.class).asFormEncodedRequestBody();
} else if (MediaType.APPLICATION_JSON.equals(contentType)) {
if (!paramsMap.get(FormParam.class).isEmpty()) {
throw new IllegalArgumentException("@FormParams are not allowed with " + MediaType.APPLICATION_JSON);
} else if (unannanotatedParams.size() > 1) {
throw new IllegalArgumentException("Can only have a single unnanotated parameter with " + MediaType.APPLICATION_JSON);
}
if (unannanotatedParams.size() == 0) {
return null;
}
try {
return objectMapper.writeValueAsString(unannanotatedParams.get(0));
} catch (IOException e) {
throw new RuntimeException("Error writing json, probably a bug.", e);
}
}
throw new IllegalArgumentException("Unsupported media type: " + contentType);
}
public Map<String, String> getHttpHeaders() {
return paramsMap.get(HeaderParam.class).asHttpHeaders();
}
public String getContentType() {
return contentType;
}
/**
* @return The invocation url that is used in this invocation.
*/
public String getInvocationUrl() {
return invocationUrl;
}
/**
* @return The part of the url path that corresponds to the method.
*/
public String getMethodPath() {
return methodPath;
}
/**
* @return The whole url path: the interface path together with the method path.
* This is usally the part of the url that follows the host name.
*/
public String getPath() {
return path;
}
public String getBaseUrl() {
return restMethodMetadata.baseUrl;
}
/**
* @return The part of the invocation url that follows the '?' charater, ie. the &-separated name=value parameter pairs.
*/
public String getQueryString() {
return queryString;
}
public RestMethodMetadata getRestMethodMetadata() {
return restMethodMetadata;
}
}
|
package com.lordmau5.ffs;
import com.lordmau5.ffs.blocks.BlockTankFrame;
import com.lordmau5.ffs.blocks.BlockValve;
import com.lordmau5.ffs.network.NetworkHandler;
import com.lordmau5.ffs.proxy.CommonProxy;
import com.lordmau5.ffs.proxy.GuiHandler;
import com.lordmau5.ffs.tile.TileEntityTankFrame;
import com.lordmau5.ffs.tile.TileEntityValve;
import com.lordmau5.ffs.util.GenericUtil;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
@Mod(modid = FancyFluidStorage.modId, name = "Fancy Fluid Storage")
public class FancyFluidStorage {
public static final String modId = "FFS";
public static BlockValve blockValve;
public static BlockTankFrame blockTankFrame;
@Mod.Instance(modId)
public static FancyFluidStorage instance;
@SidedProxy(clientSide = "com.lordmau5.ffs.proxy.ClientProxy", serverSide = "com.lordmau5.ffs.proxy.CommonProxy")
public static CommonProxy proxy;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
proxy.preInit();
GameRegistry.registerBlock(blockValve = new BlockValve(), "blockValve");
GameRegistry.registerBlock(blockTankFrame = new BlockTankFrame(), "blockTankFrame");
GameRegistry.registerTileEntity(TileEntityValve.class, "tileEntityValve");
GameRegistry.registerTileEntity(TileEntityTankFrame.class, "tileEntityTankFrame");
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
NetworkHandler.registerChannels(event.getSide());
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
GameRegistry.addRecipe(new ItemStack(blockValve), "IGI", "GBG", "IGI",
'I', Items.iron_ingot,
'G', Blocks.iron_bars,
'B', Items.bucket);
proxy.init();
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
GenericUtil.init();
}
}
|
package com.jwetherell.algorithms.data_structures;
import java.util.ArrayList;
import java.util.List;
public class SkipList<T extends Comparable<T>> {
private int size = 0;
private List<List<ExpressNode<T>>> lanes = null;
private Node<T> head = null;
public SkipList() {
}
public SkipList(T[] nodes) {
this();
populateLinkedList(nodes);
generateExpressLanes();
}
private void populateLinkedList(T[] nodes) {
for (T n : nodes) {
add(n);
}
}
private boolean refactorExpressLanes(int expressLanes) {
if (expressLanes != lanes.size()) return true;
int length = size;
for (int i = 0; i < expressLanes; i++) {
List<ExpressNode<T>> expressLane = lanes.get(i);
if (expressLane.size() != length) return true;
length = length / 2;
}
return false;
}
private int determineNumberOfExpressLanes() {
return (int) Math.ceil(Math.log10(size) / Math.log10(2));
}
private void generateExpressLanes() {
int expressLanes = determineNumberOfExpressLanes();
if (lanes == null) lanes = new ArrayList<List<ExpressNode<T>>>(expressLanes);
if (!refactorExpressLanes(expressLanes)) return;
lanes.clear();
int length = size;
int width = 0;
int index = 0;
for (int i = 0; i < expressLanes; i++) {
width = size / length;
List<ExpressNode<T>> expressLane = new ArrayList<ExpressNode<T>>();
for (int j = 0; j < length; j++) {
Node<T> node = null;
if (i == 0) {
node = this.getNode(j);
} else {
List<ExpressNode<T>> previousLane = lanes.get(i - 1);
int prevIndex = j * 2;
node = previousLane.get(prevIndex);
}
index = j;
ExpressNode<T> expressNode = new ExpressNode<T>(index, width, node);
expressLane.add(expressNode);
}
lanes.add(expressLane);
length = length / 2;
}
}
public void add(T value) {
Node<T> node = new Node<T>(value);
if (head == null) {
head = node;
} else {
Node<T> prev = null;
Node<T> next = head;
while (next != null) {
prev = next;
next = next.nextNode;
}
if (prev != null) prev.nextNode = node;
}
node.index = size;
int prevLanes = determineNumberOfExpressLanes();
size++;
int newLanes = determineNumberOfExpressLanes();
if (newLanes!=prevLanes) generateExpressLanes();
}
public boolean remove(T value) {
Node<T> prev = null;
Node<T> node = head;
while (node != null && (node.value.compareTo(value) != 0)) {
prev = node;
node = node.nextNode;
}
if (node == null) return false;
Node<T> next = node.nextNode;
if (prev != null && next != null) {
prev.nextNode = next;
} else if (prev != null && next == null) {
prev.nextNode = null;
} else if (prev == null && next != null) {
// Node is the head
head = next;
} else {
// prev==null && next==null
head = null;
}
if (prev != null) {
node = prev;
int prevIndex = prev.index;
while (node != null) {
node = node.nextNode;
if (node != null) node.index = ++prevIndex;
}
}
int prevLanes = determineNumberOfExpressLanes();
size
int newLanes = determineNumberOfExpressLanes();
if (newLanes!=prevLanes) generateExpressLanes();
return true;
}
private Node<T> getNode(int index) {
Node<T> node = null;
if (lanes.size() > 0) {
int currentLane = lanes.size() - 1;
int currentIndex = 0;
List<ExpressNode<T>> lane = lanes.get(currentLane);
node = lane.get(currentIndex);
while (true) {
if (node instanceof ExpressNode) {
// If the node is an ExpressNode
ExpressNode<T> expressNode = (ExpressNode<T>) node;
if (index < (currentIndex + 1) * expressNode.width) {
// If the index is less than the current ExpressNode's
// cumulative width, try to go down a level.
if (currentLane > 0) lane = lanes.get(--currentLane); // This will be true when the
// nextNode is a ExpressNode.
node = expressNode.nextNode;
currentIndex = node.index;
} else if (lane.size() > (expressNode.index + 1)) {
// If the index greater than the current ExpressNode's
// cumulative width, try the next ExpressNode.
currentIndex = expressNode.index + 1;
node = lane.get(currentIndex);
} else if (currentLane > 0) {
// We have run out of nextNodes, try going down a level.
lane = lanes.get(--currentLane);
node = expressNode.nextNode;
currentIndex = node.index;
} else {
// Yikes! I don't know how I got here. break, just in
// case.
break;
}
} else {
break;
}
}
} else {
node = head;
}
while (node != null && node.index < index) {
node = node.nextNode;
}
return node;
}
public T get(int index) {
Node<T> node = this.getNode(index);
if (node != null) return node.value;
else return null;
}
public int getSize() {
return size;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lanes.size(); i++) {
builder.append("Lane=").append(i).append("\n");
List<ExpressNode<T>> lane = lanes.get(i);
for (int j = 0; j < lane.size(); j++) {
ExpressNode<T> node = lane.get(j);
builder.append(node);
}
builder.append("\n");
}
return builder.toString();
}
private static class ExpressNode<T extends Comparable<T>> extends Node<T> {
private Integer width = null;
private ExpressNode(int index, int width, Node<T> pointer) {
this.width = width;
this.index = index;
this.nextNode = pointer;
}
private Node<T> getNodeFromExpress(ExpressNode<T> node) {
Node<T> nextNode = node.nextNode;
if (nextNode != null && (nextNode instanceof ExpressNode)) {
ExpressNode<T> eNode = (ExpressNode<T>) nextNode;
return getNodeFromExpress(eNode);
} else {
return nextNode;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (nextNode != null && (nextNode instanceof ExpressNode)) {
ExpressNode<T> eNode = (ExpressNode<T>) nextNode;
Node<T> pointerRoot = getNodeFromExpress(eNode);
builder.append("width=").append(width).append(" pointer=[").append(pointerRoot.value).append("]\t");
} else {
builder.append("width=").append(width);
if (nextNode != null) builder.append(" node=[").append(nextNode.value).append("]\t");
}
return builder.toString();
}
}
private static class Node<T extends Comparable<T>> {
private T value = null;
protected Integer index = null;
protected Node<T> nextNode = null;
private Node() {
this.index = Integer.MIN_VALUE;
this.value = null;
}
private Node(T value) {
this();
this.value = value;
}
private Node(int index, T value) {
this(value);
this.index = index;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (index != Integer.MIN_VALUE) builder.append("index=").append(index).append(" ");
if (value != null) builder.append("value=").append(value).append(" ");
builder.append("next=").append((nextNode != null) ? nextNode.value : "NULL");
return builder.toString();
}
}
}
|
package com.wb.nextgenlibrary.fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.wb.nextgenlibrary.R;
import com.wb.nextgenlibrary.analytic.NextGenAnalyticData;
import com.wb.nextgenlibrary.data.MovieMetaData;
import com.wb.nextgenlibrary.util.utils.F;
import com.wb.nextgenlibrary.util.utils.NextGenLogger;
import com.wb.nextgenlibrary.util.utils.StringHelper;
import com.wb.nextgenlibrary.videoview.ObservableVideoView;
import com.wb.nextgenlibrary.widget.ECMediaController;
import com.wb.nextgenlibrary.widget.FixedAspectRatioFrameLayout;
public class ECVideoViewFragment extends ECViewFragment{
protected ObservableVideoView videoView;
ECMediaController mediaController;
protected TextView selectedECNameTextView;
protected TextView descriptionTextView;
protected TextView countDownTextView;
protected View countDownCountainer;
protected ProgressBar countDownProgressBar;
ImageView previewImageView = null;
RelativeLayout previewFrame = null;
ImageButton previewPlayBtn = null;
FixedAspectRatioFrameLayout aspectRatioFrame = null;
MovieMetaData.AudioVisualItem selectedAVItem = null;
boolean bSetOnResume= false;
ImageView bgImageView;
String bgImageUrl = null;
boolean bCountDown = false;
boolean shouldAutoPlay = true;
boolean shouldExitWhenComplete = false;
FixedAspectRatioFrameLayout.Priority aspectFramePriority = null;
private static int COUNT_DOWN_SECONDS = 5;
ECVideoListAdaptor ecsAdaptor = null;
private int previousPlaybackTime = 0;
public static interface ECVideoListAdaptor{
void playbackFinished();
boolean shouldStartCountDownForNext();
}
String getReportContentName(){
if (selectedAVItem != null)
return selectedAVItem.getTitle();
else
return null;
}
public void setBGImageUrl(String url){
bgImageUrl = url;
}
@Override
public int getContentViewId(){
return R.layout.ec_video_frame_view;
}
public void setShouldExitWhenComplete(boolean bTrue){
shouldExitWhenComplete = bTrue;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoView = (ObservableVideoView) view.findViewById(R.id.ec_video_view);
mediaController = new ECMediaController(getActivity(), videoView);
selectedECNameTextView = (TextView)view.findViewById(R.id.ec_content_name);
descriptionTextView = (TextView)view.findViewById(R.id.ec_content_runtime);
previewImageView = (ImageView)view.findViewById(R.id.ec_video_preview_image);
previewFrame = (RelativeLayout)view.findViewById(R.id.ec_video_preview_image_frame);
previewPlayBtn = (ImageButton)view.findViewById(R.id.ec_video_preview_playButton);
aspectRatioFrame = (FixedAspectRatioFrameLayout) view.findViewById(R.id.ec_video_aspect_ratio_frame);
countDownCountainer = view.findViewById(R.id.count_down_container);
countDownTextView = (TextView) view.findViewById(R.id.count_down_text_view);
countDownProgressBar = (ProgressBar) view.findViewById(R.id.count_down_progressBar);
if (countDownCountainer != null)
countDownCountainer.setVisibility(View.INVISIBLE);
if (countDownProgressBar != null){
countDownProgressBar.setMax(COUNT_DOWN_SECONDS);
}
if (aspectRatioFrame != null){
aspectRatioFrame.setAspectRatioPriority(aspectFramePriority);
}
if (previewPlayBtn != null) {
previewPlayBtn.setVisibility(View.GONE);
previewPlayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (previewFrame != null)
previewFrame.setVisibility(View.GONE);
videoView.start();
NextGenAnalyticData.reportEvent(getActivity(), ECVideoViewFragment.this, "EC Play Button",
NextGenAnalyticData.AnalyticAction.ACTION_CLICK, null);
}
});
}
//videoView.setMediaController(mediaController);
videoView.setMediaController(mediaController);
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
private Handler mHandler = new Handler();
int counter = COUNT_DOWN_SECONDS;
@Override
public void onCompletion(MediaPlayer mp) {
if (shouldExitWhenComplete){
closeBtn.callOnClick();
}else if (ecsAdaptor != null) {
if (ecsAdaptor.shouldStartCountDownForNext()){
//new
startRepeatingTask();
}else {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
videoView.seekTo(0);
if (previewFrame != null) {
if (!StringHelper.isEmpty(selectedAVItem.getPosterImgUrl())) {
Picasso.with(getActivity()).load(selectedAVItem.getPreviewImageUrl()).fit().into(previewImageView);
}
previewFrame.setVisibility(View.VISIBLE);
}
if (previewPlayBtn != null)
previewPlayBtn.setVisibility(View.VISIBLE);
}
});
}
}
}
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
boolean shouldFinish = false;
try {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (countDownCountainer != null) {
if (counter >= 0) {
countDownCountainer.setVisibility(View.VISIBLE);
countDownTextView.setText(String.format(getResources().getString(R.string.count_down_text), Integer.toString(counter)) );
countDownProgressBar.setProgress(counter);
}else {
countDownTextView.setText("");
countDownCountainer.setVisibility(View.GONE);
}
}
}
});
}
if (counter < 0){
ecsAdaptor.playbackFinished();
stopRepeatingTask();
shouldFinish = true;
}
counter = counter - 1;
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
if (!shouldFinish)
mHandler.postDelayed(mStatusChecker, 1000);
}
}
};
void startRepeatingTask() {
counter = 5;
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
});
videoView.setOnPreparedListener(new PreparedListener());
videoView.requestFocus();
bgImageView = (ImageView)view.findViewById(R.id.ec_video_frame_bg);
if (bgImageView != null && !StringHelper.isEmpty(bgImageUrl)){
Glide.with(getActivity()).load(bgImageUrl).fitCenter().into(bgImageView);
}
}
public void setAspectRatioFramePriority(FixedAspectRatioFrameLayout.Priority priority){
if (aspectRatioFrame != null)
aspectRatioFrame.setAspectRatioPriority(priority);
aspectFramePriority = priority;
}
private class PreparedListener implements MediaPlayer.OnPreparedListener {
@Override
public void onPrepared(MediaPlayer mp) {
if (shouldAutoPlay) {
if (previousPlaybackTime != 0){
videoView.seekTo(previousPlaybackTime);
//added: tr 9/19
mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mp) {
videoView.start();
}
});
}else
videoView.start();
}else {
if (previewPlayBtn != null){
previewPlayBtn.setVisibility(View.VISIBLE);
}
shouldAutoPlay = true;
}
}
}
@Override
public void onPause(){
super.onPause();
videoView.pause();
previousPlaybackTime = videoView.getCurrentPosition();
}
@Override
public void onResume() {
super.onResume();
/*Intent intent = getIntent();
Uri uri = intent.getData();*/
videoView.setVisibility(View.VISIBLE);
if (bSetOnResume){
bSetOnResume = false;
setAudioVisualItem(selectedAVItem);
}
}
@Override
public void onDestroyView(){
videoView.setMediaController(null);
videoView.stopPlayback();
mediaController.onPlayerDestroy();
mediaController = null;
super.onDestroyView();
}
public void setEnableCountDown(boolean bCountDown){
this.bCountDown = bCountDown;
}
Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
videoView.setBackground(new BitmapDrawable(bitmap));
}
});
}
@Override
public void onPrepareLoad(Drawable var1){
NextGenLogger.d(F.TAG, "haha");
}
@Override
public void onBitmapFailed(Drawable var1) {
NextGenLogger.d(F.TAG, "haha");
}
};
public void setAudioVisualItem(MovieMetaData.AudioVisualItem avItem){
if (avItem != null) {
selectedAVItem = avItem;
if (countDownCountainer != null)
countDownCountainer.setVisibility(View.INVISIBLE);
if (selectedECNameTextView != null && videoView != null) {
selectedECNameTextView.setText(avItem.getTitle());
if (descriptionTextView != null) {
descriptionTextView.setText(avItem.getSummary());
}
if (!shouldAutoPlay) {
if(videoView.isPlaying())
videoView.stopPlayback();
if (previewFrame != null) {
previewFrame.setVisibility(View.VISIBLE);
previewPlayBtn.setVisibility(View.GONE);
}
if (!StringHelper.isEmpty(selectedAVItem.getPosterImgUrl())) {
Picasso.with(getActivity()).load(selectedAVItem.getPreviewImageUrl()).fit().into(previewImageView);
}
}else{
if (previewFrame != null) {
previewFrame.setVisibility(View.GONE);
previewPlayBtn.setVisibility(View.GONE);
}
}
videoView.setVideoURI(Uri.parse(avItem.videoUrl));
if (mediaController != null) {
mediaController.reset();
}
}else{
bSetOnResume = true;
}
}
}
public void onRequestToggleFullscreen(boolean bFullscreen) {
mediaController.onToggledFullScreen(bFullscreen);
}
public void setEcsAdaptor(ECVideoListAdaptor adaptor){
ecsAdaptor = adaptor;
}
public void setShouldAutoPlay(boolean shouldAutoPlay){
this.shouldAutoPlay = shouldAutoPlay;
}
public void stopPlayback(){
videoView.stopPlayback();
}
}
|
package yanagishima.util;
import static java.lang.String.format;
import static yanagishima.util.PathUtil.getResultFilePath;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import javax.annotation.Nullable;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import io.airlift.units.DataSize;
import yanagishima.row.Query;
import yanagishima.row.SessionProperty;
public final class HistoryUtil {
private HistoryUtil() { }
public static void createHistoryResult(Map<String, Object> responseBody, int limit, String datasource, Query query, boolean resultVisible, List<SessionProperty> sessionPropertyList) {
String queryId = query.getQueryId();
String queryString = query.getQueryString();
responseBody.put("queryString", queryString);
responseBody.put("finishedTime", query.getFetchResultTimeString());
responseBody.put("lineNumber", query.getLinenumber());
responseBody.put("elapsedTimeMillis", query.getElapsedTimeMillis());
responseBody.put("rawDataSize", toSuccinctDataSize(query.getResultFileSize()));
responseBody.put("user", query.getUser());
Map<String, String> map = new HashMap<>();
for (SessionProperty sessionProperty : sessionPropertyList) {
map.put(sessionProperty.getSessionKey(), sessionProperty.getSessionValue());
}
responseBody.put("session_property", map);
Path errorFilePath = getResultFilePath(datasource, queryId, true);
if (errorFilePath.toFile().exists()) {
try {
responseBody.put("error", String.join(System.getProperty("line.separator"), Files.readAllLines(errorFilePath)));
return;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (!resultVisible) {
responseBody.put("error", "you can't see query result which other submitted");
}
List<List<String>> rows = new ArrayList<>();
int lineNumber = 0;
Path resultFilePath = getResultFilePath(datasource, queryId, false);
if (!resultFilePath.toFile().exists()) {
responseBody.put("error", format("%s is not found", resultFilePath.getFileName()));
return;
}
try (BufferedReader reader = Files.newBufferedReader(resultFilePath, StandardCharsets.UTF_8)) {
CSVParser parser = CSVFormat.EXCEL.withDelimiter('\t').withNullString("\\N").parse(reader);
for (CSVRecord record : parser) {
List<String> row = new ArrayList<>();
record.forEach(row::add);
if (lineNumber == 0) {
responseBody.put("headers", row);
} else {
if (queryString.toLowerCase().startsWith("show") || lineNumber <= limit) {
rows.add(row);
} else {
break;
}
}
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
responseBody.put("results", rows);
}
@Nullable
private static String toSuccinctDataSize(Integer size) {
if (size == null) {
return null;
}
DataSize dataSize = new DataSize(size, DataSize.Unit.BYTE);
return dataSize.convertToMostSuccinctDataSize().toString();
}
}
|
package com.legit2.Demigods.Listeners;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.legit2.Demigods.DDivineBlocks;
import com.legit2.Demigods.Demigods;
import com.legit2.Demigods.DTributeValue;
import com.legit2.Demigods.Database.DDatabase;
import com.legit2.Demigods.Utilities.DCharUtil;
import com.legit2.Demigods.Utilities.DConfigUtil;
import com.legit2.Demigods.Utilities.DDataUtil;
import com.legit2.Demigods.Utilities.DObjUtil;
import com.legit2.Demigods.Utilities.DPlayerUtil;
import com.legit2.Demigods.Utilities.DMiscUtil;
public class DDivineBlockListener implements Listener
{
static Demigods plugin;
public static double FAVORMULTIPLIER = DConfigUtil.getSettingDouble("global_favor_multiplier");
public static int RADIUS = 8;
public DDivineBlockListener(Demigods instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGH)
public void shrineBlockInteract(PlayerInteractEvent event)
{
// Return if the player is mortal
if(!DCharUtil.isImmortal(event.getPlayer())) return;
if(event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
// Define variables
Location location = event.getClickedBlock().getLocation();
Player player = event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
String charAlliance = DCharUtil.getAlliance(charID);
String charDeity = DCharUtil.getDeity(charID);
if(event.getClickedBlock().getType().equals(Material.GOLD_BLOCK) && event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK)
{
try
{
// Shrine created!
ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location);
DDivineBlocks.createShrine(charID, locations);
player.getInventory().remove(Material.BOOK);
location.getWorld().getBlockAt(location).setType(Material.BEDROCK);
location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL);
location.getWorld().strikeLightningEffect(location);
player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased...");
player.sendMessage(ChatColor.GRAY + "A shrine has been created in the name of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!");
}
catch(Exception e)
{
// Creation of shrine failed...
e.printStackTrace();
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void shrineEntityInteract(PlayerInteractEntityEvent event)
{
// Define variables
Location location = event.getRightClicked().getLocation().subtract(0.5, 1.0, 0.5);
Player player = event.getPlayer();
// First handle admin wand
if(DMiscUtil.hasPermissionOrOP(player, "demigods.admin") && DDataUtil.hasPlayerData(player, "temp_admin_wand") && DDataUtil.getPlayerData(player, "temp_admin_wand").equals(true) && player.getItemInHand().getTypeId() == DConfigUtil.getSettingInt("admin_wand_tool"))
{
if(DDataUtil.hasPlayerData(player, "temp_destroy_shrine") && System.currentTimeMillis() < DObjUtil.toLong(DDataUtil.getPlayerData(player, "temp_destroy_shrine")))
{
// We can destroy the Shrine
event.getRightClicked().remove();
location.getBlock().setType(Material.AIR);
DDivineBlocks.removeShrine(location);
// Drop the block of gold and book
location.getWorld().dropItemNaturally(location, new ItemStack(Material.GOLD_BLOCK, 1));
location.getWorld().dropItemNaturally(location, new ItemStack(Material.BOOK, 1));
// Save Divine Blocks
DDatabase.saveDivineBlocks();
player.sendMessage(ChatColor.RED + "Shrine removed!");
return;
}
else
{
DDataUtil.savePlayerData(player, "temp_destroy_shrine", System.currentTimeMillis() + 5000);
player.sendMessage(ChatColor.RED + "If you want to destroy this shrine, please click it again.");
return;
}
}
// Return if the player is mortal
if(!DCharUtil.isImmortal(event.getPlayer())) event.getPlayer().sendMessage(ChatColor.RED + "Mortals can't do that!");
// More variables
int charID = DPlayerUtil.getCurrentChar(player);
try
{
// Check if block is divine
int shrineOwner = DDivineBlocks.getShrineOwner(location);
String shrineDeity = DDivineBlocks.getShrineDeity(location);
OfflinePlayer charOwner = DCharUtil.getOwner(shrineOwner);
if(shrineDeity == null) return;
if(DDivineBlocks.isDivineBlock(location))
{
// Check if character has deity
if(DCharUtil.hasDeity(charID, shrineDeity))
{
// Open the tribute inventory
Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, charOwner.getName() + "'s Shrine to " + shrineDeity);
player.openInventory(ii);
DDataUtil.saveCharData(charID, "temp_tributing", shrineOwner);
event.setCancelled(true);
return;
}
player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here.");
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerTribute(InventoryCloseEvent event)
{
try
{
if(!(event.getPlayer() instanceof Player)) return;
Player player = (Player)event.getPlayer();
int charID = DPlayerUtil.getCurrentChar(player);
String charDeity = DCharUtil.getDeity(charID);
if(!DCharUtil.isImmortal(player)) return;
// If it isn't a tribute chest then break the method
if(!event.getInventory().getName().contains("Shrine")) return;
// Get the creator of the shrine
//int shrineCreator = DDivineBlocks.getShrineOwner((Location) DDataUtil.getCharData(charID, "temp_tributing"));
DDataUtil.removeCharData(charID, "temp_tributing");
//calculate value of chest
int tributeValue = 0, items = 0;
for(ItemStack ii : event.getInventory().getContents())
{
if(ii != null)
{
tributeValue += DTributeValue.getTributeValue(ii);
items ++;
}
}
tributeValue *= FAVORMULTIPLIER;
// Process tributes and send messages
int favorBefore = DCharUtil.getMaxFavor(charID);
int devotionBefore = DCharUtil.getDevotion(charID);
DCharUtil.addMaxFavor(charID, tributeValue / 5);
DCharUtil.giveDevotion(charID, tributeValue);
DCharUtil.giveDevotion(charID, tributeValue / 7);
if(devotionBefore < DCharUtil.getDevotion(charID)) player.sendMessage(ChatColor.YELLOW + "Your devotion to " + charDeity + " has increased to " + DCharUtil.getDevotion(charID) + ".");
if(favorBefore < DCharUtil.getMaxFavor(charID)) player.sendMessage(ChatColor.YELLOW + "Your favor cap has increased to " + DCharUtil.getMaxFavor(charID) + ".");
// If they aren't good enough let them know
if((favorBefore == DCharUtil.getMaxFavor(charID)) && (devotionBefore == DCharUtil.getDevotion(charID)) && (items > 0)) player.sendMessage(ChatColor.YELLOW + "Your tributes were insufficient for " + charDeity + "'s blessings.");
// Clear the tribute case
event.getInventory().clear();
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGH)
public void divineBlockAlerts(PlayerMoveEvent event)
{
if(event.getFrom().distance(event.getTo()) < 0.1) return;
// Define variables
for(Location divineBlock : DDivineBlocks.getAllShrines())
{
OfflinePlayer charOwner = DCharUtil.getOwner(DDivineBlocks.getShrineOwner(divineBlock));
// Check for world errors
if(!divineBlock.getWorld().equals(event.getPlayer().getWorld())) return;
if(event.getFrom().getWorld() != divineBlock.getWorld()) return;
/*
* Entering
*/
if(event.getFrom().distance(divineBlock) > RADIUS)
{
if(divineBlock.distance(event.getTo()) <= RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have entered " + charOwner.getName() + "'s shrine to " + ChatColor.YELLOW + DDivineBlocks.getShrineDeity(divineBlock) + ChatColor.GRAY + ".");
return;
}
}
/*
* Leaving
*/
else if(event.getFrom().distance(divineBlock) <= RADIUS)
{
if(divineBlock.distance(event.getTo()) > RADIUS)
{
event.getPlayer().sendMessage(ChatColor.GRAY + "You have left a holy area.");
return;
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void stopDestroyEnderCrystal(EntityDamageEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getEntity().getLocation().subtract(0.5, 1.0, 0.5).equals(divineBlock))
{
event.setDamage(0);
event.setCancelled(true);
return;
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void stopDestroyDivineBlock(BlockBreakEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.getPlayer().sendMessage(ChatColor.YELLOW + "Divine blocks cannot be broken by hand.");
event.setCancelled(true);
return;
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockDamage(BlockDamageEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockIgnite(BlockIgniteEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockBurn(BlockBurnEvent event)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(event.getBlock().getLocation().equals(divineBlock))
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonExtend(BlockPistonExtendEvent event)
{
List<Block> blocks = event.getBlocks();
CHECKBLOCKS:
for(Block block : blocks)
{
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals(divineBlock))
{
event.setCancelled(true);
break CHECKBLOCKS;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void stopDivineBlockPistonRetract(BlockPistonRetractEvent event)
{
// Define variables
final Block block = event.getBlock().getRelative(event.getDirection(), 2);
try
{
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals((divineBlock)) && event.isSticky())
{
event.setCancelled(true);
}
}
}
catch(Exception e) {}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void divineBlockExplode(final EntityExplodeEvent event)
{
try
{
// Remove divineBlock blocks from explosions
Iterator<Block> i = event.blockList().iterator();
while(i.hasNext())
{
Block block = i.next();
if(!DMiscUtil.canLocationPVP(block.getLocation())) i.remove();
for(Location divineBlock : DDivineBlocks.getAllDivineBlocks())
{
if(block.getLocation().equals(divineBlock)) i.remove();
}
}
}
catch (Exception er) {}
}
}
|
package com.ociweb.iot.grove;
import java.io.IOException;
import java.util.Arrays;
import com.ociweb.iot.hardware.I2CConnection;
import com.ociweb.iot.hardware.IODevice;
import com.ociweb.iot.maker.CommandChannel;
import com.ociweb.pronghorn.iot.i2c.I2CStage;
import com.ociweb.pronghorn.iot.schema.I2CCommandSchema;
import com.ociweb.pronghorn.pipe.DataOutputBlobWriter;
/**
* TODO: This class probably needs to be renamed and moved; it's now both a simple API and collection of constants.
*
* @author Nathan Tippy
* @author Brandon Sanders [brandon@alicorn.io]
* @author Alex Herriott
*/
public class Grove_LCD_RGB implements IODevice{
public static boolean isStarted = false;
// Current LCD_DISPLAYCONTROL states
private static int LCD_DISPLAY =Grove_LCD_RGB_Constants.LCD_DISPLAYON;
private static int LCD_CURSOR =Grove_LCD_RGB_Constants.LCD_CURSOROFF;
private static int LCD_BLINK =Grove_LCD_RGB_Constants.LCD_BLINKOFF;
public static boolean begin(CommandChannel target){
if (!target.i2cIsReady()) {
return false;
}
isStarted = true;
writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, Grove_LCD_RGB_Constants.LCD_TWO_LINES);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, 5*Grove_LCD_RGB_Constants.MS_TO_NS); // wait more than 4.1ms
// second try
writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, Grove_LCD_RGB_Constants.LCD_TWO_LINES);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, 1*Grove_LCD_RGB_Constants.MS_TO_NS);
// third go
writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, Grove_LCD_RGB_Constants.LCD_TWO_LINES);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, 1*Grove_LCD_RGB_Constants.MS_TO_NS);
// turn the display on with no cursor or blinking default
setDisplayControl(target);
// clear it off
displayClear(target);
// set the entry mode
//writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, LCD_SETDDRAMADDR, LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, 1*Grove_LCD_RGB_Constants.MS_TO_NS);
setCursor(target, 0, 0);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, 1*Grove_LCD_RGB_Constants.MS_TO_NS);
target.i2cFlushBatch();
return true;
}
/**
* <pre>
* Creates a complete byte array that will set the text and color of a Grove RGB
* LCD display when passed to a {@link com.ociweb.pronghorn.stage.test.ByteArrayProducerStage}
* which is using chunk sizes of 3 and is being piped to a {@link I2CStage}.
*
* TODO: This function is currently causing the last letter of the text to be dropped
* when displayed on the Grove RGB LCD; there's currently a work-around that
* simply appends a space to the incoming text variable, but it's hackish
* and should be looked into more...
*
* @param text String to display on the Grove RGB LCD.
* @param r 0-255 value for the Red color.
* @param g 0-255 value for the Green color.
* @param b 0-255 value for the Blue color.
*
* @return Formatted byte array which can be passed directly to a
* {@link com.ociweb.pronghorn.stage.test.ByteArrayProducerStage}.
* </pre>
*/
public static boolean commandForTextAndColor(CommandChannel target, String text, int r, int g, int b) {
if (!target.i2cIsReady()) {
return false;
}
showRGBColor(target, r, g, b);
showTwoLineText(target, text);
target.i2cFlushBatch();
return true;
}
public static boolean commandForColor(CommandChannel target, int r, int g, int b) {
if (!target.i2cIsReady()) {
return false;
}
showRGBColor(target, r, g, b);
target.i2cFlushBatch();
return true;
}
public static boolean commandForText(CommandChannel target, String text) {
if (!target.i2cIsReady()) {
return false;
}
showTwoLineText(target, text);
target.i2cFlushBatch();
return true;
}
/**
* Switches the lcd display on or off. Default is on
*
* @param target CommandChannel to send command on
* @param on boolean to set display to
* @return boolean command is successful
*/
public static boolean commandForDisplay (CommandChannel target, boolean on){
if (!target.i2cIsReady()) {
return false;
}
if(on){
LCD_DISPLAY = Grove_LCD_RGB_Constants.LCD_DISPLAYON;
}else{
LCD_DISPLAY = Grove_LCD_RGB_Constants.LCD_DISPLAYOFF;
}
setDisplayControl(target);
target.i2cFlushBatch();
return true;
}
/**
* Switches the cursor on or off. Default is off
*
* @param target CommandChannel to send command on
* @param on boolean to set cursor to
* @return boolean command is successful
*/
public static boolean commandForCursor (CommandChannel target, boolean on){
if (!target.i2cIsReady()) {
return false;
}
if(on){
LCD_CURSOR = Grove_LCD_RGB_Constants.LCD_CURSORON;
}else{
LCD_CURSOR = Grove_LCD_RGB_Constants.LCD_CURSOROFF;
}
setDisplayControl(target);
target.i2cFlushBatch();
return true;
}
/**
* Switches the blinking cursor on or off. Default is off
*
* @param target CommandChannel to send command on
* @param on boolean to set blink to
* @return boolean command is successful
*/
public static boolean commandForBlink (CommandChannel target, boolean on){
if (!target.i2cIsReady()) {
return false;
}
if(on){
LCD_BLINK = Grove_LCD_RGB_Constants.LCD_BLINKON;
}else{
LCD_BLINK = Grove_LCD_RGB_Constants.LCD_BLINKOFF;
}
setDisplayControl(target);
target.i2cFlushBatch();
return true;
}
/**
* Creates a custom char from an array of 8 bytes. Can save up to 8 custom chars in the LCD.
* @param target CommandChannel to send command on
* @param location location 0-7 to store the charmap in the LCD
* @param charMap Array of 8 bytes. Each byte is a row. Least significant 5 bits determines values within row
* @return
*/
public static boolean setCustomChar(CommandChannel target, int location, byte charMap[]){
if (!target.i2cIsReady()) {
return false;
}
if(!isStarted){
begin(target);
}
assert(location < 8 && location >= 0) : "Only locations 0-7 are valid";
assert(charMap.length == 8) : "charMap must contain an array of 8 bytes";
location &= 0x7;
for (int i = 0; i < charMap.length; i++) {
charMap[i] &= 0x1F; //each element contains 5 bits
}
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR | (location<<3));
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.CGRAM_SET_DELAY);
writeMultipleBytesToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR, charMap);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.DDRAM_WRITE_DELAY);
target.i2cFlushBatch();
//begin(target); //TODO: Seems to be necessary, but shouldn't be
return true;
}
/**
* Writes an ascii char with idx characterIdx. Locations 0-7 contain custom characters.
* @param target CommandChannel to send command on
* @param characterIdx Index of the character
* @return
*/
public static boolean writeChar(CommandChannel target, int characterIdx){
if (!target.i2cIsReady()) {
return false;
}
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR, characterIdx);
target.i2cDelay(Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.DDRAM_WRITE_DELAY);
target.i2cFlushBatch();
return true;
}
public static boolean writeMultipleChars(CommandChannel target, byte[] characterIdx, int col, int row){
if (!target.i2cIsReady()) {
return false;
}
int steps = 4;
int iterator = 0;
setCursor(target, col, row);
while(iterator<characterIdx.length){
writeMultipleBytesToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR,
Arrays.copyOfRange(characterIdx, iterator, iterator + Math.min(Math.min(16-col, characterIdx.length-iterator), steps)));
col += Math.min(Math.min(16-col, characterIdx.length-iterator), steps);
iterator += Math.min(Math.min(16-col, characterIdx.length-iterator), steps);
row = (row + col/16) % 2;
col = col % 16;
setCursor(target, col, row);
}
target.i2cFlushBatch();
return true;
}
// int steps = 4;
// for(String line: lines) {
// int p = 0;
// while (p<line.length()) {
// writeUTF8ToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR, line, p, Math.min(steps, line.length()-p) );
// p+=steps;
// //new line
// writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, 0xc0);
public static boolean clearDisplay(CommandChannel target){
if (!target.i2cIsReady()) {
return false;
}
displayClear(target);
target.i2cFlushBatch();
return true;
}
public static boolean setCursor(CommandChannel target, int col, int row){
if (!target.i2cIsReady()) {
return false;
}
col = (row == 0 ? col|0x80 : col|0xc0);
writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, col);
target.i2cFlushBatch();
return true;
}
/// Private Methods ////
private static void setDisplayControl(CommandChannel target){
writeSingleByteToRegister(target, Grove_LCD_RGB_Constants.LCD_ADDRESS, Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR,
Grove_LCD_RGB_Constants.LCD_DISPLAYCONTROL | LCD_DISPLAY | LCD_CURSOR | LCD_BLINK);
target.i2cDelay((Grove_LCD_RGB_Constants.LCD_ADDRESS), Grove_LCD_RGB_Constants.DISPLAY_SWITCH_DELAY);
}
private static void showRGBColor(CommandChannel target, int r, int g, int b) {
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 0, 0);
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 1, 0);
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 0x08, 0xaa);
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 4, r);
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 3, g);
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.RGB_ADDRESS)), 2, b);
}
private static void displayClear(CommandChannel target) {
//clear display
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, Grove_LCD_RGB_Constants.LCD_CLEARDISPLAY);
target.i2cDelay((Grove_LCD_RGB_Constants.LCD_ADDRESS), Grove_LCD_RGB_Constants.SCREEN_CLEAR_DELAY);
}
private static void showTwoLineText(CommandChannel target, String text) {
if(!isStarted){
begin(target);
}
displayClear(target);
String[] lines = text.split("\n");
int steps = 4;
for(String line: lines) {
int p = 0;
while (p<line.length()) {
writeUTF8ToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETCGRAMADDR, line, p, Math.min(steps, line.length()-p) );
p+=steps;
}
//new line
writeSingleByteToRegister(target, ((Grove_LCD_RGB_Constants.LCD_ADDRESS)), Grove_LCD_RGB_Constants.LCD_SETDDRAMADDR, 0xc0);
}
}
private static void writeSingleByteToRegister(CommandChannel target, int address, int register, int value) {
try {
DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = target.i2cCommandOpen(address);
//i2cPayloadWriter.write(new byte[]{(byte)register,(byte)value});
i2cPayloadWriter.writeByte(register);
i2cPayloadWriter.writeByte(value);
//System.out.println(Arrays.toString(new byte[]{(byte)register,(byte)value}));
target.i2cCommandClose();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void writeMultipleBytesToRegister(CommandChannel target, int address, int register, byte[] values) {
try {
DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = target.i2cCommandOpen(address);
i2cPayloadWriter.writeByte(register);
i2cPayloadWriter.writeByteArray(values);;
target.i2cCommandClose();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void writeUTF8ToRegister(CommandChannel target, int address, int register, CharSequence text, int pos, int len) {
try {
DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = target.i2cCommandOpen(address);
i2cPayloadWriter.writeByte(register);
DataOutputBlobWriter.encodeAsUTF8(i2cPayloadWriter, text, pos, len);
target.i2cCommandClose();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isInput() {
return false;
}
@Override
public boolean isOutput() {
return true;
}
@Override
public boolean isPWM() {
return false;
}
@Override
public int range() {
return 0;
}
@Override
public I2CConnection getI2CConnection() { //putting getI2CConnection in i2cOutput twigs allows setup commands to be sent
byte[] LCD_READCMD = {};
byte[] LCD_SETUP = {};
byte LCD_ADDR = 0x04;
byte LCD_BYTESTOREAD = 0;
byte LCD_REGISTER = 0;
return new I2CConnection(this, LCD_ADDR, LCD_READCMD, LCD_BYTESTOREAD, LCD_REGISTER, LCD_SETUP);
}
@Override
public boolean isGrove() {
return false;
}
@Override
public int response() {
return 20;
}
@Override
public boolean isValid(byte[] backing, int position, int length, int mask) {
return true;
}
@Override
public int pinsUsed() {
return 1;
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.BasicBlock.InstructionIterator;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
/**
* finds fields that are used in a locals only fashion, specifically private fields
* that are accessed first in each method with a store vs. a load.
*/
public class FieldCouldBeLocal extends BytecodeScanningDetector
{
private final BugReporter bugReporter;
private ClassContext clsContext;
private Map<String, FieldInfo> localizableFields;
private CFG cfg;
private ConstantPoolGen cpg;
private BitSet visitedBlocks;
private Map<String, Set<String>> methodFieldModifiers;
private String clsName;
/**
* constructs a FCBL detector given the reporter to report bugs on.
* @param bugReporter the sync of bug reports
*/
public FieldCouldBeLocal(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* overrides the visitor to collect localizable fields, and then report those that
* survive all method checks.
*
* @param classContext the context object that holds the JavaClass parsed
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
localizableFields = new HashMap<String, FieldInfo>();
visitedBlocks = new BitSet();
clsContext = classContext;
clsName = clsContext.getJavaClass().getClassName();
JavaClass cls = classContext.getJavaClass();
Field[] fields = cls.getFields();
ConstantPool cp = classContext.getConstantPoolGen().getConstantPool();
for (Field f : fields) {
if (!f.isStatic() && !f.isVolatile() && (f.getName().indexOf('$') < 0) && f.isPrivate()) {
FieldAnnotation fa = new FieldAnnotation(cls.getClassName(), f.getName(), f.getSignature(), false);
boolean hasExternalAnnotation = false;
for (AnnotationEntry entry : f.getAnnotationEntries()) {
ConstantUtf8 cutf = (ConstantUtf8) cp.getConstant(entry.getTypeIndex());
if (!cutf.getBytes().startsWith("java")) {
hasExternalAnnotation = true;
break;
}
}
localizableFields.put(f.getName(), new FieldInfo(fa, hasExternalAnnotation));
}
}
if (localizableFields.size() > 0) {
buildMethodFieldModifiers(classContext);
super.visitClassContext(classContext);
for (FieldInfo fi : localizableFields.values()) {
FieldAnnotation fa = fi.getFieldAnnotation();
SourceLineAnnotation sla = fi.getSrcLineAnnotation();
BugInstance bug = new BugInstance(this, BugType.FCBL_FIELD_COULD_BE_LOCAL.name(), NORMAL_PRIORITY)
.addClass(this)
.addField(fa);
if (sla != null)
bug.addSourceLine(sla);
bugReporter.reportBug(bug);
}
}
} finally {
localizableFields = null;
visitedBlocks = null;
clsContext = null;
methodFieldModifiers = null;
}
}
/**
* overrides the visitor to navigate basic blocks looking for all first usages of fields, removing
* those that are read from first.
*
* @param obj the context object of the currently parsed method
*/
@Override
public void visitMethod(Method obj) {
if (localizableFields.isEmpty())
return;
try {
cfg = clsContext.getCFG(obj);
cpg = cfg.getMethodGen().getConstantPool();
BasicBlock bb = cfg.getEntry();
Set<String> uncheckedFields = new HashSet<String>(localizableFields.keySet());
visitedBlocks.clear();
checkBlock(bb, uncheckedFields);
}
catch (CFGBuilderException cbe) {
localizableFields.clear();
}
finally {
cfg = null;
cpg = null;
}
}
/**
* looks for methods that contain a GETFIELD or PUTFIELD opcodes
*
* @param method the context object of the current method
* @return if the class uses synchronization
*/
private boolean prescreen(Method method) {
BitSet bytecodeSet = getClassContext().getBytecodeSet(method);
return (bytecodeSet != null) && (bytecodeSet.get(Constants.PUTFIELD) || bytecodeSet.get(Constants.GETFIELD));
}
/**
* implements the visitor to pass through constructors and static initializers to the
* byte code scanning code. These methods are not reported, but are used to build
* SourceLineAnnotations for fields, if accessed.
*
* @param obj the context object of the currently parsed code attribute
*/
@Override
public void visitCode(Code obj) {
Method m = getMethod();
if (prescreen(m)) {
String methodName = m.getName();
if ("<clinit".equals(methodName) || Values.CONSTRUCTOR.equals(methodName))
super.visitCode(obj);
}
}
/**
* implements the visitor to add SourceLineAnnotations for fields in constructors and static
* initializers.
*
* @param seen the opcode of the currently visited instruction
*/
@Override
public void sawOpcode(int seen) {
if ((seen == GETFIELD) || (seen == PUTFIELD)) {
String fieldName = getNameConstantOperand();
FieldInfo fi = localizableFields.get(fieldName);
if (fi != null) {
SourceLineAnnotation sla = SourceLineAnnotation.fromVisitedInstruction(this);
fi.setSrcLineAnnotation(sla);
}
}
}
/**
* looks in this basic block for the first access to the fields in uncheckedFields. Once found
* the item is removed from uncheckedFields, and removed from localizableFields if the access is
* a GETFIELD. If any unchecked fields remain, this method is recursively called on all outgoing edges
* of this basic block.
*
* @param bb this basic block
* @param uncheckedFields the list of fields to look for
*/
private void checkBlock(BasicBlock bb, Set<String> uncheckedFields) {
LinkedList<BlockState> toBeProcessed = new LinkedList<BlockState>();
toBeProcessed.add(new BlockState(bb, uncheckedFields));
visitedBlocks.set(bb.getLabel());
while (!toBeProcessed.isEmpty()) {
if (localizableFields.isEmpty())
return;
BlockState bState = toBeProcessed.removeFirst();
bb = bState.getBasicBlock();
InstructionIterator ii = bb.instructionIterator();
while ((bState.getUncheckedFieldSize() > 0) && ii.hasNext()) {
InstructionHandle ih = ii.next();
Instruction ins = ih.getInstruction();
if (ins instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) ins;
String fieldName = fi.getFieldName(cpg);
FieldInfo finfo = localizableFields.get(fieldName);
if ((finfo != null) && localizableFields.get(fieldName).hasAnnotation()) {
localizableFields.remove(fieldName);
} else {
boolean justRemoved = bState.removeUncheckedField(fieldName);
if (ins instanceof GETFIELD) {
if (justRemoved) {
localizableFields.remove(fieldName);
if (localizableFields.isEmpty())
return;
}
} else {
if (finfo != null)
finfo.setSrcLineAnnotation(SourceLineAnnotation.fromVisitedInstruction(clsContext, this, ih.getPosition()));
}
}
} else if (ins instanceof INVOKESPECIAL) {
INVOKESPECIAL is = (INVOKESPECIAL) ins;
if (Values.CONSTRUCTOR.equals(is.getMethodName(cpg)) && (is.getClassName(cpg).startsWith(clsContext.getJavaClass().getClassName() + "$"))) {
localizableFields.clear();
}
} else if (ins instanceof INVOKEVIRTUAL) {
INVOKEVIRTUAL is = (INVOKEVIRTUAL) ins;
if (is.getClassName(cpg).equals(clsName)) {
String methodDesc = is.getName(cpg) + is.getSignature(cpg);
Set<String> fields = methodFieldModifiers.get(methodDesc);
if (fields != null) {
for (String field : fields) {
localizableFields.remove(field);
}
}
}
}
}
if (bState.getUncheckedFieldSize() > 0) {
Iterator<Edge> oei = cfg.outgoingEdgeIterator(bb);
while (oei.hasNext()) {
Edge e = oei.next();
BasicBlock cb = e.getTarget();
int label = cb.getLabel();
if (!visitedBlocks.get(label)) {
toBeProcessed.addLast(new BlockState(cb, bState));
visitedBlocks.set(label);
}
}
}
}
}
/**
* builds up the method to field map of what method write to which fields
* this is one recursively so that if method A calls method B, and method B
* writes to field C, then A modifies F.
*
* @param classContext the context object of the currently parsed class
*/
private void buildMethodFieldModifiers(ClassContext classContext) {
FieldModifier fm = new FieldModifier();
fm.visitClassContext(classContext);
methodFieldModifiers = fm.getMethodFieldModifiers();
}
/**
* holds information about a field and it's first usage
*/
private static class FieldInfo {
private final FieldAnnotation fieldAnnotation;
private SourceLineAnnotation srcLineAnnotation;
private final boolean hasAnnotation;
/**
* creates a FieldInfo from an annotation, and assumes no source line information
* @param fa the field annotation for this field
* @param hasExternalAnnotation the field has a non java based annotation
*/
FieldInfo(final FieldAnnotation fa, boolean hasExternalAnnotation) {
fieldAnnotation = fa;
srcLineAnnotation = null;
hasAnnotation = hasExternalAnnotation;
}
/**
* set the source line annotation of first use for this field
* @param sla the source line annotation
*/
void setSrcLineAnnotation(final SourceLineAnnotation sla) {
if (srcLineAnnotation == null)
srcLineAnnotation = sla;
}
/**
* get the field annotation for this field
* @return the field annotation
*/
FieldAnnotation getFieldAnnotation() {
return fieldAnnotation;
}
/**
* get the source line annotation for the first use of this field
* @return the source line annotation
*/
SourceLineAnnotation getSrcLineAnnotation() {
return srcLineAnnotation;
}
/**
* gets whether the field has a non java annotation
* @return if the field has a non java annotation
*/
boolean hasAnnotation() {
return hasAnnotation;
}
@Override
public String toString() {
return ToString.build(this);
}
}
private static class BlockState {
private final BasicBlock basicBlock;
private Set<String> uncheckedFields;
private boolean fieldsAreSharedWithParent;
/**
* creates a BlockState consisting of the next basic block to parse,
* and what fields are to be checked
* @param bb the basic block to parse
* @param fields the fields to look for first use
*/
public BlockState(final BasicBlock bb, final Set<String> fields) {
basicBlock = bb;
uncheckedFields = fields;
fieldsAreSharedWithParent = true;
}
/**
* creates a BlockState consisting of the next basic block to parse,
* and what fields are to be checked
* @param bb the basic block to parse
* @param the basic block to copy from
*/
public BlockState(final BasicBlock bb, BlockState parentBlockState) {
basicBlock = bb;
uncheckedFields = parentBlockState.uncheckedFields;
fieldsAreSharedWithParent = true;
}
/**
* get the basic block to parse
* @return the basic block
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
/**
* returns the number of unchecked fields
* @return the number of unchecked fields
*/
public int getUncheckedFieldSize() {
return (uncheckedFields == null) ? 0 : uncheckedFields.size();
}
/**
* return the field from the set of unchecked fields
* if this occurs make a copy of the set on write to reduce memory usage
* @return whether the object was removed.
*/
public boolean removeUncheckedField(String field) {
if ((uncheckedFields != null) && uncheckedFields.contains(field)) {
if (uncheckedFields.size() == 1) {
uncheckedFields = null;
fieldsAreSharedWithParent = false;
return true;
}
if (fieldsAreSharedWithParent) {
uncheckedFields = new HashSet<String>(uncheckedFields);
fieldsAreSharedWithParent = false;
uncheckedFields.remove(field);
} else {
uncheckedFields.remove(field);
}
return true;
}
return false;
}
@Override
public String toString() {
return ToString.build(this);
}
}
private static class FieldModifier extends BytecodeScanningDetector {
private final Map<String, Set<String>> methodCallChain = new HashMap<String, Set<String>>();
private final Map<String, Set<String>> mfModifiers = new HashMap<String, Set<String>>();
private String clsName;
public Map<String, Set<String>> getMethodFieldModifiers() {
Map<String, Set<String>> modifiers = new HashMap<String, Set<String>>(mfModifiers.size());
modifiers.putAll(mfModifiers);
for (Entry<String, Set<String>> method : modifiers.entrySet()) {
modifiers.put(method.getKey(), new HashSet<String>(method.getValue()));
}
boolean modified = true;
while (modified) {
modified = false;
for (Map.Entry<String, Set<String>> entry : methodCallChain.entrySet()) {
String methodDesc = entry.getKey();
Set<String> calledMethods = entry.getValue();
for (String calledMethodDesc : calledMethods) {
Set<String> fields = mfModifiers.get(calledMethodDesc);
if (fields != null) {
Set<String> flds = modifiers.get(methodDesc);
if (flds == null) {
flds = new HashSet<String>();
modifiers.put(methodDesc, flds);
}
if (flds.addAll(fields))
modified = true;
}
}
}
}
return modifiers;
}
@Override
public void visitClassContext(ClassContext context) {
clsName = context.getJavaClass().getClassName();
super.visitClassContext(context);
}
@Override
public void sawOpcode(int seen) {
if (seen == PUTFIELD) {
if (clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName()+getMethodSig();
Set<String> fields = mfModifiers.get(methodDesc);
if (fields == null) {
fields = new HashSet<String>();
mfModifiers.put(methodDesc, fields);
}
fields.add(getNameConstantOperand());
}
} else if (seen == INVOKEVIRTUAL) {
if (clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName()+getMethodSig();
Set<String> methods = methodCallChain.get(methodDesc);
if (methods == null) {
methods = new HashSet<String>();
methodCallChain.put(methodDesc, methods);
}
methods.add(getNameConstantOperand()+getSigConstantOperand());
}
}
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
|
package com.redhat.ceylon.compiler.typechecker;
import java.util.List;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator;
import com.redhat.ceylon.compiler.typechecker.context.Context;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.io.VFS;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.util.AssertionVisitor;
import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory;
import com.redhat.ceylon.compiler.typechecker.util.StatisticsVisitor;
/**
* Executes type checking upon construction and retrieve a CompilationUnit object for a given File.
*
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
//TODO make an interface?
public class TypeChecker {
public static final String LANGUAGE_MODULE_VERSION = "0.3.1";
private final boolean verbose;
private final boolean statistics;
private final List<VirtualFile> srcDirectories;
private final Context context;
private final PhasedUnits phasedUnits;
private List<PhasedUnits> phasedUnitsOfDependencies;
private final boolean verifyDependencies;
private final AssertionVisitor assertionVisitor;
private final StatisticsVisitor statsVisitor;
//package level
TypeChecker(VFS vfs, List<VirtualFile> srcDirectories, RepositoryManager repositoryManager, boolean verifyDependencies,
AssertionVisitor assertionVisitor, ModuleManagerFactory moduleManagerFactory, boolean verbose, boolean statistics,
List<String> moduleFilters) {
long start = System.nanoTime();
this.srcDirectories = srcDirectories;
this.verbose = verbose;
this.statistics = statistics;
this.context = new Context(repositoryManager, vfs);
this.phasedUnits = new PhasedUnits(context, moduleManagerFactory);
this.verifyDependencies = verifyDependencies;
this.assertionVisitor = assertionVisitor;
statsVisitor = new StatisticsVisitor();
phasedUnits.setModuleFilters(moduleFilters);
phasedUnits.parseUnits(srcDirectories);
long time = System.nanoTime()-start;
if(statistics)
System.out.println("Parsed in " + time/1000000 + " ms");
}
public PhasedUnits getPhasedUnits() {
return phasedUnits;
}
public List<PhasedUnits> getPhasedUnitsOfDependencies() {
return phasedUnitsOfDependencies;
}
public void setPhasedUnitsOfDependencies(
List<PhasedUnits> phasedUnitsOfDependencies) {
this.phasedUnitsOfDependencies = phasedUnitsOfDependencies;
}
public Context getContext() {
return context;
}
/**
* Return the PhasedUnit for a given relative path.
* The path is relative to the source directory
* eg ceylon/language/Object.ceylon
*/
public PhasedUnit getPhasedUnitFromRelativePath(String relativePath) {
PhasedUnit phasedUnit = phasedUnits.getPhasedUnitFromRelativePath(relativePath);
if (phasedUnit == null) {
for (PhasedUnits units : phasedUnitsOfDependencies) {
phasedUnit = units.getPhasedUnitFromRelativePath(relativePath);
if (phasedUnit != null) {
return phasedUnit;
}
}
return null;
}
else {
return phasedUnit;
}
}
public PhasedUnit getPhasedUnit(VirtualFile file) {
PhasedUnit phasedUnit = phasedUnits.getPhasedUnit(file);
if (phasedUnit == null) {
for (PhasedUnits units : phasedUnitsOfDependencies) {
phasedUnit = units.getPhasedUnit(file);
if (phasedUnit != null) {
return phasedUnit;
}
}
return null;
}
else {
return phasedUnit;
}
}
/*
* Return the CompilationUnit for a given file.
* May return null of the CompilationUnit has not been parsed.
*/
/*public Tree.CompilationUnit getCompilationUnit(File file) {
final PhasedUnit phasedUnit = phasedUnits.getPhasedUnit( context.getVfs().getFromFile(file) );
return phasedUnit.getCompilationUnit();
}*/
public void process() throws RuntimeException {
long start = System.nanoTime();
executePhases(phasedUnits, false);
long time = System.nanoTime()-start;
if(statistics)
System.out.println("Type checked in " + time/1000000 + " ms");
}
private void executePhases(PhasedUnits phasedUnits, boolean forceSilence) {
final List<PhasedUnit> listOfUnits = phasedUnits.getPhasedUnits();
phasedUnits.getModuleManager().prepareForTypeChecking();
phasedUnits.visitModules();
phasedUnits.getModuleManager().modulesVisited();
//By now le language module version should be known (as local)
//or we should use the default one.
Module languageModule = context.getModules().getLanguageModule();
if (languageModule.getVersion() == null) {
languageModule.setVersion(LANGUAGE_MODULE_VERSION);
}
final ModuleValidator moduleValidator = new ModuleValidator(context, phasedUnits);
if (verifyDependencies) {
moduleValidator.verifyModuleDependencyTree();
}
phasedUnitsOfDependencies = moduleValidator.getPhasedUnitsOfDependencies();
for (PhasedUnit pu : listOfUnits) {
pu.validateTree();
pu.scanDeclarations();
}
for (PhasedUnit pu : listOfUnits) {
pu.scanTypeDeclarations();
}
for (PhasedUnit pu: listOfUnits) {
pu.validateRefinement();
}
for (PhasedUnit pu : listOfUnits) {
pu.analyseTypes();
}
for (PhasedUnit pu: listOfUnits) {
pu.analyseFlow();
}
for (PhasedUnit pu: listOfUnits) {
pu.analyseUsage();
}
if (!forceSilence) {
for (PhasedUnit pu : listOfUnits) {
if (verbose) {
pu.display();
}
pu.generateStatistics(statsVisitor);
pu.runAssertions(assertionVisitor);
}
if(verbose||statistics)
statsVisitor.print();
assertionVisitor.print(verbose);
}
}
public int getErrors(){
return assertionVisitor.getErrors();
}
public int getWarnings(){
return assertionVisitor.getWarnings();
}
public List<Message> getMessages(){
return assertionVisitor.getFoundErrors();
}
}
|
package com.rarchives.ripme.utils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.rarchives.ripme.ripper.AbstractRipper;
import com.rarchives.ripme.ripper.rippers.ImgurRipper;
import com.rarchives.ripme.ripper.rippers.VidbleRipper;
import com.rarchives.ripme.ripper.rippers.ImgurRipper.ImgurAlbum;
import com.rarchives.ripme.ripper.rippers.ImgurRipper.ImgurImage;
import com.rarchives.ripme.ripper.rippers.video.GfycatRipper;
public class RipUtils {
private static final Logger logger = Logger.getLogger(RipUtils.class);
public static List<URL> getFilesFromURL(URL url) {
List<URL> result = new ArrayList<URL>();
logger.debug("Checking " + url);
// Imgur album
if ((url.getHost().endsWith("imgur.com"))
&& url.toExternalForm().contains("imgur.com/a/")) {
try {
ImgurAlbum imgurAlbum = ImgurRipper.getImgurAlbum(url);
for (ImgurImage imgurImage : imgurAlbum.images) {
result.add(imgurImage.url);
}
} catch (IOException e) {
logger.error("[!] Exception while loading album " + url, e);
}
return result;
}
else if (url.getHost().endsWith("gfycat.com")) {
try {
String videoURL = GfycatRipper.getVideoURL(url);
result.add(new URL(videoURL));
} catch (IOException e) {
// Do nothing
logger.warn("Exception while retrieving gfycat page:", e);
}
return result;
}
else if (url.toExternalForm().contains("vidble.com/album/")) {
try {
result.addAll(VidbleRipper.getURLsFromPage(url));
} catch (IOException e) {
// Do nothing
logger.warn("Exception while retrieving vidble page:", e);
}
return result;
}
// Direct link to image
Pattern p = Pattern.compile("(https?://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(/\\S*)\\.(jpg|jpeg|gif|png|mp4)(\\?.*)?)");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
try {
URL singleURL = new URL(m.group(1));
result.add(singleURL);
return result;
} catch (MalformedURLException e) {
logger.error("[!] Not a valid URL: '" + url + "'", e);
}
}
if (url.getHost().equals("imgur.com") ||
url.getHost().equals("m.imgur.com")){
try {
// Fetch the page
Document doc = Jsoup.connect(url.toExternalForm())
.userAgent(AbstractRipper.USER_AGENT)
.get();
for (Element el : doc.select("meta")) {
if (el.attr("name").equals("twitter:image:src")) {
result.add(new URL(el.attr("content")));
return result;
}
}
} catch (IOException ex) {
logger.error("[!] Error", ex);
}
}
logger.error("[!] Unable to rip URL: " + url);
return result;
}
public static Pattern getURLRegex() {
return Pattern.compile("(https?://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(/\\S*))");
}
}
|
package com.redhat.ceylon.compiler.typechecker;
import java.util.List;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator;
import com.redhat.ceylon.compiler.typechecker.context.Context;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.io.VFS;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.util.AssertionVisitor;
import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory;
import com.redhat.ceylon.compiler.typechecker.util.StatisticsVisitor;
import com.redhat.ceylon.model.typechecker.model.Module;
/**
* Executes type checking upon construction and retrieve a CompilationUnit object for a given File.
*
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
//TODO make an interface?
public class TypeChecker {
public static final String LANGUAGE_MODULE_VERSION = Versions.CEYLON_VERSION_NUMBER;
private final boolean verbose;
private final boolean statistics;
private final Context context;
private final PhasedUnits phasedUnits;
private List<PhasedUnits> phasedUnitsOfDependencies;
private final boolean verifyDependencies;
private final AssertionVisitor assertionVisitor;
private final StatisticsVisitor statsVisitor;
//package level
TypeChecker(VFS vfs, List<VirtualFile> srcDirectories, RepositoryManager repositoryManager, boolean verifyDependencies,
AssertionVisitor assertionVisitor, ModuleManagerFactory moduleManagerFactory, boolean verbose, boolean statistics,
List<String> moduleFilters, List<VirtualFile> srcFiles, String encoding) {
long start = System.nanoTime();
this.verbose = verbose;
this.statistics = statistics;
this.context = new Context(repositoryManager, vfs);
this.phasedUnits = new PhasedUnits(context, moduleManagerFactory);
this.verifyDependencies = verifyDependencies;
this.assertionVisitor = assertionVisitor;
statsVisitor = new StatisticsVisitor();
phasedUnits.setSourceFiles(srcFiles);
phasedUnits.setModuleFilters(moduleFilters);
phasedUnits.setEncoding(encoding);
phasedUnits.parseUnits(srcDirectories);
long time = System.nanoTime()-start;
if(statistics)
System.out.println("Parsed in " + time/1000000 + " ms");
}
public PhasedUnits getPhasedUnits() {
return phasedUnits;
}
public List<PhasedUnits> getPhasedUnitsOfDependencies() {
return phasedUnitsOfDependencies;
}
public void setPhasedUnitsOfDependencies(
List<PhasedUnits> phasedUnitsOfDependencies) {
this.phasedUnitsOfDependencies = phasedUnitsOfDependencies;
}
public Context getContext() {
return context;
}
/**
* Return the PhasedUnit for a given relative path.
* The path is relative to the source directory
* eg ceylon/language/Object.ceylon
*/
public PhasedUnit getPhasedUnitFromRelativePath(String relativePath) {
PhasedUnit phasedUnit = phasedUnits.getPhasedUnitFromRelativePath(relativePath);
if (phasedUnit == null) {
for (PhasedUnits units : phasedUnitsOfDependencies) {
phasedUnit = units.getPhasedUnitFromRelativePath(relativePath);
if (phasedUnit != null) {
return phasedUnit;
}
}
return null;
}
else {
return phasedUnit;
}
}
public PhasedUnit getPhasedUnit(VirtualFile file) {
PhasedUnit phasedUnit = phasedUnits.getPhasedUnit(file);
if (phasedUnit == null) {
for (PhasedUnits units : phasedUnitsOfDependencies) {
phasedUnit = units.getPhasedUnit(file);
if (phasedUnit != null) {
return phasedUnit;
}
}
return null;
}
else {
return phasedUnit;
}
}
/*
* Return the CompilationUnit for a given file.
* May return null of the CompilationUnit has not been parsed.
*/
/*public Tree.CompilationUnit getCompilationUnit(File file) {
final PhasedUnit phasedUnit = phasedUnits.getPhasedUnit( context.getVfs().getFromFile(file) );
return phasedUnit.getCompilationUnit();
}*/
public void process() throws RuntimeException {
process(false);
}
public void process(boolean forceSilence) throws RuntimeException {
long start = System.nanoTime();
executePhases(phasedUnits, forceSilence);
long time = System.nanoTime()-start;
if(statistics)
System.out.println("Type checked in " + time/1000000 + " ms");
}
private void executePhases(PhasedUnits phasedUnits, boolean forceSilence) {
List<PhasedUnit> listOfUnits = phasedUnits.getPhasedUnits();
phasedUnits.getModuleManager().prepareForTypeChecking();
phasedUnits.visitModules();
phasedUnits.getModuleManager().modulesVisited();
//By now le language module version should be known (as local)
//or we should use the default one.
Module languageModule = context.getModules().getLanguageModule();
if (languageModule.getVersion() == null) {
languageModule.setVersion(LANGUAGE_MODULE_VERSION);
}
ModuleValidator moduleValidator =
new ModuleValidator(context, phasedUnits);
if (verifyDependencies) {
moduleValidator.verifyModuleDependencyTree();
}
phasedUnitsOfDependencies =
moduleValidator.getPhasedUnitsOfDependencies();
executePhases(listOfUnits);
if (!forceSilence) {
for (PhasedUnit pu : listOfUnits) {
if (verbose) {
pu.display();
}
pu.generateStatistics(statsVisitor);
pu.runAssertions(assertionVisitor);
}
if (verbose||statistics) {
statsVisitor.print();
}
assertionVisitor.print(verbose);
}
}
protected void executePhases(List<PhasedUnit> listOfUnits) {
for (PhasedUnit pu : listOfUnits) {
pu.validateTree();
pu.scanDeclarations();
}
for (PhasedUnit pu : listOfUnits) {
pu.scanTypeDeclarations();
}
for (PhasedUnit pu: listOfUnits) {
pu.validateRefinement();
}
for (PhasedUnit pu : listOfUnits) {
pu.analyseTypes();
}
for (PhasedUnit pu: listOfUnits) {
pu.analyseFlow();
}
for (PhasedUnit pu: listOfUnits) {
pu.analyseUsage();
}
}
public int getErrors(){
return assertionVisitor.getErrors();
}
public int getWarnings(){
return assertionVisitor.getWarnings();
}
public List<Message> getMessages(){
return assertionVisitor.getFoundErrors();
}
}
|
package com.rmn.testrail.entity;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.Serializable;
/**
* @author mmerrell
*
* If you have custom fields on TestResults in TestRails, it will be necessary to extend this class and add those fields in order to capture them.
* Otherwise they will be ignored.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestResult extends BaseEntity implements Serializable {
@JsonProperty("id")
private Integer id;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@JsonProperty("case_id")
private Integer caseId;
public Integer getCaseId() { return caseId; }
public void setCaseId(Integer caseId) { this.caseId = caseId; }
@JsonProperty("test_id")
private Integer testId;
public Integer getTestId() { return testId; }
public void setTestId(Integer testId) { this.testId = testId; }
@JsonProperty("status_id")
private Integer statusId;
public Integer getStatusId() { return statusId; }
public void setStatusId(Integer statusId) { this.statusId = statusId; }
@JsonProperty("created_by")
private Integer createdBy;
public Integer getCreatedBy() { return createdBy; }
public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; }
@JsonProperty("created_on")
private Integer createdOn;
public Integer getCreatedOn() { return createdOn; }
public void setCreatedOn(Integer createdOn) { this.createdOn = createdOn; }
@JsonProperty("assignedto_id")
private Integer assignedtoId;
public Integer getAssignedtoId() { return assignedtoId; }
public void setAssignedtoId(Integer assignedtoId) { this.assignedtoId = assignedtoId; }
@JsonProperty("comment")
private String comment = "";
public String getComment() { return comment; }
public void setComment(String comment) { this.comment = comment; }
@JsonProperty("version")
private String version;
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
@JsonProperty("elapsed")
private String elapsed;
public String getElapsed() { return elapsed; }
public void setElapsed(String elapsed) { this.elapsed = elapsed; }
@JsonProperty("defects")
private String defects;
public String getDefects() { return defects; }
public void setDefects(String defects) { this.defects = defects; }
/**
* Set the Verdict for this TestResult (does not actually send the update to the TestRails Service)
* @param verdict the String verdict
*/
public void setVerdict(String verdict) {
this.statusId = TestStatus.getStatus(verdict);
}
/**
* Set the verdict by using the actual StatusId (useful for customizations). Alternatively, you can extend the TestStatus
* class and add custom status key-value pairs to it. This method can't be overloaded to match setVerdict(int), because
* it confuses Jackson's Serializer
* @param verdict the integer verdict
*/
public void setVerdictId(int verdict) {
this.statusId = verdict;
}
}
|
package com.sandwell.JavaSimulation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.InputGroup;
import com.jaamsim.input.Output;
import com.jaamsim.input.OutputHandle;
import com.jaamsim.units.Unit;
/**
* Abstract class that encapsulates the methods and data needed to create a
* simulation object. Encapsulates the basic system objects to achieve discrete
* event execution.
*/
public class Entity {
private static long entityCount = 0;
private static final ArrayList<Entity> allInstances;
private static final HashMap<String, Entity> namedEntities;
private String entityName;
private String entityInputName; // Name input by user
private final long entityNumber;
private HashMap<String, OutputHandle> outputCache = null;
// A list of outputs, sorted first by class, then alphabetically
private String[] sortedOutputNames = null;
//public static final int FLAG_TRACE = 0x01; // reserved in case we want to treat tracing like the other flags
public static final int FLAG_TRACEREQUIRED = 0x02;
public static final int FLAG_TRACESTATE = 0x04;
public static final int FLAG_LOCKED = 0x08;
public static final int FLAG_TRACKEVENTS = 0x10;
public static final int FLAG_ADDED = 0x20;
public static final int FLAG_EDITED = 0x40;
public static final int FLAG_GENERATED = 0x80;
public static final int FLAG_DEAD = 0x0100;
private int flags;
protected boolean traceFlag = false;
private final ArrayList<Input<?>> editableInputs;
private final HashMap<String, Input<?>> inputMap;
private final ArrayList<InputGroup> inputGroups;
static {
allInstances = new ArrayList<Entity>(100);
namedEntities = new HashMap<String, Entity>(100);
}
/**
* Constructor for entity initializing members.
*/
public Entity() {
entityNumber = ++entityCount;
synchronized(allInstances) {
allInstances.add(this);
}
flags = 0;
editableInputs = new ArrayList<Input<?>>();
inputMap = new HashMap<String, Input<?>>();
inputGroups = new ArrayList<InputGroup>();
}
public static ArrayList<? extends Entity> getAll() {
synchronized(allInstances) {
return allInstances;
}
}
public static Entity idToEntity(long id) {
synchronized (allInstances) {
for (Entity e : allInstances) {
if (e.getEntityNumber() == id) {
return e;
}
}
return null;
}
}
// This is defined for handlers only
public void validate() throws InputErrorException {
for (InputGroup grp : inputGroups) {
grp.validate();
}
}
public void earlyInit() {
for (InputGroup grp : inputGroups) {
grp.earlyInit();
}
}
public void startUp() {}
public void kill() {
synchronized (allInstances) {
allInstances.remove(this);
}
if (namedEntities.get(this.getInputName()) == this)
namedEntities.remove(this.getInputName());
setFlag(FLAG_DEAD);
}
public void doEnd() {}
public static Entity getNamedEntity(String name) {
return namedEntities.get(name);
}
public static long getEntitySequence() {
long seq = (long)allInstances.size() << 32;
seq += entityCount;
return seq;
}
/**
* Get the current Simulation ticks value.
* @return the current simulation tick
*/
public final long getSimTicks() {
try {
return Process.currentTime();
}
catch (ErrorException e) {
return EventManager.rootManager.currentTime();
}
}
/**
* Get the current Simulation time.
* @return the current time in seconds
*/
public final double getSimTime() {
long ticks = getSimTicks();
return ticks * Process.getSecondsPerTick();
}
public final double getCurrentTime() {
long ticks = getSimTicks();
return ticks / Process.getSimTimeFactor();
}
protected void mapInput(Input<?> in, String key) {
if (inputMap.put(key.toUpperCase().intern(), in) != null) {
System.out.format("WARN: keyword handled twice, %s:%s\n", this.getClass().getName(), key);
}
}
protected void addInput(Input<?> in, boolean editable, String... synonyms) {
this.mapInput(in, in.getKeyword());
// Editable inputs are sorted by category
if (editable) {
int index = editableInputs.size();
for( int i = editableInputs.size() - 1; i >= 0; i
Input<?> ei = editableInputs.get( i );
if( ei.getCategory().equals( in.getCategory() ) ) {
index = i+1;
break;
}
}
editableInputs.add(index, in);
}
for (String each : synonyms)
this.mapInput(in, each);
}
protected void addInputGroup(InputGroup grp) {
inputGroups.add(grp);
for (Input<?> in : grp.getInputs()) {
this.addInput(in, true);
}
}
public Input<?> getInput(String key) {
return inputMap.get(key.toUpperCase());
}
public ArrayList<InputGroup> getInputGroups() {
return inputGroups;
}
public void resetInputs() {
Iterator<Entry<String,Input<?>>> iterator = inputMap.entrySet().iterator();
while(iterator. hasNext()){
iterator.next().getValue().reset();
}
}
public void setFlag(int flag) {
flags |= flag;
}
public void clearFlag(int flag) {
flags &= ~flag;
}
public boolean testFlag(int flag) {
return (flags & flag) != 0;
}
public void setTraceFlag() {
traceFlag = true;
}
public void clearTraceFlag() {
traceFlag = false;
}
/**
* Static method to get the eventManager for all entities.
*/
public EventManager getEventManager() {
return EventManager.rootManager;
}
/**
* Method to return the name of the entity.
* Note that the name of the entity may not be the unique identifier used in the namedEntityHashMap; see Entity.toString()
*/
public String getName() {
if (entityName == null)
return "Entity-" + entityNumber;
else
return entityName;
}
/**
* Get the unique number for this entity
* @return
*/
public long getEntityNumber() {
return entityNumber;
}
/**
* Method to set the name of the entity.
*/
public void setName(String newName) {
entityName = newName;
}
/**
* Method to set the name of the entity to prefix+entityNumber.
*/
public void setNamePrefix(String prefix) {
entityName = prefix + entityNumber;
}
/**
* Method to return the unique identifier of the entity. Used when building Edit tree labels
* @return entityName
*/
@Override
public String toString() {
return getInputName();
}
/**
* Method to set the input name of the entity.
*/
public void setInputName(String newName) {
entityInputName = newName;
namedEntities.put(newName, this);
String name = newName;
if (newName.contains("/"))
name = newName.substring(newName.indexOf("/") + 1);
this.setName(name);
}
/**
* Method to set an alias of the entity.
*/
public void setAlias(String newName) {
namedEntities.put(newName, this);
}
/**
* Method to remove an alias of the entity.
*/
public void removeAlias(String newName) {
namedEntities.remove(newName);
}
/**
* Method to get the input name of the entity.
*/
public String getInputName() {
if (entityInputName == null) {
return this.getName();
}
else {
return entityInputName;
}
}
/**
* This method updates the Entity for changes in the given input
*/
public void updateForInput( Input<?> in ) {}
/**
* Interpret the input data in the given buffer of strings corresponding to the given keyword.
* Reads keyword from a configuration file:
* TRACE - trace flag (0 = off, 1 = on)
* @param data - Vector of Strings containing data to be parsed
* @param keyword - the keyword to determine what the data represents
*/
public void readData_ForKeyword(StringVector data, String keyword)
throws InputErrorException {
if( "TRACE".equalsIgnoreCase( keyword ) ) {
Input.assertCount(data, 1);
boolean trace = Input.parseBoolean(data.get(0));
if (trace)
this.setFlag(FLAG_TRACEREQUIRED);
else
this.clearFlag(FLAG_TRACEREQUIRED);
return;
}
if( "TRACESTATE".equalsIgnoreCase( keyword ) ) {
Input.assertCount(data, 1);
boolean value = Input.parseBoolean(data.get(0));
if (value)
this.setFlag(FLAG_TRACESTATE);
else
this.clearFlag(FLAG_TRACESTATE);
return;
}
if( "LOCK".equalsIgnoreCase( keyword ) ) {
Input.assertCount(data, 1);
boolean value = Input.parseBoolean(data.get(0));
if (!value)
throw new InputErrorException("Object cannot be unlocked");
if (value)
this.setFlag(FLAG_LOCKED);
else
this.clearFlag(FLAG_LOCKED);
return;
}
if( "LOCKKEYWORDS".equalsIgnoreCase( keyword ) ) {
// Check that the individual keywords for locking are valid
for( int i = 0; i < data.size(); i++ ) {
if( this.getInput( data.get(i) ) == null ) {
throw new InputErrorException( "LockKeyword " + data.get( i ) + " is not a valid keyword" );
}
}
// Lock the individual keywords for this entity
for( int i = 0; i < data.size(); i++ ) {
Input<?> input = this.getInput( data.get(i) );
input.setLocked( true );
}
return;
}
throw new InputErrorException( "Invalid keyword " + keyword );
}
/**
* Accessor to return information about the entity.
*/
public Vector getInfo() {
Vector info = new Vector( 1, 1 );
info.addElement( "Name" + "\t" + getName() );
String[] temp = getClass().getName().split( "[.]" );
info.addElement( "Type" + "\t" + temp[temp.length - 1] );
return info;
}
private long calculateDelayLength(double waitLength) {
return Math.round(waitLength * Process.getSimTimeFactor());
}
public double calculateDiscreteTime(double time) {
long discTime = calculateDelayLength(time);
return discTime / Process.getSimTimeFactor();
}
public double calculateEventTime(double waitLength) {
long eventTime = Process.currentTime() + this.calculateDelayLength(waitLength);
return eventTime / Process.getSimTimeFactor();
}
public double calculateEventTimeBefore(double waitLength) {
long eventTime = Process.currentTime() + (long)Math.floor(waitLength * Process.getSimTimeFactor());
return eventTime / Process.getSimTimeFactor();
}
public double calculateEventTimeAfter(double waitLength) {
long eventTime = Process.currentTime() + (long)Math.ceil(waitLength * Process.getSimTimeFactor());
return eventTime / Process.getSimTimeFactor();
}
public final void startProcess(String methodName, Object... args) {
Process.start(this, methodName, args);
}
public final void startExternalProcess(String methodName, Object... args) {
getEventManager().startExternalProcess(this, methodName, args);
}
public final void scheduleSingleProcess(String methodName, Object... args) {
getEventManager().scheduleSingleProcess(0, EventManager.PRIO_LASTFIFO, this, methodName, args);
}
/**
* Wait a number of simulated seconds.
* @param secs
*/
public final void simWait(double secs) {
simWait(secs, EventManager.PRIO_DEFAULT);
}
/**
* Wait a number of simulated seconds and a given priority.
* @param secs
* @param priority
*/
public final void simWait(double secs, int priority) {
long ticks = (long)Math.floor(secs * Process.getTicksPerSecond());
this.simWaitTicks(ticks, priority);
}
/**
* Wait a number of discrete simulation ticks.
* @param secs
*/
public final void simWaitTicks(long ticks) {
simWaitTicks(ticks, EventManager.PRIO_DEFAULT);
}
/**
* Wait a number of discrete simulation ticks and a given priority.
* @param secs
* @param priority
*/
public final void simWaitTicks(long ticks, int priority) {
getEventManager().waitTicks(ticks, priority, this);
}
/**
* Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for
* calling the wait method.
*
* @param duration The duration to wait
*/
public final void scheduleWait(double duration) {
long waitLength = calculateDelayLength(duration);
getEventManager().scheduleWait(waitLength, EventManager.PRIO_DEFAULT, this);
}
/**
* Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for
* calling the wait method.
*
* @param duration The duration to wait
* @param priority The relative priority of the event scheduled
*/
public final void scheduleWait( double duration, int priority ) {
long waitLength = calculateDelayLength(duration);
getEventManager().scheduleWait(waitLength, priority, this);
}
/**
* Schedules an event to happen as the last event at the current time.
* Additional calls to scheduleLast will place a new event as the last event.
*/
public final void scheduleLastFIFO() {
getEventManager().scheduleLastFIFO( this );
}
/**
* Schedules an event to happen as the last event at the current time.
* Additional calls to scheduleLast will place a new event as the last event.
*/
public final void scheduleLastLIFO() {
getEventManager().scheduleLastLIFO( this );
}
public final void waitUntil() {
getEventManager().waitUntil(this);
}
public final void waitUntilEnded() {
getEventManager().waitUntilEnded(this);
}
// EDIT TABLE METHODS
public ArrayList<Input<?>> getEditableInputs() {
return editableInputs;
}
/**
* Make the given keyword editable from the edit box with Synonyms
*/
public void addEditableKeyword( String keyword, String unit, String defaultValue, boolean append, String category, String... synonymsArray ) {
if( this.getInput( keyword ) == null ) {
// Create a new input object
CompatInput in = new CompatInput(this, keyword, category, defaultValue);
in.setUnits(unit);
in.setAppendable( append );
this.addInput(in, true, synonymsArray);
} else {
System.out.format("Edited keyword added twice %s:%s%n", this.getClass().getName(), keyword);
}
}
// TRACING METHODS
/**
* Track the given subroutine.
*/
public void trace(String meth) {
if (traceFlag) InputAgent.trace(0, this, meth);
}
/**
* Track the given subroutine.
*/
public void trace(int level, String meth) {
if (traceFlag) InputAgent.trace(level, this, meth);
}
/**
* Track the given subroutine (one line of text).
*/
public void trace(String meth, String text1) {
if (traceFlag) InputAgent.trace(0, this, meth, text1);
}
/**
* Track the given subroutine (two lines of text).
*/
public void trace(String meth, String text1, String text2) {
if (traceFlag) InputAgent.trace(0, this, meth, text1, text2);
}
/**
* Print an addition line of tracing.
*/
public void traceLine(String text) {
this.trace( 1, text );
}
/**
* Print an error message.
*/
public void error( String meth, String text1, String text2 ) {
InputAgent.logError("Time:%.5f Entity:%s%n%s%n%s%n%s%n",
getCurrentTime(), getName(),
meth, text1, text2);
// We don't want the model to keep executing, throw an exception and let
// the higher layers figure out if we should terminate the run or not.
throw new ErrorException("ERROR: %s", getName());
}
/**
* Print a warning message.
*/
public void warning( String meth, String text1, String text2 ) {
InputAgent.logWarning("Time:%.5f Entity:%s%n%s%n%s%n%s%n",
getCurrentTime(), getName(),
meth, text1, text2);
}
private static class OutputComparator implements Comparator<OutputHandle> {
@Override
public int compare(OutputHandle oh0, OutputHandle oh1) {
Class<?> class0 = oh0.method.getDeclaringClass();
Class<?> class1 = oh1.method.getDeclaringClass();
if (class0 == class1) {
return oh0.annotation.name().compareTo(oh1.annotation.name());
}
if (class0.isAssignableFrom(class1))
return -1;
else
return 1;
}
}
private void buildOutputCache() {
outputCache = new HashMap<String, OutputHandle>();
ArrayList<OutputHandle> handles = new ArrayList<OutputHandle>();
for (Method m : this.getClass().getMethods()) {
Output o = m.getAnnotation(Output.class);
if (o == null) {
continue;
}
// Check that this method only takes a single double (simTime) parameter
Class<?>[] paramTypes = m.getParameterTypes();
if (paramTypes.length != 1 ||
paramTypes[0] != double.class) {
continue;
}
OutputHandle handle = new OutputHandle(o, m);
handles.add(handle);
outputCache.put(o.name(), handle);
}
Collections.sort(handles, new OutputComparator());
sortedOutputNames = new String[handles.size()];
for (int i = 0; i < handles.size(); ++i) {
sortedOutputNames[i] = handles.get(i).annotation.name();
}
}
/**
* A generic method to return any declared outputs for this Entity
* @param outputName - The name of the output
* @param simTime - the simulation time to get the value for
* @param klass - the class of the return type expected
* @return
*/
@SuppressWarnings("unchecked") // This suppresses the warning on the cast, which is effectively checked
private <T> T getOutputValueImp(String outputName, double simTime, Class<T> klass) {
// lazily initialize the output cache
if (outputCache == null) {
buildOutputCache();
}
Method m = outputCache.get(outputName).method;
if (m == null) {
return null;
}
T ret = null;
try {
if (!klass.isAssignableFrom(m.getReturnType()))
return null;
ret = (T)m.invoke(this, simTime);
}
catch (InvocationTargetException ex) {}
catch (IllegalAccessException ex) {}
catch (ClassCastException ex) {}
return ret;
}
private <T> T getInputValueImp(String inputName, double simTime, Class<T> klass) {
Input<?> input = inputMap.get(inputName.toUpperCase().intern());
if (input == null) {
return null;
}
T ret = null;
try {
ret = klass.cast(input.getValue());
}
catch(ClassCastException ex) {}
return ret;
}
/**
* Returns the value of the Output for 'outputName' at 'simTime', if if can be cast to 'klass'
* This also checks the entities inputs, effectively mapping inputs to outputs
* @param outputName
* @param simTime
* @param klass
* @return
*/
public <T> T getOutputValue(String outputName, double simTime, Class<T> klass) {
T ret = getOutputValueImp(outputName, simTime, klass);
if (ret != null) {
return ret;
}
// Instead try the inputs
return getInputValueImp(outputName, simTime, klass);
}
/**
* Return the value of the output at 'simTime' with toString() called on it
* @param outputName
* @param simTime
* @return
*/
public String getOutputAsString(String outputName, double simTime) {
// lazily initialize the output cache
if (outputCache == null) {
buildOutputCache();
}
Method m = outputCache.get(outputName).method;
if (m == null) {
// Instead try the inputs
return getInputAsString(outputName);
}
String ret = null;
try {
Object o = m.invoke(this, simTime);
if (o == null)
return null;
return o.toString();
} catch (InvocationTargetException ex) {
assert false;
} catch (IllegalAccessException ex) {
assert false;
}
return ret;
}
private String getInputAsString(String inputName) {
Input<?> input = inputMap.get(inputName.toUpperCase().intern());
if (input == null) {
return null;
}
Object val = input.getValue();
if (val == null) {
return "null";
}
return val.toString();
}
public boolean hasOutput(String name, boolean includeInputs) {
if (outputCache == null)
buildOutputCache();
if (outputCache.containsKey(name))
return true;
if (includeInputs && this.getInput(name) != null)
return true;
return false;
}
public String[] getOutputNames(boolean includeInputs) {
// lazily initialize the output cache
if (outputCache == null) {
buildOutputCache();
}
int outputSize = outputCache.size();
if (includeInputs) {
outputSize += inputMap.size();
}
String[] ret = new String[outputSize];
int outIndex = 0;
for (String s : outputCache.keySet()) {
ret[outIndex++] = s;
}
if (includeInputs) {
for (String s : inputMap.keySet()) {
ret[outIndex++] = s;
}
}
return ret;
}
public String[] getSortedOutputNames() {
if (outputCache == null) {
buildOutputCache();
}
return sortedOutputNames;
}
/**
* Returns the type (Class) of the output, or null if there is no such output
* @param outputName
* @return
*/
public Class<?> getOutputType(String outputName) {
// lazily initialize the output cache
if (outputCache == null) {
buildOutputCache();
}
Method m = outputCache.get(outputName).method;
assert (m != null);
return m.getReturnType();
}
public Class<?> getOutputDeclaringClass(String outputName) {
if (outputCache == null) {
buildOutputCache();
}
Method m = outputCache.get(outputName).method;
assert (m != null);
return m.getDeclaringClass();
}
public Class<? extends Unit> getOutputUnit(String outputName) {
if (outputCache == null) {
buildOutputCache();
}
Output a = outputCache.get(outputName).annotation;
assert (a != null);
return a.unit();
}
public String getOutputDescripion(String outputName) {
if (outputCache == null) {
buildOutputCache();
}
Output a = outputCache.get(outputName).annotation;
assert (a != null);
return a.description();
}
@Output(name = "Name",
description="The unique input name for this entity.")
public String getNameOutput(double simTime) {
return entityName;
}
}
|
package com.xpn.xwiki.web;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.plugin.captcha.CaptchaPluginApi;
public class CommentAddAction extends XWikiAction {
public boolean action(XWikiContext context) throws XWikiException {
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
XWikiDocument doc = context.getDoc();
ObjectAddForm oform = (ObjectAddForm) context.getForm();
Boolean isResponseCorrect = Boolean.TRUE;
if (xwiki.hasCaptcha(context)) {
CaptchaPluginApi captchaPluginApi = (CaptchaPluginApi) xwiki.getPluginApi("jcaptcha", context);
if (captchaPluginApi != null)
isResponseCorrect = captchaPluginApi.verifyCaptcha("comment");
}
// Make sure this class exists
BaseClass baseclass = xwiki.getCommentsClass(context);
if (isResponseCorrect.booleanValue()) {
if (doc.isNew()) {
return true;
} else {
String className = baseclass.getName(); // XWiki.XWikiComments
int nb = doc.createNewObject(className, context);
BaseObject oldobject = doc.getObject(className, nb);
BaseObject newobject = (BaseObject) baseclass.fromMap(oform.getObject(className), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(doc.getFullName());
doc.setObject(className, nb, newobject);
doc.setContentDirty(false); // Consider comments not being content
xwiki.saveDocument(doc, context.getMessageTool().get("core.comment.addComment"), context);
}
// forward to edit
String redirect = Utils.getRedirect("edit", context);
sendRedirect(response, redirect);
} else {
String url = context.getDoc().getURL("view", "xpage=comments&confirm=false",context);
try {
response.sendRedirect(url);
} catch (Exception e) {
System.err.println(e.getStackTrace().toString());
}
}
return false;
}
public String render(XWikiContext context) throws XWikiException {
context.put("message", "nocommentwithnewdoc");
return "exception";
}
}
|
package common.base.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import common.base.R;
import common.base.WeakHandler;
import common.base.activitys.IProxyCallback;
import common.base.activitys.UIHintAgent;
import common.base.interfaces.ICommonUiHintActions;
import common.base.netAbout.BaseServerResult;
import common.base.netAbout.NetRequestLifeMarker;
import common.base.utils.CommonLog;
public abstract class BaseFragment extends Fragment implements
View.OnClickListener,
IProxyCallback,
DialogInterface.OnClickListener,
ICommonUiHintActions,
WeakHandler.Handleable {
protected final String TAG = getClass().getSimpleName();
protected LayoutInflater mLayoutInflater;
protected Context context;
protected Context appContext;
protected boolean LIFE_DEBUG = false;
protected String extraInfoInLifeDebug = "";
protected UIHintAgent someUiHintAgent;
protected NetRequestLifeMarker netRequestLifeMarker = new NetRequestLifeMarker();
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityCreated() savedInstanceState = " + savedInstanceState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onViewStateRestored() savedInstanceState = " + savedInstanceState);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onSaveInstanceState() outState = " + outState);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onConfigurationChanged() newConfig = " + newConfig);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onAttach() ");
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreate() savedInstanceState = " + savedInstanceState);
}
}
@Override
public void onStart() {
super.onStart();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStart() ");
}
}
/**
*
* Activity
*/
public void onReStart() {
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onReStart() ");
}
}
@Override
public void onResume() {
super.onResume();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onResume() ");
}
if (someUiHintAgent != null) {
someUiHintAgent.setOwnerVisibility(true);
}
if (needUpdateData) {
initData();
needUpdateData = false;
}
}
@Override
public void onPause() {
super.onPause();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onPause() ");
}
}
@Override
public void onStop() {
super.onStop();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStop() ");
}
if (someUiHintAgent != null) {
someUiHintAgent.setOwnerVisibility(false);
}
}
@Override
public void onDetach() {
super.onDetach();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDetach() ");
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroyView() ");
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onHiddenChanged() hidden = " + hidden);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroy() ");
}
}
private View rootView;
private boolean needReDrawUi = true;
protected boolean needUpdateData = false;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() container id = " + container.getId() +" savedInstanceState = " + savedInstanceState);
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() rootView = " + rootView);
}
mLayoutInflater = inflater;
context = getActivity();
appContext = context.getApplicationContext();
if (rootView == null) {
needReDrawUi = true;
int curFragmentViewResId = providedFragmentViewResId();
if (curFragmentViewResId > 0) {
rootView = inflater.inflate(curFragmentViewResId, null);
}
else{
rootView = providedFragmentView();
}
}
else{
needReDrawUi = false;
}
if (rootView == null) {
needReDrawUi = false;
return null;
}
ViewGroup rootViewOldParentView = (ViewGroup) rootView.getParent();
if (rootViewOldParentView != null) {
rootViewOldParentView.removeView(rootView);
}
return rootView;
}
/**
*
* @param view
* @param savedInstanceState
*/
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (needReDrawUi) {
preInitViews(view);
initViews(view);
initData();
initEvent();
}
}
/**
*
* @param contentView
*/
protected abstract void initViews(View contentView);
/**
*
* ButterKnifebind
* @param fragmentContentView
*/
protected void preInitViews(View fragmentContentView) {
}
protected abstract void initData();
protected void initEvent() {
}
protected void fixPageHeaderView(View headerView) {
}
/**
* ID
* @return
*/
protected abstract int providedFragmentViewResId();
/**
* View
* @return
*/
protected abstract View providedFragmentView();
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (LIFE_DEBUG) {
CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityResult() requestCode = " + requestCode + " resultCode = " + resultCode + " data = " + data);
}
}
protected void needSomeUiHintAgent() {
if (someUiHintAgent == null) {
someUiHintAgent = new UIHintAgent(context);
someUiHintAgent.setProxyCallback(this);
someUiHintAgent.setHintDialogOnClickListener(this);
}
}
protected void switchActivity(boolean finishSelf) {
if (finishSelf) {
getActivity().overridePendingTransition(R.anim.common_part_left_in, R.anim.common_whole_right_out);
} else {
getActivity().overridePendingTransition(R.anim.common_whole_right_in, R.anim.common_part_right_out);
}
}
/**
* (),,
*
* @param requestDataType
* @param result
* @return true:[] false:[]
*/
@Override
public boolean ownerDealWithServerResult(int requestDataType, BaseServerResult result) {
return false;
}
/**
* (),,
*
* @param requestDataType
* @param errorInfo
* @return true:[] false:[]
*/
@Override
public boolean ownerDealWithServerError(int requestDataType, String errorInfo) {
return false;
}
@Override
public void ownerToCancelLoadingRequest() {
}
@Override
public void ownerToCancelHintDialog() {
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
}
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog The dialog that received the click.
* @param which The button that was clicked (e.g.
* {@link DialogInterface#BUTTON1}) or the position
*/
@Override
public final void onClick(DialogInterface dialog, int which) {
}
protected void onClickInDialog(DialogInterface dialog, int which) {
}
/**
* xmlViwe
* @param viewId
* @param <T>
* @return T
*/
protected <T extends View> T findAviewById(int viewId) {
return findLocalViewById(viewId);//changed by fee 2017-09-13 FragmentActivity
}
/**
* Activityview id
* @param viewId
* @param <T>
* @return
*/
protected <T extends View> T findAviewByIdInHostActivity(int viewId){
if (viewId > 0) {
return (T) getActivity().findViewById(viewId);
}
return null;
}
/**
* Fragment
* @param viewId
* @param <T>
* @return
*/
protected <T extends View> T findLocalViewById(int viewId) {
if (viewId > 0 && rootView != null) {
return (T) rootView.findViewById(viewId);
}
return null;
}
/**
* View ID
* @param containerView View
* @param childViewId View ID
* @param <T>
* @return
*/
protected <T extends View> T findAviewInContainer(ViewGroup containerView, int childViewId) {
if (containerView == null || childViewId <= 0) {
return null;
}
return (T) containerView.findViewById(childViewId);
}
protected void jumpToActivity(Intent startIntent, int requestCode,boolean needReturnResult) {
if (startIntent != null) {
if (!needReturnResult) {
startActivity(startIntent);
}
else{
startActivityForResult(startIntent,requestCode);
}
}
}
protected void jumpToActivity(Class<?> targetActivityClass) {
Intent startIntent = new Intent(context, targetActivityClass);
jumpToActivity(startIntent,0,false);
}
protected void jumpToActivity(Class<?> targetActiviyClass, int requestCode, boolean needReturnResult) {
Intent startIntent = new Intent(context,targetActiviyClass);
jumpToActivity(startIntent,requestCode,needReturnResult);
}
/**
*
* @param dataType
* @return
*/
protected boolean curRequestCanceled(int dataType) {
if(netRequestLifeMarker != null){
return netRequestLifeMarker.curRequestCanceled(dataType);
}
return false;
}
/**
* :
* @see {@link NetRequestLifeMarker#REQUEST_STATE_ING}
* @param requestDataType
* @param targetState
*/
protected void addRequestStateMark(int requestDataType,byte targetState){
if(netRequestLifeMarker != null){
netRequestLifeMarker.addRequestToMark(requestDataType, targetState);
}
}
/**
*
* @param curRequestDataType
*/
protected void trackARequestState(int curRequestDataType) {
if (netRequestLifeMarker != null) {
netRequestLifeMarker.addRequestToMark(curRequestDataType, NetRequestLifeMarker.REQUEST_STATE_ING);
}
}
/**
*
* @param requestDataType
* @return
*/
protected boolean curRequestFinished(int requestDataType) {
if (netRequestLifeMarker != null) {
return netRequestLifeMarker.curRequestLifeState(requestDataType) == NetRequestLifeMarker.REQUEST_STATE_FINISHED;
}
return false;
}
/***
* Retrofit
* OkGoAPP,
* @param curRequestType
*/
protected void cancelNetRequest(int curRequestType) {
if (netRequestLifeMarker != null) {
netRequestLifeMarker.cancelCallRequest(curRequestType);
}
}
/**
*
* @param theRequestTypes
* @return true:false:
*/
protected boolean isAllRequestFinished(int... theRequestTypes) {
if (theRequestTypes == null || theRequestTypes.length == 0) {
return false;
}
for (int oneRequestType : theRequestTypes) {
if (!curRequestFinished(oneRequestType)) {
return false;
}
}
return true;
}
/**
* PopupWindow
*
* @param anchorView
* @param xOffset X
* @param yOffset Y
*/
@Override
public void initCommonHintPopuWindow(View anchorView, int xOffset, int yOffset) {
if (someUiHintAgent != null) {
someUiHintAgent.initHintPopuWindow(anchorView,xOffset,yOffset);
}
}
@Override
public void showCommonLoading(String hintMsg) {
if (someUiHintAgent != null) {
someUiHintAgent.showLoading(hintMsg);
}
}
@Override
public void showCommonLoading(int hintMsgResID) {
showCommonLoading(getString(hintMsgResID));
}
@Override
public void dialogHint(String dialogTitle, String hintMsg, String cancelBtnName, String sureBtnName, int dialogInCase) {
if (someUiHintAgent != null) {
someUiHintAgent.dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase);
}
}
@Override
public void dialogHint(int titleResID, int hintMsgResID, int cancelBtnNameResID, int sureBtnNameResID, int dialogInCase) {
String dialogTitle = getString(titleResID);
String hintMsg = getString(hintMsgResID);
String cancelBtnName = getString(cancelBtnNameResID);
String sureBtnName = getString(sureBtnNameResID);
dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase);
}
@Override
public void popupHint(String hintMsg) {
if(someUiHintAgent != null)
someUiHintAgent.popupHint(hintMsg);
}
@Override
public void popupHint(int hintMsgResID) {
popupHint(getString(hintMsgResID));
}
protected WeakHandler mHandler;
/**
* Handler
*/
protected void initHandler() {
if (mHandler == null) {
mHandler = new WeakHandler<>(this);
}
}
/**
*
*
* @param msg
* @return MessageId
*/
@Override
public int handleMessage(Message msg) {
return 0;
}
protected void i(String tag, Object... logBodys) {
if (tag == null) {
tag = TAG + "[" + extraInfoInLifeDebug + "]";
}
CommonLog.i(tag, logBodys);
}
protected void e(String tag, Object... logBodys) {
if (tag == null) {
tag = TAG + "[" + extraInfoInLifeDebug + "]";
}
CommonLog.e(tag, logBodys);
}
/**
* Fragment
* Activity
* def false
* @return true:false:
*/
public boolean onHandleBackPressed(){
return false;
}
protected void letHostActivityFinish() {
if (getActivity() != null) {
getActivity().finish();
}
}
protected void sendBroadcast(Intent actionIntent) {
if (getActivity() != null) {
getActivity().sendBroadcast(actionIntent);
}
}
protected void finishHost(boolean needTransAnim) {
if (mFragmentHost != null) {
mFragmentHost.finishHost(needTransAnim);
}
}
protected void onFragmentShow() {
if (mFragmentHost != null) {
mFragmentHost.onFragmentShow(this);
}
}
protected IFragmentHost mFragmentHost;
/**
* Fragment
*/
public interface IFragmentHost{
void onFragmentShow(BaseFragment curFragment);
void finishHost(boolean needTransAnim);
}
}
|
package de.lessvoid.nifty.elements;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import de.lessvoid.nifty.EndNotify;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyMethodInvoker;
import de.lessvoid.nifty.controls.Controller;
import de.lessvoid.nifty.controls.FocusHandler;
import de.lessvoid.nifty.controls.NiftyInputControl;
import de.lessvoid.nifty.effects.Effect;
import de.lessvoid.nifty.effects.EffectEventId;
import de.lessvoid.nifty.effects.EffectManager;
import de.lessvoid.nifty.effects.Falloff;
import de.lessvoid.nifty.elements.render.ElementRenderer;
import de.lessvoid.nifty.elements.render.TextRenderer;
import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent;
import de.lessvoid.nifty.input.mouse.MouseInputEvent;
import de.lessvoid.nifty.layout.LayoutPart;
import de.lessvoid.nifty.layout.align.HorizontalAlign;
import de.lessvoid.nifty.layout.align.VerticalAlign;
import de.lessvoid.nifty.layout.manager.LayoutManager;
import de.lessvoid.nifty.loaderv2.types.ElementType;
import de.lessvoid.nifty.render.NiftyRenderEngine;
import de.lessvoid.nifty.screen.KeyInputHandler;
import de.lessvoid.nifty.screen.MouseOverHandler;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import de.lessvoid.nifty.tools.SizeValue;
import de.lessvoid.nifty.tools.TimeProvider;
/**
* The Element.
* @author void
*/
public class Element {
/**
* Time before we start an automated click when mouse button is holded.
*/
private static final long REPEATED_CLICK_START_TIME = 100;
/**
* The time between automatic clicks.
*/
private static final long REPEATED_CLICK_TIME = 100;
/**
* the logger.
*/
private static Logger log = Logger.getLogger(Element.class.getName());
/**
* element type.
*/
private ElementType elementType;
/**
* our identification.
*/
private String id;
/**
* the parent element.
*/
private Element parent;
/**
* the child elements.
*/
private ArrayList < Element > elements = new ArrayList < Element >();
/**
* The LayoutManager we should use for all child elements.
*/
private LayoutManager layoutManager;
/**
* The LayoutPart for layout this element.
*/
private LayoutPart layoutPart;
/**
* The ElementRenderer we should use to render this element.
*/
private ElementRenderer[] elementRenderer;
/**
* the effect manager for this element.
*/
private EffectManager effectManager;
/**
* Element interaction.
*/
private ElementInteraction interaction;
/**
* Nifty instance this element is attached to.
*/
private Nifty nifty;
/**
* The focus handler this element is attached to.
*/
private FocusHandler focusHandler;
/**
* Listeners listening for changes to this element
*/
private List<ElementChangeListener> listeners;
/**
* enable element.
*/
private boolean enabled;
/**
* visible element.
*/
private boolean visible;
/**
* this is set to true, when there's no interaction with the element
* possible. this happens when the onEndScreen effect starts.
*/
private boolean done;
/**
* this is set to true when there's no interaction with this element possibe.
* (as long as onStartScreen and onEndScreen events are active even when this
* element is not using the onStartScreen effect at all but a parent element did)
*/
private boolean interactionBlocked;
/**
* mouse down flag.
*/
private boolean mouseDown;
/**
* visible to mouse events.
*/
private boolean visibleToMouseEvents;
/**
* Last position of mouse X.
*/
private int lastMouseX;
/**
* Last position of mouse Y.
*/
private int lastMouseY;
/**
* mouse first click down time.
*/
private long mouseDownTime;
/**
* Time the last repeat has been activated.
*/
private long lastRepeatStartTime;
/**
* clip children.
*/
private boolean clipChildren;
/**
* attached control when this element is an control.
*/
private NiftyInputControl attachedInputControl = null;
/**
* remember if we've calculated this constraint ourself.
*/
private boolean isCalcWidthConstraint;
/**
* remember if we've calculated this constraint ourself.
*/
private boolean isCalcHeightConstraint;
/**
* focusable.
*/
private boolean focusable = false;
/**
* screen we're connected to.
*/
private Screen screen;
/**
* TimeProvider.
*/
private TimeProvider time;
private boolean parentClipArea = false;
private int parentClipX;
private int parentClipY;
private int parentClipWidth;
private int parentClipHeight;
/**
* construct new instance of Element.
* @param newNifty Nifty
* @param newElementType elementType
* @param newId the id
* @param newParent new parent
* @param newFocusHandler the new focus handler
* @param newVisibleToMouseEvents visible to mouse
* @param newTimeProvider TimeProvider
* @param newElementRenderer the element renderer
*/
public Element(
final Nifty newNifty,
final ElementType newElementType,
final String newId,
final Element newParent,
final FocusHandler newFocusHandler,
final boolean newVisibleToMouseEvents,
final TimeProvider newTimeProvider,
final ElementRenderer ... newElementRenderer) {
initialize(
newNifty,
newElementType,
newId,
newParent,
newElementRenderer,
new LayoutPart(),
newFocusHandler,
newVisibleToMouseEvents, newTimeProvider);
}
/**
* construct new instance of Element using the given layoutPart instance.
* @param newNifty Nifty
* @param newElementType element type
* @param newId the id
* @param newParent new parent
* @param newLayoutPart the layout part
* @param newFocusHandler the new focus handler
* @param newVisibleToMouseEvents visible to mouse
* @param newTimeProvider TimeProvider
* @param newElementRenderer the element renderer
*/
public Element(
final Nifty newNifty,
final ElementType newElementType,
final String newId,
final Element newParent,
final LayoutPart newLayoutPart,
final FocusHandler newFocusHandler,
final boolean newVisibleToMouseEvents,
final TimeProvider newTimeProvider, final ElementRenderer ... newElementRenderer) {
initialize(
newNifty,
newElementType,
newId,
newParent,
newElementRenderer,
newLayoutPart,
newFocusHandler,
newVisibleToMouseEvents, newTimeProvider);
}
/**
* initialize this instance helper.
* @param newNifty Nifty
* @param newElementType element
* @param newId the id
* @param newParent parent
* @param newElementRenderer the element renderer to use
* @param newLayoutPart the layoutPart to use
* @param newFocusHandler the focus handler that this element is attached to
* @param newVisibleToMouseEvents visible to mouse
* @param timeProvider TimeProvider to use
*/
private void initialize(
final Nifty newNifty,
final ElementType newElementType,
final String newId,
final Element newParent,
final ElementRenderer[] newElementRenderer,
final LayoutPart newLayoutPart,
final FocusHandler newFocusHandler,
final boolean newVisibleToMouseEvents,
final TimeProvider timeProvider) {
this.nifty = newNifty;
this.elementType = newElementType;
this.id = newId;
this.parent = newParent;
this.elementRenderer = newElementRenderer;
this.effectManager = new EffectManager();
this.effectManager.setAlternateKey(nifty.getAlternateKey());
this.layoutPart = newLayoutPart;
this.enabled = true;
this.visible = true;
this.done = false;
this.interactionBlocked = false;
this.focusHandler = newFocusHandler;
this.visibleToMouseEvents = newVisibleToMouseEvents;
this.time = timeProvider;
this.setMouseDown(false, 0);
this.interaction = new ElementInteraction(nifty);
}
/**
* get the id of this element.
* @return the id
*/
public String getId() {
return id;
}
/**
* get parent.
* @return parent
*/
public Element getParent() {
return parent;
}
public void setParent(final Element element) {
parent = element;
}
/**
* get element state as string.
* @param offset offset string
* @return the element state as string.
*/
public String getElementStateString(final String offset) {
String pos = ""
+ " style [" + getElementType().getAttributes().get("style") + "]\n" + offset
+ " state [" + getState() + "]\n" + offset
+ " position [x=" + getX() + ", y=" + getY() + ", w=" + getWidth() + ", h=" + getHeight() + "]\n" + offset
+ " constraint [" + outputSizeValue(layoutPart.getBoxConstraints().getX()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getY()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getWidth()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getHeight()) + "]\n" + offset
+ " padding [" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingLeft()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getPaddingRight()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getPaddingTop()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getPaddingBottom()) + "]\n" + offset
+ " focusable [" + focusable + "]\n" + offset
+ " mouseable [" + visibleToMouseEvents + "]";
return pos;
}
private String getState() {
if (isEffectActive(EffectEventId.onStartScreen)) {
return "starting";
}
if (isEffectActive(EffectEventId.onEndScreen)) {
return "ending";
}
if (!visible) {
return "hidden";
}
if (interactionBlocked) {
return "interactionBlocked";
}
return "normal";
}
/**
* Output SizeValue.
* @param value SizeValue
* @return value string
*/
private String outputSizeValue(final SizeValue value) {
if (value == null) {
return "null";
} else {
return value.toString();
}
}
/**
* get x.
* @return x position of this element.
*/
public int getX() {
return layoutPart.getBox().getX();
}
/**
* get y.
* @return the y position of this element.
*/
public int getY() {
return layoutPart.getBox().getY();
}
/**
* get height.
* @return the height of this element.
*/
public int getHeight() {
return layoutPart.getBox().getHeight();
}
/**
* get width.
* @return the width of this element.
*/
public int getWidth() {
return layoutPart.getBox().getWidth();
}
/**
* Sets the height of this element
* @param height the new height in pixels
*/
public void setHeight(int height) {
layoutPart.getBox().setHeight(height);
}
/**
* Sets the width of this element
* @param width the new width in pixels
*/
public void setWidth(int width) {
layoutPart.getBox().setWidth(width);
}
/**
* get all child elements of this element.
* @return the list of child elements
*/
public List < Element > getElements() {
return elements;
}
/**
* add a child element.
* @param widget the child to add
*/
public void add(final Element widget) {
elements.add(widget);
}
/**
* render this element.
* @param r the RenderDevice to use
*/
public void render(final NiftyRenderEngine r) {
if (visible) {
if (effectManager.isEmpty()) {
r.saveState(null);
renderElement(r);
renderChildren(r);
r.restoreState();
} else {
r.saveState(null);
effectManager.begin(r, this);
effectManager.renderPre(r, this);
renderElement(r);
effectManager.renderPost(r, this);
effectManager.end(r);
renderChildren(r);
r.restoreState();
r.saveState(null);
effectManager.renderOverlay(r, this);
r.restoreState();
}
}
}
private void renderElement(final NiftyRenderEngine r) {
if (elementRenderer != null) {
for (ElementRenderer renderer : elementRenderer) {
renderer.render(this, r);
}
}
}
private void renderChildren(final NiftyRenderEngine r) {
if (clipChildren) {
r.enableClip(getX(), getY(), getX() + getWidth(), getY() + getHeight());
renderInternalChildElements(r);
r.disableClip();
} else {
renderInternalChildElements(r);
}
}
private void renderInternalChildElements(final NiftyRenderEngine r) {
for (Element p : elements) {
p.render(r);
}
}
/**
* Set a new LayoutManager.
* @param newLayout the new LayoutManager to use.
*/
public void setLayoutManager(final LayoutManager newLayout) {
this.layoutManager = newLayout;
}
private void preProcessConstraintWidth() {
for (Element e : elements) {
e.preProcessConstraintWidth();
}
preProcessConstraintWidthThisLevel();
}
private void preProcessConstraintWidthThisLevel() {
// try the original width value first
SizeValue myWidth = getConstraintWidth();
// is it empty and we have an layoutManager there's still hope for a width constraint
if (layoutManager != null && (myWidth == null || isCalcWidthConstraint)) {
// collect all child layoutPart that have a fixed pixel size in a list
List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >();
for (Element e : elements) {
SizeValue childWidth = e.getConstraintWidth();
if (childWidth != null && childWidth.isPixel()) {
layoutPartChild.add(e.layoutPart);
}
}
// if all (!) child elements have a pixel fixed width we can calculate a new width constraint for this element!
if (elements.size() == layoutPartChild.size()) {
SizeValue newWidth = layoutManager.calculateConstraintWidth(this.layoutPart, layoutPartChild);
if (newWidth != null) {
setConstraintWidth(newWidth);
isCalcWidthConstraint = true;
}
}
}
}
private void preProcessConstraintHeight() {
for (Element e : elements) {
e.preProcessConstraintHeight();
}
preProcessConstraintHeightThisLevel();
}
private void preProcessConstraintHeightThisLevel() {
// try the original height value first
SizeValue myHeight = getConstraintHeight();
// is it empty and we have an layoutManager there's still hope for a height constraint
if (layoutManager != null && (myHeight == null || isCalcHeightConstraint)) {
// collect all child layoutPart that have a fixed px size in a list
List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >();
for (Element e : elements) {
SizeValue childHeight = e.getConstraintHeight();
if (childHeight != null && childHeight.isPixel()) {
layoutPartChild.add(e.layoutPart);
}
}
// if all (!) child elements have a px fixed height we can calculate a new height constraint for this element!
if (elements.size() == layoutPartChild.size()) {
SizeValue newHeight = layoutManager.calculateConstraintHeight(this.layoutPart, layoutPartChild);
if (newHeight != null) {
setConstraintHeight(newHeight);
isCalcHeightConstraint = true;
}
}
}
}
private void processLayoutInternal() {
for (Element w : elements) {
TextRenderer textRenderer = w.getRenderer(TextRenderer.class);
if (textRenderer != null) {
textRenderer.setWidthConstraint(w, w.getConstraintWidth(), getWidth(), nifty.getRenderEngine());
}
}
}
private void processLayout() {
processLayoutInternal();
if (layoutManager != null) {
// we need a list of LayoutPart and not of Element, so we'll build one on the fly here
List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >();
for (Element w : elements) {
layoutPartChild.add(w.layoutPart);
}
// use out layoutManager to layout our children
layoutManager.layoutElements(layoutPart, layoutPartChild);
// repeat this step for all child elements
for (Element w : elements) {
w.processLayout();
}
}
if (clipChildren) {
for (Element w : elements) {
w.setParentClipArea(getX(), getY(), getWidth(), getHeight());
}
}
}
public void layoutElements() {
prepareLayout();
processLayout();
prepareLayout();
processLayout();
}
private void prepareLayout() {
preProcessConstraintWidth();
preProcessConstraintHeight();
}
private void setParentClipArea(final int x, final int y, final int width, final int height) {
parentClipArea = true;
parentClipX = x;
parentClipY = y;
parentClipWidth = width;
parentClipHeight = height;
for (Element w : elements) {
w.setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight);
}
notifyListeners();
}
/**
* reset all effects.
*/
public void resetEffects() {
// mouseDown = false;
effectManager.reset();
for (Element w : elements) {
w.resetEffects();
}
}
public void resetAllEffects() {
// mouseDown = false;
effectManager.resetAll();
for (Element w : elements) {
w.resetAllEffects();
}
}
public void resetSingleEffect(final EffectEventId effectEventId) {
// mouseDown = false;
effectManager.resetSingleEffect(effectEventId);
for (Element w : elements) {
w.resetSingleEffect(effectEventId);
}
}
public void resetSingleEffect(final EffectEventId effectEventId, final String customKey) {
// mouseDown = false;
effectManager.resetSingleEffect(effectEventId, customKey);
for (Element w : elements) {
w.resetSingleEffect(effectEventId, customKey);
}
}
public void resetMouseDown() {
// mouseDown = false;
for (Element w : elements) {
w.resetMouseDown();
}
}
/**
* set new x position constraint.
* @param newX new x constraint.
*/
public void setConstraintX(final SizeValue newX) {
layoutPart.getBoxConstraints().setX(newX);
notifyListeners();
}
/**
* set new y position constraint.
* @param newY new y constaint.
*/
public void setConstraintY(final SizeValue newY) {
layoutPart.getBoxConstraints().setY(newY);
notifyListeners();
}
/**
* set new width constraint.
* @param newWidth new width constraint.
*/
public void setConstraintWidth(final SizeValue newWidth) {
layoutPart.getBoxConstraints().setWidth(newWidth);
notifyListeners();
}
/**
* set new height constraint.
* @param newHeight new height constraint.
*/
public void setConstraintHeight(final SizeValue newHeight) {
layoutPart.getBoxConstraints().setHeight(newHeight);
notifyListeners();
}
public SizeValue getConstraintX() {
return layoutPart.getBoxConstraints().getX();
}
public SizeValue getConstraintY() {
return layoutPart.getBoxConstraints().getY();
}
/**
* get current width constraint.
* @return current width constraint
*/
public SizeValue getConstraintWidth() {
return layoutPart.getBoxConstraints().getWidth();
}
/**
* get current height constraint.
* @return current height constraint.
*/
public SizeValue getConstraintHeight() {
return layoutPart.getBoxConstraints().getHeight();
}
/**
* set new horizontal align.
* @param newHorizontalAlign new horizontal align.
*/
public void setConstraintHorizontalAlign(final HorizontalAlign newHorizontalAlign) {
layoutPart.getBoxConstraints().setHorizontalAlign(newHorizontalAlign);
}
/**
* set new vertical align.
* @param newVerticalAlign new vertical align.
*/
public void setConstraintVerticalAlign(final VerticalAlign newVerticalAlign) {
layoutPart.getBoxConstraints().setVerticalAlign(newVerticalAlign);
}
/**
* get current horizontal align.
* @return current horizontal align.
*/
public HorizontalAlign getConstraintHorizontalAlign() {
return layoutPart.getBoxConstraints().getHorizontalAlign();
}
/**
* get current vertical align.
* @return current vertical align.
*/
public VerticalAlign getConstraintVerticalAlign() {
return layoutPart.getBoxConstraints().getVerticalAlign();
}
/**
* register an effect for this element.
* @param theId the effect id
* @param e the effect
*/
public void registerEffect(
final EffectEventId theId,
final Effect e) {
log.fine("[" + this.getId() + "] register: " + theId.toString() + "(" + e.getStateString() + ")");
effectManager.registerEffect(theId, e);
}
public void startEffect(final EffectEventId effectEventId) {
startEffect(effectEventId, null);
}
public void startEffect(final EffectEventId effectEventId, final EndNotify effectEndNotiy) {
if (effectEventId == EffectEventId.onStartScreen) {
if (!visible) {
return;
}
done = false;
interactionBlocked = true;
}
if (effectEventId == EffectEventId.onEndScreen) {
if (!visible) {
return;
}
done = true;
interactionBlocked = true;
}
// whenever the effect ends we forward to this event
// that checks first, if all child elements are finished
// and when yes forwards to the actual effectEndNotify event.
// this way we ensure that all child finished the effects
// before forwarding this to the real event handler.
// little bit tricky though :/
LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotiy);
// start the effect for ourself
effectManager.startEffect(effectEventId, this, time, forwardToSelf);
// notify all child elements of the start effect
for (Element w : getElements()) {
w.startEffectInternal(effectEventId, forwardToSelf);
}
if (effectEventId == EffectEventId.onFocus) {
if (attachedInputControl != null) {
attachedInputControl.onFocus(true);
}
}
// just in case there was no effect activated, we'll check here, if we're already done
forwardToSelf.perform();
}
public void startEffect(final EffectEventId effectEventId, final EndNotify effectEndNotiy, final String customKey) {
if (effectEventId == EffectEventId.onStartScreen) {
if (!visible) {
return;
}
done = false;
interactionBlocked = true;
}
if (effectEventId == EffectEventId.onEndScreen) {
if (!visible) {
return;
}
done = true;
interactionBlocked = true;
}
// whenever the effect ends we forward to this event
// that checks first, if all child elements are finished
// and when yes forwards to the actual effectEndNotify event.
// this way we ensure that all child finished the effects
// before forwarding this to the real event handler.
// little bit tricky though :/
LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotiy);
// start the effect for ourself
effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey);
// notify all child elements of the start effect
for (Element w : getElements()) {
w.startEffectInternal(effectEventId, forwardToSelf, customKey);
}
if (effectEventId == EffectEventId.onFocus) {
if (attachedInputControl != null) {
attachedInputControl.onFocus(true);
}
}
// just in case there was no effect activated, we'll check here, if we're already done
forwardToSelf.perform();
}
public void startEffectInternal(final EffectEventId effectEventId, final EndNotify effectEndNotiy) {
if (effectEventId == EffectEventId.onStartScreen) {
if (!visible) {
return;
}
done = false;
interactionBlocked = true;
}
if (effectEventId == EffectEventId.onEndScreen) {
if (!visible) {
return;
}
done = true;
interactionBlocked = true;
}
// whenever the effect ends we forward to this event
// that checks first, if all child elements are finished
// and when yes forwards to the actual effectEndNotify event.
// this way we ensure that all child finished the effects
// before forwarding this to the real event handler.
// little bit tricky though :/
LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotiy);
// start the effect for ourself
effectManager.startEffect(effectEventId, this, time, forwardToSelf);
// notify all child elements of the start effect
for (Element w : getElements()) {
w.startEffectInternal(effectEventId, forwardToSelf);
}
if (effectEventId == EffectEventId.onFocus) {
if (attachedInputControl != null) {
attachedInputControl.onFocus(true);
}
}
}
public void startEffectInternal(final EffectEventId effectEventId, final EndNotify effectEndNotiy, final String customKey) {
if (effectEventId == EffectEventId.onStartScreen) {
if (!visible) {
return;
}
done = false;
interactionBlocked = true;
}
if (effectEventId == EffectEventId.onEndScreen) {
if (!visible) {
return;
}
done = true;
interactionBlocked = true;
}
// whenever the effect ends we forward to this event
// that checks first, if all child elements are finished
// and when yes forwards to the actual effectEndNotify event.
// this way we ensure that all child finished the effects
// before forwarding this to the real event handler.
// little bit tricky though :/
LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotiy);
// start the effect for ourself
effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey);
// notify all child elements of the start effect
for (Element w : getElements()) {
w.startEffectInternal(effectEventId, forwardToSelf, customKey);
}
if (effectEventId == EffectEventId.onFocus) {
if (attachedInputControl != null) {
attachedInputControl.onFocus(true);
}
}
}
/**
* stop the given effect.
* @param effectEventId effect event id to stop
*/
public void stopEffect(final EffectEventId effectEventId) {
if (EffectEventId.onStartScreen == effectEventId ||
EffectEventId.onEndScreen == effectEventId) {
interactionBlocked = false;
if (!visible) {
return;
}
}
effectManager.stopEffect(effectEventId);
// notify all child elements of the start effect
for (Element w : getElements()) {
w.stopEffect(effectEventId);
}
if (effectEventId == EffectEventId.onFocus) {
if (attachedInputControl != null) {
attachedInputControl.onFocus(false);
}
}
}
/**
* check if a certain effect is still active. travels down to child elements.
* @param effectEventId the effect type id to check
* @return true, if the effect has ended and false otherwise
*/
public boolean isEffectActive(final EffectEventId effectEventId) {
for (Element w : getElements()) {
if (w.isEffectActive(effectEventId)) {
return true;
}
}
return effectManager.isActive(effectEventId);
}
/**
* enable this element.
*/
public void enable() {
enabled = true;
}
/**
* disable this element.
*/
public void disable() {
enabled = false;
}
/**
* is this element enabled?
* @return true, if enabled and false otherwise.
*/
public boolean isEnabled() {
return enabled;
}
/**
* show this element.
*/
public void show() {
// don't show if show is still in progress
if (isEffectActive(EffectEventId.onShow)) {
return;
}
// stop any onHide effects when a new onShow effect is about to be started
if (isEffectActive(EffectEventId.onHide)) {
resetSingleEffect(EffectEventId.onHide);
}
// show
internalShow();
startEffect(EffectEventId.onShow);
}
private void internalShow() {
visible = true;
for (Element element : elements) {
element.internalShow();
}
}
public void setVisible(final boolean visibleParam) {
if (visibleParam) {
show();
} else {
hide();
}
}
/**
* hide this element.
*/
public void hide() {
// don't hide if not visible
if (!isVisible()) {
return;
}
// don't hide if hide is still in progress
if (isEffectActive(EffectEventId.onHide)) {
return;
}
// stop any onShow effects when a new onHide effect is about to be started
if (isEffectActive(EffectEventId.onShow)) {
resetSingleEffect(EffectEventId.onShow);
}
// start effect and shizzle
startEffect(EffectEventId.onHide, new EndNotify() {
public void perform() {
focusHandler.lostKeyboardFocus(Element.this);
focusHandler.lostMouseFocus(Element.this);
resetEffects();
internalHide();
}
});
}
public void showWithoutEffects() {
internalShow();
}
public void hideWithoutEffect() {
// don't hide if not visible
if (!isVisible()) {
return;
}
focusHandler.lostKeyboardFocus(Element.this);
focusHandler.lostMouseFocus(Element.this);
resetEffects();
internalHide();
}
private void internalHide() {
visible = false;
for (Element element : elements) {
element.internalHide();
}
}
/**
* check if this element is visible.
* @return true, if this element is visible and false otherwise.
*/
public boolean isVisible() {
return visible;
}
/**
* set a new Falloff.
* @param newFalloff new Falloff
*/
public void setHotSpotFalloff(final Falloff newFalloff) {
effectManager.setFalloff(newFalloff);
}
public Falloff getFalloff() {
return effectManager.getFalloff();
}
/**
* Checks if this element can handle mouse events.
* @return true can handle mouse events, false can't handle them
*/
boolean canHandleMouseEvents() {
if (isEffectActive(EffectEventId.onStartScreen)) {
return false;
}
if (isEffectActive(EffectEventId.onEndScreen)) {
return false;
}
if (!visible) {
return false;
}
if (done) {
return false;
}
if (!visibleToMouseEvents) {
return false;
}
if (!focusHandler.canProcessMouseEvents(this)) {
return false;
}
if (interactionBlocked) {
return false;
}
return true;
}
/**
* This should check of the mouse event is inside the current element and if it is
* forward the event to it's child. The purpose of this is to build a list of all
* elements from front to back that are available for a certain mouse position.
* @param mouseEvent MouseInputEvent
* @param eventTime time this event occured in ms
* @param mouseOverHandler MouseOverHandler to fill
*/
public void buildMouseOverElements(
final MouseInputEvent mouseEvent,
final long eventTime,
final MouseOverHandler mouseOverHandler) {
if (canHandleMouseEvents()) {
if (isInside(mouseEvent)) {
mouseOverHandler.addMouseOverElement(this);
} else {
mouseOverHandler.addMouseElement(this);
}
}
for (Element w : getElements()) {
w.buildMouseOverElements(mouseEvent, eventTime, mouseOverHandler);
}
}
/**
* MouseEvent.
* @param mouseEvent mouse event
* @param eventTime event time
*/
public boolean mouseEvent(final MouseInputEvent mouseEvent, final long eventTime) {
effectManager.handleHover(this, mouseEvent.getMouseX(), mouseEvent.getMouseY());
boolean mouseInside = isInside(mouseEvent);
if (interaction.isOnClickRepeat()) {
if (mouseInside && isMouseDown() && mouseEvent.isLeftButton()) {
long deltaTime = eventTime - mouseDownTime;
if (deltaTime > REPEATED_CLICK_START_TIME) {
long pastTime = deltaTime - REPEATED_CLICK_START_TIME;
long repeatTime = pastTime - lastRepeatStartTime;
if (repeatTime > REPEATED_CLICK_TIME) {
lastRepeatStartTime = pastTime;
if (onClick(mouseEvent)) {
return true;
}
}
}
}
}
if (mouseInside && !isMouseDown()) {
if (mouseEvent.isInitialLeftButtonDown()) {
setMouseDown(true, eventTime);
if (focusable) {
focusHandler.requestExclusiveMouseFocus(this);
focusHandler.setKeyFocus(this);
}
return onClick(mouseEvent);
}
} else if (!mouseEvent.isLeftButton() && isMouseDown()) {
setMouseDown(false, eventTime);
effectManager.stopEffect(EffectEventId.onClick);
focusHandler.lostMouseFocus(this);
if (mouseInside) {
onRelease();
}
}
if (isMouseDown()) {
onClickMouseMove(mouseEvent);
}
return false;
}
/**
* Handle the MouseOverEvent. Must not call child elements. This is handled by caller.
* @param mouseEvent mouse event
* @param eventTime event time
* @return true the mouse event has been eated and false when the mouse event can be processed further down
*/
public boolean mouseOverEvent(final MouseInputEvent mouseEvent, final long eventTime) {
boolean eatMouseEvent = false;
if (interaction.onMouseOver(this, mouseEvent)) {
eatMouseEvent = true;
}
return eatMouseEvent;
}
/**
* checks to see if the given mouse position is inside of this element.
* @param inputEvent MouseInputEvent
* @return true when inside, false otherwise
*/
private boolean isInside(final MouseInputEvent inputEvent) {
return isMouseInsideElement(inputEvent.getMouseX(), inputEvent.getMouseY());
}
public boolean isMouseInsideElement(final int mouseX, final int mouseY) {
if (parentClipArea) {
// must be inside the parent to continue
if (mouseX >= parentClipX
&&
mouseX <= (parentClipX + parentClipWidth)
&&
mouseY > (parentClipY)
&&
mouseY < (parentClipY + parentClipHeight)) {
return
mouseX >= getX()
&&
mouseX <= (getX() + getWidth())
&&
mouseY > (getY())
&&
mouseY < (getY() + getHeight());
} else {
return false;
}
} else {
return
mouseX >= getX()
&&
mouseX <= (getX() + getWidth())
&&
mouseY > (getY())
&&
mouseY < (getY() + getHeight());
}
}
/**
* on click method.
* @param inputEvent event
*/
public boolean onClick(final MouseInputEvent inputEvent) {
if (canHandleInteraction()) {
effectManager.startEffect(EffectEventId.onClick, this, time, null);
lastMouseX = inputEvent.getMouseX();
lastMouseY = inputEvent.getMouseY();
return interaction.onClick(inputEvent);
} else {
return false;
}
}
public void onClick() {
if (canHandleInteraction()) {
effectManager.startEffect(EffectEventId.onClick, this, time, null);
interaction.onClick();
}
}
private boolean canHandleInteraction() {
return !screen.isEffectActive(EffectEventId.onStartScreen) && !screen.isEffectActive(EffectEventId.onEndScreen);
}
public void onRelease() {
interaction.onRelease();
}
/**
* on click mouse move method.
* @param inputEvent MouseInputEvent
*/
private void onClickMouseMove(final MouseInputEvent inputEvent) {
if (lastMouseX == inputEvent.getMouseX() && lastMouseY == inputEvent.getMouseY()) {
return;
}
lastMouseX = inputEvent.getMouseX();
lastMouseY = inputEvent.getMouseY();
interaction.onClickMouseMoved(inputEvent);
}
/**
* set on click method for the given screen.
* @param methodInvoker the method to invoke
* @param useRepeat repeat on click (true) or single event (false)
*/
public void setOnClickMethod(final NiftyMethodInvoker methodInvoker, final boolean useRepeat) {
interaction.setOnClickMethod(methodInvoker, useRepeat);
}
public void setOnReleaseMethod(final NiftyMethodInvoker onReleaseMethod) {
interaction.setOnReleaseMethod(onReleaseMethod);
}
/**
* Set on click mouse move method.
* @param methodInvoker the method to invoke
*/
public void setOnClickMouseMoveMethod(final NiftyMethodInvoker methodInvoker) {
interaction.setOnClickMouseMoved(methodInvoker);
}
/**
* set mouse down.
* @param newMouseDown new state of mouse button.
* @param eventTime the time in ms the event occured
*/
private void setMouseDown(final boolean newMouseDown, final long eventTime) {
this.mouseDownTime = eventTime;
this.lastRepeatStartTime = 0;
this.mouseDown = newMouseDown;
}
/**
* is mouse down.
* @return mouse down state.
*/
private boolean isMouseDown() {
return mouseDown;
}
/**
* find an element by name.
*
* @param name the name of the element (id)
* @return the element or null
*/
public Element findElementByName(final String name) {
if (id != null && id.equals(name)) {
return this;
}
for (Element e : elements) {
Element found = e.findElementByName(name);
if (found != null) {
return found;
}
}
return null;
}
/**
* set a new alternate key.
* @param newAlternateKey new alternate key to use
*/
public void setOnClickAlternateKey(final String newAlternateKey) {
interaction.setAlternateKey(newAlternateKey);
}
/**
* set alternate key.
* @param alternateKey new alternate key
*/
public void setAlternateKey(final String alternateKey) {
effectManager.setAlternateKey(alternateKey);
for (Element e : elements) {
e.setAlternateKey(alternateKey);
}
}
/**
* get the effect manager.
* @return the EffectManager
*/
public EffectManager getEffectManager() {
return effectManager;
}
/**
* Set a New EffectManager.
* @param effectManagerParam new Effectmanager
*/
public void setEffectManager(final EffectManager effectManagerParam) {
effectManager = effectManagerParam;
}
public void bindToScreen(final Screen newScreen) {
screen = newScreen;
for (Element e : elements) {
e.bindToScreen(newScreen);
}
}
/**
* On start screen event.
* @param newScreen screen
*/
public void onStartScreen(final Screen newScreen) {
screen = newScreen;
for (Element e : elements) {
e.onStartScreen(newScreen);
}
if (focusable) {
focusHandler.addElement(this);
}
if (attachedInputControl != null) {
attachedInputControl.onStartScreen(screen);
}
}
/**
*
* @param <T> the ElementRenderer type
* @param requestedRendererClass the special ElementRenderer type to check for
* @return the ElementRenderer that matches the class
*/
public < T extends ElementRenderer > T getRenderer(final Class < T > requestedRendererClass) {
for (ElementRenderer renderer : elementRenderer) {
if (requestedRendererClass.isInstance(renderer)) {
return requestedRendererClass.cast(renderer);
}
}
return null;
}
/**
* Set visible to mouse flag.
* @param newVisibleToMouseEvents true or false
*/
public void setVisibleToMouseEvents(final boolean newVisibleToMouseEvents) {
this.visibleToMouseEvents = newVisibleToMouseEvents;
}
/**
* keyboard event.
* @param inputEvent keyboard event
*/
public boolean keyEvent(final KeyboardInputEvent inputEvent) {
if (attachedInputControl != null) {
return attachedInputControl.keyEvent(inputEvent);
}
return false;
}
/**
* Set clip children.
* @param clipChildrenParam clip children flag
*/
public void setClipChildren(final boolean clipChildrenParam) {
this.clipChildren = clipChildrenParam;
}
/**
* Is clip children enabled?
* @return clip children
*/
public boolean isClipChildren() {
return this.clipChildren;
}
/**
* Set the focus to this element.
*/
public void setFocus() {
if (nifty != null && nifty.getCurrentScreen() != null) {
if (focusable) {
focusHandler.setKeyFocus(this);
}
}
}
/**
* attach an input control to this element.
* @param newInputControl input control
*/
public void attachInputControl(final NiftyInputControl newInputControl) {
attachedInputControl = newInputControl;
}
/**
* attach popup.
* @param screenController screencontroller
*/
public void attachPopup(final ScreenController screenController) {
log.fine("attachPopup(" + screenController + ") to element [" + id + "]");
attach(interaction.getOnClickMethod(), screenController);
attach(interaction.getOnClickMouseMoveMethod(), screenController);
attach(interaction.getOnReleaseMethod(), screenController);
}
/**
* attach method.
* @param method method
* @param screenController method controller
*/
private void attach(final NiftyMethodInvoker method, final ScreenController screenController) {
method.setFirst(screenController);
for (Element e : elements) {
e.attachPopup(screenController);
}
}
private boolean hasParentActiveOnStartOrOnEndScreenEffect() {
if (parent != null) {
return
parent.effectManager.isActive(EffectEventId.onStartScreen) ||
parent.effectManager.isActive(EffectEventId.onEndScreen) ||
parent.hasParentActiveOnStartOrOnEndScreenEffect();
}
return false;
}
private void resetInteractionBlocked() {
interactionBlocked = false;
for (Element e : elements) {
e.resetInteractionBlocked();
}
}
/**
* LocalEndNotify helper class.
* @author void
*/
public class LocalEndNotify implements EndNotify {
/**
* event id.
*/
private EffectEventId effectEventId;
/**
* end notify.
*/
private EndNotify effectEndNotiy;
/**
* create it.
* @param effectEventIdParam event id
* @param effectEndNotiyParam end notify
*/
public LocalEndNotify(final EffectEventId effectEventIdParam, final EndNotify effectEndNotiyParam) {
effectEventId = effectEventIdParam;
effectEndNotiy = effectEndNotiyParam;
}
/**
* perform.
*/
public void perform() {
if (effectEventId.equals(EffectEventId.onStartScreen) || effectEventId.equals(EffectEventId.onEndScreen)) {
if (interactionBlocked &&
!hasParentActiveOnStartOrOnEndScreenEffect() &&
!isEffectActive(effectEventId)) {
resetInteractionBlocked();
}
}
// notify parent if:
// a) the effect is done for ourself
// b) the effect is done for all of our children
if (!isEffectActive(effectEventId)) {
// all fine. we can notify the actual event handler
if (effectEndNotiy != null) {
effectEndNotiy.perform();
}
}
}
}
/**
* set id.
* @param newId new id
*/
public void setId(final String newId) {
this.id = newId;
}
/**
* get element type.
* @return element type
*/
public ElementType getElementType() {
return elementType;
}
/**
* get element renderer.
* @return element renderer array
*/
public ElementRenderer[] getElementRenderer() {
return elementRenderer;
}
/**
* set focusable flag.
* @param newFocusable focusable flag
*/
public void setFocusable(final boolean newFocusable) {
this.focusable = newFocusable;
for (Element e : elements) {
e.setFocusable(newFocusable);
}
}
/**
* @return the attachedInputControl
*/
public NiftyInputControl getAttachedInputControl() {
return attachedInputControl;
}
/**
* remove this and all children from the focushandler.
*/
public void removeFromFocusHandler() {
if (screen != null) {
if (screen.getFocusHandler() != null) {
screen.getFocusHandler().remove(this);
for (Element element : elements) {
element.removeFromFocusHandler();
}
}
}
}
/**
* set a new style.
* @param newStyle new style to set
*/
public void setStyle(final String newStyle) {
removeStyle(elementType.getAttributes().get("style"));
elementType.getAttributes().set("style", newStyle);
elementType.applyStyles(nifty.getDefaultStyleResolver());
elementType.applyAttributes(this, elementType.getAttributes(), nifty.getRenderEngine());
elementType.applyEffects(nifty, screen, this);
elementType.applyInteract(nifty, screen, this);
log.info("after setStyle [" + newStyle + "]\n" + elementType.output(0));
notifyListeners();
}
void removeStyle(final String style) {
log.info("before removeStyle [" + style + "]\n" + elementType.output(0));
elementType.removeWithTag(style);
effectManager.removeAllEffects();
log.info("after removeStyle [" + style + "]\n" + elementType.output(0));
notifyListeners();
}
/**
* add additional input handler to this element or childs of the elements.
* @param handler additiona handler
*/
public void addInputHandler(final KeyInputHandler handler) {
if (attachedInputControl != null) {
attachedInputControl.addInputHandler(handler);
}
for (Element element : elements) {
element.addInputHandler(handler);
}
}
public < T extends Controller > T findControl(final String elementName, final Class < T > requestedControlClass) {
Element element = findElementByName(elementName);
if (element == null) {
return null;
}
return element.getControl(requestedControlClass);
}
/**
* Get Control from element.
* @param <T> Type
* @param requestedControlClass requested class
* @return controller or null
*/
public < T extends Controller > T getControl(final Class < T > requestedControlClass) {
if (attachedInputControl != null) {
T t = attachedInputControl.getControl(requestedControlClass);
if (t != null) {
return t;
}
} else {
for (Element element : elements) {
T t = element.getControl(requestedControlClass);
if (t != null) {
return t;
}
}
}
return null;
}
/**
* is focusable?
* @return focusable
*/
public boolean isFocusable() {
return focusable;
}
/**
* Set onMouseOverMethod.
* @param onMouseOverMethod new on mouse over method
*/
public void setOnMouseOverMethod(final NiftyMethodInvoker onMouseOverMethod) {
this.interaction.setOnMouseOver(onMouseOverMethod);
}
/**
* Get LayoutPart.
* @return LayoutPart
*/
public LayoutPart getLayoutPart() {
return layoutPart;
}
/**
* Get Element Interaction.
* @return current ElementInteraction
*/
public ElementInteraction getInteraction() {
return interaction;
}
/**
* Set Element Interaction.
* @param elementInteractionParam ElementInteraction
*/
public void setInteraction(final ElementInteraction elementInteractionParam) {
interaction = elementInteractionParam;
}
/**
* Is this element visible to mouse events.
* @return true visible and false not visible
*/
public boolean isVisibleToMouseEvents() {
return visibleToMouseEvents;
}
public void setPaddingLeft(final SizeValue paddingValue) {
layoutPart.getBoxConstraints().setPaddingLeft(paddingValue);
notifyListeners();
}
public void setPaddingRight(final SizeValue paddingValue) {
layoutPart.getBoxConstraints().setPaddingRight(paddingValue);
notifyListeners();
}
public void setPaddingTop(final SizeValue paddingValue) {
layoutPart.getBoxConstraints().setPaddingTop(paddingValue);
notifyListeners();
}
public void setPaddingBottom(final SizeValue paddingValue) {
layoutPart.getBoxConstraints().setPaddingBottom(paddingValue);
notifyListeners();
}
public String toString() {
return id + " (" + super.toString() + ")";
}
public boolean isStarted() {
return isEffectActive(EffectEventId.onStartScreen);
}
public void markForRemoval() {
markForRemoval(null);
}
public void markForRemoval(final EndNotify endNotify) {
nifty.removeElement(screen, this, endNotify);
}
public void markForMove(final Element destination) {
markForMove(destination, null);
}
public void markForMove(final Element destination, final EndNotify endNotify) {
nifty.moveElement(screen, this, destination, endNotify);
}
public void reactivate() {
done = false;
for (Element element : elements) {
element.reactivate();
}
}
public void addElementChangeListener(ElementChangeListener listener) {
if(listeners == null) listeners = new ArrayList<ElementChangeListener>();
listeners.add(listener);
}
public void removeElementChangeListener(ElementChangeListener listener) {
if(listeners == null) return;
listeners.remove(listener);
}
private void notifyListeners() {
if(listeners == null) return;
for(ElementChangeListener listener : listeners) {
listener.elementChanged(this);
}
}
}
|
package frc.team4215.stronghold;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.Timer;
/**
* The class for Autonomous.
*
* @author James
*/
public class Autonomous {
private Victor frontLeft, frontRight, backLeft, backRight,
armMotor, intake;
private Interface choiceAuto;
public Autonomous(Victor frontLeft_, Victor frontRight_,
Victor backLeft_, Victor backRight_, Victor armMotor_,
Victor intake_) throws RobotException {
this(new Victor[] { frontLeft_, frontRight_, backLeft_,
backRight_, armMotor_, intake_ });
}
public Autonomous(Victor[] sixVictors) throws RobotException {
if (sixVictors.length < 6) throw new RobotException(
"Victor array's length is less than 6");
// Point to the other constructor.
Victor[] a = sixVictors; // a nickname
this.frontLeft = a[0];
this.frontRight = a[1];
this.backLeft = a[2];
this.backRight = a[3];
this.armMotor = a[4];
this.intake = a[5];
}
public void chooseAuto(int num) {
if (num == 1) this.choiceAuto = () -> this.autoLowBar();
else if (num == 2)
this.choiceAuto = () -> this.autoSpyBotLowGoal();
else if (num == 3)
this.choiceAuto = () -> this.autoChevalDeFrise();
else if (num == 4)
this.choiceAuto = () -> this.autoPortcullis();
else this.choiceAuto = null;
}
public void autoChoice() throws RobotException {
if (null != this.choiceAuto)
throw new RobotException("There is not a method chosen.");
this.choiceAuto.runAuto();
}
/* working variables */
private long lastTime;
private double Input, Output, Setpoint;
private double errSum, lastErr;
private double kp, ki, kd;
/**
* PID controller
*
* @author Jack Rausch
*/
public double errorCompute() {
/* How long since we last calculated */
long now = Autonomous.getTime();
double timeChange = now - this.lastTime;
/* Compute all the working error variables */
double error = this.Setpoint - this.Input;
this.errSum += (error * timeChange);
double dErr = (error - this.lastErr) / timeChange;
/* Compute PID Output */
this.Output = this.kp * error + this.ki * this.errSum
+ this.kd * dErr;
/* Remember some variables for next time */
this.lastErr = error;
this.lastTime = now;
return this.Output;
}
void SetTunings(double Kp, double Ki, double Kd) {
this.kp = Kp;
this.ki = Ki;
this.kd = Kd;
}
/**
* Method called to set the Setpoint so the PID controller has the
* capability to calculate errors and correct them.
*
* @param defSetpoint
* double value
* @author Jack Rausch
*/
public static void setSetpoint(double defSetpoint) {
double Setpoint = defSetpoint;
}
/**
* Timer method integrating the Timer class from wpilibj. USE THIS
* TIMER UNIVERSALLY!!!!!
*
* @author Jack Rausch
*/
public static void startTimer() {
javax.management.timer.Timer timer = new Timer();
timer.start();
}
/**
* Called to retrieve the Time from previously defined method
* "startTimer"
*
* @author Jack Rausch
*/
public static double getTime() {
double currentTime = timer.get();
return currentTime;
}
/**
* All constants.
*
* @author James
*/
private static final class Constant {
/**
* Const shared.
*
* @author James
*/
public static final class Shared {
static final double armMoveMaxTime = 2d;
static final double armDown = -1, armUp = 1, armStop = 0;
public static final double intakeDelay = 1d;
}
/**
* Const for autoLowBar.
*
* @author James
*/
private static final class ConstLowBar {
public static final double driveThroughDelay = 5d;
}
/**
* Const for autoSpyBotLowGoal.
*
* @author James
*/
private static final class ConstSpyBotLowGoal {
public static final double driveToDelay = 5d;
}
/**
* Const for autoChevalDeFrise.
*
* @author James
*/
private static final class ConstChevalDeFrise {
public static final double driveToDelay = 5d;
public static final double driveThroughDelay = 5d;
}
/**
* Const for autoPortcullis.
*
* @author James
*/
public static final class ConstPortcullis {
public static final double driveDelay = 5d;
public static final double driveThroughDelay = 5d;
}
}
/**
* The interface for programs outside to run the chosen autonomous
* function.
*
* @author James
*/
public interface Interface {
public void runAuto();
}
/**
* to lower arm. Need more info.
*
* @author James
*/
private void armLowerBottom() {
this.armMotor.set(Constant.Shared.armDown);
Autonomous.delay(Constant.Shared.armMoveMaxTime);
this.armMotor.set(Constant.Shared.armStop);
}
/**
* to delay for some time. Need more info.
*
* @author James
* @param delayTime
* delay time in seconds
*/
private static void delay(double delayTime) {
// Just realized there is a delay thing in Timer. But I'd just
// stick to using Autonomous.delay.
edu.wpi.first.wpilibj.Timer.delay(delayTime);
}
/**
* to lift arm. Need more info
*
* @author James
*/
private void armLifterTop() {
this.armMotor.set(Constant.Shared.armUp);
Autonomous.delay(Constant.Shared.armMoveMaxTime);
this.armMotor.set(Constant.Shared.armStop);
}
/**
* To drive straight some distance.
*
* @author James
* @param driveDistance
* Meters of driving
* @param PLACEHOLDER
* This is just a placeholder and does not do anything.
* You can just use empty string "" for this.
*/
private void driveStraight(double driveDistance,
Object PLACEHOLDER) {
PLACEHOLDER = "";
}
/**
* Place Holder. To drive straight. Need more info.
*
* @author James
* @param driveTime
* Seconds of driving
*/
private void driveStraight(double driveTime) {
// getting the victor[] array.
Victor[] vicList = new Victor[] { this.frontLeft,
this.frontRight, this.backLeft, this.backRight };
// command starts
Autonomous.setVictorArray(vicList, Const.Motor.Run.Forward);
DriveTrain dT = new DriveTrain(this.frontLeft, this.backLeft,
this.frontRight, this.backRight);
// command starts
dT.drive(Const.Motor.Run.Forward);
Autonomous.delay(driveTime);
dT.drive(Const.Motor.Run.Stop);
}
private static void setVictorArray(Victor[] vicList,
double setValue) {
for (Victor v : vicList)
v.set(setValue);
}
/**
* throw ball out. Yet tested.
*
* @author James
*/
private void throwBall() {
this.intake.set(Const.Motor.Run.Forward);
Autonomous.delay(Constant.Shared.intakeDelay);
this.intake.set(Const.Motor.Run.Stop);
}
/**
* Autonomous function No.1
*
* @author James
*/
public void autoLowBar() {
this.armLowerBottom();
this.driveStraight(Constant.ConstLowBar.driveThroughDelay);
}
/**
* Autonomous function No.2
*
* @author James
*/
public void autoSpyBotLowGoal() {
this.armLowerBottom();
this.driveStraight(Constant.ConstSpyBotLowGoal.driveToDelay);
this.throwBall();
}
/**
* Autonomous function No.3
*
* @author James
*/
public void autoChevalDeFrise() {
this.driveStraight(Constant.ConstChevalDeFrise.driveToDelay);
this.armLowerBottom();
this.driveStraight(
Constant.ConstChevalDeFrise.driveThroughDelay);
}
/**
* Autonomous function No.4
*
* @author James
*/
public void autoPortcullis() {
this.armLowerBottom();
this.driveStraight(Constant.ConstPortcullis.driveDelay);
this.armLifterTop();
this.driveStraight(
Constant.ConstPortcullis.driveThroughDelay);
}
/**
* Should be equivalent to a method called getAccel of another
* class I2CAccelerometer which isn't here yet.
*
* @author James
* @return Accelerations, double[] with length of 3
*/
private static double[] I2CAccelerometer_getAccel() {
double[] accel = new double[3];
return accel; // placeholder
}
/**
* Calculates distance traveled based on information from the
* accelerometer.
*
* @author Joey
* @return
*/
private static double[] I2CDistanceTraveled() {
while (true) {
double[] acceleration =
Autonomous.I2CAccelerometer_getAccel();
double[] vtx = acceleration[0] * dt;
double[] vty = acceleration[1] * dt;
double[] xt = vtx * dt;
double[] yt = vty * dt;
}
}
/**
* Should be equivalent to a method called getAngles of another
* class I2CGyro which isn't here yet.
*
* @author James
* @return Angles, double[] with length of 3
*/
private static double[] I2CGyro_getAngles() {
double[] angles = new double[3];
return angles; // placeholder
}
}
|
package gvs.ui.application.controller;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private Stage primaryStage;
private BorderPane rootLayout;
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("GVS");
initRootLayout();
}
private void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("../view/Main.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
// TODO add logging framework
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
|
package innovimax.mixthem.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
/**
* <p>This is the representation of an input resource.</p>
* @author Innovimax
* @version 1.0
*/
public abstract class InputResource {
private static class FileResource extends InputResource {
private final File file;
private FileResource(File file) {
this.file = file;
}
@Override
public BufferedReader newBufferedReader() throws IOException {
return Files.newBufferedReader(input.toPath(), StandardCharsets.UTF_8);
}
}
private static class InputStreamResource extends InputResource {
private final InputStream input;
private InputStreamResource(File input) {
this.input = input;
}
@Override
public BufferedReader newBufferedReader() throws IOException {
return new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
}
}
/**
* private Constructor
*/
public InputResource() {}
public static InputResource createFile(File file) {
return new FileResource(file);
}
public static InputResource createInputStream(InputStream input) {
return new InputStreamResource(input);
}
/**
* Returns a new BufferedReader for this input resource.
* @return The BufferedReader for this input resource
*/
public abstract BufferedReader newBufferedReader() throws IOException;
}
|
package me.unrealization.jeeves.bot;
import me.unrealization.jeeves.interfaces.BotModule;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import me.unrealization.jeeves.modules.Ccn;
import me.unrealization.jeeves.modules.Cron;
import me.unrealization.jeeves.modules.Edsm;
import me.unrealization.jeeves.modules.Internal;
import me.unrealization.jeeves.modules.ModLog;
import me.unrealization.jeeves.modules.ParadoxWing;
import me.unrealization.jeeves.modules.Roles;
import me.unrealization.jeeves.modules.UserLog;
import me.unrealization.jeeves.modules.Welcome;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.xml.sax.SAXException;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.api.events.EventDispatcher;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.DiscordException;
public class Jeeves
{
public static String version = null;
public static IDiscordClient bot = null;
public static ClientConfig clientConfig = null;
public static ServerConfig serverConfig = null;
private static HashMap<String, BotModule> modules = null;
private static IDiscordClient createClient(String token)
{
return Jeeves.createClient(token, true);
}
private static IDiscordClient createClient(String token, boolean login)
{
ClientBuilder clientBuilder = new ClientBuilder();
clientBuilder.withToken(token);
IDiscordClient client = null;
try
{
if (login == true)
{
client = clientBuilder.login();
}
else
{
client = clientBuilder.build();
}
}
catch (DiscordException e)
{
Jeeves.debugException(e);
}
return client;
}
private static void loadModules()
{
Jeeves.modules = new HashMap< String, BotModule>();
Jeeves.modules.put("ccn", new Ccn());
try
{
Jeeves.modules.put("cron", new Cron());
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
}
try
{
Jeeves.modules.put("edsm", new Edsm());
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
}
Jeeves.modules.put("internal", new Internal());
Jeeves.modules.put("modLog", new ModLog());
Jeeves.modules.put("paradoxWing", new ParadoxWing());
Jeeves.modules.put("roles", new Roles());
Jeeves.modules.put("userLog", new UserLog());
Jeeves.modules.put("welcome", new Welcome());
}
public static BotModule getModule(String moduleName)
{
BotModule module = Jeeves.modules.get(moduleName);
return module;
}
public static String[] getModuleList()
{
Set<String> moduleSet = Jeeves.modules.keySet();
String[] moduleList = moduleSet.toArray(new String[moduleSet.size()]);
return moduleList;
}
public static void checkConfig(long serverId, HashMap<String, Object> defaultConfig) throws ParserConfigurationException, TransformerException
{
if (defaultConfig == null)
{
return;
}
boolean updated = false;
Set<String> keySet = defaultConfig.keySet();
String[] keyList = keySet.toArray(new String[keySet.size()]);
for (int keyIndex = 0; keyIndex < keyList.length; keyIndex++)
{
if (Jeeves.serverConfig.hasKey(serverId, keyList[keyIndex]) == false)
{
Jeeves.serverConfig.setValue(serverId, keyList[keyIndex], defaultConfig.get(keyList[keyIndex]));
updated = true;
}
}
if (updated == true)
{
Jeeves.serverConfig.saveConfig();
}
}
public static boolean debugException(Exception e)
{
String debugging = (String)Jeeves.clientConfig.getValue("debugging");
if (debugging.equals("1") == true)
{
e.printStackTrace();
return true;
}
return false;
}
public static List<String> listToStringList(List<?> list)
{
List<String> stringList = new ArrayList<String>();
for (int listIndex = 0; listIndex < list.size(); listIndex++)
{
Object item = list.get(listIndex);
if (item.getClass() != String.class)
{
continue;
}
String value = (String)item;
stringList.add(value);
}
return stringList;
}
public static IChannel findChannel(IGuild server, String channelName)
{
List<IChannel> channelList = server.getChannelsByName(channelName);
if (channelList.size() > 0)
{
return channelList.get(0);
}
else
{
channelList = server.getChannels();
for (int channelIndex = 0; channelIndex < channelList.size(); channelIndex++)
{
IChannel channel = channelList.get(channelIndex);
if (channel.mention().equals(channelName) == true)
{
return channel;
}
}
}
return null;
}
public static IRole findRole(IGuild server, String roleName)
{
List<IRole> roleList = server.getRolesByName(roleName);
if (roleList.size() > 0)
{
return roleList.get(0);
}
else
{
roleList = server.getRoles();
for (int roleIndex = 0; roleIndex < roleList.size(); roleIndex++)
{
IRole role = roleList.get(roleIndex);
if (role.mention().equals(roleName) == true)
{
return role;
}
}
}
return null;
}
public static IUser findUser(IGuild server, String userName)
{
List<IUser> userList = server.getUsersByName(userName);
if (userList.size() > 0)
{
return userList.get(0);
}
else
{
userList = server.getUsers();
for (int userIndex = 0; userIndex < userList.size(); userIndex++)
{
IUser user = userList.get(userIndex);
if ((user.mention(true).equals(userName) == true) || (user.mention(false).equals(userName) == true))
{
return user;
}
}
}
return null;
}
public static boolean isIgnored(IChannel channel)
{
Object ignoredChannels = Jeeves.serverConfig.getValue(channel.getGuild().getLongID(), "ignoredChannels");
if (ignoredChannels.getClass() == String.class)
{
return false;
}
List<String> ignoredChannelList = Jeeves.listToStringList((List<?>)ignoredChannels);
return ignoredChannelList.contains(Long.toString(channel.getLongID()));
}
public static boolean isIgnored(long serverId, IUser user)
{
Object ignoredUsers = Jeeves.serverConfig.getValue(serverId, "ignoredUsers");
if (ignoredUsers.getClass() == String.class)
{
return false;
}
List<String> ignoredUserList = Jeeves.listToStringList((List<?>)ignoredUsers);
return ignoredUserList.contains(Long.toString(user.getLongID()));
}
public static boolean isIgnored(IRole role)
{
Object ignoredRoles = Jeeves.serverConfig.getValue(role.getGuild().getLongID(), "ignoredRoles");
if (ignoredRoles.getClass() == String.class)
{
return false;
}
List<String> ignoredRoleList = Jeeves.listToStringList((List<?>)ignoredRoles);
return ignoredRoleList.contains(Long.toString(role.getLongID()));
}
public static boolean isDisabled(long serverId, BotModule module)
{
Long discordId = module.getDiscordId();
if ((discordId != null) && (discordId.equals(serverId) == false))
{
return true;
}
Object disabledModules = Jeeves.serverConfig.getValue(serverId, "disabledModules");
if (disabledModules.getClass() == String.class)
{
return false;
}
String moduleName = module.getClass().getSimpleName().toLowerCase();
List<String> disabledModuleList = Jeeves.listToStringList((List<?>)disabledModules);
return disabledModuleList.contains(moduleName);
}
public static String getUtcTime()
{
Instant now = Instant.now();
String timeString = now.toString();
Pattern regEx = Pattern.compile("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}:[\\d]{2}:[\\d]{2})\\.[\\d]{3}Z$");
Matcher regExMatcher = regEx.matcher(timeString);
if (regExMatcher.matches() == false)
{
return timeString;
}
String year = regExMatcher.group(1);
String month = regExMatcher.group(2);
String day = regExMatcher.group(3);
String time = regExMatcher.group(4);
timeString = year + "-" + month + "-" + day + " " + time;
return timeString;
}
public static String[] splitArguments(String argumentString)
{
String[] arguments = argumentString.split(":");
for (int index = 0; index < arguments.length; index++)
{
arguments[index] = arguments[index].trim();
}
return arguments;
}
private static class ShutdownHook extends Thread
{
@Override
public void run()
{
try
{
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.shutdown();
}
catch (SchedulerException e)
{
Jeeves.debugException(e);
}
if (Jeeves.bot.isLoggedIn() == true)
{
System.out.println("Logging out.");
try
{
Jeeves.bot.logout();
}
catch (DiscordException e)
{
Jeeves.debugException(e);
}
}
}
}
public static void main(String[] args)
{
Jeeves.version = Jeeves.class.getPackage().getImplementationVersion();
if (Jeeves.version == null)
{
Jeeves.version = "Testing";
}
try
{
Jeeves.clientConfig = new ClientConfig();
}
catch (ParserConfigurationException | SAXException | IOException e)
{
Jeeves.debugException(e);
return;
}
try
{
Jeeves.serverConfig = new ServerConfig();
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
return;
}
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
Jeeves.loadModules();
Jeeves.bot = Jeeves.createClient((String)Jeeves.clientConfig.getValue("loginToken"));
EventDispatcher dispatcher = Jeeves.bot.getDispatcher();
dispatcher.registerListener(new DiscordEventHandlers.ReadyEventListener());
}
}
|
package mil.dds.anet;
import com.google.common.collect.ImmutableList;
import io.dropwizard.Application;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import java.util.List;
import java.util.Scanner;
import mil.dds.anet.beans.AdminSetting;
import mil.dds.anet.beans.ApprovalStep;
import mil.dds.anet.beans.ApprovalStep.ApprovalStepType;
import mil.dds.anet.beans.Organization;
import mil.dds.anet.beans.Organization.OrganizationType;
import mil.dds.anet.beans.Person;
import mil.dds.anet.beans.Person.Role;
import mil.dds.anet.beans.Position;
import mil.dds.anet.beans.Position.PositionType;
import mil.dds.anet.beans.search.PersonSearchQuery;
import mil.dds.anet.config.AnetConfiguration;
import mil.dds.anet.database.AdminDao.AdminSettingKeys;
import net.sourceforge.argparse4j.inf.Namespace;
public class InitializationCommand extends EnvironmentCommand<AnetConfiguration> {
protected InitializationCommand(Application<AnetConfiguration> application) {
super(application, "init", "Initializes the ANET Database");
}
@Override
protected void run(Environment environment, Namespace namespace, AnetConfiguration configuration)
throws Exception {
final AnetObjectEngine engine = AnetObjectEngine.getInstance();
System.out.println("
System.out.println("We're going to ask you a few questions to get ANET set up.");
System.out.println();
System.out.println("Detecting state of database...");
final PersonSearchQuery psq = new PersonSearchQuery();
final List<Person> currPeople = engine.getPersonDao().search(psq).getList();
if (currPeople.isEmpty()) {
System.out.println("ERROR: ANET Importer missing from database");
System.out.println("\tYou should run all migrations first");
System.exit(1);
return;
}
// Only person should be "ANET Importer"
if (currPeople.size() != 1 || !"ANET Importer".equals(currPeople.get(0).getName())) {
System.out.println("ERROR: Other people besides ANET Importer detected in database");
System.out.println("\tThis task can only be run on an otherwise empty database");
System.exit(1);
return;
}
System.out.println("OK!");
System.out.println();
System.out.println("Please provide the following information:");
Scanner scanner = new Scanner(System.in);
// Set Classification String
System.out.print("Classification String >>");
AdminSetting classifString = new AdminSetting();
classifString.setKey(AdminSettingKeys.SECURITY_BANNER_TEXT.name());
classifString.setValue(scanner.nextLine());
engine.getAdminDao().saveSetting(classifString);
System.out.println("... Saved!");
// Set Classification Color
System.out.print("Classification Color >>");
AdminSetting classifColor = new AdminSetting();
classifColor.setKey(AdminSettingKeys.SECURITY_BANNER_COLOR.name());
classifColor.setValue(scanner.nextLine());
engine.getAdminDao().saveSetting(classifColor);
System.out.println("... Saved!");
// Create First Organization
System.out.print("Name of Administrator Organization >>");
Organization adminOrg = new Organization();
adminOrg.setType(OrganizationType.ADVISOR_ORG);
adminOrg.setShortName(scanner.nextLine());
adminOrg.setStatus(Organization.Status.ACTIVE);
adminOrg = engine.getOrganizationDao().insert(adminOrg);
System.out.println("... Organization " + adminOrg.getUuid() + " Saved!");
// Create First Position
System.out.print("Name of Administrator Position >>");
Position adminPos = new Position();
adminPos.setType(PositionType.ADMINISTRATOR);
adminPos.setOrganizationUuid(adminOrg.getUuid());
adminPos.setName(scanner.nextLine());
adminPos.setStatus(Position.Status.ACTIVE);
adminPos = engine.getPositionDao().insert(adminPos);
System.out.println("... Position " + adminPos.getUuid() + " Saved!");
// Create First User
System.out.print("Your Name [LAST NAME, First name(s)] >>");
Person admin = new Person();
admin.setName(scanner.nextLine());
System.out.print("Your Domain Username >>");
admin.setDomainUsername(scanner.nextLine());
admin.setRole(Role.ADVISOR);
admin = engine.getPersonDao().insert(admin);
engine.getPositionDao().setPersonInPosition(admin.getUuid(), adminPos.getUuid());
System.out.println("... Person " + admin + " Saved!");
// Set Default Approval Chain.
System.out.println("Setting you as the default approver...");
AdminSetting defaultOrg = new AdminSetting();
defaultOrg.setKey(AdminSettingKeys.DEFAULT_APPROVAL_ORGANIZATION.name());
defaultOrg.setValue(adminOrg.getUuid());
engine.getAdminDao().saveSetting(defaultOrg);
ApprovalStep defaultStep = new ApprovalStep();
defaultStep.setName("Default Approver");
defaultStep.setType(ApprovalStepType.REPORT_APPROVAL);
defaultStep.setRelatedObjectUuid(adminOrg.getUuid());
defaultStep.setApprovers(ImmutableList.of(adminPos));
engine.getApprovalStepDao().insert(defaultStep);
System.out.println("DONE!");
AdminSetting contactEmail = new AdminSetting();
contactEmail.setKey(AdminSettingKeys.CONTACT_EMAIL.name());
contactEmail.setValue("");
engine.getAdminDao().saveSetting(contactEmail);
AdminSetting helpUrl = new AdminSetting();
helpUrl.setKey(AdminSettingKeys.HELP_LINK_URL.name());
helpUrl.setValue("");
engine.getAdminDao().saveSetting(helpUrl);
System.out.println();
System.out.println("All Done! You should be able to start the server now and log in");
scanner.close();
System.exit(0);
}
}
|
package com.pphi.iron.dragon.component.deck;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.pphi.iron.dragon.component.card.ship.ShipCard;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public class ShipDeck extends Deck<ShipCard> {
private final ShipDiscardPile shipDiscardPile;
public ShipDeck() {
super();
shipDiscardPile = new ShipDiscardPile();
}
@Override
@JsonIgnore
public DiscardPile<ShipCard> getDiscardPile() {
return shipDiscardPile;
}
@Override
public void discard(ShipCard card) {
shipDiscardPile.addCardToDiscardPile(card);
}
@Override
@JsonIgnore
public List<ShipCard> combineDiscardPileWithDeck() {
deck.addAll(shipDiscardPile.getDiscardPile());
shipDiscardPile.emptyDiscardPile();
return deck;
}
@Override
@JsonIgnore
protected ShipCard getCardFromDiscardPile() {
throw new UnsupportedOperationException("That action is not allowed");
}
}
|
package net.finmath.analytic.products;
import net.finmath.analytic.model.AnalyticModel;
import net.finmath.analytic.model.AnalyticModelInterface;
import net.finmath.analytic.model.curves.CurveInterface;
import net.finmath.analytic.model.curves.DiscountCurveFromForwardCurve;
import net.finmath.analytic.model.curves.DiscountCurveInterface;
import net.finmath.analytic.model.curves.ForwardCurveInterface;
import net.finmath.montecarlo.AbstractRandomVariableFactory;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.RegularSchedule;
import net.finmath.time.ScheduleInterface;
import net.finmath.time.TimeDiscretizationInterface;
/**
* Implements the valuation of a swap using curves (discount curve, forward curve).
* The swap valuation supports distinct discounting and forward curve.
* Support for day counting is limited to the capabilities of
* <code>TimeDiscretizationInterface</code>.
*
* The swap is just the composition of two <code>SwapLeg</code>s, namely the
* receiver leg and the payer leg. The value of the swap is the value of the receiver leg minus the value of the payer leg.
*
* @author Christian Fries
*/
public class Swap extends AbstractAnalyticProduct implements AnalyticProductInterface {
private final AnalyticProductInterface legReceiver;
private final AnalyticProductInterface legPayer;
/**
* Create a swap which values as <code>legReceiver - legPayer</code>.
*
* @param legReceiver The receiver leg.
* @param legPayer The payler leg.
*/
public Swap(AnalyticProductInterface legReceiver, AnalyticProductInterface legPayer) {
super();
this.legReceiver = legReceiver;
this.legPayer = legPayer;
}
/**
* Creates a swap with notional exchange. The swap has a unit notional of 1.
*
* @param scheduleReceiveLeg Schedule of the receiver leg.
* @param forwardCurveReceiveName Name of the forward curve, leave empty if this is a fix leg.
* @param spreadReceive Fixed spread on the forward or fix rate.
* @param discountCurveReceiveName Name of the discount curve for the receiver leg.
* @param schedulePayLeg Schedule of the payer leg.
* @param forwardCurvePayName Name of the forward curve, leave empty if this is a fix leg.
* @param spreadPay Fixed spread on the forward or fix rate.
* @param discountCurvePayName Name of the discount curve for the payer leg.
* @param isNotionalExchanged If true, both leg will pay notional at the beginning of each swap period and receive notional at the end of the swap period. Note that the cash flow date for the notional is periodStart and periodEnd (not fixingDate and paymentDate).
*/
public Swap(ScheduleInterface scheduleReceiveLeg,
String forwardCurveReceiveName, double spreadReceive,
String discountCurveReceiveName,
ScheduleInterface schedulePayLeg,
String forwardCurvePayName, double spreadPay,
String discountCurvePayName,
boolean isNotionalExchanged
) {
super();
legReceiver = new SwapLeg(scheduleReceiveLeg, forwardCurveReceiveName, spreadReceive, discountCurveReceiveName, isNotionalExchanged /* Notional Exchange */);
legPayer = new SwapLeg(schedulePayLeg, forwardCurvePayName, spreadPay, discountCurvePayName, isNotionalExchanged /* Notional Exchange */);
}
/**
* Creates a swap with notional exchange. The swap has a unit notional of 1.
*
* @param scheduleReceiveLeg Schedule of the receiver leg.
* @param forwardCurveReceiveName Name of the forward curve, leave empty if this is a fix leg.
* @param spreadReceive Fixed spread on the forward or fix rate.
* @param discountCurveReceiveName Name of the discount curve for the receiver leg.
* @param schedulePayLeg Schedule of the payer leg.
* @param forwardCurvePayName Name of the forward curve, leave empty if this is a fix leg.
* @param spreadPay Fixed spread on the forward or fix rate.
* @param discountCurvePayName Name of the discount curve for the payer leg.
*/
public Swap(ScheduleInterface scheduleReceiveLeg,
String forwardCurveReceiveName, double spreadReceive,
String discountCurveReceiveName,
ScheduleInterface schedulePayLeg,
String forwardCurvePayName, double spreadPay,
String discountCurvePayName
) {
this(scheduleReceiveLeg, forwardCurveReceiveName, spreadReceive, discountCurveReceiveName, schedulePayLeg, forwardCurvePayName, spreadPay, discountCurvePayName, true);
}
@Override
public RandomVariableInterface getValue(double evaluationTime, AnalyticModelInterface model) {
RandomVariableInterface valueReceiverLeg = legReceiver.getValue(evaluationTime, model);
RandomVariableInterface valuePayerLeg = legPayer.getValue(evaluationTime, model);
return valueReceiverLeg.sub(valuePayerLeg);
}
static public RandomVariableInterface getForwardSwapRate(TimeDiscretizationInterface fixTenor, TimeDiscretizationInterface floatTenor, ForwardCurveInterface forwardCurve) {
return getForwardSwapRate(new RegularSchedule(fixTenor), new RegularSchedule(floatTenor), forwardCurve);
}
static public RandomVariableInterface getForwardSwapRate(TimeDiscretizationInterface fixTenor, TimeDiscretizationInterface floatTenor, ForwardCurveInterface forwardCurve, DiscountCurveInterface discountCurve) {
AnalyticModel model = null;
if(discountCurve != null) {
model = new AnalyticModel(new CurveInterface[] { forwardCurve, discountCurve });
}
return getForwardSwapRate(new RegularSchedule(fixTenor), new RegularSchedule(floatTenor), forwardCurve, model);
}
static public RandomVariableInterface getForwardSwapRate(ScheduleInterface fixSchedule, ScheduleInterface floatSchedule, ForwardCurveInterface forwardCurve) {
return getForwardSwapRate(fixSchedule, floatSchedule, forwardCurve, null);
}
static public RandomVariableInterface getForwardSwapRate(ScheduleInterface fixSchedule, ScheduleInterface floatSchedule, ForwardCurveInterface forwardCurve, AnalyticModelInterface model) {
DiscountCurveInterface discountCurve = model == null ? null : model.getDiscountCurve(forwardCurve.getDiscountCurveName());
if(discountCurve == null) {
discountCurve = new DiscountCurveFromForwardCurve(forwardCurve.getName());
model = new AnalyticModel(new CurveInterface[] { forwardCurve, discountCurve });
}
double evaluationTime = fixSchedule.getFixing(0); // Consider all values
RandomVariableInterface swapAnnuity = SwapAnnuity.getSwapAnnuity(evaluationTime, fixSchedule, discountCurve, model);
// Create floating leg
double fixing = floatSchedule.getFixing(0);
double payment = floatSchedule.getPayment(0);
double periodLength = floatSchedule.getPeriodLength(0);
RandomVariableInterface forward = forwardCurve.getForward(model, fixing);
RandomVariableInterface discountFactor = discountCurve.getDiscountFactor(model, payment);
RandomVariableInterface floatLeg = forward.mult(discountFactor).mult(periodLength);
for(int periodIndex=1; periodIndex<floatSchedule.getNumberOfPeriods(); periodIndex++) {
fixing = floatSchedule.getFixing(periodIndex);
payment = floatSchedule.getPayment(periodIndex);
periodLength = floatSchedule.getPeriodLength(periodIndex);
forward = forwardCurve.getForward(model, fixing);
discountFactor = discountCurve.getDiscountFactor(model, payment);
floatLeg = floatLeg.add(forward.mult(discountFactor).mult(periodLength));
}
RandomVariableInterface valueFloatLeg = floatLeg.div(discountCurve.getDiscountFactor(model, evaluationTime));
return valueFloatLeg.div(swapAnnuity);
}
/**
* Return the receiver leg of the swap, i.e. the leg who's value is added to the swap value.
*
* @return The receiver leg of the swap.
*/
public AnalyticProductInterface getLegReceiver() {
return legReceiver;
}
/**
* Return the payer leg of the swap, i.e. the leg who's value is subtracted from the swap value.
*
* @return The payer leg of the swap.
*/
public AnalyticProductInterface getLegPayer() {
return legPayer;
}
@Override
public String toString() {
return "Swap [legReceiver=" + legReceiver + ", legPayer=" + legPayer
+ "]";
}
}
|
package com.socrata.datasync.publishers;
import com.socrata.datasync.SocrataConnectionInfo;
import com.socrata.datasync.job.GISJob;
import com.socrata.datasync.job.JobStatus;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GISPublisher {
private static final Logger logging = Logger.getLogger(GISJob.class.getName());
private static String ticket = "";
public static JobStatus replaceGeo(File file, SocrataConnectionInfo connectionInfo, String datasetID) {
String scan_url = makeUri(connectionInfo.getUrl(), "scan");
String blueprint = "";
JobStatus status = JobStatus.SUCCESS;
try {
blueprint = postRawFile(scan_url, file, connectionInfo);
status = replaceGeoFile(blueprint, file, connectionInfo, datasetID);
} catch (IOException e) {
String message = e.getMessage();
JobStatus s = JobStatus.PUBLISH_ERROR;
s.setMessage(message);
return s;
}
return status;
}
public static JobStatus replaceGeoFile(String blueprint, File file, SocrataConnectionInfo connectionInfo, String datasetID) {
JobStatus status = JobStatus.SUCCESS;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(blueprint);
JSONObject array = (JSONObject)obj;
if (array.containsKey("error")) {
boolean error = (boolean) array.get("error");
if(error) {
String message = array.get("message").toString();
logging.log(Level.INFO,message);
JobStatus s = JobStatus.PUBLISH_ERROR;
s.setMessage(message);
return s;
}
}
String fileId = array.get("fileId").toString();
String name = file.getName();
String bluepr = array.get("summary").toString();
String query = "";
String url = makeUri(connectionInfo.getUrl(),"replace");
query = query + "&fileId="+ URLEncoder.encode(fileId,"UTF-8");
query = query + "&name="+URLEncoder.encode(name,"UTF-8");
query = query + "&blueprint=" + URLEncoder.encode(bluepr,"UTF-8");
query = query + "&viewUid=" + URLEncoder.encode(datasetID,"UTF-8");
url = url + query;
//logging.log(Level.INFO,url);
status = postReplaceGeoFile(url, connectionInfo);
} catch(ParseException | UnsupportedEncodingException e) {
String message = e.getMessage();
JobStatus s = JobStatus.PUBLISH_ERROR;
s.setMessage(message);
return s;
}
return status;
}
public static JobStatus postReplaceGeoFile(String url, SocrataConnectionInfo connectionInfo) {
JobStatus status = JobStatus.SUCCESS;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
logging.log(Level.INFO, url);
HttpPost httpPost = new HttpPost(url);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpPost.setHeader("Authorization","Basic "+auth);
httpPost.setHeader("X-App-Token", connectionInfo.getToken());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
JSONParser parser = new JSONParser();
JSONObject resJson = (JSONObject) parser.parse(result);
logging.log(Level.INFO, result);
boolean error = (boolean) resJson.get("error");
if(error) {
JobStatus s = JobStatus.PUBLISH_ERROR;
String error_message = (String) resJson.get("message");
s.setMessage(error_message);
return s;
}
ticket = resJson.get("ticket").toString();
try {
logging.log(Level.INFO,"Polling for Status...");
status = pollForStatus(ticket, connectionInfo,false);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException | ParseException e) {
String message = e.getMessage();
JobStatus s = JobStatus.PUBLISH_ERROR;
s.setMessage(message);
return s;
}
return status;
}
public static JobStatus pollForStatus(String ticket, SocrataConnectionInfo connectionInfo, boolean complete) throws InterruptedException {
String status_url = makeUri(connectionInfo.getUrl(),"status") + ticket;
String[] status = new String[2];
if(!complete)
{
status = getStatus(status_url,connectionInfo);
logging.log(Level.INFO,status[1]);
Thread.sleep(1000);
if (status[0] == "Complete") {
return JobStatus.SUCCESS;
}
if (status[0] == "Error"){
JobStatus s = JobStatus.PUBLISH_ERROR;
s.setMessage(status[1]);
return s;
}
pollForStatus(ticket,connectionInfo,false);
}
return JobStatus.SUCCESS;
}
public static String[] getStatus(String url, SocrataConnectionInfo connectionInfo) {
String[] status = new String[2];
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpGet.setHeader("Authorization","Basic "+auth);
httpGet.setHeader("X-App-Token", connectionInfo.getToken());
HttpResponse response = httpClient.execute(httpGet);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
JSONParser parser = new JSONParser();
JSONObject resJson = (JSONObject) parser.parse(result);
try {
boolean error = (boolean) resJson.get("error");
JSONObject details = (JSONObject) resJson.get("details");
if(error){
status[0] = "Error";
status[1] = resJson.get("message").toString()+" with code: "+resJson.get("code").toString();
return status;
}
else {
try {
status[0] = "Progress";
status[1] = details.get("status").toString() + ": " + details.get("progress").toString() + " features completed";
} catch (NullPointerException e) {
status[0] = "Progress";
status[1] = details.get("stage").toString();
return status;
}
}
} catch (NullPointerException e) {
// For once the ticket is complete
status[0] = "Complete";
status[1] = "Complete";
return status;
}
return status;
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
status[0] = "Complete";
status[1] = "Complete";
return status;
}
return status;
}
public static String postRawFile(String uri, File file, SocrataConnectionInfo connectionInfo) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpPost.setHeader("Authorization","Basic "+auth);
httpPost.setHeader("X-App-Token", connectionInfo.getToken());
logging.log(Level.INFO, "Posting file...");
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM,file.getName())
.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
logging.log(Level.INFO,result);
return result;
}
public static String makeUri(String domain,String method) {
switch(method) {
case "scan":
return domain + "/api/imports2?method=scanShape";
case "replace":
return domain + "/api/imports2?method=replaceShapefile";
case "status":
return domain + "/api/imports2?ticket=";
default:
return "Method Required";
}
}
}
|
package net.oneandone.inline.parser;
import net.oneandone.inline.types.Repository;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** Reference to a Class or an Instance. A ContextFactory factory. */
public class Handle {
private final Object classOrInstance;
public Handle(Object classOrInstance) {
this.classOrInstance = classOrInstance;
}
private boolean isClass() {
return classOrInstance instanceof Class<?>;
}
private Object instance() {
if (isClass()) {
throw new IllegalStateException();
}
return classOrInstance;
}
public ExceptionHandler exceptionHandler() {
if (isClass()) {
return null;
}
if (classOrInstance instanceof ExceptionHandler) {
return (ExceptionHandler) classOrInstance;
} else {
return null;
}
}
public Class<?> clazz() {
if (isClass()) {
return (Class) classOrInstance;
} else {
return classOrInstance.getClass();
}
}
public ContextFactory compile(Context context, Repository schema, List<Source> constructorSources) {
Class<?> clazz;
ContextFactory found;
ContextFactory candidate;
found = null;
if (isClass()) {
clazz = clazz();
for (Constructor constructor : clazz.getDeclaredConstructors()) {
candidate = match(context, schema, constructor, constructorSources);
if (candidate != null) {
if (found != null) {
throw new InvalidCliException("constructor is ambiguous: " + clazz.getName());
}
found = candidate;
}
}
if (found == null) {
throw new InvalidCliException("no matching constructor: " + clazz.getName() + "(" + names(constructorSources) + ")");
}
return found;
} else {
if (!constructorSources.isEmpty()) {
throw new InvalidCliException("cannot apply constructor argument to an instance");
}
return new IdentityContextFactory(instance());
}
}
private ContextFactory match(Context context, Repository schema, Constructor constructor, List<Source> initialSources) {
List<Argument> arguments;
List<Context> remainingContext;
List<Source> remainingSources;
Parameter[] formals;
Object[] actuals;
Parameter formal;
Object ctx;
Source source;
arguments = new ArrayList<>();
remainingContext = context.parentList();
remainingSources = new ArrayList<>(initialSources);
formals = constructor.getParameters();
actuals = new Object[formals.length];
for (int i = 0; i < formals.length; i++) {
formal = formals[i];
ctx = eatContext(remainingContext, formal.getType());
if (ctx != null) {
actuals[i] = ctx;
} else if (remainingSources.isEmpty()) {
return null; // too many constructor arguments
} else {
source = remainingSources.remove(0);
arguments.add(new Argument(context, source, new TargetParameter(schema, formal.getParameterizedType(), actuals, i)));
}
}
if (!remainingSources.isEmpty()) {
return null; // not all arguments matched
}
return new ConstructorContextFactory(constructor, actuals, arguments);
}
private static Object eatContext(List<Context> parents, Class<?> type) {
Context context;
boolean isClass;
for (int i = 0, max = parents.size(); i < max; i++) {
context = parents.get(i);
isClass = context.handle.isClass();
if (type.isAssignableFrom(context.handle.clazz())) {
parents.remove(i);
return isClass ? context : context.handle.instance();
}
}
return null;
}
private static String names(List<Source> sources) {
StringBuilder result;
result = new StringBuilder();
for (Source source : sources) {
if (result.length() > 0) {
result.append(", ");
}
result.append(source.getName());
}
return result.toString();
}
public static class IdentityContextFactory extends ContextFactory {
private final Object instance;
public IdentityContextFactory(Object instance) {
super(new ArrayList<>());
this.instance = instance;
}
@Override
public Object newInstance(Map<Context, Object> instantiatedContexts) throws Throwable {
return instance;
}
}
public static class ConstructorContextFactory extends ContextFactory {
private final Constructor<?> constructor;
private final Object[] constructorActuals;
public ConstructorContextFactory(Constructor<?> constructor, Object[] constructorActuals, List<Argument> arguments) {
super(arguments);
this.constructor = constructor;
this.constructorActuals = constructorActuals;
}
@Override
public Object newInstance(Map<Context, Object> instantiatedContexts) throws Throwable {
Object instance;
for (int i = 0, max = constructorActuals.length; i < max; i++) {
if (constructorActuals[i] instanceof Context) {
instance = instantiatedContexts.get(constructorActuals[i]);
if (instance == null) {
throw new IllegalStateException();
}
constructorActuals[i] = instance;
}
}
try {
instance = constructor.newInstance(constructorActuals);
} catch (InvocationTargetException e) {
throw e.getCause();
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("TODO", e);
}
return instance;
}
}
}
|
package com.softinstigate.restheart.db;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.softinstigate.restheart.utils.RequestContext;
import java.time.Instant;
import java.util.Map;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author uji
*/
public class MetadataFixer
{
private static final MongoClient client = MongoDBClientSingleton.getInstance().getClient();
private static final Logger logger = LoggerFactory.getLogger(MetadataFixer.class);
public static boolean addCollectionMetadata(String dbName, String collName)
{
Map<String, Object> dbmd = DBDAO.getDbMetaData(dbName);
if (dbmd == null)
{
// db must exists with metadata
return false;
}
Map<String, Object> md = CollectionDAO.getCollectionMetadata(dbName, collName);
if (md != null) // metadata exists
{
return false;
}
// check if collection has data
DB db = DBDAO.getDB(dbName);
if (!db.collectionExists(collName))
{
return false;
}
// ok, create the metadata
DBObject metadata = new BasicDBObject();
ObjectId timestamp = new ObjectId();
Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());
metadata.put("_id", "@metadata");
metadata.put("@created_on", now.toString());
metadata.put("@etag", timestamp);
DBCollection coll = CollectionDAO.getCollection(dbName, collName);
coll.insert(metadata);
logger.info("metadata added to {}/{}", dbName, collName);
return true;
}
public static boolean addDbMetadata(String dbName)
{
if (!DBDAO.doesDbExists(dbName))
{
return false;
}
Map<String, Object> dbmd = DBDAO.getDbMetaData(dbName);
if (dbmd != null) // metadata exists
{
return false;
}
DB db = DBDAO.getDB(dbName);
// ok, create the metadata
DBObject metadata = new BasicDBObject();
ObjectId timestamp = new ObjectId();
Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());
metadata.put("_id", "@metadata");
metadata.put("@created_on", now.toString());
metadata.put("@etag", timestamp);
DBCollection coll = CollectionDAO.getCollection(dbName, "@metadata");
coll.insert(metadata);
logger.info("metadata added to {}", dbName);
return true;
}
public static void fixMetadata()
{
client.getDatabaseNames().stream().filter((dbName) -> (!RequestContext.isReservedResourceDb(dbName))).map((dbName) ->
{
try
{
addDbMetadata(dbName);
}
catch (Throwable t)
{
logger.error("error fixing metadata of db {}", dbName, t);
}
return dbName;
}).forEach((dbName) ->
{
DB db = DBDAO.getDB(dbName);
DBDAO.getDbCollections(db).stream().filter((collectionName) -> (!RequestContext.isReservedResourceCollection(collectionName))).forEach(
(collectionName) ->
{
try
{
addCollectionMetadata(dbName, collectionName);
}
catch (Throwable t)
{
logger.error("error fixing metadata of collection {}/{}", dbName, collectionName, t);
}
}
);
});
}
}
|
package net.sf.jabref.gui.search;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.GUIGlobals;
import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.gui.autocompleter.AutoCompleteSupport;
import net.sf.jabref.gui.help.HelpAction;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.logic.autocompleter.AutoCompleter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.search.SearchQuery;
import net.sf.jabref.logic.search.rules.util.SentenceAnalyzer;
import net.sf.jabref.model.entry.BibtexEntry;
import org.apache.commons.logging.LogFactory;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* The search bar at the top of the screen allowing the user to search his database.
*/
public class SearchBar extends JPanel {
private SearchQuery getSearchQuery() {
return new SearchQuery(this.searchField.getText(), this.caseSensitive.isSelected(), this.regularExp.isSelected());
}
public void updateResults(int matched, String description) {
if (matched == 0) {
this.currentResults.setText(Localization.lang("No results found."));
this.searchField.setBackground(Color.RED);
} else {
this.currentResults.setText(Localization.lang("Found %0 results.", String.valueOf(matched)));
this.searchField.setBackground(Color.GREEN);
}
this.searchField.setToolTipText("<html>" + description + "</html>");
}
private final BasePanel basePanel;
private JSearchTextField searchField;
private JRadioButtonMenuItem modeFloat, modeLiveFilter;
private JMenu settings;
private JCheckBoxMenuItem highlightWords, autoComplete;
private final JCheckBox caseSensitive;
private final JCheckBox regularExp;
private final JButton openCurrentResultsInDialog;
private final JLabel currentResults = new JLabel("");
AutoCompleteSupport<String> autoCompleteSupport;
private final SearchWorker worker;
private final ArrayList<SearchTextListener> listeners = new ArrayList<>();
/**
* Initializes the search bar.
*
* @param frame the main window
*/
public SearchBar(BasePanel basePanel) {
super();
this.basePanel = basePanel;
worker = new SearchWorker(basePanel);
currentResults.setFont(currentResults.getFont().deriveFont(Font.BOLD));
caseSensitive = new JCheckBox(Localization.lang("Match case"), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_CASE_SENSITIVE));
caseSensitive.addItemListener(ae -> performSearch());
caseSensitive.addItemListener(ae -> updatePrefs());
regularExp = new JCheckBox(Localization.lang("Regex"), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_REG_EXP));
regularExp.addItemListener(ae -> performSearch());
regularExp.addItemListener(ae -> updatePrefs());
openCurrentResultsInDialog = new JButton(IconTheme.JabRefIcon.OPEN_IN_NEW_WINDOW.getSmallIcon());
openCurrentResultsInDialog.setToolTipText(Localization.lang("Show search results in a window"));
openCurrentResultsInDialog.addActionListener(ae -> {
SearchResultsDialog searchDialog = new SearchResultsDialog(basePanel.frame(), Localization.lang("Search results in database %0 for %1",
basePanel.getFile().getName(), this.getSearchQuery().toString()));
for (BibtexEntry entry : basePanel.getDatabase().getEntries()) {
if (entry.isSearchHit()) {
searchDialog.addEntry(entry, basePanel);
}
}
searchDialog.selectFirstEntry();
searchDialog.setVisible(true);
});
// Init controls
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel searchIcon = new JLabel(IconTheme.JabRefIcon.SEARCH.getSmallIcon());
this.add(searchIcon);
initSearchField();
this.add(searchField);
JButton button = new JButton(Localization.lang("Settings"));
JPopupMenu settingsMenu = createSettingsMenu();
button.addActionListener(l -> {
settingsMenu.show(button, 0, button.getHeight());
});
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.add(regularExp);
toolBar.add(caseSensitive);
toolBar.addSeparator();
toolBar.add(button);
toolBar.addSeparator();
toolBar.add(openCurrentResultsInDialog);
JButton globalSearch = new JButton(Localization.lang("Search in all open databases"));
globalSearch.addActionListener(l -> {
AbstractWorker worker = new GlobalSearchWorker(basePanel.frame(), getSearchQuery());
worker.run();
worker.update();
});
toolBar.add(globalSearch);
toolBar.addSeparator();
toolBar.add(new HelpAction(basePanel.frame().helpDiag, GUIGlobals.searchHelp, Localization.lang("Help")));
this.add(toolBar);
this.add(currentResults);
paintBackgroundWhite(this);
}
private void paintBackgroundWhite(Container container) {
container.setBackground(Color.WHITE);
for (Component component : container.getComponents()) {
component.setBackground(Color.WHITE);
if(component instanceof Container) {
paintBackgroundWhite((Container) component);
}
}
}
private JPopupMenu createSettingsMenu() {
// Populate popup menu and add it to search button
JPopupMenu menu = new JPopupMenu("Settings");
initSearchModeMenu();
menu.add(getSearchModeMenuItem(SearchMode.FILTER));
menu.add(getSearchModeMenuItem(SearchMode.FLOAT));
menu.addSeparator();
highlightWords = new JCheckBoxMenuItem(Localization.lang("Highlight Words"), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_HIGHLIGHT_WORDS));
highlightWords.addActionListener(ae -> updatePrefs());
autoComplete = new JCheckBoxMenuItem(Localization.lang("Autocomplete names"), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_AUTO_COMPLETE));
autoComplete.addActionListener(ae -> updatePrefs());
menu.add(highlightWords);
menu.add(autoComplete);
return menu;
}
/**
* Initializes the popup menu items controlling the search mode
*/
private void initSearchModeMenu() {
ButtonGroup searchMethod = new ButtonGroup();
for (SearchMode mode : SearchMode.values()) {
// Create menu items
switch (mode) {
case FLOAT:
modeFloat = new JRadioButtonMenuItem(mode.getDisplayName(), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_MODE_FLOAT));
break;
case FILTER:
modeLiveFilter = new JRadioButtonMenuItem(mode.getDisplayName(), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_MODE_LIVE_FILTER));
break;
}
// Set tooltips on menu items
getSearchModeMenuItem(mode).setToolTipText(mode.getToolTipText());
// Add menu item to group
searchMethod.add(getSearchModeMenuItem(mode));
// Listen to selection changed events
getSearchModeMenuItem(mode).addChangeListener(e -> performSearch());
}
}
/**
* Initializes the search text field
*/
private void initSearchField() {
searchField = new JSearchTextField();
searchField.setTextWhenNotFocused(Localization.lang("Search..."));
searchField.setColumns(30);
// Add autocompleter
autoCompleteSupport = new AutoCompleteSupport<>(searchField);
autoCompleteSupport.install();
// Add the global focus listener, so a menu item can see if this field was focused when an action was called.
searchField.addFocusListener(Globals.focusListener);
// Search if user press enter
searchField.addActionListener(e -> performSearch());
// Subscribe to changes to the text in the search field in order to "live search"
// TODO: With this implementation "onSearchTextChanged" gets called two times when setText() is invoked (once for removing the initial string and then again for inserting the new one). This happens for example when an autocompletion is accepted.
searchField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
LogFactory.getLog(SearchBar.class).debug("Text insert: " + e.toString());
onSearchTextChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
LogFactory.getLog(SearchBar.class).debug("Text remove: " + e.toString());
onSearchTextChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
LogFactory.getLog(SearchBar.class).debug("Text updated: " + e.toString());
}
});
}
/**
* Returns the item in the popup menu of the search button corresponding to the given search mode
*/
private JRadioButtonMenuItem getSearchModeMenuItem(SearchMode mode) {
switch (mode) {
case FLOAT:
return modeFloat;
case FILTER:
return modeLiveFilter;
}
return null;
}
/**
* Switches to another search mode.
*
* @param mode the new search mode
*/
private void setSearchMode(SearchMode mode) {
getSearchModeMenuItem(mode).setSelected(true);
}
/**
* Returns the currently activated search mode.
*
* @return current search mode
*/
private SearchMode getSearchMode() {
if (modeFloat.isSelected()) {
return SearchMode.FLOAT;
}
if (modeLiveFilter.isSelected()) {
return SearchMode.FILTER;
}
return SearchMode.FILTER;
}
/**
* Adds a SearchTextListener to the search bar. The added listener is immediately informed about the current search.
* Subscribers will be notified about searches.
*
* @param l SearchTextListener to be added
*/
public void addSearchListener(SearchTextListener l) {
if (listeners.contains(l)) {
return;
} else {
listeners.add(l);
}
// fire event for the new subscriber
l.searchText(getSearchwords(searchField.getText()));
}
/**
* Remove a SearchTextListener
*
* @param l SearchTextListener to be removed
*/
public void removeSearchListener(SearchTextListener l) {
listeners.remove(l);
}
/**
* Parses the search query for valid words and returns a list these words. For example, "The great Vikinger" will
* give ["The","great","Vikinger"]
*
* @param searchText the search query
* @return list of words found in the search query
*/
private List<String> getSearchwords(String searchText) {
return (new SentenceAnalyzer(searchText)).getWords();
}
/**
* Fires an event if a search was started (or cleared)
*
* @param searchText the search query
*/
private void fireSearchlistenerEvent(String searchText) {
// Parse the search string to words
List<String> words;
if ((searchText == null) || (searchText.isEmpty())) {
words = null;
} else {
words = getSearchwords(searchText);
}
// Fire an event for every listener
for (SearchTextListener s : listeners) {
s.searchText(words);
}
}
/**
* Save current settings.
*/
public void updatePrefs() {
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_MODE_FLOAT, modeFloat.isSelected());
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_MODE_LIVE_FILTER, modeLiveFilter.isSelected());
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_CASE_SENSITIVE, caseSensitive.isSelected());
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_REG_EXP, regularExp.isSelected());
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_HIGHLIGHT_WORDS, highlightWords.isSelected());
Globals.prefs.putBoolean(JabRefPreferences.SEARCH_AUTO_COMPLETE, autoComplete.isSelected());
}
/**
* Focuses the search field if it is not focused. Otherwise, cycles to the next search type.
*/
public void focus() {
if (searchField.hasFocus()) {
switch (getSearchMode()) {
case FLOAT:
setSearchMode(SearchMode.FILTER);
break;
case FILTER:
setSearchMode(SearchMode.FLOAT);
break;
}
} else {
searchField.requestFocus();
}
}
/**
* Reacts to the change of the search text. A change in the search query results in an immediate search in
* incremental or live filter search mode.
*/
private void onSearchTextChanged() {
if ((getSearchMode() == SearchMode.FILTER) || (getSearchMode() == SearchMode.FLOAT)) {
// wait until the text is changed
SwingUtilities.invokeLater(this::performSearch);
}
}
/**
* Clears (asynchronously) the current search. This includes resetting the search text.
*/
private void clearSearch() {
SwingUtilities.invokeLater(() -> {
worker.restart();
searchField.setText("");
searchField.setBackground(Color.WHITE);
fireSearchlistenerEvent(null);
this.currentResults.setText("");
});
}
/**
* Performs a new search based on the current search query.
*/
private void performSearch() {
String searchText = searchField.getText();
// Notify others about the search
fireSearchlistenerEvent(searchText);
// An empty search field should cause the search to be cleared.
if (searchText.isEmpty()) {
clearSearch();
return;
}
if (basePanel == null) {
return;
}
SearchQuery searchQuery = getSearchQuery();
if (!searchQuery.isValidQuery()) {
basePanel.output(Localization.lang("Search failed: illegal search expression"));
clearSearch();
return;
}
worker.initSearch(searchQuery, getSearchMode());
worker.getWorker().run();
worker.getCallBack().update();
}
/**
* Sets the autocompleter used in the search field.
*
* @param searchCompleter the autocompleter
*/
public void setAutoCompleter(AutoCompleter<String> searchCompleter) {
this.autoCompleteSupport.setAutoCompleter(searchCompleter);
}
}
|
package oasis.web.authz;
import java.security.interfaces.RSAPublicKey;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.google.common.io.BaseEncoding;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import oasis.auth.AuthModule;
@Path("/a/keys")
@Api(value = "/a/keys", description = "Keys API")
public class KeysEndpoint {
private static final BaseEncoding BASE64_ENCODING = BaseEncoding.base64Url().omitPadding();
public static final String JSONWEBKEY_PK_ID = "oasis.openid-connect.public-key";
@Inject AuthModule.Settings settings;
@GET
@Produces("application/jwk-set+json")
@ApiOperation(
value = "Retrieve the public key used for OpenID Connect.",
notes = "Returns a JSON Web Key Set containing the public key. See the <a href='http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18'>RFC</a> for more informations about JWKS."
)
public Response get() {
RSAPublicKey publicKey = (RSAPublicKey) settings.keyPair.getPublic();
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet();
RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey();
rsaJsonWebKey.modulus = BASE64_ENCODING.encode(publicKey.getModulus().toByteArray());
rsaJsonWebKey.exponent = BASE64_ENCODING.encode(publicKey.getPublicExponent().toByteArray());
rsaJsonWebKey.keyId = JSONWEBKEY_PK_ID;
jsonWebKeySet.rsaJsonWebKeys = new RsaJsonWebKey[]{rsaJsonWebKey};
return Response.ok().entity(jsonWebKeySet).build();
}
}
|
package org.kumoricon.presenter.order;
import com.vaadin.ui.Notification;
import org.kumoricon.KumoRegUI;
import org.kumoricon.model.attendee.Attendee;
import org.kumoricon.model.attendee.AttendeeRepository;
import org.kumoricon.model.badge.BadgeRepository;
import org.kumoricon.model.order.Order;
import org.kumoricon.model.order.OrderRepository;
import org.kumoricon.view.attendee.AttendeeDetailForm;
import org.kumoricon.view.order.AttendeeWindow;
import org.kumoricon.view.order.OrderView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import java.math.BigDecimal;
@Controller
@Scope("request")
public class OrderPresenter {
@Autowired
private OrderRepository orderRepository;
@Autowired
private BadgeRepository badgeRepository;
@Autowired
private AttendeeRepository attendeeRepository;
private OrderView view;
public OrderPresenter() {
}
public void createNewOrder() {
Order order = new Order();
order.setOrderId(order.generateOrderId());
orderRepository.save(order);
KumoRegUI.getCurrent().getNavigator().navigateTo(view.VIEW_NAME + "/" + order.getId());
}
public void showOrder(int id) {
Order order = orderRepository.findOne(id);
if (order != null) {
view.afterSuccessfulFetch(order);
} else {
Notification.show("Error: order " + id + " not found.");
}
}
public void cancelOrder() {
// Todo: Remove from database if order hasn't been saved yet? Make sure to not
// delete orders that are already paid for. Not sure if this is a good feature
// or not
KumoRegUI.getCurrent().getNavigator().navigateTo("");
}
public OrderView getView() { return view; }
public void setView(OrderView view) { this.view = view; }
public void addNewAttendee() {
Attendee newAttendee = new Attendee();
newAttendee.setOrder(view.getOrder());
AttendeeWindow attendeeWindow = new AttendeeWindow(this);
KumoRegUI.getCurrent().addWindow(attendeeWindow);
AttendeeDetailForm form = attendeeWindow.getDetailForm();
form.setAvailableBadges(badgeRepository.findAll());
form.show(newAttendee);
}
public void addAttendeeToOrder(Attendee attendee) {
Order order = view.getOrder();
order.addAttendee(attendee);
order.setTotalAmount(getOrderTotal(order));
orderRepository.save(order);
view.afterSuccessfulFetch(order);
}
private static BigDecimal getOrderTotal(Order order) {
// Just get the total for all the attendees instead of keeping a running total
// and adding the latest amount to it. Keeping a running total made testing a pain
// if a value somehow got corrupt along the way
BigDecimal total = BigDecimal.ZERO;
for (Attendee a : order.getAttendeeList()) {
total = total.add(a.getPaidAmount());
}
return total;
}
public void removeAttendeeFromOrder(Attendee attendee) {
if (attendee != null && !attendee.isCheckedIn()) {
String name = attendee.getName();
Order order = view.getOrder();
order.removeAttendee(attendee);
attendee.setOrder(null);
order.setTotalAmount(getOrderTotal(order));
orderRepository.save(order);
attendeeRepository.delete(attendee);
Notification.show(name + " deleted");
view.afterSuccessfulFetch(order);
}
}
public void takeMoney() {
Order currentOrder = view.getOrder();
if (currentOrder.getAttendeeList().size() == 0) {
Notification.show("Error: No attendees in order");
return;
}
if (currentOrder.getPaymentType() == null) {
Notification.show("Error: Payment type not selected");
return;
}
// Print badges here
currentOrder.paymentComplete();
orderRepository.save(currentOrder);
KumoRegUI.getCurrent().getNavigator().navigateTo("/");
Notification.show("Order complete");
}
public void selectAttendee(Attendee attendee) {
AttendeeWindow attendeeWindow = new AttendeeWindow(this);
KumoRegUI.getCurrent().addWindow(attendeeWindow);
AttendeeDetailForm form = attendeeWindow.getDetailForm();
form.setAvailableBadges(badgeRepository.findAll());
form.show(attendee);
}
}
|
package org.arachb.arachadmin;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.arachb.owlbuilder.Owlbuilder;
import org.arachb.owlbuilder.lib.Individual;
public class PElementBean implements CachingBean,BeanBase {
final static int DBID = 1;
final static int DBTYPE = 2;
final static int DBPARTICIPANT = 3;
final static int DBTERM = 4;
final static int DBINDIVIDUAL = 5;
private static final Map<Integer, PElementBean> cache = new HashMap<>();
private static Logger log = Logger.getLogger(PElementBean.class);
private int id;
private int eletype;
private int participant;
private Integer termId = null;
private Integer individualId = null;
private final Map<Integer,Integer> parents = new HashMap<Integer,Integer>();
private final Map<Integer,Integer> children = new HashMap<Integer,Integer>();
@Override
public void fill(AbstractResults record) throws SQLException {
id = record.getInt(DBID);
eletype = record.getInt(DBTYPE);
participant = record.getInt(DBPARTICIPANT);
termId = record.getInt(DBTERM);
individualId = record.getInt(DBINDIVIDUAL);
}
@Override
public int getId() {
return id;
}
public int getType(){
return eletype;
}
public int getParticipant(){
return participant;
}
public Integer getTermId(){
return termId;
}
public Integer getIndividualId(){
return individualId;
}
/* package visibility for next two is deliberate */
void addParent(Integer parent, Integer property){
parents.put(parent, property);
}
void addChild(Integer child, Integer property){
children.put(child, property);
}
public Set<Integer> getParents(){
return parents.keySet();
}
public Set<Integer> getChildren(){
return children.keySet();
}
public Integer getParentProperty(Integer parent){
if (parents.containsKey(parent)){
return parents.get(parent);
}
throw new RuntimeException(String.format("PElement %d has no parent %d",getId(),parent));
}
public Integer getChildProperty(Integer child){
if (children.containsKey(child)){
return children.get(child);
}
throw new RuntimeException(String.format("PElement %d has no child %d",getId(),child));
}
/**
* may not be needed, but if we ever need to reopen a database
*/
static void flushCache(){
cache.clear();
}
public static boolean isCached(int id){
return cache.containsKey(id);
}
public static PElementBean getCached(int id){
assert cache.containsKey(id) : String.format("no cache entry for %d",id);
return cache.get(id);
}
@Override
public void cache(){
if (isCached(getId())){
log.warn(String.format("Tried multiple caching of %s with id %d",
getClass().getSimpleName(),
getId()));
}
cache.put(getId(), this);
}
@Override
public void updatecache(){
if (!this.equals(cache.get(getId()))){
log.warn(String.format("Forcing update of cached bean %s with id %d",
getClass().getSimpleName(),
getId()));
cache.put(getId(), this);
}
}
}
|
package org.getchunky.chunkyciv;
import org.getchunky.chunky.ChunkyManager;
import org.getchunky.chunky.object.ChunkyChunk;
import org.getchunky.chunky.object.ChunkyObject;
import org.getchunky.chunky.object.ChunkyPlayer;
import org.getchunky.chunky.permission.PermissionFlag;
import org.getchunky.chunkyciv.object.ChunkyCitizen;
import org.getchunky.chunkyciv.object.ChunkyCivChunk;
import org.getchunky.chunkyciv.object.ChunkyNation;
import org.getchunky.chunkyciv.util.Logging;
import java.util.HashMap;
import java.util.HashSet;
/**
* @author dumptruckman
*/
public class CivManager {
public static PermissionFlag CIV_CLAIM = new PermissionFlag("Civ Claim", "cc");
public static PermissionFlag CIV_UNCLAIM = new PermissionFlag("Civ Unclaim", "cu");
private static HashMap<ChunkyPlayer, ChunkyCitizen> citizensMap = new HashMap<ChunkyPlayer, ChunkyCitizen>();
private static HashMap<String, ChunkyNation> nationsMap = new HashMap<String, ChunkyNation>();
private static HashMap<ChunkyChunk, ChunkyCivChunk> chunksMap = new HashMap<ChunkyChunk, ChunkyCivChunk>();
public static ChunkyCitizen getCitizen(ChunkyPlayer player) {
ChunkyCitizen cit = citizensMap.get(player);
if (cit == null) {
cit = new ChunkyCitizen(player);
citizensMap.put(player, cit);
}
return cit;
}
public static ChunkyNation getNation(String name) {
ChunkyNation nation = nationsMap.get(name);
Logging.debug("Name: " + name + " in " + nationsMap);
if (nation == null) {
HashMap<String, ChunkyObject> objectsOfType = ChunkyManager.getObjectsOfType(ChunkyNation.class.getName());
if (objectsOfType == null) return null;
for (ChunkyObject object : ChunkyManager.getObjectsOfType(ChunkyNation.class.getName()).values()) {
if (object.getName().equalsIgnoreCase(name)) {
nation = (ChunkyNation)object;
nationsMap.put(nation.getName(), nation);
break;
}
}
}
Logging.debug("Got nation: " + nation);
return nation;
}
public static ChunkyNation createNation(String name) {
ChunkyNation nation = getNation(name);
if (nation != null)
return null;
nation = new ChunkyNation();
nation.setId(ChunkyManager.getUniqueId());
nation.setName(name);
Logging.debug("Created a new nation: " + name);
return nation;
}
public static ChunkyCivChunk getCivChunk(ChunkyChunk chunk) {
if (chunk == null) return null;
ChunkyCivChunk civChunk = chunksMap.get(chunk);
if (civChunk == null) {
civChunk = new ChunkyCivChunk(chunk);
chunksMap.put(chunk, civChunk);
}
return civChunk;
}
public static boolean checkNationEligibility(ChunkyCitizen citizen) {
HashSet<ChunkyObject> objects = citizen.getChunkyPlayer().getOwnables().get(ChunkyChunk.class.getName());
if (objects == null) return false;
for (ChunkyObject object : objects) {
ChunkyCivChunk civChunk = CivManager.getCivChunk((ChunkyChunk)object);
if (civChunk.hasNation()) return true;
}
return false;
}
}
|
package org.jcodec.containers.mps;
import static org.jcodec.common.io.NIOUtils.getRel;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import org.jcodec.common.Assert;
import org.jcodec.common.IntArrayList;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.containers.mps.psi.PATSection;
import org.jcodec.containers.mps.psi.PMTSection;
import org.jcodec.containers.mps.psi.PMTSection.PMTStream;
import org.jcodec.containers.mps.psi.PSISection;
public class MTSUtils {
public final static class StreamType {
public final static StreamType RESERVED = new StreamType(0x0, false, false);
public final static StreamType VIDEO_MPEG1 = new StreamType(0x01, true, false);
public final static StreamType VIDEO_MPEG2 = new StreamType(0x02, true, false);
public final static StreamType AUDIO_MPEG1 = new StreamType(0x03, false, true);
public final static StreamType AUDIO_MPEG2 = new StreamType(0x04, false, true);
public final static StreamType PRIVATE_SECTION = new StreamType(0x05, false, false);
public final static StreamType PRIVATE_DATA = new StreamType(0x06, false, false);
public final static StreamType MHEG = new StreamType(0x7, false, false);
public final static StreamType DSM_CC = new StreamType(0x8, false, false);
public final static StreamType ATM_SYNC = new StreamType(0x9, false, false);
public final static StreamType DSM_CC_A = new StreamType(0xa, false, false);
public final static StreamType DSM_CC_B = new StreamType(0xb, false, false);
public final static StreamType DSM_CC_C = new StreamType(0xc, false, false);
public final static StreamType DSM_CC_D = new StreamType(0xd, false, false);
public final static StreamType MPEG_AUX = new StreamType(0xe, false, false);
public final static StreamType AUDIO_AAC_ADTS = new StreamType(0x0f, false, true);
public final static StreamType VIDEO_MPEG4 = new StreamType(0x10, true, false);
public final static StreamType AUDIO_AAC_LATM = new StreamType(0x11, false, true);
public final static StreamType FLEXMUX_PES = new StreamType(0x12, false, false);
public final static StreamType FLEXMUX_SEC = new StreamType(0x13, false, false);
public final static StreamType DSM_CC_SDP = new StreamType(0x14, false, false);
public final static StreamType META_PES = new StreamType(0x15, false, false);
public final static StreamType META_SEC = new StreamType(0x16, false, false);
public final static StreamType DSM_CC_DATA_CAROUSEL = new StreamType(0x17, false, false);
public final static StreamType DSM_CC_OBJ_CAROUSEL = new StreamType(0x18, false, false);
public final static StreamType DSM_CC_SDP1 = new StreamType(0x19, false, false);
public final static StreamType IPMP = new StreamType(0x1a, false, false);
public final static StreamType VIDEO_H264 = new StreamType(0x1b, true, false);
public final static StreamType AUDIO_AAC_RAW = new StreamType(0x1c, false, true);
public final static StreamType SUBS = new StreamType(0x1d, false, false);
public final static StreamType AUX_3D = new StreamType(0x1e, false, false);
public final static StreamType VIDEO_AVC_SVC = new StreamType(0x1f, true, false);
public final static StreamType VIDEO_AVC_MVC = new StreamType(0x20, true, false);
public final static StreamType VIDEO_J2K = new StreamType(0x21, true, false);
public final static StreamType VIDEO_MPEG2_3D = new StreamType(0x22, true, false);
public final static StreamType VIDEO_H264_3D = new StreamType(0x23, true, false);
public final static StreamType VIDEO_CAVS = new StreamType(0x42, false, true);
public final static StreamType IPMP_STREAM = new StreamType(0x7f, false, false);
public final static StreamType AUDIO_AC3 = new StreamType(0x81, false, true);
public final static StreamType AUDIO_DTS = new StreamType(0x8a, false, true);
private int tag;
private boolean video;
private boolean audio;
private final static List<StreamType> _values =new ArrayList<StreamType>();
private StreamType(int tag, boolean video, boolean audio) {
this.tag = tag;
this.video = video;
this.audio = audio;
_values.add(this);
}
public static StreamType[] values() {
return _values.toArray(new StreamType[0]);
}
public static StreamType fromTag(int streamTypeTag) {
StreamType[] values = values();
for (int i = 0; i < values.length; i++) {
StreamType streamType = values[i];
if (streamType.tag == streamTypeTag)
return streamType;
}
return null;
}
public int getTag() {
return tag;
}
public boolean isVideo() {
return video;
}
public boolean isAudio() {
return audio;
}
};
/**
* Parses PAT ( Program Association Table )
*
* @param data
* @deprecated Use org.jcodec.containers.mps.psi.PAT.parse method instead,
* this method will not work correctly for streams with multiple
* programs
* @return Pid of the first PMT found in the PAT
*/
@Deprecated
public static int parsePAT(ByteBuffer data) {
PATSection pat = PATSection.parsePAT(data);
if (pat.getPrograms().size() > 0)
return pat.getPrograms().values()[0];
else
return -1;
}
@Deprecated
public static PMTSection parsePMT(ByteBuffer data) {
return PMTSection.parsePMT(data);
}
@Deprecated
public static PSISection parseSection(ByteBuffer data) {
return PSISection.parsePSI(data);
}
private static void parseEsInfo(ByteBuffer read) {
}
public static PMTStream[] getProgramGuids(File src) throws IOException {
SeekableByteChannel ch = null;
try {
ch = NIOUtils.readableChannel(src);
return getProgramGuidsFromChannel(ch);
} finally {
NIOUtils.closeQuietly(ch);
}
}
public static PMTStream[] getProgramGuidsFromChannel(SeekableByteChannel _in) throws IOException {
PMTExtractor ex = new PMTExtractor();
ex.readTsFile(_in);
PMTSection pmt = ex.getPmt();
return pmt.getStreams();
}
private static class PMTExtractor extends TSReader {
public PMTExtractor() {
super(false);
}
private int pmtGuid = -1;
private PMTSection pmt;
@Override
public boolean onPkt(int guid, boolean payloadStart, ByteBuffer tsBuf, long filePos, boolean sectionSyntax,
ByteBuffer fullPkt) {
if (guid == 0) {
pmtGuid = parsePAT(tsBuf);
} else if (pmtGuid != -1 && guid == pmtGuid) {
pmt = parsePMT(tsBuf);
return false;
}
return true;
}
public PMTSection getPmt() {
return pmt;
}
};
public static abstract class TSReader {
private static final int TS_SYNC_MARKER = 0x47;
private static final int TS_PKT_SIZE = 188;
// Buffer must have an integral number of MPEG TS packets
public static final int BUFFER_SIZE = TS_PKT_SIZE << 9;
private boolean flush;
public TSReader(boolean flush) {
this.flush = flush;
}
public void readTsFile(SeekableByteChannel ch) throws IOException {
ch.setPosition(0);
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
for (long pos = ch.position(); ch.read(buf) >= TS_PKT_SIZE; pos = ch.position()) {
long posRem = pos;
buf.flip();
while (buf.remaining() >= TS_PKT_SIZE) {
ByteBuffer tsBuf = NIOUtils.read(buf, TS_PKT_SIZE);
ByteBuffer fullPkt = tsBuf.duplicate();
pos += TS_PKT_SIZE;
Assert.assertEquals(TS_SYNC_MARKER, tsBuf.get() & 0xff);
int guidFlags = ((tsBuf.get() & 0xff) << 8) | (tsBuf.get() & 0xff);
int guid = (int) guidFlags & 0x1fff;
int payloadStart = (guidFlags >> 14) & 0x1;
int b0 = tsBuf.get() & 0xff;
int counter = b0 & 0xf;
if ((b0 & 0x20) != 0) {
NIOUtils.skip(tsBuf, tsBuf.get() & 0xff);
}
boolean sectionSyntax = payloadStart == 1 && (getRel(tsBuf, getRel(tsBuf, 0) + 2) & 0x80) == 0x80;
if (sectionSyntax) {
// Adaptation field
NIOUtils.skip(tsBuf, tsBuf.get() & 0xff);
}
if (!onPkt(guid, payloadStart == 1, tsBuf, pos - tsBuf.remaining(), sectionSyntax, fullPkt))
return;
}
if (flush) {
buf.flip();
ch.setPosition(posRem);
ch.write(buf);
}
buf.clear();
}
}
protected boolean onPkt(int guid, boolean payloadStart, ByteBuffer tsBuf, long filePos, boolean sectionSyntax,
ByteBuffer fullPkt) {
// DO NOTHING
return true;
}
}
public static int getVideoPid(File src) throws IOException {
for (PMTStream stream : MTSUtils.getProgramGuids(src)) {
if (stream.getStreamType().isVideo())
return stream.getPid();
}
throw new RuntimeException("No video stream");
}
public static int getAudioPid(File src) throws IOException {
for (PMTStream stream : MTSUtils.getProgramGuids(src)) {
if (stream.getStreamType().isAudio())
return stream.getPid();
}
throw new RuntimeException("No audio stream");
}
public static int[] getMediaPidsFromChannel(SeekableByteChannel src) throws IOException {
return filterMediaPids(MTSUtils.getProgramGuidsFromChannel(src));
}
public static int[] getMediaPids(File src) throws IOException {
return filterMediaPids(MTSUtils.getProgramGuids(src));
}
private static int[] filterMediaPids(PMTStream[] programs) {
IntArrayList result = IntArrayList.createIntArrayList();
for (PMTStream stream : programs) {
if (stream.getStreamType().isVideo() || stream.getStreamType().isAudio())
result.add(stream.getPid());
}
return result.toArray();
}
}
|
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.BreakIterator;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ParamChecks;
/**
* Some utility methods for working with text.
*/
public class TextUtilities {
private static boolean drawStringsWithFontAttributes = false;
/**
* A flag that controls whether or not the rotated string workaround is
* used.
*/
private static boolean useDrawRotatedStringWorkaround = false;
/**
* A flag that controls whether the FontMetrics.getStringBounds() method
* is used or a workaround is applied.
*/
private static boolean useFontMetricsGetStringBounds = false;
/**
* Private constructor prevents object creation.
*/
private TextUtilities() {
}
/**
* Creates a {@link TextBlock} from a {@code String}. Line breaks
* are added where the {@code String} contains '\n' characters.
*
* @param text the text ({@code null} not permitted).
* @param font the font.
* @param paint the paint.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint) {
ParamChecks.nullNotPermitted(text, "text");
TextBlock result = new TextBlock();
String input = text;
boolean moreInputToProcess = (text.length() > 0);
int start = 0;
while (moreInputToProcess) {
int index = input.indexOf("\n");
if (index > start) {
String line = input.substring(start, index);
if (index < input.length() - 1) {
result.addLine(line, font, paint);
input = input.substring(index + 1);
} else {
moreInputToProcess = false;
}
} else if (index == start) {
if (index < input.length() - 1) {
input = input.substring(index + 1);
} else {
moreInputToProcess = false;
}
} else {
result.addLine(input, font, paint);
moreInputToProcess = false;
}
}
return result;
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the {@code maxWidth} value is respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font, Paint paint,
float maxWidth, TextMeasurer measurer) {
return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,
measurer);
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the {@code maxWidth} value is respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param maxLines the maximum number of lines.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {
TextBlock result = new TextBlock();
BreakIterator iterator = BreakIterator.getLineInstance();
iterator.setText(text);
int current = 0;
int lines = 0;
int length = text.length();
while (current < length && lines < maxLines) {
int next = nextLineBreak(text, current, maxWidth, iterator,
measurer);
if (next == BreakIterator.DONE) {
result.addLine(text.substring(current), font, paint);
return result;
} else if (next == current) {
next++; // we must take one more character or we'll loop forever
}
result.addLine(text.substring(current, next), font, paint);
lines++;
current = next;
while (current < text.length()&& text.charAt(current) == '\n') {
current++;
}
}
if (current < length) {
TextLine lastLine = result.getLastLine();
TextFragment lastFragment = lastLine.getLastTextFragment();
String oldStr = lastFragment.getText();
String newStr = "...";
if (oldStr.length() > 3) {
newStr = oldStr.substring(0, oldStr.length() - 3) + "...";
}
lastLine.removeFragment(lastFragment);
TextFragment newFragment = new TextFragment(newStr,
lastFragment.getFont(), lastFragment.getPaint());
lastLine.addFragment(newFragment);
}
return result;
}
/**
* Returns the character index of the next line break. If the next
* character is wider than {@code width} this method will return
* {@code start} - the caller should check for this case.
*
* @param text the text ({@code null} not permitted).
* @param start the start index.
* @param width the target display width.
* @param iterator the word break iterator.
* @param measurer the text measurer.
*
* @return The index of the next line break.
*/
private static int nextLineBreak(String text, int start, float width,
BreakIterator iterator, TextMeasurer measurer) {
// this method is (loosely) based on code in JFreeReport's
// TextParagraph class
int current = start;
int end;
float x = 0.0f;
boolean firstWord = true;
int newline = text.indexOf('\n', start);
if (newline < 0) {
newline = Integer.MAX_VALUE;
}
while (((end = iterator.following(current)) != BreakIterator.DONE)) {
x += measurer.getStringWidth(text, current, end);
if (x > width) {
if (firstWord) {
while (measurer.getStringWidth(text, start, end) > width) {
end
if (end <= start) {
return end;
}
}
return end;
}
else {
end = iterator.previous();
return end;
}
}
else {
if (end > newline) {
return newline;
}
}
// we found at least one word that fits ...
firstWord = false;
current = end;
}
return BreakIterator.DONE;
}
/**
* Returns the bounds for the specified text.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics context (not {@code null}).
* @param fm the font metrics (not {@code null}).
*
* @return The text bounds ({@code null} if the {@code text} argument is
* {@code null}).
*/
public static Rectangle2D getTextBounds(String text, Graphics2D g2,
FontMetrics fm) {
Rectangle2D bounds;
if (TextUtilities.useFontMetricsGetStringBounds) { // default FALSE
bounds = fm.getStringBounds(text, g2);
// getStringBounds() can return incorrect height for some Unicode
// characters...see bug parade 6183356, let's replace it with
// something correct
LineMetrics lm = fm.getFont().getLineMetrics(text,
g2.getFontRenderContext());
bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
lm.getHeight());
} else {
double width = fm.stringWidth(text);
double height = fm.getHeight();
bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
height);
}
return bounds;
}
/**
* Returns the bounds for the attributed string.
*
* @param text the attributed string ({@code null} not permitted).
* @param g2 the graphics target ({@code null} not permitted).
*
* @return The bounds (never {@code null}).
*/
public static Rectangle2D getTextBounds(AttributedString text,
Graphics2D g2) {
TextLayout tl = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
return tl.getBounds();
}
/**
* Draws a string such that the specified anchor point is aligned to the
* given (x, y) location.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x coordinate (Java 2D).
* @param y the y coordinate (Java 2D).
* @param anchor the anchor location.
*
* @return The text bounds (adjusted for the text position).
*/
public static Rectangle2D drawAlignedString(String text, Graphics2D g2,
float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
if (!drawStringsWithFontAttributes) {
g2.drawString(text, x + adjust[0], y + adjust[1]);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]);
}
return textBounds;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not {@code null}).
* @param text the text.
* @param anchor the anchor point.
* @param textBounds the text bounds (if not {@code null}, this
* object will be updated by this method to match the
* string bounds).
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor, Rectangle2D textBounds) {
float[] result = new float[3];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
} else if (anchor.isHorizontalRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
} else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
} else if (anchor.isHalfHeight()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
} else if (anchor.isBaseline()) {
yAdj = 0.0f;
} else if (anchor.isBottom()) {
yAdj = -descent - leading;
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param angle the angle of the (clockwise) rotation (in radians).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(String text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
ParamChecks.nullNotPermitted(text, "text");
if (angle == 0.0) {
drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT);
return;
}
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
TextLayout tl = new TextLayout(text, g2.getFont(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
} else {
if (!drawStringsWithFontAttributes) {
g2.drawString(text, textX, textY);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), textX, textY);
}
}
g2.setTransform(saved);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle.
* @param rotationX the x-coordinate for the rotation anchor point.
* @param rotationY the y-coordinate for the rotation anchor point.
*/
public static void drawRotatedString(String text, Graphics2D g2, float x,
float y, TextAnchor textAnchor, double angle,
float rotationX, float rotationY) {
ParamChecks.nullNotPermitted(text, "text");
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,
rotationX, rotationY);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics device.
* @param x the x coordinate for the anchor point.
* @param y the y coordinate for the anchor point.
* @param textAnchor the text anchor.
* @param angle the angle.
* @param rotationAnchor the rotation anchor.
*
* @return The bounds (possibly {@code null}).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor, double angle,
TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return null;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
Shape result = calculateRotatedStringBounds(text, g2,
x + textAdj[0], y + textAdj[1], angle,
x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* ({@code BASELINE_LEFT}).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point ({@code null} not permitted).
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalLeft()) {
xAdj = 0.0f;
} else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
} else if (anchor.isHorizontalRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
} else if (anchor.isHalfHeight()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
} else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
} else if (anchor.isBaseline()) {
yAdj = 0.0f;
} else if (anchor.isBottom()) {
yAdj = descent + leading;
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text ({@code null} permitted).
* @param g2 the graphics device.
* @param textX the x coordinate for the text.
* @param textY the y coordinate for the text.
* @param angle the angle.
* @param rotateX the x coordinate for the rotation point.
* @param rotateY the y coordinate for the rotation point.
*
* @return The bounds ({@code null} if {@code text} is {@code null} or has
* zero length).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
if ((text == null) || (text.equals(""))) {
return null;
}
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
AffineTransform translate = AffineTransform.getTranslateInstance(
textX, textY);
Shape translatedBounds = translate.createTransformedShape(bounds);
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
Shape result = rotate.createTransformedShape(translatedBounds);
return result;
}
/**
* Returns the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @return A boolean.
*/
public static boolean getUseFontMetricsGetStringBounds() {
return useFontMetricsGetStringBounds;
}
/**
* Sets the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @param use the flag.
*/
public static void setUseFontMetricsGetStringBounds(boolean use) {
useFontMetricsGetStringBounds = use;
}
/**
* Returns the flag that controls whether or not a workaround is used for
* drawing rotated strings.
*
* @return A boolean.
*/
public static boolean getUseDrawRotatedStringWorkaround() {
return useDrawRotatedStringWorkaround;
}
/**
* Sets the flag that controls whether or not a workaround is used for
* drawing rotated strings. The related bug is on Sun's bug parade
* (id 4312117) and the workaround involves using a {@code TextLayout}
* instance to draw the text instead of calling the
* {@code drawString()} method in the {@code Graphics2D} class.
*
* @param use the new flag value.
*/
public static void setUseDrawRotatedStringWorkaround(boolean use) {
TextUtilities.useDrawRotatedStringWorkaround = use;
}
/**
* Draws the attributed string at {@code (x, y)}, rotated by the
* specified angle about {@code (x, y)}.
*
* @param text the attributed string ({@code null} not permitted).
* @param g2 the graphics output target.
* @param angle the angle.
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* Draws the attributed string at {@code (textX, textY)}, rotated by
* the specified angle about {@code (rotateX, rotateY)}.
*
* @param text the attributed string ({@code null} not permitted).
* @param g2 the graphics output target ({@code null} not permitted).
* @param textX the x-coordinate for the text.
* @param textY the y-coordinate for the text.
* @param angle the rotation angle (in radians).
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the y-coordinate for the rotation point.
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
ParamChecks.nullNotPermitted(text, "text");
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
g2.transform(rotate);
TextLayout tl = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
g2.setTransform(saved);
}
/**
* Draws an attributed string with the {@code textAnchor} point
* aligned to {@code (x, y)} and rotated by {@code angle} radians
* about the {@code rotationAnchor}.
*
* @param text the attributed string ({@code null} not permitted).
* @param g2 the graphics target ({@code null} not permitted).
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param textAnchor the text anchor ({@code null} not permitted).
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor point ({@code null} not
* permitted).
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
ParamChecks.nullNotPermitted(text, "text");
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
AttributedString text, TextAnchor anchor, Rectangle2D textBounds) {
TextLayout layout = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
float[] result = new float[3];
float ascent = layout.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = layout.getDescent();
float leading = layout.getLeading();
double height = Math.max(bounds.getHeight(),
ascent + descent + leading);
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
} else if (anchor.isHorizontalRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) height;
} else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
} else if (anchor.isHalfHeight()) {
yAdj = -descent - leading + (float) (height / 2.0);
} else if (anchor.isBaseline()) {
yAdj = 0.0f;
} else if (anchor.isBottom()) {
yAdj = -descent - leading;
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* (BASELINE_LEFT).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
AttributedString text, TextAnchor anchor) {
float[] result = new float[2];
TextLayout layout = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
float ascent = layout.getAscent();
float halfAscent = ascent / 2.0f;
float descent = layout.getDescent();
float leading = layout.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalLeft()) {
xAdj = 0.0f;
} else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
} else if (anchor.isHorizontalRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
} else if (anchor.isHalfHeight()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
} else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
} else if (anchor.isBaseline()) {
yAdj = 0.0f;
} else if (anchor.isBottom()) {
yAdj = descent + leading;
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns the flag that controls whether or not strings are drawn using
* the current font attributes (such as underlining, strikethrough etc).
* The default value is {@code false}.
*
* @return A boolean.
*
* @since 1.0.21
*/
public static boolean getDrawStringsWithFontAttributes() {
return TextUtilities.drawStringsWithFontAttributes;
}
public static void setDrawStringsWithFontAttributes(boolean b) {
TextUtilities.drawStringsWithFontAttributes = b;
}
}
|
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.yaml.snakeyaml.Yaml;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// Cache for all configuration passed programmatically or read from file
private final Map<Object, Object> config = new HashMap<Object, Object>();
// Runtime to get available processors
private static final Runtime RUNTIME = Runtime.getRuntime();
// Default properties
public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties";
public static final String IP_ADDRESS_DEF = "0.0.0.0";
public static final String PORT_DEF = "1199";
public static final String BOSS_POOL_DEF = "1";
public static final int WORKER_POOL_DEF = 3;
public static final String CONNECTION_TIMEOUT_DEF = "1000";
public static final boolean SERVER_DEF = Boolean.TRUE;
public static final String DATA_SOURCE_PATH_DEF = "./ds";
// Properties which version of server is running remote it requires server
// client RPC infrastructure or local (embedded mode)
private static final String REMOTE_KEY = "remote";
private static final String SERVER_KEY = "server";
private static final String CLIENT_KEY = "client";
public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>(
Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)));
public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>(
Arrays.asList("./ds"));
private static final String CONFIG_FILE = "./config/configuration.yaml";
// Configuration keys properties for deployment
private static final String DEPLOY_CONFIG_KEY = "deployConfiguration";
private static final String ADMIN_USER_PATH_KEY = "adminPath";
private static final String HOT_DEPLOYMENT_KEY = "hotDeployment";
private static final String WATCH_STATUS_KEY = "watchStatus";
private static final String LIBRARY_PATH_KEY = "libraryPaths";
// Persistence provider property keys
private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig";
private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities";
private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName";
private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath";
private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar";
private static final String SWAP_DATASOURCE_KEY = "swapDataSource";
private static final String SCAN_ARCHIVES_KEY = "scanArchives";
private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource";
private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties";
// Connection pool provider property keys
private static final String POOL_CONFIG_KEY = "poolConfig";
private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath";
private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType";
private static final String POOL_PROPERTIES_KEY = "poolProperties";
// Configuration properties for deployment
private static String ADMIN_USERS_PATH;
// Is configuration server or client (default is server)
private static boolean server = SERVER_DEF;
private static boolean remote;
// Instance of pool configuration
private static final PoolConfig POOL_CONFIG = new PoolConfig();
private static final String META_INF_PATH = "META-INF/";
// Error messages
private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration";
private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file";
private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist";
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) {
if (from == null) {
from = config;
}
@SuppressWarnings("unchecked")
Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from);
return value;
}
private <K, V> Map<K, V> getAsMap(Object key) {
return getAsMap(key, null);
}
private <K, V> void setSubConfigValue(Object key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (ObjectUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K> boolean containsSubConfigKey(Object key, K subKey) {
Map<K, ?> subConfig = getAsMap(key);
boolean valid = ObjectUtils.available(subConfig);
if (valid) {
valid = subConfig.containsKey(subKey);
}
return valid;
}
private <K> boolean containsConfigKey(K key) {
return containsSubConfigKey(DEPLOY_CONFIG_KEY, key);
}
private <K, V> V getSubConfigValue(Object key, K subKey) {
return getSubConfigValue(key, subKey, null);
}
private <K, V> void setConfigValue(K subKey, V value) {
setSubConfigValue(DEPLOY_CONFIG_KEY, subKey, value);
}
private <K, V> V getConfigValue(K subKey, V defaultValue) {
return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey, defaultValue);
}
private <K, V> V getConfigValue(K subKey) {
return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey);
}
private <K, V> Map<K, V> getWithInitialization(Object key) {
Map<K, V> result = getConfigValue(key);
if (result == null) {
result = new HashMap<K, V>();
setConfigValue(key, result);
}
return result;
}
private <K, V> void setWithInitialization(Object key, K subKey, V value) {
Map<K, V> result = getWithInitialization(key);
result.put(subKey, value);
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration if value is null then returns passed default value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY,
PERSISTENCE_CONFIG_KEY, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key) {
return getPersistenceConfigValue(key, null);
}
/**
* Sets specific value for appropriated key in persistence configuration sub
* {@link Map} of configuration
*
* @param key
* @param value
*/
public void setPersistenceConfigValue(Object key, Object value) {
setWithInitialization(PERSISTENCE_CONFIG_KEY, key, value);
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration if value is null then returns passed default
* value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY,
POOL_CONFIG_KEY, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key) {
V value = getPoolConfigValue(key, null);
return value;
}
/**
* Sets specific value for appropriated key in connection pool configuration
* sub {@link Map} of configuraion
*
* @param key
* @param value
*/
public void setPoolConfigValue(Object key, Object value) {
setWithInitialization(POOL_CONFIG_KEY, key, value);
}
/**
* Configuration for {@link PoolConfig} instance
*/
private void configurePool() {
Map<Object, Object> poolProperties = getPoolConfigValue(POOL_PROPERTIES_KEY);
if (ObjectUtils.available(poolProperties)) {
setPoolProperties(poolProperties);
}
String type = getPoolConfigValue(POOL_PROVIDER_TYPE_KEY);
if (ObjectUtils.available(type)) {
getPoolConfig().setPoolProviderType(type);
}
String path = getPoolConfigValue(POOL_PROPERTIES_PATH_KEY);
if (ObjectUtils.available(path)) {
setPoolPropertiesPath(path);
}
}
/**
* Configures server from properties
*/
private void configureServer() {
// Sets default values to remote server configuration
boolean contains = containsConfigKey(Config.IP_ADDRESS.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value);
}
contains = containsConfigKey(Config.PORT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.PORT.key, Config.PORT.value);
}
contains = containsConfigKey(Config.BOSS_POOL.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value);
}
contains = containsConfigKey(Config.WORKER_POOL_KEY.key);
if (ObjectUtils.notTrue(contains)) {
int workers = RUNTIME.availableProcessors()
* (Integer) Config.WORKER_POOL_KEY.value;
String workerProperty = String.valueOf(workers);
setConfigValue(Config.WORKER_POOL_KEY.key, workerProperty);
}
contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.CONNECTION_TIMEOUT.key,
Config.CONNECTION_TIMEOUT.value);
}
// Sets default values is application on server or client mode
Object serverValue = getConfigValue(Config.SERVER.key);
if (ObjectUtils.notNull(serverValue)) {
if (serverValue instanceof Boolean) {
server = (Boolean) serverValue;
} else {
server = Boolean.valueOf(serverValue.toString());
}
}
Object remoteValue = getConfigValue(Config.REMOTE.key);
if (ObjectUtils.notNull(remoteValue)) {
if (remoteValue instanceof Boolean) {
remote = (Boolean) remoteValue;
} else {
remote = Boolean.valueOf(remoteValue.toString());
}
}
}
/**
* Merges configuration with default properties
*/
public void configureDeployments() {
// Sets administrator user configuration file path
ADMIN_USERS_PATH = getConfigValue(ADMIN_USER_PATH_KEY,
ADMIN_USERS_PATH_DEF);
// Checks if application run in hot deployment mode
Boolean hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY);
if (hotDeployment == null) {
setConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE);
hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY);
}
// Check if application needs directory watch service
boolean watchStatus;
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
setConfigValue(WATCH_STATUS_KEY, watchStatus);
// Sets deployments directories
Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY);
if (deploymentPaths == null) {
deploymentPaths = DEPLOYMENT_PATHS_DEF;
setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths);
}
}
/**
* Configures server and connection pooling
*/
public void configure() {
configureServer();
configureDeployments();
configurePool();
}
/**
* Merges two {@link Map}s and if second {@link Map}'s value is instance of
* {@link Map} merges this value with first {@link Map}'s value recursively
*
* @param map1
* @param map2
* @return <code>{@link Map}<Object, Object></code>
*/
@SuppressWarnings("unchecked")
protected Map<Object, Object> deepMerge(Map<Object, Object> map1,
Map<Object, Object> map2) {
if (map1 == null) {
map1 = map2;
} else {
Set<Map.Entry<Object, Object>> entries2 = map2.entrySet();
Object key;
Map<Object, Object> value1;
Object value2;
Object mergedValue;
for (Map.Entry<Object, Object> entry2 : entries2) {
key = entry2.getKey();
value2 = entry2.getValue();
if (value2 instanceof Map) {
value1 = ObjectUtils.getAsMap(key, map1);
mergedValue = deepMerge(value1,
(Map<Object, Object>) value2);
} else {
mergedValue = value2;
}
if (ObjectUtils.notNull(mergedValue)) {
map1.put(key, mergedValue);
}
}
}
return map1;
}
/**
* Reads configuration from passed properties
*
* @param configuration
*/
public void configure(Map<Object, Object> configuration) {
deepMerge(config, configuration);
}
/**
* Reads configuration from passed file path
*
* @param configuration
*/
public void configure(String path) throws IOException {
File yamlFile = new File(path);
if (yamlFile.exists()) {
InputStream stream = new FileInputStream(yamlFile);
try {
Yaml yaml = new Yaml();
Object configuration = yaml.load(stream);
if (configuration instanceof Map) {
@SuppressWarnings("unchecked")
Map<Object, Object> innerConfig = (Map<Object, Object>) configuration;
configure(innerConfig);
}
} finally {
ObjectUtils.close(stream);
}
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) throws IOException {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
} catch (IOException ex) {
LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex);
} finally {
ObjectUtils.close(propertiesStream);
}
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
try {
File configFile = new File(CONFIG_FILE);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader)
throws IOException {
InputStream resourceStream = loader.getResourceAsStream(StringUtils
.concat(META_INF_PATH, resourceName));
if (resourceStream == null) {
LOG.error(RESOURCE_NOT_EXISTS_ERROR);
} else {
loadFromStream(resourceStream);
}
}
public static String getAdminUsersPath() {
return ADMIN_USERS_PATH;
}
public static void setAdminUsersPath(String aDMIN_USERS_PATH) {
ADMIN_USERS_PATH = aDMIN_USERS_PATH;
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remoteValue) {
remote = remoteValue;
}
public static boolean isServer() {
return server;
}
public static void setServer(boolean serverValue) {
server = serverValue;
}
public boolean isClient() {
return getConfigValue(CLIENT_KEY, Boolean.FALSE);
}
public void setClient(boolean client) {
setConfigValue(CLIENT_KEY, client);
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY);
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths);
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
Set<String> dataSourcePaths = getConfigValue(DATA_SOURCE_PATH_KEY);
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
setConfigValue(DATA_SOURCE_PATH_KEY, dataSourcePaths);
}
dataSourcePaths.add(path);
}
public Set<DeploymentDirectory> getDeploymentPath() {
return getConfigValue(DEMPLOYMENT_PATH_KEY);
}
public Set<String> getDataSourcePath() {
return getConfigValue(DATA_SOURCE_PATH_KEY);
}
public String[] getLibraryPaths() {
return getConfigValue(LIBRARY_PATH_KEY);
}
public void setLibraryPaths(String[] libraryPaths) {
setConfigValue(LIBRARY_PATH_KEY, libraryPaths);
}
public boolean isHotDeployment() {
return getConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE);
}
public void setHotDeployment(boolean hotDeployment) {
setConfigValue(HOT_DEPLOYMENT_KEY, hotDeployment);
}
public boolean isWatchStatus() {
return getConfigValue(WATCH_STATUS_KEY, Boolean.FALSE);
}
public void setWatchStatus(boolean watchStatus) {
setConfigValue(WATCH_STATUS_KEY, watchStatus);
}
/**
* Property for persistence configuration
*
* @return <code>boolean</code>
*/
public boolean isScanForEntities() {
return getPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities);
}
public String getAnnotatedUnitName() {
return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName);
}
public String getPersXmlPath() {
return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY);
}
public void setPersXmlPath(String persXmlPath) {
setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath);
}
public boolean isPersXmlFromJar() {
return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY,
Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar);
}
public boolean isSwapDataSource() {
return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource);
}
public boolean isScanArchives() {
return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives);
}
public boolean isPooledDataSource() {
return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource);
}
public Map<Object, Object> getPersistenceProperties() {
return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY,
persistenceProperties);
}
/**
* Property for connection pool configuration
*
* @return {@link PoolConfig}
*/
public static PoolConfig getPoolConfig() {
return POOL_CONFIG;
}
public void setDataSourcePooledType(boolean dsPooledType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPooledDataSource(dsPooledType);
}
public void setPoolPropertiesPath(String path) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolPath(path);
}
public void setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().putAll(properties);
}
public void addPoolProperty(Object key, Object value) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().put(key, value);
}
public void setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolProviderType(poolProviderType);
}
@Override
public Object clone() throws CloneNotSupportedException {
Configuration cloneConfig = (Configuration) super.clone();
cloneConfig.config.clear();
cloneConfig.configure(this.config);
return cloneConfig;
}
}
|
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.yaml.snakeyaml.Yaml;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// Cache for all configuration passed from API or read from file
private final Map<Object, Object> config = new HashMap<Object, Object>();
// Instance of pool configuration
private static final PoolConfig POOL_CONFIG = new PoolConfig();
// Runtime to get available processors
private static final Runtime RUNTIME = Runtime.getRuntime();
// Resource path (META-INF)
private static final String META_INF_PATH = "META-INF/";
// Error messages
private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration";
private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file";
private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist";
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) {
if (from == null) {
from = config;
}
Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from));
return value;
}
private <K, V> Map<K, V> getAsMap(Object key) {
return getAsMap(key, null);
}
private <K, V> void setSubConfigValue(Object key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (CollectionUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K> boolean containsSubConfigKey(Object key, K subKey) {
Map<K, ?> subConfig = getAsMap(key);
boolean valid = CollectionUtils.available(subConfig);
if (valid) {
valid = subConfig.containsKey(subKey);
}
return valid;
}
private <K> boolean containsConfigKey(K key) {
return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key);
}
private <K, V> V getSubConfigValue(Object key, K subKey) {
return getSubConfigValue(key, subKey, null);
}
private <K, V> void setConfigValue(K subKey, V value) {
setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value);
}
private <K, V> V getConfigValue(K subKey, V defaultValue) {
return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey,
defaultValue);
}
private <K, V> V getConfigValue(K subKey) {
return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey);
}
private <K, V> Map<K, V> getWithInitialization(Object key) {
Map<K, V> result = getConfigValue(key);
if (result == null) {
result = new HashMap<K, V>();
setConfigValue(key, result);
}
return result;
}
private <K, V> void setWithInitialization(Object key, K subKey, V value) {
Map<K, V> result = getWithInitialization(key);
result.put(subKey, value);
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration if value is null then returns passed default value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key, V defaultValue) {
V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key,
ConfigKeys.PERSISTENCE_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key) {
return getPersistenceConfigValue(key, null);
}
/**
* Sets specific value for appropriated key in persistence configuration sub
* {@link Map} of configuration
*
* @param key
* @param value
*/
public void setPersistenceConfigValue(Object key, Object value) {
setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value);
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration if value is null then returns passed default
* value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key, V defaultValue) {
V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key,
ConfigKeys.POOL_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key) {
V value = getPoolConfigValue(key, null);
return value;
}
/**
* Sets specific value for appropriated key in connection pool configuration
* sub {@link Map} of configuraion
*
* @param key
* @param value
*/
public void setPoolConfigValue(Object key, Object value) {
setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value);
}
/**
* Configuration for {@link PoolConfig} instance
*/
private void configurePool() {
Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key);
if (CollectionUtils.available(poolProperties)) {
setPoolProperties(poolProperties);
}
String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key);
if (CollectionUtils.available(type)) {
getPoolConfig().setPoolProviderType(type);
}
String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key);
if (CollectionUtils.available(path)) {
setPoolPropertiesPath(path);
}
}
/**
* Configures server from properties and default values
*/
private void configureServer() {
// Sets default values to remote server configuration
boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(ConfigKeys.IP_ADDRESS.key,
ConfigKeys.IP_ADDRESS.value);
}
contains = containsConfigKey(ConfigKeys.PORT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value);
}
contains = containsConfigKey(ConfigKeys.BOSS_POOL.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value);
}
contains = containsConfigKey(ConfigKeys.WORKER_POOL.key);
if (ObjectUtils.notTrue(contains)) {
int defaultWorkers = ConfigKeys.WORKER_POOL.getValue();
int workers = RUNTIME.availableProcessors() * defaultWorkers;
String workerProperty = String.valueOf(workers);
setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty);
}
contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key,
ConfigKeys.CONNECTION_TIMEOUT.value);
}
}
/**
* Merges configuration with default properties
*/
public void configureDeployments() {
// Checks if application run in hot deployment mode
Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key);
if (hotDeployment == null) {
setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE);
hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key);
}
// Check if application needs directory watch service
boolean watchStatus;
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus);
// Sets deployments directories
Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue();
setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths);
}
}
/**
* Configures server and connection pooling
*/
public void configure() {
configureServer();
configureDeployments();
configurePool();
}
/**
* Merges two {@link Map}s and if second {@link Map}'s value is instance of
* {@link Map} merges this value with first {@link Map}'s value recursively
*
* @param map1
* @param map2
* @return <code>{@link Map}<Object, Object></code>
*/
protected Map<Object, Object> deepMerge(Map<Object, Object> map1,
Map<Object, Object> map2) {
if (map1 == null) {
map1 = map2;
} else {
Set<Map.Entry<Object, Object>> entries2 = map2.entrySet();
Object key;
Map<Object, Object> value1;
Object value2;
Map<Object, Object> mapValue2;
Object mergedValue;
for (Map.Entry<Object, Object> entry2 : entries2) {
key = entry2.getKey();
value2 = entry2.getValue();
if (value2 instanceof Map) {
value1 = CollectionUtils.getAsMap(key, map1);
mapValue2 = ObjectUtils.cast(value2);
mergedValue = deepMerge(value1, mapValue2);
} else {
mergedValue = value2;
}
if (ObjectUtils.notNull(mergedValue)) {
map1.put(key, mergedValue);
}
}
}
return map1;
}
/**
* Reads configuration from passed properties
*
* @param configuration
*/
public void configure(Map<Object, Object> configuration) {
deepMerge(config, configuration);
}
/**
* Reads configuration from passed file path
*
* @param configuration
*/
public void configure(String path) throws IOException {
File yamlFile = new File(path);
if (yamlFile.exists()) {
InputStream stream = new FileInputStream(yamlFile);
try {
Yaml yaml = new Yaml();
Object configuration = yaml.load(stream);
if (configuration instanceof Map) {
Map<Object, Object> innerConfig = ObjectUtils
.cast(configuration);
configure(innerConfig);
}
} finally {
ObjectUtils.close(stream);
}
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) throws IOException {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
} catch (IOException ex) {
LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex);
} finally {
ObjectUtils.close(propertiesStream);
}
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
String configFilePath = ConfigKeys.CONFIG_FILE.getValue();
try {
File configFile = new File(configFilePath);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader)
throws IOException {
InputStream resourceStream = loader.getResourceAsStream(StringUtils
.concat(META_INF_PATH, resourceName));
if (resourceStream == null) {
LOG.error(RESOURCE_NOT_EXISTS_ERROR);
} else {
loadFromStream(resourceStream);
}
}
public static String getAdminUsersPath() {
return ConfigKeys.ADMIN_USER_PATH.getValue();
}
public static void setAdminUsersPath(String adminUserPath) {
ConfigKeys.ADMIN_USERS_PATH.value = adminUserPath;
}
public boolean isRemote() {
return ConfigKeys.REMOTE.getValue();
}
public void setRemote(boolean remote) {
ConfigKeys.REMOTE.value = remote;
}
public static boolean isServer() {
return ConfigKeys.SERVER.getValue();
}
public static void setServer(boolean server) {
ConfigKeys.SERVER.value = server;
}
public boolean isClient() {
return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE);
}
public void setClient(boolean client) {
setConfigValue(ConfigKeys.CLIENT.key, client);
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths);
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key);
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths);
}
dataSourcePaths.add(path);
}
public Set<DeploymentDirectory> getDeploymentPath() {
return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key);
}
public Set<String> getDataSourcePath() {
return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key);
}
public String[] getLibraryPaths() {
return getConfigValue(ConfigKeys.LIBRARY_PATH.key);
}
public void setLibraryPaths(String[] libraryPaths) {
setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths);
}
public boolean isHotDeployment() {
return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE);
}
public void setHotDeployment(boolean hotDeployment) {
setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment);
}
public boolean isWatchStatus() {
return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE);
}
public void setWatchStatus(boolean watchStatus) {
setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus);
}
/**
* Property for persistence configuration
*
* @return <code>boolean</code>
*/
public boolean isScanForEntities() {
return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key,
Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key,
scanForEntities);
}
public String getAnnotatedUnitName() {
return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key,
annotatedUnitName);
}
public String getPersXmlPath() {
return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key);
}
public void setPersXmlPath(String persXmlPath) {
setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key,
persXmlPath);
}
public boolean isPersXmlFromJar() {
return getPersistenceConfigValue(
ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key,
persXmlFromJar);
}
public boolean isSwapDataSource() {
return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key,
Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key,
swapDataSource);
}
public boolean isScanArchives() {
return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key,
Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives);
}
public boolean isPooledDataSource() {
return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key,
Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key,
pooledDataSource);
}
public Map<Object, Object> getPersistenceProperties() {
return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key,
persistenceProperties);
}
/**
* Property for connection pool configuration
*
* @return {@link PoolConfig}
*/
public static PoolConfig getPoolConfig() {
return POOL_CONFIG;
}
public void setDataSourcePooledType(boolean dsPooledType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPooledDataSource(dsPooledType);
}
public void setPoolPropertiesPath(String path) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolPath(path);
}
public void setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().putAll(properties);
}
public void addPoolProperty(Object key, Object value) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().put(key, value);
}
public void setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolProviderType(poolProviderType);
}
@Override
public Object clone() throws CloneNotSupportedException {
Configuration cloneConfig = (Configuration) super.clone();
cloneConfig.config.clear();
cloneConfig.configure(this.config);
return cloneConfig;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.